v0.3.0 format a document, each comment with its owner; fewer allocations on the hot path
Test / test (push) Canceled after 0s

* Benchmarks for the parse, decode, encode and document paths

A command's payload from text to its struct, a settings file with comment
blocks, a scenario file of arrays of inline tables across lines, decoding
and encoding that scenario, and ParseDocument: the readings the changes
that follow are measured by.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ThctvSRwt5kV1pVMKtsdWc

* Fewer allocations on the parse, decode and encode paths

The parser's lexer drops what it never reads: a comment's text and a
number's literal, which the parser parses from the input bytes in place.
A string without escapes is one allocation, one with escapes is decoded
into a buffer sized to its source. The lexer scans ASCII bytewise, the
parser holds its lexer by value, keeps key paths on the stack, gathers an
array's elements in a reused buffer and allocates the array once at its
length, and holds the first few frozen inline tables in place; an inline
table that is an array element is not held, as no key can reach it.

Decode, Marshal and Unmapped read a struct's fields from one cache per
type instead of splitting every tag on every call. Decode reuses one key
and one element per map; Marshal sets a map's values into one array, and
writes keys, headers and numbers into its buffer without concatenating.

Tokens, positions, trees, error messages, encoded bytes and decoded
values are unchanged: a differential fuzz against the previous sources
ran 1.7M inputs over the lexer and parser and 9.5M over Marshal and
Decode without a difference.

benchstat, 8 runs each, Xeon 2.1 GHz:
  payload, parse and decode  3.31us -> 2.30us   31 -> 14 allocs  1.41 -> 1.09 KiB
  parse payload              2.40us -> 1.89us   24 -> 12 allocs
  parse settings            10.25us -> 6.98us   68 -> 32 allocs
  parse scenario             536us -> 391us   4959 -> 2970 allocs
  decode scenario            225us -> 110us   1863 -> 776 allocs
  marshal scenario           397us -> 252us   2326 -> 976 allocs
  ParseDocument settings    21.7us -> 16.5us   128 -> 85 allocs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ThctvSRwt5kV1pVMKtsdWc

* Document: a comment goes with what fewer blank lines part it from

ParseDocument lays a document out as statements, runs of statements no
blank line parts, and the comment groups between them. A group belongs
to the side fewer blank lines part it from, the side below on a tie:
right above a statement it is that statement's own; right below a run, or
apart from it, it is the run's. Between two runs several groups split at
the widest gap. The file's start counts as no blank line and its end as
half of one, so a comment at the top with a blank line under it, or at
the end with one above it, is the file's, and one touching the last
statement stays with it.

Delete takes a statement with its own comments; a run going whole takes
its comments too and one blank run beside it, so no comment is left
orphaned and no gap doubles. Set puts a new table above the file's
closing comments and a first root key above the first table's comments,
a blank line apart. What v0.2.0 kept by position (the comment above a
dropped key, a dropped table's heading) now goes with its owner.

FuzzDocument checks that a delete leaves whole lines the document had,
in order, and that adding a key loses none; it ran 12.6M inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ThctvSRwt5kV1pVMKtsdWc

* Format: one layout for a document, every comment kept with its owner

Format, and Formatter for its options, writes a document spaced as
Marshal writes one: one space around = and after a comma, [1, 2] and
{ a = 1 }, LF line ends, a value's lines a level deeper than the line its
bracket opens on, and a trailing comma exactly when the closing bracket
has a line of its own. Keys, scalars and comments keep their spelling.

Comments stay with what they belong to by the rule Document reads them
with, and the result's blank lines encode it again: a run of blank lines
becomes one, or two below a comment group that belongs above it, so a
second Format reads every comment as the first did and writes the same
bytes. Each table is written once, at its first header: a header opening
it again gives its keys there, its comments above the key they touched or
else below what is there before them, and a dotted key reaching a table
that has a header moves into it with its own comments. Tables of an array
of tables never merge.

Options: Indent (up to 8 tabs or spaces, a tab by default), IndentTables
(a level per enclosing table whose header comes first), Align (= and
comments of consecutive keys).

Hardening: Format refuses what Parse refuses, a comment holding a
bidirectional embedding, override or isolate or a line break other than
LF (U+202A-202E, U+2066-2069, U+0085, U+2028, U+2029), which can show a
reader text other than what parses, and a result that would not parse to
the same values. Such a rune in a string or quoted key is written as its
\u escape, by Format and by the encoder alike. A line indents at most 16
levels and aligns within 32 runes of key and 80 of line, so the result
stays within a fixed multiple of its source; table paths sit in a trie,
so placing a key costs its length, not its square.

Marshal writes { a = 1 } and no blank first line, so Format(Marshal(v))
is Marshal(v), which FuzzRoundTrip now checks. FuzzFormat checks, with
the options off and on, that the result reads as the source, formats to
itself, keeps every comment once, holds no CR or trailing blank and stays
within the size bound; CI runs it for 10 s. All 29 TOML files in vif
format idempotently to the same values; vif.toml and keymap.toml are
unchanged byte for byte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ThctvSRwt5kV1pVMKtsdWc

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
LixenandClaude Opus 5.5 authored and GitHub committed 2026-10-25 04:49:22 -04:00
1 parent e2712e32a2
commit 170e71f10a
12 files changed
+1809 -440

No files matched your search

+63 -56
View File
@@ -8,15 +8,14 @@ import (
"reflect"
"slices"
"strconv"
"strings"
"unicode/utf8"
)
// Marshal encodes a struct or string-keyed map with deterministic key order.
// Nil pointer/interface fields are omitted; nil pointer/interface array elements,
// cycles/excessive nesting,
// non-finite floats, and integers outside TOML's signed 64-bit range error.
// Comments and whitespace are not retained. Datetimes are not supported.
// Marshal encodes a struct or string-keyed map with deterministic key order, laid
// out as Format lays it. Nil pointer/interface fields are omitted; nil
// pointer/interface array elements, cycles/excessive nesting, non-finite floats,
// and integers outside TOML's signed 64-bit range error. Datetimes are not
// supported.
func Marshal(v any) ([]byte, error) {
var e encoder
if err := e.table(reflect.ValueOf(v), "", 0); err != nil {
@@ -27,7 +26,8 @@ func Marshal(v any) ([]byte, error) {
type encoder struct{ buf bytes.Buffer }
type entry struct {
key string
name string // the key
key string // as a document spells it
value reflect.Value
}
@@ -58,52 +58,44 @@ func entries(v reflect.Value) ([]entry, error) {
if v.Type().Key().Kind() != reflect.String {
return nil, fmt.Errorf("map keys must be strings")
}
out = make([]entry, 0, v.Len())
it := v.MapRange()
for it.Next() {
out = append(out, entry{it.Key().String(), it.Value()})
// The values go into one array, each set in place, not a copy apiece
n := v.Len()
out = make([]entry, 0, n)
values := reflect.MakeSlice(reflect.SliceOf(v.Type().Elem()), n, n)
key := reflect.New(v.Type().Key()).Elem()
for it := v.MapRange(); it.Next() && len(out) < n; {
key.SetIterKey(it)
value := values.Index(len(out))
value.SetIterValue(it)
out = append(out, entry{name: key.String(), value: value})
}
case reflect.Struct:
t := v.Type()
out = make([]entry, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
fields := fieldsOf(v.Type())
out = make([]entry, 0, len(fields))
for _, f := range fields {
if value := v.Field(f.index); !f.omitempty || !isEmptyValue(value) {
out = append(out, entry{name: f.key, value: value})
}
parts := strings.Split(f.Tag.Get("toml"), ",")
if parts[0] == "-" {
continue
}
key := f.Name
if parts[0] != "" {
key = parts[0]
}
if slices.Contains(parts[1:], "omitempty") && isEmptyValue(v.Field(i)) {
continue
}
out = append(out, entry{key, v.Field(i)})
}
default:
return nil, fmt.Errorf("expected struct or map, got %s", v.Kind())
}
slices.SortFunc(out, func(a, b entry) int { return cmp.Compare(a.key, b.key) })
slices.SortFunc(out, func(a, b entry) int { return cmp.Compare(a.name, b.name) })
result := out[:0]
previous := ""
for i, x := range out {
if _, err := keyText(x.key); err != nil {
if x.key, err = keyText(x.name); err != nil {
return nil, err
}
if i > 0 && previous == x.key {
return nil, fmt.Errorf("duplicate TOML key %q", x.key)
if i > 0 && previous == x.name {
return nil, fmt.Errorf("duplicate TOML key %q", x.name)
}
previous = x.key
value, err := indirect(x.value)
if err != nil {
previous = x.name
if x.value, err = indirect(x.value); err != nil {
return nil, err
}
if value.IsValid() {
result = append(result, entry{x.key, value})
if x.value.IsValid() {
result = append(result, x)
}
}
return result, nil
@@ -121,32 +113,32 @@ func (e *encoder) table(v reflect.Value, prefix string, depth int) error {
if err != nil {
return err
}
var tables []entry
tables := fields[:0] // filtered in place: a table is never ahead of its entry
for _, x := range fields {
key, _ := keyText(x.key)
if (isTable(x.value) || isTableArray(x.value)) && len(prefix)+len(key) < maxHeaderBytes {
if (isTable(x.value) || isTableArray(x.value)) && len(prefix)+len(x.key) < maxHeaderBytes {
tables = append(tables, x)
continue
}
e.buf.WriteString(key + " = ")
e.buf.WriteString(x.key)
e.buf.WriteString(" = ")
if err := e.value(x.value, depth+1); err != nil {
return fmt.Errorf("key %q: %w", x.key, err)
return fmt.Errorf("key %q: %w", x.name, err)
}
e.buf.WriteByte('\n')
}
for _, x := range tables {
key, _ := keyText(x.key)
key := x.key
if prefix != "" {
key = prefix + "." + key
}
if isTable(x.value) {
e.buf.WriteString("\n[" + key + "]\n")
e.header(key, "[", "]")
if err := e.table(x.value, key, depth+1); err != nil {
return err
}
} else {
for i := 0; i < x.value.Len(); i++ {
e.buf.WriteString("\n[[" + key + "]]\n")
e.header(key, "[[", "]]")
if err := e.table(x.value.Index(i), key, depth+1); err != nil {
return err
}
@@ -156,6 +148,17 @@ func (e *encoder) table(v reflect.Value, prefix string, depth int) error {
return nil
}
// header writes a table's header a blank line below what is above it
func (e *encoder) header(key, open, close string) {
if e.buf.Len() > 0 {
e.buf.WriteString("\n")
}
e.buf.WriteString(open)
e.buf.WriteString(key)
e.buf.WriteString(close)
e.buf.WriteString("\n")
}
func isTable(v reflect.Value) bool { return v.Kind() == reflect.Map || v.Kind() == reflect.Struct }
func isTableArray(v reflect.Value) bool {
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array || v.Len() == 0 {
@@ -190,22 +193,22 @@ func (e *encoder) value(v reflect.Value, depth int) error {
}
e.string(v.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
e.buf.WriteString(strconv.FormatInt(v.Int(), 10))
e.buf.Write(strconv.AppendInt(e.buf.AvailableBuffer(), v.Int(), 10))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if v.Uint() > math.MaxInt64 {
return fmt.Errorf("unsigned integer %d exceeds TOML int64 range", v.Uint())
}
e.buf.WriteString(strconv.FormatUint(v.Uint(), 10))
e.buf.Write(strconv.AppendUint(e.buf.AvailableBuffer(), v.Uint(), 10))
case reflect.Float32, reflect.Float64:
f := v.Float()
if math.IsNaN(f) || math.IsInf(f, 0) {
return fmt.Errorf("non-finite float")
}
s := strconv.FormatFloat(f, 'g', -1, v.Type().Bits())
if !strings.ContainsAny(s, ".eE") {
s += ".0"
b := strconv.AppendFloat(e.buf.AvailableBuffer(), f, 'g', -1, v.Type().Bits())
if !bytes.ContainsAny(b, ".eE") {
b = append(b, ".0"...)
}
e.buf.WriteString(s)
e.buf.Write(b)
case reflect.Slice, reflect.Array:
e.buf.WriteByte('[')
for i := 0; i < v.Len(); i++ {
@@ -225,14 +228,18 @@ func (e *encoder) value(v reflect.Value, depth int) error {
e.buf.WriteByte('{')
for i, x := range fields {
if i > 0 {
e.buf.WriteString(", ")
e.buf.WriteByte(',')
}
key, _ := keyText(x.key)
e.buf.WriteString(key + " = ")
e.buf.WriteByte(' ')
e.buf.WriteString(x.key)
e.buf.WriteString(" = ")
if err := e.value(x.value, depth+1); err != nil {
return err
}
}
if len(fields) > 0 {
e.buf.WriteByte(' ')
}
e.buf.WriteByte('}')
default:
return fmt.Errorf("unsupported type %s", v.Type())
@@ -274,7 +281,7 @@ func (e *encoder) string(s string) {
case '\f':
e.buf.WriteString(`\f`)
default:
if r < 0x20 || r == 0x7f {
if r < 0x20 || r == 0x7f || hides(r) {
fmt.Fprintf(&e.buf, `\u%04X`, r)
} else {
e.buf.WriteRune(r)