001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.json; 018 019import com.google.errorprone.annotations.CanIgnoreReturnValue; 020import com.google.errorprone.annotations.CheckReturnValue; 021import com.revetsec.internal.json.JsonWriter; 022import org.jspecify.annotations.NonNull; 023import org.jspecify.annotations.Nullable; 024 025import javax.annotation.concurrent.Immutable; 026import javax.annotation.concurrent.NotThreadSafe; 027import java.math.BigDecimal; 028import java.util.Collections; 029import java.util.LinkedHashMap; 030import java.util.List; 031import java.util.Map; 032import java.util.Optional; 033 034import static java.util.Objects.requireNonNull; 035 036/** 037 * A JSON object: an unmodifiable map from member names to values that keeps the order in which members were added. 038 * <p> 039 * <strong>Names</strong> are unique and compared exactly, with no case folding or Unicode normalization. Two objects 040 * are equal when they have the same names with equal values, whatever the order of their members. 041 * <p> 042 * <strong>Building.</strong> {@link #builder()} adds one member per {@code put} call, and a name that is already 043 * present throws {@link IllegalArgumentException} instead of replacing the earlier value. {@link #fromMembers(Map)} 044 * takes a complete map. 045 * <p> 046 * <strong>Member lookups.</strong> {@link #find(String)} returns an empty {@link Optional} only when a member is 047 * absent. A present member retains its {@link JsonValue} type, including {@link JsonNull}; callers can inspect that 048 * type to distinguish an absent member from a malformed one. 049 * 050 * @author <a href="https://www.revetkn.com">Mark Allen</a> 051 * @since 1.0.0 052 */ 053@Immutable 054public final class JsonObject implements JsonValue { 055 @NonNull 056 private static final JsonObject EMPTY = new JsonObject(new LinkedHashMap<>(), 1); 057 058 private static final String DUPLICATE_NAME_MESSAGE = "A JSON object must not contain two members with the same " 059 + "name."; 060 061 /** 062 * A {@link LinkedHashMap}, so iteration follows insertion order. Never modified after construction and never 063 * exposed except through an unmodifiable view. 064 */ 065 @NonNull 066 private final Map<@NonNull String, @NonNull JsonValue> members; 067 private final int depth; 068 private final int hashCode; 069 070 /** 071 * Returns the empty JSON object. 072 * 073 * @return the shared empty object 074 * @since 1.0.0 075 */ 076 @NonNull 077 public static JsonObject emptyInstance() { 078 return EMPTY; 079 } 080 081 /** 082 * Returns a new builder, which adds one member per {@code put} call. 083 * 084 * @return a builder with no members 085 * @since 1.0.0 086 */ 087 @NonNull 088 public static Builder builder() { 089 return new Builder(); 090 } 091 092 /** 093 * Returns a JSON object holding a snapshot of {@code members}, in the map's iteration order. 094 * 095 * @param members the members; later changes to the map do not affect the object 096 * @return the JSON object 097 * @throws NullPointerException if {@code members}, or any name or value in it, is {@code null} 098 * @throws IllegalArgumentException if a name contains an unpaired surrogate, the map holds two equal names (as an 099 * identity-based map can), or the object would nest more than 64 deep 100 * @since 1.0.0 101 */ 102 @NonNull 103 public static JsonObject fromMembers(@NonNull Map<@NonNull String, ? extends @NonNull JsonValue> members) { 104 requireNonNull(members); 105 LinkedHashMap<@NonNull String, @NonNull JsonValue> snapshot = new LinkedHashMap<>(capacityFor(members.size())); 106 int deepestChild = 0; 107 108 for (Map.Entry<@NonNull String, ? extends @NonNull JsonValue> member : members.entrySet()) { 109 String name = JsonInvariants.requireWellFormed(member.getKey()); 110 JsonValue value = requireNonNull(member.getValue()); 111 112 if (snapshot.putIfAbsent(name, value) != null) 113 throw new IllegalArgumentException(DUPLICATE_NAME_MESSAGE); 114 115 deepestChild = Math.max(deepestChild, JsonInvariants.depthOf(value)); 116 } 117 118 return fromSnapshot(snapshot, deepestChild); 119 } 120 121 /** 122 * Keeps a {@link LinkedHashMap} that no caller can reach any more. 123 */ 124 @NonNull 125 private static JsonObject fromSnapshot(@NonNull Map<@NonNull String, @NonNull JsonValue> snapshot, 126 int deepestChild) { 127 if (snapshot.isEmpty()) 128 return EMPTY; 129 130 return new JsonObject(snapshot, JsonInvariants.requireContainerDepth(deepestChild)); 131 } 132 133 /** 134 * A hash-table capacity that holds {@code size} members without resizing, so a parsed document's many small 135 * objects do not each carry a 16-slot table. 136 */ 137 private static int capacityFor(int size) { 138 return (int) Math.min(Integer.MAX_VALUE, size * 4L / 3 + 1); 139 } 140 141 private JsonObject(@NonNull Map<@NonNull String, @NonNull JsonValue> members, int depth) { 142 this.members = members; 143 this.depth = depth; 144 // Order-independent: the sum of each member's name hash XOR value hash (Map.hashCode()). 145 this.hashCode = members.hashCode(); 146 } 147 148 /** 149 * Returns this object's members, in the order they were added. 150 * 151 * @return an unmodifiable map 152 * @since 1.0.0 153 */ 154 @NonNull 155 public Map<@NonNull String, @NonNull JsonValue> getMembers() { 156 return Collections.unmodifiableMap(this.members); 157 } 158 159 /** 160 * Returns the value of the member named {@code name}. 161 * 162 * @param name the member name, compared exactly 163 * @return the value, which may be {@link JsonNull}, or empty if there is no such member 164 * @throws NullPointerException if {@code name} is {@code null} 165 * @since 1.0.0 166 */ 167 @NonNull 168 public Optional<@NonNull JsonValue> find(@NonNull String name) { 169 requireNonNull(name); 170 return Optional.ofNullable(this.members.get(name)); 171 } 172 173 174 175 176 177 /** 178 * The G7-6 depth: 1 if empty, otherwise 1 more than the deepest member value. 179 */ 180 int getDepth() { 181 return this.depth; 182 } 183 184 @Override 185 @NonNull 186 public String toJson() { 187 return JsonWriter.toJson(this); 188 } 189 190 @Override 191 public boolean equals(@Nullable Object other) { 192 return this == other || (other instanceof JsonObject object && this.hashCode == object.hashCode 193 && this.members.equals(object.members)); 194 } 195 196 @Override 197 public int hashCode() { 198 return this.hashCode; 199 } 200 201 @Override 202 @NonNull 203 public String toString() { 204 return "JsonObject{members=<redacted>}"; 205 } 206 207 /** 208 * Builds a {@link JsonObject} one member at a time, keeping the order in which members are added. 209 * <p> 210 * Each {@code put} adds exactly one member, and a name that is already present throws 211 * {@link IllegalArgumentException} rather than replacing the earlier value. Every check runs in {@code put}, so 212 * {@link #build()} never fails. A builder may be reused: each {@link #build()} returns a snapshot of the members 213 * added so far. 214 * 215 * @author <a href="https://www.revetkn.com">Mark Allen</a> 216 * @since 1.0.0 217 */ 218 @NotThreadSafe 219 @CheckReturnValue 220 public static final class Builder { 221 @NonNull 222 private final LinkedHashMap<@NonNull String, @NonNull JsonValue> members; 223 private int deepestChild; 224 225 private Builder() { 226 this.members = new LinkedHashMap<>(); 227 } 228 229 /** 230 * Adds a member. 231 * 232 * @param name the member name 233 * @param value the member value 234 * @return this builder 235 * @throws NullPointerException if an argument is {@code null} 236 * @throws IllegalArgumentException if {@code name} contains an unpaired surrogate or is already present, or 237 * the object would nest more than 64 deep 238 * @since 1.0.0 239 */ 240 @NonNull 241 @CanIgnoreReturnValue 242 public Builder put(@NonNull String name, @NonNull JsonValue value) { 243 JsonInvariants.requireWellFormed(name); 244 requireNonNull(value); 245 246 if (this.members.containsKey(name)) 247 throw new IllegalArgumentException(DUPLICATE_NAME_MESSAGE); 248 249 int valueDepth = JsonInvariants.depthOf(value); 250 JsonInvariants.requireContainerDepth(valueDepth); 251 this.members.put(name, value); 252 this.deepestChild = Math.max(this.deepestChild, valueDepth); 253 return this; 254 } 255 256 /** 257 * Adds a member whose value is a JSON string. 258 * 259 * @param name the member name 260 * @param value the string 261 * @return this builder 262 * @throws NullPointerException if an argument is {@code null} 263 * @throws IllegalArgumentException if {@code name} or {@code value} contains an unpaired surrogate, or 264 * {@code name} is already present 265 * @since 1.0.0 266 */ 267 @NonNull 268 @CanIgnoreReturnValue 269 public Builder put(@NonNull String name, @NonNull String value) { 270 return put(name, JsonString.fromValue(value)); 271 } 272 273 /** 274 * Adds a member whose value is a JSON number. 275 * 276 * @param name the member name 277 * @param value the number 278 * @return this builder 279 * @throws NullPointerException if an argument is {@code null} 280 * @throws IllegalArgumentException if {@code name} contains an unpaired surrogate or is already present 281 * @since 1.0.0 282 */ 283 @NonNull 284 @CanIgnoreReturnValue 285 public Builder put(@NonNull String name, @NonNull Long value) { 286 return put(name, JsonNumber.fromValue(value)); 287 } 288 289 /** 290 * Adds a member whose value is a JSON number, held exactly (see {@link JsonNumber#fromValue(BigDecimal)}). 291 * 292 * @param name the member name 293 * @param value the number 294 * @return this builder 295 * @throws NullPointerException if an argument is {@code null} 296 * @throws IllegalArgumentException if {@code value} is outside the caps of {@link JsonNumber}, or 297 * {@code name} contains an unpaired surrogate or is already present 298 * @since 1.0.0 299 */ 300 @NonNull 301 @CanIgnoreReturnValue 302 public Builder put(@NonNull String name, @NonNull BigDecimal value) { 303 return put(name, JsonNumber.fromValue(value)); 304 } 305 306 /** 307 * Adds a member whose value is a JSON boolean. 308 * 309 * @param name the member name 310 * @param value the boolean 311 * @return this builder 312 * @throws NullPointerException if an argument is {@code null} 313 * @throws IllegalArgumentException if {@code name} contains an unpaired surrogate or is already present 314 * @since 1.0.0 315 */ 316 @NonNull 317 @CanIgnoreReturnValue 318 public Builder put(@NonNull String name, @NonNull Boolean value) { 319 return put(name, JsonBoolean.fromValue(value)); 320 } 321 322 /** 323 * Adds a member whose value is the JSON {@code null}. 324 * 325 * @param name the member name 326 * @return this builder 327 * @throws NullPointerException if {@code name} is {@code null} 328 * @throws IllegalArgumentException if {@code name} contains an unpaired surrogate or is already present 329 * @since 1.0.0 330 */ 331 @NonNull 332 @CanIgnoreReturnValue 333 public Builder putNull(@NonNull String name) { 334 return put(name, JsonNull.defaultInstance()); 335 } 336 337 /** 338 * Returns an object holding the members added so far, in the order they were added. 339 * 340 * @return the JSON object; {@link JsonObject#emptyInstance()} if no member was added 341 * @since 1.0.0 342 */ 343 @NonNull 344 public JsonObject build() { 345 LinkedHashMap<@NonNull String, @NonNull JsonValue> snapshot = new LinkedHashMap<>(capacityFor( 346 this.members.size())); 347 snapshot.putAll(this.members); 348 return fromSnapshot(snapshot, this.deepestChild); 349 } 350 351 @Override 352 @NonNull 353 public String toString() { 354 return "JsonObject.Builder{members=<redacted>}"; 355 } 356 } 357}