WriteMapSorted writes a map to the provided Writer. The keys of the map are sorted before writing. This provides deterministic output, but will allocate to sort the keys. The writeKey and writeVal parameters specify the functions to use to write each key and value of the map.
(w *Writer, m map[K]V, writeKey func(K) error, writeVal func(V) error)
| 141 | // The writeKey and writeVal parameters specify the functions |
| 142 | // to use to write each key and value of the map. |
| 143 | func WriteMapSorted[K cmp.Ordered, V any](w *Writer, m map[K]V, writeKey func(K) error, writeVal func(V) error) error { |
| 144 | if m == nil { |
| 145 | return w.WriteNil() |
| 146 | } |
| 147 | if uint64(len(m)) > math.MaxUint32 { |
| 148 | return fmt.Errorf("map too large to encode: %d elements", len(m)) |
| 149 | } |
| 150 | |
| 151 | // Write map header |
| 152 | err := w.WriteMapHeader(uint32(len(m))) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | // Write elements |
| 157 | for _, k := range slices.Sorted(maps.Keys(m)) { |
| 158 | err = writeKey(k) |
| 159 | if err != nil { |
| 160 | return err |
| 161 | } |
| 162 | err = writeVal(m[k]) |
| 163 | if err != nil { |
| 164 | return err |
| 165 | } |
| 166 | } |
| 167 | return nil |
| 168 | } |
| 169 | |
| 170 | // ReadArrayBytes returns an iterator that can be used to iterate over the elements |
| 171 | // of an array in the MessagePack data while being read by the provided Reader. |
searching dependent graphs…