File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -30,6 +30,7 @@ package tcpip
30
30
31
31
import (
32
32
"bytes"
33
+ "encoding/json"
33
34
"errors"
34
35
"fmt"
35
36
"io"
@@ -1633,6 +1634,21 @@ func (s *StatCounter) String() string {
1633
1634
return strconv .FormatUint (s .Value (), 10 )
1634
1635
}
1635
1636
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
+
1636
1652
// A MultiCounterStat keeps track of two counters at once.
1637
1653
//
1638
1654
// +stateify savable
Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ package tcpip
16
16
17
17
import (
18
18
"bytes"
19
+ "encoding/json"
19
20
"fmt"
20
21
"io"
21
22
"net"
@@ -345,3 +346,25 @@ func padTo4(partial string) []byte {
345
346
}
346
347
return []byte (partial )
347
348
}
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
+ }
You can’t perform that action at this time.
0 commit comments