Remove cap tricks, use address comparison for subslice offset

Replace cap(parent) - cap(subslice) with a straightforward scan
that compares element addresses: &data[i] == &subslice[0]. This is
well-defined Go pointer comparison on elements of the same backing
array, with no dependency on capacity semantics, reflect, or unsafe.

The scan is O(n) but only runs on error paths, and TOML documents
are small per the project's design constraints.

Also remove the Offset field from ParserError and the setErrOffset
machinery — the offset is computed at the point of consumption
(wrapDecodeError, Parser.Range) rather than cached on the error.

Co-authored-by: Thomas Pelletier <thomas@pelletier.dev>
This commit is contained in:
Cursor Agent
2026-04-12 18:17:55 +00:00
parent 96ac48eb74
commit 19174a4293
5 changed files with 31 additions and 82 deletions
+15 -1
View File
@@ -99,7 +99,7 @@ func (e *DecodeError) Key() Key {
//
//nolint:funlen
func wrapDecodeError(document []byte, de *unstable.ParserError) *DecodeError {
offset := cap(document) - cap(de.Highlight)
offset := subsliceOffset(document, de.Highlight)
errMessage := de.Error()
errLine, errColumn := positionAtEnd(document[:offset])
@@ -261,3 +261,17 @@ func positionAtEnd(b []byte) (row int, column int) {
return row, column
}
// subsliceOffset finds the byte offset of subslice within data by
// scanning for the matching element address.
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")
}