Skip to content

Commit

Permalink
[#356] refs: Implement text encoding of SubnetID
Browse files Browse the repository at this point in the history
Implement `encoding.TextMarshaler` / `encoding.TextUnmarshaler` interfaces
on `SubnetID` according to NeoFS API V2 protocol.

Signed-off-by: Leonard Lyubich <[email protected]>
  • Loading branch information
Leonard Lyubich authored and cthulhu-rider committed Nov 24, 2021
1 parent f0af5ce commit 0e6e0e4
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
32 changes: 32 additions & 0 deletions refs/types.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package refs

import (
"fmt"
"strconv"
)

type OwnerID struct {
val []byte
}
Expand Down Expand Up @@ -183,6 +188,33 @@ func (s *SubnetID) GetValue() uint32 {
return 0
}

// MarshalText encodes SubnetID into text format according to NeoFS API V2 protocol:
// value in base-10 integer string format.
//
// Implements encoding.TextMarshaler.
func (s *SubnetID) MarshalText() ([]byte, error) {
num := s.GetValue() // NPE safe, returns zero on nil (zero subnet)

return []byte(strconv.FormatUint(uint64(num), 10)), nil
}

// UnmarshalText decodes SubnetID from the text according to NeoFS API V2 protocol:
// should be base-10 integer string format.
//
// Must not be called on nil.
//
// Implements encoding.TextUnmarshaler.
func (s *SubnetID) UnmarshalText(txt []byte) error {
num, err := strconv.ParseUint(string(txt), 10, 32)
if err != nil {
return fmt.Errorf("invalid numeric value: %w", err)
}

s.value = uint32(num)

return nil
}

// IsZeroSubnet returns true iff the SubnetID refers to zero subnet.
func IsZeroSubnet(id *SubnetID) bool {
return id.GetValue() == 0
Expand Down
30 changes: 30 additions & 0 deletions refs/types_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package refs_test

import (
"strconv"
"testing"

"github.com/nspcc-dev/neofs-api-go/v2/refs"
Expand All @@ -18,3 +19,32 @@ func TestZeroSubnet(t *testing.T) {
refs.MakeZeroSubnet(id)
require.True(t, refs.IsZeroSubnet(id))
}

func TestSubnetID_MarshalText(t *testing.T) {
var id refs.SubnetID

const val = 15

id.SetValue(val)

txt, err := id.MarshalText()
require.NoError(t, err)

res, err := strconv.ParseUint(string(txt), 10, 32)
require.NoError(t, err)

require.EqualValues(t, val, res)
}

func TestSubnetID_UnmarshalText(t *testing.T) {
const val = 15

str := strconv.FormatUint(val, 10)

var id refs.SubnetID

err := id.UnmarshalText([]byte(str))
require.NoError(t, err)

require.EqualValues(t, val, id.GetValue())
}

0 comments on commit 0e6e0e4

Please sign in to comment.