-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProtocol.lua
More file actions
73 lines (63 loc) · 2.08 KB
/
Protocol.lua
File metadata and controls
73 lines (63 loc) · 2.08 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
local Protocol = {}
-- str = json string
Protocol.strencode = function(str)
if not str then return end
do return {string.byte(str, 1, #str)} end
local byteArray = {}
local offset = 1
for i=1,#str do
local charCode = string.byte(str, i)
local codes = nil
if charCode <= 0x7f then
codes = {charCode}
elseif charCode <= 0x7ff then
codes = {bit.bor(0xc0,bit.rshift(charCode,6)),bit.bor(0x80,bit.band(charCode,0x3f))}
console.log(codes, "Protocol.strencode")
else
codes = {bit.bor(0xe0,bit.rshift(charCode,12)),bit.rshift(bit.band(charCode,0xfc0),6),bit.bor(0x80,bit.band(charCode,0x3f))}
end
for j=1,#codes do
byteArray[offset] = codes[j]
offset = offset +1
end
end
return byteArray
-- return clone(byteArray)
end
Protocol.strdecode2 = function(bytes)
local array = {}
local charCode = 0
local offset = 1
while offset<=#bytes do
if bytes[offset] < 128 then
charCode = bytes[offset]
offset = offset + 1
elseif bytes[offset] < 224 then
charCode = bit.lshift(bit.band(bytes[offset],0x3f),6) + bit.band(bytes[offset+1],0x3f)
offset = offset + 2
else
charCode = bit.lshift(bit.band(bytes[offset],0x0f),12) + bit.lshift(bit.band(bytes[offset+1],0x3f),6) + bit.band(bytes[offset+2],0x3f)
offset = offset + 3
end
table.insert(array, charCode)
end
dump(array, #array)
return string.char(unpack(array))
-- local arr = {}
-- local len = #array
-- for i = 1, len do
-- arr[i] = string.char(array[i])
-- end
-- return table.concat(arr)
end
Protocol.strdecode = function(bytes)
local array = {}
local len = #bytes
for i = 1, len do
-- table.insert(array, string.char(bytes[i]))
array[i] = string.char(bytes[i]) -- 更快一些
end
return table.concat(array)
-- return string.char(unpack(bytes)) //爆栈
end
return Protocol