Merge pull request #443 from fntlnz/feature/static-id-string

Static id from string function
pull/10616/head
Lorenzo Fontana 2018-07-20 17:02:44 +02:00 committed by GitHub
commit 5f1f9a99c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

10
id.go
View File

@ -14,6 +14,16 @@ type IDGenerator interface {
ID() ID ID() ID
} }
// IDFromString creates an ID from a given string
func IDFromString(idstr string) (*ID, error) {
var id ID
err := id.DecodeFromString(idstr)
if err != nil {
return nil, err
}
return &id, nil
}
// Decode parses b as a hex-encoded byte-slice-string. // Decode parses b as a hex-encoded byte-slice-string.
func (i *ID) Decode(b []byte) error { func (i *ID) Decode(b []byte) error {
dst := make([]byte, hex.DecodedLen(len(b))) dst := make([]byte, hex.DecodedLen(len(b)))

38
id_test.go Normal file
View File

@ -0,0 +1,38 @@
package platform
import (
"reflect"
"testing"
)
func TestIDFromString(t *testing.T) {
tests := []struct {
name string
idstr string
want *ID
wantErr bool
}{
{
name: "Is able to decode an id",
idstr: "020f755c3c082000",
want: &ID{0x02, 0x0f, 0x75, 0x5c, 0x3c, 0x08, 0x20, 0x00},
},
{
name: "It should not be able to decode an id that's not hex",
idstr: "gggggggggggggg",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := IDFromString(tt.idstr)
if (err != nil) != tt.wantErr {
t.Errorf("IDFromString() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("IDFromString() = %v, want %v", got, tt.want)
}
})
}
}