diff --git a/id.go b/id.go index 6d3dcdc..a212133 100644 --- a/id.go +++ b/id.go @@ -126,6 +126,13 @@ func New() ID { return id } +// FromString reads an ID from its string representation +func FromString(id string) (ID, error) { + i := &ID{} + err := i.UnmarshalText([]byte(id)) + return *i, err +} + // String returns a base32 hex lowercased with no padding representation of the id (char set is 0-9, a-v). func (id ID) String() string { text, _ := id.MarshalText() diff --git a/id_test.go b/id_test.go index 24e1281..7e9341a 100644 --- a/id_test.go +++ b/id_test.go @@ -82,6 +82,18 @@ func TestIDString(t *testing.T) { assert.Equal(t, "9m4e2mr0ui3e8a215n4g", id.String()) } +func TestFromString(t *testing.T) { + id, err := FromString("9m4e2mr0ui3e8a215n4g") + assert.NoError(t, err) + assert.Equal(t, ID{0x4d, 0x88, 0xe1, 0x5b, 0x60, 0xf4, 0x86, 0xe4, 0x28, 0x41, 0x2d, 0xc9}, id) +} + +func TestFromStringInvalid(t *testing.T) { + id, err := FromString("invalid") + assert.EqualError(t, err, "invalid ID") + assert.Equal(t, ID{}, id) +} + type jsonType struct { ID *ID }