sorcery  str.lua at [9278734b41]

File lib/str.lua artifact e883d78392 part of check-in 9278734b41


local sanitable = {
	['\xfe'] = '\xf0';
	['\1'] = '\xf1';
	['\2'] = '\xf2';
	['\3'] = '\xf3';

	['\xf0'] = '\xfe';
	['\xf1'] = '\1';
	['\xf2'] = '\2';
	['\xf3'] = '\3';
}
return {
	capitalize = function(str)
		return string.upper(string.sub(str, 1,1)) .. string.sub(str, 2)
	end;

	rand = function(min,max)
		if not min then min = 16  end
		if not max then max = min end
		local str = ''
		local r_int   =            0x39 - 0x30
		local r_upper = r_int   + (0x5a - 0x41)
		local r_lower = r_upper + (0x7a - 0x61)
		for i = 1,math.random(max - min) + min do
			-- 0x30 -- 0x39
			-- 0x41 -- 0x5A
			-- 0x61 -- 0x71
			local codepoint = math.random(r_lower)
			if codepoint > r_upper then
				codepoint = (codepoint - r_upper) + 0x61
			elseif codepoint > r_int then
				codepoint = (codepoint - r_int) + 0x41
			else
				codepoint = codepoint + 0x30
			end
			str = str .. string.char(codepoint)
		end
		return str
	end;

	chop = function(str)
		if string.sub(str, 1,1) == ' ' then
			str = string.sub(str, 2)
		end
		if string.sub(str, #str,#str) == ' ' then
			str = string.sub(str, 1, #str - 1)
		end
		return str
	end;

	meta_armor = function(str,mark_struct)
		-- binary values stored in metadata need to be sanitized so
		-- they don't contain values that will disrupt parsing of the
		-- KV store, as minetest (stupidly) uses in-band signalling
		local sanitized = string.gsub(str, '[\xfe\1\2\3]', function(char)
			return '\xfe' .. sanitable[char]
		end)
		if sanitized ~= str and mark_struct then
			-- use different type code to mark struct headers for
			-- back-compat
			return string.gsub(sanitized,'^\xfe\xf0\x99','\xfe\x98')
		else return sanitized end
	end;
	meta_dearmor = function(str,cond)
		local dearmor = function(s)
			return string.gsub(s, '\xfe([\xf0\xf1\xf2\xf3])', function(char)
				return sanitable[char]
			end)
		end
		if cond then
			if string.sub(str,1,2) == '\xfe\x98' then
				return dearmor(string.gsub(str,'^\xfe\x98','\xfe\xf0\x99'))
			else return str end
		else return dearmor(str) end
	end;
}