forked from rxi/json.lua
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.lua
More file actions
Latest commit
388 lines (325 loc) · 9.41 KB
/
Copy pathjson.lua
File metadata and controls
388 lines (325 loc) · 9.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
--
-- json.lua
--
-- Copyright (c) 2020 rxi
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do
-- so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
localjson= { _version="0.1.2" }
-------------------------------------------------------------------------------
-- Encode
-------------------------------------------------------------------------------
localencode
localescape_char_map= {
[ "\\" ] ="\\",
[ "\"" ] ="\"",
[ "\b" ] ="b",
[ "\f" ] ="f",
[ "\n" ] ="n",
[ "\r" ] ="r",
[ "\t" ] ="t",
}
localescape_char_map_inv= { [ "/" ] ="/" }
fork, vinpairs(escape_char_map) do
escape_char_map_inv[v] =k
end
localfunctionescape_char(c)
return"\\" .. (escape_char_map[c] orstring.format("u%04x", c:byte()))
end
localfunctionencode_nil(val)
return"null"
end
localfunctionencode_table(val, stack)
localres= {}
stack=stackor {}
-- Circular reference?
ifstack[val] thenerror("circular reference") end
stack[val] =true
ifrawget(val, 1) ~=nilornext(val) ==nilthen
-- Treat as array -- check keys are valid and it is not sparse
localn=0
forkinpairs(val) do
iftype(k) ~="number" then
error("invalid table: mixed or invalid key types")
end
n=n+1
end
ifn~=#valthen
error("invalid table: sparse array")
end
-- Encode
fori, vinipairs(val) do
table.insert(res, encode(v, stack))
end
stack[val] =nil
return"[" ..table.concat(res, ",") .."]"
else
-- Treat as an object
fork, vinpairs(val) do
iftype(k) ~="string" then
error("invalid table: mixed or invalid key types")
end
table.insert(res, encode(k, stack) ..":" ..encode(v, stack))
end
stack[val] =nil
return"{" ..table.concat(res, ",") .."}"
end
end
localfunctionencode_string(val)
return'"' ..val:gsub('[%z\1-\31\\"]', escape_char) ..'"'
end
localfunctionencode_number(val)
-- Check for NaN, -inf and inf
ifval~=valorval<=-math.hugeorval>=math.hugethen
error("unexpected number value '" ..tostring(val) .."'")
end
returnstring.format("%.14g", val)
end
localtype_func_map= {
[ "nil" ] =encode_nil,
[ "table" ] =encode_table,
[ "string" ] =encode_string,
[ "number" ] =encode_number,
[ "boolean" ] =tostring,
}
encode=function(val, stack)
localt=type(val)
localf=type_func_map[t]
iffthen
returnf(val, stack)
end
error("unexpected type '" ..t.."'")
end
functionjson.encode(val)
return ( encode(val) )
end
-------------------------------------------------------------------------------
-- Decode
-------------------------------------------------------------------------------
localparse
localfunctioncreate_set(...)
localres= {}
fori=1, select("#", ...) do
res[ select(i, ...) ] =true
end
returnres
end
localspace_chars=create_set("", "\t", "\r", "\n")
localdelim_chars=create_set("", "\t", "\r", "\n", "]", "}", ",")
localescape_chars=create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
localliterals=create_set("true", "false", "null")
localliteral_map= {
[ "true" ] =true,
[ "false" ] =false,
[ "null" ] =nil,
}
localfunctionnext_char(str, idx, set, negate)
fori=idx, #strdo
ifset[str:sub(i, i)] ~=negatethen
returni
end
end
return#str+1
end
localfunctiondecode_error(str, idx, msg)
localline_count=1
localcol_count=1
fori=1, idx-1do
col_count=col_count+1
ifstr:sub(i, i) =="\n" then
line_count=line_count+1
col_count=1
end
end
error( string.format("%s at line %d col %d", msg, line_count, col_count) )
end
localfunctioncodepoint_to_utf8(n)
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
localf=math.floor
ifn<=0x7fthen
returnstring.char(n)
elseifn<=0x7ffthen
returnstring.char(f(n/64) +192, n%64+128)
elseifn<=0xffffthen
returnstring.char(f(n/4096) +224, f(n%4096/64) +128, n%64+128)
elseifn<=0x10ffffthen
returnstring.char(f(n/262144) +240, f(n%262144/4096) +128,
f(n%4096/64) +128, n%64+128)
end
error( string.format("invalid unicode codepoint '%x'", n) )
end
localfunctionparse_unicode_escape(s)
localn1=tonumber( s:sub(1, 4), 16 )
localn2=tonumber( s:sub(7, 10), 16 )
-- Surrogate pair?
ifn2then
returncodepoint_to_utf8((n1-0xd800) *0x400+ (n2-0xdc00) +0x10000)
else
returncodepoint_to_utf8(n1)
end
end
localfunctionparse_string(str, i)
localres=""
localj=i+1
localk=j
whilej<=#strdo
localx=str:byte(j)
ifx<32then
decode_error(str, j, "control character in string")
elseifx==92then-- `\`: Escape
res=res..str:sub(k, j-1)
j=j+1
localc=str:sub(j, j)
ifc=="u" then
localhex=str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j+1)
orstr:match("^%x%x%x%x", j+1)
ordecode_error(str, j-1, "invalid unicode escape in string")
res=res..parse_unicode_escape(hex)
j=j+#hex
else
ifnotescape_chars[c] then
decode_error(str, j-1, "invalid escape char '" ..c.."' in string")
end
res=res..escape_char_map_inv[c]
end
k=j+1
elseifx==34then-- `"`: End of string
res=res..str:sub(k, j-1)
returnres, j+1
end
j=j+1
end
decode_error(str, i, "expected closing quote for string")
end
localfunctionparse_number(str, i)
localx=next_char(str, i, delim_chars)
locals=str:sub(i, x-1)
localn=tonumber(s)
ifnotnthen
decode_error(str, i, "invalid number '" ..s.."'")
end
returnn, x
end
localfunctionparse_literal(str, i)
localx=next_char(str, i, delim_chars)
localword=str:sub(i, x-1)
ifnotliterals[word] then
decode_error(str, i, "invalid literal '" ..word.."'")
end
returnliteral_map[word], x
end
localfunctionparse_array(str, i)
localres= {}
localn=1
i=i+1
while1do
localx
i=next_char(str, i, space_chars, true)
-- Empty / end of array?
ifstr:sub(i, i) =="]" then
i=i+1
break
end
-- Read token
x, i=parse(str, i)
res[n] =x
n=n+1
-- Next token
i=next_char(str, i, space_chars, true)
localchr=str:sub(i, i)
i=i+1
ifchr=="]" thenbreakend
ifchr~="," thendecode_error(str, i, "expected ']' or ','") end
end
returnres, i
end
localfunctionparse_object(str, i)
localres= {}
i=i+1
while1do
localkey, val
i=next_char(str, i, space_chars, true)
-- Empty / end of object?
ifstr:sub(i, i) =="}" then
i=i+1
break
end
-- Read key
ifstr:sub(i, i) ~='"' then
decode_error(str, i, "expected string for key")
end
key, i=parse(str, i)
-- Read ':' delimiter
i=next_char(str, i, space_chars, true)
ifstr:sub(i, i) ~=":" then
decode_error(str, i, "expected ':' after key")
end
i=next_char(str, i+1, space_chars, true)
-- Read value
val, i=parse(str, i)
-- Set
res[key] =val
-- Next token
i=next_char(str, i, space_chars, true)
localchr=str:sub(i, i)
i=i+1
ifchr=="}" thenbreakend
ifchr~="," thendecode_error(str, i, "expected '}' or ','") end
end
returnres, i
end
localchar_func_map= {
[ '"' ] =parse_string,
[ "0" ] =parse_number,
[ "1" ] =parse_number,
[ "2" ] =parse_number,
[ "3" ] =parse_number,
[ "4" ] =parse_number,
[ "5" ] =parse_number,
[ "6" ] =parse_number,
[ "7" ] =parse_number,
[ "8" ] =parse_number,
[ "9" ] =parse_number,
[ "-" ] =parse_number,
[ "t" ] =parse_literal,
[ "f" ] =parse_literal,
[ "n" ] =parse_literal,
[ "[" ] =parse_array,
[ "{" ] =parse_object,
}
parse=function(str, idx)
localchr=str:sub(idx, idx)
localf=char_func_map[chr]
iffthen
returnf(str, idx)
end
decode_error(str, idx, "unexpected character '" ..chr.."'")
end
functionjson.decode(str)
iftype(str) ~="string" then
error("expected argument of type string, got " ..type(str))
end
localres, idx=parse(str, next_char(str, 1, space_chars, true))
idx=next_char(str, idx, space_chars, true)
ifidx<=#strthen
decode_error(str, idx, "trailing garbage")
end
returnres
end
returnjson