[#168] refs: Implement binary/JSON encoders/decoders on ContainerID

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 16:07:32 +03:00 committed by Alex Vanin
parent 7289ff6c64
commit c0f3ac51d4
6 changed files with 103 additions and 4 deletions

View file

@ -65,3 +65,35 @@ func (id *ID) Parse(s string) error {
func (id *ID) String() string {
return base58.Encode((*refs.ContainerID)(id).GetValue())
}
// Marshal marshals ID into a protobuf binary form.
//
// Buffer is allocated when the argument is empty.
// Otherwise, the first buffer is used.
func (id *ID) Marshal(b ...[]byte) ([]byte, error) {
var buf []byte
if len(b) > 0 {
buf = b[0]
}
return (*refs.ContainerID)(id).
StableMarshal(buf)
}
// Unmarshal unmarshals protobuf binary representation of ID.
func (id *ID) Unmarshal(data []byte) error {
return (*refs.ContainerID)(id).
Unmarshal(data)
}
// MarshalJSON encodes ID to protobuf JSON format.
func (id *ID) MarshalJSON() ([]byte, error) {
return (*refs.ContainerID)(id).
MarshalJSON()
}
// UnmarshalJSON decodes ID from protobuf JSON format.
func (id *ID) UnmarshalJSON(data []byte) error {
return (*refs.ContainerID)(id).
UnmarshalJSON(data)
}

View file

@ -90,3 +90,28 @@ func TestID_String(t *testing.T) {
}
})
}
func TestContainerIDEncoding(t *testing.T) {
id := NewID()
id.SetSHA256(randSHA256Checksum(t))
t.Run("binary", func(t *testing.T) {
data, err := id.Marshal()
require.NoError(t, err)
id2 := NewID()
require.NoError(t, id2.Unmarshal(data))
require.Equal(t, id, id2)
})
t.Run("json", func(t *testing.T) {
data, err := id.MarshalJSON()
require.NoError(t, err)
a2 := NewID()
require.NoError(t, a2.UnmarshalJSON(data))
require.Equal(t, id, a2)
})
}