Debian Codegraph @

utils/merkletrie/internal/frame/frame.go

raw
1 package frame
2
3 import (
4 "bytes"
5 "fmt"
6 "sort"
7 "strings"
8
9 "github.com/go-git/go-git/v5/utils/merkletrie/noder"
10 )
11
12 // A Frame is a collection of siblings in a trie, sorted alphabetically
13 // by name.
14 type Frame struct {
15 // siblings, sorted in reverse alphabetical order by name
16 stack []noder.Noder
17 }
18
19 type byName []noder.Noder
20
21 func (a byName) Len() int { return len(a) }
22 func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
23 func (a byName) Less(i, j int) bool {
24 return strings.Compare(a[i].Name(), a[j].Name()) < 0
25 }
26
27 // New returns a frame with the children of the provided node.
28 func New(n noder.Noder) (*Frame, error) {
29 children, err := n.Children()
30 if err != nil {
31 return nil, err
32 }
33
34 sort.Sort(sort.Reverse(byName(children)))
35 return &Frame{
36 stack: children,
37 }, nil
38 }
39
40 // String returns the quoted names of the noders in the frame sorted in
41 // alphabetical order by name, surrounded by square brackets and
42 // separated by comas.
43 //
44 // Examples:
45 // []
46 // ["a", "b"]
47 func (f *Frame) String() string {
48 var buf bytes.Buffer
49 _ = buf.WriteByte('[')
50
51 sep := ""
52 for i := f.Len() - 1; i >= 0; i-- {
53 _, _ = buf.WriteString(sep)
54 sep = ", "
55 _, _ = buf.WriteString(fmt.Sprintf("%q", f.stack[i].Name()))
56 }
57
58 _ = buf.WriteByte(']')
59
60 return buf.String()
61 }
62
63 // First returns, but dont extract, the noder with the alphabetically
64 // smaller name in the frame and true if the frame was not empty.
65 // Otherwise it returns nil and false.
66 func (f *Frame) First() (noder.Noder, bool) {
67 if f.Len() == 0 {
68 return nil, false
69 }
70
71 top := f.Len() - 1
72
73 return f.stack[top], true
74 }
75
76 // Drop extracts the noder with the alphabetically smaller name in the
77 // frame or does nothing if the frame was empty.
78 func (f *Frame) Drop() {
79 if f.Len() == 0 {
80 return
81 }
82
83 top := f.Len() - 1
84 f.stack[top] = nil
85 f.stack = f.stack[:top]
86 }
87
88 // Len returns the number of noders in the frame.
89 func (f *Frame) Len() int {
90 return len(f.stack)
91 }