5 Several common useful Lua functions
11 Copyright 2008 Steven Barth <steven@midlink.org>
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
17 http://www.apache.org/licenses/LICENSE-2.0
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
27 local io = require "io"
28 local math = require "math"
29 local table = require "table"
30 local debug = require "debug"
31 local ldebug = require "luci.debug"
32 local string = require "string"
33 local coroutine = require "coroutine"
35 local getmetatable, setmetatable = getmetatable, setmetatable
36 local rawget, rawset, unpack = rawget, rawset, unpack
37 local tostring, type, assert = tostring, type, assert
38 local ipairs, pairs, loadstring = ipairs, pairs, loadstring
39 local require, pcall, xpcall = require, pcall, xpcall
40 local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit
42 --- LuCI utility functions.
46 -- Pythonic string formatting extension
48 getmetatable("").__mod = function(a, b)
51 elseif type(b) == "table" then
52 return a:format(unpack(b))
60 -- Class helper routines
63 -- Instantiates a class
64 local function _instantiate(class, ...)
65 local inst = setmetatable({}, {__index = class})
74 --- Create a Class object (Python-style object model).
75 -- The class object can be instantiated by calling itself.
76 -- Any class functions or shared parameters can be attached to this object.
77 -- Attaching a table to the class object makes this table shared between
78 -- all instances of this class. For object parameters use the __init__ function.
79 -- Classes can inherit member functions and values from a base class.
80 -- Class can be instantiated by calling them. All parameters will be passed
81 -- to the __init__ function of this class - if such a function exists.
82 -- The __init__ function must be used to set any object parameters that are not shared
83 -- with other objects of this class. Any return values will be ignored.
84 -- @param base The base class to inherit from (optional)
85 -- @return A class object
89 return setmetatable({}, {
90 __call = _instantiate,
95 --- Test whether the given object is an instance of the given class.
96 -- @param object Object instance
97 -- @param class Class object to test against
98 -- @return Boolean indicating whether the object is an instance
101 function instanceof(object, class)
102 local meta = getmetatable(object)
103 while meta and meta.__index do
104 if meta.__index == class then
107 meta = getmetatable(meta.__index)
114 -- Scope manipulation routines
117 --- Create a new or get an already existing thread local store associated with
118 -- the current active coroutine. A thread local store is private a table object
119 -- whose values can't be accessed from outside of the running coroutine.
120 -- @return Table value representing the corresponding thread local store
121 function threadlocal()
124 local function get(self, key)
125 local t = rawget(self, coxpt[coroutine.running()] or coroutine.running() or 0)
129 local function set(self, key, value)
130 local c = coxpt[coroutine.running()] or coroutine.running() or 0
131 if not rawget(self, c) then
132 rawset(self, c, { [key] = value })
134 rawget(self, c)[key] = value
138 setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
145 -- Debugging routines
148 --- Write given object to stderr.
149 -- @param obj Value to write to stderr
150 -- @return Boolean indicating whether the write operation was successful
152 return io.stderr:write(tostring(obj) .. "\n")
155 --- Recursively dumps a table to stdout, useful for testing and debugging.
156 -- @param t Table value to dump
157 -- @param maxdepth Maximum depth
158 -- @return Always nil
159 function dumptable(t, maxdepth, i, seen)
161 seen = seen or setmetatable({}, {__mode="k"})
163 for k,v in pairs(t) do
164 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
165 if type(v) == "table" and (not maxdepth or i < maxdepth) then
168 dumptable(v, maxdepth, i+1, seen)
170 perror(string.rep("\t", i) .. "*** RECURSION ***")
178 -- String and data manipulation routines
181 --- Escapes all occurrences of the given character in given string.
182 -- @param s String value containing unescaped characters
183 -- @param c String value with character to escape (optional, defaults to "\")
184 -- @return String value with each occurrence of character escaped with "\"
185 function escape(s, c)
187 return s:gsub(c, "\\" .. c)
190 --- Create valid XML PCDATA from given string.
191 -- @param value String value containing the data to escape
192 -- @return String value containing the escaped data
193 local function _pcdata_repl(c)
194 local i = string.byte(c)
196 if ( i >= 0x00 and i <= 0x08 ) or ( i >= 0x0B and i <= 0x0C ) or
197 ( i >= 0x0E and i <= 0x1F ) or ( i == 0x7F )
201 elseif ( i == 0x26 ) or ( i == 0x27 ) or ( i == 0x22 ) or
202 ( i == 0x3C ) or ( i == 0x3E )
204 return string.format("&#%i;", i)
210 function pcdata(value)
211 return value and tostring(value):gsub("[&\"'<>%c]", _pcdata_repl)
214 --- Strip HTML tags from given string.
215 -- @param value String containing the HTML text
216 -- @return String with HTML tags stripped of
217 function striptags(s)
218 return pcdata(tostring(s):gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
221 --- Splits given string on a defined separator sequence and return a table
222 -- containing the resulting substrings. The optional max parameter specifies
223 -- the number of bytes to process, regardless of the actual length of the given
224 -- string. The optional last parameter, regex, specifies whether the separator
225 -- sequence is interpreted as regular expression.
226 -- @param str String value containing the data to split up
227 -- @param pat String with separator pattern (optional, defaults to "\n")
228 -- @param max Maximum times to split (optional)
229 -- @param regex Boolean indicating whether to interpret the separator
230 -- pattern as regular expression (optional, default is false)
231 -- @return Table containing the resulting substrings
232 function split(str, pat, max, regex)
252 local s, e = str:find(pat, c, not regex)
254 if s and max < 0 then
257 t[#t+1] = str:sub(c, s and s - 1)
259 c = e and e + 1 or #str + 1
260 until not s or max < 0
265 --- Remove leading and trailing whitespace from given string value.
266 -- @param str String value containing whitespace padded data
267 -- @return String value with leading and trailing space removed
269 return (str:gsub("^%s*(.-)%s*$", "%1"))
272 --- Count the occurences of given substring in given string.
273 -- @param str String to search in
274 -- @param pattern String containing pattern to find
275 -- @return Number of found occurences
276 function cmatch(str, pat)
278 for _ in str:gmatch(pat) do count = count + 1 end
282 --- Parse certain units from the given string and return the canonical integer
283 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
284 -- Recognized units are:
285 -- o "y" - one year (60*60*24*366)
286 -- o "m" - one month (60*60*24*31)
287 -- o "w" - one week (60*60*24*7)
288 -- o "d" - one day (60*60*24)
289 -- o "h" - one hour (60*60)
290 -- o "min" - one minute (60)
291 -- o "kb" - one kilobyte (1024)
292 -- o "mb" - one megabyte (1024*1024)
293 -- o "gb" - one gigabyte (1024*1024*1024)
294 -- o "kib" - one si kilobyte (1000)
295 -- o "mib" - one si megabyte (1000*1000)
296 -- o "gib" - one si gigabyte (1000*1000*1000)
297 -- @param ustr String containing a numerical value with trailing unit
298 -- @return Number containing the canonical value
299 function parse_units(ustr)
306 y = 60 * 60 * 24 * 366,
307 m = 60 * 60 * 24 * 31,
308 w = 60 * 60 * 24 * 7,
316 gb = 1024 * 1024 * 1024,
318 -- storage sizes (si)
321 gib = 1000 * 1000 * 1000
324 -- parse input string
325 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
327 local num = spec:gsub("[^0-9%.]+$","")
328 local spn = spec:gsub("^[0-9%.]+", "")
330 if map[spn] or map[spn:sub(1,1)] then
331 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
341 -- also register functions above in the central string class for convenience
342 string.escape = escape
343 string.pcdata = pcdata
344 string.striptags = striptags
347 string.cmatch = cmatch
348 string.parse_units = parse_units
351 --- Appends numerically indexed tables or single objects to a given table.
352 -- @param src Target table
353 -- @param ... Objects to insert
354 -- @return Target table
355 function append(src, ...)
356 for i, a in ipairs({...}) do
357 if type(a) == "table" then
358 for j, v in ipairs(a) do
368 --- Combines two or more numerically indexed tables and single objects into one table.
369 -- @param tbl1 Table value to combine
370 -- @param tbl2 Table value to combine
371 -- @param ... More tables to combine
372 -- @return Table value containing all values of given tables
373 function combine(...)
374 return append({}, ...)
377 --- Checks whether the given table contains the given value.
378 -- @param table Table value
379 -- @param value Value to search within the given table
380 -- @return Boolean indicating whether the given value occurs within table
381 function contains(table, value)
382 for k, v in pairs(table) do
390 --- Update values in given table with the values from the second given table.
391 -- Both table are - in fact - merged together.
392 -- @param t Table which should be updated
393 -- @param updates Table containing the values to update
394 -- @return Always nil
395 function update(t, updates)
396 for k, v in pairs(updates) do
401 --- Retrieve all keys of given associative table.
402 -- @param t Table to extract keys from
403 -- @return Sorted table containing the keys
407 for k, _ in kspairs(t) do
414 --- Clones the given object and return it's copy.
415 -- @param object Table value to clone
416 -- @param deep Boolean indicating whether to do recursive cloning
417 -- @return Cloned table value
418 function clone(object, deep)
421 for k, v in pairs(object) do
422 if deep and type(v) == "table" then
428 return setmetatable(copy, getmetatable(object))
432 --- Create a dynamic table which automatically creates subtables.
433 -- @return Dynamic Table
435 return setmetatable({}, { __index =
437 return rawget(tbl, key)
438 or rawget(rawset(tbl, key, dtable()), key)
444 -- Serialize the contents of a table value.
445 function _serialize_table(t, seen)
446 assert(not seen[t], "Recursion detected.")
453 for k, v in pairs(t) do
454 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
455 k = serialize_data(k, seen)
456 v = serialize_data(v, seen)
457 data = data .. ( #data > 0 and ", " or "" ) ..
458 '[' .. k .. '] = ' .. v
465 local v = serialize_data(t[i], seen)
466 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
469 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
472 --- Recursively serialize given data to lua code, suitable for restoring
473 -- with loadstring().
474 -- @param val Value containing the data to serialize
475 -- @return String value containing the serialized code
478 function serialize_data(val, seen)
479 seen = seen or setmetatable({}, {__mode="k"})
483 elseif type(val) == "number" then
485 elseif type(val) == "string" then
487 elseif type(val) == "boolean" then
488 return val and "true" or "false"
489 elseif type(val) == "function" then
490 return "loadstring(%q)" % get_bytecode(val)
491 elseif type(val) == "table" then
492 return "{ " .. _serialize_table(val, seen) .. " }"
494 return '"[unhandled data type:' .. type(val) .. ']"'
498 --- Restore data previously serialized with serialize_data().
499 -- @param str String containing the data to restore
500 -- @return Value containing the restored data structure
501 -- @see serialize_data
503 function restore_data(str)
504 return loadstring("return " .. str)()
509 -- Byte code manipulation routines
512 --- Return the current runtime bytecode of the given data. The byte code
513 -- will be stripped before it is returned.
514 -- @param val Value to return as bytecode
515 -- @return String value containing the bytecode of the given data
516 function get_bytecode(val)
519 if type(val) == "function" then
520 code = string.dump(val)
522 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
525 return code and strip_bytecode(code)
528 --- Strips unnescessary lua bytecode from given string. Information like line
529 -- numbers and debugging numbers will be discarded. Original version by
530 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
531 -- @param code String value containing the original lua byte code
532 -- @return String value containing the stripped lua byte code
533 function strip_bytecode(code)
534 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
537 subint = function(code, i, l)
540 val = val * 256 + code:byte(i + n - 1)
545 subint = function(code, i, l)
548 val = val * 256 + code:byte(i + n - 1)
554 local function strip_function(code)
555 local count, offset = subint(code, 1, size)
556 local stripped = { string.rep("\0", size) }
557 local dirty = offset + count
558 offset = offset + count + int * 2 + 4
559 offset = offset + int + subint(code, offset, int) * ins
560 count, offset = subint(code, offset, int)
563 t, offset = subint(code, offset, 1)
567 offset = offset + size + subint(code, offset, size)
569 offset = offset + num
570 elseif t == 254 or t == 9 then
571 offset = offset + lnum
574 count, offset = subint(code, offset, int)
575 stripped[#stripped+1] = code:sub(dirty, offset - 1)
577 local proto, off = strip_function(code:sub(offset, -1))
578 stripped[#stripped+1] = proto
579 offset = offset + off - 1
581 offset = offset + subint(code, offset, int) * int + int
582 count, offset = subint(code, offset, int)
584 offset = offset + subint(code, offset, size) + size + int * 2
586 count, offset = subint(code, offset, int)
588 offset = offset + subint(code, offset, size) + size
590 stripped[#stripped+1] = string.rep("\0", int * 3)
591 return table.concat(stripped), offset
594 return code:sub(1,12) .. strip_function(code:sub(13,-1))
599 -- Sorting iterator functions
602 function _sortiter( t, f )
605 for k, v in pairs(t) do
611 table.sort( keys, f )
615 if _pos <= #keys then
616 return keys[_pos], t[keys[_pos]]
621 --- Return a key, value iterator which returns the values sorted according to
622 -- the provided callback function.
623 -- @param t The table to iterate
624 -- @param f A callback function to decide the order of elements
625 -- @return Function value containing the corresponding iterator
627 return _sortiter( t, f )
630 --- Return a key, value iterator for the given table.
631 -- The table pairs are sorted by key.
632 -- @param t The table to iterate
633 -- @return Function value containing the corresponding iterator
635 return _sortiter( t )
638 --- Return a key, value iterator for the given table.
639 -- The table pairs are sorted by value.
640 -- @param t The table to iterate
641 -- @return Function value containing the corresponding iterator
643 return _sortiter( t, function (a,b) return t[a] < t[b] end )
648 -- System utility functions
651 --- Test whether the current system is operating in big endian mode.
652 -- @return Boolean value indicating whether system is big endian
654 return string.byte(string.dump(function() end), 7) == 0
657 --- Execute given commandline and gather stdout.
658 -- @param command String containing command to execute
659 -- @return String containing the command's stdout
660 function exec(command)
661 local pp = io.popen(command)
662 local data = pp:read("*a")
668 --- Return a line-buffered iterator over the output of given command.
669 -- @param command String containing the command to execute
671 function execi(command)
672 local pp = io.popen(command)
674 return pp and function()
675 local line = pp:read()
686 function execl(command)
687 local pp = io.popen(command)
693 if (line == nil) then break end
701 --- Returns the absolute path to LuCI base directory.
702 -- @return String containing the directory path
704 return require "nixio.fs".dirname(ldebug.__file__)
709 -- Coroutine safe xpcall and pcall versions modified for Luci
711 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
713 -- Copyright © 2005 Kepler Project.
714 -- Permission is hereby granted, free of charge, to any person obtaining a
715 -- copy of this software and associated documentation files (the "Software"),
716 -- to deal in the Software without restriction, including without limitation
717 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
718 -- and/or sell copies of the Software, and to permit persons to whom the
719 -- Software is furnished to do so, subject to the following conditions:
721 -- The above copyright notice and this permission notice shall be
722 -- included in all copies or substantial portions of the Software.
724 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
725 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
726 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
727 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
728 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
729 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
730 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
732 local performResume, handleReturnValue
733 local oldpcall, oldxpcall = pcall, xpcall
735 setmetatable(coxpt, {__mode = "kv"})
737 -- Identity function for copcall
738 local function copcall_id(trace, ...)
742 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
743 -- @param f Lua function to be called protected
744 -- @param err Custom error handler
745 -- @param ... Parameters passed to the function
746 -- @return A boolean whether the function call succeeded and the return
747 -- values of either the function or the error handler
748 function coxpcall(f, err, ...)
749 local res, co = oldpcall(coroutine.create, f)
752 local newf = function() return f(unpack(params)) end
753 co = coroutine.create(newf)
755 local c = coroutine.running()
756 coxpt[co] = coxpt[c] or c or 0
758 return performResume(err, co, ...)
761 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
762 -- @param f Lua function to be called protected
763 -- @param ... Parameters passed to the function
764 -- @return A boolean whether the function call succeeded and the returns
765 -- values of the function or the error object
766 function copcall(f, ...)
767 return coxpcall(f, copcall_id, ...)
770 -- Handle return value of protected call
771 function handleReturnValue(err, co, status, arg1, arg2, arg3, arg4, arg5)
773 return false, err(debug.traceback(co, arg1), arg1, arg2, arg3, arg4, arg5)
776 if coroutine.status(co) ~= 'suspended' then
777 return true, arg1, arg2, arg3, arg4, arg5
780 return performResume(err, co, coroutine.yield(arg1, arg2, arg3, arg4, arg5))
783 -- Resume execution of protected function call
784 function performResume(err, co, arg1, arg2, arg3, arg4, arg5)
785 return handleReturnValue(err, co, coroutine.resume(co, arg1, arg2, arg3, arg4, arg5))