Skip to content

Commit

Permalink
Add Path.Index helper method (#56)
Browse files Browse the repository at this point in the history
An analysis of user code shows that Path.Last was not sufficient and
that what users really wanted was an easy want to do negative indexing
without needing to constantly check for out-of-bounds.

Thus, add a generic Index method that does not panic on out-of-bounds
accesses and supports negative indexing.
  • Loading branch information
dsnet committed Dec 2, 2017
1 parent 009f2ca commit 88141e9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
11 changes: 4 additions & 7 deletions cmp/cmpopts/ignore.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (tf typeFilter) filter(p cmp.Path) bool {
if len(p) < 1 {
return false
}
t := p[len(p)-1].Type()
t := p.Last().Type()
for _, ti := range tf {
if t.AssignableTo(ti) {
return true
Expand Down Expand Up @@ -95,7 +95,7 @@ func (tf ifaceFilter) filter(p cmp.Path) bool {
if len(p) < 1 {
return false
}
t := p[len(p)-1].Type()
t := p.Last().Type()
for _, ti := range tf {
if t.AssignableTo(ti) {
return true
Expand Down Expand Up @@ -131,14 +131,11 @@ func newUnexportedFilter(typs ...interface{}) unexportedFilter {
return ux
}
func (xf unexportedFilter) filter(p cmp.Path) bool {
if len(p) < 2 {
return false
}
sf, ok := p[len(p)-1].(cmp.StructField)
sf, ok := p.Index(-1).(cmp.StructField)
if !ok {
return false
}
return xf.m[p[len(p)-2].Type()] && !isExported(sf.Name())
return xf.m[p.Index(-2).Type()] && !isExported(sf.Name())
}

// isExported reports whether the identifier is exported.
Expand Down
17 changes: 14 additions & 3 deletions cmp/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,21 @@ func (pa *Path) pop() {
// Last returns the last PathStep in the Path.
// If the path is empty, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Last() PathStep {
if len(pa) > 0 {
return pa[len(pa)-1]
return pa.Index(-1)
}

// Index returns the ith step in the Path and supports negative indexing.
// A negative index starts counting from the tail of the Path such that -1
// refers to the last step, -2 refers to the second-to-last step, and so on.
// If index is invalid, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Index(i int) PathStep {
if i < 0 {
i = len(pa) + i
}
if i < 0 || i >= len(pa) {
return pathStep{}
}
return pathStep{}
return pa[i]
}

// String returns the simplified path to a node.
Expand Down

0 comments on commit 88141e9

Please sign in to comment.