Debian Codegraph @

internal/sort/map.go

raw
1 // Copyright (c) 2025, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package sort
8
9 import (
10 "reflect"
11 "sort"
12
13 "github.com/maxatome/go-testdeep/internal/compare"
14 "github.com/maxatome/go-testdeep/internal/visited"
15 )
16
17 type kv struct {
18 key reflect.Value
19 value reflect.Value
20 }
21
22 type kvSlice struct {
23 v visited.Visited
24 s []kv
25 }
26
27 func newKvSlice(l int) *kvSlice {
28 s := kvSlice{}
29 if l > 0 {
30 s.s = make([]kv, 0, l)
31 if l > 1 {
32 s.v = visited.NewVisited()
33 }
34 }
35 return &s
36 }
37
38 func (s *kvSlice) Len() int { return len(s.s) }
39 func (s *kvSlice) Less(i, j int) bool {
40 return compare.Compare(s.v, s.s[i].key, s.s[j].key) < 0
41 }
42 func (s *kvSlice) Swap(i, j int) { s.s[i], s.s[j] = s.s[j], s.s[i] }
43
44 // MapEach calls fn for each key/value pair of map m using the order
45 // of keys. If fn returns false, it will not be called again.
46 // MapEach returns false if fn returned false.
47 func MapEach(m reflect.Value, fn func(k, v reflect.Value) bool) bool {
48 kvs := newKvSlice(m.Len())
49 iter := m.MapRange()
50 for iter.Next() {
51 kvs.s = append(kvs.s, kv{key: iter.Key(), value: iter.Value()})
52 }
53 sort.Sort(kvs)
54
55 for _, kv := range kvs.s {
56 if !fn(kv.key, kv.value) {
57 return false
58 }
59 }
60 return true
61 }