[#168] object: Implement binary/JSON encoders/decoders on Attribute

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 15:31:15 +03:00 committed by Alex Vanin
parent ce0d70fa02
commit 0caff85fb7
6 changed files with 103 additions and 4 deletions

View file

@ -43,3 +43,35 @@ func (a *Attribute) SetValue(v string) {
func (a *Attribute) ToV2() *object.Attribute {
return (*object.Attribute)(a)
}
// Marshal marshals Attribute into a protobuf binary form.
//
// Buffer is allocated when the argument is empty.
// Otherwise, the first buffer is used.
func (d *Attribute) Marshal(b ...[]byte) ([]byte, error) {
var buf []byte
if len(b) > 0 {
buf = b[0]
}
return (*object.Attribute)(d).
StableMarshal(buf)
}
// Unmarshal unmarshals protobuf binary representation of Attribute.
func (d *Attribute) Unmarshal(data []byte) error {
return (*object.Attribute)(d).
Unmarshal(data)
}
// MarshalJSON encodes Attribute to protobuf JSON format.
func (d *Attribute) MarshalJSON() ([]byte, error) {
return (*object.Attribute)(d).
MarshalJSON()
}
// UnmarshalJSON decodes Attribute from protobuf JSON format.
func (d *Attribute) UnmarshalJSON(data []byte) error {
return (*object.Attribute)(d).
UnmarshalJSON(data)
}

View file

@ -21,3 +21,29 @@ func TestAttribute(t *testing.T) {
require.Equal(t, key, aV2.GetKey())
require.Equal(t, val, aV2.GetValue())
}
func TestAttributeEncoding(t *testing.T) {
a := NewAttribute()
a.SetKey("key")
a.SetValue("value")
t.Run("binary", func(t *testing.T) {
data, err := a.Marshal()
require.NoError(t, err)
a2 := NewAttribute()
require.NoError(t, a2.Unmarshal(data))
require.Equal(t, a, a2)
})
t.Run("json", func(t *testing.T) {
data, err := a.MarshalJSON()
require.NoError(t, err)
a2 := NewAttribute()
require.NoError(t, a2.UnmarshalJSON(data))
require.Equal(t, a, a2)
})
}