diff --git a/index.ts b/index.ts index 04dd9b9..cac1639 100644 --- a/index.ts +++ b/index.ts @@ -1108,6 +1108,92 @@ export class JSONValue { assert(this.kind == JSONValueKind.OBJECT, 'JSON value is not an object.') return changetype>(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 | 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 | 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 '?' + } + } } /**