util.dbuffer: dynamic string buffer
Similar to util.ringbuffer (and shares almost identical API). Differences:
- size limit is optional and dynamic
- does not allocate a fixed buffer of max_size bytes
- focus on simply storing references to existing string objects where possible,
avoiding unnecessary allocations
- references are still stored in a ring buffer to enable use as a fast FIFO
Optional second parameter to new() provides the number of ring buffer segments. On
Lua 5.2 on my laptop, a segment is ~19 bytes. If the ring buffer fills up, the next
write will compact all strings into a single item.
-- Prosody IM
-- Copyright (C) 2008-2017 Matthew Wild
-- Copyright (C) 2008-2017 Waqas Hussain
-- Copyright (C) 2008-2017 Kim Alvefur
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local s_gsub = string.gsub;
local random_bytes = require "util.random".bytes;
local base64_encode = require "util.encodings".base64.encode;
local b64url = { ["+"] = "-", ["/"] = "_", ["="] = "" };
local function b64url_random(len)
return (s_gsub(base64_encode(random_bytes(len)), "[+/=]", b64url));
end
return {
short = function () return b64url_random(6); end;
medium = function () return b64url_random(12); end;
long = function () return b64url_random(24); end;
custom = function (size)
return function () return b64url_random(size); end;
end;
}