scoop:scoop.json:0.1.0
src/value.scoop
Selected production source · src/value.scoop
1
package scoop.json3
import scoop.collections.Map4
import scoop.collections.LinkedHashMap6
/**7
* An immutable JSON value tree. Accessors check the JSON kind without coercion, collection8
* snapshots preserve order, and the codec preserves exact JSON number tokens.9
*/10
public class JsonValue internal constructor(internal val node: JsonNode) {11
/** The JSON kind of this value. */12
public val kind: JsonValueKind get() =13
when (node) {14
case JsonNode.Null -> JsonValueKind.Null15
case JsonNode.BooleanValue(_) -> JsonValueKind.Boolean16
case JsonNode.Number(_) -> JsonValueKind.Number17
case JsonNode.Text(_) -> JsonValueKind.String18
case JsonNode.Record(_) -> JsonValueKind.Object19
case JsonNode.Sequence(_) -> JsonValueKind.Array20
}22
/** Object member or array element count; other kinds throw DecodingException. */23
public val size: Long get() =24
when (node) {25
case JsonNode.Record(val members) -> members.size26
case JsonNode.Sequence(val elements) -> elements.size27
else -> throw DecodingException("", "expected an object or array")28
}30
/** Reads a Boolean, rejecting every other JSON kind. */31
public fun asBoolean(): Boolean = JsonDecoder(node, "").readBoolean()32
/** Reads a String, rejecting every other JSON kind. */33
public fun asString(): String = JsonDecoder(node, "").readString()34
/** Reads an exact Long; fractions, exponents, and out-of-range integers fail. */35
public fun asLong(): Long = JsonDecoder(node, "").readLong()36
/** Reads an exactly integral Long, allowing decimal and exponent spellings without rounding. */37
public fun asIntegralLong(): Long = readJsonIntegralLong(asNumberToken())38
/** Reads an exact ULong; signs, fractions, exponents, and overflow are checked. */39
public fun asULong(): ULong = JsonDecoder(node, "").readULong()40
/** Rounds a JSON number directly to Float, rejecting overflow. */41
public fun asFloat(): Float = JsonDecoder(node, "").readFloat()42
/** Rounds a JSON number directly to Double, rejecting overflow. */43
public fun asDouble(): Double = JsonDecoder(node, "").readDouble()44
/** Returns the original number token without imposing a machine-number range. */45
public fun asNumberToken(): String =46
when (node) {47
case JsonNode.Number(val text) -> text48
else -> throw DecodingException("", "expected a number")49
}51
private fun objectMembers(): Map<String, JsonNode> =52
when (node) {53
case JsonNode.Record(val members) -> members54
else -> throw DecodingException("", "expected an object")55
}57
private fun arrayElements(): ArrayList<JsonNode> =58
when (node) {59
case JsonNode.Sequence(val elements) -> elements60
else -> throw DecodingException("", "expected an array")61
}63
/** Looks up a field by name. A present JSON null is returned as Some(JsonValue). */64
public operator fun get(name: String): JsonValue? =65
when (val node = objectMembers()[name]) {66
case Some(val value) -> Some(JsonValue(value))67
case None -> None68
}70
/** Tests object membership by name. Other kinds throw DecodingException. */71
public fun containsKey(name: String): Boolean = objectMembers().containsKey(name)73
/** Reads an array element in constant time; invalid indices throw IndexOutOfBoundsException. */74
public operator fun get(index: Long): JsonValue = JsonValue(arrayElements()[index])76
/** Returns an independent array of object keys in stored order, in linear time. */77
public fun keys(): Array<String> {78
val result = ArrayList<String>()79
for (member in objectMembers()) {80
result.add(member.key)81
}82
return result.toArray()83
}85
/** Returns an independent member array in stored order, sharing immutable child nodes. */86
public fun members(): Array<(String, JsonValue)> {87
val result = ArrayList<(String, JsonValue)>()88
for (member in objectMembers()) {89
result.add((member.key, JsonValue(member.value)))90
}91
return result.toArray()92
}94
/** Returns an independent element array in index order, sharing immutable child nodes. */95
public fun elements(): Array<JsonValue> {96
val result = ArrayList<JsonValue>()97
for (element in arrayElements()) {98
result.add(JsonValue(element))99
}100
return result.toArray()101
}103
/**104
* The codec for embedding an opaque [JsonValue] in a JSON document.105
*/106
public companion object: ValueEncoder<JsonValue>, ValueDecoder<JsonValue> {107
/** Creates the JSON null value. */108
public fun nullValue(): JsonValue = JsonValue(JsonNode.Null)109
/** Creates a JSON Boolean. */110
public fun fromBoolean(value: Boolean): JsonValue = JsonValue(JsonNode.BooleanValue(value))111
/** Creates a JSON String without interpreting it as JSON source. */112
public fun fromString(value: String): JsonValue = JsonValue(JsonNode.Text(value))113
/** Creates an exact signed integer value. */114
public fun fromLong(value: Long): JsonValue = JsonValue(JsonNode.Number(value.toString()))115
/** Creates an exact unsigned integer value. */116
public fun fromULong(value: ULong): JsonValue = JsonValue(JsonNode.Number(value.toString()))117
/** Creates a finite Float value, preserving negative zero; non-finite values fail. */118
public fun fromFloat(value: Float): JsonValue = Json.encodeToValue(value)119
/** Creates a finite Double value, preserving negative zero; non-finite values fail. */120
public fun fromDouble(value: Double): JsonValue = Json.encodeToValue(value)122
/** Accepts exactly one JSON number token without whitespace, preserving its spelling. */123
public fun fromNumberToken(text: String): JsonValue {124
val parser = JsonParser(text)125
val token = readJsonNumber(parser, "")126
if (parser.peek() != None) {127
throw parser.error("", "unexpected input after the number")128
}129
return JsonValue(JsonNode.Number(token))130
}132
/** Copies the element sequence while sharing immutable child nodes. */133
public fun fromArray(elements: List<JsonValue>): JsonValue {134
val nodes = ArrayList<JsonNode>()135
for (element in elements) {136
nodes.add(element.node)137
}138
return JsonValue(JsonNode.Sequence(nodes))139
}141
/** Copies members in input order; duplicate names throw EncodingException. */142
public fun fromObject(members: List<(String, JsonValue)>): JsonValue {143
val objectMembers = LinkedHashMap<String, JsonNode>()144
for ((name, value) in members) {145
addJsonMember(objectMembers, name, value)146
}147
return JsonValue(JsonNode.Record(objectMembers))148
}150
/**151
* Copies the stored JSON tree into a JSON encoder. Other encoder implementations produce152
* [EncodingException].153
*/154
public override fun encode(value: JsonValue, encoder: Encoder) {155
if (encoder !is JsonEncoder) {156
throw EncodingException(encoder.path, "JsonValue requires a JSON encoder")157
}158
encodeJsonNode(value.node, encoder)159
}161
/**162
* Retains the current subtree of a JSON decoder. Other decoder implementations produce163
* [DecodingException].164
*/165
public override fun decode(decoder: Decoder): JsonValue {166
if (decoder !is JsonDecoder) {167
throw DecodingException(decoder.path, "JsonValue requires a JSON decoder")168
}169
return JsonValue(decoder.value)170
}171
}172
}174
internal fun encodeJsonNode(node: JsonNode, encoder: JsonEncoder) {175
when (node) {176
case JsonNode.Null -> encoder.singleValue().writeNull()177
case JsonNode.BooleanValue(val value) -> encoder.singleValue().writeBoolean(value)178
case JsonNode.Text(val text) -> encoder.singleValue().writeString(text)179
case JsonNode.Number(val text) -> {180
encoder.singleValue()181
encoder.writeNumberToken(text)182
}183
case JsonNode.Record(val members) -> {184
val fields = encoder.keyed()185
for (member in members) {186
encodeJsonNode(member.value, fields.field(member.key) as JsonEncoder)187
}188
fields.end()189
}190
case JsonNode.Sequence(val elements) -> {191
val sequence = encoder.unkeyed()192
for (element in elements) {193
encodeJsonNode(element, sequence.element() as JsonEncoder)194
}195
sequence.end()196
}197
}198
}