Skip to content
This repository was archived by the owner on Feb 23, 2023. It is now read-only.

Add JSON utils for returning kinds, valid utf8, and kinds to strings #116

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,92 @@ export class JSONValue {
assert(this.kind == JSONValueKind.OBJECT, 'JSON value is not an object.')
return changetype<TypedMap<string, JSONValue>>(this.data as u32)
}

/**
* Make sure the given JSONValue is a string and returns string it contains.
* Returns `null` or a blank string otherwise, depending on returnNull value.
*/
asStringOrNull(val: JSONValue | null, returnNull: boolean): string | null {
if (val != null && val.kind === JSONValueKind.STRING) {
return val.toString()
}
if (returnNull) {
return null
} else {
return ''
}
}

/**
* Makes sure the given JSONValue is an object and return the object it contains.
* Returns `null` otherwise.
*/
asObject(val: JSONValue | null): TypedMap<string, JSONValue> | null {
if (val != null && val.kind === JSONValueKind.OBJECT) {
return val.toObject()
}
return null
}

/**
* Make sure the given JSONValue is an array and returns that array it contains.
* Returns `null` otherwise.
*/
asArray(val: JSONValue | null): Array<JSONValue> | null {
if (val != null && val.kind === JSONValueKind.ARRAY) {
return val.toArray()
}
return null
}

/**
* This function checks if the given byte array contains a valid
* UTF-8 sequence and can be successfully parsed into a string.
*/
isValidUtf8(bytes: Bytes): boolean {
let pending = 0
for (let i = 0; i < bytes.length; i++) {
let b = bytes[i]
if (pending === 0) {
let m = 0b10000000
while ((m & b) !== 0) {
pending += 1
m = m >> 1
}
if (pending === 0) {
continue
}
if (pending === 1 || pending > 4) {
return false
}
} else {
if ((b & 0b11000000) !== 0b10000000) {
return false
}
}
pending -= 1
}
return pending === 0
}

kindToString(kind: JSONValueKind): string {
switch (kind) {
case JSONValueKind.ARRAY:
return 'ARRAY'
case JSONValueKind.OBJECT:
return 'OBJECT'
case JSONValueKind.STRING:
return 'STRING'
case JSONValueKind.NUMBER:
return 'NUMBER'
case JSONValueKind.BOOL:
return 'BOOL'
case JSONValueKind.NULL:
return 'NULL'
default:
return '?'
}
}
}

/**
Expand Down