@@ -1108,6 +1108,92 @@ export class JSONValue {
1108
1108
assert ( this . kind == JSONValueKind . OBJECT , 'JSON value is not an object.' )
1109
1109
return changetype < TypedMap < string , JSONValue > > ( this . data as u32 )
1110
1110
}
1111
+
1112
+ /**
1113
+ * Make sure the given JSONValue is a string and returns string it contains.
1114
+ * Returns `null` or a blank string otherwise, depending on returnNull value.
1115
+ */
1116
+ asStringOrNull ( val : JSONValue | null , returnNull : boolean ) : string | null {
1117
+ if ( val != null && val . kind === JSONValueKind . STRING ) {
1118
+ return val . toString ( )
1119
+ }
1120
+ if ( returnNull ) {
1121
+ return null
1122
+ } else {
1123
+ return ''
1124
+ }
1125
+ }
1126
+
1127
+ /**
1128
+ * Makes sure the given JSONValue is an object and return the object it contains.
1129
+ * Returns `null` otherwise.
1130
+ */
1131
+ asObject ( val : JSONValue | null ) : TypedMap < string , JSONValue > | null {
1132
+ if ( val != null && val . kind === JSONValueKind . OBJECT ) {
1133
+ return val . toObject ( )
1134
+ }
1135
+ return null
1136
+ }
1137
+
1138
+ /**
1139
+ * Make sure the given JSONValue is an array and returns that array it contains.
1140
+ * Returns `null` otherwise.
1141
+ */
1142
+ asArray ( val : JSONValue | null ) : Array < JSONValue > | null {
1143
+ if ( val != null && val . kind === JSONValueKind . ARRAY ) {
1144
+ return val . toArray ( )
1145
+ }
1146
+ return null
1147
+ }
1148
+
1149
+ /**
1150
+ * This function checks if the given byte array contains a valid
1151
+ * UTF-8 sequence and can be successfully parsed into a string.
1152
+ */
1153
+ isValidUtf8 ( bytes : Bytes ) : boolean {
1154
+ let pending = 0
1155
+ for ( let i = 0 ; i < bytes . length ; i ++ ) {
1156
+ let b = bytes [ i ]
1157
+ if ( pending === 0 ) {
1158
+ let m = 0b10000000
1159
+ while ( ( m & b ) !== 0 ) {
1160
+ pending += 1
1161
+ m = m >> 1
1162
+ }
1163
+ if ( pending === 0 ) {
1164
+ continue
1165
+ }
1166
+ if ( pending === 1 || pending > 4 ) {
1167
+ return false
1168
+ }
1169
+ } else {
1170
+ if ( ( b & 0b11000000 ) !== 0b10000000 ) {
1171
+ return false
1172
+ }
1173
+ }
1174
+ pending -= 1
1175
+ }
1176
+ return pending === 0
1177
+ }
1178
+
1179
+ kindToString ( kind : JSONValueKind ) : string {
1180
+ switch ( kind ) {
1181
+ case JSONValueKind . ARRAY :
1182
+ return 'ARRAY'
1183
+ case JSONValueKind . OBJECT :
1184
+ return 'OBJECT'
1185
+ case JSONValueKind . STRING :
1186
+ return 'STRING'
1187
+ case JSONValueKind . NUMBER :
1188
+ return 'NUMBER'
1189
+ case JSONValueKind . BOOL :
1190
+ return 'BOOL'
1191
+ case JSONValueKind . NULL :
1192
+ return 'NULL'
1193
+ default :
1194
+ return '?'
1195
+ }
1196
+ }
1111
1197
}
1112
1198
1113
1199
/**
0 commit comments