Convert the given input array of byte values to an IP address string.
\n
Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16\nto IPv6 ones. All other lengths are rejected. If any array element is not an\ninteger or exceeds the range 0..255 (inclusive), the array is rejected.
\n
Returns a string containing the formatted IP address.\nReturns null if the input array was invalid.
Calls the given function value with a modified environment.
\n
The given ctx argument is used as this context for the invoked function\nand the given scope value as global environment. Any further arguments are\npassed to the invoked function as-is.
\n
When ctx is omitted or null, the function will get invoked with this\nbeing null.
\n
When scope is omitted or null, the function will get executed with the\ncurrent global environment of the running program. When scope is set to a\ndictionary, the dictionary is used as global function environment.
\n
When the scope dictionary has no prototype, the current global environment\nwill be set as prototype, means the scope will inherit from it.
\n
When a scope prototype is set, it is kept. This allows passing an isolated\n(sandboxed) function scope without access to the global environment.
\n
Any further argument is forwarded as-is to the invoked function as function\ncall argument.
\n
Returns null if the given function value fn is not callable.
\n
Returns the return value of the invoked function in all other cases.
\n
Forwards exceptions thrown by the invoked function.
Converts each given numeric value to a byte and return the resulting string.\nInvalid numeric values or values < 0 result in \\0 bytes, values larger than\n255 are truncated to 255.
\n
Returns a new strings consisting of the given byte values.
Reads the current second and microsecond value of the system clock.
\n
By default, the realtime clock is queried which might skew forwards or\nbackwards due to NTP changes, system sleep modes etc. If a truish value is\npassed as argument, the monotonic system clock is queried instead, which will\nreturn the monotonically increasing time since some arbitrary point in the\npast (usually the system boot time).
\n
Returns a two element array containing the full seconds as the first element\nand the nanosecond fraction as the second element.
\n
Returns null if a monotonic clock value is requested and the system does\nnot implement this clock type.
Filter the array passed as the first argument by invoking the function\nspecified in the second argument for each array item.
\n
If the invoked function returns a truthy result, the item is retained,\notherwise, it is dropped. The filter function is invoked with three\narguments:
\n\n
The array value
\n
The current index
\n
The array being filtered
\n\n
Returns a new array containing only retainted items, in the same order as\nthe input array.
Interacts with the mark and sweep garbage collector of the running ucode\nvirtual machine.
\n
Depending on the given operation string argument, the meaning of argument\nand the function return value differs.
\n
The following operations are defined:
\n
\n
collect - Perform a complete garbage collection cycle, returns true.
\n
start - (Re-)start periodic garbage collection, argument is an optional\ninteger in the range 1..65535 specifying the interval.\nDefaults to 1000 if omitted. Returns true if the periodic GC\nwas previously stopped and is now started or if the interval\nchanged. Returns false otherwise.
\n
stop - Stop periodic garbage collection. Returns true if the periodic\nGC was previously started and is now stopped, false otherwise.
\n
count - Count the amount of active complex object references in the VM\ncontext, returns the counted amount.
\n
\n
If the operation argument is omitted, the default is collect.
Evaluate and include the file at the given path and optionally override the\nexecution scope with the given scope object.
\n
By default, the file is executed within the same scope as the calling\ninclude(), but by passing an object as the second argument, it is possible\nto extend the scope available to the included file.
\n
This is useful to supply additional properties as global variables to the\nincluded code. To sandbox included code, that is giving it only access to\nexplicitly provided properties, the proto() function can be used to create\na scope object with an empty prototype.
Convert the given IP address string to an array of byte values.
\n
IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays\ncontaining 16 intergers. The resulting array can be turned back into IP\naddress strings using the inverse arrtoip() function.
\n
Returns an array containing the address byte values.\nReturns null if the given argument is not a string or an invalid IP.
Parse the given string or resource as JSON and return the resulting value.
\n
If the input argument is a plain string, it is directly parsed as JSON.
\n
If an array, object or resource value is given, this function will attempt to\ninvoke a read() method on it to read chunks of input text to incrementally\nparse as JSON data. Reading will stop if the object's read() method returns\neither null or an empty string.
\n
Throws an exception on parse errors, trailing garbage, or premature EOF.
Return the given epoch timestamp (or now, if omitted) as a dictionary\ncontaining broken-down date and time information according to the local\nsystem timezone.
\n
The resulting dictionary contains the following fields:
\n
\n
sec Seconds (0-60)
\n
min Minutes (0-59)
\n
hour Hours (0-23)
\n
mday Day of month (1-31)
\n
mon Month (1-12)
\n
year Year (>= 1900)
\n
wday Day of the week (1-7, Sunday = 7)
\n
yday Day of the year (1-366, Jan 1st = 1)
\n
isdst Daylight saving time in effect (yes = 1)
\n
\n
Note that in contrast to the underlying localtime(3) C library function,\nthe values for mon, wday, and yday are 1-based, and the year is\n1900-based.
Trim any of the specified characters from the start of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.
Without further arguments, this function returns the byte value of the first\ncharacter in the given string.
\n
If an offset argument is supplied, the byte value of the character at this\nposition is returned. If an invalid index is supplied, the function will\nreturn null. Negative index entries are counted towards the end of the\nstring, e.g. -2 will return the value of the second last character.
\n
Returns the byte value of the character.\nReturns null if the offset is invalid or if the input is not a string.
The print() function writes a string representation of each given argument\nto stdout and returns the amount of bytes written.
\n
String values are printed as-is, integer and double values are printed in\ndecimal notation, boolean values are printed as true or false while\narrays and objects are converted to their JSON representation before being\nwritten to the standard output. The null value is represented by an empty\nstring so print(null) would print nothing. Resource values are printed in\nthe form <type address>, e.g. <fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
\n
Examples:
\n
print(1 != 2); // Will print 'true'\nprint(0xff); // Will print '255'\nprint(2e3); // Will print '2000'\nprint(null); // Will print nothing\nprint({ hello: true, world: 123 }); // Will print '{ "hello": true, "world": 123 }'\nprint([1,2,3]); // Will print '[ 1, 2, 3 ]'\n\nprint(proto({ foo: "bar" }, // Will print 'MyObj'\n { tostring: () => "MyObj" })); // instead of '{ "foo": "bar" }'\n\n
Formats the given arguments according to the given format string and outputs\nthe result to stdout.
\n
Ucode supports a restricted subset of the formats allowed by the underlying\nlibc's printf() implementation, namely it allows the d, i, o, u,\nx, X, e, E, f, F, g, G, c and s conversions.
\n
Additionally, an ucode specific J format is implemented, which causes the\ncorresponding value to be formatted as JSON string. By prefixing the J\nformat letter with a precision specifier, the resulting JSON output will be\npretty printed. A precision of 0 will use tabs for indentation, any other\npositive precision will use that many spaces for indentation while a negative\nor omitted precision specifier will turn off pretty printing.
\n
Other format specifiers such as n or z are not accepted and returned\nverbatim. Format specifiers including * directives are rejected as well.
\n
Returns the number of bytes written to the standard output.
Get or set the prototype of the array or object value val.
\n
When invoked without a second argument, the function returns the current\nprototype of the value in val or null if there is no prototype or if the\ngiven value is neither an object nor an array.
\n
When invoked with a second prototype argument, the given proto value is set\nas the prototype on the array or object in val.
\n
Throws an exception if the given prototype value is not an object.
When invoked with a string value as the first argument, the function acts\nlike include() but captures the output of the included file as a string and\nreturns the captured contents.
\n
The second argument is treated as the scope.
\n
When invoked with a function value as the first argument, render() calls\nthe given function and passes all subsequent arguments to it.
\n
Any output produced by the called function is captured and returned as a\nstring. The return value of the called function is discarded.
Replace occurrences of the specified pattern in the string passed as the\nfirst argument.
\n
\n
The pattern value may be either a regular expression or a plain string.
\n
The replace value may be a function which is invoked for each found pattern\nor any other value which is converted into a plain string and used as\nreplacement.
\n
When an optional limit is specified, substitutions are performed only that\nmany times.
\n
If the pattern is a regular expression and not using the g flag, then\nonly the first occurrence in the string is replaced.
\n
If the g flag is used or if the pattern is not a regular expression, all\noccurrences are replaced.
\n
If the replace value is a callback function, it is invoked with the found\nsubstring as the first and any capture group values as subsequent\nparameters.
\n
If the replace value is a string, specific substrings are substituted\nbefore it is inserted into the result.
Trim any of the specified characters from the end of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.
When invoked with two arguments, a signal specification and a signal handler\nvalue, this function configures a new process signal handler.
\n
When invoked with one argument, a signal specification, this function returns\nthe currently configured handler for the given signal.
\n
The signal specification might either be an integer signal number or a string\nvalue containing a signal name (with or without "SIG" prefix). Signal names\nare treated case-insensitively.
\n
The signal handler might be either a callable function value or one of the\ntwo special string values "ignore" and "default". Passing "ignore" will\nmask the given process signal while "default" will restore the operating\nsystems default behaviour for the given signal.
\n
In case a callable handler function is provided, it is invoked at the\nearliest opportunity after receiving the corresponding signal from the\noperating system. The invoked function will receive a single argument, the\nnumber of the signal it is invoked for.
\n
Note that within the ucode VM, process signals are not immediately delivered,\ninstead the VM keeps track of received signals and delivers them to the ucode\nscript environment at the next opportunity, usually before executing the next\nbyte code instruction. This means that if a signal is received while\nperforming a computationally expensive operation in C mode, such as a complex\nregexp match, the corresponding ucode signal handler will only be invoked\nafter that operation concluded and control flow returns to the VM.
\n
Returns the signal handler function or one of the special values "ignore"\nor "default" corresponding to the given signal specification.
\n
Returns null if an invalid signal spec or signal handler was provided.
\n
Returns null if changing the signal action failed, e.g. due to insufficient\npermission, or when attempting to ignore a non-ignorable signal.
Sort the given array according to the given sort function.\nIf no sort function is provided, a default ascending sort order is applied.
\n
The input array is sorted in-place, no copy is made.
\n
The custom sort function is repeatedly called until the entire array is\nsorted. It will receive two values as arguments and should return a value\nlower than, larger than or equal to zero depending on whether the first\nargument is smaller, larger or equal to the second argument respectively.
Split the given string using the separator passed as the second argument\nand return an array containing the resulting pieces.
\n
If a limit argument is supplied, the resulting array contains no more than\nthe given amount of entries, that means the string is split at most\nlimit - 1 times total.
\n
The separator may either be a plain string or a regular expression.
\n
Returns a new array containing the resulting pieces.
Executes the given command, waits for completion, and returns the resulting\nexit code.
\n
The command argument may be either a string, in which case it is passed to\n/bin/sh -c, or an array, which is directly converted into an execv()\nargument vector.
\n
\n
If the program terminated normally, a positive integer holding the\nprogram's exit() code is returned.
\n
If the program was terminated by an uncaught signal, a negative signal\nnumber is returned.
\n
If the optional timeout argument is specified, the program is terminated\nby SIGKILL after that many milliseconds if it doesn't complete within\nthe timeout.
\n
\n
Omitting the timeout argument or passing 0 disables the command timeout.
Performs the inverse operation of localtime() by taking a broken-down date\nand time dictionary and transforming it into an epoch value according to the\nlocal system timezone.
\n
The wday and yday fields of the given date time specification are\nignored. Field values outside of their valid range are internally normalized,\ne.g. October 40th is interpreted as November 9th.
\n
Returns the resulting epoch value or null if the input date time dictionary\nwas invalid or if the date time specification cannot be represented as epoch\nvalue.
Trim any of the specified characters in c from the start and end of str.\nIf the second argument is omitted, trims the characters, (space), \\t,\n\\r, and \\n.
This module provides runtime debug functionality for ucode scripts.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\n\nmemdump("/tmp/dump.txt");\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\n\ndebug.memdump("/tmp/dump.txt");\n
\n
Additionally, the debug module namespace may also be imported by invoking the\nucode interpreter with the -ldebug switch.
\n
Upon loading, the debug module will register a SIGUSR2 signal handler\nwhich, upon receipt of the signal, will write a memory dump of the currently\nrunning program to /tmp/ucode.$timestamp.$pid.memdump. This default\nbehavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED\nenvironment variable to 0 when starting the process. The memory dump signal\nand output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL\nand UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.
The getinfo() function allows querying internal information about the\ngiven ucode value, such as the current reference count, the mark bit state\netc.
\n
Returns a dictionary with value type specific details.
The getlocal() function retrieves information about the specified local\nvariable at the given call stack depth.
\n
The call stack depth specifies the amount of levels up local variables should\nbe queried. A value of 0 refers to this getlocal() function call itself,\n1 to the function calling getlocal() and so on.
\n
The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the given variable.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is a C call.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
The getupval() function retrieves information about the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.
\n
The call stack depth specifies the amount of levels up the function should be\nselected to query associated captured variables for. A value of 0 refers to\nthis getupval() function call itself, 1 to the function calling\ngetupval() and so on.
\n
The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the given variable.
\n
Returns null if the given function value is not a closure.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is not a closure.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
This function generates a human readable memory dump of ucode values\ncurrently managed by the running VM which is useful to track down logical\nmemory leaks in scripts.
\n
The file parameter can be either a string value containing a file path, in\nwhich case this function tries to create and write the report file at the\ngiven location, or an already open file handle this function should write to.
\n
Returns true if the report has been written.
\n
Returns null if the file could not be opened or if the handle was invalid.
The setlocal() function manipulates the value of the specified local\nvariable at the given call stack depth.
\n
The call stack depth specifies the amount of levels up local variables should\nbe updated. A value of 0 refers to this setlocal() function call itself,\n1 to the function calling setlocal() and so on.
\n
The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the updated variable.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is a C call.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
The setupval() function manipulates the value of the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.
\n
The call stack depth specifies the amount of levels up the function should be\nselected to update associated captured variables for. A value of 0 refers\nto this setupval() function call itself, 1 to the function calling\nsetupval() and so on.
\n
The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the updated variable.
\n
Returns null if the given function value is not a closure.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is not a closure.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
This function captures the current call stack and returns it. The optional\nlevel parameter controls how many calls up the trace should start. It\ndefaults to 1, that is the function calling this traceback() function.
\n
Returns an array of stack trace entries describing the function invocations\nup to the point where traceback() is called.
The fs module provides functions for interacting with the file system.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { readlink, popen } from 'fs';\n\nlet dest = readlink('/sys/class/net/eth0');\nlet proc = popen('ps ww');\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as fs from 'fs';\n\nlet dest = fs.readlink('/sys/class/net/eth0');\nlet proc = fs.popen('ps ww');\n
\n
Additionally, the filesystem module namespace may also be imported by invoking\nthe ucode interpreter with the -lfs switch.
The optional modes argument specifies the access modes which should be\nchecked. A file is only considered accessible if all access modes specified\nin the modes argument are possible.
\n
The following modes are recognized:
\n
\n\n
\n
Mode
\n
Description
\n
\n\n\n
\n
"r"
\n
Tests whether the file is readable.
\n
\n
\n
"w"
\n
Tests whether the file is writable.
\n
\n
\n
"x"
\n
Tests whether the file is executable.
\n
\n
\n
"f"
\n
Tests whether the file exists.
\n
\n\n
\n
Returns true if the given path is accessible or false when it is not.
\n
Returns null if an error occurred, e.g. due to inaccessible intermediate\npath components, invalid path arguments etc.
Changes the owner and group of a file or directory.
\n
The user and group may be specified either as uid or gid number respectively,\nor as a string containing the user or group name, in which case it is\nresolved to the proper uid/gid first.
\n
If either the user or group parameter is omitted or given as -1,\nit is not changed.
\n
Returns true if the ownership change was successful.
\n
Returns null if an error occurred or if a user/group name cannot be\nresolved to a uid/gid value.
Creates a new temporary file, opens it in read and write mode, unlinks it and\nreturns a file handle object referring to the yet open but deleted file.
\n
Upon closing the handle, the associated file will automatically vanish from\nthe system.
\n
The optional path template argument may be used to override the path and name\nchosen for the temporary file. If the path template contains no path element,\n/tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is\nappended to it. The XXXXXX sequence is replaced with a random value\nensuring uniqueness of the temporary file name.
\n
Returns a file handle object referring to the ephemeral file on success.
\n
Returns null if an error occurred, e.g. on insufficient permissions or\ninaccessible directory.
Creates a pipe and returns file handle objects associated with the read- and\nwrite end of the pipe respectively.
\n
Returns a two element array containing both a file handle object open in read\nmode referring to the read end of the pipe and a file handle object open in\nwrite mode referring to the write end of the pipe.
Starts a process and returns a handle representing the executed process.
\n
The handle will be connected to the process stdin or stdout, depending on the\nvalue of the mode argument.
\n
The mode argument may be either "r" to open the process for reading (connect\nto its stdin) or "w" to open the process for writing (connect to its stdout).
\n
The mode character "r" or "w" may be optionally followed by "e" to apply the\nFD_CLOEXEC flag onto the open descriptor.
\n
Returns a process handle referring to the executed process.
Writes the given data to a file, optionally truncated to the given amount\nof bytes.
\n
In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written into the file. The null value is\nrepresented by an empty string so writefile(…, null) would write an empty\nfile. Resource values are written in the form <type address>, e.g.\n<fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
\n
If a file already exists at the given path, it is truncated. If no file\nexists, it is created with default permissions 0o666 masked by the currently\neffective umask.
\n
Returns the number of bytes written.
\n
Returns null if an error occurred, e.g. due to insufficient permissions.
Sets the read position within the open directory handle to the given offset\nvalue. The offset value should be obtained by a previous call to tell() as\nthe specific integer values are implementation defined.
Returns the current read position in the open directory handle which can be\npassed back to the seek() function to return to this position. This is\nmainly useful to read an open directory handle (or specific items) multiple\ntimes.
\n
Returns an integer referring to the current position.
The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.
\n
\n
\n
If length is a number, the method will read the specified number of bytes\nfrom the handle. Reading stops after the given amount of bytes or after\nencountering EOF, whatever comes first.
\n
\n
\n
If length is the string "line", the method will read an entire line,\nterminated by "\\n" (a newline), from the handle. Reading stops at the next\nnewline or when encountering EOF. The returned data will contain the\nterminating newline character if one was read.
\n
\n
\n
If length is the string "all", the method will read from the handle until\nencountering EOF and return the complete contents.
\n
\n
\n
If length is a single character string, the method will read from the\nhandle until encountering the specified character or upon encountering\nEOF. The returned data will contain the terminating character if one was\nread.
In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written. The null value is represented by an\nempty string so file.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
Closes the program handle and awaits program termination.
\n
Upon calling close() on the handle, the program's input or output stream\n(depending on the open mode) is closed. Afterwards, the function awaits the\ntermination of the underlying program and returns its exit code.
\n
\n
\n
When the program was terminated by a signal, the return value will be the\nnegative signal number, e.g. -9 for SIGKILL.
\n
\n
\n
When the program terminated normally, the return value will be the positive\nexit code of the program.
\n
\n
\n
Returns a negative signal number if the program was terminated by a signal.
\n
Returns a positive exit code if the program terminated normally.
The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.
\n
\n
\n
If length is a number, the method will read the specified number of bytes\nfrom the handle. Reading stops after the given amount of bytes or after\nencountering EOF, whatever comes first.
\n
\n
\n
If length is the string "line", the method will read an entire line,\nterminated by "\\n" (a newline), from the handle. Reading stops at the next\nnewline or when encountering EOF. The returned data will contain the\nterminating newline character if one was read.
\n
\n
\n
If length is the string "all", the method will read from the handle until\nencountering EOF and return the complete contents.
\n
\n
\n
If length is a single character string, the method will read from the\nhandle until encountering the specified character or upon encountering\nEOF. The returned data will contain the terminating character if one was\nread.
In case the given data is not a string, it is converted to a string before\nbeing written to the program's stdin. String values are written as-is,\ninteger and double values are written in decimal notation, boolean values are\nwritten as true or false while arrays and objects are converted to their\nJSON representation before being written. The null value is represented by\nan empty string so proc.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
The math module bundles various mathematical and trigonometrical functions.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { pow, rand } from 'math';\n\nlet x = pow(2, 5);\nlet y = rand();\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as math from 'math';\n\nlet x = math.pow(2, 5);\nlet y = math.rand();\n
\n
Additionally, the math module namespace may also be imported by invoking the\nucode interpreter with the -lmath switch.
Returns the calculated pseuo-random value. The value is within the range\n0 to RAND_MAX inclusive where RAND_MAX is a platform specific value\nguaranteed to be at least 32767.
\n
The {@link module:math~srand srand()} function sets its argument as the\nseed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are\nrepeatable by calling {@link module:math~srand srand()} with the same\nseed value.
\n
If no seed value is explicitly set by calling\n{@link module:math~srand srand()} prior to the first call to rand(),\nthe math module will automatically seed the PRNG once, using the current\ntime of day in milliseconds as seed value.
This functions seeds the PRNG with the given value and thus affects the\npseudo-random integer sequence produced by subsequent calls to\n{@link module:math~rand rand()}.
\n
Setting the same seed value will result in the same pseudo-random numbers\nproduced by {@link module:math~rand rand()}.
The struct module provides routines for interpreting byte strings as packed\nbinary data.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n
\n
Additionally, the struct module namespace may also be imported by invoking\nthe ucode interpreter with the -lstruct switch.
\n
Format Strings
\n
Format strings describe the data layout when packing and unpacking data.\nThey are built up from format-characters, which specify the type of data\nbeing packed/unpacked. In addition, special characters control the byte\norder, size and alignment.
\n
Each format string consists of an optional prefix character which describes\nthe overall properties of the data and one or more format characters which\ndescribe the actual data values and padding.
\n
Byte Order, Size, and Alignment
\n
By default, C types are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary (according to\nthe rules used by the C compiler).
\n
This behavior is chosen so that the bytes of a packed struct correspond\nexactly to the memory layout of the corresponding C struct.
\n
Whether to use native byte ordering and padding or standard formats depends\non the application.
\n
Alternatively, the first character of the format string can be used to indicate\nthe byte order, size and alignment of the packed data, according to the\nfollowing table:
\n
\n\n
\n
Character
\n
Byte order
\n
Size
\n
Alignment
\n
\n\n\n
\n
@
\n
native
\n
native
\n
native
\n
\n
\n
=
\n
native
\n
standard
\n
none
\n
\n
\n
<
\n
little-endian
\n
standard
\n
none
\n
\n
\n
>
\n
big-endian
\n
standard
\n
none
\n
\n
\n
!
\n
network (= big-endian)
\n
standard
\n
none
\n
\n\n
\n
If the first character is not one of these, '@' is assumed.
\n
Native byte order is big-endian or little-endian, depending on the\nhost system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are\nlittle-endian; IBM z and many legacy architectures are big-endian.
\n
Native size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte order.
\n
Standard size depends only on the format character; see the table in\nthe format-characters section.
\n
Note the difference between '@' and '=': both use native byte order,\nbut the size and alignment of the latter is standardized.
\n
The form '!' represents the network byte order which is always big-endian\nas defined in IETF RFC 1700.
\n
There is no way to indicate non-native byte order (force byte-swapping); use\nthe appropriate choice of '<' or '>'.
\n
Notes:
\n
(1) Padding is only automatically added between successive structure members.\nNo padding is added at the beginning or the end of the encoded struct.
\n
(2) No padding is added when using non-native size and alignment, e.g.\nwith '<', '>', '=', and '!'.
\n
(3) To align the end of a structure to the alignment requirement of a\nparticular type, end the format with the code for that type with a repeat\ncount of zero.
\n
Format Characters
\n
Format characters have the following meaning; the conversion between C and\nucode values should be obvious given their types. The 'Standard size' column\nrefers to the size of the packed value in bytes when using standard size;\nthat is, when the format string starts with one of '<', '>', '!' or\n'='. When using native size, the size of the packed value is platform\ndependent.
\n
\n\n
\n
Format
\n
C Type
\n
Ucode type
\n
Standard size
\n
Notes
\n
\n\n\n
\n
x
\n
pad byte
\n
no value
\n
\n
(7)
\n
\n
\n
c
\n
char
\n
string
\n
1
\n
\n
\n
\n
b
\n
signed char
\n
int
\n
1
\n
(1), (2)
\n
\n
\n
B
\n
unsigned char
\n
int
\n
1
\n
(2)
\n
\n
\n
?
\n
_Bool
\n
bool
\n
1
\n
(1)
\n
\n
\n
h
\n
short
\n
int
\n
2
\n
(2)
\n
\n
\n
H
\n
unsigned short
\n
int
\n
2
\n
(2)
\n
\n
\n
i
\n
int
\n
int
\n
4
\n
(2)
\n
\n
\n
I
\n
unsigned int
\n
int
\n
4
\n
(2)
\n
\n
\n
l
\n
long
\n
int
\n
4
\n
(2)
\n
\n
\n
L
\n
unsigned long
\n
int
\n
4
\n
(2)
\n
\n
\n
q
\n
long long
\n
int
\n
8
\n
(2)
\n
\n
\n
Q
\n
unsigned long long
\n
int
\n
8
\n
(2)
\n
\n
\n
n
\n
ssize_t
\n
int
\n
\n
(3)
\n
\n
\n
N
\n
size_t
\n
int
\n
\n
(3)
\n
\n
\n
e
\n
(6)
\n
double
\n
2
\n
(4)
\n
\n
\n
f
\n
float
\n
double
\n
4
\n
(4)
\n
\n
\n
d
\n
double
\n
double
\n
8
\n
(4)
\n
\n
\n
s
\n
char[]
\n
double
\n
\n
(9)
\n
\n
\n
p
\n
char[]
\n
double
\n
\n
(8)
\n
\n
\n
P
\n
void *
\n
int
\n
\n
(5)
\n
\n
\n
*
\n
char[]
\n
string
\n
\n
(10)
\n
\n\n
\n
Notes:
\n
\n
\n
(1) The '?' conversion code corresponds to the _Bool type defined by\nC99. If this type is not available, it is simulated using a char. In\nstandard mode, it is always represented by one byte.
\n
\n
\n
(2) When attempting to pack a non-integer using any of the integer\nconversion codes, this module attempts to convert the given value into an\ninteger. If the value is not convertible, a type error exception is thrown.
\n
\n
\n
(3) The 'n' and 'N' conversion codes are only available for the native\nsize (selected as the default or with the '@' byte order character).\nFor the standard size, you can use whichever of the other integer formats\nfits your application.
\n
\n
\n
(4) For the 'f', 'd' and 'e' conversion codes, the packed\nrepresentation uses the IEEE 754 binary32, binary64 or binary16 format\n(for 'f', 'd' or 'e' respectively), regardless of the floating-point\nformat used by the platform.
\n
\n
\n
(5) The 'P' format character is only available for the native byte\nordering (selected as the default or with the '@' byte order character).\nThe byte order character '=' chooses to use little- or big-endian\nordering based on the host system. The struct module does not interpret\nthis as native ordering, so the 'P' format is not available.
\n
\n
\n
(6) The IEEE 754 binary16 "half precision" type was introduced in the 2008\nrevision of the IEEE 754 standard. It has a sign bit, a 5-bit exponent\nand 11-bit precision (with 10 bits explicitly stored), and can represent\nnumbers between approximately 6.1e-05 and 6.5e+04 at full precision.\nThis type is not widely supported by C compilers: on a typical machine, an\nunsigned short can be used for storage, but not for math operations. See\nthe Wikipedia page on the half-precision floating-point format for more\ninformation.
\n
\n
\n
(7) When packing, 'x' inserts one NUL byte.
\n
\n
\n
(8) The 'p' format character encodes a "Pascal string", meaning a short\nvariable-length string stored in a fixed number of bytes, given by the\ncount. The first byte stored is the length of the string, or 255,\nwhichever is smaller. The bytes of the string follow. If the string\npassed in to pack() is too long (longer than the count minus 1), only\nthe leading count-1 bytes of the string are stored. If the string is\nshorter than count-1, it is padded with null bytes so that exactly count\nbytes in all are used. Note that for unpack(), the 'p' format\ncharacter consumes count bytes, but that the string returned can never\ncontain more than 255 bytes.
\n
\n
\n
(9) For the 's' format character, the count is interpreted as the length\nof the bytes, not a repeat count like for the other format characters; for\nexample, '10s' means a single 10-byte string mapping to or from a single\nucode byte string, while '10c' means 10 separate one byte character\nelements (e.g., cccccccccc) mapping to or from ten different ucode byte\nstrings. If a count is not given, it defaults to 1. For packing, the\nstring is truncated or padded with null bytes as appropriate to make it\nfit. For unpacking, the resulting bytes object always has exactly the\nspecified number of bytes. As a special case, '0s' means a single,\nempty string (while '0c' means 0 characters).
\n
\n
\n
(10) The * format character serves as wildcard. For pack() it will\nappend the corresponding byte argument string as-is, not applying any\npadding or zero filling. When a repeat count is given, that many bytes of\nthe input byte string argument will be appended at most on pack(),\neffectively truncating longer input strings. For unpack(), the wildcard\nformat will yield a byte string containing the entire remaining input data\nbytes, or - when a repeat count is given - that many bytes of input data\nat most.
\n
\n
\n
A format character may be preceded by an integral repeat count. For example,\nthe format string '4h' means exactly the same as 'hhhh'.
\n
Whitespace characters between formats are ignored; a count and its format\nmust not contain whitespace though.
\n
When packing a value x using one of the integer formats ('b',\n'B', 'h', 'H', 'i', 'I', 'l', 'L',\n'q', 'Q'), if x is outside the valid range for that format, a type\nerror exception is raised.
\n
For the '?' format character, the return value is either true or false.\nWhen packing, the truish result value of the argument is used. Either 0 or 1\nin the native or standard bool representation will be packed, and any\nnon-zero value will be true when unpacking.
\n
Examples
\n
Note:\nNative byte order examples (designated by the '@' format prefix or\nlack of any prefix character) may not match what the reader's\nmachine produces as\nthat depends on the platform and compiler.
\n
Pack and unpack integers of three different sizes, using big endian\nordering:
Attempt to pack an integer which is too large for the defined field:
\n
$ ucode -lstruct -p 'struct.pack(">h", 99999)'\nType error: Format 'h' requires numeric argument between -32768 and 32767\nIn [-p argument], line 1, byte 24:\n\n `struct.pack(">h", 99999)`\n Near here -------------^\n
\n
Demonstrate the difference between 's' and 'c' format characters:
The ordering of format characters may have an impact on size in native\nmode since padding is implicit. In standard mode, the user is\nresponsible for inserting any desired padding.
\n
Note in the first pack() call below that three NUL bytes were added after\nthe packed '#' to align the following integer on a four-byte boundary.\nIn this example, the output was produced on a little endian machine:
The new() function precompiles the given format string argument and returns\na struct object instance useful for packing and unpacking multiple items\nwithout having to recompute the internal format each time.
\n
Returns an precompiled struct format instance.
\n
Raises a runtime exception if the format string is invalid.
The pack() function creates a byte string containing the argument values\npacked according to the given format string.
\n
Returns the packed string.
\n
Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive or if and invalid\nformat string is provided.
Unpack given byte string according to specified format.
\n
The unpack() function interpretes a byte string according to the given\nformat string and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.
\n
Returns an array of unpacked values.
\n
Raises a runtime exception if the format string is invalid or if an invalid\ninput string or offset value is given.
The unpack() function interpretes a byte string according to the given\nformat instance and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.
\n
Returns an array of unpacked values.
\n
Raises a runtime exception if an invalid input string or offset value is\ngiven.
"}]}
\ No newline at end of file
+{"list":[{"title":"module:core","link":"core","description":"
Builtin functions
\n
The core namespace is not an actual module but refers to the set of\nbuiltin functions and properties available to ucode scripts.
Convert the given input array of byte values to an IP address string.
\n
Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16\nto IPv6 ones. All other lengths are rejected. If any array element is not an\ninteger or exceeds the range 0..255 (inclusive), the array is rejected.
\n
Returns a string containing the formatted IP address.\nReturns null if the input array was invalid.
Calls the given function value with a modified environment.
\n
The given ctx argument is used as this context for the invoked function\nand the given scope value as global environment. Any further arguments are\npassed to the invoked function as-is.
\n
When ctx is omitted or null, the function will get invoked with this\nbeing null.
\n
When scope is omitted or null, the function will get executed with the\ncurrent global environment of the running program. When scope is set to a\ndictionary, the dictionary is used as global function environment.
\n
When the scope dictionary has no prototype, the current global environment\nwill be set as prototype, means the scope will inherit from it.
\n
When a scope prototype is set, it is kept. This allows passing an isolated\n(sandboxed) function scope without access to the global environment.
\n
Any further argument is forwarded as-is to the invoked function as function\ncall argument.
\n
Returns null if the given function value fn is not callable.
\n
Returns the return value of the invoked function in all other cases.
\n
Forwards exceptions thrown by the invoked function.
Converts each given numeric value to a byte and return the resulting string.\nInvalid numeric values or values < 0 result in \\0 bytes, values larger than\n255 are truncated to 255.
\n
Returns a new strings consisting of the given byte values.
Reads the current second and microsecond value of the system clock.
\n
By default, the realtime clock is queried which might skew forwards or\nbackwards due to NTP changes, system sleep modes etc. If a truish value is\npassed as argument, the monotonic system clock is queried instead, which will\nreturn the monotonically increasing time since some arbitrary point in the\npast (usually the system boot time).
\n
Returns a two element array containing the full seconds as the first element\nand the nanosecond fraction as the second element.
\n
Returns null if a monotonic clock value is requested and the system does\nnot implement this clock type.
Filter the array passed as the first argument by invoking the function\nspecified in the second argument for each array item.
\n
If the invoked function returns a truthy result, the item is retained,\notherwise, it is dropped. The filter function is invoked with three\narguments:
\n\n
The array value
\n
The current index
\n
The array being filtered
\n\n
Returns a new array containing only retainted items, in the same order as\nthe input array.
Interacts with the mark and sweep garbage collector of the running ucode\nvirtual machine.
\n
Depending on the given operation string argument, the meaning of argument\nand the function return value differs.
\n
The following operations are defined:
\n
\n
collect - Perform a complete garbage collection cycle, returns true.
\n
start - (Re-)start periodic garbage collection, argument is an optional\ninteger in the range 1..65535 specifying the interval.\nDefaults to 1000 if omitted. Returns true if the periodic GC\nwas previously stopped and is now started or if the interval\nchanged. Returns false otherwise.
\n
stop - Stop periodic garbage collection. Returns true if the periodic\nGC was previously started and is now stopped, false otherwise.
\n
count - Count the amount of active complex object references in the VM\ncontext, returns the counted amount.
\n
\n
If the operation argument is omitted, the default is collect.
Evaluate and include the file at the given path and optionally override the\nexecution scope with the given scope object.
\n
By default, the file is executed within the same scope as the calling\ninclude(), but by passing an object as the second argument, it is possible\nto extend the scope available to the included file.
\n
This is useful to supply additional properties as global variables to the\nincluded code. To sandbox included code, that is giving it only access to\nexplicitly provided properties, the proto() function can be used to create\na scope object with an empty prototype.
Convert the given IP address string to an array of byte values.
\n
IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays\ncontaining 16 intergers. The resulting array can be turned back into IP\naddress strings using the inverse arrtoip() function.
\n
Returns an array containing the address byte values.\nReturns null if the given argument is not a string or an invalid IP.
Parse the given string or resource as JSON and return the resulting value.
\n
If the input argument is a plain string, it is directly parsed as JSON.
\n
If an array, object or resource value is given, this function will attempt to\ninvoke a read() method on it to read chunks of input text to incrementally\nparse as JSON data. Reading will stop if the object's read() method returns\neither null or an empty string.
\n
Throws an exception on parse errors, trailing garbage, or premature EOF.
Return the given epoch timestamp (or now, if omitted) as a dictionary\ncontaining broken-down date and time information according to the local\nsystem timezone.
\n
The resulting dictionary contains the following fields:
\n
\n
sec Seconds (0-60)
\n
min Minutes (0-59)
\n
hour Hours (0-23)
\n
mday Day of month (1-31)
\n
mon Month (1-12)
\n
year Year (>= 1900)
\n
wday Day of the week (1-7, Sunday = 7)
\n
yday Day of the year (1-366, Jan 1st = 1)
\n
isdst Daylight saving time in effect (yes = 1)
\n
\n
Note that in contrast to the underlying localtime(3) C library function,\nthe values for mon, wday, and yday are 1-based, and the year is\n1900-based.
Trim any of the specified characters from the start of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.
Without further arguments, this function returns the byte value of the first\ncharacter in the given string.
\n
If an offset argument is supplied, the byte value of the character at this\nposition is returned. If an invalid index is supplied, the function will\nreturn null. Negative index entries are counted towards the end of the\nstring, e.g. -2 will return the value of the second last character.
\n
Returns the byte value of the character.\nReturns null if the offset is invalid or if the input is not a string.
The print() function writes a string representation of each given argument\nto stdout and returns the amount of bytes written.
\n
String values are printed as-is, integer and double values are printed in\ndecimal notation, boolean values are printed as true or false while\narrays and objects are converted to their JSON representation before being\nwritten to the standard output. The null value is represented by an empty\nstring so print(null) would print nothing. Resource values are printed in\nthe form <type address>, e.g. <fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
\n
Examples:
\n
print(1 != 2); // Will print 'true'\nprint(0xff); // Will print '255'\nprint(2e3); // Will print '2000'\nprint(null); // Will print nothing\nprint({ hello: true, world: 123 }); // Will print '{ "hello": true, "world": 123 }'\nprint([1,2,3]); // Will print '[ 1, 2, 3 ]'\n\nprint(proto({ foo: "bar" }, // Will print 'MyObj'\n { tostring: () => "MyObj" })); // instead of '{ "foo": "bar" }'\n\n
Formats the given arguments according to the given format string and outputs\nthe result to stdout.
\n
Ucode supports a restricted subset of the formats allowed by the underlying\nlibc's printf() implementation, namely it allows the d, i, o, u,\nx, X, e, E, f, F, g, G, c and s conversions.
\n
Additionally, an ucode specific J format is implemented, which causes the\ncorresponding value to be formatted as JSON string. By prefixing the J\nformat letter with a precision specifier, the resulting JSON output will be\npretty printed. A precision of 0 will use tabs for indentation, any other\npositive precision will use that many spaces for indentation while a negative\nor omitted precision specifier will turn off pretty printing.
\n
Other format specifiers such as n or z are not accepted and returned\nverbatim. Format specifiers including * directives are rejected as well.
\n
Returns the number of bytes written to the standard output.
Get or set the prototype of the array or object value val.
\n
When invoked without a second argument, the function returns the current\nprototype of the value in val or null if there is no prototype or if the\ngiven value is neither an object nor an array.
\n
When invoked with a second prototype argument, the given proto value is set\nas the prototype on the array or object in val.
\n
Throws an exception if the given prototype value is not an object.
When invoked with a string value as the first argument, the function acts\nlike include() but captures the output of the included file as a string and\nreturns the captured contents.
\n
The second argument is treated as the scope.
\n
When invoked with a function value as the first argument, render() calls\nthe given function and passes all subsequent arguments to it.
\n
Any output produced by the called function is captured and returned as a\nstring. The return value of the called function is discarded.
Replace occurrences of the specified pattern in the string passed as the\nfirst argument.
\n
\n
The pattern value may be either a regular expression or a plain string.
\n
The replace value may be a function which is invoked for each found pattern\nor any other value which is converted into a plain string and used as\nreplacement.
\n
When an optional limit is specified, substitutions are performed only that\nmany times.
\n
If the pattern is a regular expression and not using the g flag, then\nonly the first occurrence in the string is replaced.
\n
If the g flag is used or if the pattern is not a regular expression, all\noccurrences are replaced.
\n
If the replace value is a callback function, it is invoked with the found\nsubstring as the first and any capture group values as subsequent\nparameters.
\n
If the replace value is a string, specific substrings are substituted\nbefore it is inserted into the result.
Trim any of the specified characters from the end of the string.\nIf the second argument is omitted, trims the characters (space), '\\t',\n'\\r', and '\\n'.
When invoked with two arguments, a signal specification and a signal handler\nvalue, this function configures a new process signal handler.
\n
When invoked with one argument, a signal specification, this function returns\nthe currently configured handler for the given signal.
\n
The signal specification might either be an integer signal number or a string\nvalue containing a signal name (with or without "SIG" prefix). Signal names\nare treated case-insensitively.
\n
The signal handler might be either a callable function value or one of the\ntwo special string values "ignore" and "default". Passing "ignore" will\nmask the given process signal while "default" will restore the operating\nsystems default behaviour for the given signal.
\n
In case a callable handler function is provided, it is invoked at the\nearliest opportunity after receiving the corresponding signal from the\noperating system. The invoked function will receive a single argument, the\nnumber of the signal it is invoked for.
\n
Note that within the ucode VM, process signals are not immediately delivered,\ninstead the VM keeps track of received signals and delivers them to the ucode\nscript environment at the next opportunity, usually before executing the next\nbyte code instruction. This means that if a signal is received while\nperforming a computationally expensive operation in C mode, such as a complex\nregexp match, the corresponding ucode signal handler will only be invoked\nafter that operation concluded and control flow returns to the VM.
\n
Returns the signal handler function or one of the special values "ignore"\nor "default" corresponding to the given signal specification.
\n
Returns null if an invalid signal spec or signal handler was provided.
\n
Returns null if changing the signal action failed, e.g. due to insufficient\npermission, or when attempting to ignore a non-ignorable signal.
Sort the given array according to the given sort function.\nIf no sort function is provided, a default ascending sort order is applied.
\n
The input array is sorted in-place, no copy is made.
\n
The custom sort function is repeatedly called until the entire array is\nsorted. It will receive two values as arguments and should return a value\nlower than, larger than or equal to zero depending on whether the first\nargument is smaller, larger or equal to the second argument respectively.
Split the given string using the separator passed as the second argument\nand return an array containing the resulting pieces.
\n
If a limit argument is supplied, the resulting array contains no more than\nthe given amount of entries, that means the string is split at most\nlimit - 1 times total.
\n
The separator may either be a plain string or a regular expression.
\n
Returns a new array containing the resulting pieces.
Executes the given command, waits for completion, and returns the resulting\nexit code.
\n
The command argument may be either a string, in which case it is passed to\n/bin/sh -c, or an array, which is directly converted into an execv()\nargument vector.
\n
\n
If the program terminated normally, a positive integer holding the\nprogram's exit() code is returned.
\n
If the program was terminated by an uncaught signal, a negative signal\nnumber is returned.
\n
If the optional timeout argument is specified, the program is terminated\nby SIGKILL after that many milliseconds if it doesn't complete within\nthe timeout.
\n
\n
Omitting the timeout argument or passing 0 disables the command timeout.
Performs the inverse operation of localtime() by taking a broken-down date\nand time dictionary and transforming it into an epoch value according to the\nlocal system timezone.
\n
The wday and yday fields of the given date time specification are\nignored. Field values outside of their valid range are internally normalized,\ne.g. October 40th is interpreted as November 9th.
\n
Returns the resulting epoch value or null if the input date time dictionary\nwas invalid or if the date time specification cannot be represented as epoch\nvalue.
Trim any of the specified characters in c from the start and end of str.\nIf the second argument is omitted, trims the characters, (space), \\t,\n\\r, and \\n.
This module provides runtime debug functionality for ucode scripts.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\n\nmemdump("/tmp/dump.txt");\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\n\ndebug.memdump("/tmp/dump.txt");\n
\n
Additionally, the debug module namespace may also be imported by invoking the\nucode interpreter with the -ldebug switch.
\n
Upon loading, the debug module will register a SIGUSR2 signal handler\nwhich, upon receipt of the signal, will write a memory dump of the currently\nrunning program to /tmp/ucode.$timestamp.$pid.memdump. This default\nbehavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED\nenvironment variable to 0 when starting the process. The memory dump signal\nand output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL\nand UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.
The getinfo() function allows querying internal information about the\ngiven ucode value, such as the current reference count, the mark bit state\netc.
\n
Returns a dictionary with value type specific details.
The getlocal() function retrieves information about the specified local\nvariable at the given call stack depth.
\n
The call stack depth specifies the amount of levels up local variables should\nbe queried. A value of 0 refers to this getlocal() function call itself,\n1 to the function calling getlocal() and so on.
\n
The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the given variable.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is a C call.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
The getupval() function retrieves information about the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.
\n
The call stack depth specifies the amount of levels up the function should be\nselected to query associated captured variables for. A value of 0 refers to\nthis getupval() function call itself, 1 to the function calling\ngetupval() and so on.
\n
The variable to query might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the given variable.
\n
Returns null if the given function value is not a closure.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is not a closure.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
This function generates a human readable memory dump of ucode values\ncurrently managed by the running VM which is useful to track down logical\nmemory leaks in scripts.
\n
The file parameter can be either a string value containing a file path, in\nwhich case this function tries to create and write the report file at the\ngiven location, or an already open file handle this function should write to.
\n
Returns true if the report has been written.
\n
Returns null if the file could not be opened or if the handle was invalid.
The setlocal() function manipulates the value of the specified local\nvariable at the given call stack depth.
\n
The call stack depth specifies the amount of levels up local variables should\nbe updated. A value of 0 refers to this setlocal() function call itself,\n1 to the function calling setlocal() and so on.
\n
The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the updated variable.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is a C call.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
The setupval() function manipulates the value of the specified captured\nvariable associated with the given function value or the invoked function at\nthe given call stack depth.
\n
The call stack depth specifies the amount of levels up the function should be\nselected to update associated captured variables for. A value of 0 refers\nto this setupval() function call itself, 1 to the function calling\nsetupval() and so on.
\n
The variable to update might be either specified by name or by its index with\nindex numbers following the source code declaration order.
\n
Returns a dictionary holding information about the updated variable.
\n
Returns null if the given function value is not a closure.
\n
Returns null if the stack depth exceeds the size of the current call stack.
\n
Returns null if the invocation at the given stack depth is not a closure.
\n
Returns null if the given variable name is not found or the given variable\nindex is invalid.
This function captures the current call stack and returns it. The optional\nlevel parameter controls how many calls up the trace should start. It\ndefaults to 1, that is the function calling this traceback() function.
\n
Returns an array of stack trace entries describing the function invocations\nup to the point where traceback() is called.
The fs module provides functions for interacting with the file system.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { readlink, popen } from 'fs';\n\nlet dest = readlink('/sys/class/net/eth0');\nlet proc = popen('ps ww');\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as fs from 'fs';\n\nlet dest = fs.readlink('/sys/class/net/eth0');\nlet proc = fs.popen('ps ww');\n
\n
Additionally, the filesystem module namespace may also be imported by invoking\nthe ucode interpreter with the -lfs switch.
The optional modes argument specifies the access modes which should be\nchecked. A file is only considered accessible if all access modes specified\nin the modes argument are possible.
\n
The following modes are recognized:
\n
\n\n
\n
Mode
\n
Description
\n
\n\n\n
\n
"r"
\n
Tests whether the file is readable.
\n
\n
\n
"w"
\n
Tests whether the file is writable.
\n
\n
\n
"x"
\n
Tests whether the file is executable.
\n
\n
\n
"f"
\n
Tests whether the file exists.
\n
\n\n
\n
Returns true if the given path is accessible or false when it is not.
\n
Returns null if an error occurred, e.g. due to inaccessible intermediate\npath components, invalid path arguments etc.
Changes the owner and group of a file or directory.
\n
The user and group may be specified either as uid or gid number respectively,\nor as a string containing the user or group name, in which case it is\nresolved to the proper uid/gid first.
\n
If either the user or group parameter is omitted or given as -1,\nit is not changed.
\n
Returns true if the ownership change was successful.
\n
Returns null if an error occurred or if a user/group name cannot be\nresolved to a uid/gid value.
Creates a new temporary file, opens it in read and write mode, unlinks it and\nreturns a file handle object referring to the yet open but deleted file.
\n
Upon closing the handle, the associated file will automatically vanish from\nthe system.
\n
The optional path template argument may be used to override the path and name\nchosen for the temporary file. If the path template contains no path element,\n/tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is\nappended to it. The XXXXXX sequence is replaced with a random value\nensuring uniqueness of the temporary file name.
\n
Returns a file handle object referring to the ephemeral file on success.
\n
Returns null if an error occurred, e.g. on insufficient permissions or\ninaccessible directory.
Creates a pipe and returns file handle objects associated with the read- and\nwrite end of the pipe respectively.
\n
Returns a two element array containing both a file handle object open in read\nmode referring to the read end of the pipe and a file handle object open in\nwrite mode referring to the write end of the pipe.
Starts a process and returns a handle representing the executed process.
\n
The handle will be connected to the process stdin or stdout, depending on the\nvalue of the mode argument.
\n
The mode argument may be either "r" to open the process for reading (connect\nto its stdin) or "w" to open the process for writing (connect to its stdout).
\n
The mode character "r" or "w" may be optionally followed by "e" to apply the\nFD_CLOEXEC flag onto the open descriptor.
\n
Returns a process handle referring to the executed process.
Writes the given data to a file, optionally truncated to the given amount\nof bytes.
\n
In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written into the file. The null value is\nrepresented by an empty string so writefile(…, null) would write an empty\nfile. Resource values are written in the form <type address>, e.g.\n<fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
\n
If a file already exists at the given path, it is truncated. If no file\nexists, it is created with default permissions 0o666 masked by the currently\neffective umask.
\n
Returns the number of bytes written.
\n
Returns null if an error occurred, e.g. due to insufficient permissions.
Sets the read position within the open directory handle to the given offset\nvalue. The offset value should be obtained by a previous call to tell() as\nthe specific integer values are implementation defined.
Returns the current read position in the open directory handle which can be\npassed back to the seek() function to return to this position. This is\nmainly useful to read an open directory handle (or specific items) multiple\ntimes.
\n
Returns an integer referring to the current position.
The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.
\n
\n
\n
If length is a number, the method will read the specified number of bytes\nfrom the handle. Reading stops after the given amount of bytes or after\nencountering EOF, whatever comes first.
\n
\n
\n
If length is the string "line", the method will read an entire line,\nterminated by "\\n" (a newline), from the handle. Reading stops at the next\nnewline or when encountering EOF. The returned data will contain the\nterminating newline character if one was read.
\n
\n
\n
If length is the string "all", the method will read from the handle until\nencountering EOF and return the complete contents.
\n
\n
\n
If length is a single character string, the method will read from the\nhandle until encountering the specified character or upon encountering\nEOF. The returned data will contain the terminating character if one was\nread.
In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written. The null value is represented by an\nempty string so file.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
Closes the program handle and awaits program termination.
\n
Upon calling close() on the handle, the program's input or output stream\n(depending on the open mode) is closed. Afterwards, the function awaits the\ntermination of the underlying program and returns its exit code.
\n
\n
\n
When the program was terminated by a signal, the return value will be the\nnegative signal number, e.g. -9 for SIGKILL.
\n
\n
\n
When the program terminated normally, the return value will be the positive\nexit code of the program.
\n
\n
\n
Returns a negative signal number if the program was terminated by a signal.
\n
Returns a positive exit code if the program terminated normally.
The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.
\n
\n
\n
If length is a number, the method will read the specified number of bytes\nfrom the handle. Reading stops after the given amount of bytes or after\nencountering EOF, whatever comes first.
\n
\n
\n
If length is the string "line", the method will read an entire line,\nterminated by "\\n" (a newline), from the handle. Reading stops at the next\nnewline or when encountering EOF. The returned data will contain the\nterminating newline character if one was read.
\n
\n
\n
If length is the string "all", the method will read from the handle until\nencountering EOF and return the complete contents.
\n
\n
\n
If length is a single character string, the method will read from the\nhandle until encountering the specified character or upon encountering\nEOF. The returned data will contain the terminating character if one was\nread.
In case the given data is not a string, it is converted to a string before\nbeing written to the program's stdin. String values are written as-is,\ninteger and double values are written in decimal notation, boolean values are\nwritten as true or false while arrays and objects are converted to their\nJSON representation before being written. The null value is represented by\nan empty string so proc.write(null) would be a no-op. Resource values are\nwritten in the form <type address>, e.g. <fs.file 0x7f60f0981760>.
\n
If resource, array or object values contain a tostring() function in their\nprototypes, then this function is invoked to obtain an alternative string\nrepresentation of the value.
The log module provides bindings to the POSIX syslog functions openlog(),\nsyslog() and closelog() as well as - when available - the OpenWrt\nspecific ulog library functions.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';\n\nopenlog("my-log-ident", LOG_PID, LOG_USER);\nsyslog(LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nimport { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';\n\nulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");\nulog(LOG_INFO, "The current epoch is %d", time());\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as log from 'log';\n\nlog.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);\nlog.syslog(log.LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nlog.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");\nlog.ulog(log.LOG_INFO, "The current epoch is %d", time());\n
\n
Additionally, the log module namespace may also be imported by invoking the\nucode interpreter with the -llog switch.
\n
Constants
\n
The log module declares a number of numeric constants to specify logging\nfacility, priority and option values, as well as ulog specific channels.
\n
Syslog Options
\n
\n\n
\n
Constant Name
\n
Description
\n
\n\n\n
\n
LOG_PID
\n
Include PID with each message.
\n
\n
\n
LOG_CONS
\n
Log to console if error occurs while sending to syslog.
\n
\n
\n
LOG_NDELAY
\n
Open the connection to the logger immediately.
\n
\n
\n
LOG_ODELAY
\n
Delay open until the first message is logged.
\n
\n
\n
LOG_NOWAIT
\n
Do not wait for child processes created during logging.
The openlog() function instructs the program to establish a connection to\nthe system log service and configures the default facility and identification\nfor use in subsequent log operations. It may be omitted, in which case the\nfirst call to syslog() will implicitly call openlog() with a default\nident value representing the program name and a default LOG_USER facility.
\n
The log option argument may be either a single string value containing an\noption name, an array of option name strings or a numeric value representing\na bitmask of LOG_* option constants.
\n
The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.
\n
Returns true if the system openlog() function was invoked.
\n
Returns false if an invalid argument, such as an unrecognized option or\nfacility name, was provided.
This function logs a message to the system logger. The function behaves in a\nsprintf-like manner, allowing the use of format strings and associated\narguments to construct log messages.
\n
If the openlog function has not been called explicitly before, syslog()\nimplicitly calls openlog(), using a default ident and LOG_USER facility\nvalue before logging the message.
\n
If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.
\n
Returns true if a message was passed to the system syslog() function.
\n
Returns false if an invalid priority value or an empty message was given.
The ulog() function outputs the given log message to all configured ulog\nchannels unless the given priority level exceeds the globally configured ulog\npriority threshold. See {@link module:log#ulog_threshold|ulog_threshold()}\nfor details.
\n
The ulog() function is OpenWrt specific and may not be present on other\nsystems. Use syslog() instead for portability to non-OpenWrt environments.
\n
Like syslog(), the function behaves in a sprintf-like manner, allowing the\nuse of format strings and associated arguments to construct log messages.
\n
If the ulog_open() function has not been called explicitly before, ulog()\nimplicitly configures certain defaults, see\n{@link module:log#ulog_open|ulog_open()} for a detailled description.
\n
If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.
\n
Returns true if a message was passed to the underlying ulog() function.
\n
Returns false if an invalid priority value or an empty message was given.
Resets the ulog channels, the default facility and the log ident value to\ndefaults.
\n
In case the "syslog" channel has been configured, the underlying\ncloselog() function will be invoked.
\n
The usage of this function is optional, and usually an explicit ulog teardown\nis not required.
\n
The ulog_close() function is OpenWrt specific and may not be present on\nother systems. Use closelog() in conjunction with syslog() instead for\nportability to non-OpenWrt environments.
This functions configures the ulog mechanism and is analogeous to using the\nopenlog() function in conjuncton with syslog().
\n
The ulog_open() function is OpenWrt specific and may not be present on\nother systems. Use openlog() and syslog() instead for portability to\nnon-OpenWrt environments.
\n
A program may use multiple channels to simultaneously output messages using\ndifferent means. The channel argument may either be a single string value\ncontaining a channel name, an array of channel names or a numeric value\nrepresenting a bitmask of ULOG_* channel constants.
\n
The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.
\n
The default facility value varies, depending on the execution context of the\nprogram. In OpenWrt's preinit boot phase, or when stdout is not connected to\nan interactive terminal, the facility defaults to "daemon" (LOG_DAEMON),\notherwise to "user" (LOG_USER).
\n
Likewise, the default channel is selected depending on the context. During\nOpenWrt's preinit boot phase, the "kmsg" channel is used, for interactive\nterminals the "stdio" one and for all other cases the "syslog" channel\nis selected.
\n
Returns true if ulog was configured.
\n
Returns false if an invalid argument, such as an unrecognized channel or\nfacility name, was provided.
This function configures the application wide log message threshold for log\nmessages emitted with ulog(). Any message with a priority higher (= less\nsevere) than the threshold priority will be discarded. This is useful to\nimplement application wide verbosity settings without having to wrap ulog()\ninvocations into a helper function or guarding code.
\n
When no explicit threshold has been set, LOG_DEBUG is used by default,\nallowing log messages with all known priorities.
\n
The ulog_threshold() function is OpenWrt specific and may not be present on\nother systems. There is no syslog equivalent to this ulog specific threshold\nmechanism.
\n
The priority argument may be either a string value containing a priority name\nor one of the numeric LOG_* priority constants in the module namespace.
\n
Returns true if a threshold was set.
\n
Returns false if an invalid priority value was given.
The math module bundles various mathematical and trigonometrical functions.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
\n
import { pow, rand } from 'math';\n\nlet x = pow(2, 5);\nlet y = rand();\n
\n
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as math from 'math';\n\nlet x = math.pow(2, 5);\nlet y = math.rand();\n
\n
Additionally, the math module namespace may also be imported by invoking the\nucode interpreter with the -lmath switch.
Returns the calculated pseuo-random value. The value is within the range\n0 to RAND_MAX inclusive where RAND_MAX is a platform specific value\nguaranteed to be at least 32767.
\n
The {@link module:math~srand srand()} function sets its argument as the\nseed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are\nrepeatable by calling {@link module:math~srand srand()} with the same\nseed value.
\n
If no seed value is explicitly set by calling\n{@link module:math~srand srand()} prior to the first call to rand(),\nthe math module will automatically seed the PRNG once, using the current\ntime of day in milliseconds as seed value.
This functions seeds the PRNG with the given value and thus affects the\npseudo-random integer sequence produced by subsequent calls to\n{@link module:math~rand rand()}.
\n
Setting the same seed value will result in the same pseudo-random numbers\nproduced by {@link module:math~rand rand()}.
The struct module provides routines for interpreting byte strings as packed\nbinary data.
\n
Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:
Alternatively, the module namespace can be imported\nusing a wildcard import statement:
\n
import * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n
\n
Additionally, the struct module namespace may also be imported by invoking\nthe ucode interpreter with the -lstruct switch.
\n
Format Strings
\n
Format strings describe the data layout when packing and unpacking data.\nThey are built up from format-characters, which specify the type of data\nbeing packed/unpacked. In addition, special characters control the byte\norder, size and alignment.
\n
Each format string consists of an optional prefix character which describes\nthe overall properties of the data and one or more format characters which\ndescribe the actual data values and padding.
\n
Byte Order, Size, and Alignment
\n
By default, C types are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary (according to\nthe rules used by the C compiler).
\n
This behavior is chosen so that the bytes of a packed struct correspond\nexactly to the memory layout of the corresponding C struct.
\n
Whether to use native byte ordering and padding or standard formats depends\non the application.
\n
Alternatively, the first character of the format string can be used to indicate\nthe byte order, size and alignment of the packed data, according to the\nfollowing table:
\n
\n\n
\n
Character
\n
Byte order
\n
Size
\n
Alignment
\n
\n\n\n
\n
@
\n
native
\n
native
\n
native
\n
\n
\n
=
\n
native
\n
standard
\n
none
\n
\n
\n
<
\n
little-endian
\n
standard
\n
none
\n
\n
\n
>
\n
big-endian
\n
standard
\n
none
\n
\n
\n
!
\n
network (= big-endian)
\n
standard
\n
none
\n
\n\n
\n
If the first character is not one of these, '@' is assumed.
\n
Native byte order is big-endian or little-endian, depending on the\nhost system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are\nlittle-endian; IBM z and many legacy architectures are big-endian.
\n
Native size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte order.
\n
Standard size depends only on the format character; see the table in\nthe format-characters section.
\n
Note the difference between '@' and '=': both use native byte order,\nbut the size and alignment of the latter is standardized.
\n
The form '!' represents the network byte order which is always big-endian\nas defined in IETF RFC 1700.
\n
There is no way to indicate non-native byte order (force byte-swapping); use\nthe appropriate choice of '<' or '>'.
\n
Notes:
\n
(1) Padding is only automatically added between successive structure members.\nNo padding is added at the beginning or the end of the encoded struct.
\n
(2) No padding is added when using non-native size and alignment, e.g.\nwith '<', '>', '=', and '!'.
\n
(3) To align the end of a structure to the alignment requirement of a\nparticular type, end the format with the code for that type with a repeat\ncount of zero.
\n
Format Characters
\n
Format characters have the following meaning; the conversion between C and\nucode values should be obvious given their types. The 'Standard size' column\nrefers to the size of the packed value in bytes when using standard size;\nthat is, when the format string starts with one of '<', '>', '!' or\n'='. When using native size, the size of the packed value is platform\ndependent.
\n
\n\n
\n
Format
\n
C Type
\n
Ucode type
\n
Standard size
\n
Notes
\n
\n\n\n
\n
x
\n
pad byte
\n
no value
\n
\n
(7)
\n
\n
\n
c
\n
char
\n
string
\n
1
\n
\n
\n
\n
b
\n
signed char
\n
int
\n
1
\n
(1), (2)
\n
\n
\n
B
\n
unsigned char
\n
int
\n
1
\n
(2)
\n
\n
\n
?
\n
_Bool
\n
bool
\n
1
\n
(1)
\n
\n
\n
h
\n
short
\n
int
\n
2
\n
(2)
\n
\n
\n
H
\n
unsigned short
\n
int
\n
2
\n
(2)
\n
\n
\n
i
\n
int
\n
int
\n
4
\n
(2)
\n
\n
\n
I
\n
unsigned int
\n
int
\n
4
\n
(2)
\n
\n
\n
l
\n
long
\n
int
\n
4
\n
(2)
\n
\n
\n
L
\n
unsigned long
\n
int
\n
4
\n
(2)
\n
\n
\n
q
\n
long long
\n
int
\n
8
\n
(2)
\n
\n
\n
Q
\n
unsigned long long
\n
int
\n
8
\n
(2)
\n
\n
\n
n
\n
ssize_t
\n
int
\n
\n
(3)
\n
\n
\n
N
\n
size_t
\n
int
\n
\n
(3)
\n
\n
\n
e
\n
(6)
\n
double
\n
2
\n
(4)
\n
\n
\n
f
\n
float
\n
double
\n
4
\n
(4)
\n
\n
\n
d
\n
double
\n
double
\n
8
\n
(4)
\n
\n
\n
s
\n
char[]
\n
double
\n
\n
(9)
\n
\n
\n
p
\n
char[]
\n
double
\n
\n
(8)
\n
\n
\n
P
\n
void *
\n
int
\n
\n
(5)
\n
\n
\n
*
\n
char[]
\n
string
\n
\n
(10)
\n
\n\n
\n
Notes:
\n
\n
\n
(1) The '?' conversion code corresponds to the _Bool type defined by\nC99. If this type is not available, it is simulated using a char. In\nstandard mode, it is always represented by one byte.
\n
\n
\n
(2) When attempting to pack a non-integer using any of the integer\nconversion codes, this module attempts to convert the given value into an\ninteger. If the value is not convertible, a type error exception is thrown.
\n
\n
\n
(3) The 'n' and 'N' conversion codes are only available for the native\nsize (selected as the default or with the '@' byte order character).\nFor the standard size, you can use whichever of the other integer formats\nfits your application.
\n
\n
\n
(4) For the 'f', 'd' and 'e' conversion codes, the packed\nrepresentation uses the IEEE 754 binary32, binary64 or binary16 format\n(for 'f', 'd' or 'e' respectively), regardless of the floating-point\nformat used by the platform.
\n
\n
\n
(5) The 'P' format character is only available for the native byte\nordering (selected as the default or with the '@' byte order character).\nThe byte order character '=' chooses to use little- or big-endian\nordering based on the host system. The struct module does not interpret\nthis as native ordering, so the 'P' format is not available.
\n
\n
\n
(6) The IEEE 754 binary16 "half precision" type was introduced in the 2008\nrevision of the IEEE 754 standard. It has a sign bit, a 5-bit exponent\nand 11-bit precision (with 10 bits explicitly stored), and can represent\nnumbers between approximately 6.1e-05 and 6.5e+04 at full precision.\nThis type is not widely supported by C compilers: on a typical machine, an\nunsigned short can be used for storage, but not for math operations. See\nthe Wikipedia page on the half-precision floating-point format for more\ninformation.
\n
\n
\n
(7) When packing, 'x' inserts one NUL byte.
\n
\n
\n
(8) The 'p' format character encodes a "Pascal string", meaning a short\nvariable-length string stored in a fixed number of bytes, given by the\ncount. The first byte stored is the length of the string, or 255,\nwhichever is smaller. The bytes of the string follow. If the string\npassed in to pack() is too long (longer than the count minus 1), only\nthe leading count-1 bytes of the string are stored. If the string is\nshorter than count-1, it is padded with null bytes so that exactly count\nbytes in all are used. Note that for unpack(), the 'p' format\ncharacter consumes count bytes, but that the string returned can never\ncontain more than 255 bytes.
\n
\n
\n
(9) For the 's' format character, the count is interpreted as the length\nof the bytes, not a repeat count like for the other format characters; for\nexample, '10s' means a single 10-byte string mapping to or from a single\nucode byte string, while '10c' means 10 separate one byte character\nelements (e.g., cccccccccc) mapping to or from ten different ucode byte\nstrings. If a count is not given, it defaults to 1. For packing, the\nstring is truncated or padded with null bytes as appropriate to make it\nfit. For unpacking, the resulting bytes object always has exactly the\nspecified number of bytes. As a special case, '0s' means a single,\nempty string (while '0c' means 0 characters).
\n
\n
\n
(10) The * format character serves as wildcard. For pack() it will\nappend the corresponding byte argument string as-is, not applying any\npadding or zero filling. When a repeat count is given, that many bytes of\nthe input byte string argument will be appended at most on pack(),\neffectively truncating longer input strings. For unpack(), the wildcard\nformat will yield a byte string containing the entire remaining input data\nbytes, or - when a repeat count is given - that many bytes of input data\nat most.
\n
\n
\n
A format character may be preceded by an integral repeat count. For example,\nthe format string '4h' means exactly the same as 'hhhh'.
\n
Whitespace characters between formats are ignored; a count and its format\nmust not contain whitespace though.
\n
When packing a value x using one of the integer formats ('b',\n'B', 'h', 'H', 'i', 'I', 'l', 'L',\n'q', 'Q'), if x is outside the valid range for that format, a type\nerror exception is raised.
\n
For the '?' format character, the return value is either true or false.\nWhen packing, the truish result value of the argument is used. Either 0 or 1\nin the native or standard bool representation will be packed, and any\nnon-zero value will be true when unpacking.
\n
Examples
\n
Note:\nNative byte order examples (designated by the '@' format prefix or\nlack of any prefix character) may not match what the reader's\nmachine produces as\nthat depends on the platform and compiler.
\n
Pack and unpack integers of three different sizes, using big endian\nordering:
Attempt to pack an integer which is too large for the defined field:
\n
$ ucode -lstruct -p 'struct.pack(">h", 99999)'\nType error: Format 'h' requires numeric argument between -32768 and 32767\nIn [-p argument], line 1, byte 24:\n\n `struct.pack(">h", 99999)`\n Near here -------------^\n
\n
Demonstrate the difference between 's' and 'c' format characters:
The ordering of format characters may have an impact on size in native\nmode since padding is implicit. In standard mode, the user is\nresponsible for inserting any desired padding.
\n
Note in the first pack() call below that three NUL bytes were added after\nthe packed '#' to align the following integer on a four-byte boundary.\nIn this example, the output was produced on a little endian machine:
The new() function precompiles the given format string argument and returns\na struct object instance useful for packing and unpacking multiple items\nwithout having to recompute the internal format each time.
\n
Returns an precompiled struct format instance.
\n
Raises a runtime exception if the format string is invalid.
The pack() function creates a byte string containing the argument values\npacked according to the given format string.
\n
Returns the packed string.
\n
Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive or if and invalid\nformat string is provided.
Unpack given byte string according to specified format.
\n
The unpack() function interpretes a byte string according to the given\nformat string and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.
\n
Returns an array of unpacked values.
\n
Raises a runtime exception if the format string is invalid or if an invalid\ninput string or offset value is given.
The unpack() function interpretes a byte string according to the given\nformat instance and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.
\n
Returns an array of unpacked values.
\n
Raises a runtime exception if an invalid input string or offset value is\ngiven.
"}]}
\ No newline at end of file
diff --git a/index.html b/index.html
index 6aa10eed..31ac6c8d 100644
--- a/index.html
+++ b/index.html
@@ -1,6 +1,6 @@
ucode - Reference Documentation
The ucode language is a tiny general purpose scripting language featuring a syntax closely resembling ECMAScript. It can be used in a stand-alone manner by using the ucode command line interpreter or embedded into host applications by linking libucode and utilizing its C language API. Additionally, ucode can be invoked in template mode where control flow and expression logic statements are embedded in Jinja-like markup blocks.
Besides aiming for small size, the major design goals of ucode are the ability to trivially read and write JSON data, good embeddability into C applications, template capabilities for output formatting, extensiblity through loadable native extension modules and a straightforward set of built-in functions mimicking those found in the Perl 5 language.
History and Motivation
In spring 2021 it has been decided to rewrite the OpenWrt firewall framework on top of nftables with the goal to replace the then current C application with a kind of preprocessor generating nftables rulesets using a set of templates instead of relying on built-in hardcoded rules like its predecessor.
That decision spurred the development of ucode, initially meant to be a simple template processor solely for the OpenWrt nftables firewall but quickly evolving into a general purpose scripting language suitable for a wider range of system scripting tasks.
Despite OpenWrt predominantly relying on POSIX shell and Lua as system scripting languages already, a new solution was needed to accomodate the needs of the new firewall implementation; mainly the ability to efficiently deal with JSON data and complex data structures such as arrays and dictionaries and the ability to closely interface with OpenWrt's ubus message bus system.
Throughout the design process of the new firewall and its template processor, the following design goals were defined for the ucode scripting language:
Ability to embed code logic fragments such as control flow statements, function calls or arithmetic expressions into plain text templates, using a block syntax and functionality roughly inspired by Jinja templates
Built-in support for JSON data parsing and serialization, without the need for external libraries
Distinct array and object types (compared to Lua's single table datatype)
Distinct integer and float types and guaranteed 64bit integer range
Built-in support for bit operations
Built-in support for (POSIX) regular expressions
A comprehensive set of built-in standard functions, inspired by the core functions found in the Perl 5 interpreter
Staying as close to ECMAScript syntax as possible due to higher developer familiarity and to be able to reuse existing tooling such as editor syntax highlighting
Bindings for all relevant Linux and OpenWrt APIs, such as ubus, uci, uloop, netlink etc.
Procedural, synchronous programming flow
Very small executable size (the interpreter and runtime is currently around 64KB on ARM Cortex A9)
Embeddability into C host applications
Summarized, ucode can be described as synchronous ECMAScript without the object oriented standard library.
Installation
OpenWrt
In OpenWrt 22.03 and later, ucode should already be preinstalled. If not, it can be installed via the package manager, using the opkg install ucode command.
MacOS
To build on MacOS, first install cmake and json-c via Homebrew, then clone the ucode repository and execute cmake followed by make:
The ucode language is a tiny general purpose scripting language featuring a syntax closely resembling ECMAScript. It can be used in a stand-alone manner by using the ucode command line interpreter or embedded into host applications by linking libucode and utilizing its C language API. Additionally, ucode can be invoked in template mode where control flow and expression logic statements are embedded in Jinja-like markup blocks.
Besides aiming for small size, the major design goals of ucode are the ability to trivially read and write JSON data, good embeddability into C applications, template capabilities for output formatting, extensiblity through loadable native extension modules and a straightforward set of built-in functions mimicking those found in the Perl 5 language.
History and Motivation
In spring 2021 it has been decided to rewrite the OpenWrt firewall framework on top of nftables with the goal to replace the then current C application with a kind of preprocessor generating nftables rulesets using a set of templates instead of relying on built-in hardcoded rules like its predecessor.
That decision spurred the development of ucode, initially meant to be a simple template processor solely for the OpenWrt nftables firewall but quickly evolving into a general purpose scripting language suitable for a wider range of system scripting tasks.
Despite OpenWrt predominantly relying on POSIX shell and Lua as system scripting languages already, a new solution was needed to accomodate the needs of the new firewall implementation; mainly the ability to efficiently deal with JSON data and complex data structures such as arrays and dictionaries and the ability to closely interface with OpenWrt's ubus message bus system.
Throughout the design process of the new firewall and its template processor, the following design goals were defined for the ucode scripting language:
Ability to embed code logic fragments such as control flow statements, function calls or arithmetic expressions into plain text templates, using a block syntax and functionality roughly inspired by Jinja templates
Built-in support for JSON data parsing and serialization, without the need for external libraries
Distinct array and object types (compared to Lua's single table datatype)
Distinct integer and float types and guaranteed 64bit integer range
Built-in support for bit operations
Built-in support for (POSIX) regular expressions
A comprehensive set of built-in standard functions, inspired by the core functions found in the Perl 5 interpreter
Staying as close to ECMAScript syntax as possible due to higher developer familiarity and to be able to reuse existing tooling such as editor syntax highlighting
Bindings for all relevant Linux and OpenWrt APIs, such as ubus, uci, uloop, netlink etc.
Procedural, synchronous programming flow
Very small executable size (the interpreter and runtime is currently around 64KB on ARM Cortex A9)
Embeddability into C host applications
Summarized, ucode can be described as synchronous ECMAScript without the object oriented standard library.
Installation
OpenWrt
In OpenWrt 22.03 and later, ucode should already be preinstalled. If not, it can be installed via the package manager, using the opkg install ucode command.
MacOS
To build on MacOS, first install cmake and json-c via Homebrew, then clone the ucode repository and execute cmake followed by make: