util/set: implement json.Marshaler/Unmarshaler (#10308)

Marshal as a JSON list instead of a map. Because set elements are
`comparable` and not `cmp.Ordered`, we cannot easily sort the items
before marshaling.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
This commit is contained in:
Andrew Lytvynov
2023-11-20 09:00:31 -07:00
committed by GitHub
parent dd8bc9ba03
commit 2c1f14d9e6
2 changed files with 60 additions and 0 deletions

View File

@@ -5,6 +5,7 @@
package set
import (
"encoding/json"
"maps"
)
@@ -66,3 +67,16 @@ func (s Set[T]) Len() int { return len(s) }
func (s Set[T]) Equal(other Set[T]) bool {
return maps.Equal(s, other)
}
func (s Set[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Slice())
}
func (s *Set[T]) UnmarshalJSON(buf []byte) error {
var ss []T
if err := json.Unmarshal(buf, &ss); err != nil {
return err
}
*s = SetOf(ss)
return nil
}