Consolidate subslice offset into a single SubsliceOffset function
Remove the private subsliceOffset methods from both parser.go and errors.go. Replace them with a single exported SubsliceOffset function in ast.go (next to the Range type it serves). SubsliceOffset finds the byte offset by comparing element addresses: &data[i] == &subslice[0]. This is well-defined Go pointer comparison on elements of the same backing array. This fixes the v2.3.0 regression (#1047) where the parser's subsliceOffset used len(data) - len(b), which only works for suffix slices, not arbitrary subslices like error highlights. It also removes the reflect-based implementation from errors.go. Fixes #1047 Co-authored-by: Thomas Pelletier <thomas@pelletier.dev>
This commit is contained in:
@@ -90,6 +90,21 @@ type Range struct {
|
||||
Length uint32
|
||||
}
|
||||
|
||||
// SubsliceOffset returns the byte offset of subslice within data.
|
||||
// Subslice must be a subslice of data, meaning it must point into the
|
||||
// same backing array. Panics if subslice is not within data.
|
||||
func SubsliceOffset(data []byte, subslice []byte) int {
|
||||
if len(subslice) == 0 {
|
||||
return len(data)
|
||||
}
|
||||
for i := range data {
|
||||
if &data[i] == &subslice[0] {
|
||||
return i
|
||||
}
|
||||
}
|
||||
panic("subslice is not within data")
|
||||
}
|
||||
|
||||
// Next returns a pointer to the next node, or nil if there is no next node.
|
||||
func (n *Node) Next() *Node {
|
||||
if n.next < 0 {
|
||||
|
||||
Reference in New Issue
Block a user