Skip to content

Commit d53107c

Browse files
committed
pkg/tcpip: impl json.Marshaler/Unmarshaler for StatCounter to Marshal/Unmarshal *Stats
1 parent c8952f7 commit d53107c

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

pkg/tcpip/tcpip.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ package tcpip
3030

3131
import (
3232
"bytes"
33+
"encoding/json"
3334
"errors"
3435
"fmt"
3536
"io"
@@ -1633,6 +1634,21 @@ func (s *StatCounter) String() string {
16331634
return strconv.FormatUint(s.Value(), 10)
16341635
}
16351636

1637+
// MarshalJSON implements json.Marshaler.MarshalJSON
1638+
func (s *StatCounter) MarshalJSON() ([]byte, error) {
1639+
return json.Marshal(s.Value())
1640+
}
1641+
1642+
// UnmarshalJSON implements json.Unmarshaler.UnmarshalJSON
1643+
func (s *StatCounter) UnmarshalJSON(data []byte) error {
1644+
var val uint64
1645+
if err := json.Unmarshal(data, &val); err != nil {
1646+
return err
1647+
}
1648+
s.count.Store(val)
1649+
return nil
1650+
}
1651+
16361652
// A MultiCounterStat keeps track of two counters at once.
16371653
//
16381654
// +stateify savable

pkg/tcpip/tcpip_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package tcpip
1616

1717
import (
1818
"bytes"
19+
"encoding/json"
1920
"fmt"
2021
"io"
2122
"net"
@@ -345,3 +346,25 @@ func padTo4(partial string) []byte {
345346
}
346347
return []byte(partial)
347348
}
349+
350+
func TestStats_Marshal(t *testing.T) {
351+
s := Stats{}.FillIn()
352+
s.TCP.ForwardMaxInFlightDrop.Increment()
353+
jb, err := json.Marshal(s)
354+
if err != nil {
355+
t.Fail()
356+
}
357+
if !bytes.Contains(jb, []byte(`"ForwardMaxInFlightDrop":1`)) {
358+
t.Fatalf("Marshal did not contain ForwardMaxInFlightDrop")
359+
}
360+
361+
todo := `{"TCP":{"ForwardMaxInFlightDrop":1}}`
362+
var to Stats
363+
err = json.Unmarshal([]byte(todo), &to)
364+
if err != nil {
365+
t.Fail()
366+
}
367+
if got := to.TCP.ForwardMaxInFlightDrop.Value(); got != uint64(1) {
368+
t.Fatalf("got ForwardMaxInFlightDrop.Value() = %d, want = %d", got, uint64(1))
369+
}
370+
}

0 commit comments

Comments
 (0)