1package pointerstructure
2
3import (
4	"sort"
5)
6
7// Sort does an in-place sort of the pointers so that they are in order
8// of least specific to most specific alphabetized. For example:
9// "/foo", "/foo/0", "/qux"
10//
11// This ordering is ideal for applying the changes in a way that ensures
12// that parents are set first.
13func Sort(p []*Pointer) { sort.Sort(PointerSlice(p)) }
14
15// PointerSlice is a slice of pointers that adheres to sort.Interface
16type PointerSlice []*Pointer
17
18func (p PointerSlice) Len() int      { return len(p) }
19func (p PointerSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
20func (p PointerSlice) Less(i, j int) bool {
21	// Equal number of parts, do a string compare per part
22	for idx, ival := range p[i].Parts {
23		// If we're passed the length of p[j] parts, then we're done
24		if idx >= len(p[j].Parts) {
25			break
26		}
27
28		// Compare the values if they're not equal
29		jval := p[j].Parts[idx]
30		if ival != jval {
31			return ival < jval
32		}
33	}
34
35	// Equal prefix, take the shorter
36	if len(p[i].Parts) != len(p[j].Parts) {
37		return len(p[i].Parts) < len(p[j].Parts)
38	}
39
40	// Equal, it doesn't matter
41	return false
42}
43