Optimize ContextPairs nested name splitting

See gh-48999

Signed-off-by: aalsanie <ahmad.alsanie@hotmail.com>
This commit is contained in:
aalsanie
2026-02-08 15:37:42 -08:00
committed by Phillip Webb
parent e48c619505
commit dd8ace8d68
2 changed files with 43 additions and 5 deletions
@@ -193,24 +193,49 @@ public class ContextPairs {
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
this.addedPairs.forEach((addedPair) -> {
addedPair.accept(item, joining((name, value) -> {
List<String> nameParts = List.of(name.split("\\."));
Map<String, Object> destination = result;
for (int i = 0; i < nameParts.size() - 1; i++) {
Object existing = destination.computeIfAbsent(nameParts.get(i), (key) -> new LinkedHashMap<>());
int end = trimTrailingDelimiters(name);
if (end == 0) {
return;
}
int start = 0;
while (true) {
int dot = name.indexOf('.', start);
if (dot == -1 || dot >= end) {
break;
}
String part = name.substring(start, dot);
Object existing = destination.computeIfAbsent(part, (key) -> new LinkedHashMap<>());
if (!(existing instanceof Map)) {
String common = String.join(".", nameParts.subList(0, i + 1));
String common = name.substring(0, dot);
throw new IllegalStateException(
"Duplicate nested pairs added under '%s'".formatted(common));
}
destination = (Map<String, Object>) existing;
start = dot + 1;
}
Object previous = destination.put(nameParts.get(nameParts.size() - 1), value);
String leaf = name.substring(start, end);
Object previous = destination.put(leaf, value);
Assert.state(previous == null, () -> "Duplicate nested pairs added under '%s'".formatted(name));
}));
});
result.forEach(pairs);
}
private int trimTrailingDelimiters(String name) {
int end = name.length();
while (end > 0 && name.charAt(end - 1) == '.') {
end--;
}
return end;
}
private <V> BiConsumer<String, V> joining(BiConsumer<String, V> pairs) {
return (name, value) -> {
name = this.joiner.join(ContextPairs.this.prefix, (name != null) ? name : "");
@@ -120,6 +120,19 @@ class ContextPairsTests {
assertThat(actual).isEqualTo(expected);
}
@Test
void nestedWhenNameEndsWithDelimiterDropsTrailingDelimiter() {
ContextPairs contextPairs = new ContextPairs(true, null);
Map<String, String> map = new LinkedHashMap<>();
map.put("a1.b1.", "A1B1");
Map<String, Object> actual = apply(contextPairs.nested((pairs) -> pairs.addMapEntries((item) -> map)));
Map<String, Object> expected = new LinkedHashMap<>();
Map<String, Object> a1 = new LinkedHashMap<>();
expected.put("a1", a1);
a1.put("b1", "A1B1");
assertThat(actual).isEqualTo(expected);
}
@Test
void nestedWhenDuplicateInParentThrowsException() {
ContextPairs contextPairs = new ContextPairs(true, null);