Skip to content

Commit

Permalink
hashentry: Add HashEntry.String()
Browse files Browse the repository at this point in the history
Add String() to HashEntry. Unlike stringify(), which is used internally,
this cannot fail. "unknown-alg" is used for unidentified algorithm
values, and "<empty>" is used if base64 encoding returns an empty
string.

Signed-off-by: Sergei Trofimov <sergei.trofimov@arm.com>
  • Loading branch information
setrofim committed Sep 11, 2023
1 parent 2e8ff3c commit 8ffdd07
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
18 changes: 17 additions & 1 deletion hashentry.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,29 @@ func ValidHashEntry(algID uint64, value []byte) error {
return nil
}

// String returns a string representation of the HashEntry. The representation
// consists of the algorithm name and the base64-encoded hash value separated by
// a semicolon.
func (h HashEntry) String() string {
sAlg, ok := algToString[h.HashAlgID]
if !ok {
sAlg = "unknown-alg"
}

sVal := base64.StdEncoding.EncodeToString(h.HashValue)
if len(sVal) == 0 {
sVal = "<empty>"
}

return sAlg + ";" + sVal
}

func (h HashEntry) stringify() (string, error) {
sAlg, ok := algToString[h.HashAlgID]
if !ok {
return "", fmt.Errorf("unknown hash algorithm ID %d", h.HashAlgID)
}

//sVal := hex.EncodeToString(h.HashValue)
sVal := base64.StdEncoding.EncodeToString(h.HashValue)
if len(sVal) == 0 {
return "", fmt.Errorf("empty hash value")
Expand Down
25 changes: 25 additions & 0 deletions hashentry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,31 @@ func TestHashEntry_Set_OK(t *testing.T) {
}
}

func TestHashEntry_String(t *testing.T) {
for _, tv := range []struct {
In HashEntry
Expected string
}{
{
In: HashEntry{
HashAlgID: 1,
HashValue: []byte{0xde, 0xad, 0xbe, 0xef},
},
Expected: "sha-256;3q2+7w==",
},
{
In: HashEntry{
HashAlgID: 1337,
HashValue: nil,
},
Expected: "unknown-alg;<empty>",
},
} {
ret := tv.In.String()
assert.Equal(t, tv.Expected, ret)
}
}

func TestHashEntry_Set_mismatched_input(t *testing.T) {
tvs := []struct {
alg uint64
Expand Down

0 comments on commit 8ffdd07

Please sign in to comment.