Skip to content

Commit

Permalink
feat: add MarshalSlice
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Stewart <[email protected]>
  • Loading branch information
paralin committed Jul 19, 2024
1 parent 969a3aa commit c529f78
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
18 changes: 18 additions & 0 deletions json/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,24 @@ func (c MarshalerConfig) Marshal(m Marshaler) ([]byte, error) {
return buf.Bytes(), nil
}

// MarshalSlice marshals a slice of Marshalers into a JSON array.
func (c MarshalerConfig) MarshalSlice(ms []Marshaler) ([]byte, error) {
var buf bytes.Buffer
s := NewMarshalState(c, NewJsonStream(&buf))
s.WriteArrayStart()
for i, m := range ms {
if i > 0 {
s.WriteMore()
}
m.MarshalProtoJSON(s)
}
s.WriteArrayEnd()
if err := s.Err(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}

// MarshalState is the internal state of the Marshaler.
type MarshalState struct {
inner *JsonStream
Expand Down
32 changes: 32 additions & 0 deletions json/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,35 @@ func TestMarshaler(t *testing.T) {
testMarshal(t, func(s *MarshalState) { s.WriteDuration(testDuration.Truncate(100000000)) }, `"3723.100s"`)
testMarshal(t, func(s *MarshalState) { s.WriteDuration(testDuration.Truncate(1000000000)) }, `"3723s"`)
}

type testMarshaler struct {
value int
}

func (m *testMarshaler) MarshalProtoJSON(s *MarshalState) {
s.WriteObjectStart()
s.WriteObjectField("value")
s.WriteInt32(int32(m.value))
s.WriteObjectEnd()
}

func TestMarshalSlice(t *testing.T) {
testSlice := []Marshaler{
&testMarshaler{value: 1},
&testMarshaler{value: 2},
&testMarshaler{value: 3},
}

expected := `[{"value":1},{"value":2},{"value":3}]`

config := DefaultMarshalerConfig

result, err := config.MarshalSlice(testSlice)
if err != nil {
t.Errorf("MarshalSlice returned an error: %v", err)
}

if string(result) != expected {
t.Errorf("MarshalSlice result does not match expected.\nGot: %s\nExpected: %s", string(result), expected)
}
}

0 comments on commit c529f78

Please sign in to comment.