-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointer.go
More file actions
782 lines (711 loc) · 26 KB
/
Copy pathpointer.go
File metadata and controls
782 lines (711 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
// Package jsonx provides extended JSON functionality including RFC 6901 JSON Pointer
// implementation and synchronous data providers for JSON document access.
//
// This package enhances Go's standard encoding/json package by providing:
// - Complete RFC 6901 JSON Pointer implementation for document navigation
// - Optimized parsing and evaluation with minimal allocations
// - Comprehensive error handling with predefined error types
// - Reflection-based navigation for custom types and structures
// - Sync providers for accessing JSON data from various sources
//
// Key features:
// - RFC 6901 compliant JSON Pointer parsing and evaluation
// - Support for escape sequences (~0 for ~, ~1 for /)
// - Array index validation and bounds checking
// - Type-safe navigation with detailed error messages
// - Performance optimizations for common cases (no escapes, direct types)
// - Reflection fallback for custom types and complex structures
//
// Example usage:
//
// // Parse a JSON document
// var doc interface{}
// json.Unmarshal([]byte(`{"users": [{"name": "Alice"}, {"name": "Bob"}]}`), &doc)
//
// // Create and use JSON Pointers
// ptr, err := jsonx.NewPointer("/users/1/name")
// if err != nil {
// log.Fatal(err)
// }
//
// value, err := ptr.Get(doc)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(value) // Output: "Bob"
//
// // Handle special characters and escapes
// ptr, _ := jsonx.NewPointer("/path~1with~0special/chars")
// // This references the key "path/with~special" in the object at root
//
// JSON Pointer Syntax (RFC 6901):
// - Empty string "" refers to the root document
// - Must start with "/" (except for root)
// - Tokens are separated by "/"
// - Special characters: "~0" becomes "~", "~1" becomes "/"
// - Array indices must be non-negative integers without leading zeros
// - "-" is reserved for array append operations (not supported in Get)
package jsonpointer
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
// Pointer represents a JSON Pointer as defined in RFC 6901.
// It consists of a sequence of reference tokens that identify a specific
// value within a JSON document. Each token in the slice is already decoded
// and ready for direct comparison against JSON object keys or parsing as
// array indices.
//
// The Pointer type provides methods for parsing JSON Pointer strings,
// navigating JSON documents, and converting back to string representation.
// It supports the full RFC 6901 specification including escape sequences
// and array index validation.
//
// Example:
//
// // Create from string
// ptr, err := jsonx.NewPointer("/users/0/profile/name")
//
// // Manual construction
// ptr := jsonx.Pointer{"users", "0", "profile", "name"}
//
// // Navigate document
// value, err := ptr.Get(document)
//
// // Convert back to string
// pointerStr := ptr.String() // "/users/0/profile/name"
type Pointer []string
// Predefined errors for clear error handling and easy error checking using errors.Is.
// These errors follow the pattern of providing both machine-readable error types
// and human-readable context through error wrapping.
var (
// ErrInvalidSyntax indicates that the JSON Pointer string does not conform
// to the RFC 6901 syntax rules (e.g., missing leading slash, invalid escapes).
ErrInvalidSyntax = errors.New("jsonx: invalid pointer syntax")
// ErrNotFound indicates that the specified path could not be resolved
// (e.g., missing key, array index out of bounds, null value encountered).
ErrNotFound = errors.New("jsonx: value not found")
// ErrInvalidIndex indicates that an array index is malformed
// (e.g., non-numeric, leading zeros, negative numbers).
ErrInvalidIndex = errors.New("jsonx: invalid array index")
// ErrNotAnObjectOrArray indicates an attempt to dereference a value
// that is neither a JSON object nor array (e.g., trying to access "/string/key").
ErrNotAnObjectOrArray = errors.New("jsonx: cannot dereference a non-object or non-array value")
// ErrArrayAppendIndexOnly indicates that the "-" array append index
// was used in a context where it's not supported (Get operations).
ErrArrayAppendIndexOnly = errors.New("jsonx: '-' can only be used as an array append index")
)
// New parses a JSON Pointer string according to RFC 6901 and returns a Pointer object.
// The function handles escape sequence decoding (~0 to ~, ~1 to /) and validates syntax.
//
// Syntax rules (RFC 6901):
// - Empty string "" represents the root document
// - Non-empty pointers must start with "/"
// - Tokens are separated by "/" characters
// - Escape sequences: "~0" becomes "~", "~1" becomes "/"
// - No other escape sequences are valid
//
// Performance optimizations:
// - Pre-allocates token slice based on "/" count to reduce reallocations
// - Avoids string operations when no escape sequences are present
// - Uses efficient character-by-character parsing
//
// Example:
//
// // Basic pointers
// root, _ := jsonx.New("") // Root document
// simple, _ := jsonx.New("/users") // ["users"]
// nested, _ := jsonx.New("/a/b/c") // ["a", "b", "c"]
//
// // Escape sequences
// escaped, _ := jsonx.New("/path~1with~0special") // ["path/with~special"]
//
// // Error cases
// _, err := jsonx.New("no-slash") // ErrInvalidSyntax
// _, err := jsonx.New("/invalid~2") // ErrInvalidSyntax
func New(s string) (Pointer, error) {
// Empty string represents the root document (RFC 6901, Section 3)
if s == "" {
return Pointer{}, nil
}
// Non-empty pointers must start with "/" (RFC 6901, Section 3)
if s[0] != '/' {
return nil, fmt.Errorf("%w: pointer must start with '/' unless empty", ErrInvalidSyntax)
}
// Optimize allocation by pre-counting "/" characters to estimate token count.
// This reduces slice reallocations during parsing.
numSlashes := 0
for i := 1; i < len(s); i++ {
if s[i] == '/' {
numSlashes++
}
}
// For non-empty strings, calculate expected token count:
// "/a" has 0 internal slashes but 1 token
// "/a/b" has 1 internal slash but 2 tokens
// So tokens = numSlashes + 1 for non-empty strings
var tokens []string
if len(s) > 0 {
tokens = make([]string, 0, numSlashes+1)
}
// Parse tokens by manually splitting on "/" to avoid strings.Split overhead
start := 1 // Skip the initial "/"
for i := 1; i < len(s); i++ {
if s[i] == '/' {
// Decode the token between start and i
decoded, err := decodeToken(s[start:i])
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidSyntax, err.Error())
}
tokens = append(tokens, decoded)
start = i + 1
}
}
// Handle the final token (everything after the last "/" or after initial "/")
// This also handles the special case of "/" (single slash = empty string token)
decoded, err := decodeToken(s[start:])
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidSyntax, err.Error())
}
tokens = append(tokens, decoded)
return tokens, nil
}
// String converts the Pointer back to its RFC 6901 string representation.
// This is the inverse operation of NewPointer, ensuring round-trip consistency.
//
// The method properly encodes special characters in tokens:
// - "~" becomes "~0"
// - "/" becomes "~1"
//
// Performance optimizations:
// - Pre-calculates approximate buffer size to reduce allocations
// - Avoids encoding when no special characters are present
// - Uses efficient string building techniques
//
// Example:
//
// ptr := jsonx.Pointer{"users", "1", "name"}
// s := ptr.String() // "/users/1/name"
//
// // With special characters
// ptr := jsonx.Pointer{"path/with~special"}
// s := ptr.String() // "/path~1with~0special"
//
// // Root pointer
// ptr := jsonx.Pointer{}
// s := ptr.String() // ""
func (p Pointer) String() string {
// Root pointer is represented as empty string (RFC 6901, Section 3)
if len(p) == 0 {
return ""
}
var sb strings.Builder
// Pre-calculate approximate size to reduce allocations.
// Each token gets a "/" prefix plus its encoded length.
// This is a conservative estimate; actual size may be larger due to encoding.
estimatedLen := 0
for _, token := range p {
estimatedLen += 1 + len(token) // 1 for "/" + token length
}
sb.Grow(estimatedLen)
// Build the pointer string by prefixing each token with "/" and encoding it
for _, token := range p {
sb.WriteByte('/')
sb.WriteString(encodeToken(token))
}
return sb.String()
}
// encodeToken encodes special characters in a token for JSON Pointer string representation.
// Implements the encoding rules from RFC 6901, Section 3:
// - "~" (tilde) becomes "~0"
// - "/" (slash) becomes "~1"
//
// Performance optimization: checks if encoding is needed before allocating a new string.
func encodeToken(s string) string {
// Fast path: check if the token contains any characters that need escaping.
// This avoids allocations for the common case of tokens without special chars.
needsEscape := false
for i := 0; i < len(s); i++ {
if s[i] == '~' || s[i] == '/' {
needsEscape = true
break
}
}
if !needsEscape {
return s
}
// Slow path: build escaped string using strings.Builder for efficiency
var sb strings.Builder
sb.Grow(len(s) + 3) // Pre-allocate assuming a few escapes
for i := 0; i < len(s); i++ {
switch s[i] {
case '~':
sb.WriteString("~0")
case '/':
sb.WriteString("~1")
default:
sb.WriteByte(s[i])
}
}
return sb.String()
}
// decodeToken decodes JSON Pointer escape sequences in a token.
// Implements the decoding rules from RFC 6901, Section 3:
// - "~0" becomes "~" (tilde)
// - "~1" becomes "/" (slash)
// - Any other "~X" sequence is invalid
//
// Performance optimization: avoids allocation when no escape sequences are present.
func decodeToken(s string) (string, error) {
// Fast path: check if the token contains any escape characters.
// This avoids allocations for the common case of tokens without escapes.
containsEscape := false
for i := 0; i < len(s); i++ {
if s[i] == '~' {
containsEscape = true
break
}
}
if !containsEscape {
return s, nil
}
// Slow path: decode escape sequences using strings.Builder for efficiency
var sb strings.Builder
sb.Grow(len(s)) // Pre-allocate to minimize reallocations
for i := 0; i < len(s); i++ {
if s[i] == '~' {
i++ // Move to the character after '~'
if i >= len(s) {
return "", errors.New("incomplete escape sequence")
}
switch s[i] {
case '1':
sb.WriteByte('/') // "~1" -> "/"
case '0':
sb.WriteByte('~') // "~0" -> "~"
default:
return "", fmt.Errorf("invalid escape sequence: ~%c", s[i])
}
} else {
sb.WriteByte(s[i])
}
}
return sb.String(), nil
}
// Get is a convenience function that parses a JSON Pointer string and uses it
// to retrieve a value from a document. For repeated lookups, it is more efficient
// to create a Pointer object once and reuse it.
func Get(doc any, pointer string) (any, error) {
if pointer == "" {
return doc, nil
}
if pointer[0] != '/' {
return nil, fmt.Errorf("%w: pointer must start with '/' unless empty", ErrInvalidSyntax)
}
current := doc
start := 1
pathSegment := 0
for i := 1; i < len(pointer); i++ {
if pointer[i] == '/' {
token, err := decodeToken(pointer[start:i])
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidSyntax, err.Error())
}
current, err = dereference(current, token, pathSegment)
if err != nil {
return nil, err
}
start = i + 1
pathSegment++
}
}
token, err := decodeToken(pointer[start:])
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidSyntax, err.Error())
}
return dereference(current, token, pathSegment)
}
// Remove is a convenience function that parses a JSON Pointer string and uses it
// to remove a value from a document.
func Remove(doc any, pointer string) (any, error) {
if pointer == "" {
return nil, errors.New("cannot remove the root of the document with an empty pointer")
}
p, err := New(pointer)
if err != nil {
return nil, err
}
return p.Remove(doc)
}
// Set is a convenience function that parses a JSON Pointer string and uses it
// to set a value in a document. It offers better performance for single-use cases
// by avoiding the intermediate allocation of a Pointer object.
func Set(doc any, pointer string, value any) (any, error) {
if pointer == "" {
return value, nil
}
p, err := New(pointer)
if err != nil {
return nil, err
}
return p.Set(doc, value)
}
// Set evaluates the JSON Pointer against a JSON document, sets the referenced value,
// and returns the potentially modified document. It creates nested objects or slices as needed
// when parts of the path do not exist.
//
// This implementation prioritizes performance for standard JSON types (`map[string]any`
// and `[]any`) by avoiding reflection. If a path segment encounters a value that
// is not one of these container types and the path is not fully resolved, an
// error is returned.
//
// Key behaviors:
// - Creates nested maps for non-existent object keys.
// - Appends to slices when the index is the last token and is either "-"
// or equal to the slice length.
// - Replaces the entire document if the pointer is empty.
//
// Example:
//
// var doc any
// json.Unmarshal([]byte(`{"users": [{"name": "Alice"}]}`), &doc)
//
// // Set a value
// ptr, _ := New("/users/0/name")
// doc, err := ptr.Set(doc, "Alicia")
//
// // Create a new value
// ptr, _ := New("/users/1")
// doc, err = ptr.Set(doc, map[string]any{"name": "Bob"})
//
// // Append to an array
// ptr, _ := New("/users/-")
// doc, err = ptr.Set(doc, map[string]any{"name": "Charlie"})
func (p Pointer) Set(doc any, value any) (any, error) {
if len(p) == 0 {
return value, nil
}
return p.setRecursive(doc, p, value)
}
// setRecursive is the helper that implements the modification logic.
func (p Pointer) setRecursive(currentDoc any, tokens []string, value any) (any, error) {
// Base case: we've reached the end of the path, so we return the value to be set.
if len(tokens) == 0 {
return value, nil
}
token := tokens[0]
remainingTokens := tokens[1:]
pathSegment := len(p) - len(tokens)
// If the current document is nil, create a container for the next level.
if currentDoc == nil {
if _, err := ParseArrayIndex(token); err == nil || token == "-" {
// If token is an index, we expect a slice.
currentDoc = []any{}
} else {
// Otherwise, create a map.
currentDoc = make(map[string]any)
}
}
switch c := currentDoc.(type) {
case map[string]any:
child, _ := c[token]
newChild, err := p.setRecursive(child, remainingTokens, value)
if err != nil {
return nil, err
}
c[token] = newChild
return c, nil
case []any:
if token == "-" {
// "-" is only valid for appending, which means it must be the last token.
if len(remainingTokens) > 0 {
return nil, fmt.Errorf("%w: '-' may only be the last token in a pointer (path segment %d)", ErrInvalidIndex, pathSegment)
}
// The recursive call with empty remaining tokens will just return the value.
newChild, err := p.setRecursive(nil, remainingTokens, value)
if err != nil {
return nil, err
}
return append(c, newChild), nil
}
idx, err := ParseArrayIndex(token)
if err != nil {
return nil, fmt.Errorf("%w: '%s' is not a valid array index (path segment %d): %v", ErrInvalidIndex, token, pathSegment, err)
}
// Case 1: Append to slice or insert into slice
if idx == uint64(len(c)) {
newChild, err := p.setRecursive(nil, remainingTokens, value)
if err != nil {
return nil, err
}
return append(c, newChild), nil
}
// Case 2: Index out of bounds
if idx > uint64(len(c)) {
return nil, fmt.Errorf("%w: array index %d out of bounds for set (length %d) (path segment %d)", ErrNotFound, idx, len(c), pathSegment)
}
// Case 3: Replace element at index
if len(remainingTokens) == 0 {
// This is a direct replacement at this level
c[idx] = value
return c, nil
}
// Case 4: Recursive set on an existing element
child := c[idx]
newChild, err := p.setRecursive(child, remainingTokens, value)
if err != nil {
return nil, err
}
c[idx] = newChild
return c, nil
default:
return nil, fmt.Errorf("%w: value for token '%s' is not an object or array (path segment %d)", ErrNotAnObjectOrArray, token, pathSegment)
}
}
// Remove evaluates the JSON Pointer against a JSON document and removes the
// referenced value.
//
// Note that removing an element from a slice will cause subsequent elements to
// shift their indices. The underlying array is modified and re-sliced.
func (p Pointer) Remove(doc any) (any, error) {
if len(p) == 0 {
return nil, errors.New("jsonx: cannot remove the root of the document with an empty pointer")
}
return p.removeRecursive(doc, p)
}
// removeRecursive is the helper that implements the removal logic.
func (p Pointer) removeRecursive(currentDoc any, tokens []string) (any, error) {
if currentDoc == nil {
return nil, fmt.Errorf("%w: cannot remove from a nil document", ErrNotFound)
}
token := tokens[0]
remainingTokens := tokens[1:]
pathSegment := len(p) - len(tokens)
// Base case: last token in path, perform the removal.
if len(remainingTokens) == 0 {
switch c := currentDoc.(type) {
case map[string]any:
if _, ok := c[token]; !ok {
return nil, fmt.Errorf("%w: key '%s' not found for removal (path segment %d)", ErrNotFound, token, pathSegment)
}
delete(c, token)
return c, nil
case []any:
idx, err := ParseArrayIndex(token)
if err != nil {
return nil, fmt.Errorf("%w: '%s' is not a valid array index for removal (path segment %d): %v", ErrInvalidIndex, token, pathSegment, err)
}
if idx >= uint64(len(c)) {
return nil, fmt.Errorf("%w: array index %d out of bounds for removal (length %d) (path segment %d)", ErrNotFound, idx, len(c), pathSegment)
}
return append(c[:idx], c[idx+1:]...), nil
default:
return nil, fmt.Errorf("%w: value for token '%s' is not a removable object or array (path segment %d)", ErrNotAnObjectOrArray, token, pathSegment)
}
}
// Recursive step: navigate deeper.
switch c := currentDoc.(type) {
case map[string]any:
child, ok := c[token]
if !ok {
return nil, fmt.Errorf("%w: key '%s' not found in path (path segment %d)", ErrNotFound, token, pathSegment)
}
newChild, err := p.removeRecursive(child, remainingTokens)
if err != nil {
return nil, err
}
c[token] = newChild
return c, nil
case []any:
idx, err := ParseArrayIndex(token)
if err != nil {
return nil, fmt.Errorf("%w: '%s' is not a valid array index in path (path segment %d): %v", ErrInvalidIndex, token, pathSegment, err)
}
if idx >= uint64(len(c)) {
return nil, fmt.Errorf("%w: array index %d out of bounds in path (length %d) (path segment %d)", ErrNotFound, idx, len(c), pathSegment)
}
child := c[idx]
newChild, err := p.removeRecursive(child, remainingTokens)
if err != nil {
return nil, err
}
c[idx] = newChild
return c, nil
default:
return nil, fmt.Errorf("%w: value for token '%s' is not an object or array (path segment %d)", ErrNotAnObjectOrArray, token, pathSegment)
}
}
// Get evaluates the JSON Pointer against a JSON document and returns the referenced value.
// The document parameter should be the result of json.Unmarshal or compatible structure.
//
// Navigation rules:
// - Empty pointer returns the root document
// - Object navigation uses string keys for maps
// - Array navigation uses numeric indices for slices/arrays
// - Reflection is used as fallback for custom types
//
// Array index rules (RFC 6901, Section 4):
// - Must be non-negative integers
// - No leading zeros (except "0" itself)
// - "-" is reserved for append operations (not supported in Get)
// - Index must be within array bounds
//
// Error handling:
// - Returns specific error types for different failure modes
// - Includes path context (segment number) in error messages
// - Supports errors.Is for error type checking
//
// Performance optimizations:
// - Direct type checking for common JSON types (map[string]any, []any)
// - Reflection fallback only when necessary
// - Efficient array index parsing and validation
//
// Example:
//
// // Parse JSON document
// var doc interface{}
// json.Unmarshal([]byte(`{"users": [{"name": "Alice"}, {"name": "Bob"}]}`), &doc)
//
// // Navigate to specific values
// ptr, _ := jsonx.NewPointer("/users/1/name")
// value, err := ptr.Get(doc)
// if err != nil {
// if errors.Is(err, jsonx.ErrNotFound) {
// // Handle missing value
// }
// }
// fmt.Println(value) // "Bob"
//
// // Error examples
// ptr, _ := jsonx.NewPointer("/users/5/name") // Index out of bounds
// _, err = ptr.Get(doc) // Returns ErrNotFound
//
// ptr, _ := jsonx.NewPointer("/users/abc") // Invalid array index
// _, err = ptr.Get(doc) // Returns ErrInvalidIndex
func (p Pointer) Get(doc interface{}) (any, error) {
current := doc
// Empty pointer refers to the whole document (RFC 6901, Section 3)
if len(p) == 0 {
return doc, nil
}
// Navigate through each token in the pointer path
for i, token := range p {
var err error
current, err = dereference(current, token, i)
if err != nil {
return nil, err
}
}
return current, nil
}
// dereference takes a document segment and a token and returns the next segment.
// It contains the core navigation logic for both maps and slices, including reflection.
func dereference(current any, token string, pathSegment int) (any, error) {
// Check for nil values in the path
if current == nil {
return nil, fmt.Errorf("%w: encountered nil value at token '%s' (path segment %d)", ErrNotFound, token, pathSegment)
}
// Handle common JSON types with direct type assertions for performance
switch val := current.(type) {
case map[string]any:
// JSON object navigation: look up the key
next, ok := val[token]
if !ok {
return nil, fmt.Errorf("%w: key '%s' not found (path segment %d)", ErrNotFound, token, pathSegment)
}
return next, nil
case []any:
// JSON array navigation: parse and validate index
if token == "-" {
// "-" is reserved for array append operations (RFC 6901, Section 4)
return nil, fmt.Errorf("%w: array append index '-' cannot be used for retrieval (path segment %d)", ErrArrayAppendIndexOnly, pathSegment)
}
// Parse and validate array index
idx, err := ParseArrayIndex(token)
if err != nil {
return nil, fmt.Errorf("%w: '%s' is not a valid array index (path segment %d): %v", ErrInvalidIndex, token, pathSegment, err)
}
// Check bounds
if int(idx) >= len(val) {
return nil, fmt.Errorf("%w: array index %d out of bounds (length %d) (path segment %d)", ErrNotFound, idx, len(val), pathSegment)
}
return val[idx], nil
default:
// Fallback to reflection for custom types or non-standard JSON structures.
// This handles cases where JSON is unmarshaled into structs or other types.
currentValReflect := reflect.ValueOf(current)
// Dereference pointers and interfaces recursively
for currentValReflect.Kind() == reflect.Ptr || currentValReflect.Kind() == reflect.Interface {
if currentValReflect.IsNil() {
return nil, fmt.Errorf("%w: encountered nil value via reflection at token '%s' (path segment %d)", ErrNotFound, token, pathSegment)
}
currentValReflect = currentValReflect.Elem()
}
// Validate the reflected value
if !currentValReflect.IsValid() {
return nil, fmt.Errorf("%w: encountered invalid value via reflection at token '%s' (path segment %d)", ErrNotFound, token, pathSegment)
}
// Handle different reflected types
switch currentValReflect.Kind() {
case reflect.Map:
// Ensure map has string keys (required for JSON object semantics)
if currentValReflect.Type().Key().Kind() != reflect.String {
return nil, fmt.Errorf("%w: expected map with string keys, got map with %s keys for token '%s' (path segment %d)", ErrNotAnObjectOrArray, currentValReflect.Type().Key().Kind(), token, pathSegment)
}
// Look up the key in the map
nextValReflect := currentValReflect.MapIndex(reflect.ValueOf(token))
if !nextValReflect.IsValid() {
return nil, fmt.Errorf("%w: key '%s' not found via reflection (path segment %d)", ErrNotFound, token, pathSegment)
}
return nextValReflect.Interface(), nil
case reflect.Slice, reflect.Array:
// Handle array/slice navigation via reflection
if token == "-" {
return nil, fmt.Errorf("%w: array append index '-' cannot be used for retrieval via reflection (path segment %d)", ErrArrayAppendIndexOnly, pathSegment)
}
// Parse and validate array index
idx, err := ParseArrayIndex(token)
if err != nil {
return nil, fmt.Errorf("%w: '%s' is not a valid array index via reflection (path segment %d): %v", ErrInvalidIndex, token, pathSegment, err)
}
// Check bounds
if int(idx) >= currentValReflect.Len() {
return nil, fmt.Errorf("%w: array index %d out of bounds via reflection (length %d) (path segment %d)", ErrNotFound, idx, currentValReflect.Len(), pathSegment)
}
return currentValReflect.Index(int(idx)).Interface(), nil
default:
// Value is neither an object nor array, cannot dereference further
return nil, fmt.Errorf("%w: value for token '%s' is not an object or array (path segment %d)", ErrNotAnObjectOrArray, token, pathSegment)
}
}
}
// ParseArrayIndex parses a string as an array index according to RFC 6901, Section 4.
// The function validates that the string conforms to the array-index ABNF:
// - "0" (exactly zero), or
// - Digits without leading zeros (1, 2, 10, 123, etc.)
//
// This ensures compatibility with JSON array indexing semantics and prevents
// ambiguities that could arise from octal interpretation or other number formats.
//
// Example valid indices: "0", "1", "42", "123"
// Example invalid indices: "", "01", "007", "-1", "abc", "1.5"
func ParseArrayIndex(s string) (uint64, error) {
// Empty string is not a valid array index
if s == "" {
return 0, errors.New("empty string is not a valid array index")
}
// Check for leading zeros (RFC 6901, Section 4: leading zeros not allowed except for "0")
if len(s) > 1 && s[0] == '0' {
return 0, errors.New("leading zeros are not allowed in array indices (unless the index is '0')")
}
// Parse as unsigned integer (negative indices are not valid)
idx, err := strconv.ParseUint(s, 10, 64)
if err != nil {
// strconv.ParseUint handles non-numeric strings and overflow cases
return 0, err
}
return idx, nil
}