Skip to content

Commit

Permalink
Add a utility function for converting path.Trace to a list
Browse files Browse the repository at this point in the history
There are cases in which users of path.Trace want to do forward
iteration of the path. path.Trace does not permit it, because it's a
backward pointing linked list.

Instead of adding a ToList() function, we could have extended Trace to
implement Parser. But this is needlessly complex, because traces are
guaranteed to be well formed, and unlike Builder don't contain any ".."
components.
  • Loading branch information
EdSchouten committed Aug 10, 2024
1 parent 02b8a19 commit 3f5e30c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/filesystem/path/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,19 @@ func (t *Trace) GetWindowsString() (string, error) {
t.writeToStringBuilder('\\', &sb)
return sb.String(), nil
}

// ToList returns the pathname components contained in the trace to a list.
func (t *Trace) ToList() []Component {
count := 0
for tCount := t; tCount != nil; tCount = tCount.parent {
count++
}

components := make([]Component, count)
for count > 0 {
count--
components[count] = t.component
t = t.parent
}
return components
}
23 changes: 23 additions & 0 deletions pkg/filesystem/path/trace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,27 @@ func TestTrace(t *testing.T) {
testutil.RequireEqualStatus(t, status.Error(codes.InvalidArgument, "Invalid pathname component \"b?\": Pathname component contains reserved characters"), err)
}
})

t.Run("ToList", func(t *testing.T) {
var p1 *path.Trace
require.Empty(t, p1.ToList())

p2 := p1.Append(path.MustNewComponent("a"))
require.Equal(t, []path.Component{
path.MustNewComponent("a"),
}, p2.ToList())

p3 := p2.Append(path.MustNewComponent("b"))
require.Equal(t, []path.Component{
path.MustNewComponent("a"),
path.MustNewComponent("b"),
}, p3.ToList())

p4 := p3.Append(path.MustNewComponent("c"))
require.Equal(t, []path.Component{
path.MustNewComponent("a"),
path.MustNewComponent("b"),
path.MustNewComponent("c"),
}, p4.ToList())
})
}

0 comments on commit 3f5e30c

Please sign in to comment.