decoder: fixes 5.2-strict mode state object
[luajson.git] / tests / utf8_processor.lua
blobf49e15beaced675286bed7a448836f1061b9a1d1
1 local lpeg = require("lpeg")
3 local string = string
5 module("utf8_processor")
7 local function encode_utf(codepoint)
8 if codepoint > 0x10FFFF then
9 error("Codepoint > 10FFFF cannot be encoded")
10 elseif codepoint > 0xFFFF then
11 -- Surrogate pair needed
12 codepoint = codepoint - 0x10000
13 local first, second = codepoint / 0x0400 + 0xD800, codepoint % 0x0400 + 0xDC00
14 return ("\\u%.4X\\u%.4X"):format(first, second)
15 else
16 return ("\\u%.4X"):format(codepoint)
17 end
18 end
20 -- decode a two-byte UTF-8 sequence
21 local function f2 (s)
22 local c1, c2 = string.byte(s, 1, 2)
23 return encode_utf(c1 * 64 + c2 - 12416)
24 end
26 -- decode a three-byte UTF-8 sequence
27 local function f3 (s)
28 local c1, c2, c3 = string.byte(s, 1, 3)
29 return encode_utf((c1 * 64 + c2) * 64 + c3 - 925824)
30 end
32 -- decode a four-byte UTF-8 sequence
33 local function f4 (s)
34 local c1, c2, c3, c4 = string.byte(s, 1, 4)
35 return encode_utf(((c1 * 64 + c2) * 64 + c3) * 64 + c4 - 63447168)
36 end
38 local cont = lpeg.R("\128\191") -- continuation byte
40 local utf8 = lpeg.R("\0\127") -- Do nothing here
41 + lpeg.R("\194\223") * cont / f2
42 + lpeg.R("\224\239") * cont * cont / f3
43 + lpeg.R("\240\244") * cont * cont * cont / f4
45 local utf8_decode_pattern = lpeg.Cs(utf8^0) * -1
48 function process(s)
49 return utf8_decode_pattern:match(s)
50 end