Debian Codegraph @

utils/merkletrie/noder/path.go

raw
1 package noder
2
3 import (
4 "bytes"
5 "strings"
6 )
7
8 // Path values represent a noder and its ancestors. The root goes first
9 // and the actual final noder the path is referring to will be the last.
10 //
11 // A path implements the Noder interface, redirecting all the interface
12 // calls to its final noder.
13 //
14 // Paths build from an empty Noder slice are not valid paths and should
15 // not be used.
16 type Path []Noder
17
18 func (p Path) Skip() bool {
19 if len(p) > 0 {
20 return p.Last().Skip()
21 }
22
23 return false
24 }
25
26 // String returns the full path of the final noder as a string, using
27 // "/" as the separator.
28 func (p Path) String() string {
29 var buf bytes.Buffer
30 sep := ""
31 for _, e := range p {
32 _, _ = buf.WriteString(sep)
33 sep = "/"
34 _, _ = buf.WriteString(e.Name())
35 }
36
37 return buf.String()
38 }
39
40 // Last returns the final noder in the path.
41 func (p Path) Last() Noder {
42 return p[len(p)-1]
43 }
44
45 // Hash returns the hash of the final noder of the path.
46 func (p Path) Hash() []byte {
47 return p.Last().Hash()
48 }
49
50 // Name returns the name of the final noder of the path.
51 func (p Path) Name() string {
52 return p.Last().Name()
53 }
54
55 // IsDir returns if the final noder of the path is a directory-like
56 // noder.
57 func (p Path) IsDir() bool {
58 return p.Last().IsDir()
59 }
60
61 // Children returns the children of the final noder in the path.
62 func (p Path) Children() ([]Noder, error) {
63 return p.Last().Children()
64 }
65
66 // NumChildren returns the number of children the final noder of the
67 // path has.
68 func (p Path) NumChildren() (int, error) {
69 return p.Last().NumChildren()
70 }
71
72 // Compare returns -1, 0 or 1 if the path p is smaller, equal or bigger
73 // than other, in "directory order"; for example:
74 //
75 // "a" < "b"
76 // "a/b/c/d/z" < "b"
77 // "a/b/a" > "a/b"
78 func (p Path) Compare(other Path) int {
79 i := 0
80 for {
81 switch {
82 case len(other) == len(p) && i == len(p):
83 return 0
84 case i == len(other):
85 return 1
86 case i == len(p):
87 return -1
88 default:
89 // We do *not* normalize Unicode here. CGit doesn't.
90 // https://github.com/src-d/go-git/issues/1057
91 cmp := strings.Compare(p[i].Name(), other[i].Name())
92 if cmp != 0 {
93 return cmp
94 }
95 }
96 i++
97 }
98 }