aboutsummaryrefslogtreecommitdiffstats
path: root/utils/merkletrie/internal/frame/frame.go
blob: fd0630781675a3a01e70b126b95585f5aca2b2b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package frame

import (
	"bytes"
	"fmt"
	"sort"
	"strings"

	"srcd.works/go-git.v4/utils/merkletrie/noder"
)

// A Frame is a collection of siblings in a trie, sorted alphabetically
// by name.
type Frame struct {
	// siblings, sorted in reverse alphabetical order by name
	stack []noder.Noder
}

type byName []noder.Noder

func (a byName) Len() int      { return len(a) }
func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool {
	return strings.Compare(a[i].Name(), a[j].Name()) < 0
}

// New returns a frame with the children of the provided node.
func New(n noder.Noder) (*Frame, error) {
	children, err := n.Children()
	if err != nil {
		return nil, err
	}

	sort.Sort(sort.Reverse(byName(children)))
	return &Frame{
		stack: children,
	}, nil
}

// String returns the quoted names of the noders in the frame sorted in
// alphabeticall order by name, surrounded by square brackets and
// separated by comas.
//
// Examples:
//     []
//     ["a", "b"]
func (f *Frame) String() string {
	var buf bytes.Buffer
	_ = buf.WriteByte('[')

	sep := ""
	for i := f.Len() - 1; i >= 0; i-- {
		_, _ = buf.WriteString(sep)
		sep = ", "
		_, _ = buf.WriteString(fmt.Sprintf("%q", f.stack[i].Name()))
	}

	_ = buf.WriteByte(']')

	return buf.String()
}

// First returns, but dont extract, the noder with the alphabetically
// smaller name in the frame and true if the frame was not empy.
// Otherwise it returns nil and false.
func (f *Frame) First() (noder.Noder, bool) {
	if f.Len() == 0 {
		return nil, false
	}

	top := f.Len() - 1

	return f.stack[top], true
}

// Drop extracts the noder with the alphabetically smaller name in the
// frame or does nothing if the frame was empty.
func (f *Frame) Drop() {
	if f.Len() == 0 {
		return
	}

	top := f.Len() - 1
	f.stack[top] = nil
	f.stack = f.stack[:top]
}

// Len returns the number of noders in the frame.
func (f *Frame) Len() int {
	return len(f.stack)
}