Comparison

net/websocket/frames.lua @ 6899:5f3da8b00b9b

net.websocket.frames: Use struct packing in Lua 5.3 or struct lib if available
author Kim Alvefur <zash@zash.se>
date Tue, 06 Oct 2015 18:05:27 +0200
parent 6898:d01254d5a825
child 6900:44a7e9152b9a
comparison
equal deleted inserted replaced
6898:d01254d5a825 6899:5f3da8b00b9b
20 20
21 local t_concat = table.concat; 21 local t_concat = table.concat;
22 local s_byte = string.byte; 22 local s_byte = string.byte;
23 local s_char= string.char; 23 local s_char= string.char;
24 local s_sub = string.sub; 24 local s_sub = string.sub;
25 local s_pack = string.pack;
26 local s_unpack = string.unpack;
27
28 if not s_pack and softreq"struct" then
29 s_pack = softreq"struct".pack;
30 s_unpack = softreq"struct".unpack;
31 end
25 32
26 local function read_uint16be(str, pos) 33 local function read_uint16be(str, pos)
27 local l1, l2 = s_byte(str, pos, pos+1); 34 local l1, l2 = s_byte(str, pos, pos+1);
28 return l1*256 + l2; 35 return l1*256 + l2;
29 end 36 end
42 end 49 end
43 local function pack_uint64be(x) 50 local function pack_uint64be(x)
44 local h = band(x / 2^32, 2^32-1); 51 local h = band(x / 2^32, 2^32-1);
45 return s_char(get_byte(h, 24), get_byte(h, 16), get_byte(h, 8), band(h, 0xFF)); 52 return s_char(get_byte(h, 24), get_byte(h, 16), get_byte(h, 8), band(h, 0xFF));
46 get_byte(x, 24), get_byte(x, 16), get_byte(x, 8), band(x, 0xFF); 53 get_byte(x, 24), get_byte(x, 16), get_byte(x, 8), band(x, 0xFF);
54 end
55
56 if s_pack then
57 function pack_uint16be(x)
58 return s_pack(">I2", x);
59 end
60 function pack_uint64be(x)
61 return s_pack(">I8", x);
62 end
63 end
64
65 if s_unpack then
66 function read_uint16be(str, pos)
67 return s_unpack(">I2", str, pos);
68 end
69 function read_uint64be(str, pos)
70 return s_unpack(">I8", str, pos);
71 end
47 end 72 end
48 73
49 local function parse_frame_header(frame) 74 local function parse_frame_header(frame)
50 if #frame < 2 then return; end 75 if #frame < 2 then return; end
51 76