[#41] chain: Fix ID serialization

Signed-off-by: Denis Kirillov <d.kirillov@yadro.com>
This commit is contained in:
Denis Kirillov 2024-01-12 10:49:12 +03:00
parent ed93bb5cc5
commit c80c99b13e
2 changed files with 26 additions and 0 deletions

View file

@ -31,6 +31,19 @@ type Chain struct {
MatchType MatchType MatchType MatchType
} }
func (id ID) MarshalJSON() ([]byte, error) {
return json.Marshal([]byte(id))
}
func (id *ID) UnmarshalJSON(data []byte) error {
var idRaw []byte
if err := json.Unmarshal(data, &idRaw); err != nil {
return err
}
*id = ID(idRaw)
return nil
}
func (c *Chain) Bytes() []byte { func (c *Chain) Bytes() []byte {
data, err := json.Marshal(c) data, err := json.Marshal(c)
if err != nil { if err != nil {

View file

@ -9,6 +9,19 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestChainIDSerialization(t *testing.T) {
chainIDBytes := []byte{93, 236, 80, 138, 168, 3, 144, 92, 173, 141, 16, 42, 249, 90, 97, 109, 211, 169, 54, 163}
chain1 := &Chain{ID: ID(chainIDBytes)}
data := chain1.Bytes()
var chain2 Chain
err := chain2.DecodeBytes(data)
require.NoError(t, err)
require.Equal(t, chain1.ID, chain2.ID)
}
func TestEncodeDecode(t *testing.T) { func TestEncodeDecode(t *testing.T) {
expected := Chain{ expected := Chain{
MatchType: MatchTypeFirstMatch, MatchType: MatchTypeFirstMatch,