2026-09-10 14:15:13: merge [main:14224c2de53289839839d51f5885722051e41349];

This commit is contained in:
txix committed 2026-09-10 14:15:13 +03:00
1 parent 554123722d
commit 5cb3885330
2726 files changed
+779293 -2185

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
*.test
*.out
*.mprof
.idea
vendor/github.com/buger/goterm/
prof.cpu
prof.mem
.proof/
tests/
PROOF_*.md
REQPROOF_*.md
proof-ux-log.md
PROOF_UNDER_MODELED_REQUIREMENTS_PROPOSAL.md
fuzz_results/
testdata/fuzz/
+12
View File
@@ -0,0 +1,12 @@
language: go
arch:
- amd64
- ppc64le
go:
- 1.13.x
- 1.14.x
- 1.15.x
- 1.16.x
- 1.17.x
- 1.18.x
script: go test -v ./.
+272
View File
@@ -0,0 +1,272 @@
# Changelog
## [v1.6.1] — 2026-07-29
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
### Performance — gjson-style fast-skip in hot loops
Ported gjson's `>'\\'` fast-skip trick to three inner loops in parser.go:
`stringEndConfig` tail, `blockEndConfig`, and `searchKeysConfig`. The trick
uses a single unsigned comparison (`byte > 0x5C`) to skip all non-structural
bytes in bulk, reducing per-byte branch overhead.
| Payload | Before | After | Improvement |
|---|---|---|---|
| Small (190B) | 382 ns | **339 ns** | -11.3% |
| Medium (2.4kB) | 3,899 ns | **3,141 ns** | -19.4% |
| Large (24kB) | 20,788 ns | **20,114 ns** | -3.2% |
Zero allocations maintained on all paths.
### Benchmarks — now includes gjson and sonic
Added [tidwall/gjson](https://github.com/tidwall/gjson) (15.5k⭐, path-based
parser like jsonparser) and [bytedance/sonic](https://github.com/bytedance/sonic)
(9.6k⭐, SIMD-accelerated deserializer) to the benchmark suite.
**Final leaderboard (large payload):**
| Library | time/op | bytes/op | allocs/op |
|---|---|---|---|
| **buger/jsonparser** | **20,114** | **0** | **0** |
| tidwall/gjson | 22,756 | 28,672 | 2 |
| mailru/easyjson | 33,771 | 4,016 | 134 |
| bytedance/sonic | 41,053 | 31,368 | 71 |
| pquerna/ffjson | 59,063 | 4,822 | 144 |
| encoding/json | 130,565 | 4,432 | 147 |
jsonparser is **the fastest across all payload sizes** and the **only zero-allocation** parser.
---
## [v1.6.0] — 2026-07-29
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
### New API — `Append`
```go
// Append to an array without knowing its length
data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items")
```
- **`Append(data, value, keys...)`** — appends `value` to the end of the JSON array addressed by `keys`. Addresses the top-level value when `keys` is empty; auto-vivifies a missing keyed path as a single-element array. Returns `MalformedArrayError` when the addressed value is not an array. Traced to SYS-REQ-009, SYS-REQ-110.
### Known issues — all resolved (zero open)
- **KI-2 fixed** — `ParseInt("-")` now returns an error instead of `(0, nil)`. One-line sign-only guard in `bytes.go:parseInt` (after stripping the sign byte, an empty remainder returns `(0, false, false)`).
- **KI-3 fixed** — `Set` with an array-index path component under an object parent (and vice-versa) now auto-coerces the container type instead of emitting malformed JSON. (Disposition already set to `fixed` in v1.5.x.)
- **KI-4 fixed** — `Set` on a top-level array-index beyond length now appends at the array's end (matching nested-array behavior under SYS-REQ-110) instead of returning `KeyPathNotFoundError`. Also cleans up trailing commas in malformed arrays.
**Zero open known issues.** Every previously shipped known issue is now resolved and covered by ReqProof L3 Assurance.
---
## [v1.5.1] — 2026-07-28
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
### Performance — 6.1x large-payload speedup
- **Fix stringEnd unbounded backslash scan** — `stringEndConfig` was scanning the ENTIRE remaining parent document for backslashes (`bytes.IndexByte(data, '\\')`) instead of just the string body. On a 24kb large payload this walked tens of KB per string. Now bounded to `data[:firstQuote]` (the string body only). **128µs → 22µs (5.8x).**
- **SWAR string scan** — replaced two separate `bytes.IndexByte` calls (quote + backslash) with a single inline 8-byte SWAR (SIMD-Within-A-Register) loop that checks for both characters simultaneously. **22µs → 21µs (additional 8%).**
- **Benchmark suite updated** — all comparison libraries (gabs, easyjson, ffjson, etc.) updated to latest versions. Benchmark methodology documented (Apple M4 Max, Go 1.26.3, median of 5 runs). The `encoding/json` benchmark no longer uses ffjson-generated methods (the #126 ffjson measurement bug was fixed in v1.3.1).
- **README benchmarks refreshed** — all numbers now reflect real measurements on modern hardware with current library versions.
### Updated benchmark results (Apple M4 Max, Go 1.26.3, median of 5 runs)
| Payload | jsonparser | encoding/json | easyjson | Speedup vs encoding/json |
|---|---|---|---|---|
| Small (190B, Get) | 382 ns | 1,335 ns | 312 ns | 3.5x |
| Small (190B, EachKey) | 241 ns | — | — | 5.5x |
| Medium (2.4kB, Get) | 3,894 ns | 10,564 ns | 2,444 ns | 2.7x |
| Medium (2.4kB, EachKey) | 1,923 ns | — | — | 5.5x |
| Large (24kB) | 20,788 ns | 134,123 ns | 32,765 ns | **6.4x** |
All jsonparser results: **0 bytes allocated, 0 allocations**.
---
## [v1.5.0] — 2026-07-28
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance
v1.5.0 extends the formal-verification coverage to **123 requirements** (0 errors, 0 warnings) across all new APIs. Every new function is traced via source annotations, tested with MC/DC witnesses, and covered by the structure-aware fuzzer.
### Config struct — opt-in lenient parsing (#160, #115)
```go
var Lenient = jsonparser.Config{AllowSingleQuotes: true, AllowUnknownEscapes: true}
Lenient.Get(data, "key") // parses {'key':'value'} and unknown escapes
```
- **`AllowSingleQuotes`** — accept `'key':'value'` alongside `"key":"value"` (JavaScript/Python-style). The same escape rules apply inside single-quoted strings.
- **`AllowUnknownEscapes`** — pass through unknown escape sequences (`` \` ``, `\x`) literally instead of erroring.
- The default Config is strict (RFC 8259 only). Package-level functions are unchanged.
- Config methods mirror the full API: `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, `ObjectEach`.
### Streaming ReaderParser (#132, #257)
```go
rp := jsonparser.NewReaderParser(file) // any io.Reader
rp.Get("users", "[0]", "name") // path-based access from a stream
```
- Path-based access to JSON data from an `io.Reader` — **no need to load the entire document into memory**.
- Buffers data incrementally in 64KB chunks; memory is bounded by the largest value, not the document size.
- Enables parsing **10GB+ JSON files** without OOM.
- Methods: `Get`, `GetString`, `ArrayEach`.
### Name aliases (#66)
Canonical `EachXxx` pattern added alongside existing `XxxEach` names:
| New (canonical) | Old (kept for compat) |
|---|---|
| `EachArray` | `ArrayEach` |
| `EachObject` | `ObjectEach` |
| `EachArrayErr` | `ArrayEachErr` |
| `EachArrayWildcard` | `ArrayEachWildcard` |
`EachKey`, `EachKeyErr`, `EachKeyWildcard` already matched the pattern. All old names remain functional.
### Proof
- 2 new SYS-REQs: 115 (Config/lenient parsing), 116 (streaming ReaderParser)
- **123 requirements, 0 errors, 0 warnings, 279/279 functions traced**
---
## [v1.4.0] — 2026-07-28
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance
v1.4.0 adds 9 new backward-compatible APIs, each traced to a formal requirement and verified with MC/DC coverage. **121 requirements, 0 errors, 0 warnings.**
### New APIs
**Iteration with error/break control** — resolves #53, #129, #176, #230, #255, #262
- `ArrayEachErr` — callback returns `error` to stop early (`io.EOF` = graceful stop)
- `EachKeyErr` — same pattern for EachKey
**Safe string handling** — resolves #144, #158, #218, #270
- `Escape(s string) []byte` — RFC 8259 string escaping (inverse of `Unescape`)
- `SetString(data, val, keys...)` — Set with auto-quoted value
**Container accessors** — resolves #175, #261, #271
- `GetArrayLen` / `GetObjectLen` — count elements without a callback
- `GetUint64` — uint64 variant of `GetInt`
**Delete found signal** — resolves #229
- `DeleteFound(data, keys...) ([]byte, bool)` — returns whether the key was found
**Wildcard paths** — resolves #112
- `EachKeyWildcard`, `ArrayEachWildcard`, `SetWildcard` — `[*]` path component
**JSONPath compiled paths** — resolves #234, #251
- `ParsePath("$.users[0].name")` → `[]string` path
- `CompilePath` + `CompiledPath` — pre-compile and reuse with Get/Set/Delete
### Fixes
- EachKey no longer panics with >64 key components (#56)
- Set pre-allocates output buffer, reducing allocations from 6 to 1 (#107)
### Proof
- 3 new SYS-REQs: 112 (container length), 113 (wildcard paths), 114 (compiled paths)
- **121 requirements, 384 MC/DC witness rows, 0 uncovered**
---
## [v1.3.1] — 2026-07-28
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance
v1.3.1 fixes 3 bugs that escaped the initial proof review, with new proof gates to prevent recurrence.
### Bug fixes
- **Fix Set/Delete input-buffer aliasing** (#209, #141) — `Set` and `Delete` no longer corrupt the caller's input `[]byte` when the slice has spare capacity. All mutation paths now allocate a fresh buffer.
- **Fix EachKey array-index inconsistency** (#232) — `EachKey` now descends into terminal array-index paths consistently with `Get`.
- **Fix benchmark measuring ffjson, not encoding/json** (#126) — benchmark payload types stripped of generated methods.
### Proof strengthening
| Bug | Proof gap | New gate |
|---|---|---|
| #209/#141 Set aliasing | No obligation said "Set must not mutate the input buffer" | New obligation `no_input_mutation` + `assertInputUnchanged` gate |
| #232 EachKey ≠ Get | No cross-API consistency obligation | New obligation `api_consistency` + differential gate |
| #126 benchmark ffjson | Proof didn't cover benchmarks | Benchmark honesty lint |
---
## [v1.3.0] — 2026-07-27
### Formally verified by [ReqProof](https://reqproof.com)
jsonparser v1.3.0 is the **first Go library proven to L3 assurance** by [ReqProof](https://reqproof.com), a git-native requirements-engineering and formal-verification platform. The entire codebase is now covered by:
- **118 formal requirements** (7 stakeholder + 111 system-level), each traced to code via source annotations and verified with FRETish formalization.
- **100% Modified Condition/Decision Coverage (MC/DC)** — both code-level (every decision/condition branch exercised) and requirement-side (377/377 truth-table rows witnessed).
- **A custom structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) generating grammar-valid mutations at 250k inputs/sec, plus path-mutation and `encoding/json` differential harnesses.
- **L3 strict audit posture**: 0 errors, 0 warnings, all checks enabled.
The proof review found and fixed **7 real bugs** that years of community use, OSS-Fuzz, and standard fuzzing had missed. [Read the root-cause analysis →](docs/proof-gap-root-cause.md)
jsonparser serves as the **reference case study** for ReqProof — [learn more at reqproof.com](https://reqproof.com).
### Security / bug fixes
- **Fix Delete panic on malformed input with leading comma** (OSS-Fuzz 4649128545288192)
`Delete` panicked with `index out of range [-1]` on inputs like `,{"test":1{}`.
The `data[prevTok]` dereference is now guarded.
- **Fix empty-string key-component panics** (8 sites)
`Get`, `GetString`, `GetInt`, `GetFloat`, `GetBoolean`, `GetUnsafeString`, `Set`,
`Delete`, `EachKey` panicked with `index out of range [0]` when a key path contained
an empty string (`""`). All 8 unguarded `keys[i][0]` dereference sites are now guarded
with `len(...) > 0`. Found by the structure-aware hazard sweep.
Reported by @c-tonneslan (#284).
- **Fix Set data loss on scalar arrays** (#267)
`Set` on an array-index path beyond the current length silently overwrote the array
instead of appending. `Set({"a":[1,2,3]}, 99, "a", "[9]")` now returns `{"a":[1,2,3,99]}`
instead of `{"a":[99]}`. Reported by @Solaris-star (#286).
- **Fix Set malformed-JSON output on cross-type paths**
`Set` with an array-index path component under an object parent (e.g. `Set({}, 9, "[5]")`)
produced invalid JSON (`{[9]}`). Set now auto-coerces the container type to match the
path, always producing valid JSON output.
- **Fix Delete trailing-comma malformation**
`Delete` left a dangling trailing comma in the output when the deleted element was
followed by JSON whitespace (space/tab/LF/CR) and a comma. Found by the structure-aware
path-mutation fuzzer.
- **Fix ArrayEach spurious callback on non-array root**
`ArrayEach` on a non-array root value (e.g. `ArrayEach({"a":1}, cb)`) invoked the
callback with a spurious element before returning an error. The callback is no longer
invoked; a clean error is returned immediately.
- **Fix lone-Unicode-surrogate mishandling in Unescape**
`ParseString` on a string containing a lone high surrogate (e.g. `\uDB29` without a
following low surrogate) synthesized a bogus non-BMP code point from the following
literal bytes. Now substitutes U+FFFD (matching `encoding/json` behavior).
### Performance
- **parseInt fast-path for short numbers** — 22–37% faster on typical 1–10 digit integers.
Numbers with ≤18 digits use direct int64 accumulation, bypassing the overflow-checked
uint64 slow path. Contributed by @trevorprater (#285).
- **stringEnd SIMD fast path** — 12× faster on no-escape strings, 4.5× faster end-to-end
on `Get` for string values. Uses `bytes.IndexByte` for the common case (no `\` before
the closing `"`).
### Acknowledgments
- @c-tonneslan (#284) — reported the empty-string key-component panic
- @Solaris-star (#286) — reported the Set array-index data-loss bug (#267)
- @trevorprater (#285) — contributed the parseInt performance optimization
- OSS-Fuzz (issue 4649128545288192) — the original Delete leading-comma panic
- The [probelabs/json-fuzz](https://github.com/probelabs/json-fuzz) structure-aware fuzzer
+12
View File
@@ -0,0 +1,12 @@
FROM golang:1.25
WORKDIR /go/src/github.com/buger/jsonparser
ADD . /go/src/github.com/buger/jsonparser
RUN go get github.com/Jeffail/gabs
RUN go get github.com/bitly/go-simplejson
RUN go get github.com/pquerna/ffjson
RUN go get github.com/antonholmquist/jason
RUN go get github.com/mreiferson/go-ujson
RUN go get -tags=unsafe -u github.com/ugorji/go/codec
RUN go get github.com/mailru/easyjson
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Leonid Bugaev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+47
View File
@@ -0,0 +1,47 @@
SOURCE = parser.go
CONTAINER = jsonparser
SOURCE_PATH = /go/src/github.com/buger/jsonparser
BENCHMARK = JsonParser
BENCHTIME = 5s
TEST = .
DRUN = docker run -v `pwd`:$(SOURCE_PATH) -i -t $(CONTAINER)
build:
docker build -t $(CONTAINER) .
race:
$(DRUN) --env GORACE="halt_on_error=1" go test ./. $(ARGS) -v -race -timeout 15s
bench:
$(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -benchtime $(BENCHTIME) -v
bench_local:
$(DRUN) go test $(LDFLAGS) -test.benchmem -bench . $(ARGS) -benchtime $(BENCHTIME) -v
profile:
$(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -memprofile mem.mprof -v
$(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -cpuprofile cpu.out -v
$(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -c
test:
$(DRUN) go test $(LDFLAGS) ./ -run $(TEST) -timeout 10s $(ARGS) -v
# Full test suite including the heavy iteration-count suites that the standard
# `proof audit` skips (property-based, reference-oracle, fuzz-harness coverage).
# Run this in the dedicated CI fuzz job or locally before a release.
test-full:
go test ./... -count=1 -race -timeout 5m
# Structure-aware JSON fuzzer (grammar-based, far faster than generic
# libFuzzer for finding parser-specific defects). See json_fuzz_test.go.
fuzz-json:
go test -run='^$$' -fuzz=FuzzJSONStructureAware -fuzztime=$(FUZZTIME) ./...
fmt:
$(DRUN) go fmt ./...
vet:
$(DRUN) go vet ./.
bash:
$(DRUN) /bin/bash
+454
View File
@@ -0,0 +1,454 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/buger/jsonparser)](https://goreportcard.com/report/github.com/buger/jsonparser) [![Audit](https://img.shields.io/badge/ReqProof-L3%20Assurance-success)](https://reqproof.com) ![License](https://img.shields.io/dub/l/vibe-d.svg)
# Alternative JSON parser for Go (10x times faster standard library)
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **6.5x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
---
## 🔒 Formally Verified — the first Go library proven to L3 assurance by [ReqProof](https://reqproof.com)
jsonparser is the **reference case study** for [ReqProof](https://reqproof.com) — a git-native requirements-engineering and formal-verification platform. Every public API is traced to a formal requirement, every requirement is tested with **100% Modified Condition/Decision Coverage (MC/DC)**, and the entire parser is fuzzed by a custom **structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) that generates grammar-valid mutations at 250,000 inputs/second.
| Metric | Value |
|---|---|
| Requirements traced | 118 (7 stakeholder + 111 system) |
| Proof audit | **0 errors, 0 warnings** (L3 strict) |
| Code-level MC/DC | **100% decisions, 100% conditions** |
| Requirement-side MC/DC | **377/377 witness rows covered** |
| Fuzz executions | 16M+ (structure-aware + path-mutation + encoding/json differential) |
| Bugs found & fixed by the proof review | 7 (4 panics, 2 data-corruption, 1 encoding bug) |
The proof review caught bugs that years of community use, OSS-Fuzz, and standard fuzzing had missed — including a panic class across 8 unchecked-dereference sites, a silent data-loss bug in `Set`, and a malformed-output bug in `Delete`. [Read the full root-cause analysis →](docs/proof-gap-root-cause.md)
---
## Rationale
Originally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex.
I love simplicity and prefer to avoid external dependecies. `encoding/json` requires you to know exactly your data structures, or if you prefer to use `map[string]interface{}` instead, it will be very slow and hard to manage.
I investigated what's on the market and found that most libraries are just wrappers around `encoding/json`, there is few options with own parsers (`ffjson`, `easyjson`), but they still requires you to create data structures.
Goal of this project is to push JSON parser to the performance limits and not sacrifice with compliance and developer user experience.
## Example
For the given JSON our goal is to extract the user's full name, number of github followers and avatar.
```go
import "github.com/buger/jsonparser"
...
data := []byte(`{
"person": {
"name": {
"first": "Leonid",
"last": "Bugaev",
"fullName": "Leonid Bugaev"
},
"github": {
"handle": "buger",
"followers": 109
},
"avatars": [
{ "url": "https://avatars1.githubusercontent.com/u/14009?v=3&s=460", "type": "thumbnail" }
]
},
"company": {
"name": "Acme"
}
}`)
// You can specify key path by providing arguments to Get function
jsonparser.Get(data, "person", "name", "fullName")
// There is `GetInt` and `GetBoolean` helpers if you exactly know key data type
jsonparser.GetInt(data, "person", "github", "followers")
// When you try to get object, it will return you []byte slice pointer to data containing it
// In `company` it will be `{"name": "Acme"}`
jsonparser.Get(data, "company")
// If the key doesn't exist it will throw an error
var size int64
if value, err := jsonparser.GetInt(data, "company", "size"); err == nil {
size = value
}
// You can use `EachArray` helper to iterate items [item1, item2 .... itemN]
jsonparser.EachArray(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
fmt.Println(jsonparser.Get(value, "url"))
}, "person", "avatars")
// Or use can access fields by index!
jsonparser.GetString(data, "person", "avatars", "[0]", "url")
// You can use `EachObject` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN }
jsonparser.EachObject(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType)
return nil
}, "person", "name")
// The most efficient way to extract multiple keys is `EachKey`
paths := [][]string{
[]string{"person", "name", "fullName"},
[]string{"person", "avatars", "[0]", "url"},
[]string{"company", "url"},
}
jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, err error){
switch idx {
case 0: // []string{"person", "name", "fullName"}
...
case 1: // []string{"person", "avatars", "[0]", "url"}
...
case 2: // []string{"company", "url"},
...
}
}, paths...)
// For more information see docs below
```
## Lenient Parsing
The package-level functions remain strict RFC 8259 parsers. For inputs that use
single-quoted strings or non-standard escapes, use a `Config` explicitly:
```go
data := []byte(`{'name':'Ada','role':'engineer'}`)
name, err := jsonparser.Lenient.GetString(data, "name")
// name == "Ada"
```
`Lenient` enables both compatibility options. You can also enable only the
extension your input requires:
```go
config := jsonparser.Config{AllowUnknownEscapes: true}
data := []byte("{\"path\":\"docs\\`draft\\x\"}")
path, err := config.GetString(data, "path")
// path == "docs`draftx"
```
The config-aware `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, and
`ObjectEach` methods share the same signatures and behavior as their
package-level counterparts apart from the enabled parsing extensions.
`jsonparser.DefaultConfig` is strict; `jsonparser.Lenient` enables
`AllowSingleQuotes` and `AllowUnknownEscapes`.
## Streaming
`ReaderParser` provides the same path-based lookup model for JSON read from an
`io.Reader`, so a large document does not need to be loaded into a single byte
slice:
```go
file, err := os.Open("large.json")
if err != nil {
log.Fatal(err)
}
defer file.Close()
parser := jsonparser.NewReaderParser(file)
name, err := parser.GetString("person", "name")
```
To process a root array incrementally, use `ArrayEach`. Each callback value is
valid for the duration of the callback; copy it if it must be retained:
```go
parser := jsonparser.NewReaderParser(file)
err := parser.ArrayEach(func(value []byte, valueType jsonparser.ValueType, err error) {
if err != nil {
return
}
process(value, valueType)
})
```
The parser reads in 64 KiB chunks and discards completed prefixes. Its default
sliding-window target is 64 MiB; customize it with
`jsonparser.Config{MaxBufferSize: size}`. A single returned value or array
element may exceed that target because its complete bytes are supplied to the
caller. Create a new `ReaderParser` for each lookup or array traversal.
`ReaderParser` also honors `AllowSingleQuotes` and `AllowUnknownEscapes`.
## Reference
Library API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it.
You also can view API at [godoc.org](https://godoc.org/github.com/buger/jsonparser)
### **`Get`**
```go
func Get(data []byte, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error)
```
Receives data structure, and key path to extract value from.
Returns:
* `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error
* `dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`
* `offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.
* `err` - If the key is not found or any other parsing issue, it should return error. If key not found it also sets `dataType` to `NotExist`
Accepts multiple keys to specify path to JSON value (in case of quering nested structures).
If no keys are provided it will try to extract the closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation.
Note that keys can be an array indexes: `jsonparser.GetInt("person", "avatars", "[0]", "url")`, pretty cool, yeah?
### **`GetString`**
```go
func GetString(data []byte, keys ...string) (val string, err error)
```
Returns strings properly handing escaped and unicode characters. Note that this will cause additional memory allocations.
### **`GetUnsafeString`**
If you need string in your app, and ready to sacrifice with support of escaped symbols in favor of speed. It returns string mapped to existing byte slice memory, without any allocations:
```go
s, _, := jsonparser.GetUnsafeString(data, "person", "name", "title")
switch s {
case 'CEO':
...
case 'Engineer'
...
...
}
```
Note that `unsafe` here means that your string will exist until GC will free underlying byte slice, for most of cases it means that you can use this string only in current context, and should not pass it anywhere externally: through channels or any other way.
### **`GetBoolean`**, **`GetInt`** and **`GetFloat`**
```go
func GetBoolean(data []byte, keys ...string) (val bool, err error)
func GetFloat(data []byte, keys ...string) (val float64, err error)
func GetInt(data []byte, keys ...string) (val int64, err error)
```
If you know the key type, you can use the helpers above.
If key data type do not match, it will return error.
### **`EachArray`**
```go
func EachArray(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)
```
Needed for iterating arrays, accepts a callback function with the same return arguments as `Get`.
`ArrayEach` remains available as a backward-compatible alias.
The error-returning and wildcard variants follow the same naming convention:
use `EachArrayErr` and `EachArrayWildcard`; `ArrayEachErr` and
`ArrayEachWildcard` remain available for backward compatibility.
### **`EachObject`**
```go
func EachObject(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
```
Needed for iterating object, accepts a callback function. Example:
```go
var handler func([]byte, []byte, jsonparser.ValueType, int) error
handler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
//do stuff here
}
jsonparser.EachObject(myJson, handler)
```
`ObjectEach` remains available as a backward-compatible alias.
### **`EachKey`**
```go
func EachKey(data []byte, cb func(idx int, value []byte, dataType jsonparser.ValueType, err error), paths ...[]string)
```
When you need to read multiple keys, and you do not afraid of low-level API `EachKey` is your friend. It read payload only single time, and calls callback function once path is found. For example when you call multiple times `Get`, it has to process payload multiple times, each time you call it. Depending on payload `EachKey` can be multiple times faster than `Get`. Path can use nested keys as well!
```go
paths := [][]string{
[]string{"uuid"},
[]string{"tz"},
[]string{"ua"},
[]string{"st"},
}
var data SmallPayload
jsonparser.EachKey(smallFixture, func(idx int, value []byte, vt jsonparser.ValueType, err error){
switch idx {
case 0:
data.Uuid, _ = value
case 1:
v, _ := jsonparser.ParseInt(value)
data.Tz = int(v)
case 2:
data.Ua, _ = value
case 3:
v, _ := jsonparser.ParseInt(value)
data.St = int(v)
}
}, paths...)
```
### **`Set`**
```go
func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error)
```
Receives existing data structure, key path to set, and value to set at that key. *This functionality is experimental.*
Returns:
* `value` - Pointer to original data structure with updated or added key value.
* `err` - If any parsing issue, it should return error.
Accepts multiple keys to specify path to JSON value (in case of updating or creating nested structures).
Note that keys can be an array indexes: `jsonparser.Set(data, []byte("http://github.com"), "person", "avatars", "[0]", "url")`
### **`Delete`**
```go
func Delete(data []byte, keys ...string) value []byte
```
Receives existing data structure, and key path to delete. *This functionality is experimental.*
Returns:
* `value` - Pointer to original data structure with key path deleted if it can be found. If there is no key path, then the whole data structure is deleted.
Accepts multiple keys to specify path to JSON value (in case of updating or creating nested structures).
Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avatars", "[0]", "url")`
### **`Append`**
```go
func Append(data []byte, value []byte, keys ...string) ([]byte, error)
```
Appends `value` to the end of the JSON array addressed by `keys`. When `keys` is
empty, `Append` addresses the top-level value. If a keyed path does not exist,
`Append` creates it as a single-element array using `Set`'s auto-vivification
behavior. Returns `MalformedArrayError` if the addressed value is not an array.
```go
// Append to an array without knowing its length
data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items")
```
## What makes it so fast?
* It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`.
* Operates with JSON payload on byte level, providing you pointers to the original data structure: no memory allocation.
* No automatic type conversions, by default everything is a []byte, but it provides you value type, so you can convert by yourself (there is few helpers included).
* Does not parse full record, only keys you specified
## Benchmarks
There are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.
For each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.
> **Methodology:** Benchmarks run with `go test -bench=. -benchmem -count=5` on Apple M4 Max (ARM64, darwin), Go 1.26.3. Median of 5 runs. All comparison libraries updated to their latest versions as of 2026-07-29.
Compared libraries:
* https://golang.org/pkg/encoding/json
* https://github.com/tidwall/gjson — path-based, like jsonparser
* https://github.com/bytedance/sonic — SIMD-accelerated full deserializer
* https://github.com/Jeffail/gabs/v2
* https://github.com/pquerna/ffjson
* https://github.com/mailru/easyjson
* https://github.com/buger/jsonparser
#### TLDR
`jsonparser` is the **fastest overall** across all payload sizes — faster than gjson, sonic, easyjson, and encoding/json — with **zero allocations** on every code path.
#### Small payload
Each test processes 190 bytes of http log as a JSON record.
It should read multiple fields.
https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go
| Library | time/op | bytes/op | allocs/op |
| ------ | ------- | -------- | ------- |
| encoding/json struct | 1,300 | 416 | 9 |
| bytedance/sonic | 460 | 522 | 4 |
| tidwall/gjson | 402 | 64 | 3 |
| pquerna/ffjson | **632** | **520** | **10** |
| mailru/easyjson | **237** | **216** | **7** |
| buger/jsonparser (ObjectEach) | **205** | 64 | 2 |
| buger/jsonparser (EachKey) | **227** | **0** | **0** |
| buger/jsonparser (Get) | **339** | **0** | **0** |
#### Medium payload
Each test processes a 2.4kb JSON record (based on Clearbit API).
It should read multiple nested fields and 1 array.
https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_payload_test.go
| Library | time/op | bytes/op | allocs/op |
| ------- | ------- | -------- | --------- |
| encoding/json struct | 9,911 | 616 | 18 |
| bytedance/sonic | 2,703 | 3,428 | 14 |
| tidwall/gjson | 2,241 | 168 | 4 |
| pquerna/ffjson | 3,731 | 736 | 15 |
| mailru/easyjson | 2,368 | 216 | 7 |
| buger/jsonparser (Get) | **3,141** | **0** | **0** |
| buger/jsonparser (EachKey) | **1,657** | **0** | **0** |
`jsonparser` with `EachKey` beats every competitor on medium payloads while remaining zero-allocation.
#### Large payload
Each test processes a 24kb JSON record (based on Discourse API).
It should read 2 arrays, and for each item in array get a few fields.
Basically it means processing a full JSON file.
https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payload_test.go
| Library | time/op | bytes/op | allocs/op |
| --- | --- | --- | --- |
| encoding/json struct | 130,565 | 4,432 | 147 |
| bytedance/sonic | 41,053 | 31,368 | 71 |
| pquerna/ffjson | 59,063 | 4,822 | 144 |
| mailru/easyjson | 33,771 | 4,016 | 134 |
| tidwall/gjson | 22,756 | 28,672 | 2 |
| buger/jsonparser | **20,114** | **0** | **0** |
`jsonparser` is the **fastest library overall** on large payloads: **6.5x faster than encoding/json**, **2x faster than sonic**, **1.7x faster than easyjson**, **1.1x faster than gjson** — and the **only zero-allocation** parser.
## Formal Verification
<!-- Documents: SYS-REQ-001, SYS-REQ-016, SYS-REQ-017, SYS-REQ-018, SYS-REQ-019, SYS-REQ-020, SYS-REQ-021, SYS-REQ-022, SYS-REQ-023, SYS-REQ-024, SYS-REQ-025, SYS-REQ-026, SYS-REQ-027 -->
This project uses [ReqProof](https://reqproof.com) for formal requirements verification, achieving:
- **92 formally specified requirements** covering all public API behavior including edge cases, malformed input, boundary values, and error propagation
- **100% MC/DC coverage** (Modified Condition/Decision Coverage) — every boolean decision in the code is independently proven exercised
- **Kind2 model checking** — mathematical proof that the specification is realizable and consistent
- **Z3 SMT proofs** — data-level properties verified for all possible inputs, not just test samples
ReqProof found **2 real bugs** during the verification process ([see PR #281](https://github.com/buger/jsonparser/pull/281)):
1. `Delete` panic on truncated JSON input — bounds check missing after internal sentinel value
2. `ArrayEach` callback silently swallowing parse errors — the callback's `err` parameter was always nil
It also identified and safely removed **7 dead code blocks** that MC/DC analysis proved unreachable from any input.
The verification runs on every PR via [probelabs/proof-action](https://github.com/probelabs/proof-action).
## Questions and support
All bug-reports and suggestions should go though Github Issues.
## Contributing
1. Fork it
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Added some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create new Pull Request
## Development
All my development happens using Docker, and repo include some Make tasks to simplify development.
* `make build` - builds docker image, usually can be called only once
* `make test` - run tests
* `make fmt` - run go fmt
* `make bench` - run benchmarks (if you need to run only single benchmark modify `BENCHMARK` variable in make file)
* `make profile` - runs benchmark and generate 3 files- `cpu.out`, `mem.mprof` and `benchmark.test` binary, which can be used for `go tool pprof`
* `make bash` - enter container (i use it for running `go tool pprof` above)
+25
View File
@@ -0,0 +1,25 @@
package jsonparser
// SYS-REQ-006, SYS-REQ-028, SYS-REQ-029, SYS-REQ-052, SYS-REQ-053, SYS-REQ-055, SYS-REQ-083
// EachArray is the canonical name; ArrayEach is kept for backward compatibility.
func EachArray(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) {
ArrayEach(data, cb, keys...)
}
// SYS-REQ-007, SYS-REQ-030, SYS-REQ-031, SYS-REQ-032, SYS-REQ-054, SYS-REQ-084
// EachObject is the canonical name; ObjectEach is kept for backward compatibility.
func EachObject(data []byte, cb func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) error {
return ObjectEach(data, cb, keys...)
}
// SYS-REQ-004
// EachArrayErr is the canonical name; ArrayEachErr is kept for backward compatibility.
func EachArrayErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (int, error) {
return ArrayEachErr(data, cb, keys...)
}
// SYS-REQ-113
// EachArrayWildcard is the canonical name; ArrayEachWildcard is kept for backward compatibility.
func EachArrayWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) {
return ArrayEachWildcard(data, cb, keys...)
}
+49
View File
@@ -0,0 +1,49 @@
package jsonparser
// Append adds value to the end of the JSON array addressed by keys.
//
// When keys is empty, Append addresses the top-level value. If a keyed path
// does not exist, Append creates it as a single-element array using Set's
// auto-vivification behavior.
//
// SYS-REQ-009, SYS-REQ-110
func Append(data []byte, value []byte, keys ...string) ([]byte, error) {
_, dataType, startOffset, endOffset, err := internalGet(data, keys...)
if err != nil {
if err != KeyPathNotFoundError || len(keys) == 0 {
return nil, err
}
arrayValue := make([]byte, len(value)+2)
offset := WriteToBuffer(arrayValue, "[")
offset += copy(arrayValue[offset:], value)
WriteToBuffer(arrayValue[offset:], "]")
return Set(data, arrayValue, keys...)
}
if dataType != Array {
return nil, MalformedArrayError
}
closeOffset := endOffset - 1
if closeOffset <= startOffset || closeOffset >= len(data) || data[closeOffset] != ']' {
return nil, MalformedArrayError
}
hasElements := nextToken(data[startOffset+1:closeOffset]) != -1
extraSpace := len(value)
if hasElements {
extraSpace++
}
result := make([]byte, len(data)+extraSpace)
offset := copy(result, data[:closeOffset])
if hasElements {
offset += WriteToBuffer(result[offset:], ",")
}
offset += copy(result[offset:], value)
copy(result[offset:], data[closeOffset:])
return result, nil
}
+72
View File
@@ -0,0 +1,72 @@
// SYS-REQ-015, SYS-REQ-058, SYS-REQ-059, SYS-REQ-064: integer parsing internals
package jsonparser
const absMinInt64 = 1 << 63
const maxInt64 = 1<<63 - 1
const maxUint64 = 1<<64 - 1
// About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON
func parseInt(bytes []byte) (v int64, ok bool, overflow bool) {
l := len(bytes)
if l == 0 {
return 0, false, false
}
var neg bool = false
i := 0
if bytes[0] == '-' {
neg = true
i = 1
}
if i == l {
return 0, false, false
}
if l-i < 19 {
for ; i < l; i++ {
d := bytes[i] - '0'
if d > 9 {
return 0, false, false
}
v = 10*v + int64(d)
}
if neg {
return -v, true, false
}
return v, true, false
}
if neg {
bytes = bytes[1:]
}
var n uint64 = 0
for _, c := range bytes {
if c < '0' || c > '9' {
return 0, false, false
}
if n > maxUint64/10 {
return 0, false, true
}
n *= 10
n1 := n + uint64(c-'0')
if n1 < n {
return 0, false, true
}
n = n1
}
if n > maxInt64 {
if neg && n == absMinInt64 {
return -absMinInt64, true, false
}
return 0, false, true
}
if neg {
return -int64(n), true, false
} else {
return int64(n), true, false
}
}
+26
View File
@@ -0,0 +1,26 @@
// +build appengine appenginevm tinygo
// SYS-REQ-001, SYS-REQ-013, SYS-REQ-014: safe build-tag byte utilities
package jsonparser
import (
"strconv"
)
// See fastbytes_unsafe.go for explanation on why *[]byte is used (signatures must be consistent with those in that file)
func equalStr(b *[]byte, s string) bool {
return string(*b) == s
}
func parseFloat(b *[]byte) (float64, error) {
return strconv.ParseFloat(string(*b), 64)
}
func bytesToString(b *[]byte) string {
return string(*b)
}
func StringToBytes(s string) []byte {
return []byte(s)
}
+45
View File
@@ -0,0 +1,45 @@
// +build !appengine,!appenginevm, !tinygo
// SYS-REQ-001, SYS-REQ-013, SYS-REQ-014: unsafe build-tag byte utilities
package jsonparser
import (
"reflect"
"strconv"
"unsafe"
"runtime"
)
//
// The reason for using *[]byte rather than []byte in parameters is an optimization. As of Go 1.6,
// the compiler cannot perfectly inline the function when using a non-pointer slice. That is,
// the non-pointer []byte parameter version is slower than if its function body is manually
// inlined, whereas the pointer []byte version is equally fast to the manually inlined
// version. Instruction count in assembly taken from "go tool compile" confirms this difference.
//
// TODO: Remove hack after Go 1.7 release
//
func equalStr(b *[]byte, s string) bool {
return *(*string)(unsafe.Pointer(b)) == s
}
func parseFloat(b *[]byte) (float64, error) {
return strconv.ParseFloat(*(*string)(unsafe.Pointer(b)), 64)
}
// A hack until issue golang/go#2632 is fixed.
// See: https://github.com/golang/go/issues/2632
func bytesToString(b *[]byte) string {
return *(*string)(unsafe.Pointer(b))
}
func StringToBytes(s string) []byte {
b := make([]byte, 0, 0)
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
runtime.KeepAlive(s)
return b
}
+87
View File
@@ -0,0 +1,87 @@
package jsonparser
import (
"bytes"
"fmt"
)
// Config controls opt-in parsing extensions. The zero value is strict and
// accepts only RFC 8259 JSON strings and escapes.
// SYS-REQ-115
type Config struct {
AllowSingleQuotes bool // #160: accept 'key':'value' alongside "key":"value"
AllowUnknownEscapes bool // #115: accept unknown escape sequences instead of erroring
MaxBufferSize int // ReaderParser sliding-window target; zero uses the 64 MiB default
}
// DefaultConfig is the strict parser configuration used by package-level
// functions.
// SYS-REQ-115
var DefaultConfig = Config{}
// Lenient accepts single-quoted strings and unknown escape sequences.
// SYS-REQ-115
var Lenient = Config{
AllowSingleQuotes: true,
AllowUnknownEscapes: true,
}
// Get returns the value addressed by keys using c's parsing options.
// SYS-REQ-115
func (c Config) Get(data []byte, keys ...string) ([]byte, ValueType, int, error) {
value, dataType, _, endOffset, err := internalGetConfig(c, data, keys...)
return value, dataType, endOffset, err
}
// GetString returns the decoded string addressed by keys using c's parsing
// options.
// SYS-REQ-115
func (c Config) GetString(data []byte, keys ...string) (string, error) {
value, dataType, _, err := c.Get(data, keys...)
if err != nil {
return "", err
}
if dataType != String {
if dataType == Null {
return "", NullValueError
}
return "", fmt.Errorf("Value is not a string: %s", string(value))
}
if bytes.IndexByte(value, '\\') == -1 {
return string(value), nil
}
var stackbuf [unescapeStackBufSize]byte
unescaped, err := unescapeConfig(c, value, stackbuf[:])
if err != nil {
return "", MalformedValueError
}
return string(unescaped), nil
}
// Set replaces the value addressed by keys using c's parsing options.
// SYS-REQ-115
func (c Config) Set(data []byte, value []byte, keys ...string) ([]byte, error) {
return setConfig(c, data, value, keys...)
}
// Delete removes the value addressed by keys using c's parsing options.
// SYS-REQ-115
func (c Config) Delete(data []byte, keys ...string) []byte {
result, _ := deleteFoundConfig(c, data, keys...)
return result
}
// ArrayEach iterates over the addressed array using c's parsing options.
// SYS-REQ-115
func (c Config) ArrayEach(data []byte, cb func([]byte, ValueType, int, error), keys ...string) (int, error) {
return arrayEachConfig(c, data, cb, keys...)
}
// ObjectEach iterates over the addressed object using c's parsing options.
// SYS-REQ-115
func (c Config) ObjectEach(data []byte, cb func([]byte, []byte, ValueType, int) error, keys ...string) error {
return objectEachConfig(c, data, cb, keys...)
}
+336
View File
@@ -0,0 +1,336 @@
// SYS-REQ-014, SYS-REQ-060, SYS-REQ-061, SYS-REQ-062, SYS-REQ-063: string escape and Unicode handling
package jsonparser
import (
"bytes"
"unicode/utf8"
)
// JSON Unicode stuff: see https://tools.ietf.org/html/rfc7159#section-7
const supplementalPlanesOffset = 0x10000
const highSurrogateOffset = 0xD800
const lowSurrogateOffset = 0xDC00
const basicMultilingualPlaneReservedOffset = 0xDFFF
const basicMultilingualPlaneOffset = 0xFFFF
// NOTE: combineUTF16Surrogates is blocked by an unsupported `<<` shift op
// in the translator (Phase T.* gap, beyond #1/#2/#5). Even though Fix #6
// resolves the package-const references in this body, the shift remains
// untranslated, so no lemma is attached here.
func combineUTF16Surrogates(high, low rune) rune {
return supplementalPlanesOffset + (high-highSurrogateOffset)<<10 + (low - lowSurrogateOffset)
}
const badHex = -1
// reqproof:lemma h2I_range func(c byte) bool {
// r := h2I(c)
// return r == -1 || (r >= 0 && r <= 15)
// }
//
// reqproof:lemma h2I_decimal_digit func(c byte) bool {
// if c < '0' || c > '9' { return true }
// r := h2I(c)
// return r >= 0 && r <= 9
// }
//
// reqproof:lemma h2I_uppercase_hex func(c byte) bool {
// if c < 'A' || c > 'F' { return true }
// r := h2I(c)
// return r >= 10 && r <= 15
// }
//
// reqproof:lemma h2I_lowercase_hex func(c byte) bool {
// if c < 'a' || c > 'f' { return true }
// r := h2I(c)
// return r >= 10 && r <= 15
// }
//
// reqproof:lemma h2I_nondigit_is_badhex func(c byte) bool {
// if c >= '0' && c <= '9' { return true }
// if c >= 'A' && c <= 'F' { return true }
// if c >= 'a' && c <= 'f' { return true }
// return h2I(c) == badHex
// }
//
// reqproof:lemma h2I_nonneg_implies_le_15 func(c byte) bool {
// r := h2I(c)
// if r >= 0 {
// return r <= 15
// }
// return true
// }
func h2I(c byte) int {
if c >= 48 && c <= 57 { // '0'..'9'
return int(c - 48)
}
if c >= 65 && c <= 70 { // 'A'..'F'
return int(c-65) + 10
}
if c >= 97 && c <= 102 { // 'a'..'f'
return int(c-97) + 10
}
return badHex
}
// decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and
// is not checked.
// In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together.
// This function only handles one; decodeUnicodeEscape handles this more complex case.
func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
// We need at least 6 characters total
if len(in) < 6 {
return utf8.RuneError, false
}
// Convert hex to decimal
h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5])
if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
return utf8.RuneError, false
}
// Compose the hex digits
return rune(h1<<12 + h2<<8 + h3<<4 + h4), true
}
// isUTF16EncodedRune checks if a rune is in the range for non-BMP characters,
// which is used to describe UTF16 chars.
// Source: https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
//
// reqproof:lemma isUTF16EncodedRune_low_excluded func(r rune) bool {
// return !(r < 0xD800) || !isUTF16EncodedRune(r)
// }
//
// reqproof:lemma isUTF16EncodedRune_const_high_bound func(r rune) bool {
// // Fix #6: package-level const highSurrogateOffset (= 0xD800) now
// // resolves at translation time. Below the high surrogate offset
// // means definitely outside the UTF-16 surrogate range.
// return !(r < highSurrogateOffset) || !isUTF16EncodedRune(r)
// }
//
// reqproof:lemma isUTF16EncodedRune_const_bmp_bound func(r rune) bool {
// // Fix #6: package-level const basicMultilingualPlaneReservedOffset (= 0xDFFF).
// // Above the BMP-reserved offset means outside the UTF-16 surrogate range.
// return !(r > basicMultilingualPlaneReservedOffset) || !isUTF16EncodedRune(r)
// }
func isUTF16EncodedRune(r rune) bool {
return 0xD800 <= r && r <= 0xDFFF
}
// SYS-REQ-115
func decodeUnicodeEscape(in []byte) (rune, int) {
if r, ok := decodeSingleUnicodeEscape(in); !ok {
// Invalid Unicode escape
return utf8.RuneError, -1
} else if !isUTF16EncodedRune(r) {
// Valid Unicode escape in Basic Multilingual Plane.
// Note: a single \uXXXX escape produces r in [0, 0xFFFF], so r is always
// within the BMP. The former r <= basicMultilingualPlaneOffset guard was
// tautological and has been removed — the real discriminator is whether r
// falls in the UTF-16 surrogate range.
return r, 6
} else if r >= lowSurrogateOffset {
// Lone low surrogate (0xDC00-0xDFFF) with no preceding high surrogate.
// Per RFC 8259/WHATWG a lone surrogate in a JSON string is malformed;
// match encoding/json by substituting U+FFFD and consuming only the 6
// bytes of this escape.
return utf8.RuneError, 6
} else if len(in) < 8 || in[6] != '\\' || in[7] != 'u' {
// Lone high surrogate (0xD800-0xDBFF): the high-surrogate escape is not
// followed by a "\u" low-surrogate escape. decodeSingleUnicodeEscape
// assumes the \u prefix and reads hex at fixed offsets, so without this
// guard it would misread whatever bytes follow (e.g. the literal "A7FA"
// after "\uDB29") as a low surrogate and synthesize a bogus code point
// (DEFECT-260727-SNGT). Substitute U+FFFD and consume only the 6 bytes
// of the high surrogate, matching encoding/json.
return utf8.RuneError, 6
} else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok {
// A "\u" follows the high surrogate but the low-surrogate escape is
// itself malformed (truncated / bad hex) — the whole escape is broken.
return utf8.RuneError, -1
} else if r2 < lowSurrogateOffset || r2 > basicMultilingualPlaneReservedOffset {
// The following "\uXXXX" is not a valid low surrogate (0xDC00-0xDFFF):
// e.g. a BMP codepoint or another high surrogate. Treat the first escape
// as a lone high surrogate → U+FFFD, consuming 6 bytes; the following
// escape is reprocessed by the caller.
return utf8.RuneError, 6
} else {
// Valid UTF16 surrogate pair
return combineUTF16Surrogates(r, r2), 12
}
}
// backslashCharEscapeTable: when '\X' is found for some byte X, it is to be replaced with backslashCharEscapeTable[X]
var backslashCharEscapeTable = [...]byte{
'"': '"',
'\\': '\\',
'/': '/',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
}
// unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns
// how many characters were consumed from 'in' and emitted into 'out'.
// If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error.
func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
return unescapeToUTF8Config(DefaultConfig, in, out)
}
// SYS-REQ-115
func unescapeToUTF8Config(config Config, in, out []byte) (inLen int, outLen int) {
if len(in) < 2 || in[0] != '\\' {
// Invalid escape due to insufficient characters for any escape or no initial backslash
return -1, -1
}
// https://tools.ietf.org/html/rfc7159#section-7
switch e := in[1]; e {
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
// Valid basic 2-character escapes (use lookup table)
out[0] = backslashCharEscapeTable[e]
return 2, 1
case '\'':
if config.AllowSingleQuotes {
out[0] = e
return 2, 1
}
case 'u':
// Unicode escape
if r, inLen := decodeUnicodeEscape(in); inLen == -1 {
// Invalid Unicode escape
return -1, -1
} else {
// Valid Unicode escape; re-encode as UTF8
outLen := utf8.EncodeRune(out, r)
return inLen, outLen
}
}
if config.AllowUnknownEscapes {
// Lenient mode treats the escaped byte as a literal and discards the
// escape marker. A trailing '\' and malformed \u escape remain errors:
// they are truncated/invalid encodings, not unknown escape names.
out[0] = in[1]
return 2, 1
}
return -1, -1
}
const lowerHex = "0123456789abcdef"
// Escape returns in as a JSON string literal, including the surrounding
// quotation marks.
// SYS-REQ-014
func Escape(in string) []byte {
var stackbuf [unescapeStackBufSize]byte
out := stackbuf[:0]
out = append(out, '"')
start := 0
for i := 0; i < len(in); i++ {
c := in[i]
if c >= 0x20 && c != '"' && c != '\\' {
continue
}
out = append(out, in[start:i]...)
switch c {
case '"', '\\':
out = append(out, '\\', c)
case '\b':
out = append(out, '\\', 'b')
case '\f':
out = append(out, '\\', 'f')
case '\n':
out = append(out, '\\', 'n')
case '\r':
out = append(out, '\\', 'r')
case '\t':
out = append(out, '\\', 't')
default:
out = append(out, '\\', 'u', '0', '0', lowerHex[c>>4], lowerHex[c&0x0f])
}
start = i + 1
}
out = append(out, in[start:]...)
return append(out, '"')
}
// SetString replaces the value at keys with val encoded as a JSON string.
// SYS-REQ-009
func SetString(data []byte, val string, keys ...string) ([]byte, error) {
return Set(data, Escape(val), keys...)
}
// unescape unescapes the string contained in 'in' and returns it as a slice.
// If 'in' contains no escaped characters:
//
// Returns 'in'.
//
// Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)):
//
// 'out' is used to build the unescaped string and is returned with no extra allocation
//
// Else:
//
// A new slice is allocated and returned.
func Unescape(in, out []byte) ([]byte, error) {
return unescapeConfig(DefaultConfig, in, out)
}
// SYS-REQ-115
func unescapeConfig(config Config, in, out []byte) ([]byte, error) {
firstBackslash := bytes.IndexByte(in, '\\')
if firstBackslash == -1 {
return in, nil
}
// Get a buffer of sufficient size (allocate if needed)
if cap(out) < len(in) {
out = make([]byte, len(in))
} else {
out = out[0:len(in)]
}
// Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice)
copy(out, in[:firstBackslash])
in = in[firstBackslash:]
buf := out[firstBackslash:]
// The loop always exits via break: either on error (MalformedStringEscapeError)
// or after copying the final non-escaped tail. The former `for len(in) > 0`
// guard was structurally always true on re-entry since the else branch always
// leaves at least the backslash character in `in`.
for {
// Unescape the next escaped character
inLen, bufLen := unescapeToUTF8Config(config, in, buf)
if inLen == -1 {
return nil, MalformedStringEscapeError
}
in = in[inLen:]
buf = buf[bufLen:]
// Copy everything up until the next backslash
nextBackslash := bytes.IndexByte(in, '\\')
if nextBackslash == -1 {
copy(buf, in)
buf = buf[len(in):]
break
} else {
copy(buf, in[:nextBackslash])
buf = buf[nextBackslash:]
in = in[nextBackslash:]
}
}
// Trim the out buffer to the amount that was actually emitted
return out[:len(out)-len(buf)], nil
}
+131
View File
@@ -0,0 +1,131 @@
package jsonparser
// SYS-REQ-014
func FuzzParseString(data []byte) int {
r, err := ParseString(data)
if err != nil || r == "" {
return 0
}
return 1
}
// SYS-REQ-008
func FuzzEachKey(data []byte) int {
paths := [][]string{
{"name"},
{"order"},
{"nested", "a"},
{"nested", "b"},
{"nested2", "a"},
{"nested", "nested3", "b"},
{"arr", "[1]", "b"},
{"arrInt", "[3]"},
{"arrInt", "[5]"},
{"nested"},
{"arr", "["},
{"a\n", "b\n"},
}
EachKey(data, func(idx int, value []byte, vt ValueType, err error) {}, paths...)
return 1
}
// SYS-REQ-010
func FuzzDelete(data []byte) int {
Delete(data, "test")
return 1
}
// SYS-REQ-009
func FuzzSet(data []byte) int {
_, err := Set(data, []byte(`"new value"`), "test")
if err != nil {
return 0
}
return 1
}
// SYS-REQ-007
func FuzzObjectEach(data []byte) int {
_ = ObjectEach(data, func(key, value []byte, valueType ValueType, off int) error {
return nil
})
return 1
}
// SYS-REQ-013
func FuzzParseFloat(data []byte) int {
_, err := ParseFloat(data)
if err != nil {
return 0
}
return 1
}
// SYS-REQ-015
func FuzzParseInt(data []byte) int {
_, err := ParseInt(data)
if err != nil {
return 0
}
return 1
}
// SYS-REQ-012
func FuzzParseBool(data []byte) int {
_, err := ParseBoolean(data)
if err != nil {
return 0
}
return 1
}
// SYS-REQ-001
func FuzzTokenStart(data []byte) int {
_ = tokenStart(data)
return 1
}
// SYS-REQ-002
func FuzzGetString(data []byte) int {
_, err := GetString(data, "test")
if err != nil {
return 0
}
return 1
}
// SYS-REQ-004
func FuzzGetFloat(data []byte) int {
_, err := GetFloat(data, "test")
if err != nil {
return 0
}
return 1
}
// SYS-REQ-003
func FuzzGetInt(data []byte) int {
_, err := GetInt(data, "test")
if err != nil {
return 0
}
return 1
}
// SYS-REQ-005
func FuzzGetBoolean(data []byte) int {
_, err := GetBoolean(data, "test")
if err != nil {
return 0
}
return 1
}
// SYS-REQ-011
func FuzzGetUnsafeString(data []byte) int {
_, err := GetUnsafeString(data, "test")
if err != nil {
return 0
}
return 1
}
+47
View File
@@ -0,0 +1,47 @@
#!/bin/bash -eu
git clone https://github.com/dvyukov/go-fuzz-corpus
zip corpus.zip go-fuzz-corpus/json/corpus/*
cp corpus.zip $OUT/fuzzparsestring_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzParseString fuzzparsestring
cp corpus.zip $OUT/fuzzeachkey_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzEachKey fuzzeachkey
cp corpus.zip $OUT/fuzzdelete_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzDelete fuzzdelete
cp corpus.zip $OUT/fuzzset_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzSet fuzzset
cp corpus.zip $OUT/fuzzobjecteach_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzObjectEach fuzzobjecteach
cp corpus.zip $OUT/fuzzparsefloat_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzParseFloat fuzzparsefloat
cp corpus.zip $OUT/fuzzparseint_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzParseInt fuzzparseint
cp corpus.zip $OUT/fuzzparsebool_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzParseBool fuzzparsebool
cp corpus.zip $OUT/fuzztokenstart_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzTokenStart fuzztokenstart
cp corpus.zip $OUT/fuzzgetstring_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzGetString fuzzgetstring
cp corpus.zip $OUT/fuzzgetfloat_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzGetFloat fuzzgetfloat
cp corpus.zip $OUT/fuzzgetint_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzGetInt fuzzgetint
cp corpus.zip $OUT/fuzzgetboolean_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzGetBoolean fuzzgetboolean
cp corpus.zip $OUT/fuzzgetunsafestring_seed_corpus.zip
compile_go_fuzzer github.com/buger/jsonparser FuzzGetUnsafeString fuzzgetunsafestring
+2535
View File
File diff suppressed because it is too large. Load diff
+226
View File
@@ -0,0 +1,226 @@
package jsonparser
import (
"errors"
"strings"
)
var (
errEmptyPath = errors.New("jsonparser: path must not be empty")
errMalformedPath = errors.New("jsonparser: malformed path")
errUnterminatedKey = errors.New("jsonparser: unterminated quoted key")
)
// ParsePath converts a JSONPath-style path into the path components accepted
// by Get, Set, Delete, ArrayEach, and EachKey.
// SYS-REQ-114
func ParsePath(jsonPath string) ([]string, error) {
if jsonPath == "" {
return nil, errEmptyPath
}
switch {
case jsonPath == "$":
return []string{}, nil
case strings.HasPrefix(jsonPath, "$."):
jsonPath = jsonPath[2:]
case strings.HasPrefix(jsonPath, "$["):
jsonPath = jsonPath[1:]
case jsonPath[0] == '$':
return nil, errMalformedPath
}
if jsonPath == "" {
return nil, errMalformedPath
}
// A path component is either a dot-delimited key or bracket notation.
// Counting both separators gives an exact capacity for ordinary paths and
// a safe upper bound for quoted keys containing dots or brackets.
parts := make([]string, 0, 1+strings.Count(jsonPath, ".")+strings.Count(jsonPath, "["))
for pos := 0; pos < len(jsonPath); {
switch jsonPath[pos] {
case '.':
return nil, errMalformedPath
case '"':
key, next, err := parseQuotedPathKey(jsonPath, pos)
if err != nil {
return nil, err
}
parts = append(parts, key)
pos = next
case '[':
// A root array path or a bracket immediately following a dot has
// no key component before its index.
default:
start := pos
for pos < len(jsonPath) && jsonPath[pos] != '.' && jsonPath[pos] != '[' {
if jsonPath[pos] == ']' || jsonPath[pos] == '"' {
return nil, errMalformedPath
}
pos++
}
if start == pos {
return nil, errMalformedPath
}
parts = append(parts, jsonPath[start:pos])
}
for pos < len(jsonPath) && jsonPath[pos] == '[' {
component, next, err := parseBracketPathComponent(jsonPath, pos)
if err != nil {
return nil, err
}
parts = append(parts, component)
pos = next
}
if pos == len(jsonPath) {
break
}
if jsonPath[pos] != '.' {
return nil, errMalformedPath
}
pos++
if pos == len(jsonPath) {
return nil, errMalformedPath
}
}
if len(parts) == 0 {
return nil, errMalformedPath
}
return parts, nil
}
// SYS-REQ-114
func parseQuotedPathKey(path string, start int) (string, int, error) {
contentStart := start + 1
for pos := contentStart; pos < len(path); pos++ {
switch path[pos] {
case '\\':
// Skip the escaped byte while locating the closing quote. Unescape
// below performs complete JSON escape validation.
pos++
if pos >= len(path) {
return "", 0, errUnterminatedKey
}
case '"':
content := path[contentStart:pos]
if strings.IndexByte(content, '\\') == -1 {
return content, pos + 1, nil
}
unescaped, err := Unescape([]byte(content), nil)
if err != nil {
return "", 0, errMalformedPath
}
return string(unescaped), pos + 1, nil
default:
if path[pos] < 0x20 {
return "", 0, errMalformedPath
}
}
}
return "", 0, errUnterminatedKey
}
// SYS-REQ-114
func parseBracketPathComponent(path string, start int) (string, int, error) {
end := start + 1
for end < len(path) && path[end] != ']' {
if path[end] == '[' || path[end] == '"' {
return "", 0, errMalformedPath
}
end++
}
if end == len(path) || end == start+1 {
return "", 0, errMalformedPath
}
if path[start+1] == '*' {
if end != start+2 {
return "", 0, errMalformedPath
}
} else {
for pos := start + 1; pos < end; pos++ {
if path[pos] < '0' || path[pos] > '9' {
return "", 0, errMalformedPath
}
}
}
return path[start : end+1], end + 1, nil
}
// CompiledPath stores a parsed path for repeated operations.
// SYS-REQ-114
type CompiledPath struct {
parts []string
}
// CompilePath parses jsonPath once for reuse.
// SYS-REQ-114
func CompilePath(jsonPath string) (CompiledPath, error) {
parts, err := ParsePath(jsonPath)
if err != nil {
return CompiledPath{}, err
}
return CompiledPath{parts: parts}, nil
}
// Get resolves the compiled path in data.
// Verifies: SYS-REQ-001 (Get)
// SYS-REQ-114
func (c CompiledPath) Get(data []byte) ([]byte, ValueType, int, error) {
return Get(data, c.parts...)
}
// GetString resolves the compiled path and returns its string value.
// SYS-REQ-114
func (c CompiledPath) GetString(data []byte) (string, error) {
return GetString(data, c.parts...)
}
// GetInt resolves the compiled path and returns its integer value.
// SYS-REQ-114
func (c CompiledPath) GetInt(data []byte) (int64, error) {
return GetInt(data, c.parts...)
}
// Set writes value at the compiled path.
// Verifies: SYS-REQ-009 (Set)
// SYS-REQ-114
func (c CompiledPath) Set(data []byte, value []byte) ([]byte, error) {
return Set(data, value, c.parts...)
}
// Delete removes the value at the compiled path.
// SYS-REQ-114
func (c CompiledPath) Delete(data []byte) []byte {
return Delete(data, c.parts...)
}
// ArrayEach iterates over the array at the compiled path.
// SYS-REQ-114
func (c CompiledPath) ArrayEach(data []byte, cb func([]byte, ValueType, int, error)) (int, error) {
return ArrayEach(data, cb, c.parts...)
}
// EachKey resolves the compiled path using EachKey.
// SYS-REQ-114
func (c CompiledPath) EachKey(data []byte, cb func(int, []byte, ValueType, error)) error {
EachKey(data, cb, c.parts)
return nil
}
// Parts returns a copy of the compiled path components.
// SYS-REQ-114
func (c CompiledPath) Parts() []string {
parts := make([]string, len(c.parts))
copy(parts, c.parts)
return parts
}
+252
View File
@@ -0,0 +1,252 @@
project:
name: jsonparser
# High-assurance posture: the library is a pure function over untrusted,
# adversarial byte input (fuzz targets, OSS-Fuzz). L3 is the strict
# non-trivial level that obligates formalization, coverage, and hazard
# review rather than informal inspection alone.
assurance_target: L3
specs:
- path: specs/stakeholder
prefix: STK-REQ
type: stakeholder
- path: specs/system
prefix: SYS-REQ
type: system
parent_spec: specs/stakeholder
obligation_classes:
- nominal
- missing_path
- malformed_input
- truncated_at_value_boundary
- truncated_mid_structure
- truncated_mid_key
- empty_input
- boundary
- type_mismatch
- negative_array_index
- sentinel_value_boundary
- error_propagation
- no_path_provided
- nested_mutation
- callback_error_propagation
- truncated_escape_sequence
- partial_literal
- truncated_mid_element
- determinism
- idempotency
- nil_safety
- encoding_safety
- edge_case
- no_input_mutation
- api_consistency
- element_type_partition
- non_array_root_no_callback
commands:
build: go build ./...
# Standard audit test command: runs unit + MC/DC witness tests but
# SKIPS the heavy iteration-count suites (property-based, reference-
# oracle, fuzz-harness coverage) so `proof audit` stays fast on every
# PR. Those suites run via `make test-full` (see Makefile) in the
# dedicated CI "Fuzzing" job. Go's -skip flag (1.20+) accepts a regex;
# Fuzz* functions only run under -fuzz anyway.
test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1
# Named per-language test commands consumed by code_mcdc (the MC/DC
# engine needs a discoverable go test command it can instrument and
# rerun, then collect fingerprints). Mirrors the reqforge schema.
tests:
go:
language: go
command: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1
# Instrumented execution path used only when the code-level
# MC/DC engine reruns tests in its temp workspace (cwd =
# <ws>/module). The engine does NOT inject -coverprofile or
# -count into a user-provided command, so this must write the
# managed cover artifact itself: ../cover.out resolves to the
# workspace root the engine reads. -json is redirected back to
# the source workspace via REQPROOF_MCDC_ORIGINAL_SOURCE_DIR so
# test_results auto_link sees a fresh report. The ordinary
# `command` above still feeds coverage_threshold / test_results
# for the non-MC/DC path; -race still comes from test_args.
mcdc_command: go test ./... -coverprofile=../cover.out -json > "$REQPROOF_MCDC_ORIGINAL_SOURCE_DIR/.proof/test-results/go-test.json" 2>&1
# Fixtures are generated artifacts, not committed to the repo.
# MC/DC coverage is enforced through test annotations instead.
# To regenerate locally:
# proof testgen specs/system parser --output tests/
# proof proptest specs/system parser --source z3 --output tests/parser/
#
# Code signals — project-local OpenGrep rule packs.
#
# The jsonparser.boundary.unchecked-caller-slice-deref rule closes the
# gap exposed by the 8th empty-key panic site (parser.go:1000): the
# prior hazard sweep matched only `identifier[index][0]` and missed the
# slice-expression variant `keys[depth:][0][0]`. The rule treats
# slice-expression-then-index, direct-index-then-field, nested direct
# index, computed-offset byte-slice index, and path-segment index as
# the SAME hazard class, while excluding `len(X) > N && ...` /
# `if len(X) > N { ... }` guarded sites and bounded `for i := range`
# loops. Findings map to the boundary obligation class (already owned
# by the parser requirement family) so each one opens a real review
# item. The semantically precise class is panic_free_input_handling;
# adopting it project-wide is the right follow-up — see the rule file
# header for the migration note.
#
# Local dev / CI install of the analyzer backend:
# npm install -g @opengrep/cli@1.22.0
# `tools.opengrep.auto_download: true` below also fetches the pinned
# version on the first `proof signals collect --provider opengrep`.
signals:
output_dir: proof/signals
# Keep audit refresh explicit so a missing analyzer in CI does not
# turn into a spurious red. Run `proof signals collect --provider
# opengrep` before merge / locally to refresh findings; the audit
# check consumes whatever cache that command writes.
refresh_on_audit: false
defaults: auto
rule_packs:
- proof/signals/rules/unchecked-caller-slice-deref.yaml
providers:
opengrep:
enabled: true
mode: run
command:
- opengrep
- scan
- '{configs}'
- --sarif
- --quiet
- --no-rewrite-rule-ids
- '{include_paths}'
format: sarif
include_paths:
- parser.go
- bytes.go
- bytes_safe.go
- bytes_unsafe.go
- escape.go
- fuzz.go
exclude_paths:
- '*_test.go'
- benchmark/**
# `go.parameter-boundary.degenerate` anchors the
# parameter_boundary_safe catalog class, DEFINED as a
# Solidity-style governance / operator setter whose value
# is later consumed in slippage / throttle / timelock
# arithmetic or truncated by a narrowing cast. This
# project is a pure-function Go JSON parser library: the
# only "setters" it exposes are top-level exported
# functions taking byte slices, none consumed in
# protection arithmetic and none cast to a narrower type.
# The class's applies_when is never satisfied here, so
# the project can neither satisfy nor violate it. The
# honest record is "rule does not apply", not "83
# requirement-owners each adjudicated and excused the
# same site". Rule entries use the ProviderRuleID form
# (hyphenated), matching how reqforge disables the same
# rule for the same reason.
disabled_rules:
- go.parameter-boundary.degenerate
fail_if_missing: false
timeout_seconds: 120
tools:
opengrep:
version: 1.22.0
auto_download: true
checks:
solver_latency_clean:
threshold: 360
coverage_threshold:
threshold: 80
auto_link: false
report_path: .proof/coverage/unit.coverprofile
format: go-cover
test_results:
auto_link: true
report_path: .proof/test-results/go-test.json
slow_tests:
enabled: true
threshold_seconds: 60
max_allowed: 5
code_mcdc:
severity: warn
languages:
go:
test_args:
- -race
min_decision_percent: 100
min_condition_percent: 100
max_incomplete_decisions: 0
targets:
- id: parser
enabled: true
language: go
scope: ./...
mcdc_coverage: {}
proof_complexity_clean:
max_formalized_requirements: 120
max_variables: 280
max_guarantees: 120
evidence_diversity:
min_classes:
A: 3
B: 2
C: 1
# Worst-case-first hazard coverage gate (hazard-sweep role precondition).
# `all` is stricter than proof's built-in default `security`: every
# in-scope obligation class must carry an enumerated worst_case, so a
# missing worst-case surfaces as a finding instead of a silent gap.
hazard_consequence:
require_worst_case_scope: all
# Keep every remaining check enabled so the audit surface is fully
# honest (no silently-disabled gates). Each was verified PASS on this
# project; keeping them on catches regressions.
change_evidence_complete:
enabled: true
code_signal_obligations_reviewed:
enabled: true
code_signal_unbindable:
enabled: true
description_grammar_enumeration_complete:
enabled: true
no_authored_change_surface_reviewed:
enabled: true
property_fixtures_exist:
enabled: true
flip_fixtures_exist:
enabled: false
fixture_staleness_clean:
enabled: true
signal_fixtures_valid:
enabled: true
property_based_test_coverage:
enabled: true
approval:
required_for:
assurance_levels:
- A
- B
roles:
- system_owner
- lead_engineer
comment_required: true
# Agent-driven review posture (mirrors reqforge self-dogfood): an AI
# agent driving this repo may run `proof approve` at any assurance
# level so the spec/hazard review loops can close autonomously. Set
# `all: false` and enumerate levels to re-human-gate.
agent_autonomous_for:
all: true
audit:
# CI runs `proof audit --fail-level warn --scope full`; pinning the
# same posture in config makes local runs match CI exactly.
fail_level: warn
scope: full
invocation_log:
enabled: true
path: .proof/invocations.jsonl
documentation:
sources:
- path: .
type: auto
threshold: 0
verification_scope:
exclude: null
include: null
+696
View File
@@ -0,0 +1,696 @@
package jsonparser
import (
"bytes"
"io"
"strconv"
)
const (
defaultReaderBufferSize = 64 * 1024
defaultReaderMaxBufferSize = 64 * 1024 * 1024
maxConsecutiveEmptyReads = 100
)
// ReaderParser provides path-based access to a JSON stream. It is intended for
// one operation per stream: call Get, GetString, or ArrayEach after creating
// the parser. ReaderParser is not safe for concurrent use.
//
// The sliding window is bounded by Config.MaxBufferSize while skipping input.
// A returned value (or one ArrayEach element) may exceed that size because its
// complete byte slice must remain available to the caller.
// SYS-REQ-116
type ReaderParser struct {
reader io.Reader
buf []byte
bufStart int64
pos int
config Config
readErr error
emptyReads int
}
// NewReaderParser creates a streaming parser. If opts contains a Config, the
// first Config controls lenient parsing and the sliding-window size.
// SYS-REQ-116
func NewReaderParser(r io.Reader, opts ...Config) *ReaderParser {
config := DefaultConfig
if len(opts) > 0 {
config = opts[0]
}
return &ReaderParser{
reader: r,
config: config,
}
}
// Get returns the value addressed by keys without loading the whole document.
// As with the package-level Get, string values are returned without quotes but
// retain their JSON escapes.
// SYS-REQ-116
func (rp *ReaderParser) Get(keys ...string) (value []byte, vt ValueType, err error) {
for _, key := range keys {
if key == "" {
return nil, NotExist, KeyPathNotFoundError
}
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return nil, NotExist, KeyPathNotFoundError
}
return nil, NotExist, err
}
var raw []byte
if len(keys) == 0 {
raw, err = rp.captureValue()
} else {
var found bool
found, raw, err = rp.findValue(keys, 0)
if err == nil && !found {
err = KeyPathNotFoundError
}
}
if err != nil {
return nil, NotExist, err
}
value, vt, _, err = rp.config.Get(raw)
if err != nil {
return value, vt, err
}
return value, vt, nil
}
// GetString returns and decodes the string addressed by keys.
// SYS-REQ-116
func (rp *ReaderParser) GetString(keys ...string) (string, error) {
value, vt, err := rp.Get(keys...)
if err != nil {
return "", err
}
if vt != String {
if vt == Null {
return "", NullValueError
}
return "", valueTypeError("string", value)
}
if bytes.IndexByte(value, '\\') == -1 {
return string(value), nil
}
var stackbuf [unescapeStackBufSize]byte
unescaped, err := unescapeConfig(rp.config, value, stackbuf[:])
if err != nil {
return "", MalformedValueError
}
return string(unescaped), nil
}
// ArrayEach incrementally iterates a root JSON array. Callback value slices are
// valid for the duration of the callback and must be copied if retained.
// Memory use is bounded by the largest element plus the sliding read window.
// SYS-REQ-116
func (rp *ReaderParser) ArrayEach(cb func(value []byte, vt ValueType, err error)) error {
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return MalformedObjectError
}
return err
}
b, err := rp.peekByte(false)
if err != nil {
return err
}
if b != '[' {
return MalformedArrayError
}
rp.pos++
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return MalformedArrayError
}
return err
}
b, err = rp.peekByte(false)
if err != nil {
return err
}
if b == ']' {
rp.pos++
return nil
}
for {
raw, captureErr := rp.captureValue()
if captureErr != nil {
cb(nil, Unknown, captureErr)
return captureErr
}
value, vt, _, valueErr := rp.config.Get(raw)
cb(value, vt, valueErr)
if valueErr != nil {
return valueErr
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return MalformedArrayError
}
return err
}
b, err = rp.peekByte(false)
if err != nil {
return err
}
switch b {
case ']':
rp.pos++
return nil
case ',':
rp.pos++
default:
return MalformedArrayError
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return MalformedArrayError
}
return err
}
b, err = rp.peekByte(false)
if err != nil {
return err
}
if b == ']' {
return MalformedArrayError
}
}
}
// findValue resolves keys[depth:] against the value at rp.pos. A not-found
// result consumes the current value so a containing object can continue past a
// duplicate key. A found result leaves the final value in the sliding buffer.
// SYS-REQ-116
func (rp *ReaderParser) findValue(keys []string, depth int) (bool, []byte, error) {
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedJsonError
}
return false, nil, err
}
if depth == len(keys) {
raw, err := rp.captureValue()
return err == nil, raw, err
}
b, err := rp.peekByte(false)
if err != nil {
return false, nil, err
}
switch b {
case '{':
return rp.findObjectValue(keys, depth)
case '[':
return rp.findArrayValue(keys, depth)
default:
if err := rp.skipValue(); err != nil {
return false, nil, err
}
return false, nil, nil
}
}
// SYS-REQ-116
func (rp *ReaderParser) findObjectValue(keys []string, depth int) (bool, []byte, error) {
rp.pos++ // opening {
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedObjectError
}
return false, nil, err
}
b, err := rp.peekByte(false)
if err != nil {
return false, nil, err
}
if b == '}' {
rp.pos++
return false, nil, nil
}
for {
matches, err := rp.readObjectKey(keys[depth])
if err != nil {
return false, nil, err
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedJsonError
}
return false, nil, err
}
b, err = rp.peekByte(false)
if err != nil {
return false, nil, err
}
if b != ':' {
return false, nil, MalformedJsonError
}
rp.pos++
if matches {
found, raw, err := rp.findValue(keys, depth+1)
if err != nil || found {
return found, raw, err
}
} else {
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedJsonError
}
return false, nil, err
}
if err := rp.skipValue(); err != nil {
return false, nil, err
}
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedObjectError
}
return false, nil, err
}
b, err = rp.peekByte(false)
if err != nil {
return false, nil, err
}
switch b {
case '}':
rp.pos++
return false, nil, nil
case ',':
rp.pos++
default:
return false, nil, MalformedObjectError
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedObjectError
}
return false, nil, err
}
b, err = rp.peekByte(false)
if err != nil {
return false, nil, err
}
if b == '}' {
return false, nil, MalformedObjectError
}
}
}
// SYS-REQ-116
func (rp *ReaderParser) findArrayValue(keys []string, depth int) (bool, []byte, error) {
wanted, ok := parseReaderArrayIndex(keys[depth])
if !ok {
if err := rp.skipValue(); err != nil {
return false, nil, err
}
return false, nil, nil
}
rp.pos++ // opening [
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedArrayError
}
return false, nil, err
}
b, err := rp.peekByte(false)
if err != nil {
return false, nil, err
}
if b == ']' {
rp.pos++
return false, nil, nil
}
for index := 0; ; index++ {
if index == wanted {
found, raw, err := rp.findValue(keys, depth+1)
if err != nil || found {
return found, raw, err
}
} else {
if err := rp.skipValue(); err != nil {
return false, nil, err
}
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedArrayError
}
return false, nil, err
}
b, err = rp.peekByte(false)
if err != nil {
return false, nil, err
}
switch b {
case ']':
rp.pos++
return false, nil, nil
case ',':
rp.pos++
default:
return false, nil, MalformedArrayError
}
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return false, nil, MalformedArrayError
}
return false, nil, err
}
b, err = rp.peekByte(false)
if err != nil {
return false, nil, err
}
if b == ']' {
return false, nil, MalformedArrayError
}
}
}
// SYS-REQ-116
func parseReaderArrayIndex(key string) (int, bool) {
if len(key) < 3 || key[0] != '[' || key[len(key)-1] != ']' {
return 0, false
}
index, err := strconv.Atoi(key[1 : len(key)-1])
return index, err == nil && index >= 0
}
// SYS-REQ-116
func (rp *ReaderParser) readObjectKey(wanted string) (bool, error) {
b, err := rp.peekByte(false)
if err != nil {
return false, err
}
if b != '"' && !(b == '\'' && rp.config.AllowSingleQuotes) {
return false, MalformedJsonError
}
// The parent prefix is no longer needed. Discarding it before retaining the
// key ensures that an arbitrarily late key does not grow the window.
rp.discardConsumed()
start := rp.pos
if err := rp.scanString(true); err != nil {
return false, err
}
token := rp.buf[start:rp.pos]
body := token[1 : len(token)-1]
if bytes.IndexByte(body, '\\') == -1 {
return string(body) == wanted, nil
}
var stackbuf [unescapeStackBufSize]byte
unescaped, err := unescapeConfig(rp.config, body, stackbuf[:])
if err != nil {
return false, err
}
return string(unescaped) == wanted, nil
}
// SYS-REQ-116
func (rp *ReaderParser) captureValue() ([]byte, error) {
if err := rp.skipWhitespace(); err != nil {
if err == io.EOF {
return nil, MalformedJsonError
}
return nil, err
}
// Retain only this value and any already-read suffix. The suffix is at most
// one read chunk; prefixes consumed while locating the value are released.
rp.discardConsumed()
start := rp.pos
if err := rp.scanValue(true); err != nil {
return nil, err
}
return rp.buf[start:rp.pos], nil
}
// SYS-REQ-116
func (rp *ReaderParser) skipValue() error {
return rp.scanValue(false)
}
// SYS-REQ-116
func (rp *ReaderParser) scanValue(retain bool) error {
b, err := rp.peekByte(retain)
if err != nil {
if err == io.EOF {
return MalformedJsonError
}
return err
}
switch {
case b == '"' || (b == '\'' && rp.config.AllowSingleQuotes):
return rp.scanString(retain)
case b == '[' || b == '{':
return rp.scanComposite(retain, b)
default:
return rp.scanScalar(retain)
}
}
// SYS-REQ-116
func (rp *ReaderParser) scanString(retain bool) error {
quote, err := rp.peekByte(retain)
if err != nil {
return err
}
rp.pos++
escaped := false
for {
b, err := rp.peekByte(retain)
if err != nil {
if err == io.EOF {
return MalformedStringError
}
return err
}
rp.pos++
if escaped {
escaped = false
continue
}
if b == '\\' {
escaped = true
continue
}
if b == quote {
return nil
}
}
}
// SYS-REQ-116
func (rp *ReaderParser) scanComposite(retain bool, opening byte) error {
stack := []byte{closingDelimiter(opening)}
rp.pos++
for len(stack) > 0 {
b, err := rp.peekByte(retain)
if err != nil {
if err == io.EOF {
if opening == '[' {
return MalformedArrayError
}
return MalformedObjectError
}
return err
}
if b == '"' || (b == '\'' && rp.config.AllowSingleQuotes) {
if err := rp.scanString(retain); err != nil {
return err
}
continue
}
switch b {
case '{':
stack = append(stack, '}')
case '[':
stack = append(stack, ']')
case '}', ']':
if b != stack[len(stack)-1] {
return MalformedJsonError
}
stack = stack[:len(stack)-1]
}
rp.pos++
}
return nil
}
// SYS-REQ-116
func closingDelimiter(opening byte) byte {
if opening == '[' {
return ']'
}
return '}'
}
// SYS-REQ-116
func (rp *ReaderParser) scanScalar(retain bool) error {
consumed := false
for {
b, err := rp.peekByte(retain)
if err != nil {
if err == io.EOF && consumed {
return nil
}
if err == io.EOF {
return MalformedJsonError
}
return err
}
if isReaderValueDelimiter(b) {
if !consumed {
return MalformedJsonError
}
return nil
}
consumed = true
rp.pos++
}
}
// SYS-REQ-116
func isReaderValueDelimiter(b byte) bool {
return isJSONWhitespace(b) || b == ',' || b == '}' || b == ']'
}
// SYS-REQ-116
func (rp *ReaderParser) skipWhitespace() error {
for {
b, err := rp.peekByte(false)
if err != nil {
return err
}
if !isJSONWhitespace(b) {
return nil
}
rp.pos++
}
}
// peekByte returns the next byte. When retain is false, fully consumed chunks
// are discarded before reading more data.
// SYS-REQ-116
func (rp *ReaderParser) peekByte(retain bool) (byte, error) {
for rp.pos >= len(rp.buf) {
if !retain {
rp.discardConsumed()
}
if err := rp.readMore(); err != nil {
return 0, err
}
}
return rp.buf[rp.pos], nil
}
// SYS-REQ-116
func (rp *ReaderParser) readMore() error {
if rp.readErr != nil {
return rp.readErr
}
if rp.reader == nil {
rp.readErr = io.EOF
return rp.readErr
}
readSize := defaultReaderBufferSize
maxBufferSize := rp.config.MaxBufferSize
if maxBufferSize <= 0 {
maxBufferSize = defaultReaderMaxBufferSize
}
if readSize > maxBufferSize {
readSize = maxBufferSize
}
if readSize < 1 {
readSize = 1
}
oldLen := len(rp.buf)
if cap(rp.buf)-oldLen < readSize {
grown := make([]byte, oldLen, oldLen+readSize)
copy(grown, rp.buf)
rp.buf = grown
}
rp.buf = rp.buf[:oldLen+readSize]
n, err := rp.reader.Read(rp.buf[oldLen:])
rp.buf = rp.buf[:oldLen+n]
if n > 0 {
rp.emptyReads = 0
if err != nil {
rp.readErr = err
}
return nil
}
if err != nil {
rp.readErr = err
return err
}
rp.emptyReads++
if rp.emptyReads >= maxConsecutiveEmptyReads {
rp.readErr = io.ErrNoProgress
return rp.readErr
}
return nil
}
// SYS-REQ-116
func (rp *ReaderParser) discardConsumed() {
if rp.pos == 0 {
return
}
rp.bufStart += int64(rp.pos)
rp.buf = rp.buf[rp.pos:]
rp.pos = 0
}
// SYS-REQ-116
func valueTypeError(want string, value []byte) error {
return &readerTypeError{want: want, value: string(value)}
}
type readerTypeError struct {
want string
value string
}
// SYS-REQ-116
func (e *readerTypeError) Error() string {
return "Value is not a " + e.want + ": " + e.value
}
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
set -u
cd "$(dirname "$0")"
mkdir -p fuzz_results/crashes
LOG=fuzz_results/campaign.log
: > "$LOG"
TARGETS=(
DeleteNative
ParseStringNative
EachKeyNative
SetNative
ObjectEachNative
ParseFloatNative
ParseIntNative
ParseBoolNative
TokenStartNative
GetStringNative
GetFloatNative
GetIntNative
GetBooleanNative
GetUnsafeStringNative
)
PER_TARGET=${PER_TARGET:-180s}
MAX_PASSES=${MAX_PASSES:-4}
count_crashes() { ls fuzz_results/crashes/ 2>/dev/null | wc -l | tr -d ' '; }
prev_count=$(count_crashes)
pass=0
while [ $pass -lt $MAX_PASSES ]; do
pass=$((pass+1))
echo "=== $(date '+%H:%M:%S') PASS $pass start (per-target=$PER_TARGET, baseline_unique_crashes=$prev_count) ===" | tee -a "$LOG"
for t in "${TARGETS[@]}"; do
pre=$(count_crashes)
echo " -> $(date '+%H:%M:%S') Fuzz${t}" | tee -a "$LOG"
go test -run='^$' -fuzz="^Fuzz${t}$" -fuzztime="${PER_TARGET}" \
> "fuzz_results/${t}_pass${pass}.log" 2>&1
rc=$?
post=$(count_crashes)
delta=$((post - pre))
summary=$(tail -n 3 "fuzz_results/${t}_pass${pass}.log" | tr '\n' ' | ')
echo " rc=$rc new_crashes=$delta total=$post :: $summary" | tee -a "$LOG"
done
new_count=$(count_crashes)
pass_delta=$((new_count - prev_count))
echo "=== $(date '+%H:%M:%S') PASS $pass done: total_unique_crashes=$new_count (+$pass_delta this pass) ===" | tee -a "$LOG"
if [ $pass_delta -eq 0 ] && [ $pass -ge 2 ]; then
echo "=== SATURATED after pass $pass — no new crashes ===" | tee -a "$LOG"
break
fi
prev_count=$new_count
done
echo "=== $(date '+%H:%M:%S') CAMPAIGN COMPLETE total_unique_crashes=$(count_crashes) ===" | tee -a "$LOG"
+158
View File
@@ -0,0 +1,158 @@
package jsonparser
import "strconv"
const wildcardPathComponent = "[*]"
// EachKeyWildcard resolves a path that may contain [*] components. A wildcard
// requires an array at that position and fans out over its elements before
// resolving the rest of the path. Multiple wildcards produce one callback for
// every matching combination, in document order.
//
// idx is the zero-based order in which matches are reported.
//
// SYS-REQ-113
func EachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), path ...string) error {
nextMatch := 0
return eachKeyWildcard(data, cb, &nextMatch, path)
}
// SYS-REQ-113
func eachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), nextMatch *int, path []string) error {
wildcard := wildcardIndex(path)
if wildcard == -1 {
value, valueType, _, err := Get(data, path...)
if err != nil {
// A missing path has no value to report. Parsing errors for a
// located terminal value, however, follow EachKey's convention
// and are delivered to the callback as well as returned.
if err != KeyPathNotFoundError {
cb(*nextMatch, value, valueType, err)
(*nextMatch)++
}
return err
}
cb(*nextMatch, value, valueType, nil)
(*nextMatch)++
return nil
}
array, valueType, _, err := Get(data, path[:wildcard]...)
if err != nil {
return err
}
if valueType != Array {
return MalformedArrayError
}
remaining := path[wildcard+1:]
_, err = ArrayEachErr(array, func(value []byte, elementType ValueType, _ int, parseErr error) error {
if parseErr != nil {
cb(*nextMatch, value, elementType, parseErr)
(*nextMatch)++
return parseErr
}
if len(remaining) == 0 {
cb(*nextMatch, value, elementType, nil)
(*nextMatch)++
return nil
}
return eachKeyWildcard(value, cb, nextMatch, remaining)
})
return err
}
// ArrayEachWildcard iterates over an array addressed by keys. A terminal [*]
// component is accepted as an explicit request for all elements; without it,
// the function behaves like ArrayEachErr.
// SYS-REQ-113
func ArrayEachWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) {
if len(keys) > 0 && keys[len(keys)-1] == wildcardPathComponent {
keys = keys[:len(keys)-1]
}
index := 0
return ArrayEachErr(data, func(value []byte, valueType ValueType, offset int, err error) error {
current := index
index++
return cb(current, value, valueType, offset, err)
}, keys...)
}
// SetWildcard applies Set to every concrete path matched by [*]. Wildcards
// may appear at any array position and may be repeated. If a wildcard matches
// an empty array, data is returned unchanged.
//
// SYS-REQ-113
func SetWildcard(data []byte, setValue []byte, keys ...string) ([]byte, error) {
if wildcardIndex(keys) == -1 {
return Set(data, setValue, keys...)
}
var paths [][]string
if err := expandWildcardPaths(data, nil, keys, &paths); err != nil {
return nil, err
}
result := data
for _, path := range paths {
var err error
result, err = Set(result, setValue, path...)
if err != nil {
return nil, err
}
}
return result, nil
}
// SYS-REQ-113
func expandWildcardPaths(data []byte, concrete, remaining []string, paths *[][]string) error {
wildcard := wildcardIndex(remaining)
if wildcard == -1 {
path := make([]string, len(concrete)+len(remaining))
copy(path, concrete)
copy(path[len(concrete):], remaining)
*paths = append(*paths, path)
return nil
}
arrayPath := make([]string, len(concrete)+wildcard)
copy(arrayPath, concrete)
copy(arrayPath[len(concrete):], remaining[:wildcard])
array, valueType, _, err := Get(data, arrayPath...)
if err != nil {
return err
}
if valueType != Array {
return MalformedArrayError
}
index := 0
_, err = ArrayEachErr(array, func(_ []byte, _ ValueType, _ int, parseErr error) error {
if parseErr != nil {
return parseErr
}
nextPath := make([]string, len(arrayPath)+1)
copy(nextPath, arrayPath)
nextPath[len(arrayPath)] = "[" + strconv.Itoa(index) + "]"
index++
return expandWildcardPaths(data, nextPath, remaining[wildcard+1:], paths)
})
return err
}
// SYS-REQ-113
func wildcardIndex(path []string) int {
for i, component := range path {
if component == wildcardPathComponent {
return i
}
}
return -1
}