forked from Wiladams/LAPHLibs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemutils.lua
More file actions
133 lines (101 loc) · 2.1 KB
/
memutils.lua
File metadata and controls
133 lines (101 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
local ffi = require "ffi"
local bit = require "bit"
local band = bit.band
local bor = bit.bor
local rshift = bit.rshift
local lshift = bit.lshift
ffi.cdef[[
void * malloc ( size_t size );
void free ( void * ptr );
void * realloc ( void * ptr, size_t size );
]]
local function bzero(dest, nbytes)
ffi.fill(dest, nbytes)
return dest
end
local function bcopy(src, dest, nbytes)
ffi.copy(dest, src, nbytes)
end
local function bcmp(ptr1, ptr2, nbytes)
for i=0,nbytes do
if ptr1[i] ~= ptr2[i] then return -1 end
end
return 0
end
local function memset(dest, c, len)
ffi.fill(dest, len, c)
return dest
end
local function memcpy(dest, src, nbytes)
ffi.copy(dest, src, nbytes)
end
local function memcmp(ptr1, ptr2, nbytes)
local p1 = ffi.cast("const uint8_t *", ptr1)
local p2 = ffi.cast("const uint8_t *", ptr2)
for i=0,nbytes do
if p1[i] ~= p2[i] then return -1 end
end
return 0
end
local function memchr(ptr, value, num)
local p = ffi.cast("const uint8_t *", ptr)
for i=0,num-1 do
if p[i] == value then return p+i end
end
return nil
end
local function memmove(dst, src, num)
local srcptr = ffi.cast("const uint8_t*", src)
-- If equal, just return
if dst == srcptr then return dst end
if srcptr < dst then
-- copy from end
for i=num-1,0, -1 do
dst[i] = srcptr[i];
end
else
-- copy from beginning
for i=0,num-1 do
dst[i] = srcptr[i];
end
end
return dst
end
local function memreverse(buff, bufflen)
local i = 0;
local tmp
while (i < (bufflen)/2) do
tmp = buff[i];
buff[i] = buff[bufflen-i-1];
buff[bufflen-i-1] = tmp;
i = i + 1;
end
return buff
end
local function getreverse(src, len)
if not len then
if type(src) == "string" then
len = #src
else
return nil, "unknown length"
end
end
local srcptr = ffi.cast("const uint8_t *", src);
local dst = ffi.new("uint8_t[?]", len)
for i = 0, len-1 do
dst[i] = srcptr[len-1-i];
end
return dst, len
end
return {
bcmp = bcmp,
bcopy = bcopy,
bzero = bzero,
memset = memset,
memcpy = memcpy,
memcmp = memcmp,
memchr = memchr,
memmove = memmove,
memreverse = memreverse,
getreverse = getreverse,
}