Fix incorrect error positions for non-suffix subslices in unstable.Parser.Range (#1047)
The unsafe removal (#1021) replaced danger.SubsliceOffset (pointer arithmetic) with len(p.data)-len(b), which only works for suffix slices. Parser.Range is called with arbitrary interior subslices (e.g. ParserError.Highlight), so the offset was wrong whenever the error occurred after previously scanned content like comments. Fix by using reflect.ValueOf().Pointer() to recover the actual data pointer, matching the approach already used in errors.go. https://claude.ai/code/session_01EXYfFXc3DDGpQ27sWdXTKq
This commit is contained in:
+8
-3
@@ -3,6 +3,7 @@ package unstable
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"unicode"
|
||||
|
||||
"github.com/pelletier/go-toml/v2/internal/characters"
|
||||
@@ -83,10 +84,14 @@ func (p *Parser) rangeOfToken(token, rest []byte) Range {
|
||||
}
|
||||
|
||||
// subsliceOffset returns the byte offset of subslice b within p.data.
|
||||
// b must be a suffix (tail) of p.data.
|
||||
// b must be a subslice of p.data (sharing the same backing array).
|
||||
func (p *Parser) subsliceOffset(b []byte) int {
|
||||
// b is a suffix of p.data, so its offset is len(p.data) - len(b)
|
||||
return len(p.data) - len(b)
|
||||
if len(b) == 0 {
|
||||
return 0
|
||||
}
|
||||
dataPtr := reflect.ValueOf(p.data).Pointer()
|
||||
subPtr := reflect.ValueOf(b).Pointer()
|
||||
return int(subPtr - dataPtr)
|
||||
}
|
||||
|
||||
// Raw returns the slice corresponding to the bytes in the given range.
|
||||
|
||||
Reference in New Issue
Block a user