Last active
September 19, 2016 04:56
-
-
Save CheyiLin/230749b1937da27b3bf2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
The MIT License (MIT) | |
Copyright (c) Cheyi Lin <[email protected]> | |
]] | |
local bit_xor | |
if jit and jit.version_num > 20000 then | |
bit_xor = bit.bxor | |
else | |
bit_xor = bit32.bxor | |
end | |
-- XOR secret | |
local secret = 0x3e | |
local function crypt(s) | |
local s = s:gsub(".", function (c) return string.char(bit_xor(c:byte(), secret)) end) | |
return s | |
end | |
-- module xint | |
local xint = {} | |
function xint:new(n) | |
local o = setmetatable({}, self) | |
self.__index = self | |
self.__tostring = self.tostring | |
self.__metatable = false | |
o:set(n) | |
return o | |
end | |
function xint:set(n) | |
self.v = crypt(tostring(n)) | |
end | |
function xint:get() | |
return tonumber(crypt(self.v)) | |
end | |
function xint:tostring() | |
return crypt(self.v) | |
end | |
-- test | |
local function printf(fmt, ...) | |
io.write(string.format(fmt, ...)) | |
end | |
local function dump_hex(s) | |
printf("[%d] ", #s) | |
s:gsub(".", function (s) printf("%02x ", s:byte()) end) | |
printf("\n") | |
end | |
-- initial number | |
local n = 1001 | |
printf("n: %d (%s)\n", n, type(n)) | |
dump_hex(tostring(n)) | |
-- create xint object | |
local x = xint:new(n) | |
printf("x: %s (%s)\n", tostring(x), type(x)) | |
dump_hex(x.v) | |
-- get number from xint object | |
local xn = x:get() | |
printf("xn: %d (%s)\n", xn, type(xn)) | |
-- set number to xint object | |
x:set(xn + 100000) | |
printf("x: %s (%s)\n", tostring(x), type(x)) | |
dump_hex(x.v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: