force will clobber existing values that don't conform to path so SetPath(5, ["a"], 6 true) would return {"a": 6}
(data any, pp pathWithPos, value any, opts SetPathOpts)
| 342 | // force will clobber existing values that don't conform to path |
| 343 | // so SetPath(5, ["a"], 6 true) would return {"a": 6} |
| 344 | func setPathInternal(data any, pp pathWithPos, value any, opts SetPathOpts) (any, error) { |
| 345 | if pp.Index >= len(pp.Path) { |
| 346 | if opts.CombineFn != nil { |
| 347 | return opts.CombineFn(data, value, pp, opts) |
| 348 | } |
| 349 | return value, nil |
| 350 | } |
| 351 | pathElemAny := pp.Path[pp.Index] |
| 352 | switch pathElem := pathElemAny.(type) { |
| 353 | case string: |
| 354 | if data == nil { |
| 355 | if opts.Remove { |
| 356 | return nil, nil |
| 357 | } |
| 358 | data = make(map[string]any) |
| 359 | } |
| 360 | mapVal, ok := data.(map[string]any) |
| 361 | if !ok && !opts.Force { |
| 362 | return nil, MakeSetTypeError(fmt.Sprintf("expected map, but got %T", data), pp.Path, pp.Index) |
| 363 | } |
| 364 | if !ok { |
| 365 | mapVal = make(map[string]any) |
| 366 | } |
| 367 | if opts.Remove && pp.isLast() { |
| 368 | delete(mapVal, pathElem) |
| 369 | if len(mapVal) == 0 { |
| 370 | return nil, nil |
| 371 | } |
| 372 | return mapVal, nil |
| 373 | } |
| 374 | if _, ok := mapVal[pathElem]; !ok { |
| 375 | if opts.Remove { |
| 376 | return mapVal, nil |
| 377 | } |
| 378 | if !checkAndModifyBudget(&opts, pp, 1) { |
| 379 | return nil, MakeBudgetError("trying to allocate map entry", pp.Path, pp.Index) |
| 380 | } |
| 381 | } |
| 382 | newVal, err := setPathInternal(mapVal[pathElem], pathWithPos{Path: pp.Path, Index: pp.Index + 1}, value, opts) |
| 383 | if opts.Remove && newVal == nil { |
| 384 | delete(mapVal, pathElem) |
| 385 | if len(mapVal) == 0 { |
| 386 | return nil, nil |
| 387 | } |
| 388 | return mapVal, nil |
| 389 | } |
| 390 | mapVal[pathElem] = newVal |
| 391 | return mapVal, err |
| 392 | case int: |
| 393 | if pathElem < 0 { |
| 394 | return nil, MakePathError("negative index", pp.Path, pp.Index) |
| 395 | } |
| 396 | if data == nil { |
| 397 | if opts.Remove { |
| 398 | return nil, nil |
| 399 | } |
| 400 | if !checkAndModifyBudget(&opts, pp, pathElem+1) { |
| 401 | return nil, MakeBudgetError(fmt.Sprintf("trying to allocate array with %d elements", pathElem+1), pp.Path, pp.Index) |
no test coverage detected