From 8f0ebe47f25d85d4cbe088de887ff8c00de4a3b4 Mon Sep 17 00:00:00 2001 From: Lorenzo Fontana Date: Fri, 20 Jul 2018 17:00:31 +0200 Subject: [PATCH] Static id from string function Signed-off-by: Lorenzo Fontana Co-authored-by: Chris Goller --- id.go | 10 ++++++++++ id_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 id_test.go diff --git a/id.go b/id.go index 0614a5f1cb..c57a0a0afe 100644 --- a/id.go +++ b/id.go @@ -14,6 +14,16 @@ type IDGenerator interface { 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. func (i *ID) Decode(b []byte) error { dst := make([]byte, hex.DecodedLen(len(b))) diff --git a/id_test.go b/id_test.go new file mode 100644 index 0000000000..f68db5042c --- /dev/null +++ b/id_test.go @@ -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) + } + }) + } +}