scoop:scoop.json:0.1.0
src/builders.scoop
Selected production source · src/builders.scoop
1
package scoop.json3
import scoop.collections.LinkedHashMap4
import scoop.collections.toMap6
/** Runs configure once and publishes an array snapshot sharing immutable child values. */7
public fun jsonArray(configure: JsonArrayBuilder.() -> Unit = {}): JsonValue {8
val builder = JsonArrayBuilder()9
builder.configure()10
return builder.snapshot()11
}13
/** Runs configure once and publishes an object snapshot in insertion order. */14
public fun jsonObject(configure: JsonObjectBuilder.() -> Unit = {}): JsonValue {15
val builder = JsonObjectBuilder()16
builder.configure()17
return builder.snapshot()18
}20
/** Collects array elements for jsonArray without exposing mutable JSON nodes. */21
public class JsonArrayBuilder internal constructor() {22
private val elements: ArrayList<JsonNode> = ArrayList<JsonNode>()24
/** Appends one immutable child value in insertion order. */25
public fun add(value: JsonValue): Unit {26
elements.add(value.node)27
}29
/** Copies the sequence structure in linear time, sharing immutable child nodes. */30
internal fun snapshot(): JsonValue {31
val snapshot = ArrayList<JsonNode>()32
for (element in elements) {33
snapshot.add(element)34
}35
return JsonValue(JsonNode.Sequence(snapshot))36
}37
}39
/** Collects object members for jsonObject, rejecting duplicates without replacing values. */40
public class JsonObjectBuilder internal constructor() {41
private val members: LinkedHashMap<String, JsonNode> = LinkedHashMap<String, JsonNode>()43
/** Adds one member; duplicate names throw EncodingException and preserve existing members. */44
public fun add(name: String, value: JsonValue): Unit {45
addJsonMember(members, name, value)46
}48
/** Copies the member structure in linear time, sharing immutable child nodes. */49
internal fun snapshot(): JsonValue = JsonValue(JsonNode.Record(members.toMap()))50
}52
internal fun addJsonMember(members: LinkedHashMap<String, JsonNode>, name: String, value: JsonValue) {53
if (members.containsKey(name)) {54
throw EncodingException(childPath("", name), "duplicate object key")55
}56
members.put(name, value.node)57
}