| 1 | package jsonparser |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | // ============================================================================= |
| 9 | // REMOVAL 1: `for true` → `for {}` in ArrayEach, Unescape, ObjectEach |
| 10 | // These are cosmetic changes. We verify exit conditions still work. |
| 11 | // ============================================================================= |
| 12 | |
| 13 | // Verifies: SYS-REQ-006 [boundary] |
| 14 | func TestRemoval1_ArrayEach_LoopExitsOnEmptyArray(t *testing.T) { |
| 15 | _, err := ArrayEach([]byte(`[]`), func(value []byte, dataType ValueType, offset int, err error) { |
| 16 | t.Fatal("callback should not be called for empty array") |
| 17 | }) |
| 18 | if err != nil { |
| 19 | t.Fatalf("unexpected error on empty array: %v", err) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | // Verifies: SYS-REQ-006 [boundary] |
| 24 | func TestRemoval1_ArrayEach_LoopExitsOnSingleElement(t *testing.T) { |
| 25 | count := 0 |
| 26 | _, err := ArrayEach([]byte(`[1]`), func(value []byte, dataType ValueType, offset int, err error) { |
| 27 | count++ |
| 28 | }) |
| 29 | if err != nil { |
| 30 | t.Fatalf("unexpected error: %v", err) |
| 31 | } |
| 32 | if count != 1 { |
| 33 | t.Fatalf("expected 1 callback, got %d", count) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Verifies: SYS-REQ-014 [boundary] |
| 38 | func TestRemoval1_Unescape_LoopExitsOnSingleEscape(t *testing.T) { |
| 39 | out, err := Unescape([]byte(`hello\nworld`), make([]byte, 64)) |
| 40 | if err != nil { |
| 41 | t.Fatalf("unexpected error: %v", err) |
| 42 | } |
| 43 | if string(out) != "hello\nworld" { |
| 44 | t.Fatalf("unexpected result: %q", out) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Verifies: SYS-REQ-014 [boundary] |
| 49 | func TestRemoval1_Unescape_LoopExitsOnTrailingEscape(t *testing.T) { |
| 50 | out, err := Unescape([]byte(`\n`), make([]byte, 64)) |
| 51 | if err != nil { |
| 52 | t.Fatalf("unexpected error: %v", err) |
| 53 | } |
| 54 | if string(out) != "\n" { |
| 55 | t.Fatalf("unexpected result: %q", out) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Verifies: SYS-REQ-007 [boundary] |
| 60 | func TestRemoval1_ObjectEach_LoopExitsOnEmptyObject(t *testing.T) { |
| 61 | err := ObjectEach([]byte(`{}`), func(key []byte, value []byte, dataType ValueType, offset int) error { |
| 62 | t.Fatal("callback should not be called for empty object") |
| 63 | return nil |
| 64 | }) |
| 65 | if err != nil { |
| 66 | t.Fatalf("unexpected error on empty object: %v", err) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // Verifies: SYS-REQ-007 [boundary] |
| 71 | func TestRemoval1_ObjectEach_LoopExitsOnSingleEntry(t *testing.T) { |
| 72 | count := 0 |
| 73 | err := ObjectEach([]byte(`{"a":1}`), func(key []byte, value []byte, dataType ValueType, offset int) error { |
| 74 | count++ |
| 75 | return nil |
| 76 | }) |
| 77 | if err != nil { |
| 78 | t.Fatalf("unexpected error: %v", err) |
| 79 | } |
| 80 | if count != 1 { |
| 81 | t.Fatalf("expected 1 callback, got %d", count) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // ============================================================================= |
| 86 | // REMOVAL 2: `end == -1` guard removed in getType |
| 87 | // tokenEnd returns len(data) instead of -1. Verify behavior for edge cases. |
| 88 | // ============================================================================= |
| 89 | |
| 90 | // Verifies: SYS-REQ-044 [boundary] |
| 91 | func TestRemoval2_TokenEnd_EmptyInput(t *testing.T) { |
| 92 | result := tokenEnd([]byte{}) |
| 93 | if result != 0 { |
| 94 | t.Fatalf("tokenEnd([]) = %d, want 0", result) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // Verifies: SYS-REQ-044 [boundary] |
| 99 | func TestRemoval2_TokenEnd_NoDelimiter(t *testing.T) { |
| 100 | // Input with no delimiter characters at all |
| 101 | result := tokenEnd([]byte("12345")) |
| 102 | if result != 5 { |
| 103 | t.Fatalf("tokenEnd(12345) = %d, want 5 (len)", result) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // Verifies: SYS-REQ-044 [boundary] |
| 108 | func TestRemoval2_TokenEnd_NeverReturnsNegative(t *testing.T) { |
| 109 | // This is the critical assertion: tokenEnd NEVER returns -1. |
| 110 | // If it did, the removed guard would be needed. |
| 111 | inputs := [][]byte{ |
| 112 | {}, |
| 113 | []byte("abc"), |
| 114 | []byte("123"), |
| 115 | []byte("true"), |
| 116 | []byte("false"), |
| 117 | []byte("null"), |
| 118 | []byte("-1"), |
| 119 | []byte("1e10"), |
| 120 | } |
| 121 | for _, in := range inputs { |
| 122 | r := tokenEnd(in) |
| 123 | if r < 0 { |
| 124 | t.Fatalf("tokenEnd(%q) returned %d, which is negative!", in, r) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // Verifies: SYS-REQ-001 [boundary] |
| 130 | func TestRemoval2_GetType_NumberAtEndOfInput(t *testing.T) { |
| 131 | // This is the key edge case: a number at the very end of the input |
| 132 | // with no trailing delimiter. tokenEnd returns len(data[endOffset:]) = 0, |
| 133 | // so end=0 and value = data[offset:endOffset+0] = data[offset:offset] = empty. |
| 134 | // Actually wait: if input is just "42", offset=0, endOffset=0, |
| 135 | // data[endOffset:] = "42", tokenEnd("42") = 2, value = data[0:2] = "42". |
| 136 | // That's correct. |
| 137 | |
| 138 | // But what about Get on bare value "42"? |
| 139 | val, dt, _, err := Get([]byte("42")) |
| 140 | if err != nil { |
| 141 | t.Fatalf("unexpected error parsing bare '42': %v", err) |
| 142 | } |
| 143 | if dt != Number { |
| 144 | t.Fatalf("expected Number, got %v", dt) |
| 145 | } |
| 146 | if string(val) != "42" { |
| 147 | t.Fatalf("expected '42', got %q", val) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | // Verifies: SYS-REQ-001 [boundary] |
| 152 | func TestRemoval2_GetType_BooleanAtEndOfInput(t *testing.T) { |
| 153 | val, dt, _, err := Get([]byte("true")) |
| 154 | if err != nil { |
| 155 | t.Fatalf("unexpected error parsing bare 'true': %v", err) |
| 156 | } |
| 157 | if dt != Boolean { |
| 158 | t.Fatalf("expected Boolean, got %v", dt) |
| 159 | } |
| 160 | if string(val) != "true" { |
| 161 | t.Fatalf("expected 'true', got %q", val) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // Verifies: SYS-REQ-001 [boundary] |
| 166 | func TestRemoval2_GetType_NullAtEndOfInput(t *testing.T) { |
| 167 | val, dt, _, err := Get([]byte("null")) |
| 168 | if err != nil { |
| 169 | t.Fatalf("unexpected error parsing bare 'null': %v", err) |
| 170 | } |
| 171 | if dt != Null { |
| 172 | t.Fatalf("expected Null, got %v", dt) |
| 173 | } |
| 174 | if string(val) != "null" { |
| 175 | t.Fatalf("expected 'null', got %q", val) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // Critical: tokenEnd returns len(data) vs stringEnd/blockEnd returning -1. |
| 180 | // The inconsistency means getType silently accepts truncated tokens. |
| 181 | // Verifies: SYS-REQ-001 [boundary] |
| 182 | func TestRemoval2_Inconsistency_TruncatedNumber(t *testing.T) { |
| 183 | // Consider: `{"a": 12` — the number "12" has no terminator. |
| 184 | // tokenEnd("12") returns 2, so getType will return "12" as a Number. |
| 185 | // This is actually CORRECT behavior for a streaming parser, |
| 186 | // but it means we can't distinguish "complete number" from "truncated input". |
| 187 | // The removed guard would NOT have caught this either (tokenEnd never returns -1). |
| 188 | val, dt, _, err := Get([]byte(`{"a": 12`), "a") |
| 189 | if err != nil { |
| 190 | t.Logf("Error on truncated number: %v (this is fine)", err) |
| 191 | } else { |
| 192 | t.Logf("Truncated number parsed as: val=%q type=%v", val, dt) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // ============================================================================= |
| 197 | // REMOVAL 3: `r <= basicMultilingualPlaneOffset` removed in decodeUnicodeEscape |
| 198 | // Verify that decodeSingleUnicodeEscape can NEVER produce r > 0xFFFF. |
| 199 | // ============================================================================= |
| 200 | |
| 201 | // Verifies: SYS-REQ-014 [boundary] |
| 202 | func TestRemoval3_DecodeSingleUnicodeEscape_MaxValue(t *testing.T) { |
| 203 | // \uFFFF is the maximum possible value from a single \uXXXX escape. |
| 204 | // 4 hex digits: max = 0xFFFF = 65535 = basicMultilingualPlaneOffset |
| 205 | r, ok := decodeSingleUnicodeEscape([]byte(`\uFFFF`)) |
| 206 | if !ok { |
| 207 | t.Fatal("failed to decode \\uFFFF") |
| 208 | } |
| 209 | if r != 0xFFFF { |
| 210 | t.Fatalf("expected 0xFFFF, got 0x%X", r) |
| 211 | } |
| 212 | if r > basicMultilingualPlaneOffset { |
| 213 | t.Fatalf("UNSAFE: r=0x%X exceeds BMP offset 0x%X", r, basicMultilingualPlaneOffset) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // Verifies: SYS-REQ-014 [boundary] |
| 218 | func TestRemoval3_DecodeSingleUnicodeEscape_MinValue(t *testing.T) { |
| 219 | r, ok := decodeSingleUnicodeEscape([]byte(`\u0000`)) |
| 220 | if !ok { |
| 221 | t.Fatal("failed to decode \\u0000") |
| 222 | } |
| 223 | if r != 0 { |
| 224 | t.Fatalf("expected 0, got 0x%X", r) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | // Verifies: SYS-REQ-014 [boundary] |
| 229 | func TestRemoval3_DecodeUnicodeEscape_BMP_NonSurrogate(t *testing.T) { |
| 230 | // \u0041 = 'A', well within BMP and not a surrogate |
| 231 | r, n := decodeUnicodeEscape([]byte(`\u0041`)) |
| 232 | if n != 6 { |
| 233 | t.Fatalf("expected consumed=6, got %d", n) |
| 234 | } |
| 235 | if r != 'A' { |
| 236 | t.Fatalf("expected 'A', got %c (0x%X)", r, r) |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // Verifies: SYS-REQ-014 [boundary] |
| 241 | func TestRemoval3_DecodeUnicodeEscape_HighSurrogateAlone(t *testing.T) { |
| 242 | // \uD800 is a high surrogate — should require a low surrogate pair |
| 243 | r, n := decodeUnicodeEscape([]byte(`\uD800`)) |
| 244 | if n != -1 { |
| 245 | t.Fatalf("expected error (n=-1) for lone high surrogate, got n=%d r=0x%X", n, r) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // Verifies: SYS-REQ-014 [boundary] |
| 250 | func TestRemoval3_DecodeUnicodeEscape_ValidSurrogatePair(t *testing.T) { |
| 251 | // \uD83D\uDE00 = U+1F600 (grinning face emoji) |
| 252 | r, n := decodeUnicodeEscape([]byte(`\uD83D\uDE00`)) |
| 253 | if n != 12 { |
| 254 | t.Fatalf("expected consumed=12, got %d", n) |
| 255 | } |
| 256 | if r != 0x1F600 { |
| 257 | t.Fatalf("expected U+1F600, got U+%X", r) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | // Verifies: SYS-REQ-014 [formal] |
| 262 | func TestRemoval3_MathematicalProof(t *testing.T) { |
| 263 | // Mathematical proof: decodeSingleUnicodeEscape computes |
| 264 | // h1<<12 + h2<<8 + h3<<4 + h4 |
| 265 | // where h1..h4 are in [0, 15]. |
| 266 | // Maximum: 15<<12 + 15<<8 + 15<<4 + 15 = 61440 + 3840 + 240 + 15 = 65535 = 0xFFFF |
| 267 | // This equals basicMultilingualPlaneOffset exactly. |
| 268 | // Therefore r <= basicMultilingualPlaneOffset is ALWAYS true. |
| 269 | maxR := rune(15<<12 + 15<<8 + 15<<4 + 15) |
| 270 | if maxR != basicMultilingualPlaneOffset { |
| 271 | t.Fatalf("max possible rune 0x%X != basicMultilingualPlaneOffset 0x%X", maxR, basicMultilingualPlaneOffset) |
| 272 | } |
| 273 | t.Logf("PROVEN: max rune from \\uXXXX = 0x%X = basicMultilingualPlaneOffset", maxR) |
| 274 | } |
| 275 | |
| 276 | // ============================================================================= |
| 277 | // REMOVAL 4: `data[i] == '{'` block removed in EachKey |
| 278 | // Test: unmatched key followed by nested object must still be skipped. |
| 279 | // ============================================================================= |
| 280 | |
| 281 | // Verifies: SYS-REQ-008 [boundary] |
| 282 | func TestRemoval4_EachKey_SkipNestedObject(t *testing.T) { |
| 283 | data := []byte(`{"skip":{"nested":"deep"},"want":"found"}`) |
| 284 | paths := [][]string{{"want"}} |
| 285 | |
| 286 | var foundValue []byte |
| 287 | var foundType ValueType |
| 288 | EachKey(data, func(idx int, value []byte, vt ValueType, err error) { |
| 289 | if idx == 0 { |
| 290 | foundValue = value |
| 291 | foundType = vt |
| 292 | } |
| 293 | }, paths...) |
| 294 | |
| 295 | if foundValue == nil { |
| 296 | t.Fatal("UNSAFE: EachKey failed to find 'want' after skipping nested object") |
| 297 | } |
| 298 | if string(foundValue) != "found" { |
| 299 | t.Fatalf("expected 'found', got %q", foundValue) |
| 300 | } |
| 301 | if foundType != String { |
| 302 | t.Fatalf("expected String type, got %v", foundType) |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | // Verifies: SYS-REQ-008 [boundary] |
| 307 | func TestRemoval4_EachKey_SkipDeeplyNestedObject(t *testing.T) { |
| 308 | data := []byte(`{"skip":{"a":{"b":{"c":"deep"}}},"want":"found"}`) |
| 309 | paths := [][]string{{"want"}} |
| 310 | |
| 311 | var foundValue []byte |
| 312 | EachKey(data, func(idx int, value []byte, vt ValueType, err error) { |
| 313 | if idx == 0 { |
| 314 | foundValue = value |
| 315 | } |
| 316 | }, paths...) |
| 317 | |
| 318 | if foundValue == nil { |
| 319 | t.Fatal("UNSAFE: EachKey failed to find 'want' after deeply nested skip") |
| 320 | } |
| 321 | if string(foundValue) != "found" { |
| 322 | t.Fatalf("expected 'found', got %q", foundValue) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | // Verifies: SYS-REQ-008 [boundary] |
| 327 | func TestRemoval4_EachKey_SkipNestedArray(t *testing.T) { |
| 328 | data := []byte(`{"skip":[1,2,3],"want":"found"}`) |
| 329 | paths := [][]string{{"want"}} |
| 330 | |
| 331 | var foundValue []byte |
| 332 | EachKey(data, func(idx int, value []byte, vt ValueType, err error) { |
| 333 | if idx == 0 { |
| 334 | foundValue = value |
| 335 | } |
| 336 | }, paths...) |
| 337 | |
| 338 | if foundValue == nil { |
| 339 | t.Fatal("UNSAFE: EachKey failed to find 'want' after array skip") |
| 340 | } |
| 341 | if string(foundValue) != "found" { |
| 342 | t.Fatalf("expected 'found', got %q", foundValue) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | // Verifies: SYS-REQ-008 [boundary] |
| 347 | func TestRemoval4_EachKey_SkipMultipleNestedObjects(t *testing.T) { |
| 348 | data := []byte(`{"a":{"x":1},"b":{"y":2},"want":"found"}`) |
| 349 | paths := [][]string{{"want"}} |
| 350 | |
| 351 | var foundValue []byte |
| 352 | EachKey(data, func(idx int, value []byte, vt ValueType, err error) { |
| 353 | if idx == 0 { |
| 354 | foundValue = value |
| 355 | } |
| 356 | }, paths...) |
| 357 | |
| 358 | if foundValue == nil { |
| 359 | t.Fatal("UNSAFE: EachKey failed to find 'want' after multiple nested objects") |
| 360 | } |
| 361 | if string(foundValue) != "found" { |
| 362 | t.Fatalf("expected 'found', got %q", foundValue) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // Verifies: SYS-REQ-008 [boundary] |
| 367 | func TestRemoval4_EachKey_NestedObjectWithString(t *testing.T) { |
| 368 | // This tests the case where a string value contains braces |
| 369 | data := []byte(`{"skip":"has {braces}","want":"found"}`) |
| 370 | paths := [][]string{{"want"}} |
| 371 | |
| 372 | var foundValue []byte |
| 373 | EachKey(data, func(idx int, value []byte, vt ValueType, err error) { |
| 374 | if idx == 0 { |
| 375 | foundValue = value |
| 376 | } |
| 377 | }, paths...) |
| 378 | |
| 379 | if foundValue == nil { |
| 380 | t.Fatal("UNSAFE: EachKey failed to find 'want' after string with braces") |
| 381 | } |
| 382 | if string(foundValue) != "found" { |
| 383 | t.Fatalf("expected 'found', got %q", foundValue) |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | // ============================================================================= |
| 388 | // REMOVAL 5: `keys[level][0] != '['` removed in searchKeys |
| 389 | // The original code was: `keys[level][0] != '[' || keys[level][keyLen-1] != ']'` |
| 390 | // within `if keyLevel == level && keys[level][0] == '['` |
| 391 | // So keys[level][0] != '[' was ALWAYS false (contradiction). Removing it is safe. |
| 392 | // ============================================================================= |
| 393 | |
| 394 | // Verifies: SYS-REQ-001 [boundary] |
| 395 | func TestRemoval5_SearchKeys_ArrayIndex_Valid(t *testing.T) { |
| 396 | data := []byte(`[1, "two", 3]`) |
| 397 | // searchKeys with "[1]" should find element at index 1 |
| 398 | offset := searchKeys(data, "[1]") |
| 399 | if offset == -1 { |
| 400 | t.Fatal("searchKeys failed to find array index [1]") |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | // Verifies: SYS-REQ-001 [boundary] |
| 405 | func TestRemoval5_SearchKeys_ArrayIndex_MalformedNoClose(t *testing.T) { |
| 406 | data := []byte(`[1, 2, 3]`) |
| 407 | // "[1" has no closing bracket — keyLen < 3 catches this |
| 408 | offset := searchKeys(data, "[1") |
| 409 | if offset != -1 { |
| 410 | t.Fatalf("expected -1 for malformed index '[1', got %d", offset) |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | // Verifies: SYS-REQ-001 [boundary] |
| 415 | func TestRemoval5_SearchKeys_ArrayIndex_TooShort(t *testing.T) { |
| 416 | data := []byte(`[1, 2, 3]`) |
| 417 | // "[]" has keyLen=2 which is < 3 — still caught |
| 418 | offset := searchKeys(data, "[]") |
| 419 | if offset != -1 { |
| 420 | t.Fatalf("expected -1 for empty index '[]', got %d", offset) |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | // Verifies: SYS-REQ-001 [boundary] |
| 425 | func TestRemoval5_SearchKeys_ArrayIndex_NestedObject(t *testing.T) { |
| 426 | data := []byte(`[{"a":1},{"a":2}]`) |
| 427 | offset := searchKeys(data, "[1]", "a") |
| 428 | if offset == -1 { |
| 429 | t.Fatal("searchKeys failed to find [1].a") |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // ============================================================================= |
| 434 | // REMOVAL 6: `if e != nil` inside `if o == 0` removed in ArrayEach |
| 435 | // Critical: Can Get return (_, _, 0, nil)? |
| 436 | // ============================================================================= |
| 437 | |
| 438 | // Verifies: SYS-REQ-006 [boundary] |
| 439 | func TestRemoval6_ArrayEach_GetReturnsZeroOffset(t *testing.T) { |
| 440 | // Get is called with data[offset:]. For Get to return endOffset=0, |
| 441 | // internalGet would need to return endOffset=0. |
| 442 | // In internalGet: if no keys, offset starts at 0. |
| 443 | // nO := nextToken(data[0:]) — if data is whitespace-only, returns -1 → error. |
| 444 | // If data starts with a token, offset += nO. |
| 445 | // Then getType is called. getType returns endOffset from getType. |
| 446 | // |
| 447 | // The question: can getType return endOffset=0? |
| 448 | // endOffset starts as `offset` in getType. If offset=0 and data[0] is '"', |
| 449 | // stringEnd returns idx, so endOffset = 0 + idx + 1 >= 1. Not 0. |
| 450 | // If data[0] is '[', blockEnd returns endOffset >= 1. Not 0. |
| 451 | // If data[0] is '{', blockEnd returns endOffset >= 1. Not 0. |
| 452 | // Otherwise tokenEnd(data[0:]) — for empty would be 0 but offset is 0, |
| 453 | // so value = data[0:0+0] = empty, which would fail the boolean/null/number check. |
| 454 | // |
| 455 | // So: getType CAN return endOffset=0 if the token at position 0 is a |
| 456 | // zero-length number token... which means tokenEnd(data[0:])=0, meaning |
| 457 | // data[0] IS a delimiter. But that contradicts reaching the else branch |
| 458 | // (data[0] is not '"', '[', or '{'). |
| 459 | // |
| 460 | // Actually, for endOffset to be 0, we need offset=0 AND |
| 461 | // tokenEnd(data[0:])=0, which means data[0] is a delimiter (space, comma, etc.). |
| 462 | // But nextToken would have skipped past spaces. If data[0] is comma, |
| 463 | // nextToken returns 0 (comma is not whitespace per nextToken). |
| 464 | // Then getType is called with offset=0, data[0]=','. |
| 465 | // getType falls to the default case → UnknownValueTypeError. |
| 466 | // endOffset = offset + end = 0 + 0 = 0. Error is returned. |
| 467 | // So internalGet returns endOffset=0 WITH an error. |
| 468 | // This means Get returns offset=0 WITH an error. |
| 469 | |
| 470 | // Test: ArrayEach with malformed content where Get returns offset 0 |
| 471 | // The `,` after `[` will cause Get to fail with offset 0 |
| 472 | count := 0 |
| 473 | _, err := ArrayEach([]byte(`[,1]`), func(value []byte, dataType ValueType, offset int, err error) { |
| 474 | count++ |
| 475 | }) |
| 476 | if err == nil { |
| 477 | t.Logf("NOTE: ArrayEach did not error on [,1] — count=%d", count) |
| 478 | } else { |
| 479 | t.Logf("ArrayEach correctly errored on [,1]: %v", err) |
| 480 | } |
| 481 | // The key check: did we infinite loop? If we get here, we didn't. |
| 482 | t.Log("PASS: no infinite loop") |
| 483 | } |
| 484 | |
| 485 | // Verifies: SYS-REQ-006 [boundary] |
| 486 | func TestRemoval6_ArrayEach_EmptyStringElement(t *testing.T) { |
| 487 | // Can Get return ([], String, 0, nil) for an empty string ""? |
| 488 | // Get("\"\"") → internalGet → searchKeys skipped → nextToken → offset 0 |
| 489 | // → getType(data, 0) → data[0]='"' → stringEnd(data[1:]) |
| 490 | // stringEnd on `"` → finds quote at position 0 → returns (1, false) |
| 491 | // So endOffset = 0 + 1 + 1 = 2. NOT 0. |
| 492 | // Get returns offset=2 (the endOffset from internalGet's 4th return). |
| 493 | // Wait — Get returns internalGet's 4th value as `offset`. |
| 494 | // Let me re-check: Get returns (a, b, d, e) where d = endOffset from internalGet. |
| 495 | // For "" at position 0: endOffset from getType = 2, so Get returns offset=2. |
| 496 | |
| 497 | count := 0 |
| 498 | _, err := ArrayEach([]byte(`["","b"]`), func(value []byte, dataType ValueType, offset int, err error) { |
| 499 | count++ |
| 500 | }) |
| 501 | if err != nil { |
| 502 | t.Fatalf("unexpected error: %v", err) |
| 503 | } |
| 504 | if count != 2 { |
| 505 | t.Fatalf("expected 2 callbacks, got %d", count) |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | // Verifies: SYS-REQ-006 [boundary] |
| 510 | func TestRemoval6_ArrayEach_WhitespaceOnlyInput(t *testing.T) { |
| 511 | // Can Get return (nil, NotExist, 0, nil)? |
| 512 | // Get(" ") → nextToken returns 0 pointing to first space... no. |
| 513 | // nextToken skips spaces. " " → returns -1 → MalformedJsonError. |
| 514 | // So Get returns (nil, NotExist, 0, MalformedJsonError). offset=0, err!=nil. |
| 515 | // In ArrayEach: if o==0, returns offset, e — correct. |
| 516 | _, err := ArrayEach([]byte(`[ `), func(value []byte, dataType ValueType, offset int, err error) { |
| 517 | // should not be called |
| 518 | }) |
| 519 | if err == nil { |
| 520 | t.Fatal("expected error for whitespace-only array content") |
| 521 | } |
| 522 | t.Logf("Correctly got error: %v", err) |
| 523 | } |
| 524 | |
| 525 | // ============================================================================= |
| 526 | // REMOVAL 7: `ln > 0` guard removed in findKeyStart |
| 527 | // Verify nextToken returning non-negative guarantees len(data) > 0 |
| 528 | // ============================================================================= |
| 529 | |
| 530 | // Verifies: SYS-REQ-001 [boundary] |
| 531 | func TestRemoval7_NextToken_EmptyInput(t *testing.T) { |
| 532 | result := nextToken([]byte{}) |
| 533 | if result != -1 { |
| 534 | t.Fatalf("nextToken([]) = %d, expected -1", result) |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | // Verifies: SYS-REQ-001 [boundary] |
| 539 | func TestRemoval7_NextToken_WhitespaceOnly(t *testing.T) { |
| 540 | result := nextToken([]byte(" \t\n")) |
| 541 | if result != -1 { |
| 542 | t.Fatalf("nextToken(whitespace) = %d, expected -1", result) |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | // Verifies: SYS-REQ-001 [boundary] |
| 547 | func TestRemoval7_FindKeyStart_NextTokenGuaranteesNonEmpty(t *testing.T) { |
| 548 | // If nextToken returns >= 0, then data has at least one non-whitespace byte, |
| 549 | // which means len(data) >= 1, which means ln > 0. |
| 550 | // Proof: nextToken iterates data[0..len-1]. If len=0, loop doesn't execute, |
| 551 | // returns -1. So nextToken >= 0 ⟹ len(data) >= 1. |
| 552 | |
| 553 | // Test: findKeyStart with valid minimal input |
| 554 | _, err := findKeyStart([]byte(`{"a":1}`), "a") |
| 555 | if err != nil { |
| 556 | t.Fatalf("findKeyStart failed: %v", err) |
| 557 | } |
| 558 | |
| 559 | // Test: findKeyStart with empty input |
| 560 | _, err = findKeyStart([]byte{}, "a") |
| 561 | if err != KeyPathNotFoundError { |
| 562 | t.Fatalf("expected KeyPathNotFoundError, got %v", err) |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | // ============================================================================= |
| 567 | // EXTRA: ObjectEach `for offset < len(data)` → `for {}` |
| 568 | // Verify the loop can't run past the end of data. |
| 569 | // ============================================================================= |
| 570 | |
| 571 | // Verifies: SYS-REQ-007 [boundary] |
| 572 | func TestRemoval_ObjectEach_MalformedTrailingComma(t *testing.T) { |
| 573 | // Object ends with comma but no more entries: `{"a":1,}` |
| 574 | // After parsing "a":1, the loop finds comma, skips it, calls nextToken. |
| 575 | // nextToken on "}" returns 0, offset points to '}', loop iteration starts, |
| 576 | // switch hits '}' → return nil. No out-of-bounds. |
| 577 | err := ObjectEach([]byte(`{"a":1,"b":2}`), func(key []byte, value []byte, dataType ValueType, offset int) error { |
| 578 | return nil |
| 579 | }) |
| 580 | if err != nil { |
| 581 | t.Fatalf("unexpected error: %v", err) |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | // Verifies: SYS-REQ-007 [boundary] |
| 586 | func TestRemoval_ObjectEach_MalformedNoClosingBrace(t *testing.T) { |
| 587 | // `{"a":1` — no closing brace. After parsing "a":1, |
| 588 | // nextToken on remaining data. Get consumes "1", offset moves past it. |
| 589 | // nextToken(data[offset:]) on empty/near-empty → returns -1 → error. |
| 590 | err := ObjectEach([]byte(`{"a":1`), func(key []byte, value []byte, dataType ValueType, offset int) error { |
| 591 | return nil |
| 592 | }) |
| 593 | if err == nil { |
| 594 | t.Fatal("expected error for missing closing brace") |
| 595 | } |
| 596 | t.Logf("Correctly got error: %v", err) |
| 597 | } |
| 598 | |
| 599 | // ============================================================================= |
| 600 | // STRESS: Ensure no infinite loops or panics on pathological inputs |
| 601 | // ============================================================================= |
| 602 | |
| 603 | // Verifies: SYS-REQ-006 [boundary] |
| 604 | func TestStress_ArrayEach_NestedEmpty(t *testing.T) { |
| 605 | _, err := ArrayEach([]byte(`[[],[]]`), func(value []byte, dataType ValueType, offset int, err error) { |
| 606 | // nested arrays |
| 607 | }) |
| 608 | if err != nil { |
| 609 | t.Fatalf("unexpected error: %v", err) |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | // Verifies: SYS-REQ-008 [boundary] |
| 614 | func TestStress_EachKey_LargeNestedSkip(t *testing.T) { |
| 615 | // Build a large nested object that must be skipped |
| 616 | inner := `{"a":{"b":{"c":{"d":"deep"}}}}` |
| 617 | data := fmt.Sprintf(`{"skip":%s,"want":"found"}`, inner) |
| 618 | paths := [][]string{{"want"}} |
| 619 | |
| 620 | var found bool |
| 621 | EachKey([]byte(data), func(idx int, value []byte, vt ValueType, err error) { |
| 622 | if idx == 0 { |
| 623 | found = true |
| 624 | if string(value) != "found" { |
| 625 | t.Fatalf("expected 'found', got %q", value) |
| 626 | } |
| 627 | } |
| 628 | }, paths...) |
| 629 | |
| 630 | if !found { |
| 631 | t.Fatal("EachKey failed to find 'want' after large nested skip") |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | // Verifies: SYS-REQ-010 [boundary] |
| 636 | func TestStress_Delete_TokenEndBoundary(t *testing.T) { |
| 637 | // Test Delete where tokenEnd reaches the sentinel (returns len(data)) |
| 638 | // This exercises the new `endOffset+tokEnd >= len(data)` guard |
| 639 | result := Delete([]byte(`{"a":1,"b":2}`), "b") |
| 640 | val, _, _, err := Get(result, "a") |
| 641 | if err != nil { |
| 642 | t.Fatalf("after delete, failed to get 'a': %v", err) |
| 643 | } |
| 644 | if string(val) != "1" { |
| 645 | t.Fatalf("after delete, 'a' = %q, want '1'", val) |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | // Verifies: SYS-REQ-001 [boundary] |
| 650 | func TestStress_Get_BareTruncatedValue(t *testing.T) { |
| 651 | // A bare value with no container and no terminator — tokenEnd returns len(data) |
| 652 | val, dt, _, err := Get([]byte("12345")) |
| 653 | if err != nil { |
| 654 | t.Fatalf("unexpected error: %v", err) |
| 655 | } |
| 656 | if dt != Number { |
| 657 | t.Fatalf("expected Number, got %v", dt) |
| 658 | } |
| 659 | if string(val) != "12345" { |
| 660 | t.Fatalf("expected '12345', got %q", val) |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | // ============================================================================= |
| 665 | // CRITICAL PATH: Verify EachKey correctly handles the removed block-skip |
| 666 | // by walking through the exact scenario step by step |
| 667 | // ============================================================================= |
| 668 | |
| 669 | // Verifies: SYS-REQ-008 [boundary] |
| 670 | func TestRemoval4_EachKey_TracePath(t *testing.T) { |
| 671 | // {"skip":{"n":1},"want":"ok"} |
| 672 | // When EachKey processes "skip" and match==-1: |
| 673 | // - i is at ':' (the colon after "skip") |
| 674 | // - tokenOffset := nextToken(data[i+1:]) — finds '{' at offset 0 |
| 675 | // - i += 0 (tokenOffset is 0, but wait: nextToken skips whitespace, |
| 676 | // and data[i+1] = '{', which is not whitespace, so nextToken returns 0) |
| 677 | // - BUT: i += tokenOffset means i is still at ':'. No, wait: |
| 678 | // the code says `i += tokenOffset`, not `i = tokenOffset`. |
| 679 | // If i was at position of ':', say position 7 in {"skip":{"n":1},"want":"ok"} |
| 680 | // then data[i+1:] starts with '{"n":1},"want":"ok"}' |
| 681 | // nextToken returns 0 (first char '{' is not whitespace) |
| 682 | // i += 0 → i is still 7 (the colon position) |
| 683 | // |
| 684 | // Then we hit `switch data[i]` where data[7] = ':' |
| 685 | // ':' is not in {'{', '}', '[', '"'} so no i-- adjustment. |
| 686 | // |
| 687 | // Then the outer loop does i++ → i = 8, which is '{'. |
| 688 | // The outer switch hits case '{': → level++. |
| 689 | // The parser then navigates the nested object naturally. |
| 690 | // |
| 691 | // The OLD code had: if data[i] == '{' { blockSkip = blockEnd(...); i += blockSkip + 1 } |
| 692 | // This would have jumped past the entire nested object. |
| 693 | // The NEW code relies on the natural '{' handler in the outer switch. |
| 694 | // |
| 695 | // Both should work, but the new code is O(n) walking character by character |
| 696 | // through the nested object, while the old code was O(n) via blockEnd. |
| 697 | // Functionally equivalent. |
| 698 | |
| 699 | data := []byte(`{"skip":{"n":1},"want":"ok"}`) |
| 700 | paths := [][]string{{"want"}} |
| 701 | |
| 702 | var found bool |
| 703 | EachKey(data, func(idx int, value []byte, vt ValueType, err error) { |
| 704 | if idx == 0 { |
| 705 | found = true |
| 706 | if string(value) != "ok" { |
| 707 | t.Fatalf("expected 'ok', got %q", value) |
| 708 | } |
| 709 | } |
| 710 | }, paths...) |
| 711 | |
| 712 | if !found { |
| 713 | t.Fatal("UNSAFE: EachKey failed the trace path test") |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | // Test with value types that aren't objects — numbers, arrays, strings, bools |
| 718 | // Verifies: SYS-REQ-008 [boundary] |
| 719 | func TestRemoval4_EachKey_SkipVariousValueTypes(t *testing.T) { |
| 720 | tests := []struct { |
| 721 | name string |
| 722 | json string |
| 723 | }{ |
| 724 | {"number", `{"skip":42,"want":"ok"}`}, |
| 725 | {"negative", `{"skip":-1,"want":"ok"}`}, |
| 726 | {"float", `{"skip":3.14,"want":"ok"}`}, |
| 727 | {"bool_true", `{"skip":true,"want":"ok"}`}, |
| 728 | {"bool_false", `{"skip":false,"want":"ok"}`}, |
| 729 | {"null", `{"skip":null,"want":"ok"}`}, |
| 730 | {"string", `{"skip":"hello","want":"ok"}`}, |
| 731 | {"array", `{"skip":[1,2,3],"want":"ok"}`}, |
| 732 | {"nested_array", `{"skip":[[1],[2]],"want":"ok"}`}, |
| 733 | {"object", `{"skip":{"a":1},"want":"ok"}`}, |
| 734 | {"deep_object", `{"skip":{"a":{"b":{"c":1}}},"want":"ok"}`}, |
| 735 | {"empty_object", `{"skip":{},"want":"ok"}`}, |
| 736 | {"empty_array", `{"skip":[],"want":"ok"}`}, |
| 737 | {"empty_string", `{"skip":"","want":"ok"}`}, |
| 738 | } |
| 739 | |
| 740 | paths := [][]string{{"want"}} |
| 741 | for _, tt := range tests { |
| 742 | t.Run(tt.name, func(t *testing.T) { |
| 743 | var found bool |
| 744 | EachKey([]byte(tt.json), func(idx int, value []byte, vt ValueType, err error) { |
| 745 | if idx == 0 { |
| 746 | found = true |
| 747 | if string(value) != "ok" { |
| 748 | t.Fatalf("expected 'ok', got %q", value) |
| 749 | } |
| 750 | } |
| 751 | }, paths...) |
| 752 | if !found { |
| 753 | t.Fatalf("EachKey failed to find 'want' in %s case", tt.name) |
| 754 | } |
| 755 | }) |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | // ============================================================================= |
| 760 | // ADDITIONAL: Test that the Unescape loop change doesn't affect error handling |
| 761 | // ============================================================================= |
| 762 | |
| 763 | // Verifies: SYS-REQ-014 [boundary] |
| 764 | func TestRemoval1_Unescape_InvalidEscape(t *testing.T) { |
| 765 | _, err := Unescape([]byte(`\z`), make([]byte, 64)) |
| 766 | if err == nil { |
| 767 | t.Fatal("expected MalformedStringEscapeError for \\z") |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | // Verifies: SYS-REQ-014 [boundary] |
| 772 | func TestRemoval1_Unescape_ConsecutiveEscapes(t *testing.T) { |
| 773 | out, err := Unescape([]byte(`\n\t\r`), make([]byte, 64)) |
| 774 | if err != nil { |
| 775 | t.Fatalf("unexpected error: %v", err) |
| 776 | } |
| 777 | if string(out) != "\n\t\r" { |
| 778 | t.Fatalf("unexpected result: %q", out) |
| 779 | } |
| 780 | } |
| 781 | |
| 782 | // Verifies: SYS-REQ-014 [boundary] |
| 783 | func TestRemoval1_Unescape_EscapedQuote(t *testing.T) { |
| 784 | out, err := Unescape([]byte(`hello\"world`), make([]byte, 64)) |
| 785 | if err != nil { |
| 786 | t.Fatalf("unexpected error: %v", err) |
| 787 | } |
| 788 | if string(out) != `hello"world` { |
| 789 | t.Fatalf("unexpected result: %q", out) |
| 790 | } |
| 791 | } |