Replace reflect-based subslice offset with cap arithmetic

Use cap(parent) - cap(subslice) to compute byte offsets between slices
that share a backing array. This is safe pure Go: subslicing preserves
the backing array and adjusts the capacity accordingly, so the
difference in capacities equals the byte offset.

This removes the reflect import from both errors.go and
unstable/parser.go, eliminating the last reflect-based pointer
arithmetic used for error position tracking.

Co-authored-by: Thomas Pelletier <thomas@pelletier.dev>
This commit is contained in:
Cursor Agent
2026-04-12 17:08:58 +00:00
parent 154d80392f
commit f7136d052b
2 changed files with 4 additions and 30 deletions
+1 -11
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"errors"
"fmt"
"reflect"
"unicode"
"github.com/pelletier/go-toml/v2/internal/characters"
@@ -105,16 +104,7 @@ func (p *Parser) rangeOfToken(token, rest []byte) Range {
// subsliceOffset returns the byte offset of subslice b within p.data.
// b must share the same backing array as p.data.
func (p *Parser) subsliceOffset(b []byte) int {
if len(b) == 0 {
return 0
}
dataPtr := reflect.ValueOf(p.data).Pointer()
subPtr := reflect.ValueOf(b).Pointer()
offset := int(subPtr - dataPtr)
if offset < 0 || offset > len(p.data) {
panic("subslice is not within parser data")
}
return offset
return cap(p.data) - cap(b)
}
// Raw returns the slice corresponding to the bytes in the given range.