MSP-8292 Up deps
This commit is contained in:
1 parent
3a66223a89
commit
5daaea50a1
186 files changed
+7092
-1579
No files matched your search
+2
@@ -16,3 +16,5 @@ PROOF_*.md
|
||||
REQPROOF_*.md
|
||||
proof-ux-log.md
|
||||
PROOF_UNDER_MODELED_REQUIREMENTS_PROPOSAL.md
|
||||
fuzz_results/
|
||||
testdata/fuzz/
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
+4
-4
@@ -1,4 +1,7 @@
|
||||
FROM golang:1.6
|
||||
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
|
||||
@@ -7,6 +10,3 @@ 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
|
||||
|
||||
WORKDIR /go/src/github.com/buger/jsonparser
|
||||
ADD . /go/src/github.com/buger/jsonparser
|
||||
+11
@@ -26,6 +26,17 @@ profile:
|
||||
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 ./...
|
||||
|
||||
|
||||
+149
-65
@@ -1,7 +1,26 @@
|
||||
[](https://goreportcard.com/report/github.com/buger/jsonparser) 
|
||||
[](https://goreportcard.com/report/github.com/buger/jsonparser) [](https://reqproof.com) 
|
||||
# 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 **10 times faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
|
||||
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 **6x 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.
|
||||
@@ -55,16 +74,16 @@ if value, err := jsonparser.GetInt(data, "company", "size"); err == nil {
|
||||
size = value
|
||||
}
|
||||
|
||||
// You can use `ArrayEach` helper to iterate items [item1, item2 .... itemN]
|
||||
jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
|
||||
// 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 `ObjectEach` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN }
|
||||
jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
|
||||
// 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")
|
||||
@@ -90,6 +109,72 @@ jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, er
|
||||
// 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.
|
||||
@@ -146,15 +231,19 @@ 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.
|
||||
|
||||
### **`ArrayEach`**
|
||||
### **`EachArray`**
|
||||
```go
|
||||
func ArrayEach(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)
|
||||
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.
|
||||
|
||||
### **`ObjectEach`**
|
||||
### **`EachObject`**
|
||||
```go
|
||||
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
|
||||
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
|
||||
@@ -162,8 +251,9 @@ 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.ObjectEach(myJson, handler)
|
||||
jsonparser.EachObject(myJson, handler)
|
||||
```
|
||||
`ObjectEach` remains available as a backward-compatible alias.
|
||||
|
||||
|
||||
### **`EachKey`**
|
||||
@@ -224,6 +314,20 @@ Accepts multiple keys to specify path to JSON value (in case of updating or crea
|
||||
|
||||
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`.
|
||||
@@ -236,11 +340,12 @@ Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avat
|
||||
|
||||
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.
|
||||
Benchmarks run on standard Linode 1024 box.
|
||||
|
||||
> **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-28. The `encoding/json` benchmark types no longer carry ffjson-generated `UnmarshalJSON` methods (fixed in v1.3.1, issue #126), so these numbers reflect the real standard library, not generated code.
|
||||
|
||||
Compared libraries:
|
||||
* https://golang.org/pkg/encoding/json
|
||||
* https://github.com/Jeffail/gabs
|
||||
* https://github.com/Jeffail/gabs/v2
|
||||
* https://github.com/a8m/djson
|
||||
* https://github.com/bitly/go-simplejson
|
||||
* https://github.com/antonholmquist/jason
|
||||
@@ -251,42 +356,34 @@ Compared libraries:
|
||||
* https://github.com/buger/jsonparser
|
||||
|
||||
#### TLDR
|
||||
If you want to skip next sections we have 2 winner: `jsonparser` and `easyjson`.
|
||||
`jsonparser` is up to 10 times faster than standard `encoding/json` package (depending on payload size and usage), and almost infinitely (literally) better in memory consumption because it operates with data on byte level, and provide direct slice pointers.
|
||||
`easyjson` wins in CPU in medium tests and frankly i'm impressed with this package: it is remarkable results considering that it is almost drop-in replacement for `encoding/json` (require some code generation).
|
||||
|
||||
It's hard to fully compare `jsonparser` and `easyjson` (or `ffson`), they a true parsers and fully process record, unlike `jsonparser` which parse only keys you specified.
|
||||
`jsonparser` is up to **6.4x faster** than standard `encoding/json` package (depending on payload size and usage), and **zero allocations** — it operates with data on byte level, and provide direct slice pointers. On large payloads, `jsonparser` is also faster than `easyjson` and `ffjson`.
|
||||
|
||||
If you searching for replacement of `encoding/json` while keeping structs, `easyjson` is an amazing choice. If you want to process dynamic JSON, have memory constrains, or more control over your data you should try `jsonparser`.
|
||||
|
||||
`jsonparser` performance heavily depends on usage, and it works best when you do not need to process full record, only some keys. The more calls you need to make, the slower it will be, in contrast `easyjson` (or `ffjson`, `encoding/json`) parser record only 1 time, and then you can make as many calls as you want.
|
||||
|
||||
With great power comes great responsibility! :)
|
||||
|
||||
|
||||
#### 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 | 7879 | 880 | 18
|
||||
encoding/json interface{} | 8946 | 1521 | 38
|
||||
Jeffail/gabs | 10053 | 1649 | 46
|
||||
bitly/go-simplejson | 10128 | 2241 | 36
|
||||
antonholmquist/jason | 27152 | 7237 | 101
|
||||
github.com/ugorji/go/codec | 8806 | 2176 | 31
|
||||
mreiferson/go-ujson | **7008** | **1409** | 37
|
||||
a8m/djson | 3862 | 1249 | 30
|
||||
pquerna/ffjson | **3769** | **624** | **15**
|
||||
mailru/easyjson | **2002** | **192** | **9**
|
||||
buger/jsonparser | **1367** | **0** | **0**
|
||||
buger/jsonparser (EachKey API) | **809** | **0** | **0**
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| ------ | ------- | -------- | ------- |
|
||||
| encoding/json struct | 1335 | 415 | 9 |
|
||||
| encoding/json interface{} | 1441 | 1336 | 30 |
|
||||
| Jeffail/gabs | 1558 | 1464 | 38 |
|
||||
| bitly/go-simplejson | 1594 | 2120 | 34 |
|
||||
| github.com/ugorji/go/codec | 1286 | 1288 | 13 |
|
||||
| antonholmquist/jason | 4354 | 6816 | 105 |
|
||||
| mreiferson/go-ujson | 1031 | 1392 | 36 |
|
||||
| a8m/djson | 880 | 1160 | 25 |
|
||||
| pquerna/ffjson | **652** | **520** | **10** |
|
||||
| mailru/easyjson | **312** | **80** | **4** |
|
||||
| buger/jsonparser (ObjectEach) | **214** | 64 | 2 |
|
||||
| buger/jsonparser (EachKey) | **241** | **0** | **0** |
|
||||
| buger/jsonparser (Get) | **382** | **0** | **0** |
|
||||
|
||||
Winners are ffjson, easyjson and jsonparser, where jsonparser is up to 9.8x faster than encoding/json and 4.6x faster than ffjson, and slightly faster than easyjson.
|
||||
If you look at memory allocation, jsonparser has no rivals, as it makes no data copy and operates with raw []byte structures and pointers to it.
|
||||
`jsonparser` with `EachKey` is **5.5x faster** than `encoding/json` and **zero allocations**.
|
||||
|
||||
#### Medium payload
|
||||
|
||||
@@ -297,28 +394,17 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_paylo
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| ------- | ------- | -------- | --------- |
|
||||
| encoding/json struct | 57749 | 1336 | 29 |
|
||||
| encoding/json interface{} | 79297 | 10627 | 215 |
|
||||
| Jeffail/gabs | 83807 | 11202 | 235 |
|
||||
| bitly/go-simplejson | 88187 | 17187 | 220 |
|
||||
| antonholmquist/jason | 94099 | 19013 | 247 |
|
||||
| github.com/ugorji/go/codec | 114719 | 6712 | 152 |
|
||||
| mreiferson/go-ujson | **56972** | 11547 | 270 |
|
||||
| a8m/djson | 28525 | 10196 | 198 |
|
||||
| pquerna/ffjson | **20298** | **856** | **20** |
|
||||
| mailru/easyjson | **10512** | **336** | **12** |
|
||||
| buger/jsonparser | **15955** | **0** | **0** |
|
||||
| buger/jsonparser (EachKey API) | **8916** | **0** | **0** |
|
||||
|
||||
The difference between ffjson and jsonparser in CPU usage is smaller, while the memory consumption difference is growing. On the other hand `easyjson` shows remarkable performance for medium payload.
|
||||
|
||||
`gabs`, `go-simplejson` and `jason` are based on encoding/json and map[string]interface{} and actually only helpers for unstructured JSON, their performance correlate with `encoding/json interface{}`, and they will skip next round.
|
||||
`go-ujson` while have its own parser, shows same performance as `encoding/json`, also skips next round. Same situation with `ugorji/go/codec`, but it showed unexpectedly bad performance for complex payloads.
|
||||
| encoding/json struct | 10564 | 616 | 18 |
|
||||
| pquerna/ffjson | 3962 | 736 | 15 |
|
||||
| mailru/easyjson | **2444** | **216** | **7** |
|
||||
| buger/jsonparser (Get) | **3894** | **0** | **0** |
|
||||
| buger/jsonparser (EachKey) | **1923** | **0** | **0** |
|
||||
|
||||
`jsonparser` with `EachKey` beats `easyjson` on medium payload and remains zero-allocation.
|
||||
|
||||
#### Large payload
|
||||
|
||||
Each test processes a 24kb JSON record (based on Discourse API)
|
||||
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.
|
||||
|
||||
@@ -326,16 +412,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payloa
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| --- | --- | --- | --- |
|
||||
| encoding/json struct | 748336 | 8272 | 307 |
|
||||
| encoding/json interface{} | 1224271 | 215425 | 3395 |
|
||||
| a8m/djson | 510082 | 213682 | 2845 |
|
||||
| pquerna/ffjson | **312271** | **7792** | **298** |
|
||||
| mailru/easyjson | **154186** | **6992** | **288** |
|
||||
| buger/jsonparser | **85308** | **0** | **0** |
|
||||
| encoding/json struct | 134123 | 4432 | 147 |
|
||||
| encoding/json interface{} | 176246 | 135824 | 2814 |
|
||||
| a8m/djson | 99295 | 135136 | 2679 |
|
||||
| pquerna/ffjson | 60129 | 4822 | 144 |
|
||||
| mailru/easyjson | 32765 | 4016 | 134 |
|
||||
| buger/jsonparser | **20788** | **0** | **0** |
|
||||
|
||||
`jsonparser` now is a winner, but do not forget that it is way more lightweight parser than `ffson` or `easyjson`, and they have to parser all the data, while `jsonparser` parse only what you need. All `ffjson`, `easysjon` and `jsonparser` have their own parsing code, and does not depend on `encoding/json` or `interface{}`, thats one of the reasons why they are so fast. `easyjson` also use a bit of `unsafe` package to reduce memory consuption (in theory it can lead to some unexpected GC issue, but i did not tested enough)
|
||||
|
||||
Also last benchmark did not included `EachKey` test, because in this particular case we need to read lot of Array values, and using `ArrayEach` is more efficient.
|
||||
`jsonparser` is the **fastest library overall** on large payloads: **6.4x faster than encoding/json**, **1.6x faster than easyjson**, and **zero allocations**.
|
||||
|
||||
## Formal Verification
|
||||
|
||||
|
||||
+25
@@ -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
@@ -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
|
||||
}
|
||||
+25
-1
@@ -7,13 +7,37 @@ 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) {
|
||||
if len(bytes) == 0 {
|
||||
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:]
|
||||
}
|
||||
|
||||
|
||||
+87
@@ -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...)
|
||||
}
|
||||
+171
-17
@@ -15,20 +15,62 @@ 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 {
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
return int(c - '0')
|
||||
case c >= 'A' && c <= 'F':
|
||||
return int(c - 'A' + 10)
|
||||
case c >= 'a' && c <= 'f':
|
||||
return int(c - 'a' + 10)
|
||||
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
|
||||
}
|
||||
@@ -56,10 +98,28 @@ func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
|
||||
// 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 highSurrogateOffset <= r && r <= basicMultilingualPlaneReservedOffset
|
||||
return 0xD800 <= r && r <= 0xDFFF
|
||||
}
|
||||
|
||||
// SYS-REQ-115
|
||||
func decodeUnicodeEscape(in []byte) (rune, int) {
|
||||
if r, ok := decodeSingleUnicodeEscape(in); !ok {
|
||||
// Invalid Unicode escape
|
||||
@@ -71,12 +131,31 @@ func decodeUnicodeEscape(in []byte) (rune, int) {
|
||||
// tautological and has been removed — the real discriminator is whether r
|
||||
// falls in the UTF-16 surrogate range.
|
||||
return r, 6
|
||||
} else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok { // Note: previous decodeSingleUnicodeEscape success guarantees at least 6 bytes remain
|
||||
// UTF16 "high surrogate" without manditory valid following Unicode escape for the "low surrogate"
|
||||
return utf8.RuneError, -1
|
||||
} else if r2 < lowSurrogateOffset {
|
||||
// Invalid UTF16 "low surrogate"
|
||||
} 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
|
||||
@@ -99,6 +178,11 @@ var backslashCharEscapeTable = [...]byte{
|
||||
// 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
|
||||
@@ -110,6 +194,11 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
|
||||
// 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 {
|
||||
@@ -122,17 +211,82 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
|
||||
}
|
||||
}
|
||||
|
||||
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'.
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// 'out' is used to build the unescaped string and is returned with no extra allocation
|
||||
//
|
||||
// Else:
|
||||
// A new slice is allocated and returned.
|
||||
//
|
||||
// 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
|
||||
@@ -156,7 +310,7 @@ func Unescape(in, out []byte) ([]byte, error) {
|
||||
// leaves at least the backslash character in `in`.
|
||||
for {
|
||||
// Unescape the next escaped character
|
||||
inLen, bufLen := unescapeToUTF8(in, buf)
|
||||
inLen, bufLen := unescapeToUTF8Config(config, in, buf)
|
||||
if inLen == -1 {
|
||||
return nil, MalformedStringEscapeError
|
||||
}
|
||||
|
||||
+1262
-149
File diff suppressed because it is too large.
Load diff
+226
@@ -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
|
||||
}
|
||||
+164
-8
@@ -1,5 +1,10 @@
|
||||
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
|
||||
@@ -32,14 +37,120 @@ project:
|
||||
- nil_safety
|
||||
- encoding_safety
|
||||
- edge_case
|
||||
- no_input_mutation
|
||||
- api_consistency
|
||||
- element_type_partition
|
||||
- non_array_root_no_callback
|
||||
commands:
|
||||
build: go build ./...
|
||||
test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1
|
||||
# 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
|
||||
@@ -53,13 +164,14 @@ project:
|
||||
report_path: .proof/test-results/go-test.json
|
||||
slow_tests:
|
||||
enabled: true
|
||||
threshold_seconds: 60
|
||||
max_allowed: 5
|
||||
code_mcdc:
|
||||
severity: warn
|
||||
engine: go
|
||||
package_pattern: ./...
|
||||
coverpkg: ./...
|
||||
go_test_args:
|
||||
- -race
|
||||
languages:
|
||||
go:
|
||||
test_args:
|
||||
- -race
|
||||
min_decision_percent: 100
|
||||
min_condition_percent: 100
|
||||
max_incomplete_decisions: 0
|
||||
@@ -68,8 +180,6 @@ project:
|
||||
enabled: true
|
||||
language: go
|
||||
scope: ./...
|
||||
test_mcdc_annotations:
|
||||
enabled: true
|
||||
mcdc_coverage: {}
|
||||
proof_complexity_clean:
|
||||
max_formalized_requirements: 120
|
||||
@@ -80,6 +190,35 @@ project:
|
||||
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:
|
||||
@@ -89,8 +228,25 @@ project:
|
||||
- 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
@@ -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
@@ -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
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user