Skip to content

Commit

Permalink
Added convince function to encode IDs to hash strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kugelschieber committed Feb 5, 2019
1 parent e0043c0 commit 8ce8eb2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
16 changes: 16 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,19 @@ package hide
func FromString(id string) (ID, error) {
return hash.Decode([]byte(id))
}

// Returns a new hash from given ID by using the hasher or an error if it couldn't encode the ID.
// If ID is 0, "null" will be returned.
func ToString(id ID) (string, error) {
if id == 0 {
return "null", nil
}

hash, err := hash.Encode(id)

if err != nil {
return "", err
}

return string(hash), nil
}
12 changes: 12 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,15 @@ func TestFromStringEmpty(t *testing.T) {
t.Fatalf("Must return 0 on empty string, but was: %v %v", err, id)
}
}

func TestToString(t *testing.T) {
if hash, err := ToString(123); err != nil || hash != "beJarVNaQM" {
t.Fatalf("Must return hash from ID, but was: %v %v", err, hash)
}
}

func TestToStringNull(t *testing.T) {
if hash, err := ToString(0); err != nil || hash != "null" {
t.Fatalf("Must return 0 from null ID, but was: %v %v", err, hash)
}
}

0 comments on commit 8ce8eb2

Please sign in to comment.