Skip to content

Commit

Permalink
optimization: using cdata instead lua table for generating masked pay…
Browse files Browse the repository at this point in the history
…load (#49)
  • Loading branch information
Gerrard-YNWA committed Aug 26, 2020
1 parent cdb16f2 commit f5ed6c4
Showing 1 changed file with 31 additions and 14 deletions.
45 changes: 31 additions & 14 deletions lib/resty/websocket/protocol.lua
Expand Up @@ -2,6 +2,7 @@


local bit = require "bit"
local ffi = require "ffi"


local byte = string.byte
Expand All @@ -15,12 +16,13 @@ local rshift = bit.rshift
--local tohex = bit.tohex
local tostring = tostring
local concat = table.concat
local str_char = string.char
local rand = math.random
local type = type
local debug = ngx.config.debug
local ngx_log = ngx.log
local ngx_DEBUG = ngx.DEBUG
local ffi_new = ffi.new
local ffi_string = ffi.string


local ok, new_tab = pcall(require, "table.new")
Expand All @@ -44,6 +46,22 @@ local types = {
[0xa] = "pong",
}

local str_buf_size = 4096
local str_buf
local c_buf_type = ffi.typeof("char[?]")


local function get_string_buf(size)
if size > str_buf_size then
return ffi_new(c_buf_type, size)
end
if not str_buf then
str_buf = ffi_new(c_buf_type, str_buf_size)
end

return str_buf
end


function _M.recv_frame(sock, max_payload_len, force_masking)
local data, err = sock:receive(2)
Expand Down Expand Up @@ -175,13 +193,12 @@ function _M.recv_frame(sock, max_payload_len, force_masking)

if payload_len > 2 then
-- TODO string.buffer optimizations
local bytes = new_tab(payload_len - 2, 0)
local bytes = get_string_buf(payload_len - 2)
for i = 3, payload_len do
bytes[i - 2] = str_char(bxor(byte(data, 4 + i),
byte(data,
(i - 1) % 4 + 1)))
bytes[i - 3] = bxor(byte(data, 4 + i),
byte(data, (i - 1) % 4 + 1))
end
msg = concat(bytes)
msg = ffi_string(bytes, payload_len - 2)

else
msg = ""
Expand Down Expand Up @@ -211,12 +228,12 @@ function _M.recv_frame(sock, max_payload_len, force_masking)
local msg
if mask then
-- TODO string.buffer optimizations
local bytes = new_tab(payload_len, 0)
local bytes = get_string_buf(payload_len)
for i = 1, payload_len do
bytes[i] = str_char(bxor(byte(data, 4 + i),
byte(data, (i - 1) % 4 + 1)))
bytes[i - 1] = bxor(byte(data, 4 + i),
byte(data, (i - 1) % 4 + 1))
end
msg = concat(bytes)
msg = ffi_string(bytes, payload_len)

else
msg = data
Expand Down Expand Up @@ -269,12 +286,12 @@ local function build_frame(fin, opcode, payload_len, payload, masking)
band(key, 0xff))

-- TODO string.buffer optimizations
local bytes = new_tab(payload_len, 0)
local bytes = get_string_buf(payload_len)
for i = 1, payload_len do
bytes[i] = str_char(bxor(byte(payload, i),
byte(masking_key, (i - 1) % 4 + 1)))
bytes[i - 1] = bxor(byte(payload, i),
byte(masking_key, (i - 1) % 4 + 1))
end
payload = concat(bytes)
payload = ffi_string(bytes, payload_len)

else
masking_key = ""
Expand Down

0 comments on commit f5ed6c4

Please sign in to comment.