2 -- Various useful functions that didn't fit anywhere else
4 local irc_debug = libs.debug
5 local socket = libs.socket
9 -- This module contains various useful functions which didn't fit in any of the
16 misc.ENDIANNESS = "big"
20 -- private functions {{{
22 -- Check for existence of a file. This returns true if renaming a file to
23 -- itself succeeds. This isn't ideal (I think anyway) but it works here, and
24 -- lets me not have to bring in LFS as a dependency.
25 -- @param filename File to check for existence
26 -- @return True if the file exists, false otherwise
27 local function exists(filename)
28 local _, err = os.rename(filename, filename)
29 if not err then return true end
30 return not err:find("No such file or directory")
34 -- internal functions {{{
37 -- Splits str into substrings based on several options.
38 -- @param str String to split
39 -- @param delim String of characters to use as the beginning of substring
41 -- @param end_delim String of characters to use as the end of substring
43 -- @param lquotes String of characters to use as opening quotes (quoted strings
44 -- in str will be considered one substring)
45 -- @param rquotes String of characters to use as closing quotes
46 -- @return Array of strings, one for each substring that was separated out
47 function misc._split(str, delim, end_delim, lquotes, rquotes)
48 -- handle arguments {{{
49 delim = "["..(delim or misc.DELIM).."]"
50 if end_delim then end_delim = "["..end_delim.."]" end
51 if lquotes then lquotes = "["..lquotes.."]" end
52 if rquotes then rquotes = "["..rquotes.."]" end
53 local optdelim = delim .. "?"
57 local instring = false
58 while str:len() > 0 do
59 -- handle case for not currently in a string {{{
61 local end_delim_ind, lquote_ind, delim_ind
62 if end_delim then end_delim_ind = str:find(optdelim..end_delim) end
63 if lquotes then lquote_ind = str:find(optdelim..lquotes) end
64 local delim_ind = str:find(delim)
65 if not end_delim_ind then end_delim_ind = str:len() + 1 end
66 if not lquote_ind then lquote_ind = str:len() + 1 end
67 if not delim_ind then delim_ind = str:len() + 1 end
68 local next_ind = math.min(end_delim_ind, lquote_ind, delim_ind)
69 if next_ind == str:len() + 1 then
70 table.insert(ret, str)
72 elseif next_ind == end_delim_ind then
74 if str:sub(next_ind, next_ind) == end_delim:gsub('[%[%]]', '') then
75 table.insert(ret, str:sub(next_ind + 1))
77 table.insert(ret, str:sub(1, next_ind - 1))
78 table.insert(ret, str:sub(next_ind + 2))
81 elseif next_ind == lquote_ind then
82 table.insert(ret, str:sub(1, next_ind - 1))
83 str = str:sub(next_ind + 2)
85 else -- last because the top two contain it
86 table.insert(ret, str:sub(1, next_ind - 1))
87 str = str:sub(next_ind + 1)
90 -- handle case for currently in a string {{{
92 local endstr = str:find(rquotes..optdelim)
93 table.insert(ret, str:sub(1, endstr - 1))
94 str = str:sub(endstr + 2)
105 -- Returns the basename of a file (the part after the last directory separator).
106 -- @param path Path to the file
107 -- @param sep Directory separator (optional, defaults to PATH_SEP)
108 -- @return The basename of the file
109 function misc._basename(path, sep)
110 sep = sep or misc.PATH_SEP
111 if not path:find(sep) then return path end
112 return socket.skip(2, path:find(".*" .. sep .. "(.*)"))
118 -- Returns the dirname of a file (the part before the last directory separator).
119 -- @param path Path to the file
120 -- @param sep Directory separator (optional, defaults to PATH_SEP)
121 -- @return The dirname of the file
122 function misc._dirname(path, sep)
123 sep = sep or misc.PATH_SEP
124 if not path:find(sep) then return "." end
125 return socket.skip(2, path:find("(.*)" .. sep .. ".*"))
131 -- Converts a number to a low-level int.
132 -- @param str String representation of the int
133 -- @param bytes Number of bytes in an int (defaults to INT_BYTES)
134 -- @param endian Which endianness to use (big, little, host, network) (defaultsi
136 -- @return A string whose first INT_BYTES characters make a low-level int
137 function misc._str_to_int(str, bytes, endian)
138 bytes = bytes or misc.INT_BYTES
139 endian = endian or misc.ENDIANNESS
141 for i = 0, bytes - 1 do
142 local new_byte = string.char(math.fmod(str / (2^(8 * i)), 256))
143 if endian == "big" or endian == "network" then ret = new_byte .. ret
144 else ret = ret .. new_byte
153 -- Converts a low-level int to a number.
154 -- @param int String whose bytes correspond to the bytes of a low-level int
155 -- @param endian Endianness of the int argument (defaults to ENDIANNESS)
156 -- @return String representation of the low-level int argument
157 function misc._int_to_str(int, endian)
158 endian = endian or misc.ENDIANNESS
160 for i = 1, int:len() do
161 if endian == "big" or endian == "network" then ind = int:len() - i + 1
164 ret = ret + string.byte(int:sub(ind, ind)) * 2^(8 * (i - 1))
170 -- _ip_str_to_int {{{
171 -- TODO: handle endianness here
173 -- Converts a string IP address to a low-level int.
174 -- @param ip_str String representation of an IP address
175 -- @return Low-level int representation of that IP address
176 function misc._ip_str_to_int(ip_str)
179 for num in ip_str:gmatch("%d+") do
180 ret = ret + num * 2^(i * 8)
187 -- _ip_int_to_str {{{
188 -- TODO: handle endianness here
190 -- Converts an int to a string IP address.
191 -- @param ip_int Low-level int representation of an IP address
192 -- @return String representation of that IP address
193 function misc._ip_int_to_str(ip_int)
196 local new_num = math.floor(ip_int / 2^(i * 8))
197 table.insert(ip, new_num)
198 ip_int = ip_int - new_num * 2^(i * 8)
200 return table.concat(ip, ".")
204 -- _get_unique_filename {{{
206 -- Returns a unique filename.
207 -- @param filename Filename to start with
208 -- @return Filename (same as the one we started with, except possibly with some
209 -- numbers appended) which does not currently exist on the filesystem
210 function misc._get_unique_filename(filename)
211 if not exists(filename) then return filename end
215 if not exists(filename .. "." .. count) then
216 return filename .. "." .. count
225 -- Call a function, if it exists.
226 -- @param fn Function to try to call
227 -- @param ... Arguments to fn
228 -- @return The return values of fn, if it was successfully called
229 function misc._try_call(fn, ...)
230 if type(fn) == "function" then
236 -- _try_call_warn {{{
238 -- Same as try_call, but complain if the function doesn't exist.
239 -- @param msg Warning message to use if the function doesn't exist
240 -- @param fn Function to try to call
241 -- @param ... Arguments to fn
242 -- @return The return values of fn, if it was successfully called
243 function misc._try_call_warn(msg, fn, ...)
244 if type(fn) == "function" then
254 -- Iterator to iterate over just the values of a table.
255 function misc._value_iter(state, arg, pred)
256 for k, v in pairs(state) do
257 if arg == v then arg = k end
259 local key, val = next(state, arg)
260 if not key then return end
262 if type(pred) == "function" then
263 while not pred(val) do
264 key, val = next(state, key)
265 if not key then return end
274 -- Gets the various parts of a full username.
275 -- @param user A usermask (i.e. returned in the from field of a callback)
277 -- @return username (if it exists)
278 -- @return hostname (if it exists)
279 function misc._parse_user(user)
280 local found, bang, nick = user:find("^([^!]*)!")
282 user = user:sub(bang + 1)
286 local found, equals = user:find("^.=")
290 local found, at, username = user:find("^([^@]*)@")
292 return nick, username, user:sub(at + 1)