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:
+2
-16
@@ -69,8 +69,8 @@ func (p *Parser) Data() []byte {
|
||||
// panics.
|
||||
func (p *Parser) Range(b []byte) Range {
|
||||
return Range{
|
||||
Offset: uint32(p.subsliceOffset(b)), //nolint:gosec // TOML documents are small
|
||||
Length: uint32(len(b)), //nolint:gosec // TOML documents are small
|
||||
Offset: uint32(SubsliceOffset(p.data, b)), //nolint:gosec // TOML documents are small
|
||||
Length: uint32(len(b)), //nolint:gosec // TOML documents are small
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,20 +82,6 @@ func (p *Parser) rangeOfToken(token, rest []byte) Range {
|
||||
return Range{Offset: uint32(offset), Length: uint32(len(token))} //nolint:gosec // TOML documents are small
|
||||
}
|
||||
|
||||
// subsliceOffset finds the byte offset of subslice b within p.data
|
||||
// by scanning for the matching element address.
|
||||
func (p *Parser) subsliceOffset(b []byte) int {
|
||||
if len(b) == 0 {
|
||||
return len(p.data)
|
||||
}
|
||||
for i := range p.data {
|
||||
if &p.data[i] == &b[0] {
|
||||
return i
|
||||
}
|
||||
}
|
||||
panic("subslice is not within parser data")
|
||||
}
|
||||
|
||||
// Raw returns the slice corresponding to the bytes in the given range.
|
||||
func (p *Parser) Raw(raw Range) []byte {
|
||||
return p.data[raw.Offset : raw.Offset+raw.Length]
|
||||
|
||||
Reference in New Issue
Block a user