Skip to content

Commit 5817f93

Browse files
authored
Add "setof" helpers (#408)
* Add `FooFromSlice` that will convert a slice of type to map[foo]struct{} * Add `Foo.AsSlice` that will return the set as a slice (sorted on sorted types). * Use `clear` to clear maps (Go 1.21) We can't use fancy `maps` and `slices` methods yet, since that is Go 1.23.
1 parent ae1aabc commit 5817f93

File tree

2 files changed

+757
-178
lines changed

2 files changed

+757
-178
lines changed

msgp/setof/_gen/main.go

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,7 @@ func (s *Foo) DecodeMsg(reader *msgp.Reader) error {
2121
if dst == nil {
2222
dst = make(Foo, sz)
2323
} else {
24-
for k := range dst {
25-
delete(dst, k)
26-
}
24+
clear(dst)
2725
}
2826
for i := uint32(0); i < sz; i++ {
2927
var k string
@@ -52,9 +50,7 @@ func (s *Foo) UnmarshalMsg(bytes []byte) ([]byte, error) {
5250
if dst == nil {
5351
dst = make(Foo, sz)
5452
} else {
55-
for k := range dst {
56-
delete(dst, k)
57-
}
53+
clear(dst)
5854
}
5955
for i := uint32(0); i < sz; i++ {
6056
var k string
@@ -80,6 +76,18 @@ func (s Foo) Msgsize() int {
8076
size += len(s) * msgp.StringPrefixSize
8177
return size
8278
}
79+
80+
// FooFromSlice creates a Foo from a slice.
81+
func FooFromSlice(s []string) Foo {
82+
if s == nil {
83+
return nil
84+
}
85+
dst := make(Foo, len(s))
86+
for _, v := range s {
87+
dst[v] = struct{}{}
88+
}
89+
return dst
90+
}
8391
`
8492

8593
const unsorted = `
@@ -119,6 +127,18 @@ func (s Foo) MarshalMsg(bytes []byte) ([]byte, error) {
119127
}
120128
return bytes, nil
121129
}
130+
131+
// AsSlice returns the set as a slice.
132+
func (s Foo) AsSlice() []string {
133+
if s == nil {
134+
return nil
135+
}
136+
dst := make([]string, 0, len(s))
137+
for k := range s {
138+
dst = append(dst, k)
139+
}
140+
return dst
141+
}
122142
`
123143

124144
const sorted = `
@@ -169,6 +189,19 @@ func (s Foo) MarshalMsg(bytes []byte) ([]byte, error) {
169189
}
170190
return bytes, nil
171191
}
192+
193+
// AsSlice returns the set as a sorted slice.
194+
func (s Foo) AsSlice() []string {
195+
if s == nil {
196+
return nil
197+
}
198+
dst := make([]string, 0, len(s))
199+
for k := range s {
200+
dst = append(dst, k)
201+
}
202+
sort.Slice(dst, func(i, j int) bool { return dst[i] < dst[j] })
203+
return dst
204+
}
172205
`
173206

174207
type replacer struct {

0 commit comments

Comments
 (0)