summaryrefslogtreecommitdiff
path: root/src/bin/elua/core/util.lua
blob: b2730541776c0fa7a17703f01767a5fcde58f9ea (plain) (blame)
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
-- elua core utilities used in other modules

local ffi  = require("ffi")
local cast = ffi.cast
local new  = ffi.new
local copy = ffi.copy
local str  = ffi.string
local gc   = ffi.gc

local C = ffi.C

local M = {}

local getmetatable, setmetatable = getmetatable, setmetatable

M.Object = {
    __call = function(self, ...)
        local r = self:clone()
        if self.__ctor then return r, self.__ctor(r, ...) end
        return r
    end,

    clone = function(self, o)
        o = o or {}
        o.__index, o.__proto, o.__call = self, self, self.__call
        if not o.__tostring then
            o.__tostring = self.__tostring
        end
        setmetatable(o, o)
        return o
    end,

    is_a = function(self, base)
        if self == base then return true end
        local pt = self.__proto
        local is = (pt == base)
        while not is and pt do
            pt = pt.__proto
            is = (pt == base)
        end
        return is
    end,

    mixin = function(self, obj)
        for k, v in pairs(obj) do self[k] = v end
    end,

    __tostring = function(self)
        return ("Object: %s"):format(self.name or "unnamed")
    end
}

local newproxy = newproxy

M.Readonly_Object = M.Object:clone {}
M.Readonly_Object.__call = function(self, ...)
    local r = newproxy(true)
    local rmt = getmetatable(r)
    rmt.__index = self
    rmt.__tostring = self.__tostring
    rmt.__metatable = false
    if self.__ctor then return r, self.__ctor(r, rmt, ...) end
    return r
end

local loaded_libs = {}
local loaded_libc = {}

local load_lib_win = function(libname, ev)
    local succ, v
    if not ev or ev == "" then
        succ, v = pcall(ffi.load, libname)
        if not succ then
            succ, v = pcall(ffi.load, "lib" .. libname)
        end
    else
        succ, v = pcall(ffi.load, ev .. "\\" .. libname .. ".dll")
        if not succ then
            succ, v = pcall(ffi.load, ev .. "\\lib" .. libname .. ".dll")
        end
    end
    return succ, v
end

local load_lib = function(libname, ev)
    local succ, v
    if ffi.os == "Windows" then
        succ, v = load_lib_win(libname, ev)
    elseif not ev or ev == "" then
        succ, v = pcall(ffi.load, libname)
    else
        local ext = (ffi.os == "OSX") and ".dylib" or ".so"
        succ, v = pcall(ffi.load, ev .. "/lib" .. libname .. ext)
    end
    return succ, v
end

-- makes sure we only keep one handle for each lib
-- reference counted
M.lib_load = function(libname)
    local  lib = loaded_libs[libname]
    if not lib then
        local ev = os.getenv("ELUA_" .. libname:upper() .. "_LIBRARY_PATH")
        local succ, v = load_lib(libname, ev)
        if not succ then
            error(v, 2)
        end
        lib = v
        loaded_libs[libname] = lib
        loaded_libc[libname] = 0
    end
    loaded_libc[libname] = loaded_libc[libname] + 1
    return lib
end

M.lib_unload = function(libname)
    local  cnt = loaded_libc[libname]
    if not cnt then return end
    if cnt == 1 then
        loaded_libs[libname], loaded_libc[libname] = nil, nil
    else
        loaded_libc[libname] = cnt - 1
    end
end

-- string fmt

ffi.cdef [[
    typedef struct _Str_Buf {
        char  *buf;
        size_t len, cap;
    } Str_Buf;

    void *malloc(size_t);
    void    free(void*);
    size_t  strlen(const char *str);

    int isalnum(int c);
    int isdigit(int c);
]]

local fmt   = string.format
local pcall = pcall
local error = error
local type  = type
local tostr = tostring

local bytes = { ("cdeEfgGiopuxXsq"):byte(1, #("cdeEfgGiopuxXsq")) }
for i, v in ipairs(bytes) do bytes[v] = true end

local Str_Buf = ffi.metatype("Str_Buf", {
    __new = function(self)
        local r = new("Str_Buf")
        r.buf = C.malloc(8)
        r.len = 0
        r.cap = 8
        gc(r, self.free)
        return r
    end,
    __tostring = function(self)
        return str(self.buf, self.len)
    end,
    __index = {
        free = function(self)
            C.free(self.buf)
            self.buf = nil
            self.len = 0
            self.cap = 0
        end,
        clear = function(self)
            self.len = 0
        end,
        grow = function(self, newcap)
            local oldcap = self.cap
            if oldcap >= newcap then return end
            local buf = C.malloc(newcap)
            if self.len ~= 0   then copy(buf, self.buf, self.len) end
            if self.buf ~= nil then C.free(self.buf) end
            self.buf = buf
            self.cap = newcap
        end,
        append_char = function(self, c)
            local len = self.len
            self:grow (len + 1)
            self.buf  [len] = c
            self.len = len + 1
        end,
        append_str = function(self, str, strlen)
            if type(str) == "string" then strlen = strlen or #str end
            local strp = cast("const char*", str)
            strlen = strlen or C.strlen(strp)
            local len = self.len
            self:grow(len + strlen)
            for i = 0, strlen - 1 do
                self.buf[len + i] = strp[i]
            end
            self.len = len + strlen
        end
    }
})

local fmterr = function(idx, msg, off)
    local argerr = (type(idx) == "number")
        and ("#" .. idx)
         or ("'" .. idx .. "'")
    error("bad argument " .. argerr .. " to '%' (" .. msg .. ")",
        3 + (off or 0))
end

-- simulates lua's coercion
local checktype = function(c, idx, val)
    if c == 115 or c == 112 then -- s, p
        return val
    end
    local tv = type(val)
    if c == 113 then -- q
        if tv ~= "string" or tv ~= "number" then
            fmterr(idx, "string expected, got " .. tv, 1)
        end
        return val
    end
    if tv == "number" then return val end
    if tv == "string" then
        local v = tonumber(val)
        if v then return v end
    end
    fmterr(idx, "number expected, got " .. tv, 1)
end

getmetatable("").__mod = function(fmts, params)
    if not fmts then return nil end
    if type(params) ~= "table" then
        params = { params }
    end

    local buf, nbuf = Str_Buf(), Str_Buf()
    local s         = cast("const char*", fmts)
    local c, s      = s[0], s + 1
    local argn      = 1

    while c ~= 0 do
        if c == 37 then -- %
            c, s = s[0], s + 1
            if c ~= 37 then
                while c ~= 0 and C.isalnum(c) ~= 0 do
                    nbuf:append_char(c)
                    c, s = s[0], s + 1
                end
                if c == 36 then -- $
                    c, s = s[0], s + 1
                    local n = tostr(nbuf)
                    nbuf:clear()
                    while C.isdigit(c) ~= 0 or c == 45 or c == 46 do -- -, .
                        nbuf:append_char(c)
                        c, s = s[0], s + 1
                    end
                    if not bytes[c] then
                        buf:append_str(n)
                        buf:append_char(36) -- $
                        buf:append_char(c)
                    else
                        nbuf:append_char(c)
                        local idx = tonumber(n) or n
                        if type(idx) == "number" and idx > #params then
                            fmterr(idx, "no value")
                        end
                        local v = params[idx]
                        v = checktype(c, idx, v)
                        buf:append_str(("%" .. tostr(nbuf)):format(v))
                        nbuf:clear()
                    end
                else
                    local fmtmark = (nbuf.len > 0) and nbuf.buf[0] or nil
                    if not fmtmark then
                        while c ~= 0 and (C.isdigit(c) ~= 0 or c == 45
                        or c == 46) do
                            nbuf:append_char(c)
                            c, s = s[0], s + 1
                        end
                        if bytes[c] then fmtmark = c end
                    end
                    if fmtmark then
                        if argn > #params then
                            fmterr(argn, "no value")
                        end
                        local v = params[argn]
                        v = checktype(fmtmark, argn, v)
                        buf:append_str(("%" .. tostr(nbuf)):format(v))
                        nbuf:clear()
                        argn = argn + 1
                    else
                        buf:append_str(nbuf.buf, nbuf.len)
                        nbuf:clear()
                    end
                    if c ~= 0 then buf:append_char(c) end
                end
            else
                buf:append_char(c)
            end
        else
            buf:append_char(c)
        end
        c, s = s[0], s + 1
    end
    nbuf:free()
    local ret = tostr(buf)
    buf:free()
    return ret
end

-- file utils

M.find_file = function(fname, paths)
    for i, path in ipairs(paths) do
        local actual_path
        if path:match(".*/") then
            actual_path = path .. fname
        else
            actual_path = path .. "/" .. fname
        end
        local f = io.open(actual_path)
        if f then
            f:close()
            return actual_path
        end
    end
end

-- table utils

table.uniq = function(tbl)
    local ret  = {}
    local used = {}
    for i, v in ipairs(tbl) do
        if not used[v] then
            ret[#ret + 1], used[v] = v, true
        end
    end
    return ret
end

M.get_namespace = function(M, nspaces)
    local last_m = M
    for i, v in ipairs(nspaces) do
        local nsp = M[v]
        if not nsp then
            nsp = {}
            last_m[v] = nsp
        end
        last_m = nsp
    end
    return last_m
end

return M