优化json库的utf8转码逻辑

This commit is contained in:
MrZ626
2021-02-06 23:54:08 +08:00
parent 38fd971d5c
commit a8387de735

View File

@@ -332,17 +332,15 @@ do--json
local function codepoint_to_utf8(n) local function codepoint_to_utf8(n)
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
local f = math.floor local f = bit.rshift
if n <= 0x7f then if n <= 0x7f then
return char(n) return char(n)
elseif n <= 0x7ff then elseif n <= 0x7ff then
return char(f(n / 64) + 192, n % 64 + 128) return char(f(n, 6) + 192, n % 64 + 128)
elseif n <= 0xffff then elseif n <= 0xffff then
return char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, return char(f(n, 12) + 224, f(n % 4096, 6) + 128, n % 64 + 128)
n % 64 + 128)
elseif n <= 0x10ffff then elseif n <= 0x10ffff then
return char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128, return char(f(n, 18) + 240, f(n % 262144, 12) + 128, f(n % 4096, 6) + 128, n % 64 + 128)
f(n % 4096 / 64) + 128, n % 64 + 128)
end end
error(string.format("invalid unicode codepoint '%x'", n)) error(string.format("invalid unicode codepoint '%x'", n))
end end