1use crate::encode::normalize::normalize_json_value;
2use crate::options::{EncodeReplacer, PathSegment};
3use crate::{JsonArray, JsonObject, JsonValue};
4
5pub fn apply_replacer(root: &JsonValue, replacer: &EncodeReplacer) -> JsonValue {
6 let replaced_root = replacer("", root, &[]);
7 if let Some(value) = replaced_root {
8 let normalized = normalize_json_value(value);
9 return transform_children(normalized, replacer, &[]);
10 }
11
12 transform_children(root.clone(), replacer, &[])
13}
14
15fn transform_children(
16 value: JsonValue,
17 replacer: &EncodeReplacer,
18 path: &[PathSegment],
19) -> JsonValue {
20 match value {
21 JsonValue::Object(entries) => JsonValue::Object(transform_object(entries, replacer, path)),
22 JsonValue::Array(values) => JsonValue::Array(transform_array(values, replacer, path)),
23 JsonValue::Primitive(value) => JsonValue::Primitive(value),
24 }
25}
26
27fn transform_object(
28 entries: JsonObject,
29 replacer: &EncodeReplacer,
30 path: &[PathSegment],
31) -> JsonObject {
32 let mut result = Vec::new();
33
34 for (key, value) in entries {
35 let mut next_path = path.to_vec();
36 next_path.push(PathSegment::Key(key.clone()));
37
38 let replacement = replacer(&key, &value, &next_path);
39 if let Some(next_value) = replacement {
40 let normalized = normalize_json_value(next_value);
41 let transformed = transform_children(normalized, replacer, &next_path);
42 result.push((key, transformed));
43 }
44 }
45
46 result
47}
48
49fn transform_array(
50 values: JsonArray,
51 replacer: &EncodeReplacer,
52 path: &[PathSegment],
53) -> JsonArray {
54 let mut result = Vec::new();
55
56 for (idx, value) in values.into_iter().enumerate() {
57 let mut next_path = path.to_vec();
58 next_path.push(PathSegment::Index(idx));
59
60 let key = idx.to_string();
61 let replacement = replacer(&key, &value, &next_path);
62 if let Some(next_value) = replacement {
63 let normalized = normalize_json_value(next_value);
64 let transformed = transform_children(normalized, replacer, &next_path);
65 result.push(transformed);
66 }
67 }
68
69 result
70}