Skip to content

Commit

Permalink
Add FromString method
Browse files Browse the repository at this point in the history
  • Loading branch information
Olivier Poitrey committed Mar 15, 2016
1 parent 9894c31 commit 057f3c9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions id.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
12 changes: 12 additions & 0 deletions id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 057f3c9

Please sign in to comment.