27. The rest

Namespace 9.0::

Description

Pike 9.0 compatibility.

The symbols in this namespace will appear in programs that use #pike 9.0 or lower.


Inherit

inherit 9.1:: :

Namespace cpp::

Description

Pike has a builtin C-style preprocessor. It works similar to the ANSI-C preprocessor but has a few extra features. These and the default set of preprocessor macros are described here.

The preprocessor is usually accessed via MasterObject->compile_file() or MasterObject->compile_string(), but may be accessed directly by calling cpp().

See also

compile(), cpp(), CompilerEnvironment.CPP

Namespace predef::

Description

This is the default namespace and contains lots of global symbols.


Typedefutf8_string

typedef __attribute__("utf8_string", string(8bit)) utf8_string

Description

String containing UTF-8 encoded data.

This is similar to a string(8bit), but allows the compiler to keep track of whether strings are UTF-8 or not.

See also

string_to_utf8(), utf8_to_string()


Typedefzero

typedefint(0)zero

Description

Zero datatype.


ConstantUNDEFINED

constantUNDEFINED

Description

The undefined value; ie a zero for which zero_type() returns 1.


Constant__null_program

constant__null_program

Description

Program used internally by the compiler to create objects that are later modified into instances of the compiled program by the compiler.

See also

__placeholder_object


Constant__placeholder_object

constant__placeholder_object

Description

Object used internally by the compiler.

See also

__null_program


Constantsprintf_args

constantsprintf_args

Description

Type constant used for typing extra arguments that are sent to sprintf().

See also

strict_sprintf_format, sprintf_format, sprintf()


Constantsprintf_format

constantsprintf_format

Description

Type constant used for typing arguments that are optionally sent to sprintf() depending on the presence of extra arguments.

See also

strict_sprintf_format, sprintf_args, sprintf()


Constantsprintf_result

constantsprintf_result

Description

Type constant used for typing the return value from sprintf().

See also

strict_sprintf_format, sprintf_format, sprintf()


Constantstrict_sprintf_format

constantstrict_sprintf_format

Description

Type constant used for typing arguments that are always sent to sprintf() regardless of the presence of extra arguments.

See also

sprintf_format, sprintf_args, sprintf()


Constantthis

constantthis

Description

Builtin read only variable that evaluates to the current object.

See also

this_program, this_object()


Constantthis_function

constantthis_function

Description

Builtin constant that evaluates to the current function.

See also

continue::this_function, this, this_object()


Constantthis_program

constantthis_program

Description

Builtin constant that evaluates to the current program.

See also

this, this_object()


MethodProxyFactory

programProxyFactory(programp)

Description

Create a class that acts as a proxy for the specified program.

Parameter p

Program to generate a proxy for.

The generated class will have the same symbols (public and private) with the same types as in p, where accesses to these will proxy the access to the same symbol in the proxied (aka wrapped) object. With the following exceptions:

protected void create(object(p) obj)

Initialize the object to act as a proxy for obj.

_sprintf(int c, mapping|void params)

Special case for c == 'O', where it will return sprintf("%O(%O)", this_program, obj), and otherwise proxy the call.

void _destruct()/void destroy()

These lfuns will not be present as the act of them being proxied would likely confuse the proxied object.

Note

The same proxy class will be returned if this function is called with the same program multiple times.


Method_Static_assert

void_Static_assert(intconstant_expression, stringconstant_message)

Description

Perform a compile-time assertion check.

If constant_expression is false, a compiler error message containing constant_message will be generated.

Note

Note that the function call compiles to the null statement, and thus does not affect the run-time.

See also

cpp::static_assert


Method__automap__

array__automap__(function(:void) fun, mixed ... args)

Description

Automap execution function.

Parameter fun

Function to call for each of the mapped arguments.

Parameter args

Arguments for fun. Either

Builtin.automap_marker

Wrapper for an array to loop over. All of the arrays will be looped over in parallel.

mixed

All other arguments will be held constant during the automap, and sent as is to fun.

Note

This function is used by the compiler to implement the automap syntax, and should in normal circumstances never be used directly.

It may however show up during module dumping and in backtraces.

Note

It is an error not to have any Builtin.automap_markers in args.

See also

Builtin.automap_marker, map()


Method__cast

mixed__cast(mixedval, string|typetype_name)

Description

Cast val to the type indicated by type_name.

See also

lfun::cast()


Method__empty_program

program__empty_program(int|voidline, string|voidfile)

Parameter line

Optional line number of file where the program to be compiled definition starts.

Parameter file

Optional file name where the program to be compiled is defined.

Returns

Returns a virgin (ie empty) program suitable as the target argument to PikeCompiler().

See also

__null_program, PikeCompiler, compile_string()


Method__handle_sprintf_format

type__handle_sprintf_format(stringattr, string|zerofmt, typearg_type, type|zerocont_type, mappingstate)

Description

Type attribute handler for "sprintf_format".

Parameter attr

Attribute to handle, either "sprintf_format" or "strict_sprintf_format".

Parameter fmt

Sprintf-style formatting string to generate type information from.

Parameter arg_type

Declared type of the fmt argument (typically string).

Parameter cont_type

Continuation function type after the fmt argument. This is scanned for the type attribute "sprintf_args" to determine where the remaining arguments to sprintf() will come from.

Parameter state

State mapping.

This function is typically called from PikeCompiler()->apply_attribute_constant() and is used to perform stricter compile-time argument checking of sprintf()-style functions.

It currently implements two operating modes depending on the value of attr:

"strict_sprintf_format"

The formatting string fmt is known to always be passed to sprintf().

"sprintf_format"

The formatting string fmt is passed to sprintf() only if there are "sprintf_args".

Returns

Returns cont_type with "sprintf_args" replaced by the arguments required by the fmt formatting string, and "sprintf_result" replaced by the resulting string type.

See also

PikeCompiler()->apply_attribute_constant(), sprintf()


Method__parse_pike_type

string(8bit)__parse_pike_type(string(8bit)t)


Method_gdb_breakpoint

void_gdb_breakpoint()

Description

This function only exists so that it is possible to set a gdb breakpoint on the function pike_gdb_breakpoint.


Methodabs

floatabs(floatf)
intabs(intf)
objectabs(objectf)

Description

Return the absolute value for f. If f is an object it must implement lfun::`< and unary lfun::`-.


Methodacos

floatacos(int|floatf)

Description

Return the arcus cosine value for f. The result will be in radians.

See also

cos(), asin()


Methodacosh

floatacosh(int|floatf)

Description

Return the hyperbolic arcus cosine value for f.

See also

cosh(), asinh()


Methodadd_constant

voidadd_constant(stringname, mixedvalue)
voidadd_constant(stringname)

Description

Add a new predefined constant.

This function is often used to add builtin functions. All programs compiled after the add_constant() function has been called can access value by the name name.

If there is a constant called name already, it will be replaced by by the new definition. This will not affect already compiled programs.

Calling add_constant() without a value will remove that name from the list of constants. As with replacing, this will not affect already compiled programs.

See also

all_constants()


Methodadd_include_path

voidadd_include_path(stringtmp)

Description

Add a directory to search for include files.

This is the same as the command line option -I.

Note

Note that the added directory will only be searched when using < > to quote the included file.

See also

remove_include_path()


Methodadd_module_path

voidadd_module_path(stringpath, string|voidsubpath)

Description

Add a directory to search for modules.

This is the same as the command line option -M.

See also

remove_module_path()

Parameter path

a string containing a path to search for Pike modules. May be a directory, or a path to a ZIP archive. If a ZIP archive path is provided, modules will be loaded from a directory, "modules" within the ZIP archive (see the subpath argument).

Parameter subpath

if path is a ZIP archive, this argument will determine the path within the archive to be searched.


Methodadd_program_path

voidadd_program_path(stringtmp)

Description

Add a directory to search for programs.

This is the same as the command line option -P.

See also

remove_program_path()


Methodaggregate

arrayaggregate(mixed ... elements)

Description

Construct an array with the arguments as indices.

This function could be written in Pike as:

array aggregate(mixed ... elems){return elems;}
Note

Arrays are dynamically allocated there is no need to declare them like int a[10]=allocate(10); (and it isn't possible either) like in C, just array(int) a=allocate(10); will do.

See also

sizeof(), arrayp(), allocate()


Methodaggregate_mapping

mappingaggregate_mapping(mixed ... elems)

Description

Construct a mapping.

Groups the arguments together two and two in key-index pairs and creates a mapping of those pairs. Generally, the mapping literal syntax is handier: ([ key1:val1, key2:val2, ... ])

See also

sizeof(), mappingp(), mkmapping()


Methodaggregate_multiset

multisetaggregate_multiset(mixed ... elems)

Description

Construct a multiset with the arguments as indices. The multiset will not contain any values. This method is most useful when constructing multisets with map or similar; generally, the multiset literal syntax is handier: (<elem1, elem2, ...>) With it, it's also possible to construct a multiset with values: (<index1: value1, index2: value2, ...>)

See also

sizeof(), multisetp(), mkmultiset()


Methodall_constants

mapping(string:mixed) all_constants()

Description

Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.

See also

add_constant()


Methodallocate

arrayallocate(intsize)
arrayallocate(intsize, mixedinit)

Description

Allocate an array of size elements. If init is specified then each element is initialized by copying that value recursively.

See also

sizeof(), aggregate(), arrayp()


Methodarray_sscanf

arrayarray_sscanf(stringdata, stringformat)

Description

This function works just like sscanf(), but returns the matched results in an array instead of assigning them to lvalues. This is often useful for user-defined sscanf strings.

See also

sscanf(), `/()


Methodasin

floatasin(int|floatf)

Description

Return the arcus sine value for f. The result will be in radians.

See also

sin(), acos()


Methodasinh

floatasinh(int|floatf)

Description

Return the hyperbolic arcus sine value for f.

See also

sinh(), acosh()


Methodatan

floatatan(int|floatf)

Description

Returns the arcus tangent value for f. The result will be in radians.

See also

tan(), asin(), acos(), atan2()


Methodatan2

floatatan2(floatf1, floatf2)

Description

Returns the arcus tangent value for f1/f2, and uses the signs of f1 and f2 to determine the quadrant. The result will be in radians.

See also

tan(), asin(), acos(), atan()


Methodatanh

floatatanh(int|floatf)

Description

Returns the hyperbolic arcus tangent value for f.

See also

tanh(), asinh(), acosh()


Methodatomic_get_set

mixedatomic_get_set(mapping|objectmap, mixedkey, mixedval)
mixedatomic_get_set(arrayarr, intindex, mixedval)

Description

Replace atomically the value for a key in a mapping or array.

Parameter map
Parameter arr

Mapping or array to alter.

Parameter key
Parameter index

Key or index to change the value for.

Parameter val

Value to change to. If value is UNDEFINED and map is a mapping this function function behaves exactly as m_delete(map, key).

Returns

Returns the previous value for key. If map is a mapping and there was no previous value UNDEFINED is returned.

If map is an object lfun::_m_replace() will be called in it.

See also

m_delete()


Methodawait

mixedawait(Concurrent.Futurefuture)

Description

Stop execution of the current restartable function for now. Resume when the future completes.

Returns

Evaluates to the result of the future if it succeeds.

Throws

Throws an error if the future failed.

Calling this special form is similar to the expression:

(future->on_await(continue::this_function), yield())
Note

Use of this from a non-restartable functions causes a compilation warning and falls back to calling future->get(). This will thus then perform a wait blocking the current thread.

Note

No checks that the future has actually completed are performed. It is assumed that nothing else will call the restartable function during the wait.

See also

Concurrent.Future()->get(), yield(), continue::this_function, Restartable functions


Methodbasetype

stringbasetype(mixedx)

Description

Same as sprintf("%t",x);

See also

sprintf()


Methodceil

floatceil(int|floatf)

Description

Return the closest integer value greater or equal to f.

Note

ceil() does not return an int, merely an integer value stored in a float.

See also

floor(), round()


Methodclone_to

objectclone_to(objectplaceholder, programp, mixed ... p_args)

Description

Coerce a placeholder object into a clone of a program.

Parameter placeholder

Clone of __null_program to alter.

Parameter p

Program to coerce the object to be a clone of.

Parameter p_args

Arguments to pass to lfun::create() in p.

Returns

Returns placeholder after successful coercion.

Note

placeholder may also already be a clone of [p], in which case this operation is a no-op.

See also

__null_program


Methodcolumn

arraycolumn(arraydata, mixedindex)

Description

Extract a column from a two-dimensional array.

This function is exactly equivalent to:

map(data,lambda(mixed x,mixed y){return x[y];}, index)

Except of course it is a lot shorter and faster. That is, it indices every index in the array data on the value of the argument index and returns an array with the results.

See also

rows()


Methodcompile

programcompile(stringsource, CompilationHandler|voidhandler, int|voidmajor, int|voidminor, program|voidtarget, object|voidplaceholder)

Description

Compile a string to a program.

This function takes a piece of Pike code as a string and compiles it into a clonable program.

The optional argument handler is used to specify an alternative error handler. If it is not specified the current master object will be used.

The optional arguments major and minor are used to tell the compiler to attempt to be compatible with Pike major.minor.

Note

Note that source must contain the complete source for a program. It is not possible to compile a single expression or statement.

Also note that compile() does not preprocess the program. To preprocess the program you can use compile_string() or call the preprocessor manually by calling cpp().

See also

compile_string(), compile_file(), cpp(), master(), CompilationHandler, DefaultCompilerEnvironment


Methodcompile_file

programcompile_file(stringfilename, CompilationHandler|voidhandler, void|programp, void|objecto)

Description

Compile the Pike code contained in the file filename into a program.

This function will compile the file filename to a Pike program that can later be instantiated. It is the same as doing compile_string(Stdio.read_file(filename), filename).

See also

compile(), compile_string(), cpp()


Methodcompile_string

programcompile_string(stringsource, string|voidfilename, CompilationHandler|voidhandler, void|programp, void|objecto, int|voidshow_if_constant_errors)

Description

Compile the Pike code in the string source into a program. If filename is not specified, it will default to "-".

Functionally equal to compile(cpp(sourcefilename)).

See also

compile(), cpp(), compile_file()


Methodcopy_value

mixedcopy_value(mixedvalue)

Description

Copy a value recursively.

If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed.

The resulting value will always be equal to the copied (as tested with the function equal()), but they may not the the same value (as tested with `==()).

See also

equal()


Methodcos

floatcos(int|floatf)

Description

Return the cosine value for f. f should be specified in radians.

See also

acos(), sin(), tan()


Methodcosh

floatcosh(int|floatf)

Description

Return the hyperbolic cosine value for f.

See also

acosh(), sinh(), tanh()


Methodcpp

stringcpp(stringdata, mapping|string|voidcurrent_file, int|string|voidcharset, object|voidhandler, void|intcompat_major, void|intcompat_minor, void|intpicky_cpp)

Description

Run a string through the preprocessor.

Preprocesses the string data with Pike's builtin ANSI-C look-alike preprocessor. If the current_file argument has not been specified, it will default to "-". charset defaults to "ISO-10646".

If the second argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are recognized:

"current_file" : string

Name of the current file. It is used for generating #line directives and for locating include files.

"charset" : int|string

Charset to use when processing data.

"handler" : object

Compilation handler.

"compat_major" : int

Sets the major pike version used for compat handling.

"compat_minor" : int

Sets the minor pike version used for compat handling.

"picky_cpp" : int

Generate more warnings.

"keep_comments" : int

This option keeps cpp() from removing comments. Useful in combination with the prefix feature below.

"prefix" : string

If a prefix is given, only prefixed directives will be processed. For example, if the prefix is "foo", then #foo_ifdef COND and foo___LINE__ would be processed, #ifdef COND and __LINE__ would not.

"predefines" : mapping(string:mixed)

Mapping of predefined macros in addition to those returned by CPP()->get_predefines().

See also

compile()


Methodctime

stringctime(inttimestamp)

Description

Convert the output from a previous call to time() into a readable string containing the current year, month, day and time.

Like localtime, this function might throw an error if the ctime(2) call failed on the system. It's platform dependent what time ranges that function can handle, e.g. Windows doesn't handle a negative timestamp.

See also

strftime(), time(), localtime(), gmtime(), mktime()


Methoddecode_value

mixeddecode_value(string(8bit)coded_value, void|Codec|int(-1)codec)

Description

Decode a value from the string coded_value.

Parameter coded_value

Value to decode.

Parameter codec

Codec to use when encoding objects and programs.

Parameter trace

String.Buffer to contain a readable dump of the value.

Parameter debug

Debug level. Only available when the runtime has been compiled --with-rtl-debug.

This function takes a string created with encode_value() or encode_value_canonic() and converts it back to the value that was coded.

If codec is specified, it's used as the codec for the decode. If none is specified, then one is instantiated through master()->Decoder(). As a compatibility fallback, the master itself is used if it has no Decoder class. If codec is the special value -1, then decoding of types, functions, programs and objects is disabled.

Note

Decoding a coded_value that you have not generated yourself is a security risk that can lead to execution of arbitrary code, unless codec is specified as -1.

See also

encode_value(), encode_value_canonic()


Methoddelay

voiddelay(int|floats)

Description

This function makes the thread stop for s seconds.

Only signal handlers can interrupt the sleep. Other callbacks are not called during delay. Beware that this function uses busy-waiting to achieve the highest possible accuracy.

See also

signal(), sleep()


Methoddescribe_backtrace

stringdescribe_backtrace(mixedtrace, void|intlinewidth)

Description

Return a readable message that describes where the backtrace trace was made (by backtrace).

It may also be an error object or array (typically caught by a catch), in which case the error message also is included in the description.

Pass linewidth -1 to disable wrapping of the output.

See also

backtrace(), describe_error(), catch(), throw()


Methoddescribe_error

stringdescribe_error(mixederr)

Description

Return the error message from an error object or array (typically caught by a catch). The type of the error is checked, hence err is declared as mixed and not object|array.

If an error message couldn't be obtained, a fallback message describing the failure is returned. No errors due to incorrectness in err are thrown.

See also

describe_backtrace(), get_backtrace


Methoddestruct

booldestruct(void|objecto)

Description

Mark an object as destructed.

Calls o->_destruct(), and then clears all variables in the object. If no argument is given, the current object is destructed.

All pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible.

Returns

Returns 1 if o has an lfun::_destruct() that returned 1 and inhibited destruction.


Methodencode_value

string(8bit)encode_value(mixedvalue, Codec|voidcodec)
string(8bit)encode_value(mixedvalue, Codec|voidcodec, String.Buffertrace)
string(8bit)encode_value(mixedvalue, Codec|voidcodec, int(0..)debug)

Description

Code a value into a string.

Parameter value

Value to encode.

Parameter codec

Codec to use when encoding objects and programs.

Parameter trace

String.Buffer to contain a readable dump of the value.

Parameter debug

Debug level. Only available when the runtime has been compiled --with-rtl-debug.

This function takes a value, and converts it to a string. This string can then be saved, sent to another Pike process, packed or used in any way you like. When you want your value back you simply send this string to decode_value() and it will return the value you encoded.

Almost any value can be coded, mappings, floats, arrays, circular structures etc.

If codec is specified, it's used as the codec for the encode. If none is specified, then one is instantiated through master()->Encoder(). As a compatibility fallback, the master itself is used if it has no Encoder class.

If codec->nameof(o) returns UNDEFINED for an object, val = o->encode_object(o) will be called. The returned value will be passed to o->decode_object(o, val) when the object is decoded.

Note

When only simple types like int, floats, strings, mappings, multisets and arrays are encoded, the produced string is very portable between pike versions. It can at least be read by any later version.

The portability when objects, programs and functions are involved depends mostly on the codec. If the byte code is encoded, i.e. when Pike programs are actually dumped in full, then the string can probably only be read by the same pike version.

See also

decode_value(), sprintf(), encode_value_canonic()


Methodencode_value_canonic

string(8bit)encode_value_canonic(mixedvalue, object|voidcodec)
string(8bit)encode_value_canonic(mixedvalue, object|voidcodec, String.buffertrace)
string(8bit)encode_value_canonic(mixedvalue, object|voidcodec, int(0..)debug)

Description

Code a value into a string on canonical form.

Parameter value

Value to encode.

Parameter codec

Codec to use when encoding objects and programs.

Parameter trace

String.Buffer to contain a readable dump of the value.

Parameter debug

Debug level. Only available when the runtime has been compiled --with-rtl-debug.

Takes a value and converts it to a string on canonical form, much like encode_value(). The canonical form means that if an identical value is encoded, it will produce exactly the same string again, even if it's done at a later time and/or in another Pike process. The produced string is compatible with decode_value().

Note

Note that this function is more restrictive than encode_value() with respect to the types of values it can encode. It will throw an error if it can't encode to a canonical form.

See also

encode_value(), decode_value()


Methodenumerate

array(int) enumerate(intn)
arrayenumerate(intn, void|mixedstep, void|mixedstart, void|function(:void) operator)

Description

Create an array with an enumeration, useful for initializing arrays or as first argument to map() or foreach().

The defaults are: step = 1, start = 0, operator = `+

Advanced use

The resulting array is calculated like this:

array enumerate(int n,mixed step,mixed start,function operator){array res = allocate(n);for(int i=0; i < n; i++){
    res[i]= start;
    start = operator(start, step);}return res;}
See also

map(), foreach()


Methodequal

intequal(mixeda, mixedb)

Description

This function checks if the values a and b are equivalent.

Returns

If either of the values is an object the (normalized) result of calling lfun::_equal() will be returned.

Returns 1 if both values are false (zero, destructed objects, prototype functions, etc).

Returns 0 (zero) if the values have different types.

Otherwise depending on the type of the values:

int

Returns the same as a == b.

array

The contents of a and b are checked recursively, and if all their contents are equal and in the same place, they are considered equal.

Note that for objects this case is only reached if neither a nor b implements lfun::_equal().

type

Returns (a <= b) && (b <= a).

See also

copy_value(), `==()


Methoderror

voiderror(sprintf_formatf, sprintf_args ... args)

Description

Throws an error. A more readable version of the code throw( ({ sprintf(f, @args), backtrace() }) ).


Methodexp

floatexp(float|intf)

Description

Return the natural exponential of f. log( exp( x ) ) == x as long as exp(x) doesn't overflow an int.

See also

pow(), log()


Methodfilter

mixedfilter(mixedarr, void|mixedfun, mixed ... extra)

Description

Filters the elements in arr through fun.

Parameter arr

arr is treated as a set of elements to be filtered, as follows:

array

Each element is filtered with fun. The return value is of the same type as arr and it contains the elements that fun accepted. fun is applied in order to each element, and that order is retained between the kept elements.

mapping

The values are filtered with fun, and the index/value pairs it accepts are kept in the returned mapping.

program

The program is treated as a mapping containing the identifiers that are indexable from it and their values.

object

If there is a lfun::cast method in the object, it's called to try to cast the object to an array, a mapping, or a multiset, in that order, which is then filtered as described above.

Parameter fun

Unless something else is mentioned above, fun is used as filter like this:

array

When both arr and fun are arrays, they should have the same lengths. In this case, the elements in arr are kept where the corresponding positions in fun are nonzero.

function(mixed ... :mixed)

fun is called for each element. It gets the current element as the first argument and extra as the rest. The element is kept if fun returns true, otherwise it's filtered out.

object

The object is used as a function like above, i.e. the lfun::`() method in it is called.

multiset

fun is indexed with each element. The element is kept if the result is nonzero, otherwise it's filtered out.

zero|void

Each element that is callable is called with extra as arguments. The element is kept if the result of the call is nonzero, otherwise it's filtered out. Elements that aren't callable are also filtered out.

string

Each element is indexed with the given string. If the result of that is zero then the element is filtered out, otherwise the result is called with extra as arguments. The element is kept if the return value is nonzero, otherwise it's filtered out.

This is typically used when arr is a collection of objects, and fun is the name of some predicate function in them.

Note

The function is never destructive on arr.

See also

map(), foreach()


Methodfloor

floatfloor(int|floatf)

Description

Return the closest integer value less or equal to f.

Note

floor() does not return an int, merely an integer value stored in a float.

See also

ceil(), round()


Methodget_active_compilation_handler

CompilationHandlerget_active_compilation_handler()

Description

Returns the currently active compilation compatibility handler, or 0 (zero) if none is active.

Note

This function should only be used during a call of compile().

See also

get_active_error_handler(), compile(), master()->get_compilation_handler(), CompilationHandler


Methodget_active_compiler

CompilerEnvironment.PikeCompiler|zeroget_active_compiler()

Description

Returns the most recent of the currently active pike compilers, or UNDEFINED if none is active.

Note

This function should only be used during a call of compile().

See also

get_active_error_handler(), compile(), master()->get_compilation_handler(), CompilationHandler


Methodget_active_error_handler

CompilationHandlerget_active_error_handler()

Description

Returns the currently active compilation error handler (second argument to compile()), or 0 (zero) if none is active.

Note

This function should only be used during a call of compile().

See also

get_active_compilation_handler(), compile(), CompilationHandler


Methodget_all_groups

array(array(int|string|array(string))) get_all_groups()

Description

Returns an array of arrays with all groups in the system groups source. Each element in the returned array has the same structure as in getgrent function.

Note

The groups source is system dependant. Refer to your system manuals for information about how to set the source.

Returns
Array
array(int|string|array(string)) 0..

Array with info about the group

See also

getgrent()


Methodget_all_users

array(array(int|string)) get_all_users()

Description

Returns an array with all users in the system.

Returns

An array with arrays of userinfo as in getpwent.

See also

getpwent()getpwnam()getpwuid()


Methodget_backtrace

arrayget_backtrace(object|arrayerr)

Description

Return the backtrace array from an error object or array (typically caught by a catch), or zero if there is none. Errors are thrown on if there are problems retrieving the backtrace.

See also

describe_backtrace(), describe_error()


Methodget_groups_for_user

array(int) get_groups_for_user(int|stringuser)

Description

Gets all groups which a given user is a member of.

Parameter user

UID or loginname of the user

Returns
Array
array0..

Information about all the users groups

See also

get_all_groups()getgrgid()getgrnam()getpwuid()getpwnam()


Methodget_iterator

Iteratorget_iterator(function(:void)|object|array|mapping|multiset|stringdata, mixed ... args)

Description

Creates and returns a canonical iterator for data.

Returns
data can have any of the following types:
object

If data is an object with lfun::_get_iterator defined then that function will be called with the arguments args to create the iterator.

If data is an object that lacks lfun::_get_iterator then it is assumed to already be an iterator object. In this case args will be ignored (note this behavior may be changed).

The iterator object is then checked whether it has lfun::_iterator_next() in which case it will simply be returned. Otherwise an attempt to wrap it in a CompatIterator will be performed.

array

If data is an array, an Array.Iterator object will be returned.

function(:void)

If data is a function, a Function.Iterator object will be returned.

mapping

If data is a mapping, a Mapping.Iterator object will be returned

multiset

If data is a multiset, a Multiset.Iterator object will be returned

string

If data is a string, a String.Iterator object will be returned

Note

This function is used by foreach to get an iterator for an object.

See also

Iterator, lfun::_get_iterator


Methodgetenv

mapping(string:string) getenv(void|intforce_update)

Description

Queries the environment variables.

Parameter force_update

A cached copy of the real environment is kept to make this function quicker. If the optional flag force_update is nonzero then the real environment is queried and the cache is updated from it. That can be necessary if the environment changes through other means than putenv, typically from a C-level library.

Returns

Returns the whole environment as a mapping. Destructive operations on the mapping will not affect the internal environment representation.

Variable names and values cannot be wide strings nor contain '\0' characters. Variable names also cannot contain '=' characters.

Note

On NT the environment variable name is case insensitive.

See also

putenv()


Methodgetenv

stringgetenv(stringvarname, void|intforce_update)

Description

Query the value of a specific environment variable.

Parameter varname

Environment variable to query.

Parameter force_update

A cached copy of the real environment is kept to make this function quicker. If the optional flag force_update is nonzero then the real environment is queried and the cache is updated from it. That can be necessary if the environment changes through other means than putenv, typically from a C-level library.

Returns

Returns the value of the environment variable varname if it exists, and 0 (zero) otherwise.

Variable names and values cannot be wide strings nor contain '\0' characters. Variable names also cannot contain '=' characters.

Note

On NT the environment variable name is case insensitive.

See also

putenv()


Methodgetgrgid

array(int|string|array(string)) getgrgid(intgid)

Description

Get the group entry for the group with the id gid using the systemfunction getgrid(3).

Parameter gid

The id of the group

Returns

An array with the information about the group

Array
string0

Group name

string1

Group password (encrypted)

int2

ID of the group

array3..

Array with UIDs of group members

See also

getgrent()getgrnam()


Methodgetgrnam

array(int|string|array(string)) getgrnam(stringstr)

Description

Get the group entry for the group with the name str using the systemfunction getgrnam(3).

Parameter str

The name of the group

Returns

An array with the information about the group

Array
string0

Group name

string1

Group password (encrypted)

int2

ID of the group

array3..

Array with UIDs of group members

See also

getgrent()getgrgid()


Methodgethrdtime

intgethrdtime(void|intnsec)

Description

Return the high resolution real time spent with threads disabled since the Pike interpreter was started. The time is normally returned in microseconds, but if the optional argument nsec is nonzero it's returned in nanoseconds.

Note

The actual accuracy on many systems is significantly less than microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION.

See also

_disable_threads(), gethrtime()


Methodgethrtime

intgethrtime(void|intnsec)

Description

Return the high resolution real time since some arbitrary event in the past. The time is normally returned in microseconds, but if the optional argument nsec is nonzero it's returned in nanoseconds.

It's system dependent whether or not this time is monotonic, i.e. if it's unaffected by adjustments of the calendaric clock in the system. System.REAL_TIME_IS_MONOTONIC tells what it is. Pike tries to use monotonic time for this function if it's available.

Note

The actual accuracy on many systems is significantly less than microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION.

See also

System.REAL_TIME_IS_MONOTONIC, System.REAL_TIME_RESOLUTION, time(), System.gettimeofday(), gethrvtime(), Pike.implicit_gc_real_time


Methodgethrvtime

intgethrvtime(void|intnsec)

Description

Return the CPU time that has been consumed by this process or thread. -1 is returned if the system couldn't determine it. The time is normally returned in microseconds, but if the optional argument nsec is nonzero it's returned in nanoseconds.

The CPU time includes both user and system time, i.e. it's approximately the same thing you would get by adding together the "utime" and "stime" fields returned by System.getrusage (but perhaps with better accuracy).

It's however system dependent whether or not it's the time consumed in all threads or in the current one only; System.CPU_TIME_IS_THREAD_LOCAL tells which. If both types are available then thread local time is preferred.

Note

The actual accuracy on many systems is significantly less than microseconds or nanoseconds. See System.CPU_TIME_RESOLUTION.

Note

The garbage collector might run automatically at any time. The time it takes is not included in the figure returned by this function, so that normal measurements aren't randomly clobbered by it. Explicit calls to gc are still included, though.

Note

The special function gauge is implemented with this function.

See also

System.CPU_TIME_IS_THREAD_LOCAL, System.CPU_TIME_RESOLUTION, gauge(), System.getrusage(), gethrtime()


Methodgetpid

intgetpid()

Description

Returns the process ID of this process.

See also

System.getppid(), System.getpgrp()


Methodgetpwnam

array(int|string) getpwnam(stringstr)

Description

Get the user entry for login str using the systemfunction getpwnam(3).

Parameter str

The login name of the user whos userrecord is requested.

Returns

An array with the information about the user

Array
string0

Users username (loginname)

string1

User password (encrypted)

int2

Users ID

int3

Users primary group ID

string4

Users real name an possibly some other info

string5

Users home directory

string6

Users shell

See also

getpwuid()getpwent()


Methodgetpwuid

array(int|string) getpwuid(intuid)

Description

Get the user entry for UID uid using the systemfunction getpwuid(3).

Parameter uid

The uid of the user whos userrecord is requested.

Returns

An array with the information about the user

Array
string0

Users username (loginname)

string1

User password (encrypted)

int2

Users ID

int3

Users primary group ID

string4

Users real name an possibly some other info

string5

Users home directory

string6

Users shell

See also

getpwnam()getpwent()


Methodgetxattr

stringgetxattr(stringfile, stringattr, void|boolsymlink)

Description

Return the value of a specified attribute, or 0 if it does not exist.


Methodglob

boolglob(stringglob, stringstr)
zero|stringglob(array(string) glob, stringstr)
array(string) glob(stringglob, array(string) str)
array(string) glob(array(string) glob, array(string) str)

Description

Match strings against a glob pattern.

Parameter glob
string

The glob pattern.

Some characters have special meanings.

When a character range is not started the following characters have special meanings:

'?'

A question sign ('?') matches any character.

'*'

An asterisk ('*') matches a string of arbitrary length.

'\\'

A back-slash ('\\') escapes the following character so that it is matched verbatim.

'['

A left-bracket ('[') starts a character range.

If a character range is started the following characters have special meanings:

'\\'

Escape (as above).

']'

A right-bracket (']') ends a character range.

'^'

The characters '^' and '!' invert the character range if they are the first character in the range and otherwise match themselves.

'!'
'-'

The character '-' separates the first and last characters in a character sequence.

All other characters only match themselves.

array(string)

An array of glob patterns (as above).

The function returns the matching glob if any of the given patterns match. Otherwise 0. If the second argument (str) is an array it will behave as if the first argument is a string (see below).

Parameter str
string

1 is returned if the string str matches glob, 0 (zero) otherwise.

array(string)

All strings in the array str are matched against glob, and those that match are returned in an array (in the same order).

Note

In Pike 8.0 and earlier only '?' and '*' had special meanings. The old implementation is available as 8.0::glob().

Note

In Pike 8.0 and earlier 1 was also returned when matching an array of globs against a single string.

See also

8.0::glob(), sscanf(), Regexp


Methodgmtime

mapping(string:int) gmtime(inttimestamp)

Description

Convert seconds since 00:00:00 UTC, Jan 1, 1970 into components.

This function works like localtime() but the result is not adjusted for the local time zone.

Note

Timestamps prior to 1970-01-01T00:00:00 (ie negative timestamps) were not supported on NT and AIX prior to Pike 9.0.

See also

localtime(), time(), ctime(), mktime(), strptime()


Methodhas_index

inthas_index(stringhaystack, intindex)
inthas_index(arrayhaystack, intindex)
inthas_index(mapping|multiset|object|programhaystack, mixedindex)

Description

Search for index in haystack.

Returns

Returns 1 if index is in the index domain of haystack, or 0 (zero) if not found.

This function is equivalent to (but sometimes faster than):

search(indices(haystack), index) != -1
Note

A negative index in strings and arrays as recognized by the index operators `[]() and `[]=() is not considered a proper index by has_index()

See also

has_value(), has_prefix(), has_suffix(), indices(), search(), values(), zero_type()


Methodhas_prefix

inthas_prefix(string|objects, stringprefix)

Description

Returns 1 if the string s starts with prefix, returns 0 (zero) otherwise.

When s is an object, it needs to implement lfun::_sizeof() and lfun::`[].

See also

has_suffix(), has_value(), search()


Methodhas_suffix

inthas_suffix(strings, stringsuffix)

Description

Returns 1 if the string s ends with suffix, returns 0 (zero) otherwise.

See also

has_prefix(), has_value(), search()


Methodhas_value

inthas_value(stringhaystack, stringvalue)
inthas_value(stringhaystack, intvalue)
inthas_value(array|mapping|object|programhaystack, mixedvalue)

Description

Search for value in haystack.

Returns

Returns 1 if value is in the value domain of haystack, or 0 (zero) if not found.

This function is in all cases except when both arguments are strings equivalent to (but sometimes faster than):

search(values(haystack), value) != -1

If both arguments are strings, has_value() is equivalent to:

search(haystack, value) != -1
See also

has_index(), indices(), search(), has_prefix(), has_suffix(), values(), zero_type()


Methodhash

inthash(strings)
inthash(strings, intmax)

Description

Return an integer derived from the string s. The same string always hashes to the same value, also between processes, architectures, and Pike versions (see compatibility notes below, though).

If max is given, the result will be >= 0 and < max, otherwise the result will be >= 0 and <= 0x7fffffff.

Note

The hash algorithm was changed in Pike 8.1. If you want a hash that is compatible with Pike 8.0 and earlier, use hash_8_0().

The hash algorithm was also changed in Pike 7.5. If you want a hash that is compatible with Pike 7.4 and earlier, use hash_7_4(). The difference with regards to hash_8_0() only affects wide strings.

The hash algorithm was also changed in Pike 7.1. If you want a hash that is compatible with Pike 7.0 and earlier, use hash_7_0().

Note

This hash function differs from the one provided by hash_value(), in that hash_value() returns a process specific value.

See also

hash_7_0(), hash_7_4(), hash_8_0(), hash_value


Methodhash_7_0

inthash_7_0(strings)
inthash_7_0(strings, intmax)

Description

Return an integer derived from the string s. The same string always hashes to the same value, also between processes.

If max is given, the result will be >= 0 and < max, otherwise the result will be >= 0 and <= 0x7fffffff.

Note

This function is provided for backward compatibility with code written for Pike up and including version 7.0.

This function is not NUL-safe, and is byte-order dependant.

See also

hash(), hash_7_4


Methodhash_7_4

inthash_7_4(strings)
inthash_7_4(strings, intmax)

Description

Return an integer derived from the string s. The same string always hashes to the same value, also between processes.

If max is given, the result will be >= 0 and < max, otherwise the result will be >= 0 and <= 0x7fffffff.

Note

This function is provided for backward compatibility with code written for Pike up and including version 7.4.

This function is byte-order dependant for wide strings.

See also

hash_7_6(), hash_7_0


Methodhash_8_0

inthash_8_0(strings)
inthash_8_0(strings, intmax)

Description

Return an integer derived from the string s. The same string always hashes to the same value, also between processes, architectures, and Pike versions (see compatibility notes below, though).

If max is given, the result will be >= 0 and < max, otherwise the result will be >= 0 and <= 0x7fffffff.

Deprecated

Use hash_value() for in-process hashing (eg, for implementing lfun::_hash()) or one of the cryptographic hash functions.

Note

This function is really bad at hashing strings. Similar string often return similar hash values.

It is especially bad for url:s, paths and similarly formatted strings.

Note

The hash algorithm was changed in Pike 7.5. If you want a hash that is compatible with Pike 7.4 and earlier, use hash_7_4(). The difference only affects wide strings.

The hash algorithm was also changed in Pike 7.1. If you want a hash that is compatible with Pike 7.0 and earlier, use hash_7_0().

Note

This hash function differs from the one provided by hash_value(), in that hash_value() returns a process specific value.

See also

hash(), hash_7_0(), hash_7_4(), hash_value


Methodhash_value

inthash_value(mixedvalue)

Description

Return a hash value for the argument. It's an integer in the native integer range.

The hash will be the same for the same value in the running process only (the memory address is typically used as the basis for the hash value).

If the value is an object with an lfun::__hash, that function is called and its result returned.

Note

This is the hashing method used by mappings.

See also

lfun::__hash()


Methodis_absolute_path

intis_absolute_path(stringp)

Description

Check if a path p is fully qualified (ie not relative).

Returns

Returns 1 if the path is absolute, 0 otherwise.


Methoditerator_index

mixediterator_index(Iteratoriter)

Description

Get the current index for iter.

See also

iterator_value(), lfun::_iterator_index(), get_iterator()


Methoditerator_next

mixediterator_next(Iteratoriter)

Description

Advance iter one step.

See also

iterator_prev(), lfun::_iterator_next(), get_iterator()


Methoditerator_prev

mixediterator_prev(Iteratoriter)

Description

Advance iter one step backward (if supported).

See also

iterator_next(), lfun::_iterator_prev(), get_iterator()


Methoditerator_value

mixediterator_value(Iteratoriter)

Description

Get the current value for iter.

See also

iterator_index(), lfun::_iterator_value(), get_iterator()


Methodkill

boolkill(intpid, intsignal)

Description

Send a signal to another process.

Some signals and their supposed purpose:

SIGHUP

Hang-up, sent to process when user logs out.

SIGINT

Interrupt, normally sent by ctrl-c.

SIGQUIT

Quit, sent by ctrl-\.

SIGILL

Illegal instruction.

SIGTRAP

Trap, mostly used by debuggers.

SIGABRT

Aborts process, can be caught, used by Pike whenever something goes seriously wrong.

SIGEMT

Emulation trap.

SIGFPE

Floating point error (such as division by zero).

SIGKILL

Really kill a process, cannot be caught.

SIGBUS

Bus error.

SIGSEGV

Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike.

SIGSYS

Bad system call. Should never happen to Pike.

SIGPIPE

Broken pipe.

SIGALRM

Signal used for timer interrupts.

SIGTERM

Termination signal.

SIGUSR1

Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library.

SIGUSR2

Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library.

SIGCHLD

Child process died. This signal is reserved for internal use by the Pike run-time.

SIGPWR

Power failure or restart.

SIGWINCH

Window change signal.

SIGURG

Urgent socket data.

SIGIO

Pollable event.

SIGSTOP

Stop (suspend) process.

SIGTSTP

Stop (suspend) process. Sent by ctrl-z.

SIGCONT

Continue suspended.

SIGTTIN

TTY input for background process.

SIGTTOU

TTY output for background process.

SIGVTALRM

Virtual timer expired.

SIGPROF

Profiling trap.

SIGXCPU

Out of CPU.

SIGXFSZ

File size limit exceeded.

SIGSTKFLT

Stack fault

Returns
1

Success.

0

Failure. errno() is set to EINVAL, EPERM or ESRCH.

Note

Note that you have to use signame to translate the name of a signal to its number.

Note that the kill function is not available on platforms that do not support signals. Some platforms may also have signals not listed here.

See also

signal(), signum(), signame(), fork()


Methodlimit

int|float|objectlimit(int|float|objectminval, int|float|objectx, int|float|objectmaxval)

Description

Limits the value x so that it's between minval and maxval. If x is an object, it must implement the lfun::`< method.

See also

max() and min()


Methodlistxattr

array(string) listxattr(stringfile, void|boolsymlink)

Description

Return an array of all extended attributes set on the file


Methodload_module

programload_module(stringmodule_name)

Description

Load a binary module.

This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.

When a module is loaded the C function pike_module_init() will be called to initialize it. When Pike exits pike_module_exit() will be called. These two functions must be available in the module.

Note

The current working directory is normally not searched for dynamic modules. Please use "./name.so" instead of just "name.so" to load modules from the current directory.


Methodlocaltime

mapping(string:int) localtime(inttimestamp)

Description

Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.

Returns

This function returns a mapping with the following components:

"sec" : int(0..60)

Seconds over the minute.

"min" : int(0..59)

Minutes over the hour.

"hour" : int(0..23)

Hour of the day.

"mday" : int(1..31)

Day of the month.

"mon" : int(0..11)

Month of the year.

"year" : int(0..)

Year since 1900.

"wday" : int(0..6)

Day of week (0 = Sunday).

"yday" : int(0..365)

Day of the year.

"isdst" : bool

Is daylight-saving time active.

"timezone" : int

Offset from UTC, including daylight-saving time adjustment.

An error is thrown if the localtime(2) call failed on the system. It's platform dependent what time ranges that function can handle, e.g. Windows doesn't handle a negative timestamp.

Note

Prior to Pike 7.5 the field "timezone" was sometimes not present, and was sometimes not adjusted for daylight-saving time.

Note

Timestamps prior to 1970-01-01T00:00:00 (ie negative timestamps) were not supported on NT and AIX prior to Pike 9.0. Note also that dst-handling may be incorrect for such timestamps.

See also

Calendar, gmtime(), time(), ctime(), mktime(), strptime()


Methodlog

floatlog(int|floatf)

Description

Return the natural logarithm of f. exp( log(x) ) == x for x > 0.

See also

pow(), exp()


Methodlower_case

stringlower_case(strings)
intlower_case(intc)

Description

Convert a string or character to lower case.

Returns

Returns a copy of the string s with all upper case characters converted to lower case, or the character c converted to lower case.

Note

Assumes the string or character to be coded according to ISO-10646 (aka Unicode). If they are not, Charset.decoder can do the initial conversion for you.

Note

Prior to Pike 7.5 this function only accepted strings.

See also

upper_case(), Charset.decoder


Methodm_add

voidm_add(multiset|objectl, mixedval)

Description

Add a member to a multiset.

See also

m_delete()


Methodm_clear

voidm_clear(mapping|multiset|objectmap)

Description

Clear the contents of a mapping or multiset.

This function clears the content of the mapping or multiset map so that it becomes empty. This is an atomic operation.

If map is an object lfun::_m_clear() will be called in it.

See also

m_delete()


Methodm_delete

mixedm_delete(object|mapping|multisetmap, mixedindex)

Description

If map is an object that implements lfun::_m_delete(), that function will be called with index as its single argument.

Otherwise if map is a mapping or multiset the entry with index index will be removed from map destructively.

If the mapping or multiset does not have an entry with index index, nothing is done.

Returns

The value that was removed will be returned, and UNDEFINED otherwise.

Note

Note that m_delete() changes map destructively.

See also

mappingp()


Methodmap

mixedmap(mixedarr, void|mixedfun, mixed ... extra)

Description

Applies fun to the elements in arr and collects the results.

Parameter arr

arr is treated as a set of elements, as follows:

array

fun is applied in order to each element. The results are collected, also in order, to a value of the same type as arr, which is returned.

mapping

fun is applied to the values, and each result is assigned to the same index in a new mapping, which is returned.

program

The program is treated as a mapping containing the identifiers that are indexable from it and their values.

object

If there is a lfun::cast method in the object, it's called to try to cast the object to an array, a mapping, or a multiset, in that order, which is then handled as described above.

Parameter fun

fun is applied in different ways depending on its type:

function(mixed ... :mixed)

fun is called for each element. It gets the current element as the first argument and extra as the rest. The result of the call is collected.

object

fun is used as a function like above, i.e. the lfun::`() method in it is called.

array

Each element of the fun array will be called for each element of arr.

multiset

fun is indexed with each element. The result of that is collected.

zero|void

Each element that is callable is called with extra as arguments. The result of the calls are collected. Elements that aren't callable gets zero as result.

string

Each element is indexed with the given string. If the result of that is zero then a zero is collected, otherwise it's called with extra as arguments and the result of that call is collected.

This is typically used when arr is a collection of objects, and fun is the name of some function in them.

Note

The function is never destructive on arr.

See also

filter(), enumerate(), foreach()


Methodmaster

objectmaster()

Description

Return the current master object.

Note

May return UNDEFINED if no master has been loaded yet.

See also

replace_master()


Methodmax

int|float|objectmax(int|float|object, int|float|object ... args)
stringmax(string, string ... args)
int(0)max()

Description

Returns the largest value among args. Compared objects must implement the lfun::`< method.

See also

min() and limit()


Methodmin

int|float|objectmin(int|float|object, int|float|object ... args)
stringmin(string, string ... args)
int(0)min()

Description

Returns the smallest value among args. Compared objects must implement the lfun::`< method.

See also

max() and limit()


Methodmkmapping

mappingmkmapping(arrayind, arrayval)

Description

Make a mapping from two arrays.

Makes a mapping ind[x]:val[x], 0 <= x < sizeof(ind).

ind and val must have the same size.

This is the inverse operation of indices() and values().

See also

indices(), values()


Methodmkmultiset

multisetmkmultiset(arraya)

Description

This function creates a multiset from an array.

See also

aggregate_multiset()


Methodmktime

intmktime(mapping(string:int) tm)
intmktime(intsec, intmin, inthour, intmday, intmon, intyear, int|voidisdst, int|voidtz)

Description

This function converts information about date and time into an integer which contains the number of seconds since 00:00:00 UTC, Jan 1, 1970.

You can either call this function with a mapping containing the following elements:

"sec" : int(0..60)

Seconds over the minute.

"min" : int(0..59)

Minutes over the hour.

"hour" : int(0..23)

Hour of the day.

"mday" : int(1..31)

Day of the month.

"mon" : int(0..11)

Month of the year.

"year" : int(0..)

Year since 1900.

"isdst" : int(-1..1)

Is daylight-saving time active. If omitted or set to -1, it means that the information is not available.

"timezone" : int

The timezone offset from UTC in seconds. If omitted, the time will be calculated in the local timezone.

Or you can just send them all on one line as the second syntax suggests.

Note

For proper UTC calculations ensure that isdst = 0andtimezone = 0; omitting either one of these parameters will mess up the UTC calculation.

Note

On some operating systems (notably AIX and Win32), dates before 00:00:00 UTC, Jan 1, 1970 were not supported prior to Pike 9.0.

On most 32-bit systems, the supported range of dates is from Dec 13, 1901 20:45:52 UTC through to Jan 19, 2038 03:14:07 UTC (inclusive).

On most 64-bit systems, the supported range of dates is expressed in 56 bits and is thus practically unlimited (at least up to 1141 milion years in the past and into the future).

See also

time(), ctime(), localtime(), gmtime(), strftime()


Methodnormalize_path

stringnormalize_path(stringpath)

Description

Replaces "\" with "/" if runing on MS Windows. It is adviced to use System.normalize_path instead.


Methodobject_variablep

boolobject_variablep(objecto, stringvar)

Description

Find out if an object identifier is a variable.

Returns

This function returns 1 if var exists as a non-protected variable in o, and returns 0 (zero) otherwise.

See also

indices(), values()


Methodobjectp

intobjectp(mixedarg)

Description

Returns 1 if arg is an object, 0 (zero) otherwise.

See also

mappingp(), programp(), arrayp(), stringp(), functionp(), multisetp(), floatp(), intp()


Methodpow

int|floatpow(float|intn, float|intx)
mixedpow(objectn, float|int|objectx)

Description

Return n raised to the power of x. If both n and x are integers the result will be an integer. If n is an object its pow method will be called with x as argument.

See also

exp(), log()


Methodputenv

voidputenv(stringvarname, void|stringvalue)

Description

Sets the environment variable varname to value.

If value is omitted or zero, the environment variable varname is removed.

varname and value cannot be wide strings nor contain '\0' characters. varname also cannot contain '=' characters.

Note

On NT the environment variable name is case insensitive.

See also

getenv()


Methodrandom

arrayrandom(mappingm)
floatrandom(floatmax)
intrandom(intmax)
mixedrandom(objecto)
mixedrandom(array|multisetx)

Description

Get a random value generated by the default RandomSystem.

See also

RandomSystem()->random(), random_string()


Methodrandom_seed

voidrandom_seed(intseed)

Description

This function sets the initial value for the random generator.

See also

random()

Deprecated

Random.Deterministic


Methodrandom_string

stringrandom_string(intlen)

Description

Get a string of random characters 0..255 with the length len from the default RandomSystem.

See also

RandomSystem()->random_string(), random()


Methodremove_include_path

voidremove_include_path(stringtmp)

Description

Remove a directory to search for include files.

This function performs the reverse operation of add_include_path().

See also

add_include_path()


Methodremove_module_path

voidremove_module_path(stringtmp)

Description

Remove a directory to search for modules.

This function performs the reverse operation of add_module_path().

See also

add_module_path()


Methodremove_program_path

voidremove_program_path(stringtmp)

Description

Remove a directory to search for programs.

This function performs the reverse operation of add_program_path().

See also

add_program_path()


Methodremovexattr

voidremovexattr(stringfile, stringattr, void|boolsymlink)

Description

Remove the specified extended attribute.


Methodreplace

stringreplace(strings, stringfrom, stringto)
stringreplace(strings, array(string) from, array(string) to)
stringreplace(strings, array(string) from, stringto)
stringreplace(strings, mapping(string:string) replacements)
arrayreplace(arraya, mixedfrom, mixedto)
mappingreplace(mappinga, mixedfrom, mixedto)

Description

Generic replace function.

This function can do several kinds replacement operations, the different syntaxes do different things as follows:

If all the arguments are strings, a copy of s with every occurrence of from replaced with to will be returned. Special case: to will be inserted between every character in s if from is the empty string.

If the first argument is a string, and the others array(string), a string with every occurrance of from[i] in s replaced with to[i] will be returned. Instead of the arrays from and to a mapping equivalent to mkmapping(fromto) can be used.

If the first argument is an array or mapping, the values of a which are `==() with from will be replaced with to destructively. a will then be returned.

Note

Note that replace() on arrays and mappings is a destructive operation.


Methodreplace_master

voidreplace_master(objecto)

Description

Replace the master object with o.

This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is usually a good idea to have your master inherit the original master and only re-define certain functions.

FIXME: Tell how to inherit the master.

See also

master()


Methodreverse

stringreverse(strings, int|voidstart, int|voidend)
arrayreverse(arraya, int|voidstart, int|voidend)
intreverse(inti, int|voidstart, int|voidend)
mixedreverse(objecto, mixed ... options)

Description

Reverses a string, array or int.

Parameter s

String to reverse.

Parameter a

Array to reverse.

Parameter i

Integer to reverse.

Parameter o

Object to reverse.

Parameter start

Optional start index of the range to reverse. Default: 0 (zero).

Parameter end

Optional end index of the range to reverse. Default for strings: sizeof(s)-1. Default for arrays: sizeof(a)-1. Default for integers: Pike.get_runtime_info()->int_size - 1.

Parameter options

Optional arguments that are to be passed to lfun::_reverse().

This function reverses a string, char by char, an array, value by value or an int, bit by bit and returns the result. It's not destructive on the input value. For objects it simply calls lfun::_reverse() in the object, and returns the result.

Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.

See also

sscanf()


Methodround

floatround(int|floatf)

Description

Return the closest integer value to f.

Note

round() does not return an int, merely an integer value stored in a float.

See also

floor(), ceil()


Methodrows

arrayrows(mixeddata, arrayindex)

Description

Select a set of rows from an array.

This function is en optimized equivalent to:

map(index,lambda(mixed x){return data[x];})

That is, it indices data on every index in the array index and returns an array with the results.

See also

column()


Methodsearch

intsearch(stringhaystack, string|intneedle, int|voidstart, int|voidend)
intsearch(arrayhaystack, mixedneedle, int|voidstart, int|voidend)
mixedsearch(mappinghaystack, mixedneedle, mixed|voidstart)
mixedsearch(objecthaystack, mixedneedle, mixed|voidstart, mixed ... extra_args)

Description

Search for needle in haystack.

Parameter haystack

Item to search in. This can be one of:

string

When haystack is a string needle must be a string or an int, and the first occurrence of the string or int is returned.

array

When haystack is an array, needle is compared only to one value at a time in haystack.

mapping

When haystack is a mapping, search() tries to find the index connected to the data needle. That is, it tries to lookup the mapping backwards.

object

When haystack is an object implementing lfun::_search(), the result of calling lfun::_search() with needle, start and any extra_args will be returned.

If haystack is an object that doesn't implement lfun::_search() it is assumed to be an Iterator, and implement Iterator()->index(), Iterator()->value(), and Iterator()->next(). search() will then start comparing elements with `==() until a match with needle is found. If needle is found haystack will be advanced to the element, and the iterator index will be returned. If needle is not found, haystack will be advanced to the end.

Parameter start

If the optional argument start is present search is started at this position. This has no effect on mappings.

Parameter end

If the optional argument end is present, the search will terminate at this position (exclusive) if not found earlier.

Returns

Returns the position of needle in haystack if found.

If not found the returned value depends on the type of haystack:

string|array

-1.

mapping|Iterator

UNDEFINED.

object

The value returned by lfun::_search().

Note

If start is supplied to an iterator object without an lfun::_search(), haystack will need to implement Iterator()->set_index().

Note

For mappings and object UNDEFINED will be returned when not found. In all other cases -1 will be returned when not found.

See also

indices(), values(), zero_type(), has_value(), has_prefix(), has_suffix()


Methodset_priority

intset_priority(stringlevel, int(0..)|voidpid)


Methodset_weak_flag

array|mapping|multisetset_weak_flag(array|mapping|multisetm, intstate)

Description

Set the value m to use weak or normal references in its indices and/or values (whatever is applicable). state is a bitfield built by using | between the following flags:

Pike.WEAK_INDICES

Use weak references for indices. Only applicable for multisets and mappings.

Pike.WEAK_VALUES

Use weak references for values. Only applicable for arrays and mappings.

Pike.WEAK

Shorthand for Pike.WEAK_INDICES|Pike.WEAK_VALUES.

If a flag is absent, the corresponding field will use normal references. state can also be 1 as a compatibility measure; it's treated like Pike.WEAK.

Returns

m will be returned.


Methodsetxattr

voidsetxattr(stringfile, stringattr, stringvalue, intflags, void|boolsymlink)

Description

Set the attribute attr to the value value.

The flags parameter can be used to refine the semantics of the operation.

Stdio.XATTR_CREATE specifies a pure create, which fails if the named attribute exists already.

Stdio.XATTR_REPLACE specifies a pure replace operation, which fails if the named attribute does not already exist.

By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.

Returns

1 if successful, 0 otherwise, setting errno.


Methodsgn

intsgn(mixedvalue)
intsgn(mixedvalue, mixedzero)

Description

Check the sign of a value.

Returns

Returns -1 if value is less than zero, 1 if value is greater than zero and 0 (zero) otherwise.

See also

abs()


Methodsignal

function(int|void:void) signal(intsig, function(int|void:void) callback)
function(int|void:void) signal(intsig)

Description

Trap signals.

This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc, I advise you not to; Pike should not receive any such signals, and if it does, it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.

The callback will receive the signal number as its only argument.

See the documentation for kill() for a list of signals.

If no second argument is given, the signal handler for that signal is restored to the default handler.

If the second argument is zero, the signal will be completely ignored.

Returns

Returns the previous signal function, or 0 if none had been registered.

See also

kill(), signame(), signum()


Methodsigname

stringsigname(intsig)

Description

Returns a string describing the signal sig.

See also

kill(), signum(), signal()


Methodsignum

intsignum(stringsig)

Description

Get a signal number given a descriptive string.

This function is the inverse of signame().

See also

signame(), kill(), signal()


Methodsin

floatsin(int|floatf)

Description

Returns the sine value for f. f should be specified in radians.

See also

asin(), cos(), tan()


Methodsinh

floatsinh(int|floatf)

Description

Returns the hyperbolic sine value for f.

See also

asinh(), cosh(), tanh()


Methodsizeof

int(0..)sizeof(stringarg)
int(0..)sizeof(arrayarg)
int(0..)sizeof(mappingarg)
int(0..)sizeof(multisetarg)
int(0..)sizeof(objectarg)

Description

Size query.

Returns

The result will be as follows:

arg can have any of the following types:
string

The number of characters in arg will be returned.

array|multiset

The number of elements in arg will be returned.

mapping

The number of key-value pairs in arg will be returned.

object

If arg implements lfun::_sizeof(), that function will be called. Otherwise the number of non-protected (ie public) symbols in arg will be returned.

See also

lfun::_sizeof()


Methodsleep

voidsleep(int|floats, void|intabort_on_signal)

Description

This function makes the thread stop for s seconds.

Only signal handlers can interrupt the sleep, and only when abort_on_signal is set. If more than one thread is running the signal must be sent to the sleeping thread. Other callbacks are not called during sleep.

If s is zero then this thread will yield to other threads but not sleep otherwise. Note that Pike yields internally at regular intervals so it's normally not necessary to do this.

See also

signal(), delay()


Methodsort

arraysort(array(mixed) index, array(mixed) ... data)

Description

Sort arrays destructively.

This function sorts the array index destructively. That means that the array itself is changed and returned, no copy is created.

If extra arguments are given, they are supposed to be arrays of the same size as index. Each of these arrays will be modified in the same way as index. I.e. if index 3 is moved to position 0 in index index 3 will be moved to position 0 in all the other arrays as well.

The sort order is as follows:

  • Integers and floats are sorted in ascending order.

  • Strings are sorted primarily on the first characters that are different, and secondarily with shorter strings before longer. Different characters are sorted in ascending order on the character value. Thus the sort order is not locale dependent.

  • Arrays are sorted recursively on the first element. Empty arrays are sorted before nonempty ones.

  • Multisets are sorted recursively on the first index. Empty multisets are sorted before nonempty ones.

  • Objects are sorted in ascending order according to `<(), `>() and `==().

  • Other types aren't reordered.

  • Different types are sorted in this order: Arrays, mappings, multisets, objects, functions, programs, strings, types, integers and floats. Note however that objects can control their ordering wrt other types with `<, `> and `==, so this ordering of types only applies to objects without those functions.

Returns

The first argument is returned.

Note

The sort is stable, i.e. elements that are compare-wise equal aren't reordered.

See also

Array.sort_array, reverse()


Methodsprintf

stringsprintf(strict_sprintf_formatformat, sprintf_args ... args)

Description

Print formated output to string.

The format string is a string containing a description of how to output the data in args. This string should generally speaking have one %<modifiers><operator> format specifier (examples: %s, %0d, %-=20s) for each of the arguments.

The following modifiers are supported:

'0'

Zero pad numbers (implies right justification).

'!'

Toggle truncation.

' '

Pad positive integers with a space.

'+'

Pad positive integers with a plus sign.

'-'

Left adjust within field size (default is right).

'|'

Centered within field size.

'='

Column mode if strings are greater than field width. Breaks between words (possibly skipping or adding spaces). Can not be used together with '/'.

'/'

Column mode with rough line break (break at exactly field width instead of between words). Can not be used together with '='.

'#'

Table mode, print a list of '\n' separated words (top-to-bottom order).

'$'

Inverse table mode (left-to-right order).

'n'

(Where n is a number or *) field width specifier.

':n'
'.n'

Precision specifier.

';n'

Column width specifier.

'*'

If n is a * then next argument is used for precision/field size. The argument may either be an integer, or a modifier mapping as received by lfun::_sprintf():

"precision" : int|void

Precision (aka '.n' where n is a number).

"width" : int(0..)|void

Field width (aka 'n' or ':n' where n is a number).

"flag_left" : bool|void

Indicates that the output should be left-aligned (aka '-').

"indent" : int(0..)|void

Base indentation level in number of spaces in %O-mode.

"'"

Set a pad string. ' cannot be a part of the pad string (yet).

'~'

Get pad string from argument list.

'<'

Use same argument again.

'^'

Repeat this on every line produced.

'@'

Repeat this format for each element in the argument array.

'>'

Put the string at the bottom end of column instead of top.

'_'

Set width to the length of data.

'[n]'

Select argument number n. Use * to use the next argument as selector. The arguments are numbered starting from 0 (zero) for the first argument after the format. Note that this only affects where the current operand is fetched.

The following operators are supported:

'%'

Percent.

'b'

Signed binary integer.

'd'

Signed decimal integer.

'u'

Unsigned decimal integer.

'o'

Signed octal integer.

'x'

Lowercase signed hexadecimal integer or 8-bit string.

'X'

Uppercase signed hexadecimal integer or 8-bit string.

'c'

Character (integer). If a fieldsize has been specified this will output the low-order bytes of the integer in network (big endian) byte order. To get little endian byte order, negate the field size.

'f'

Float. (Locale dependent formatting.)

'g'

Heuristically chosen representation of float. (Locale dependent formatting.)

'G'

Like %g, but uses uppercase E for exponent.

'e'

Exponential notation float. (Locale dependent output.)

'E'

Like %e, but uses uppercase E for exponent.

'F'

Binary IEEE representation of float (%4F gives single precision, %8F gives double precision) in network (big endian) byte order. To get little endian byte order, negate the field size.

's'

String.

'q'

Quoted string. Escapes all control and non-8-bit characters, as well as the quote characters '\\' and '\"'.

'O'

Any value, debug style. Do not rely on the exact formatting; how the result looks can vary depending on locale, phase of the moon or anything else the lfun::_sprintf() method implementor wanted for debugging.

'p'

Hexadecimal representation of the memory address of the object. Integers and floats have no address, and are printed as themselves.

'H'

Binary Hollerith string. Equivalent to sprintf("%c%s", strlen(str), str). Arguments (such as width etc) adjust the length-part of the format. Requires 8-bit strings.

'n'

No argument. Same as "%s" with an empty string as argument. Note: Does take an argument array (but ignores its content) if the modifier '@' is active.

't'

Type of the argument.

'{'

Perform the enclosed format for every element of the argument array.

'}'

Most modifiers and operators are combinable in any fashion, but some combinations may render strange results.

If an argument is an object that implements lfun::_sprintf(), that callback will be called with the operator as the first argument, and the current modifiers as the second. The callback is expected to return a string.

Note

sprintf-style formatting is applied by many formatting functions, such write() and werror(). It is also possible to get sprintf-style compile-time argument checking by using the type-attributes sprintf_format or strict_sprintf_format in combination with sprintf_args.

Note

Most formats are available in all versions of Pike; the exceptions are:

FormatVersionAvailability constantNotes
'*'Pike 7.8.238String.__HAVE_SPRINTF_STAR_MAPPING__Support for specifying modifiers via a mapping.
'b'Pike 0.7.62
'c'Pike 0.7.3Support for wide characters.
'c'Pike 0.7.64Support for little endian output.
'E'Pike 0.6.38
'F'Pike 0.6.38
'F'Pike 7.8.242String.__HAVE_SPRINTF_NEGATIVE_F__Support for litte endian byte order.
'G'Pike 0.6.38
'H'Pike 7.7.31
'p'Pike 7.5.4Implemented but disabled (#if 0-block).
'p'Pike 8.1.14Enabled.
'q'Pike 7.7.28
'x'Pike 8.1.5Support for hex-formatting strings.
'X'Pike 8.1.5Support for hex-formatting strings.
'[n]'Pike 7.1.5
Example
Pike v7.8 release 263 running Hilfe v3.5 (Incremental Pike Frontend)> sprintf("The unicode character %c has character code %04X.",'A','A');(1) Result:"The unicode character A has character code 0041."> sprintf("#%@02X is the HTML code for purple.",Image.Color.purple->rgb());(2) Result:"#A020F0 is the HTML code for purple.">int n=4711;> sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n);(3) Result:"4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary"> write(#"Formatting examples:
Left adjusted  [%-10d]
Centered       [%|10d]
Right adjusted [%10d]
Zero padded    [%010d]
", n, n, n, n);
Formatting examples:
Left adjusted  [4711      ]
Centered       [   4711   ]
Right adjusted [      4711]
Zero padded    [0000004711]
(5) Result: 142
int screen_width=70;> write("%-=*s\n", screen_width,
>> "This will wordwrap the specified string within the "+
>> "specified field size, this is useful say, if you let "+
>> "users specify their screen size, then the room "+
>> "descriptions will automagically word-wrap as appropriate.\n"+
>> "slosh-n's will of course force a new-line when needed.\n");
This will wordwrap the specified string within the specified field
size, this is useful say, if you let users specify their screen size,
then the room descriptions will automagically word-wrap as
appropriate.
slosh-n's will of course force a new-line when needed.
(6) Result: 355
> write("%-=*s %-=*s\n", screen_width/2,
>> "Two columns next to each other (any number of columns will "+
>> "of course work) independantly word-wrapped, can be useful.",
>> screen_width/2-1,
>> "The - is to specify justification, this is in addherence "+
>> "to std sprintf which defaults to right-justification, "+
>> "this version also supports centre and right justification.");
Two columns next to each other (any The - is to specify justification,
number of columns will of course    this is in addherence to std
work) independantly word-wrapped,   sprintf which defaults to
can be useful.                      right-justification, this version
                                    also supports centre and right
                                    justification.
(7) Result: 426
> write("%-$*s\n", screen_width,
>> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+
>> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+
>> "be forced\nby specifying a\npresision.\nThe most obvious\n"+
>> "use is for\nformatted\nls output.");
Given a          list of          slosh-n
separated        'words',         this option
creates a        table out        of them
the number of    columns          be forced
by specifying a  presision.       The most obvious
use is for       formatted        ls output.
(8) Result: 312
> write("%-#*s\n", screen_width,
>> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+
>> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+
>> "be forced\nby specifying a\npresision.\nThe most obvious\n"+
>> "use is for\nformatted\nls output.");
Given a          creates a        by specifying a
list of          table out        presision.
slosh-n          of them          The most obvious
separated        the number of    use is for
'words',         columns          formatted
this option      be forced        ls output.
(9) Result: 312
> sample =(["align":"left","valign":"middle"]);(10) Result:([/* 2 elements */"align":"left","valign":"middle"])> write("<td%{ %s='%s'%}>\n",(array)sample);
<td valign='middle' align='left'>
(11) Result: 34
>  write("Of course all the simple printf options "+
>> "are supported:\n %s: %d %x %o %c\n",
>> "65 as decimal, hex, octal and a char",
>> 65, 65, 65, 65);
Of course all the simple printf options are supported:
 65 as decimal, hex, octal and a char: 65 41 101 A
(12) Result: 106
> write("%[0]d, %[0]x, %[0]X, %[0]o, %[0]c\n", 75);
75, 4b, 4B, 113, K
(13) Result: 19
> write("#%|*s\n#%|*s\n", screen_width,"THE END",
>>      (["width":screen_width ]),"ALTERNATIVE END");
#                               THE END
#                           ALTERNATIVE END
(14) Result: 144
See also

lfun::_sprintf(), strict_sprintf_format, sprintf_format, sprintf_args, String.__HAVE_SPRINTF_STAR_MAPPING__, String.__HAVE_SPRINTF_NEGATIVE_F__.


Methodsqrt

floatsqrt(floatf)
int(0..)sqrt(int(0..)i)
mixedsqrt(objecto)

Description

Returns the square root of f, or in the integer case, the square root truncated to the closest lower integer. If the argument is an object, the lfun _sqrt in the object will be called.

See also

pow(), log(), exp(), floor(), lfun::_sqrt


Methodsscanf

intsscanf(stringdata, stringformat, mixed ... lvalues)

Description

The purpose of sscanf is to match a string data against a format string and place the matching results into a list of variables. The list of lvalues are destructively modified (which is only possible because sscanf really is a special form, rather than a pike function) with the values extracted from the data according to the format specification. Only the variables up to the last matching directive of the format string are touched.

The format string may contain strings separated by special matching directives like %d, %s%c and %f. Every such directive corresponds to one of the lvalues, in the order they are listed. An lvalue is the name of a variable, a name of a local variable, an index into an array, mapping or object. It is because of these lvalues that sscanf can not be implemented as a normal function.

Whenever a percent character is found in the format string, a match is performed, according to which operator and modifiers follow it:

"%b"

Reads a binary integer ("0101" makes 5)

"%d"

Reads a decimal integer ("0101" makes 101).

"%o"

Reads an octal integer ("0101" makes 65).

"%x"

Reads a hexadecimal integer ("0101" makes 257).

"%D"

Reads an integer that is either octal (leading zero), hexadecimal (leading 0x) or decimal. ("0101" makes 65).

"%c"

Reads one character and returns it as an integer ("0101" makes 48, or '0', leaving "101" for later directives). Using the field width and endianness modifiers, you can decode integers of any size and endianness. For example "%-2c" decodes "0101" into 12592, leaving "01" for later directives. The sign modifiers can be used to modify the signature of the data, making "%+1c" decode "ä" into -28.

"%n"

Returns the current character offset in data. Note that any characters matching fields scanned with the "!"-modifier are removed from the count (see below).

"%f"

Reads a float ("0101" makes 101.0).

"%F"

Reads a float encoded according to the IEEE single precision binary format ("0101" makes 6.45e-10, approximately). Given a field width modifier of 8 (4 is the default), the data will be decoded according to the IEEE double precision binary format instead. (You will however still get a float, unless your pike was compiled with the configure argument --with-double-precision.)

"%s"

Reads a string. If followed by %d, %s will only read non-numerical characters. If followed by a %[], %s will only read characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text.

"%H"

Reads a Hollerith-encoded string, i.e. first reads the length of the string and then that number of characters. The size and byte order of the length descriptor can be modified in the same way as %c. As an example "%2H" first reads "%2c" and then the resulting number of characters.

"%[set]"

Matches a string containing a given set of characters (those given inside the brackets). Ranges of characters can be defined by using a minus character between the first and the last character to be included in the range. Example: %[0-9H] means any number or 'H'. Note that sets that includes the character '-' must have it first (not possible in complemented sets, see below) or last in the brackets to avoid having a range defined. Sets including the character ']' must list this first too. If both '-' and ']' should be included then put ']' first and '-' last. It is not possible to make a range that ends with ']'; make the range end with '\' instead and put ']' at the beginning of the set. Likewise it is generally not possible to have a range start with '-'; make the range start with '.' instead and put '-' at the end of the set. If the first character after the [ bracket is '^' (%[^set]), and this character does not begin a range, it means that the set is complemented, which is to say that any character except those inside brackets is matched. To include '-' in a complemented set, it must be put last, not first. To include '^' in a non-complemented set, it can be put anywhere but first, or be specified as a range ("^-^").

"%{format%}"

Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue.

"%O"

Match a Pike constant, such as string or integer (currently only integer, string and character constants are functional).

"%%"

Match a single percent character (hence this is how you quote the % character to just match, and not start an lvalue matcher directive).

Similar to sprintf, you may supply modifiers between the % character and the operator, to slightly change its behaviour from the default:

"*"

The operator will only match its argument, without assigning any variable.

number

You may define a field width by supplying a numeric modifier. This means that the format should match that number of characters in the input data; be it a number characters long string, integer or otherwise ("0101" using the format %2c would read an unsigned short 12337, leaving the final "01" for later operators, for instance).

"-"

Supplying a minus sign toggles the decoding to read the data encoded in little-endian byte order, rather than the default network (big-endian) byte order.

"+"

Interpret the data as a signed entity. In other words, "%+1c" will read "\xFF" as -1 instead of 255, as "%1c" would have.

"!"

Ignore the matched characters with respect to any following "%n".

Note

Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.

Example
// a will be assigned "oo" and 1 will be returned
sscanf("foo","f%s", a);// a will be 4711 and b will be "bar", 2 will be returned
sscanf("4711bar","%d%s", a, b);// a will be 4711, 2 will be returned
sscanf("bar4711foo","%*s%d", a);// a will become "test", 2 will be returned
sscanf(" \t test","%*[ \t]%s", a);// Remove "the " from the beginning of a string// If 'str' does not begin with "the " it will not be changed
sscanf(str,"the %s", str);// It is also possible to declare a variable directly in the sscanf call;// another reason for sscanf not to be an ordinary function:

sscanf("abc def","%s %s",string a,string b);
Returns

The number of directives matched in the format string. Note that a string directive (%s or %[]) counts as a match even when matching just the empty string (which either may do).

See also

sprintf, array_sscanf


Methodstrftime

string(1..255)strftime(string(1..255)format, mapping(string:int) tm)

Description

Convert the structure to a string.

%a

The abbreviated weekday name according to the current locale

%A

The full weekday name according to the current locale.

%b

The abbreviated month name according to the current locale.

%B

The full month name according to the current locale.

%c

The preferred date and time representation for the current locale.

%C

The century number (year/100) as a 2-digit integer.

%d

The day of the month as a decimal number (range 01 to 31).

%D

Equivalent to %m/%d/%y. (for Americans only. Americans should note that in other countries %d/%m/%y is rather common. This means that in international context this format is ambiguous and should not be used.)

%e

Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space.

%E

Modifier: use alternative format, see below.

%F

Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)

%G

The ISO 8601 week-based year (see NOTES) with century as a decimal number. The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead.

%g

Like %G, but without century, that is, with a 2-digit year (00-99). (TZ)

%h

Equivalent to %b.

%H

The hour as a decimal number using a 24-hour clock (range 00 to 23).

%I

The hour as a decimal number using a 12-hour clock (range 01 to 12).

%j

The day of the year as a decimal number (range 001 to 366).

%m

The month as a decimal number (range 01 to 12).

%M

The minute as a decimal number (range 00 to 59).

%n

A newline character. (SU)

%O

Modifier: use alternative format, see below. (SU)

%p

Either "AM" or "PM" according to the given time value, or the corresponding strings for the current locale. Noon is treated as "PM" and midnight as "AM".

%P

Like %p but in lowercase: "am" or "pm" or a corresponding string for the current locale.

%r

The time in a.m. or p.m. notation. In the POSIX locale this is equivalent to %I:%M:%S %p.

%R

The time in 24-hour notation (%H:%M). (SU) For a version including the seconds, see %T below.

%s

The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)

%S

The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)

%t

A tab character. (SU)

%T

The time in 24-hour notation (%H:%M:%S). (SU)

%u

The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w. (SU)

%U

The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W.

%V

The ISO 8601 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the new year. See also %U and %W.

%w

The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u.

See also

ctime(), mktime(), strptime(), Gettext.setlocale


Methodstring_filter_non_unicode

string(1..)string_filter_non_unicode(strings)

Description

Replace the most obviously non-unicode characters from s with the unicode replacement character.

Note

This will replace characters outside the ranges 0x00000000-0x0000d7ff and 0x0000e000-0x0010ffff with 0xffea (the replacement character).

See also

Charset.encoder(), string_to_unicode(), unicode_to_string(), utf8_to_string(), string_to_utf8()


Methodstring_to_unicode

string(8bit)string_to_unicode(strings, int(0..2)|voidbyteorder)

Description

Converts a string into an UTF16 compliant byte-stream.

Parameter s

String to convert to UTF16.

Parameter byteorder

Byte-order for the output. One of:

0

Network (aka big-endian) byte-order (default).

1

Little-endian byte-order.

2

Native byte-order.

Note

Throws an error if characters not legal in an UTF16 stream are encountered. Valid characters are in the range 0x00000 - 0x10ffff, except for characters 0xfffe and 0xffff.

Characters in range 0x010000 - 0x10ffff are encoded using surrogates.

See also

Charset.decoder(), string_to_utf8(), unicode_to_string(), utf8_to_string()


Methodstring_to_utf8

utf8_stringstring_to_utf8(strings)
utf8_stringstring_to_utf8(strings, intextended)

Description

Convert a string into a UTF-8 compliant byte-stream.

Parameter s

String to encode into UTF-8.

Parameter extended

Bitmask with extension options.

1

Accept and encode the characters outside the valid ranges using the same algorithm. Such encoded characters are however not UTF-8 compliant.

2

Encode characters outside the BMP with UTF-8 encoded UTF-16 (ie split them into surrogate pairs and encode).

Note

Throws an error if characters not valid in an UTF-8 stream are encountered. Valid characters are in the ranges 0x00000000-0x0000d7ff and 0x0000e000-0x0010ffff.

See also

Charset.encoder(), string_to_unicode(), unicode_to_string(), utf8_to_string()


Methodstringp

intstringp(mixedarg)

Description

Returns 1 if arg is a string, 0 (zero) otherwise.

See also

intp(), programp(), arrayp(), multisetp(), objectp(), mappingp(), floatp(), functionp()


Methodstrptime

mapping(string:int) strptime(string(1..255)data, string(1..255)format)

Description

Parse the given data using the format in format as a date.

%%

The % character.

%a or %A

The weekday name according to the C locale, in abbreviated form or the full name.

%b or %B or %h

The month name according to the C locale, in abbreviated form or the full name.

%c

The date and time representation for the C locale.

%C

The century number (0-99).

%d or %e

The day of month (1-31).

%D

Equivalent to %m/%d/%y.

%H

The hour (0-23).

%I

The hour on a 12-hour clock (1-12).

%j

The day number in the year (1-366).

%m

The month number (1-12).

%M

The minute (0-59).

%n

Arbitrary whitespace.

%p

The C locale's equivalent of AM or PM.

%R

Equivalent to %H:%M.

%S

The second (0-60; 60 may occur for leap seconds; earlier also 61 was allowed).

%t

Arbitrary whitespace.

%T

Equivalent to %H:%M:%S.

%U

The week number with Sunday the first day of the week (0-53).

%w

The weekday number (0-6) with Sunday = 0.

%W

The week number with Monday the first day of the week (0-53).

%x

The date, using the C locale's date format.

%X

The time, using the C locale's time format.

%y

The year within century (0-99). When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969-1999); values in the range 00-68 refer to years in the twenty-first century (2000-2068).

%Y

The year, including century (for example, 1991).

See also

localtime(), gmtime(), strftime()


Methodtan

floattan(int|floatf)

Description

Returns the tangent value for f. f should be specified in radians.

See also

atan(), sin(), cos()


Methodtanh

floattanh(int|floatf)

Description

Returns the hyperbolic tangent value for f.

See also

atanh(), sinh(), cosh()


Methodthis_object

objectthis_object(void|intlevel)

Description

Returns the object we are currently evaluating in.

Parameter level

level may be used to access the object of a surrounding class: The object at level 0 is the current object, the object at level 1 is the one belonging to the class that surrounds the class that the object comes from, and so on.

Note

As opposed to a qualified this reference such as global::this, this function doesn't always access the objects belonging to the lexically surrounding classes. If the class containing the call has been inherited then the objects surrounding the inheriting class are accessed.


Methodthread_local

Thread.Localthread_local()

Returns

Returns Thread.Local().

This is primarily intended as a convenience function and detection symbol for use by the master before the module system has been fully initiated.

See also

Thread.Local


Methodthrow

mixed|voidthrow(mixedvalue)

Description

Throw value to a waiting catch.

If no catch is waiting the global error handling will send the value to master()->handle_error().

If you throw an array with where the first index contains an error message and the second index is a backtrace, (the output from backtrace()) then it will be treated exactly like a real error by overlying functions.

See also

catch


Methodtime

inttime()
inttime(int(1)one)
floattime(int(2..)t)

Description

This function returns the number of seconds since 00:00:00 UTC, 1 Jan 1970.

The second syntax does not query the system for the current time, instead the last time value used by the pike process is returned again. It avoids a system call, and thus is slightly faster, but can be wildly inaccurate. Pike queries the time internally when a thread has waited for something, typically in sleep or in a backend (see Pike.Backend).

The third syntax can be used to measure time more precisely than one second. It returns how many seconds have passed since t. The precision of this function varies from system to system.

See also

ctime(), localtime(), mktime(), gmtime(), System.gettimeofday(), gethrtime()


Methodualarm

intualarm(intuseconds)

Description

Set an alarm clock for delivery of a signal.

alarm() arranges for a SIGALRM signal to be delivered to the process in useconds microseconds.

If useconds is 0 (zero), no new alarm will be scheduled.

Any previous alarms will in any case be canceled.

Returns

Returns the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

Note

This function is only available on platforms that support signals.

See also

alarm(), signal(), call_out()


Methodunicode_to_string

stringunicode_to_string(string(8bit)s, int(0..2)|voidbyteorder)

Description

Converts an UTF16 byte-stream into a string.

Parameter s

String to convert to UTF16.

Parameter byteorder

Default input byte-order. One of:

0

Network (aka big-endian) byte-order (default).

1

Little-endian byte-order.

2

Native byte-order.

Note that this argument is disregarded if s starts with a BOM.

See also

Charset.decoder(), string_to_unicode(), string_to_utf8(), utf8_to_string()


Methodupper_case

stringupper_case(strings)
intupper_case(intc)

Description

Convert a string or character to upper case.

Returns

Returns a copy of the string s with all lower case characters converted to upper case, or the character c converted to upper case.

Note

Assumes the string or character to be coded according to ISO-10646 (aka Unicode). If they are not, Charset.decoder can do the initial conversion for you.

Note

Prior to Pike 7.5 this function only accepted strings.

See also

lower_case(), Charset.decoder


Methodutf8_to_string

stringutf8_to_string(utf8_strings)
stringutf8_to_string(utf8_strings, intextended)

Description

Converts an UTF-8 byte-stream into a string.

Parameter s

String of UTF-8 encoded data to decode.

Parameter extended

Bitmask with extension options.

1

Accept and decode the extension used by string_to_utf8().

2

Accept and decode UTF-8 encoded UTF-16 (ie accept and decode valid surrogates).

Note

Throws an error if the stream is not a legal UTF-8 byte-stream.

Note

In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are not decoded. An error is thrown instead.

See also

Charset.encoder(), string_to_unicode(), string_to_utf8(), unicode_to_string(), validate_utf8()


Methodvalidate_utf8

boolvalidate_utf8(utf8_strings)
boolvalidate_utf8(utf8_strings, intextended)

Description

Checks whether a string is a valid UTF-8 byte-stream.

Parameter s

String of UTF-8 encoded data to validate.

Parameter extended

Bitmask with extension options.

1

Accept the extension used by string_to_utf8(), including lone UTF-16 surrogates.

2

Accept UTF-8 encoded UTF-16 (ie accept valid surrogate-pairs).

Returns

Returns 0 (zero) if the stream is not a legal UTF-8 byte-stream, and 1 if it is.

Note

In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are considered invalid.

See also

Charset.encoder(), string_to_unicode(), string_to_utf8(), unicode_to_string(), utf8_to_string()


Methodwerror

intwerror(stringfmt, mixed ... args)

Description

Writes a string on stderr. Works just like Stdio.File.write on Stdio.stderr.


Methodwrite

intwrite(stringfmt, mixed ... args)

Description

Writes a string on stdout. Works just like Stdio.File.write on Stdio.stdout.


Methodyield

mixedyield(mixed|voidval)

Description

Stop execution of the current restartable function for now, and return the value val.

Parameter val

Value to be returned from the restartable function.

May be omitted in functions returning void (including asynchronous functions). For asynchronous functions this means that Concurrent.Promise()->success() in the implicit Concurrent.Promise will not be called.

Returns

Evaluates to the first argument passed to the restartable function on restart, or if it has already been called, the value passed at that time.

Calling this special form is similar to the statement:

continue return val;

This syntax is however an expression and can thus be used to pass a value back.

Note

Use of this function is only valid in restartable functions.

Throws

The second argument to a restartable function may be a function that throws a value. That value will appear to have been thrown via yield().

See also

await(), Restartable functions

Enum bool

Description

Boolean datatype.


Constantfalse
Constanttrue

constantfalse
constanttrue

Class Codec

Description

An Encoder and a Decoder lumped into a single instance which can be used for both encoding and decoding.


InheritDecoder

inherit Decoder : Decoder


InheritEncoder

inherit Encoder : Encoder

Class CompilationHandler

Description

Objects used by the compiler to handle references to global symbols, modules, external files, etc.

There can be up to three compilation handlers active at the same time during a compilation. They are in order of precedence:

  1. The error handler

    This is the object passed to compile() as the second argument (if any). This object is returned by get_active_error_handler() during a compilation.

  2. The compatibility handler

    This is the object returned by master()->get_compilation_handler() (if any), which the compiler calls when it sees #pike-directives, or expressions using the version scope (eg 7.4::rusage). This object is returned by get_active_compilation_handler() during a compilation.

  3. The master object.

    This is returned by master() at any time.

Any of the objects may implement a subset of the CompilationHandler functions, and the first object that implements a function will be used. The error handler object can thus be used to block certain functionality (eg to restrict the number of available functions).

See also

master()->get_compilation_handler(), get_active_error_handler(), get_active_compilation_handler(), compile()


Methodcompile_error

voidcompile_error(stringfilename, intline, stringmsg)

Description

Called by compile() and cpp() when they encounter errors in the code they compile.

Parameter filename

File where the error was detected.

Parameter line

Line where the error was detected.

Parameter msg

Description of error.

See also

compile_warning().


Methodcompile_exception

voidcompile_exception(mixedexception)

Description

Called by compile() and cpp() if they trigger exceptions.


Methodcompile_warning

voidcompile_warning(stringfilename, intline, stringmsg)

Description

Called by compile() to report warnings.

Parameter filename

File which triggered the warning.

Parameter line

Line which triggered the warning.

Parameter msg

Warning message.

See also

compile_error()


Methodget_default_module

mapping(string:mixed)|objectget_default_module()

Description

Returns the default module from which global symbols will be fetched.

Returns

Returns the default module, or 0 (zero).

If 0 (zero) is returned the compiler use the mapping returned by all_constants() as fallback.

See also

get_predefines()


Methodget_predefines

mapping(string:mixed) get_predefines()

Description

Called by cpp() to get the set of global symbols.

Returns

Returns a mapping from symbol name to symbol value. Returns zero on failure.

See also

resolv(), get_default_module()


Methodhandle_import

mapping(string:mixed)|object|program|zerohandle_import(stringpath, stringfilename, CompilationHandlerhandler)

Description

Called by compile() and cpp() to handle import directives specifying specific paths.

Returns

Returns the resolved value, or UNDEFINED on failure.

See also

resolv()


Methodhandle_include

stringhandle_include(stringheader_file, stringcurrent_file, boolis_local_ref)

Description

Called by cpp() to resolv #include and #string directives.

Parameter header_file

File that was requested for inclusion.

Parameter current_file

File where the directive was found.

Parameter is_local_ref

Specifies reference method.

0

Directive was #include <header_file>.

1

Directive was #include "header_file".

Returns

Returns the filename to pass to read_include() if found, and 0 (zero) on failure.

See also

read_include()


Methodread_include

stringread_include(stringfilename)

Description

Called by cpp() to read included files.

Parameter filename

Filename as returned by handle_include().

Returns

Returns a string with the content of the header file on success, and 0 (zero) on failure.

See also

handle_include()


Methodresolv

mixedresolv(stringsymbol, stringfilename, CompilationHandlerhandler)

Description

Called by compile() and cpp() to resolv module references.

Returns

Returns the resolved value, or UNDEFINED on failure.

See also

get_predefines()

Class CompilerEnvironment

Description

predef::CompilerEnvironment that supports handlers.

The compiler environment.

By inheriting this class and overloading the functions, it is possible to make a custom Pike compiler.

Note

Prior to Pike 7.8 this sort of customization has to be done either via custom master objects, or via CompilationHandlers.

See also

CompilationHandler, MasterObject, master(), replace_master()


InheritOrigCompilerEnvironment

inherit predef::CompilerEnvironment : OrigCompilerEnvironment


InheritReporter

inherit Reporter : Reporter

Description

Implements the Reporter API.

See also

Reporter()->report(), Reporter()->SeverityLevel


Methodcompile

programcompile(stringsource, CompilationHandler|voidhandler, int|voidmajor, int|voidminor, program|voidtarget, object|voidplaceholder)

Description

Compile a string to a program.

This function takes a piece of Pike code as a string and compiles it into a clonable program.

The optional argument handler is used to specify an alternative error handler. If it is not specified the current master object will be used.

The optional arguments major and minor are used to tell the compiler to attempt to be compatible with Pike major.minor.

Note

This function essentially performs

program compile(mixed ... args){return PikeCompiler(@args)->compile();}
Note

Note that source must contain the complete source for a program. It is not possible to compile a single expression or statement.

Also note that compile() does not preprocess the program. To preprocess the program you can use compile_string() or call the preprocessor manually by calling cpp().

See also

compile_string(), compile_file(), cpp(), master(), CompilationHandler


Methodcompile_exception

intcompile_exception(mixederr)


Methodformat_exception

string|zeroformat_exception(mixederr)


Methodget_compilation_handler

objectget_compilation_handler(intmajor, intminor)

Description

Get compatibility handler for Pike major.minor.

The default implementation calls the corresponding function in the master object.

Note

This function is typically called by PikeCompiler()->get_compilation_handler().

See also

MasterObject()->get_compilation_handler().


Methodget_default_module

mapping(string:mixed)|objectget_default_module()

Description

Get the default module for the current compatibility level (ie typically the value returned by predef::all_constants()).

The default implementation calls the corresponding function in the master object.

Returns
mapping(string:mixed)|object

Constant table to use.

int(0)

Use the builtin constant table.

Note

This function is typically called by Pike_compiler()->get_default_module().

See also

MasterObject()->get_default_module().


Methodhandle_import

programhandle_import(stringmodule, stringcurrent_file, object|voidhandler)

Description

Look up an import module.

The default implementation calls the corresponding function in the master object.

See also

MasterObject()->handle_import().


Methodhandle_inherit

programhandle_inherit(stringinh, stringcurrent_file, object|voidhandler)

Description

Look up an inherit inh.

The default implementation calls the corresponding function in the master object.

See also

MasterObject()->handle_inherit().


Methodresolv

mixedresolv(stringidentifier, stringfilename, object|voidhandler, object|voidcompat_handler)

Description

Look up identifier in the current context.

The default implementation calls the corresponding function in the handlers (if any), falling back to the master object.

Returns

Returns the value of the identifier if found, and UNDEFINED if not.

Class CompilerEnvironment.CPP

Description

The state for an instance of the preprocessor.

See also

predef::cpp()


Inheritthis_program

inherit ::this_program : this_program


Variablehandler
Variablecompat_handler

CompilationHandler CompilerEnvironment.CPP.handler
CompilationHandler CompilerEnvironment.CPP.compat_handler


Methodapply_handler

protectedmixedapply_handler(stringfun, mixed ... args)


Methodchange_cpp_compatibility

voidchange_cpp_compatibility(intmajor, intminor)

Description

Change the pike compatibility level for this preprocessor to the specified version of Pike.

Parameter major

Major version of Pike to attempt to be compatible with. Specifying a major version of -1 is a short hand for specifying __REAL_MAJOR__ and __REAL_MINOR__.

Parameter minor

Minor version of Pike to attempt to be compatible with.

This function is called by the preprocessor to set the compatibility level.

The default implementation performs some normalization, and then sets compat_major and compat_minor to their respective values (which in turn affects symbols such as __MAJOR__ and __MINOR__).


Methodclear_macros

voidclear_macros()

Description

Clear the set of macros.

It is recomended to call this function when the CPP object is no longer to be used.

See also

define_macro()


Methodcompile_exception

intcompile_exception(mixederr)


Methodcpp_error

voidcpp_error(sprintf_formatmsg, sprintf_args ... arguments)

Description

Convenience function for reporting a cpp error at the current position.

This function calls report() with the same arguments, but prefixed with suitable defaults.

See also

report()


Methodcreate

CompilerEnvironment.CPPCompilerEnvironment.CPP(string|voidcurrent_file, int|string|voidcharset, object|voidhandler, void|intcompat_major, void|intcompat_minor, void|intpicky_cpp)
CompilerEnvironment.CPPCompilerEnvironment.CPP(mapping(string:mixed) options)

Description

Initialize the preprocessor.

Parameter options

If the first argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are then recognized:

"current_file" : string

Name of the current file. It is used for generating #line directives and for locating include files.

"charset" : int|string

Charset to use when processing data.

"handler" : object

Compilation handler.

"compat_major" : int

Sets the major pike version used for compat handling.

"compat_minor" : int

Sets the minor pike version used for compat handling.

"picky_cpp" : int

Generate more warnings.

"keep_comments" : int

This option keeps cpp() from removing comments. Useful in combination with the prefix feature below.

"prefix" : string

If a prefix is given, only prefixed directives will be processed. For example, if the prefix is "foo", then #foo_ifdef COND and foo___LINE__ would be processed, #ifdef COND and __LINE__ would not.

"predefines" : mapping(string:mixed)

Mapping of predefined macros in addition to those returned by CPP()->get_predefines().

Parameter current_file

If the current_file argument has not been specified, it will default to "-".

Parameter charset

Turn on automatic character set detection if 1, otherwise specifies the character set used by the input. Defaults to "ISO-10646".

See also

compile()


Methodcreate

CompilerEnvironment.CPPCompilerEnvironment.CPP(string|voidcurrent_file, int|string|voidcharset, CompilationHandler|voidhandler, void|intcompat_major, void|intcompat_minor, void|intpicky_cpp)
CompilerEnvironment.CPPCompilerEnvironment.CPP(mapping(string:mixed) options)

Description

Initialize the preprocessor.

Parameter options

If the first argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are then recognized:

"current_file" : string

Name of the current file. It is used for generating #line directives and for locating include files.

"charset" : int|string

Charset to use when processing data.

"handler" : CompilationHandler

Compilation handler.

"compat_major" : int

Sets the major pike version used for compat handling.

"compat_minor" : int

Sets the minor pike version used for compat handling.

"picky_cpp" : int

Generate more warnings.

"keep_comments" : int

This option keeps cpp() from removing comments. Useful in combination with the prefix feature below.

"prefix" : string

If a prefix is given, only prefixed directives will be processed. For example, if the prefix is "foo", then #foo_ifdef COND and foo___LINE__ would be processed, #ifdef COND and __LINE__ would not.

Parameter current_file

If the current_file argument has not been specified, it will default to "-".

Parameter charset

Turn on automatic character set detection if 1, otherwise specifies the character set used by the input. Defaults to "ISO-10646".

See also

compile()


Methoddefine_ansi_macros

voiddefine_ansi_macros()

Description

Adds some cpp macros defined by the ANSI-C standards, such as __FILE__, __LINE__, etc.

See also

define_macro(), define_pike_macros()


Methoddefine_macro

voiddefine_macro(stringname, string|object|array|function(:void)|voidvalue, int(-1..)|voidnumargs, int(2bit)|voidflags)

Description

Define a cpp macro.

Parameter name

Name of macro to define. Ending the name with "()" changes the defaults for numargs and flags to 0 and 3 respectively.

Parameter value

Macro definition. Defaults to "1".

Parameter numargs

Number of required arguments to a function-style macro. -1 indicates not function-style. Defaults to -1.

Parameter flags

Bit-wise or of flags affecting the macro behavior:

1

Function style macro with a variable number of arguments. Invalid if numargs is -1.

2

Keep newlines emitted by the macro.

Defaults to 0.

See also

define_multiple_macros()


Methoddefine_multiple_macros

voiddefine_multiple_macros(mapping(string:string|function(:void)|object|array(string|int))|voidpredefs)

Description

Define multiple macros in one operation.

Parameter predefs

Macros to define.

Note

The values predefs mapping may get updated by the function in order to improve performance of a second call.

See also

define_macro(), CompilationHandler()->get_predefines(), _take_over_initial_predefines()


Methoddefine_pike_macros

voiddefine_pike_macros()

Description

Adds some pike-specific cpp macros, such as __DIR__, __VERSION__, [__PIKE__], etc.

See also

define_macro(), define_ansi_macros()


Methodformat_exception

stringformat_exception(mixederr)

Description

Format an exception caught by cpp as a suitable cpp error message.

Parameter err

Caught value.

Returns

Returns one of:

zero

Generate a cpp error using the default format (ie call master()->describe_error(), and replace any newlines with spaces).

string

Cpp error message to report(). The empty string supresses the cpp error.

The default implementation just returns 0.


Methodget_compilation_handler

objectget_compilation_handler(intmajor, intminor)


Methodget_predefines

mapping(string:string|function(:void)|object|array(string|int)) get_predefines()

Description

Get the predefined macros for this preprocessor.

This function is called by init_pike_cpp() to retrieve the set of macros to define at initialization.

The default implementation returns the internal set of predefined macros unless _take_over_initial_predefines() has been called, in which case it instead calls the corresponding function in the master.

Note

This function does NOT return the set of currently defined macros.

See also

init_pike_cpp(), define_multiple_macros(), _take_over_initial_predefines()


Methodhandle_include

stringhandle_include(stringheader_file, stringcurrent_file, boolis_local_ref)


Methodinit_pike_cpp

voidinit_pike_cpp()

Description

Convenience function for initializing the preprocessor to Pike defaults.

The default implementation is essentially:

{
      define_ansi_macros();
      define_pike_macros();
      define_multiple_macros(get_predefines());}

Methodread_include

stringread_include(stringfilename)


Methodreport

voidreport(SeverityLevelseverity, stringfilename, int(1..)linenumber, stringsubsystem, sprintf_formatmessage, sprintf_args ... extra_args)

Description

Report a diagnostic from the preprocessor.

Parameter severity

The severity of the diagnostic.

Parameter filename
Parameter linenumber

Location which triggered the diagnostic.

Parameter subsystem

Typically "cpp".

Parameter message

String with the diagnostic message, with optional sprintf()-style formatting (if any extra_args).

Parameter extra_args

Extra arguments to sprintf().

The default implementation does the following:

  • If there's a handler which implements Reporter()->report(), call it with the same arguments.

  • Otherwise if there's a handler which implements compile_warning() or compile_error() that matches severity, call it with suitable arguments.

  • Otherwise if there's a compat handler, use it in the same manner as the handler.

  • Otherwise fall back to calling ::report() with the same arguments.

Note

In Pike 8.0 and earlier MasterObject()->report() was not called.

See also

Reporter()->report()


Methodreport

voidreport(SeverityLevelseverity, stringfilename, int(1..)linenumber, stringsubsystem, stringmessage, mixed ... extra_args)

Description

Report a diagnostic from the preprocessor.

Parameter severity

The severity of the diagnostic.

Parameter filename
Parameter linenumber

Location which triggered the diagnostic.

Parameter subsystem

Always "cpp".

Parameter message

String with the diagnostic message, with optional sprintf()-style formatting (if any extra_args).

Parameter extra_args

Extra arguments to sprintf().

The default implementation just calls CompilerEnviroment::report() in the parent with the same arguments.

See also

Reporter()->report(), cpp_error()


Methodresolv

mixedresolv(stringsym)

Description

Attempt to resolve a symbol.

The default implementation calls CompilerEnvironment()->resolv() in the parent object, with the remaining arguments taken from the current CPP context.

Returns

Returns the value of sym if found, and UNDEFINED if not.

Class CompilerEnvironment.PikeCompiler

Description

The Pike compiler.

An object of this class compiles a single string of Pike code.


Inheritthis_program

inherit ::this_program : this_program


Variablehandler
Variablecompat_handler

CompilationHandler CompilerEnvironment.PikeCompiler.handler
CompilationHandler CompilerEnvironment.PikeCompiler.compat_handler


Variablecurrent_file

string CompilerEnvironment.PikeCompiler.current_file

Description

The name of the file currently being compiled (during an active compilation).


Variablecurrent_line

int CompilerEnvironment.PikeCompiler.current_line

Description

The current line number (during an active compilation).


Methodapply_attribute_constant

typeapply_attribute_constant(stringattr, mixedvalue, typearg_type, voidcont_type, mappingstate)

Description

Handle constant arguments to attributed function argument types.

Parameter attr

Attribute that arg_type had.

Parameter value

Constant value sent as parameter.

Parameter arg_type

Declared type of the function argument.

Parameter cont_type

Continuation function type after the current argument.

Parameter state

Mapping intended to hold state during checking of multiple arguments.

This function is called when a function is called with the constant value value and it has been successfully matched against arg_type, and arg_type had the type attribute attr.

This function is typically used to perform specialized argument checking and to allow for a strengthening of the function type based on value.

The default implementation handles the following attributes:

sprintf_args

This marks the arguments to sprintf().

sprintf_format and strict_sprintf_format

These mark arguments that will be sent as the first argument to sprintf().

sprintf_result

This marks the return value for sprintf().

sscanf_format and sscanf_76_format

These mark arguments that will be sent as the second argument to sscanf().

sscanf_input

This is the input for sscanf().

Returns

Returns a continuation type if it succeeded in strengthening the type.

Returns UNDEFINED otherwise (this is not an error indication).

See also

pop_type_attribute(), push_type_attribute()


Methodapply_handler

protectedmixedapply_handler(stringfun, mixed ... args)


Methodapply_type_attribute

boolapply_type_attribute(stringattribute, typea, mapping|voidstate)

Description

Type attribute handler.

Parameter attribute

Attribute that a had.

Parameter a

Continuation of the function being called or UNDEFINED indicating that there are no further arguments.

Parameter state

Mapping intended to hold state during checking of multiple arguments.

Called during type checking when there has been successfull partial evaluation of a function type that had the type attribute attribute before the evaluation.

The default implementation implements the attributes:

__deprecated__

__experimental__

Returns

Returns 1 if the type check should be allowed (ie __attribute__(attribute, a)(b)) is valid, and 0 (zero) otherwise.

See also

pop_type_attribute(), push_type_attribute()


Methodchange_compiler_compatibility

voidchange_compiler_compatibility(intmajor, intminor)

Description

Change compiler to attempt to be compatible with Pike major.minor.


Methodcompile

programcompile()

Description

Compile the current source into a program.

This function compiles the current Pike source code into a clonable program.

See also

compile_string(), compile_file(), cpp(), master(), CompilationHandler, create()


Methodcreate

CompilerEnvironment.PikeCompilerCompilerEnvironment.PikeCompiler(string|voidsource, CompilationHandler|voidhandler, int|voidmajor, int|voidminor, program|voidtarget, object|voidplaceholder)

Description

Create a PikeCompiler object for a source string.

This function takes a piece of Pike code as a string and initializes a compiler object accordingly.

Parameter source

Source code to compile.

Parameter handler

The optional argument handler is used to specify an alternative error handler. If it is not specified the current master object at compile time will be used.

Parameter major
Parameter minor

The optional arguments major and minor are used to tell the compiler to attempt to be compatible with Pike major.minor.

Parameter target

__empty_program() program to fill in. The virgin program returned by __empty_program() will be modified and returned by compile() on success.

Parameter placeholder

__null_program() placeholder object to fill in. The object will be modified into an instance of the resulting program on successfull compile. Note that lfun::create() in the program will be called without any arguments.

Note

Note that source must contain the complete source for a program. It is not possible to compile a single expression or statement.

Also note that no preprocessing is performed. To preprocess the program you can use compile_string() or call the preprocessor manually by calling cpp().

Note

Note that all references to target and placeholder should removed if compile() failes. On failure the placeholder object will be destructed.

See also

compile_string(), compile_file(), cpp(), master(), CompilationHandler


Methodeval_type_attribute

typeeval_type_attribute(stringattribute, typet, mappingstate)


Methodget_compilation_handler

objectget_compilation_handler(intmajor, intminor)

Description

Get compatibility handler for Pike major.minor.

Note

This function is called by change_compiler_compatibility().


Methodget_default_module

mapping(string:mixed)|objectget_default_module()

Description

Get the default module for the current compatibility level (ie typically the value returned by predef::all_constants()).

The default implementation calls the corresponding function in the current handler, the current compatibility handler or in the parent CompilerEnvironment in that order.

Returns
mapping(string:mixed)|object

Constant table to use.

int(0)

Use the builtin constant table.

Note

This function is called by change_compiler_compatibility().


Methodhandle_import

programhandle_import(stringmodule)

Description

Look up an import module.


Methodhandle_inherit

programhandle_inherit(stringinh)

Description

Look up an inherit inh in the current program.


Methodindex_type_attribute

boolindex_type_attribute(stringattribute, typea, typei)

Description

Type attribute handler.

Called during type checking when a value of the type a is indexed with a value of type i and a had the type attribute attribute before the comparison.

The default implementation implements the "deprecated" and "experimental" attributes.

Returns

Returns 1 if the type check should be allowed (ie __attribute__(attribute, a)[i]), and 0 (zero) otherwise.

See also

pop_type_attribute(), push_type_attribute()


Methodpop_type_attribute

bool|typepop_type_attribute(stringattribute, typea, typeb, mapping|voidstate)

Description

Type attribute handler.

Called during type checking when a <= b and a had the type attribute attribute before the comparison.

The default implementation implements the "deprecated" and "experimental" attributes.

Returns

Returns one of:

type

An alternative type for a against which b will be matched again.

int(1)

Allow the check (ie __attribute__(attribute, a) <= b).

int(0)

Do not allow the check.

See also

push_type_attribute(), index_type_attribute()


Methodpush_type_attribute

bool|typepush_type_attribute(stringattribute, typea, typeb, mapping|voidstate)

Description

Type attribute handler.

Called during type checking when a <= b and b had the type attribute attribute before the comparison.

The default implementation implements the following attributes:

"deprecated"

Warns about use of deprecated functions and values.

"experimental"

Warns about use of experimental functions and values.

"sprintf_args"

Used for type checking of sprintf() arguments. They are passed along to __handle_sprintf_format().

"sprintf_char"
"sprintf_lfun"
"sprintf_string"
"utf8"

Warns about passing non-UTF-8 string values to places that expect UTF-8 encoded strings.

Returns

Returns one of:

type

An alternative type for b against which a will be matched again.

int(1)

Allow the check (ie a <= __attribute__(attribute, b)).

int(0)

Do not allow the check.

See also

pop_type_attribute(), index_type_attribute(), utf8_string


Methodreport

voidreport(SeverityLevelseverity, stringfilename, intlinenumber, stringsubsystem, stringmessage, mixed ... extra_args)

Description

Report a diagnostic from the compiler.

The default implementation attempts to call the first corresponding function in the active handlers in priority order:

  1. Call handler->report().

  2. Call handler->compile_warning() or handler->compile_error() depending on severity.

  3. Call compat->report().

  4. Call compat->compile_warning() or compat->compile_error() depending on severity.

  5. Fallback: Call CompilerEnvironment()->report() in the parent object.

The arguments will be as follows:

report()

The report() function will be called with the same arguments as this function.

compile_warning()/compile_error()

Depending on the severity either compile_warning() or compile_error() will be called.

They will be called with the filename, linenumber and formatted message as arguments.

Note that these will not be called for the NOTICE severity, and that compile_error() will be used for both ERROR and FATAL.

Note

In Pike 7.8 and earlier the report() function was not called in the handlers.

See also

CompilerEnvironment()->report()


Methodresolv

mixedresolv(stringidentifier)

Description

Resolve the symbol identifier.

The default implementation calls CompilerEnvironment()->resolv() in the parent object, with the remaining arguments taken from the current PikeCompiler context.

Returns

Returns the value of sym if found, and UNDEFINED if not.


Methodsuppress_deprecation_warnings

int(0..2)suppress_deprecation_warnings()

Description

Allows to query whether (during an active compilation) deprecation and experimental warnings are supposed to be suppressed.

Returns

2 if deprecation and experimental warnings should be suppressed, 1 if experimental warnings should be suppressed, 0 otherwise.

Class CompilerEnvironment.PikeCompiler.CompilerState

Description

Keeps the state of a single program/class during compilation.

Note

Not in use yet!

Class CompilerEnvironment.define


Method`()

string res = CompilerEnvironment.define()()

Parameter arguments

Array of arguments to the macro. Zero if no parenthesis.

Parameter context

CPP context we are evaluating in.

Returns

Returns the expansion of the macro on success, and 0 (zero) on failure (typically due to invalid arguments).

Class CompilerEnvironment.lock

Description

This class acts as a lock against other threads accessing the compiler.

The lock is released when the object is destructed.

Class Decoder

Description

Codec used by decode_value() to decode objects, functions and programs which have been encoded by Encoder.nameof in the corresponding Encoder object.


Method__register_new_program

object__register_new_program(programp)

Description

Called to register the program that is being decoded. Might get called repeatedly with several other programs that are being decoded recursively. The only safe assumption is that when the top level thing being decoded is a program, then the first call will be with the unfinished embryo that will later become that program.

Returns

Returns either zero or a placeholder object. A placeholder object must be a clone of __null_program. When the program is finished, the placeholder object will be converted to a clone of it. This is used for pike module objects.


Methodfunctionof

function(:void) functionof(stringdata)

Description

Decode function encoded in data.

This function is called by decode_value() when it encounters encoded functions.

Parameter data

Encoding of some function as returned by Encoder.nameof().

Returns

Returns the decoded function.

See also

objectof(), programof()


Methodobjectof

objectobjectof(stringdata)

Description

Decode object encoded in data.

This function is called by decode_value() when it encounters encoded objects.

Parameter data

Encoding of some object as returned by Encoder.nameof().

Returns

Returns the decoded object.

See also

functionof(), programof()


Methodprogramof

programprogramof(stringdata)

Description

Decode program encoded in data.

This function is called by decode_value() when it encounters encoded programs.

Parameter data

Encoding of some program as returned by Encoder.nameof().

Returns

Returns the decoded program.

See also

functionof(), objectof()

Class Encoder

Description

Codec used by encode_value() to encode objects, functions and programs. Its purpose is to look up some kind of identifier for them, so they can be mapped back to the corresponding instance by decode_value(), rather than creating a new copy.


Methodnameof

mixednameof(object|function(:void)|programx)

Description

Called by encode_value() to encode objects, functions and programs.

Returns

Returns something encodable on success, typically a string. The returned value will be passed to the corresponding objectof(), functionof() or programof() by decode_value().

If it returns UNDEFINED then encode_value starts to encode the thing recursively, so that decode_value later will rebuild a copy.

Note

encode_value() has fallbacks for some classes of objects, functions and programs.

See also

Decoder.objectof(), Decoder.functionof(), Decoder.objectof()

Class Iterator

Description

This is the interface for iterator objects. They implement an interface to a collection or stream of data items and a cursor that can be used to iterate over and examine individual items in the data set.

Iterators are typically created to access a data set in some specific object, array, mapping, multiset or string. An object can have several iterators that access different data sets in it, or the same in different ways. E.g. strings have both an iterator for access char-by-char (String.Iterator), and another for access over splitted substrings (String.SplitIterator). lfun::_get_iterator may be defined in an object to get an instance of the canonical iterator type for it. It's used by e.g. foreach to iterate over objects conveniently.

It's not an error to advance an iterator past the beginning or end of the data set; _iterator_index and _iterator_value will just return UNDEFINED then. An iterator in that state need not keep track of positions, so it's undefined what happens if it's "moved back" into the set of items.

Backward movement for iterators is currently not supported.

See also

predef::get_iterator, lfun::_get_iterator, Array.Iterator, Mapping.Iterator, Multiset.Iterator, String.Iterator, String.SplitIterator, 8.0::Iterator.


Method_iterator_index

optionalprotectedmixed_iterator_index()

Description

Returns the current index, or UNDEFINED if the iterator doesn't point to any item.

If there's no obvious index set then the index is the current position in the data set, counting from 0 (zero).

See also

_iterator_value(), lfun::_iterator_index(), iterator_index()


Method_iterator_next

protectedmixed_iterator_next()

Description

This function advances the iterator one step.

Note

This is the only function that is required in the Pike 9.0 and later iterator API. Presence of this function indicates that the iterator implements the Pike 9.0 API.

Returns

Returns UNDEFINED if there are no more values in the set of elements. It may return any other value if it succeeded in advancing to a new element. The returned value is used as the result for _iterator_index() and _iterator_value() if they are not implemented.

See also

_iterator_prev(), lfun::_iterator_next(), iterator_next(), _iterator_index(), _iterator_value()


Method_iterator_prev

optionalprotectedmixed_iterator_prev()

Description

This function advances the iterator one step backwards.

Returns

Returns UNDEFINED if there are no more values in the set of elements. It may return any other value if it succeeded in advancing to the previous element. The returned value may be used as the result for _iterator_index() and _iterator_value() if they are not implemented.

See also

_iterator_next(), lfun::_iterator_prev(), iterator_prev(), _iterator_index(), _iterator_value()


Method_iterator_value

optionalprotectedmixed_iterator_value()

Description

Returns the current value, or UNDEFINED if the iterator doesn't point to any item.

See also

_iterator_index(), lfun::_iterator_value(), iterator_value()


Method_random

voidrandom(Iteratorarg)

Description

If this function is defined then it sets the iterator to point to before a random item in the accessible set. The random distribution should be rectangular within that set, and the pseudorandom sequence provided by random should be used.

See also

random()


Method_sizeof

intsizeof(Iteratorarg)

Description

Returns the total number of items in the data set according to this iterator. If the size of the data set is unlimited or unknown then this function shouldn't be defined.


Method`+

Iterator res = Iterator() + steps

Description

Returns a clone of this iterator which is advanced the specified number of steps. The amount may be negative to move backwards.

If the iterator doesn't support backward movement it should throw an exception in that case.

See also

_iterator_next, `-


Method`-

Iterator res = Iterator() - steps

Description

Returns a clone of this iterator which is backed up the specified number of steps. The amount may be negative to move forward.

See also

_iterator_next, `+,


Methodcreate

IteratorIterator(void|mixeddata)

Description

Initialize this iterator to access a data set in data. The type of data is specific to the iterator implementation. An iterator may also access some implicit data set, in which case data isn't specified at all.

The iterator initially points to before the first item in the data set, if there is any.

The iterator does not need to support being reused, so this function is typically declared protected.

Note

In the iterator API in Pike 8.0 and earlier the iterators initially pointed to the first element.

See also

CompatIterator


Methodfirst

optionalboolfirst()

Description

If this function is defined then it resets the iterator to point to before the first item.

Returns

Returns zero if there are no items at all in the data set, one otherwise.

Note

It's not enough to set the iterator to the earliest accessible item. If the iterator doesn't support backing up to the original start position then this function should not be implemented.


Methodset_index

optionalvoidset_index(zeroindex)

Description

If this function is defined it should set the iterator at the specified index.

Note

It should be possible to set the index at the end of the iterator.

Class Iterator.CompatIterator

Description

Wrapper for iterators implementing the Pike 8.0 and earlier iterator API (8.0::Iterator). Used transparently by predef::get_iterator() to provide an iterator suitable for foreach().

Note

This class provides only those functions that are required by the iterator API. It does not proxy any other functions.

See also

get_iterator(), 8.0::Iterator


InheritIterator

inherit Iterator : Iterator


Methodcreate

Iterator.CompatIteratorIterator.CompatIterator(Iteratorold_style_iterator)

Class MasterObject

Description

Master control program for Pike.

See also

predef::master(), predef::replace_master()


InheritCodec

inherit Codec : Codec


InheritCompatResolver

inherit CompatResolver : CompatResolver


InheritCompilationHandler

inherit CompilationHandler : CompilationHandler

Description

The master object acts as fallback compilation handler for compile() and cpp().


InheritPike_9_0_master

protected inherit Pike_9_0_master : Pike_9_0_master

Description

Namespaces for compat masters.

This inherit is used to provide compatibility namespaces for get_compat_master().

See also

get_compat_master()


Inherit__master

inherit Builtin.__master : __master


Constantbt_max_string_len

constantint MasterObject.bt_max_string_len

Description

This constant contains the maximum length of a function entry in a backtrace. Defaults to 200 if no BT_MAX_STRING_LEN define has been given.


Constantout_of_date_warning

constantint MasterObject.out_of_date_warning

Description

Should Pike complain about out of date compiled files. 1 means yes and 0 means no. Controlled by the OUT_OF_DATE_WARNING define.


VariableDecoder

program MasterObject.Decoder

Description

This program in the master is cloned and used as codec by decode_value if it wasn't given any codec. An instance is only created on-demand the first time decode_value encounters something for which it needs a codec, i.e. the result of a call to Pike.Encoder.nameof.

See also

Decoder, Pike.Decoder


VariableEncoder

program MasterObject.Encoder

Description

This program in the master is cloned and used as codec by encode_value if it wasn't given any codec. An instance is only created on-demand the first time encode_value encounters something for which it needs a codec, i.e. an object, program, or function.

See also

Encoder, Pike.Encoder


Variable_pike_file_name
Variable_master_file_name

string MasterObject._pike_file_name
string MasterObject._master_file_name

Description

These are useful if you want to start other Pike processes with the same options as this one was started with.


Variablecflags

string MasterObject.cflags

Description

Flags suitable for use when compiling Pike C modules


Variablecompat_major

int MasterObject.compat_major

Description

Major pike version to emulate.

This is typically set via the option "-V".

See also

compat_minor


Variablecompat_minor

int MasterObject.compat_minor

Description

Minor pike version to emulate.

This is typically set via the option "-V".

See also

compat_major


Variablecurrentversion

Version MasterObject.currentversion

Description

Version information about the current Pike version.


Variabledoc_prefix

string MasterObject.doc_prefix

Description

Prefix for autodoc files.


Variableprograms
Variabledocumentation
Variablesource_cache

mapping(string:program|NoValue) MasterObject.programs
mapping(program:object) MasterObject.documentation
mapping(program:string) MasterObject.source_cache

Description

Mapping containing the cache of currently compiled files.

This mapping currently has the following structure:

filename : program

The filename path separator is / on both NT and UNIX.

Note

Special cases: The current master program is available under the name "/master", and the program containing the main function under "/main".


Variableinclude_prefix

string MasterObject.include_prefix

Description

Prefix for Pike-related C header files.


Variableis_pike_master

int MasterObject.is_pike_master

Description

This integer variable should exist in any object that aspires to be the master. It gets set to 1 when the master is installed, and is therefore set in any object that is or has been the master. That makes the Encoder class encode references to the master and all ex-masters as references to the current master object.


Variableldflags

string MasterObject.ldflags

Description

Flags suitable for use when linking Pike C modules


Variableno_precompile

int MasterObject.no_precompile

Description

Turn off loading of precompiled modules.


Variableshow_if_constant_errors

int MasterObject.show_if_constant_errors

Description

Show compilation warnings from compilation of cpp()#if constant() expressions.

This is typically set via the option "--picky-cpp".


Variablewant_warnings

int MasterObject.want_warnings

Description

If not zero compilation warnings will be written out on stderr.


Method_main

void_main(array(string(8bit)) orig_argv)

Description

This function is called when all the driver is done with all setup of modules, efuns, tables etc. etc. and is ready to start executing _real_ programs. It receives the arguments not meant for the driver.


Methodadd_filesystem_handler

Filesystem.Base|zeroadd_filesystem_handler(stringmountpoint, Filesystem.Base|zerofilesystem)

Description

Mount a filesystem handler to be used by the resolver. On its own does nothing, but may be used with add_module_path() and friends to enable modules to be loaded from Filesystem objects.

Parameter mountpoint

The location in the filesystem to mount the handler

Parameter filesystem

A filesystem object that will handle requests for the given mountpoint.

Example
master()->add_filesystem_handler("/foo/bar.zip",Filesystem.Zip("/foo/bar.zip"));
    master()->add_module_path("/foo/bar.zip/lib");
See also

find_handler_for_path()


Methodasyncp

boolasyncp()

Description

Returns 1 if we're in async-mode, e.g. if the main method has returned a negative number.


Methodbackend_thread

objectbackend_thread()

Description

The backend_thread() function is useful to determine if you are the backend thread - important when doing async/sync protocols. This method is only available if thread_create is present.


Methodcast_to_object

objectcast_to_object(stringoname, stringcurrent_file, CompilationHandler|voidcurrent_handler)

Description

This function is called when the drivers wants to cast a string to an object because of an implict or explicit cast. This function may also receive more arguments in the future.


Methodcast_to_object

objectcast_to_object(stringstr, string|voidcurrent_file)

Description

Called by the Pike runtime to cast strings to objects.

Parameter str

String to cast to object.

Parameter current_file

Filename of the file that attempts to perform the cast.

Returns

Returns the resulting object.

See also

cast_to_program()


Methodcast_to_program

programcast_to_program(stringpname, stringcurrent_file, CompilationHandler|voidhandler)

Description

This function is called when the driver wants to cast a string to a program, this might be because of an explicit cast, an inherit or a implict cast. In the future it might receive more arguments, to aid the master finding the right program.


Methodcast_to_program

programcast_to_program(stringstr, string|voidcurrent_file)

Description

Called by the Pike runtime to cast strings to programs.

Parameter str

String to cast to object.

Parameter current_file

Filename of the file that attempts to perform the cast.

Returns

Returns the resulting program.

See also

cast_to_object()


Methodcompile_error

voidcompile_error(stringfile, intline, stringerr)

Description

This function is called whenever a compile error occurs. line is zero for errors that aren't associated with any specific line. err is not newline terminated.

See also

compile_warning(), compile_exception(), get_inhibit_compile_errors(), set_inhibit_compile_errors(),


Methodcompile_exception

intcompile_exception(array|objecttrace)

Description

This function is called when an exception is caught during compilation. Its message is also reported to compile_error if this function returns zero.

See also

compile_error(), compile_warning(), get_inhibit_compile_errors(), set_inhibit_compile_errors(),


Methodcompile_warning

voidcompile_warning(stringfile, intline, stringerr)

Description

This function is called whenever a compile warning occurs. line is zero for warnings that aren't associated with any specific line. err is not newline terminated.

See also

compile_error(), compile_exception(), get_inhibit_compile_errors(), set_inhibit_compile_errors(),


Methoddecode_charset

stringdecode_charset(stringdata, stringcharset)

Description

This function is called by cpp() when it wants to do character code conversion.


Methoddecode_charset

stringdecode_charset(stringraw, stringcharset)

Description

Convert raw from encoding charset to UNICODE.

This function is called by cpp() when it encounters #charset directives.

Parameter raw

String to convert.

Parameter charset

Name of encoding that raw uses.

Returns

raw decoded to UNICODE, or 0 (zero) if the decoding failed.

See also

Charset


Methoddescribe_backtrace

stringdescribe_backtrace(mixedexception)

Description

Called by various routines to format a readable description of an exception.

Parameter exception

Something that was thrown. Usually an Error.Generic object, or an array with the following content:

Array
stringmsg

Error message.

array(backtrace_frame|array(mixed)) backtrace

Backtrace to the point where the exception occurred.

Returns

Returns a string describing the exeception.

Note

Usually added by the initialization code the global name space with add_constant().

See also

predef::describe_backtrace()


Methoddescribe_function

string|zerodescribe_function(function(:void) f)

Description

Function called by describe_backtrace() to describe functions in the backtrace.


Methoddescribe_module

stringdescribe_module(object|programmod, array(object)|voidret_obj)

Description

Describe the path to the module mod.

Parameter mod

If mod is a program, attempt to describe the path to a clone of mod.

Parameter ret_obj

If an instance of mod is found, it will be returned by changing element 0 of ret_obj.

Returns

The a description of the path.

Note

The returned description will end with a proper indexing method currently either "." or "->".


Methoddescribe_object

string|zerodescribe_object(objecto)

Description

Function called by sprintf("%O") for objects that don't have an lfun::_sprintf(), or have one that returns UNDEFINED.


Methoddescribe_program

string|zerodescribe_program(program|function(:void) p)

Description

Function called by sprintf("%O") for programs.


Methodenable_source_cache

voidenable_source_cache()

Description

Enable caching of sources from compile_string()


Methodfc_reverse_lookup

stringfc_reverse_lookup(objectobj)

Description

Returns the path for obj in fc, if it got any.


Methodfind_handler_for_path

string|zerofind_handler_for_path(stringfile)

Description

Return the mountpoint for the filesystem handler handling the file (if any).

See also

add_filesystem_handler()


Methodget_compat_master

objectget_compat_master(intmajor, intminor)

Description

Return a master object compatible with the specified version of Pike.

This function is used to implement the various compatibility versions of master().

See also

get_compilation_handler(), master()


Methodget_compilation_handler

CompilationHandlerget_compilation_handler(intmajor, intminor)

Description

Get compilation handler for simulation of Pike vmajor.minor.

This function is called by cpp() when it encounters #pike directives.

Parameter major

Major version.

Parameter minor

Minor version.

Returns

Returns a compilation handler for Pike >= major.minor.


Methodget_inhibit_compile_errors

bool|CompilationHandler|function(string, int, string:void) get_inhibit_compile_errors()

Description

Get the current compile error, warning and exception behaviour.

See set_inhibit_compile_errors() for details.

See also

set_inhibit_compile_errors()


Methodget_precompiled_mtime

intget_precompiled_mtime(stringid)

Description

Given an identifier returned by query_precompiled_names, returns the mtime of the precompiled entry. Returns -1 if there is no entry.


Methodhandle_attribute

optionalboolhandle_attribute(mixedvalue, stringattribute)

Description

This function is called in runtime check_types mode (-rt), when encountering a soft cast to an attributed type.

Parameter value

Value that is about to receive the attribute.

Parameter attribute

Type attribute to validate.

Returns

Returns one of:

1

If the attribute is valid for the value.

0

If the attribute is not valid for the value.

UNDEFINED

If the attribute is unsupported.

The default master implements validation of the "utf8" attribute.


Methodhandle_error

voidhandle_error(mixedexception)

Description

Called by the Pike runtime if an exception isn't caught.

Parameter exception

Value that was throw()'n.

See also

describe_backtrace()


Methodhandle_error

voidhandle_error(array|objecttrace)

Description

This function is called when an error occurs that is not caught with catch().


Methodhandle_inherit

programhandle_inherit(stringpname, stringcurrent_file, CompilationHandler|voidhandler)

Description

This function is called whenever a inherit is called for. It is supposed to return the program to inherit. The first argument is the argument given to inherit, and the second is the file name of the program currently compiling. Note that the file name can be changed with #line, or set by compile_string, so it can not be 100% trusted to be a filename. previous_object(), can be virtually anything in this function, as it is called from the compiler.


Methodmaster_read_file

string|zeromaster_read_file(stringfile)

Description

Read a file from the master filesystem.

The master filesystem defaults to the system filesystem, but additional mountpoints may be added via add_filesystem_handler().

All file I/O performed by the MasterObject is performed via this function and its related functions.

See also

add_filesystem_handler(), find_handler_for_path(), master_get_dir(), master_file_stat()


Methodmodule_defined

array(string) module_defined(object|programmod)

Description

Find the files in which mod is defined, as they may be hidden away in joinnodes and dirnodes

Parameter mod

The module we are looking for.

Returns

An array of strings with filenames. (one for each file in a joinnode, or just one otherwise)


Methodobjects_reverse_lookup

programobjects_reverse_lookup(objectobj)

Description

Returns the program for obj, if known to the master.


Methodprogram_path_to_name

stringprogram_path_to_name(stringpath, string|voidmodule_prefix, string|voidmodule_suffix, string|voidobject_suffix)

Description

Converts a module path on the form "Foo.pmod/Bar.pmod" or "/path/to/pike/lib/modules/Foo.pmod/Bar.pmod" to a module identifier on the form "Foo.Bar".

If module_prefix or module_suffix are given, they are prepended and appended, respectively, to the returned string if it's a module file (i.e. ends with ".pmod" or ".so"). If object_suffix is given, it's appended to the returned string if it's an object file (i.e. ends with ".pike").


Methodprograms_reverse_lookup

stringprograms_reverse_lookup(programprog)

Description

Returns the path for prog in programs, if it got any.


Methodquery_precompiled_names

array(string) query_precompiled_names(stringfname)

Description

Returns identifiers (e.g. file names) of potentially precompiled files in priority order.


Methodread_precompiled

stringread_precompiled(stringid)

Description

Given an identifier returned by query_precompiled_names, returns the precompiled entry. Can assume the entry exists.


Methodruntime_warning

voidruntime_warning(stringsubsystem, stringmsg, mixed|voiddata)

Description

Called by the Pike runtime to warn about data inconsistencies.

Parameter subsystem

Runtime subsystem where the warning was generated. Currently the following subsystems may call this function:

"gc"

The garbage collector.

"runtime"

The runtime itself.

Parameter msg

Warning message.

Parameter data

Optional data that further describes the warning specified by msg.

Currently the following subsystems and messages are defined:

subsystemmessagedata
"gc""bad_cycle"arraycycle

A cycle where the destruction order isn't deterministic was detected by the garbage collector.

cycle is an array of the elements in the cycle.

"runtime""unsupported_compat"Versionrequested_version

Compatibility with a version older than the oldest supported version was requested.

requested_version is the requested version.


Methodruntime_warning

voidruntime_warning(stringwhere, stringwhat, mixed ... args)

Description

Called for every runtime warning. The first argument identifies where the warning comes from, the second identifies the specific message, and the rest depends on that. See code below for currently implemented warnings.


Methodset_inhibit_compile_errors

voidset_inhibit_compile_errors(bool|CompilationHandler|function(string, int, string:void) behaviour)

Description

Set the compile error, warning and exception behaviour.

Parameter behaviour

The desired behaviour. One of:

int(0)

Output compilation errors and warnings to stderr. This is the default behaviour.

int(1)

Inhibit output of compilator diagnostics.

function(string, int, string:void)

Function to call for compilation errors. Compilation warnings and exceptions are inhibited.

The function will be called with the same arguments as those passed to compile_error().

CompilationHandler

Compilation handler to use for diagnostics.

Note

Note that the behaviour is thread local, and is not copied to new threads when they are created.

See also

get_inhibit_compile_errors()


Methodshow_doc

objectshow_doc(program|object|function(:void) obj)

Description

Show documentation for the item obj

Parameter obj

The object for which the documentation should be shown

Returns

an AutoDoc object


Methodthread_quanta_exceeded

voidthread_quanta_exceeded(Thread.Threadthread, intns)

Description

Function called when a thread has exceeded the thread quanta.

Parameter thread

Thread that exceeded the thread quanta.

Parameter ns

Number of nanoseconds that the thread executed before allowing other threads to run.

The default master prints a diagnostic and the thread backtrace to Stdio.stderr.

Note

This function runs in a signal handler context, and should thus avoid handling of mutexes, etc.

See also

get_thread_quanta(), set_thread_quanta()


Methodunregister

voidunregister(programp)

Description

Unregister a program that was only partially compiled.

Called by compile() to clean up references to partially compiled programs.

Parameter p

Partially compiled program that should no longer be referenced.

FIXME

Shouldn't this function be in the compilation handler?

Class MasterObject.Codec

Description

Encoder and Decoder rolled into one. This is for mainly compatibility; there's typically no use combining encoding and decoding into the same object.


InheritDecoder

inherit Decoder : Decoder


InheritEncoder

inherit Encoder : Encoder


Methodcreate

MasterObject.CodecMasterObject.Codec(void|mixedencoded)

Description

The optional argument is the thing to encode; it's passed on to Encoder.

Class MasterObject.CompatResolver

Description

Resolver of symbols not located in the program being compiled.


Variablefallback_resolver

CompatResolver MasterObject.CompatResolver.fallback_resolver

Description

If we fail to resolv, try the fallback.

Typical configuration:

0.6->7.0->7.2-> ... ->master

Variablehandler_root_modules

mapping(CompilationHandler:joinnode) MasterObject.CompatResolver.handler_root_modules

Description

Lookup from handler module to corresponding root_module.


Variablepike_include_path

array(string) MasterObject.CompatResolver.pike_include_path

Description

The complete include search path


Variablepike_module_path

array(string) MasterObject.CompatResolver.pike_module_path

Description

The complete module search path


Variablepike_program_path

array(string) MasterObject.CompatResolver.pike_program_path

Description

The complete program search path


Variableroot_module

joinnode MasterObject.CompatResolver.root_module

Description

Join node of the root modules for this resolver.


Variablesystem_module_path

array(string) MasterObject.CompatResolver.system_module_path

Description

The pike system module path, not including any set by the user.


Methodadd_include_path

voidadd_include_path(stringtmp)

Description

Add a directory to search for include files.

This is the same as the command line option -I.

Note

Note that the added directory will only be searched when using < > to quote the included file.

See also

remove_include_path()


Methodadd_module_path

voidadd_module_path(stringpath, string|voidsubpath)

Description

Add a directory to search for modules.

This is the same as the command line option -M.

See also

remove_module_path()

Parameter path

a string containing a path to search for Pike modules. May be a directory, or a path to a ZIP archive. If a ZIP archive path is provided, modules will be loaded from a directory, "modules" within the ZIP archive (see the subpath argument).

Parameter subpath

if path is a ZIP archive, this argument will determine the path within the archive to be searched.


Methodadd_predefine

voidadd_predefine(stringname, mixedvalue)

Description

Add a define (without arguments) which will be implicitly defined in cpp calls.


Methodadd_program_path

voidadd_program_path(stringtmp)

Description

Add a directory to search for programs.

This is the same as the command line option -P.

See also

remove_program_path()


Methodcreate

MasterObject.CompatResolverMasterObject.CompatResolver(mixedversion, CompatResolver|voidfallback_resolver)

Description

The CompatResolver is initialized with a value that can be casted into a "%d.%d" string, e.g. a version object.

It can also optionally be initialized with a fallback resolver.


Methodget_default_module

mappingget_default_module()

Description

Return the default module for the CompatResolver.

This is the mapping that corresponds to the predef:: name space for the compatibility level, and is the value returned by all_constants() for the same.


Methodget_predefines

mappingget_predefines()

Description

Returns a mapping with the current predefines.


Methodhandle_include

string|zerohandle_include(stringf, stringcurrent_file, intlocal_include)

Description

This function is called whenever an #include directive is encountered. It receives the argument for #include and should return the file name of the file to include.

See also

read_include()


Methodinstantiate_static_modules

protectedmapping(string:mixed) instantiate_static_modules(object|mappingstatic_modules)

Description

Instantiate static modules in the same way that dynamic modules are instantiated.


Methodread_include

stringread_include(stringf)

Description

Read the file specified by handle_include().

See also

handle_include()


Methodremove_include_path

voidremove_include_path(stringtmp)

Description

Remove a directory to search for include files.

This function performs the reverse operation of add_include_path().

See also

add_include_path()


Methodremove_module_path

voidremove_module_path(stringtmp)

Description

Remove a directory to search for modules.

This function performs the reverse operation of add_module_path().

See also

add_module_path()


Methodremove_predefine

voidremove_predefine(stringname)

Description

Remove a define from the set that are implicitly defined in cpp calls.


Methodremove_program_path

voidremove_program_path(stringtmp)

Description

Remove a directory to search for programs.

This function performs the reverse operation of add_program_path().

See also

add_program_path()


Methodresolv

mixedresolv(stringidentifier, string|voidcurrent_file, CompilationHandler|voidcurrent_handler, CompilationHandler|voidcurrent_compat_handler)

Description

Resolve the identifier expression.

Returns

Returns the value of the identifier if it exists, and UNDEFINED otherwise.


Methodresolv_base

mixedresolv_base(stringidentifier, string|voidcurrent_file, CompilationHandler|voidcurrent_handler, CompilationHandler|voidcurrent_compat_handler)

Description

Look up identifier in the root module.


Methodresolv_or_error

mixedresolv_or_error(stringidentifier, string|voidcurrent_file, void|CompilationHandlercurrent_handler)

Description

Same as resolv, but throws an error instead of returning UNDEFINED if the resolv failed.

Class MasterObject.Decoder

Description

Codec for use with decode_value. This is the decoder corresponding to Encoder. See that one for more details.

Parameter fname

Name of file being decoded.

Parameter placeholder

Make a singleton object of the program being decoded. One of:

void|zero

Do not make an object.

object

Object to alter into the singleton. MUST be a clone of __null_program().

__deprecated__(int(1))

Old API: Generate a singleton object.

Parameter handler

Handler object to use.


Variablefname
Variableplaceholder
Variablehandler

void|string MasterObject.Decoder.fname
void|__deprecated__(int)|object MasterObject.Decoder.placeholder
void|CompilationHandler MasterObject.Decoder.handler


Method__create__

protectedlocalvoid__create__(void|stringfname, void|__deprecated__(int)|objectplaceholder, void|CompilationHandlerhandler)


Methodcreate

MasterObject.DecoderMasterObject.Decoder(void|stringfname, void|__deprecated__(int)|objectplaceholder, void|CompilationHandlerhandler)


Methoddecode_object

array(mixed)|zerodecode_object(objecto, mixeddata)

Description

Restore the state of an encoded object.

Parameter o

Object to modify.

Parameter data

State information from Encoder()->encode_object().

The default implementation calls o->_decode(data) if the object has an _decode(), otherwise if data is an array, returns it to indicate that lfun::create() should be called.

Note

This function is called beforelfun::create() in the object has been called, but after lfun::__INIT() has been called.

Returns

Returns an array to indicate to the caller that lfun::create() should be called with the elements of the array as arguments.

Returns 0 (zero) to inhibit calling of lfun::create().

See also

Encoder()->encode_object()

Class MasterObject.Describer

Description

Class used by describe_backtrace() to describe values in backtraces.


InheritDestructImmediate

inherit _static_modules.Builtin.DestructImmediate : DestructImmediate

Class MasterObject.Encoder

Description

Codec for use with encode_value. It understands all the standard references to builtin functions, pike modules, and the main program script.

The format of the produced identifiers are documented here to allow extension of this class:

The produced names are either strings or arrays. The string variant specifies the thing to look up according to the first character:

'c' Look up in all_constants(). 's' Look up in _static_modules. 'r' Look up with resolv(). 'p' Look up in programs. 'o' Look up in programs, then look up the result in objects. 'f' Look up in fc.

In the array format, the first element is a string as above and the rest specify a series of things to do with the result:

A string Look up this string in the result. 'm' Get module object in dirnode. 'p' Do object_program(result).

All lowercase letters and the symbols ':', '/' and '.' are reserved for internal use in both cases where characters are used above.


Methodcreate

MasterObject.EncoderMasterObject.Encoder(void|mixedencoded)

Description

Creates an encoder instance. If encoded is specified, it's encoded instead of being reverse resolved to a name. That's necessary to encode programs.


Methodnameof

string|arraynameof(mixedwhat, void|array(object) module_object)

Description

When module_object is set and the name would end with an object_program step (i.e. 'p'), then drop that step so that the name corresponds to the object instead. module_object[0] will receive the found object.

Class MasterObject.Pike_7_8_master

Description

Pike 7.8 master compatibility interface.

Most of the interface is implemented via mixin, or overloading by more recent masters.

This interface is used for compatibility with Pike 7.8.

Deprecated

Replaced by predef::MasterObject.

See also

get_compat_master(), master(), predef::MasterObject

Class MasterObject.Pike_8_0_master

Description

Pike 8.0 master compatibility interface.

Most of the interface is implemented via mixin, or overloading by more recent masters.

This interface is used for compatibility with Pike 8.0.

Deprecated

Replaced by predef::MasterObject.

See also

get_compat_master(), master(), predef::MasterObject


InheritPike_7_8_master

inherit Pike_7_8_master : Pike_7_8_master

Class MasterObject.Pike_9_0_master

Description

Pike 9.0 master compatibility interface.

Most of the interface is implemented via mixin, or overloading by more recent masters.

This interface is used for compatibility with Pike 9.0.

Deprecated

Replaced by predef::MasterObject.

See also

get_compat_master(), master(), predef::MasterObject


InheritPike_8_0_master

inherit Pike_8_0_master : Pike_8_0_master

Class MasterObject.Version

Description

Contains version information about a Pike version.


Variablemajor
Variableminor

int MasterObject.Version.major
int MasterObject.Version.minor

Description

The major and minor parts of the version.


Method`<
Method`>
Method`==
Method__hash

int res = MasterObject.Version() < v
int res = MasterObject.Version() > v
int res = MasterObject.Version() == v
inthash_value(MasterObject.Versionarg)

Description

Methods define so that version objects can be compared and ordered.


Methodcast

(int)MasterObject.Version()
(float)MasterObject.Version()
(string)MasterObject.Version()
(array)MasterObject.Version()
(mapping)MasterObject.Version()
(multiset)MasterObject.Version()

Description

The version object can be casted into a string.


Methodcreate

MasterObject.VersionMasterObject.Version(intmajor, intminor)

Description

Set the version in the object.

Class MasterObject.dirnode

Description

Module node representing a single directory.

See also

joinnode


Variabledirname
Variablecompilation_handler
Variablename

string MasterObject.dirnode.dirname
CompilationHandler|void MasterObject.dirnode.compilation_handler
string|void MasterObject.dirnode.name


Method__create__

protectedlocalvoid__create__(stringdirname, CompilationHandler|voidcompilation_handler, string|voidname)

Class MasterObject.joinnode

Description

Module node holding possibly multiple directories, and optionally falling back to another level.

See also

dirnode


Variablejoined_modules
Variablecompilation_handler
Variablefallback_module
Variablename

array(object|mapping) MasterObject.joinnode.joined_modules
CompilationHandler|void MasterObject.joinnode.compilation_handler
joinnode|mapping(mixed:int(0))|void MasterObject.joinnode.fallback_module
string|void MasterObject.joinnode.name


Method__create__

protectedlocalvoid__create__(array(object|mapping) joined_modules, CompilationHandler|voidcompilation_handler, joinnode|mapping(mixed:int(0))|voidfallback_module, string|voidname)

Class RandomInterface


Methodrandom

arrayrandom(mappingm)

Description

Returns a random index-value pair from the mapping.

Array
mixed0

The index of the mapping entry.

mixed1

The value f the mapping entry.

Throws

Throws an exception if the mapping is empty.


Methodrandom

floatrandom(floatmax)

Description

This function returns a random number in the range 0 .. max.

See also

Random


Methodrandom

intrandom(intmax)

Description

This function returns a random number in the range 0 .. max-1.

See also

Random


Methodrandom

mixedrandom(objecto)

Description

If random is called with an object, lfun::_random will be called in the object.

Throws

Throws an exception if the object doesn't have a _random method.

See also

lfun::_random()


Methodrandom

mixedrandom(array|multisetx)

Description

Returns a random element from x.

Throws

Throws an exception if the array or multiset is empty.


Methodrandom_string

string(8bit)random_string(int(0..))

Description

Prototype for the randomness generating function.

Override this symbol to implement a usable class.

Class RandomSystem


InheritRandomInterface

inherit RandomInterface : RandomInterface


Methodrandom_string

string(8bit)random_string(int(0..)len)

Description

Return a string of random data from the system randomness pool.

On POSIX platforms this reads random data from /dev/urandom on other platforms it may use other methods.

Throws

May throw errors on unexpected state.

Class Reporter

Description

API for reporting parse errors and similar.


Methodreport

voidreport(SeverityLevelseverity, stringfilename, int(1..)linenumber, stringsubsystem, stringmessage, mixed ... extra_args)

Description

Report a diagnostic from the compiler.

Parameter severity

The severity of the diagnostic.

Parameter filename
Parameter linenumber

Location which triggered the diagnostic.

Parameter subsystem

Compiler subsystem that generated the diagnostic.

Parameter message

sprintf()-style formatting string with the diagnostic message.

Parameter extra_args

Extra arguments to sprintf().

The default implementation does the following:

  • If there's a MasterObject()->report(), call it with the same arguments as ourselves.

  • Otherwise depending on severity:

    NOTICE

    Ignored.

    WARNING

    Calls MasterObject()->compile_warning().

    ERROR

    Calls MasterObject()->compile_error().

    FATAL

If there's no master object yet, the diagnostic is UTF8-encoded and output to Stdio.stderr.

Note

In Pike 7.8 and earlier MasterObject()->report() was not called.

In Pike 8.0 the fallback output was not UTF8-encoded.

See also

PikeCompiler()->report()

Enum Reporter.SeverityLevel

Description

Message severity level. { NOTICE, WARNING, ERROR, FATAL }

See also

report()


ConstantNOTICE
ConstantWARNING
ConstantERROR
ConstantFATAL

constant Reporter.NOTICE
constant Reporter.WARNING
constant Reporter.ERROR
constant Reporter.FATAL

Class __dirnode


Inheritdirnode

inherit MasterObject.dirnode : dirnode

Class __joinnode


Inheritjoinnode

inherit MasterObject.joinnode : joinnode

Class mklibpike


Methodparse

mapping(string:array(array(Parser.C.Token))) parse(array(Parser.C.Token) tokens)

Description

Returns a mapping from symbol to a tuple of return type and parameters.

Class mklibpike.C_Include_Handler


Variablesearch_path

array(string) mklibpike.C_Include_Handler.search_path


Method__create__

protectedlocalvoid__create__(array(string) search_path)


Methodcreate

mklibpike.C_Include_Handlermklibpike.C_Include_Handler(array(string) search_path)

Class string_assignment


Method`[]

int res = string_assignment()[ i ]

Description

String index operator.


Method`[]=

string_assignment()[ i ] = j

Description

String assign index operator.

Module Arg

Description

Argument parsing module

This module supports two rather different methods of argument parsing. The first is suitable quick argument parsing without much in the way of checking:

int main(int c,array(string) argv ){mapping arguments =Arg.parse(argv);array files = arguments[Arg.REST];if( arguments->help ) print_help();
  ...
}

The Arg.parse method will return a mapping from argument name to the argument value, if any.

Non-option arguments will be placed in the index Arg.REST

The second way to use this module is to inherit the Options class and add supported arguments.

class MyArguments {inheritArg.Options;string help_pre ="Usage: somecommand";
   Opt verbose = NoOpt("-v")|NoOpt("--verbose");string verbose_help ="Turn on verbose output";
   Opt help = MaybeOpt("--help");
   Opt output = HasOpt("--output")|HasOpt("-o");string output_help ="Determine where output goes to";string help_post ="Command aborted";};

Then, in main:

MyArguments args = MyArguments(argv);

See the documentation for OptLibrary for details about the various Opt classes.


ConstantAPP

constant Arg.APP

Description

Constant used to represent the name of the application from the command line. Can be used when indexing an Options object.


ConstantPATH

constant Arg.PATH

Description

Constant used to represent the full path of the application from the command line. Can be used when indexing an Options object.


ConstantREST

constant Arg.REST

Description

Constant used to represent command line arguments not identified as options. Can be used both in the response mapping from parse and when indexing an Options object.


Methodparse

mapping(string:string|int(1..)) parse(array(string) argv)

Description

Convenience function for simple argument parsing.

Handles the most common cases.

The return value is a mapping from option name to the option value.

The special index Arg.REST will be set to the remaining arguments after all options have been parsed.

The following argument syntaxes are supported:

--foo         ->  "foo":1
--foo=bar     ->  "foo":"bar"-bar          ->  "b":1,"a":1,"r":1
-bar=foo      ->  "b":1,"a":1,"r":"foo"(?)
--foo --bar   ->  "foo":1,"bar":1
--foo - --bar ->  "foo":1
--foo x --bar ->  "foo":1 (?)-foo          ->  "f":1,"o":2
-x -x -x      ->  "x":3
Example
void main(int n,array argv){mapping opts =Arg.parse(argv);
  argv = opts[Arg.REST];if( opts->help )/*... */}

Class Arg.LowOptions


InheritOptLibrary

protected inherit OptLibrary : OptLibrary


Variableapplication

protectedstring Arg.LowOptions.application


Variableargv

protectedarray(string) Arg.LowOptions.argv


Variableopts

protectedmapping(string:Opt) Arg.LowOptions.opts


Variablevalues

protectedmapping(string:int(1)|string) Arg.LowOptions.values


Methodcast

(int)Arg.LowOptions()
(float)Arg.LowOptions()
(string)Arg.LowOptions()
(array)Arg.LowOptions()
(mapping)Arg.LowOptions()
(multiset)Arg.LowOptions()


Methodcreate

Arg.LowOptionsArg.LowOptions(array(string) _argv, void|mapping(string:string) env)


Methodunhandled_argument

protectedboolunhandled_argument(array(string) argv, mapping(string:string) env)

Class Arg.OptLibrary

Description

This class contains a library of parser for different type of options.

Class Arg.OptLibrary.Default

Description

Default value for a setting.

Example

Opt output = HasOpt("-o")|Default("a.out");


InheritOpt

inherit Opt : Opt

Class Arg.OptLibrary.Env

Description

Environment fallback for an option. Can of course be used as only Opt source.

Example

Opt debug = NoOpt("--debug")|Env("MY_DEBUG");


InheritOpt

inherit Opt : Opt

Class Arg.OptLibrary.HasOpt

Description

Parses an option that has a parameter. --foo=bar, -x bar and -x=bar will set the variable to bar.

Example

Opt user = HasOpt("--user")|HasOpt("-u");


InheritNoOpt

inherit NoOpt : NoOpt

Class Arg.OptLibrary.Int

Description

Wrapper class that converts the option argument to an integer.

Example

Opt foo = Int(HasOpt("--foo")|Default(4711));


InheritOpt

inherit Opt : Opt


Variableopt

Opt Arg.OptLibrary.Int.opt


Method__create__

protectedlocalvoid__create__(Optopt)


Methodcreate

Arg.OptLibrary.IntArg.OptLibrary.Int(Optopt)

Class Arg.OptLibrary.MaybeOpt

Description

Parses an option that may have a parameter. --foo, -x and x in a sequence like -axb will set the variable to 1. --foo=bar, -x bar and -x=bar will set the variable to bar.

Example

Opt debug = MaybeOpt("--debug");


InheritNoOpt

inherit NoOpt : NoOpt

Class Arg.OptLibrary.Multiple

Description

Wrapper class that allows multiple instances of an option.

Example

Opt filter = Multiple(HasOpt("--filter"));


InheritOpt

inherit Opt : Opt


Variableopt

Opt Arg.OptLibrary.Multiple.opt


Method__create__

protectedlocalvoid__create__(Optopt)


Methodcreate

Arg.OptLibrary.MultipleArg.OptLibrary.Multiple(Optopt)

Class Arg.OptLibrary.NoOpt

Description

Parses an option without parameter, such as --help, -x or "x" from -axb.

Example

Opt verbose = NoOpt("-v")|NoOpt("--verbose");


InheritOpt

inherit Opt : Opt

Class Arg.OptLibrary.Opt

Description

Base class for parsing an argument. Inherit this class to create custom made option types.


Method__sprintf

protectedstring__sprintf()

Description

This function will be called by _sprintf, which handles formatting of chaining between objects.


Methodget_opts

array(string) get_opts()

Description

Should return a list of options that are parsed. To properly chain argument parsers, return your_opts +  ::get_opts().


Methodget_value

mixedget_value(array(string) argv, mapping(string:string) env, mixedprevious)

Description

The overloading method should calculate the value of the option and return it. Methods processing argv should only look at argv[0] and if it matches, set it to 0. Returning UNDEFINED means the option was not set (or matched). To properly chain arguments parsers, return ::get_value(argv, env, previous) instead of UNDEFINED, unless you want to explicitly stop the chain and not set this option.

Class Arg.Options

Description

The option parser class that contains all the argument objects.


InheritLowOptions

inherit LowOptions : LowOptions


Variablehelp
Variablehelp_help

Opt Arg.Options.help
protectedstring Arg.Options.help_help

Description

Options that trigger help output.


Methodunhandled_argument

protectedboolunhandled_argument(array(string) argv, mapping(string:string) env)

Class Arg.SimpleOptions

Description

Options parser with a unhandled_argument implementation that parses most common argument formats.


InheritLowOptions

inherit LowOptions : LowOptions


Methodunhandled_argument

boolunhandled_argument(array(string) argv, mapping(string:string) env)

Description

Handles arguments as described in Arg.parse

Module Audio

Module Audio.Codec

Class Audio.Codec.decoder

Description

Decoder object.

Note

It needs _Ffmpeg.ffmpeg module for real work.


Methodcreate

Audio.Codec.decoderAudio.Codec.decoder(string|voidcodecname, object|void_codec)

Description

Creates decoder object

Parameter codecnum

Some of supported codec, like _Ffmpeg.CODEC_ID_*

Parameter _codec

The low level object will be used for decoder. By default _Ffmpeg.ffmpeg object will be used.

Note

Until additional library is implemented the second parameter _codec hasn't effect.

See also

_Ffmpeg.ffmpeg, _Ffmpeg.CODEC_ID_MP2


Methoddecode

mapping|intdecode(int|voidpartial)

Description

Decodes audio data

Parameter partial

Only one frame will be decoded per call.

Returns

If successfull a mapping with decoded data and byte number of used input data is returned, 0 otherwise.


Methodfrom_file

this_program|zerofrom_file(Audio.Format.ANYfile)

Description

Set codec type from file

It uses Audio.Format.ANY's method get_map() to determine which codec should be used.

Parameter file

The object Audio.Format.ANY.


Methodget_status

mappingget_status()

Description

Returns decoder status

Module Audio.Format

Description

Audio data format handling

Note

API remains marked "unstable".

Class Audio.Format.ANY


Methodcheck_format

intcheck_format()

Description

Check if data are correctly formated.


Methodget_data

stringget_data()

Description

Returns data only.

Note

The operation is destructive. Ie. current data cursor is moved over.

See also

get_frame, get_sample


Methodget_frame

stringget_frame()

Description

Returns frame for current position and moves cursor forward.

Note

The operation is destructive. Ie. current data cursor is moved over.

See also

get_data, get_sample


Methodget_map

mappingget_map()


Methodget_sample

mappingget_sample()

Description

Returns sample for current position and moves cursor forward.

Note

The operation is destructive. Ie. current data cursor is moved over.

See also

get_frame, get_data


Methodread_file

this_programread_file(stringfilename, int|voidnocheck)

Description

Reads data from file

See also

read_streamed


Methodread_streamed

this_programread_streamed(stringfilename, int|voidnocheck)

Description

Reads data from stream

Ie. for packetized data source the beggining of data is searched.

See also

read_file


Methodread_string

this_programread_string(stringdata, int|voidnocheck)

Description

Reads data from string

Class Audio.Format.MP3

Description

A MP3 file parser with ID3 tag support.


InheritANY

inherit .module.ANY : ANY


Methodget_frame

mapping|intget_frame()

Description

Gets next frame from file

Frame is represented by the following mapping. It contains from parsed frame headers and frame data itself.

([ "bitrate": int "copyright": int(0..1), "data": frame_data, "emphasis": emphasis, "extension": "channels":0, "id":1, "layer":3, "original": int(0..1), "padding": int(0..1), "private": int(0..1), "sampling": int ])

Module COM


MethodCreateObject

CObjCreateObject(stringprog_id)


MethodGetConstants

mappingGetConstants(stringtypelib)
mappingGetConstants(CObjcobj)


MethodGetObject

objectGetObject(string|voidfilename, string|voidprog_id)


MethodGetTypeInfo

mixedGetTypeInfo(CObjcobj)


Method_sprintf

protectedstring_sprintf(intc, mappingopts)

Module Cache

Description

Common Caching implementation

This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies.

To create a new cache, do Cache.cache( Cache.Storage.Base storage_type, Cache.Policy.Base expiration_policy )

The cache store instances of Cache.Data.

Class Cache.Data

Description

Base stored object for the cache system.


Variableatime

int Cache.Data.atime

Description

last-access time.


Variablecost

float Cache.Data.cost

Description

relative preciousness scale


Variablectime

int Cache.Data.ctime

Description

creation-time


Variableetime

int Cache.Data.etime

Description

expiry-time (if supplied). 0 otherwise


Methodcreate

Cache.DataCache.Data(void|mixedvalue, void|intexpire_time, void|floatpreciousness)

Description

expire_time is relative and in seconds.


Methoddata

mixeddata()

Description

A method in order to allow for lazy computation


Methodrecursive_low_size

intrecursive_low_size(mixedwhatfor)

Description

Attempts a wild guess of an object's size. It's left here as a common utility. Some classes won't even need it.


Methodsize

intsize()

Description

A method in order to allow for lazy computation. Used by some Policy Managers

Class Cache.cache

Description

This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies. Mechanisms to allow for distributed caching systems will be added in time, or at least that is the plan.


Methodalookup

voidalookup(stringkey, function(string, mixed, mixed ... :void) callback, int|floattimeout, mixed ... args)

Description

Asynchronously look the cache up. The callback will be given as arguments the key, the value, and then any user-supplied arguments. If the timeout (in seconds) expires before any data could be retrieved, the callback is called anyways, with 0 as value.


Methodasync_cleanup_cache

voidasync_cleanup_cache()


Methodcreate

Cache.cacheCache.cache(Cache.Storage.Basestorage_mgr, Cache.Policy.Basepolicy_mgr, void|intcleanup_cycle_delay)

Description

Creates a new cache object. Required are a storage manager, and an expiration policy object.


Methoddelete

voiddelete(stringkey, void|boolhard)

Description

Forcibly removes some key. If the 'hard' parameter is supplied and true, deleted objects will also have their lfun::_destruct method called upon removal by some backends (i.e. memory)


Methodlookup

mixedlookup(stringkey)

Description

Looks in the cache for an element with the given key and, if available, returns it. Returns 0 if the element is not available


Methodstart_cleanup_cycle

voidstart_cleanup_cycle()


Methodstore

voidstore(stringkey, mixedvalue, void|intmax_life, void|floatpreciousness, void|multiset(string) dependants)

Description

Sets some value in the cache. Notice that the actual set operation might even not happen at all if the set data doesn't make sense. For instance, storing an object or a program in an SQL-based backend will not be done, and no error will be given about the operation not being performed.

Notice that while max_life will most likely be respected (objects will be garbage-collected at pre-determined intervals anyways), the preciousness . is to be seen as advisory only for the garbage collector If some data was stored with the same key, it gets returned. Also notice that max_life is relative and in seconds. dependants are not fully implemented yet. They are implemented after a request by Martin Stjerrholm, and their purpose is to have some weak form of referential integrity. Simply speaking, they are a list of keys which (if present) will be deleted when the stored entry is deleted (either forcibly or not). They must be handled by the storage manager.


Methodthreaded_cleanup_cycle

voidthreaded_cleanup_cycle()

Module Cache.Policy

Class Cache.Policy.Base

Description

Base class for cache expiration policies.


Methodexpire

voidexpire(Cache.Storage.Basestorage)

Description

Expire callback.

This function is called to expire parts of storage.

Note

All Storage.Policy classes must MUST implement this method.

Class Cache.Policy.Multiple

Description

A multiple-policies expiration policy manager.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Policy.Base : Base


Methodcreate

Cache.Policy.MultipleCache.Policy.Multiple(Cache.Policy.Base ... policies)


Methodexpire

voidexpire(Cache.Storage.Basestorage)

Description

This expire function calls the expire functions in all of the sub-policies in turn.

Class Cache.Policy.Null

Description

Null policy-manager for the generic Caching system

This is a policy manager that doesn't actually expire anything. It is useful in multilevel and/or network-based caches.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Policy.Base : Base


Methodexpire

voidexpire(Cache.Storage.Basestorage)

Description

This is an expire function that does nothing.

Class Cache.Policy.Sized

Description

An LRU, size-constrained expiration policy manager.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Policy.Base : Base


Methodcreate

Cache.Policy.SizedCache.Policy.Sized(intmax, void|intmin)


Methodexpire

voidexpire(Cache.Storage.Basestorage)

Class Cache.Policy.Timed

Description

An access-time-based expiration policy manager.


InheritBase

inherit Cache.Policy.Base : Base

Module Cache.Storage

Class Cache.Storage.Base

Description

Base class for cache storage managers.

All Cache.Storage managers must provide these methods.


Methodaget

voidaget(stringkey, function(string, int(0)|Cache.Data, mixed ... :void) callback, mixed ... extra_callback_args)

Description

Fetch some data from the cache asynchronously.

callback() will get as first argument key, and as second argument 0 (cache miss) or an Cache.Data object, plus any additional argument that the user may have supplied.


Methoddelete

mixeddelete(stringkey, void|boolhard)

Description

Delete the entry specified by key from the cache (if present).

If hard is 1, some backends may force a destruct() on the deleted value.

Dependants (if present) are automatically deleted.

Returns

Returns the deleted entry.


Methodfirst
Methodnext

int(0)|stringfirst()
int(0)|stringnext()

Description

These two functions are an iterator over the cache. There is an internal cursor, which is reset by each call to first(). Subsequent calls to next() will iterate over all the contents of the cache.

These functions are not meant to be exported to the user, but are solely for the policy managers' benefit.


Methodget

int(0)|Cache.Dataget(stringkey, void|boolnotouch)

Description

Fetch some data from the cache synchronously.

Note

Be careful, as with some storage managers it might block the calling thread for some time.


Methodset

voidset(stringkey, mixedvalue, void|intmax_life, void|floatpreciousness, void|multiset(string) dependants)

Description

Data-object creation is performed here if necessary, or in get() depending on the backend.

This allows the storage managers to have their own data class implementation.

Class Cache.Storage.Gdbm

Description

A GBM-based storage manager.

This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format

Settings will be added later.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Storage.Base : Base


Methodcreate

Cache.Storage.GdbmCache.Storage.Gdbm(stringpath)

Description

A GDBM storage-manager must be hooked to a GDBM Database.

Class Cache.Storage.Gdbm.Data


InheritData

inherit Cache.Data : Data

Class Cache.Storage.Memory

Description

A RAM-based storage manager.

This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format

Settings will be added later.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Storage.Base : Base


Methodget

int(0)|Cache.Dataget(stringkey, void|intnotouch)

Description

Fetches some data from the cache. If notouch is set, don't touch the data from the cache (meant to be used by the storage manager only)

Class Cache.Storage.Memory.Data


InheritData

inherit Cache.Data : Data

Class Cache.Storage.MySQL

Description

An SQL-based storage manager

This storage manager provides the means to save data to an SQL-based backend.

For now it's mysql only, dialectization will be added at a later time. Serialization should be taken care of by the low-level SQL drivers.

Note

An administrator is supposed to create the database and give the user enough privileges to write to it. It will be care of this driver to create the database tables itself.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Storage.Base : Base


Methodcreate

Cache.Storage.MySQLCache.Storage.MySQL(stringsql_url)

Class Cache.Storage.MySQL.Data

Description

Database manipulation is done externally. This class only returns values, with some lazy decoding.


InheritData

inherit Cache.Data : Data

Class Cache.Storage.Yabu

Description

A Yabu-based storage manager.

Settings will be added later.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


InheritBase

inherit Cache.Storage.Base : Base


Methodcreate

Cache.Storage.YabuCache.Storage.Yabu(stringpath)

Class Cache.Storage.Yabu.Data


InheritData

inherit Cache.Data : Data

Module CommonLog

Description

The CommonLog module is used to parse the lines in a www server's logfile, which must be in "common log" format -- such as used by default for the access log by Roxen, Caudium, Apache et al.


Methodread

intread(function(array(int|string), int:void) callback, Stdio.File|stringlogfile, void|intoffset)

Description

Reads the log file and calls the callback function for every parsed line. For lines that fails to be parsed the callback is not called not is any error thrown. The number of bytes read are returned.

Parameter callback

The callbacks first argument is an array with the different parts of the log entry.

Array
stringremote_host 
int(0)|stringident_user 
int(0)|stringauth_user 
intyear 
intmonth 
intday 
inthours 
intminutes 
intseconds 
inttimezone 
int(0)|stringmethod

One of "GET", "POST", "HEAD" etc.

int(0)|stringpath 
stringprotocol

E.g. "HTTP/1.0"

intreply_code

One of 200, 404 etc.

intbytes 

The second callback argument is the current offset to the end of the current line.

Parameter logfile

The logfile to parse. Either an open Stdio.File object, or a string with the path to the logfile.

Parameter offset

The absolute position in the file where the parser should begin. Note that the offset defaults to 0 (zero), NOT the current offset of logfile.

Module DVB

Description

Implements Digital Video Broadcasting interface

Note

Only Linux version is supported.

Class DVB.Audio

Description

Object for controlling an audio subsystem on full featured cards.


Methodcreate

DVB.AudioDVB.Audio(intcard_number)
DVB.AudioDVB.Audio()

Description

Create a Audio object.

Parameter card_number

The number of card equipment.


Methodmixer

intmixer(intleft, intright)
intmixer(intboth)

Description

Sets output level on DVB audio device.

See also

mute()


Methodmute

intmute(intmute)
intmute()

Description

Mute or unmute audio device.

See also

mixer()


Methodstatus

mappingstatus()

Description

Returns mapping of current audio device status.

Class DVB.Stream

Description

Represents an elementary data stream (PES).


Method_destruct

int_destruct()

Description

Purge a stream reader.

See also

DVB.dvb()->stream(), read()


Methodclose

voidclose()

Description

Closes an open stream.

See also

read()


Methodread

string|intread()

Description

Read data from a stream. It reads up to read buffer size data.

Note

Read buffer size is 4096 by default.

See also

DVB.dvb()->stream(), close()


Methodset_buffer

intset_buffer(intlen)

Description

Sets stream's internal buffer.

Note

The size is 4096 by default.

See also

read()

Class DVB.dvb

Description

Main class.


Methodanalyze_pat

mappinganalyze_pat()

Description

Return mapping of all PMT.

sid:prognum


Methodanalyze_pmt

array(mapping)|intanalyze_pmt(intsid, intprognum)

Description

Parse PMT table.

See also

analyze_pat()


Methodcreate

DVB.dvbDVB.dvb(intcard_number)

Description

Create a DVB object.

Parameter card_number

The number of card equipment.

Note

The number specifies which device will be opened. Ie. /dev/ost/demux0, /dev/ost/demux1 ... for DVB v0.9.4 or /dev/dvb/demux0, /dev/dvb/demux1 ... for versions 2.0+


Methodfe_info

mappingfe_info()

Description

Return info of a frondend device.

Note

The information heavily depends on driver. Many fields contain dumb values.


Methodfe_status

mapping|intfe_status()

Description

Return status of a DVB object's frondend device.

Returns

The resulting mapping contains the following fields:

"power" : string

If 1 the frontend is powered up and is ready to be used.

"signal" : string

If 1 the frontend detects a signal above a normal noise level

"lock" : string

If 1 the frontend successfully locked to a DVB signal

"carrier" : string

If 1 carrier dectected in signal

"biterbi" : string

If 1 then lock at viterbi state

"sync" : string

If 1 then TS sync byte detected

"tuner_lock" : string

If 1 then tuner has a frequency lock


Methodget_pids

mapping|intget_pids()

Description

Returns mapping with info of currently tuned program's pids.

See also

tune()


Methodstream

DVB.Streamstream(intpid, int|function(:void) rcb, intptype)
DVB.Streamstream(intpid, int|function(:void) rcb)
DVB.Streamstream(intpid)

Description

Create a new stream reader object for PID.

Parameter pid

PID of stream.

Parameter rcb

Callback function called whenever there is the data to read from stream. Only for nonblocking mode.

Parameter ptype

Type of payload data to read. By default, audio data is fetched.

Note

Setting async callback doesn't set the object to nonblocking state.

See also

DVB.Stream()->read()


Methodtune

inttune(int(2bit)lnb, intfreq, bool|stringpol, intsr)

Description

Tunes to apropriate transponder's parameters.

Parameter lnb

DiSeQc number of LNB.

Parameter freq

Frequency divided by 1000.

Parameter pol

Polarization. 0 or "v" for vertical type, 1 or "h" for horizontal one.

Parameter sr

The service rate parameter.

Module Debug


Inherit_Debug

inherit _Debug : _Debug


Variableglobals

mapping Debug.globals

Description

Can be custom filled from within your program in order to have global references to explore live datastructures using Inspect; comes preinitialised with the empty mapping, ready for use.


Methodadd_to_perf_map

voidadd_to_perf_map(programp)

Description

Updates the perf map file with new program p.

See also

generate_perf_map()

Note

Expects generate_perf_map() to have been called before.


Methodassembler_debug

int(0..)assembler_debug(int(0..)level)

Description

Set the assembler debug level.

Returns

The old assembler debug level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Methodcompiler_trace

int(0..)compiler_trace(int(0..)level)

Description

Set the compiler trace level.

Returns

The old compiler trace level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Methodcount_objects

mapping(string:int) count_objects()

Description

Returns the number of objects of every kind in memory.


Methoddebug

int(0..)debug(int(0..)level)

Description

Set the run-time debug level.

Returns

The old debug level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Methoddescribe

mixeddescribe(mixedx)

Description

Prints out a description of the thing x to standard error. The description contains various internal info associated with x.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Methoddescribe_encoded_value

intdescribe_encoded_value(stringdata)

Description

Describe the contents of an encode_value() string.

Returns

Returns the number of encoding errors that were detected (if any).


Methoddescribe_program

array(array(int|string|type)) describe_program(programp)

Description

Debug function for showing the symbol table of a program.

Returns

Returns an array of arrays with the following information for each symbol in p:

Array
intmodifiers

Bitfield with the modifiers for the symbol.

stringsymbol_name

Name of the symbol.

typevalue_type

Value type for the symbol.

intsymbol_type

Type of symbol.

intsymbol_offset

Offset into the code or data area for the symbol.

intinherit_offset

Offset in the inherit table to the inherit containing the symbol.

intinherit_level

Depth in the inherit tree for the inherit containing the symbol.

Note

The API for this function is not fixed, and has changed since Pike 7.6. In particular it would make sense to return an array of objects instead, and more information about the symbols might be added.


Methoddisassemble

voiddisassemble(function(:void) fun)

Description

Disassemble a Pike function to Stdio.stderr.

Note

This function is only available if the Pike runtime has been compiled with debug enabled.


Methoddmalloc_set_name

voiddmalloc_set_name()

Note

Only available when compiled with dmalloc.


Methoddmalloc_set_name

voiddmalloc_set_name(stringfilename, int(1..)linenumber)

Note

Only available when compiled with dmalloc.


Methoddump_backlog

voiddump_backlog()

Description

Dumps the 1024 latest executed opcodes, along with the source code lines, to standard error. The backlog is only collected on debug level 1 or higher, set with _debug or with the -d argument on the command line.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Methoddump_dmalloc_locations

voiddump_dmalloc_locations(string|array|mapping|multiset|function(:void)|object|program|typeo)

Note

Only available when compiled with dmalloc.


Methoddump_program_tables

voiddump_program_tables(programp, int(0..)|voidindent)

Description

Dumps the internal tables for the program p on stderr.

Parameter p

Program to dump.

Parameter indent

Number of spaces to indent the output.


Methodfind_all_clones

array(object) find_all_clones(programp, bool|voidinclude_subclasses)

Description

Return an array with all objects that are clones of p.

Parameter p

Program that the objects should be a clone of.

Parameter include_subclasses

If true, include also objects that are clones of programs that have inherited p. Note that this adds significant overhead.

This function is only intended to be used for debug purposes.

See also

map_all_objects()


Methodgc_set_watch

voidgc_set_watch(array|multiset|mapping|object|function(:void)|program|stringx)

Description

Sets a watch on the given thing, so that the gc will print a message whenever it's encountered. Intended to be used together with breakpoints to debug the garbage collector.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Methodgc_status

mapping(string:int|float) gc_status()

Description

Get statistics from the garbage collector.

Returns

A mapping with the following content will be returned:

"num_objects" : int

Number of arrays, mappings, multisets, objects and programs.

"num_allocs" : int

Number of memory allocations since the last gc run.

"alloc_threshold" : int

Threshold for "num_allocs" when another automatic gc run is scheduled.

"projected_garbage" : float

Estimation of the current amount of garbage.

"objects_alloced" : int

Decaying average over the number of allocated objects between gc runs.

"objects_freed" : int

Decaying average over the number of freed objects in each gc run.

"last_garbage_ratio" : float

Garbage ratio in the last gc run.

"non_gc_time" : int

Decaying average over the interval between gc runs, measured in real time nanoseconds.

"gc_time" : int

Decaying average over the length of the gc runs, measured in real time nanoseconds.

"last_garbage_strategy" : string

The garbage accumulation goal that the gc aimed for when setting "alloc_threshold" in the last run. The value is either "garbage_ratio_low", "garbage_ratio_high" or "garbage_max_interval". The first two correspond to the gc parameters with the same names in Pike.gc_parameters, and the last is the minimum gc time limit specified through the "min_gc_time_ratio" parameter to Pike.gc_parameters.

"last_gc" : int

Time when the garbage-collector last ran.

"total_gc_cpu_time" : int

The total amount of CPU time that has been consumed in implicit GC runs, in nanoseconds. 0 on systems where Pike lacks support for CPU time measurement.

"total_gc_real_time" : int

The total amount of real time that has been spent in implicit GC runs, in nanoseconds.

See also

gc(), Pike.gc_parameters(), Pike.implicit_gc_real_time


Methodgenerate_perf_map

voidgenerate_perf_map()

Description

Generates a perf map file of all Pike code and writes it to /tmp/perf-<pid>.map. This is useful only if pike has been compiled with machine code support. It allows the linux perf tool to determine the correct name of Pike functions that were compiled to machine code by pike.


Methodget_program_layout

mapping(string:int) get_program_layout(programp)

Description

Returns a mapping which describes the layout of compiled machine code in the program p. The indices of the returned mapping are function names, the values the starting address of the compiled function. The total size of the program code is stored with index 0.


Methodhexdump

voidhexdump(string(8bit)raw)

Description

Write a hexadecimal dump of the contents of raw to Stdio.stderr.


Methodlist_open_fds

voidlist_open_fds()

Note

Only available when compiled with dmalloc.


Methodlocate_references

mixedlocate_references(string|array|mapping|multiset|function(:void)|object|program|typeo)

Description

This function is mostly intended for debugging. It will search through all data structures in Pike looking for o and print the locations on stderr. o can be anything but int or float.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Methodmap_all_objects

int(0..)map_all_objects(function(object:void) cb)

Description

Call cb for all objects that currently exist. The callback will not be called with destructed objects as it's argument.

Objects might be missed if cb creates new objects or destroys old ones.

This function is only intended to be used for debug purposes.

Returns

The total number of objects

See also

next_object(), find_all_clones()


Methodmap_all_programs

int(0..)map_all_programs(function(program:void) cb)

Description

Call cb for all programs that currently exist.

Programs might be missed if cb creates new programs.

This function is only intended to be used for debug purposes.

Returns

The total number of programs

See also

map_all_objects()


Methodmap_all_strings

int(0..)map_all_strings(function(string:void) cb)

Description

Call cb for all strings that currently exist.

strings might be missed if cb creates new strings or destroys old ones.

This function is only intended to be used for debug purposes.

Returns

The total number of strings

See also

next_object()


Methodmemory_usage

mapping(string:int) memory_usage()

Description

Check memory usage.

This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use.

The entries in the mapping are typically paired, with one named "num_" + SYMBOL + "s" containing a count, and the other named SYMBOL + "_bytes" containing a best effort approximation of the size in bytes.

Note

Exactly what fields this function returns is version dependant.

See also

_verify_internals()


Methodnext

mixednext(mixedx)

Description

Find the next object/array/mapping/multiset/program or string.

All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.

See also

next_object(), prev()


Methodnext_object

objectnext_object(objecto)
objectnext_object()

Description

Returns the next object from the list of all objects.

All objects are stored in a linked list.

Returns

If no arguments have been given next_object() will return the first object from the list.

If o has been specified the object after o on the list will be returned.

Note

This function is not recomended to use.

See also

destruct()


Methodoptimizer_debug

int(0..)optimizer_debug(int(0..)level)

Description

Set the optimizer debug level.

Returns

The old optimizer debug level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Methodpp_memory_usage

stringpp_memory_usage()

Description

Returns a pretty printed version of the output from memory_usage.


Methodpp_object_usage

stringpp_object_usage()

Description

Returns a pretty printed version of the output from count_objects (with added estimated RAM usage)


Methodprev

mixedprev(mixedx)

Description

Find the previous object/array/mapping/multiset or program.

All objects, arrays, mappings, multisets and programs are stored in linked lists inside Pike. This function returns the previous item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.

Note

Unlike next() this function does not work on strings.

See also

next_object(), next()


Methodrefs

intrefs(string|array|mapping|multiset|function(:void)|object|programo)

Description

Return the number of references o has.

It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.

Note

Note that the number of references will always be at least one since the value is located on the stack when this function is executed.

See also

next(), prev()


Methodremove_from_perf_map

voidremove_from_perf_map(programp)

Description

Removed p from the perf map file.


Methodreset_dmalloc

voidreset_dmalloc()

Note

Only available when compiled with dmalloc.


Methodsize_object

intsize_object(objecto)

Description

Return the aproximate size of the object, in bytes. This might not work very well for native objects

The function tries to estimate the memory usage of variables belonging to the object.

It will not, however, include the size of objects assigned to variables in the object.

If the object has a lfun::_size_object() it will be called without arguments, and the return value will be added to the final size. It is primarily intended to be used by C-objects that allocate memory that is not normally visible to pike.

See also

lfun::_size_object(), sizeof()


Methodverify_internals

voidverify_internals()

Description

Perform sanity checks.

This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.

Note

This function does a more thorough check if the Pike runtime has been compiled with RTL debug.

Enum Debug.DecoderFP


ConstantFP_SNAN
ConstantFP_QNAN
ConstantFP_NINF
ConstantFP_PINF
ConstantFP_ZERO
ConstantFP_PZERO
ConstantFP_NZERO

constant Debug.FP_SNAN
constant Debug.FP_QNAN
constant Debug.FP_NINF
constant Debug.FP_PINF
constant Debug.FP_ZERO
constant Debug.FP_PZERO
constant Debug.FP_NZERO

Enum Debug.DecoderTags


ConstantTAG_DELAYED
ConstantTAG_AGAIN

constant Debug.TAG_DELAYED
constant Debug.TAG_AGAIN


ConstantTAG_ARRAY
ConstantTAG_MAPPING
ConstantTAG_MULTISET
ConstantTAG_OBJECT
ConstantTAG_FUNCTION
ConstantTAG_PROGRAM
ConstantTAG_STRING
ConstantTAG_FLOAT
ConstantTAG_INT
ConstantTAG_TYPE

constant Debug.TAG_ARRAY
constant Debug.TAG_MAPPING
constant Debug.TAG_MULTISET
constant Debug.TAG_OBJECT
constant Debug.TAG_FUNCTION
constant Debug.TAG_PROGRAM
constant Debug.TAG_STRING
constant Debug.TAG_FLOAT
constant Debug.TAG_INT
constant Debug.TAG_TYPE


ConstantTAG_NEG
ConstantTAG_SMALL

constant Debug.TAG_NEG
constant Debug.TAG_SMALL

Enum Debug.EntryTypes


ConstantID_ENTRY_TYPE_CONSTANT
ConstantID_ENTRY_EFUN_CONSTANT
ConstantID_ENTRY_RAW
ConstantID_ENTRY_EOT
ConstantID_ENTRY_VARIABLE
ConstantID_ENTRY_FUNCTION
ConstantID_ENTRY_CONSTANT
ConstantID_ENTRY_INHERIT
ConstantID_ENTRY_ALIAS

constant Debug.ID_ENTRY_TYPE_CONSTANT
constant Debug.ID_ENTRY_EFUN_CONSTANT
constant Debug.ID_ENTRY_RAW
constant Debug.ID_ENTRY_EOT
constant Debug.ID_ENTRY_VARIABLE
constant Debug.ID_ENTRY_FUNCTION
constant Debug.ID_ENTRY_CONSTANT
constant Debug.ID_ENTRY_INHERIT
constant Debug.ID_ENTRY_ALIAS

Enum Debug.PikeTypes


ConstantT_ATTRIBUTE
ConstantT_NSTRING
ConstantT_NAME
ConstantT_SCOPE
ConstantT_ASSIGN
ConstantT_UNKNOWN
ConstantT_MIXED
ConstantT_NOT
ConstantT_AND
ConstantT_OR

constant Debug.T_ATTRIBUTE
constant Debug.T_NSTRING
constant Debug.T_NAME
constant Debug.T_SCOPE
constant Debug.T_ASSIGN
constant Debug.T_UNKNOWN
constant Debug.T_MIXED
constant Debug.T_NOT
constant Debug.T_AND
constant Debug.T_OR


ConstantT_ARRAY
ConstantT_MAPPING
ConstantT_MULTISET
ConstantT_OBJECT
ConstantT_FUNCTION
ConstantT_PROGRAM
ConstantT_STRING
ConstantT_TYPE
ConstantT_VOID
ConstantT_MANY

constant Debug.T_ARRAY
constant Debug.T_MAPPING
constant Debug.T_MULTISET
constant Debug.T_OBJECT
constant Debug.T_FUNCTION
constant Debug.T_PROGRAM
constant Debug.T_STRING
constant Debug.T_TYPE
constant Debug.T_VOID
constant Debug.T_MANY


ConstantT_INT
ConstantT_FLOAT

constant Debug.T_INT
constant Debug.T_FLOAT


ConstantT_ZERO

constant Debug.T_ZERO

Class Debug.Decoder


Variableinput

Stdio.Buffer Debug.Decoder.input


Method__create__

protectedlocalvoid__create__(Stdio.Bufferinput)


Methodcreate

Debug.DecoderDebug.Decoder(Stdio.Bufferinput)

Class Debug.Inspect

Description

Allows for interactive debugging and live data structure inspection in both single- and multi-threaded programs. Creates an independent background thread that every pollinterval will show a list of running threads. Optionally, a triggersignal can be specified which allows the dump to be triggered by a signal.

Example: In the program you'd like to inspect, insert the following one-liner:

Debug.Inspect("/tmp/test.pike");

Then start the program and keep it running. Next you create a /tmp/test.pike with the following content:

void create(){
 werror("Only once per modification of test.pike\n");}int main(){
 werror("This will run every iteration\n");
 werror("By returning 1 here, we disable the stacktrace dumps\n");return 0;}void _destruct(){
 werror("_destruct() runs just as often as create()\n");}

Whenever you edit /tmp/test.pike, it will automatically reload the file.


Variable_callback

string|function(void:void) Debug.Inspect._callback

Description

Either the callback function which is invoked on each iteration, or the name of a file which contains a class which is (re)compiled automatically and called on each iteration.

See also

create


Variable_loopthread

Thread.Thread Debug.Inspect._loopthread

Description

The inspect-thread. It will not appear in the displayed thread-list.


Variablepollinterval

int Debug.Inspect.pollinterval

Description

The polling interval in seconds, defaults to 4.


Variabletriggersignal

int Debug.Inspect.triggersignal

Description

If assigned to, it will allow the diagnostics inspection to be triggered by this signal.


Methodcreate

Debug.InspectDebug.Inspect(string|function(void:void)|voidcb)

Description

Starts up the background thread.

Parameter cb

Specifies either the callback function which is invoked on each iteration, or the name of a file which contains a class which is (re)compiled automatically with an optional main() method, which will be called on each iteration. If the main() method returns 0, new stacktraces will be dumped every iteration; if it returns 1, stacktrace dumping will be suppressed.

Note

The compilation and the running of the callback is guarded by a catch(), so that failures (to compile) in that section will not interfere with the running program.

Note

If the list of running threads did not change, displaying the list again will be suppressed.

See also

triggersignal, pollinterval, _loopthread, _callback, Debug.globals


Methodinspect

voidinspect()

Description

The internal function which does all the work each pollinterval. Run it directly to force a thread-dump.

Class Debug.Rapidlog

Description

Allows for rapid collection of logdata, which is then fed to the real werror() at idle moments. This allows for logging to occur with minimal timing interference.


Methodwerror

voidwerror(stringformat, mixed ... args)

Description

Overloads the predef::werror() function to allow floods of logentries while introducing minimal latency. Logs are buffered, and periodically flushed from another thread. If the arrival rate of logs is excessive, it simply skips part of the logs to keep up.

Note

When parts are skipped, records are skipped in whole and will never be split up.

See also

werror_options()


Methodwerror_options

voidwerror_options(intoptions, void|intpollinterval, void|intdrainrate, void|intmaxbufentries)

Parameter options

Defaults to 0, reserved for future enhancements.

Parameter pollinterval

Pollinterval in seconds for the log-flush thread; defaults to 1. Logs will only be flushed out, if during the last pollinterval no new logs have been added.

Parameter drainrate

Maximum number of lines per second that will be dumped to stderr. Defaults to 10.

Parameter maxbufentries

Maximum number of buffered logrecords which have not been flushed to stderr yet. If this number is exceeded, the oldest maxbufentries/2 entries will be skipped; a notice to that effect is logged to stderr.

See also

werror()

Class Debug.Subject

Description

This is a probe subject which you can send in somewhere to get probed (not to be confused with a probe object, which does some active probing). All calls to LFUNs will be printed to stderr. It is possible to name the subject by passing a string as the first and only argument when creating the subject object.

Example

> object s = Debug.Subject(); create() > random(s); _random() (1) Result: 0 > abs(s); `<(0) _sprintf(79, ([ ])) (2) Result: Debug.Subject > abs(class { inherit Debug.Subject; int `<(mixed ... args) { return 1; } }()); create() `-() _destruct() (3) Result: 0 > pow(s,2); `[]("pow") Attempt to call the NULL-value Unknown program: 0(2)

Class Debug.Tracer

Description

A class that when instatiated will turn on trace, and when it's destroyed will turn it off again.


Methodcreate

Debug.TracerDebug.Tracer(intlevel)

Description

Sets the level of debug trace to level.

Class Debug.Wrapper

Description

This wrapper can be placed around another object to get printouts about what is happening to it. Only a few LFUNs are currently supported.

Example

> object x=Debug.Wrapper(Crypto.MD5()); Debug.Wrapper is proxying ___Nettle.MD5_State() > x->name(); ___Nettle.MD5_State()->name (1) Result: "md5" > !x; !___Nettle.MD5_State() (2) Result: 0


Method_indices

arrayindices(Debug.Wrapperarg)


Method_sizeof

intsizeof(Debug.Wrapperarg)


Method_sprintf

stringsprintf(stringformat, ... Debug.Wrapperarg ... )


Method_values

arrayvalues(Debug.Wrapperarg)


Method`!

bool res = !Debug.Wrapper()


Method`->

mixed res = Debug.Wrapper()->X


Method`[]

mixed res = Debug.Wrapper()[ x ]


Methodcreate

Debug.WrapperDebug.Wrapper(objectx)

Module Debug.Profiling


Methoddisplay

voiddisplay(int|voidnum, string|array(string)|voidpattern, string|array(string)|voidexclude)

Description

Show profiling information in a more-or-less readable manner. This only works if pike has been compiled with profiling support.

The function will print to stderr using werror.

This is mainly here for use from the Debug.Watchdog class, if you want to do your own formatting or output to some other channel use get_prof_info instead.


Methodget_prof_info

array(array(string|float|int)) get_prof_info(string|array(string)|voidinclude, string|array(string)|voidexclude)

Description

Collect profiling data.

This will return the CPU usage, by function, since the last time the function was called.

The returned array contains the following entries per entry:

Array
stringname

The name of the function.

intnumber_of_calls

The number of calls.

floattotal_self_time

Total self CPU time in milliseconds.

floattotal_cpu_time

Total self CPU time in milliseconds, including children.

floatavg_self_time

Average self CPU time in microseconds.

floatavg_cpu_time

Average self CPU time in microseconds, including children.

floatself_time_pct

The self CPU time as percentage of total time.

floatcpu_time_pct

The self CPU time, including children, as percentage of total time.

stringfunction_line

Function's definition source location.

Module DefaultCompilerEnvironment

Description

The CompilerEnvironment object that is used for loading C-modules and by predef::compile().

Note

predef::compile() is essentially an alias for the CompilerEnvironment()->compile() in this object.

See also

CompilerEnvironment, predef::compile()


InheritCompilerEnvironment

inherit CompilerEnvironment : CompilerEnvironment

Module Error


Methodmkerror

objectmkerror(mixederror)

Description

Returns an Error object for any argument it receives. If the argument already is an Error object or is empty, it does nothing.

Class Error.Generic

Description

Class for exception objects for errors of unspecified type.


Variableerror_backtrace

array(backtrace_frame|array(mixed)) Error.Generic.error_backtrace

Description

The backtrace as returned by backtrace where the error occurred.

Code that catches and rethrows errors should ensure that this remains the same in the rethrown error.


Variableerror_message

string Error.Generic.error_message

Description

The error message. It always ends with a newline ('\n') character and it might be more than one line.

Code that catches and rethrows errors may extend this with more error information.


Method_is_type

bool res = is_type(Error.Generic())

Description

Claims that the error object is an array, for compatibility with old style error handling code.


Method_sprintf

stringsprintf(stringformat, ... Error.Genericarg ... )


Method`[]

array|string res = Error.Generic()[ index ]

Description

Index operator.

Simulates an array

Array
stringmsg

Error message as returned by message.

arraybacktrace

Backtrace as returned by backtrace.

Note

The error message is always terminated with a newline.

See also

backtrace()


Methodbacktrace

arraybacktrace()

Description

Return the backtrace where the error occurred. Normally simply returns error_backtrace.

See also

predef::backtrace()


Methodcast

(array)Error.Generic()

Description

Cast operator.

Note

The only supported type to cast to is "array", which generates an old-style error ({message(),    backtrace()}).


Methodcreate

Error.GenericError.Generic(stringmessage, void|array(backtrace_frame|array(mixed)) backtrace)


Methoddescribe

stringdescribe()

Description

Return a readable error report that includes the backtrace.


Methodmessage

stringmessage()

Description

Return a readable message describing the error. Normally simply returns error_message.

If you override this function then you should ensure that error_message is included in the returned message, since there might be code that catches your error objects, extends error_message with more info, and rethrows the error.

Module Filesystem


Method`()

protectedfunction(:void) `()(void|stringpath)

Description

FIXME: Document this function


Methodget_filesystem

programget_filesystem(stringwhat)

Description

FIXME: Document this function


Methodparse_mode

intparse_mode(intold, int|stringmode)

Description

FIXME: Document this function

Class Filesystem.Base

Description

Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.


Methodapply

intapply()

Description

FIXME: Document this function


Methodcd

Basecd(string|voiddirectory)

Description

Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.


Methodchmod

voidchmod(stringfilename, int|stringmode)

Description

Change mode of a file or directory.


Methodchown

voidchown(stringfilename, int|objectowner, int|objectgroup)

Description

Change ownership of the file or directory


Methodchroot

Basechroot(void|stringdirectory)

Description

Change the root of the filesystem.


Methodcwd

stringcwd()

Description

Returns the current working directory within the filesystem.


Methodfind

arrayfind(void|function(Stat:int) mask, mixed ... extra)

Description

FIXME: Document this function


Methodget_dir

array(string) get_dir(void|stringdirectory, void|string|arrayglob)

Description

Returns an array of all files and directories within a given directory.

Parameter directory

Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.

Parameter glob

Return only files and dirs matching the glob (if given).

See also

[get_stats]


Methodget_stats

array(Stat) get_stats(void|stringdirectory, void|string|arrayglob)

Description

Returns stat-objects for the files and directories matching the given glob within the given directory.

See also

[get_dir]


Methodmkdir

intmkdir(stringdirectory, void|int|stringmode)

Description

Create a new directory


Methodopen

Stdio.Fileopen(stringfilename, stringmode)

Description

Open a file within the filesystem

Returns

A Stdio.File object.


Methodrm

intrm(stringfilename)

Description

Remove a file from the filesystem.


Methodstat

Statstat(stringfile, int|voidlstat)

Description

Return a stat-object for a file or a directory within the filesystem.

Class Filesystem.Stat

Description

Describes the stat of a file


Variableisblk

bool Filesystem.Stat.isblk

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableischr

bool Filesystem.Stat.ischr

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableisdir

bool Filesystem.Stat.isdir

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableisdoor

bool Filesystem.Stat.isdoor

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableisfifo

bool Filesystem.Stat.isfifo

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableislnk

bool Filesystem.Stat.islnk

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableisreg

bool Filesystem.Stat.isreg

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Variableissock

bool Filesystem.Stat.issock

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]

Note

Read only


Methodattach_statarray

voidattach_statarray(array(int) a)

Description

Fills the stat-object with data from a Stdio.File.stat() call.


Methodcd

object|zerocd()

Description

Change to the stated directory.

Returns

the directory if the stated object was a directory, 0 otherwise.


Methodnice_date

stringnice_date()

Description

Returns the date of the stated object as cleartext.


Methodopen

Stdio.Fileopen(stringmode)

Description

Open the stated file within the filesystem

Returns

a [Stdio.File] object

See also

[Stdio.File]


Methodset_type

voidset_type(stringx)

Description

Set a type for the stat-object.

Note

This call doesnot change the filetype in the underlaying filesystem.

Parameter x

Type to set. Type is one of the following:

  • fifo
  • chr
  • dir
  • blk
  • reg
  • lnk
  • sock
  • door
See also

[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]

Class Filesystem.System

Description

Implements an abstraction of the normal filesystem.


InheritBase

inherit Filesystem.Base : Base


Methodcreate

Filesystem.SystemFilesystem.System(void|stringdirectory, void|stringroot, void|intfast, void|Filesystem.Baseparent)

Description

Instanciate a new object representing the filesystem.

Parameter directory

The directory (in the real filesystem) that should become the root of the filesystemobject.

Parameter root

Internal

Parameter fast

Internal

Parameter parent

Internal

Class Filesystem.Traversion

Description

Iterator object that traverses a directory tree and returns files as values and paths as indices. Example that uses the iterator to create a really simple sort of make:

Example

object i=Filesystem.Traversion("."); foreach(i; string dir; string file) { if(!has_suffix(file, ".c")) continue; file = dir+file; string ofile = file; ofile[-1]='o'; object s=file_stat(ofile); if(s && i->stat()->mtime<s->mtime) continue; // compile file }


Methodcreate

Filesystem.TraversionFilesystem.Traversion(stringpath, void|boolsymlink, void|boolignore_errors, void|function(array:array) sort_fun)

Parameter path

The root path from which to traverse.

Parameter symlink

Don't traverse symlink directories.

Parameter ignore_errors

Ignore directories that can not be accessed.

Parameter sort_fun

Sort function to be applied to directory entries before traversing. Can also be a filter function.


Methodprogress

floatprogress(void|floatshare)

Description

Returns the current progress of the traversion as a value between 0.0 and 1.0. Note that this value isn't based on the number of files, but the directory structure.


Methodstat

Stdio.Stat|zerostat()

Description

Returns the stat for the current index-value-pair.

Module Filesystem.Monitor

Class Filesystem.Monitor.basic

Description

Basic filesystem monitor.

This module is intended to be used for incremental scanning of a filesystem.

Supports FSEvents on MacOS X and Inotify on Linux to provide low overhead monitoring; other systems use a less efficient polling approach.

See also

Filesystem.Monitor.symlinks, System.FSEvents, System.Inotify


Constantdefault_file_interval_factor

protected constantint Filesystem.Monitor.basic.default_file_interval_factor

Description

The default factor to multiply default_max_dir_check_interval with to get the maximum number of seconds between checks of files.

The value can be changed by calling create().

The value can be overridden for individual files or directories by calling monitor().

Overload this constant to change the default.


Constantdefault_max_dir_check_interval

protected constantint Filesystem.Monitor.basic.default_max_dir_check_interval

Description

The default maximum number of seconds between checks of directories in seconds.

This value is multiplied with default_file_interval_factor to get the corresponding default maximum number of seconds for files.

The value can be changed by calling create().

The value can be overridden for individual files or directories by calling monitor().

Overload this constant to change the default.


Constantdefault_stable_time

protected constantint Filesystem.Monitor.basic.default_stable_time

Description

The default minimum number of seconds without changes for a change to be regarded as stable (see stable_data_change().


Variablebackend

protectedPike.Backend Filesystem.Monitor.basic.backend

Description

Backend to use.

If 0 (zero) - use the default backend.


Variableco_id

protectedmixed Filesystem.Monitor.basic.co_id

Description

Call-out identifier for backend_check() if in nonblocking mode.

See also

set_nonblocking(), set_blocking()


Variablemonitor_mutex

protectedThread.Mutex Filesystem.Monitor.basic.monitor_mutex

Description

Mutex controlling access to monitor_queue.


Variablemonitor_queue

protectedADT.Heap Filesystem.Monitor.basic.monitor_queue

Description

Heap containing active Monitors that need polling.

The heap is sorted on Monitor()->next_poll.


Variablemonitors

protectedmapping(string:Monitor) Filesystem.Monitor.basic.monitors

Description

Mapping from monitored path to corresponding Monitor.

The paths are normalized to canonic_path(path),

Note

All filesystems are handled as if case-sensitive. This should not be a problem for case-insensitive filesystems as long as case is maintained.


Methodadjust_monitor

protectedvoidadjust_monitor(Monitorm)

Description

Update the position in the monitor_queue for the monitor m to account for an updated next_poll value.


Methodattr_changed

voidattr_changed(stringpath, Stdio.Statst)

Description

File attribute changed callback.

Parameter path

Path of the file or directory which has changed attributes.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when a change has been detected for an attribute for a monitored file or directory.

Called by check() and check_monitor().

Note

If there is a data_changed() callback, it may supersede this callback if the file content also has changed.

Overload this to do something useful.


Methodbackend_check

protectedvoidbackend_check()

Description

Backend check callback function.

This function is intended to be called from a backend, and performs a check() followed by rescheduling itself via a call to set_nonblocking().

See also

check(), set_nonblocking()


Methodcanonic_path

protectedstringcanonic_path(stringpath)

Description

Canonicalize a path.

Parameter path

Path to canonicalize.

Returns

The default implementation returns combine_path(path, "."), i.e. no trailing slashes.


Methodcheck

intcheck(int|voidmax_wait, int|voidmax_cnt, mapping(string:int)|voidret_stats)

Description

Check for changes.

Parameter max_wait

Maximum time in seconds to wait for changes. -1 for infinite wait.

Parameter max_cnt

Maximum number of paths to check in this call. 0 (zero) for unlimited.

Parameter ret_stats

Optional mapping that will be filled with statistics (see below).

A suitable subset of the monitored files will be checked for changes.

Returns

The function returns when either a change has been detected or when max_wait has expired. The returned value indicates the number of seconds until the next call of check().

If ret_stats has been provided, it will be filled with the following entries:

"num_monitors" : int

The total number of active monitors when the scan completed.

"scanned_monitors" : int

The number of monitors that were scanned for updates during the call.

"updated_monitors" : int

The number of monitors that were updated during the call.

"idle_time" : int

The number of seconds that the call slept.

Note

Any callbacks will be called from the same thread as the one calling check().

See also

check_all(), monitor()


Methodcheck_all

voidcheck_all(mapping(string:int)|voidret_stats)

Description

Check all monitors for changes.

Parameter ret_stats

Optional mapping that will be filled with statistics (see below).

All monitored paths will be checked for changes.

Note

You typically don't want to call this function, but instead check().

Note

Any callbacks will be called from the same thread as the one calling check().

See also

check(), monitor()


Methodcheck_monitor

protectedboolcheck_monitor(Monitorm, MonitorFlags|voidflags)

Description

Check a single Monitor for changes.

Parameter m

Monitor to check.

Parameter flags
0

Don't recurse.

1

Check all monitors for the entire subtree rooted in m.

This function is called by check() for the Monitors it considers need checking. If it detects any changes an appropriate callback will be called.

Returns

Returns 1 if a change was detected and 0 (zero) otherwise.

Note

Any callbacks will be called from the same thread as the one calling check_monitor().

Note

The return value can not be trusted to return 1 for all detected changes in recursive mode.

See also

check(), data_changed(), attr_changed(), file_created(), file_deleted(), stable_data_change()


Methodclear

voidclear()

Description

Clear the set of monitored files and directories.

Note

Due to circular datastructures, it's recomended to call this function prior to discarding the object.


Methodcreate

Filesystem.Monitor.basicFilesystem.Monitor.basic(int|voidmax_dir_check_interval, int|voidfile_interval_factor, int|voidstable_time)

Description

Create a new monitor.

Parameter max_dir_check_interval

Override of default_max_dir_check_interval.

Parameter file_interval_factor

Override of default_file_interval_factor.

Parameter stable_time

Override of default_stable_time.


Methoddata_changed

voiddata_changed(stringpath)

Description

File content changed callback.

Parameter path

Path of the file which has had content changed.

This function is called when a change has been detected for a monitored file.

Called by check() and check_monitor().

Overload this to do something useful.


Methodfile_created

voidfile_created(stringpath, Stdio.Statst)

Description

File creation callback.

Parameter path

Path of the new file or directory.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.

Called by check() and check_monitor().

Overload this to do something useful.

Note

This callback has similar semantics to file_exists(), but is called at run time.

See also

file_exists(), file_deleted(), stable_data_change()


Methodfile_deleted

voidfile_deleted(stringpath)

Description

File deletion callback.

Parameter path

Path of the new file or directory that has been deleted.

This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.

Called by check() and check_monitor().

Overload this to do something useful.

See also

file_created(), file_exists(), stable_data_change()


Methodfile_exists

voidfile_exists(stringpath, Stdio.Statst)

Description

File existance callback.

Parameter path

Path of the file or directory.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.

Note

For directories, file_exists() will be called for the subpaths before the call for the directory itself. This can be used to detect when the initialization for a directory is finished.

Called by check() and check_monitor() the first time a monitored path is checked (and only if it exists).

Overload this to do something useful.

Note

This callback has similar semantics to file_created(), but is called at initialization time.

See also

file_created(), file_deleted(), stable_data_change()


Methodinotify_event

protectedvoidinotify_event(intwd, intevent, intcookie, string(8bit)path)

Description

Event callback for Inotify.


Methodis_monitored

boolis_monitored(stringpath)

Description

Check whether a path is monitored or not.

Parameter path

Path to check.

Returns

Returns 1 if there is a monitor on path, and 0 (zero) otherwise.

See also

monitor(), release()


Methodlow_eventstream_callback

protectedvoidlow_eventstream_callback(stringpath, intflags, intevent_id)

Description

This function is called when the FSEvents EventStream detects a change in one of the monitored directories.


Methodmonitor

Monitor|voidmonitor(stringpath, MonitorFlags|voidflags, int(0..)|voidmax_dir_check_interval, int(0..)|voidfile_interval_factor, int(0..)|voidstable_time)

Description

Register a path for monitoring.

Parameter path

Path to monitor.

Parameter flags
0

Don't recurse.

1

Monitor the entire subtree, and any directories or files that may appear later.

3

Monitor the entire subtree, and any directories or files that may appear later. Remove the monitor automatically when path is deleted.

Parameter max_dir_check_interval

Override of default_max_dir_check_interval for this path or subtree.

Parameter file_interval_factor

Override of default_file_interval_factor for this path or subtree.

Parameter stable_time

Override of default_stable_time for this path or subtree.

See also

release()


Methodmonitor_factory

protectedDefaultMonitormonitor_factory(stringpath, MonitorFlags|voidflags, int(0..)|voidmax_dir_check_interval, int(0..)|voidfile_interval_factor, int(0..)|voidstable_time)

Description

Create a new Monitor for a path.

This function is called by monitor() to create a new Monitor object.

The default implementation just calls DefaultMonitor with the same arguments.

See also

monitor(), DefaultMonitor


Methodrelease

voidrelease(stringpath, MonitorFlags|voidflags)

Description

Release a path from monitoring.

Parameter path

Path to stop monitoring.

Parameter flags
0

Don't recurse.

1

Release the entire subtree.

3

Release the entire subtree, but only those paths that were added automatically by a recursive monitor.

See also

monitor()


Methodrelease_monitor

protectedvoidrelease_monitor(Monitorm)

Description

Release a single Monitor from monitoring.

See also

release()


Methodreport

protectedvoidreport(SeverityLevellevel, string(7bit)fun, sprintf_formatformat, sprintf_args ... args)

Description

Event tracing callback.

Parameter level

Severity level of the event.

Parameter fun

Name of the function that called report().

Parameter format

sprintf() formatting string describing the event.

Parameter args

Optional extra arguments for the format string.

This function is called in various places to provide granular tracing of the monitor state.

The default implementation calls werror() with format and args if level is ERROR or higher, or if FILESYSTEM_MONITOR_DEBUG has been defined.


Methodreschedule_backend_check

protectedvoidreschedule_backend_check(int|voidsuggested_t)

Description

Reschedule beckend check.

Parameter suggested_t

Suggested time in seconds until next call of check().

Register suitable callbacks with the backend to automatically call check().

check() and thus all the callbacks will be called from the backend thread.


Methodset_backend

voidset_backend(Pike.Backend|voidbackend)

Description

Change backend.

Parameter backend

Backend to use. 0 (zero) for the default backend.


Methodset_blocking

voidset_blocking()

Description

Turn off nonblocking mode.

See also

set_nonblocking()


Methodset_file_interval_factor

voidset_file_interval_factor(intfile_interval_factor)

Description

Set the file_interval_factor.


Methodset_max_dir_check_interval

voidset_max_dir_check_interval(intmax_dir_check_interval)

Description

Set the max_dir_check_interval.


Methodset_nonblocking

voidset_nonblocking(int|voidsuggested_t)

Description

Turn on nonblocking mode.

Parameter suggested_t

Suggested time in seconds until next call of check().

Register suitable callbacks with the backend to automatically call check().

check() and thus all the callbacks will be called from the backend thread.

Note

If nonblocking mode is already active, this function will be a noop.

See also

set_blocking(), check().


Methodset_stable_time

voidset_stable_time(intstable_time)

Description

Set the stable_time.


Methodstable_data_change

voidstable_data_change(stringpath, Stdio.Statst)

Description

Stable change callback.

Parameter path

Path of the file or directory that has stopped changing.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when previous changes to path are considered "stable".

"Stable" in this case means that there have been no detected changes for at lease stable_time seconds.

Called by check() and check_monitor().

Overload this to do something useful.

Note

This callback being called does not mean that the contents or inode has changed, just that they don't seem to change any more. In particular it is called for paths found during initialization after stable_time seconds have passed.

See also

file_created(), file_exists(), file_deleted()

Enum Filesystem.Monitor.basic.MonitorFlags

Description

Flags for Monitors.


ConstantMF_RECURSE
ConstantMF_AUTO
ConstantMF_INITED
ConstantMF_HARD

constant Filesystem.Monitor.basic.MF_RECURSE
constant Filesystem.Monitor.basic.MF_AUTO
constant Filesystem.Monitor.basic.MF_INITED
constant Filesystem.Monitor.basic.MF_HARD

Class Filesystem.Monitor.basic.DefaultMonitor

Description

This symbol evaluates to the Monitor class used by the default implementation of monitor_factory().

It is currently one of the values Monitor, EventStreamMonitor or InotifyMonitor.

See also

monitor_factory()


InheritMonitor

inherit Monitor : Monitor

Class Filesystem.Monitor.basic.EventStreamMonitor

Description

FSEvents EventStream-accelerated Monitor.


InheritMonitor

inherit Monitor : Monitor

Class Filesystem.Monitor.basic.InotifyMonitor

Description

Inotify-accelerated Monitor.


InheritMonitor

inherit Monitor : Monitor

Class Filesystem.Monitor.basic.Monitor

Description

Monitoring information for a single filesystem path.

See also

monitor()


InheritElement

inherit ADT.Heap.Element(< Monitor >) : Element


Variablepath
Variableflags
Variablemax_dir_check_interval
Variablefile_interval_factor
Variablestable_time

string Filesystem.Monitor.basic.Monitor.path
MonitorFlags Filesystem.Monitor.basic.Monitor.flags
int Filesystem.Monitor.basic.Monitor.max_dir_check_interval
int Filesystem.Monitor.basic.Monitor.file_interval_factor
int Filesystem.Monitor.basic.Monitor.stable_time


Method__create__

protectedlocalvoid__create__(stringpath, MonitorFlagsflags, intmax_dir_check_interval, intfile_interval_factor, intstable_time)


Methodattr_changed

protectedvoidattr_changed(stringpath, Stdio.Statst)

Description

File attribute or content changed callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when a change has been detected for an attribute for a monitored file or directory.

Called by check() and check_monitor().

The default implementation calls global::attr_changed() or global::data_changed() depending on the state.

Note

If there is a data_changed() callback, it may supersede this callback if the file content also has changed.


Methodbump

voidbump(MonitorFlags|voidflags, int|voidseconds)

Description

Bump the monitor to an earlier scan time.

Parameter flags
0

Don't recurse.

1

Check all monitors for the entire subtree.

Parameter seconds

Number of seconds from now to run next scan. Defaults to half of the remaining interval.


Methodcall_callback

protectedvoidcall_callback(function(string, Stdio.Stat|void:void) cb, stringpath, Stdio.Stat|voidst)

Description

Call a notification callback.

Parameter cb

Callback to call or UNDEFINED for no operation.

Parameter path

Path to notify on.

Parameter st

Stat for the path.


Methodcheck

boolcheck(MonitorFlags|voidflags)

Description

Check for changes.

Parameter flags
0

Don't recurse.

1

Check all monitors for the entire subtree rooted in m.

This function is called by check() for the Monitors it considers need checking. If it detects any changes an appropriate callback will be called.

Returns

Returns 1 if a change was detected and 0 (zero) otherwise.

Note

Any callbacks will be called from the same thread as the one calling check_monitor().

Note

The return value can not be trusted to return 1 for all detected changes in recursive mode.

See also

check(), data_changed(), attr_changed(), file_created(), file_deleted(), stable_data_change()


Methodcheck_for_release

voidcheck_for_release(intmask, intflags)

Description

Check if this monitor should be removed automatically.


Methodfile_created

protectedvoidfile_created(stringpath, Stdio.Statst)

Description

File creation callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.

Called by check() and check_monitor().

The default implementation registers the path, and calls global::file_deleted().

Note

This callback has similar semantics to file_exists(), but is called at run time.

See also

file_exists(), file_deleted(), stable_data_change()


Methodfile_deleted

protectedvoidfile_deleted(stringpath, Stdio.Stat|voidold_st)

Description

File deletion callback.

Parameter path

Path of the new file or directory that has been deleted.

Parameter old_st

Stat for the file prior to deletion (if known). Note that this argument is not passed along to top level function.

This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.

Called by check() and check_monitor().

The default implementation unregisters the path, and calls global::file_deleted().

See also

file_created(), file_exists(), stable_data_change()


Methodfile_exists

protectedvoidfile_exists(stringpath, Stdio.Statst)

Description

File existance callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.

Note

For directories, file_created() will be called for the subpaths before the call for the directory itself. This can be used to detect when the initialization for a directory is finished.

Called by check() and check_monitor() the first time a monitored path is checked (and only if it exists).

The default implementation registers the path, and calls global::file_exists().

Note

This callback has similar semantics to file_created(), but is called at initialization time.

See also

file_created(), file_deleted(), stable_data_change()


Methodmonitor

protectedvoidmonitor(stringpath, intflags, intmax_dir_interval, intfile_interval_factor, intstable_time)

Description

Called to create a sub monitor.


Methodparent

this_programparent()

Description

Returns the parent monitor, or UNDEFINED if no such monitor exists.


Methodregister_path

protectedvoidregister_path(int|voidinitial)

Description

Register the Monitor with the monitoring system.

Parameter initial

Indicates that the Monitor is newly created.


Methodreport

protectedvoidreport(SeverityLevellevel, string(7bit)fun, sprintf_formatformat, sprintf_args ... args)

Description

Event tracing callback.

Parameter level

Severity level of the event.

Parameter fun

Name of the function that called report().

Parameter format

sprintf() formatting string describing the event.

Parameter args

Optional extra arguments for the format string.

This function is called in various places to provide granular tracing of the monitor state.

The default implementation just calls global::report() with the same arguments.


Methodstable_data_change

protectedvoidstable_data_change(stringpath, Stdio.Statst)

Description

Stable change callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when previous changes to path are considered "stable".

"Stable" in this case means that there have been no detected changes for at lease stable_time seconds.

Called by check() and check_monitor().

The default implementation calls global::stable_data_change().

Note

This callback being called does not mean that the contents or inode has changed, just that they don't seem to change any more. In particular it is called for paths found during initialization after stable_time seconds have passed.

See also

file_created(), file_exists(), file_deleted()


Methodstatus_change

protectedboolstatus_change(Stdio.Statold_st, Stdio.Statst, intorig_flags, intflags)

Description

Called when the status has changed for an existing file.


Methodsubmonitor_released

voidsubmonitor_released(this_programsubmon)

Description

To be called when a (direct) submonitor is released.


Methodunregister_path

protectedvoidunregister_path(int|voiddying)

Description

Unregister the Monitor from the monitoring system.

Parameter dying

Indicates that the Monitor is being destructed. It is the destruction cause value offset by one.


Methodupdate

protectedvoidupdate(Stdio.Statst)

Description

Calculate and set a suitable time for the next poll of this monitor.

Parameter st

New stat for the monitor.

This function is called by check() to schedule the next check.

Class Filesystem.Monitor.debug

Description

Debugging filesystem monitor.

This module behaves as symlinks, but has default implementations of all callbacks that call report(), as well as an implementation of [report()] that logs everything to Stdio.stderr.

See also

Filesystem.Monitor.basic, Filesystem.Monitor.symlinks


Inherit"symlinks.pike"

inherit "symlinks.pike" : "symlinks.pike"


Methodget_monitors

mapping(string:Monitor) get_monitors()

Description

Return the set of active monitors.

Class Filesystem.Monitor.symlinks

Description

Filesystem monitor with support for symbolic links.

This module extends Filesystem.Monitor.basic with support for symbolic links.

Note

For operating systems where symbolic links aren't supported, this module will behave exactly like Filesystem.Monitor.basic.

See also

Filesystem.Monitor.basic


Inheritbasic

inherit Filesystem.Monitor.basic : basic


Variableavailable_ids

protectedint Filesystem.Monitor.symlinks.available_ids

Description

Bitmask of all unallocated symlink ids.


Variablesymlink_ids

protectedmapping(string:int) Filesystem.Monitor.symlinks.symlink_ids

Description

Mapping from symlink name to symlink id.


Variablesymlink_targets

protectedmapping(string:string) Filesystem.Monitor.symlinks.symlink_targets

Description

Mapping from symlink name to symlink target.


Methodallocate_symlink

protectedintallocate_symlink(stringsym)

Description

Allocates a symlink id for the link sym.


Methodattr_changed

voidattr_changed(stringpath, Stdio.Statst)

Description

File attribute changed callback.

Parameter path

Path of the file or directory which has changed attributes.

Parameter st

Status information for path as obtained by file_stat(path).

This function is called when a change has been detected for an attribute for a monitored file or directory.

Called by check() and check_monitor().

Note

If there is a data_changed() callback, it may supersede this callback if the file content also has changed.

Note

It differs from the Filesystem.Monitor.basic version in that symbolic links have the st of their targets.

Overload this to do something useful.


Methodfile_created

voidfile_created(stringpath, Stdio.Statst)

Description

File creation callback.

Parameter path

Path of the new file or directory.

Parameter st

Status information for path as obtained by file_stat(path).

This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.

Note

It differs from the Filesystem.Monitor.basic version in that symbolic links have the st of their targets.

Called by check() and check_monitor().

Overload this to do something useful.


Methodfile_exists

voidfile_exists(stringpath, Stdio.Statst)

Description

File existance callback.

Parameter path

Path of the file or directory.

Parameter st

Status information for path as obtained by file_stat(path).

This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.

Note

For directories, file_created() will be called for the subpaths before the call for the directory itself. This can be used to detect when the initialization for a directory is finished.

Note

It differs from the Filesystem.Monitor.basic version in that symbolic links have the st of their targets.

Called by check() and check_monitor() the first time a monitored path is checked (and only if it exists).

Overload this to do something useful.


Methodstable_data_change

voidstable_data_change(stringpath, Stdio.Statst)

Description

Stable change callback.

Parameter path

Path of the file or directory that has stopped changing.

Parameter st

Status information for path as obtained by file_stat(path).

This function is called when previous changes to path are considered "stable".

"Stable" in this case means that there have been no detected changes for at lease stable_time seconds.

Note

It differs from the Filesystem.Monitor.basic version in that symbolic links have the st of their targets.

Called by check() and check_monitor().

Overload this to do something useful.

Class Filesystem.Monitor.symlinks.DefaultMonitor

Description

Monitoring information for a single filesystem path.

With support for expansion of symbolic links.

See also

monitor()


InheritDefaultMonitor

inherit basic::DefaultMonitor : DefaultMonitor

Description

Based on Filesystem.Monitor.basic.DefaultMonitor.


Variablesymlinks

int Filesystem.Monitor.symlinks.DefaultMonitor.symlinks

Description

Mask of symlink ids that can reach this monitor.


Methodattr_changed

protectedvoidattr_changed(stringpath, Stdio.Statst)

Description

File attribute or content changed callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when a change has been detected for an attribute for a monitored file or directory.

Called by check() and check_monitor().

Note

If there is a data_changed() callback, it may supersede this callback if the file content also has changed.


Methodcall_callback

protectedvoidcall_callback(function(string, __unknown__ ... :void) cb, stringpath, Stdio.Stat|voidst)

Description

Call a notification callback and handle symlink expansion.

Parameter cb

Callback to call or UNDEFINED for no operation.

Parameter extras

Extra arguments after the path argument to cb.


Methodcheck_for_release

voidcheck_for_release(intmask, intflags)

Description

Check if this monitor should be removed automatically.


Methodcheck_symlink

protectedvoidcheck_symlink(stringpath, Stdio.Stat|zerost, int|voidinhibit_notify)

Description

Check whether a symlink has changed.


Methodfile_created

protectedvoidfile_created(stringpath, Stdio.Statst)

Description

File creation callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.

Called by check() and check_monitor().


Methodfile_deleted

protectedvoidfile_deleted(stringpath, Stdio.Statold_st)

Description

File deletion callback.

Parameter path

Path of the new file or directory that has been deleted.

This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.

Called by check() and check_monitor().


Methodfile_exists

protectedvoidfile_exists(stringpath, Stdio.Statst)

Description

File existance callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.

Note

For directories, file_created() will be called for the subpaths before the call for the directory itself. This can be used to detect when the initialization for a directory is finished.

Called by check() and check_monitor() the first time a monitored path is checked (and only if it exists).


Methodlow_call_callback

voidlow_call_callback(function(string, __unknown__ ... :void) cb, mapping(string:int) state, mapping(string:string) symlink_targets, stringpath, Stdio.Stat|voidst, string|voidsymlink)

Description

Call a notification callback and handle symlink expansion.

Parameter cb

Callback to call or UNDEFINED for no operation.

Parameter state

State mapping to avoid multiple notification and infinite loops. Call with an empty mapping.

Parameter symlinks

Symlinks that have not been expanded yet.

Parameter path

Path to notify on.

Parameter extras

Extra arguments to cb.

Parameter symlink

Symbolic link that must have been followed for the callback to be called.


Methodmonitor

protectedvoidmonitor(stringpath, intflags, intmax_dir_interval, intfile_interval_factor, intstable_time)

Description

Called to create a sub monitor.


Methodstable_data_change

protectedvoidstable_data_change(stringpath, Stdio.Statst)

Description

Stable change callback.

Parameter st

Status information for path as obtained by file_stat(path, 1).

This function is called when previous changes to path are considered "stable".

"Stable" in this case means that there have been no detected changes for at lease stable_time seconds.

Called by check() and check_monitor().


Methodstatus_change

protectedboolstatus_change(Stdio.Statold_st, Stdio.Statst, intorig_flags, intflags)

Description

Called when the status has changed for an existing file.


Methodzap_symlink

protectedvoidzap_symlink(stringpath)

Description

Called when the symlink path is no more.

Module Filesystem.Tar

Description

Filesystem which can be used to mount a Tar file.

Two kinds of extended tar file records are supported:

"ustar\0\60\60"

POSIX ustar (Version 0?).

"ustar \0"

GNU tar (POSIX draft)

Note

For a quick start, you probably want to use `()().

See also

`()()


ConstantEXTRACT_CHOWN

constantint Filesystem.Tar.EXTRACT_CHOWN

Description

Set owning user and group from the tar records.


ConstantEXTRACT_ERR_ON_UNKNOWN

constantint Filesystem.Tar.EXTRACT_ERR_ON_UNKNOWN

Description

Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise.


ConstantEXTRACT_SKIP_EXT_MODE

constantint Filesystem.Tar.EXTRACT_SKIP_EXT_MODE

Description

Don't set set-user-ID, set-group-ID, or sticky bits from the tar records.


ConstantEXTRACT_SKIP_MODE

constantint Filesystem.Tar.EXTRACT_SKIP_MODE

Description

Don't set any permission bits from the tar records.


ConstantEXTRACT_SKIP_MTIME

constantint Filesystem.Tar.EXTRACT_SKIP_MTIME

Description

Don't set mtime from the tar records.

Class Filesystem.Tar._Tar

Description

Low-level Tar Filesystem.


Methodextract

voidextract(stringsrc_dir, stringdest_dir, void|string|function(string, Filesystem.Stat:int|string) filter, void|intflags)

Description

Extracts files from the tar file in sequential order.

Parameter src_dir

The root directory in the tar file system to extract.

Parameter dest_dir

The root directory in the real file system that will receive the contents of src_dir. It is assumed to exist and be writable.

Parameter filter

A filter for the entries under src_dir to extract. If it's a string then it's taken as a glob pattern which is matched against the path below src_dir. That path always begins with a /. For directory entries it ends with a / too, otherwise not.

If it's a function then it's called for every entry under src_dir, and those where it returns nonzero are extracted. The function receives the path part below src_dir as the first argument, which is the same as in the glob case above, and the stat struct as the second. If the function returns a string, it's taken as the path below dest_dir where this entry should be extracted (any missing directories are created automatically).

If filter is zero, then everything below src_dir is extracted.

Parameter flags

Bitfield of flags to control the extraction:

Filesystem.Tar.EXTRACT_SKIP_MODE

Don't set any permission bits from the tar records.

Filesystem.Tar.EXTRACT_SKIP_EXT_MODE

Don't set set-user-ID, set-group-ID, or sticky bits from the tar records.

Filesystem.Tar.EXTRACT_SKIP_MTIME

Don't set mtime from the tar records.

Filesystem.Tar.EXTRACT_CHOWN

Set owning user and group from the tar records.

Filesystem.Tar.EXTRACT_ERR_ON_UNKNOWN

Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise.

Files and directories are supported on all platforms, and symlinks are supported whereever symlink exists. Other record types are currently not supported.

Throws

I/O errors are thrown.

Class Filesystem.Tar._TarFS


InheritSystem

inherit Filesystem.System : System


Methodchmod

voidchmod(stringfilename, int|stringmode)

FIXME

Not implemented yet.


Methodchown

voidchown(stringfilename, int|objectowner, int|objectgroup)

FIXME

Not implemented yet.


Methodcreate

Filesystem.Tar._TarFSFilesystem.Tar._TarFS(_Tar_tar, string_wd, string_root, Filesystem.Base_parent)


Methodrm

intrm(stringfilename)

FIXME

Not implemented yet.

Class Filesystem.Tar.`()


Inherit_TarFS

inherit _TarFS : _TarFS


Methodcreate

Filesystem.Tar.`()Filesystem.Tar.`()(stringfilename, void|Filesystem.Baseparent, void|objectfile)

Parameter filename

The tar file to mount.

Parameter parent

The parent filesystem. If none is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.

Parameter file

If specified, this should be an open file descriptor. This object could e.g. be a Stdio.File, Gz.File or Bz2.File object.

Module Filesystem.Zip


Methodcreate

void Filesystem.Zipcreate(stringfilename, void|Filesystem.Baseparent, void|objectfile)

Description

Filesystem which can be used to mount a ZIP file.

Parameter filename

The tar file to mount.

Parameter parent

The parent filesystem. If non is given, the normal system filesystem is assumed. This allows mounting a ZIP-file within a zipfile.

Parameter file

If specified, this should be an open file descriptor. This object could e.g. be a Stdio.File or similar object.

Class Filesystem.Zip.Decrypt

Description

traditional Zip encryption is CRC32 based, and rather insecure. support here exists to ease transition and to work with legacy files.


Methoddecrypt

stringdecrypt(stringx)

Description

decrypt a string

Parameter x

encrypted string to decrypt

Class Filesystem.Zip._Zip

Description

A class for reading and writing ZIP files.

Note that this class does not support the full ZIP format specification, but does support the most common features.

Storing, Deflating and Bzip2 (if the Bz2 module is available) are supported storage methods.

This class is able to extract data from traditional ZIP password encrypted archives.

Notably, advanced PKware encryption (beyond reading traditional password protected archives) and multi-part archives are not currently supported.


Methodadd_dir

voidadd_dir(stringpath, intrecurse, string|voidarchiveroot)

Description

adds a directory to an archive


Methodadd_file

voidadd_file(stringfilename, string|Stdio.File|zerodata, int|object|voidstamp, int|voidno_compress)

Description

add a file to an archive.


Methodcreate

Filesystem.Zip._ZipFilesystem.Zip._Zip(object|voidfd, string|voidfilename, object|voidparent)


Methoddate_dos2unix

intdate_dos2unix(inttime, intdate)

Description

Convert MS-DOS time/date pair to a linear UNIX date.


Methoddate_unix2dos

arraydate_unix2dos(intunix_date)

Description

Convert linear UNIX date to a MS-DOS time/date pair.

Returns

an array containing ({time, date})


Methodgenerate

stringgenerate()

Description

generate the zip archive


Methodis_zip64

intis_zip64()

Description

is this archive using zip64 extensions?


Methodset_compression_value

voidset_compression_value(int(0..9)v)

Description

sets the compression value (0 to 9)


Methodset_password

voidset_password(stringpw)

Description

sets the password to be used for files encrypted using traditional PKZip encryption.


Methodset_zip64

voidset_zip64(intflag)

Description

enable zip64 extensions (large files) for this archive

Note

This setting may be used to force zip64 for files that do not otherwise require its use. If a file whose properties requires the use of zip65 is added to an archive, zip64 extensions will be enabled automatically.


Methodunzip

voidunzip(stringtodir)

Class Filesystem.Zip._ZipFS


InheritSystem

inherit Filesystem.System : System


Methodset_password

voidset_password(stringpw)

Module Fuse

Description

Fuse - Filesystem in USErspace

FUSE (Filesystem in USErspace) provides a simple interface for userspace programs to export a virtual filesystem to the Linux kernel. FUSE also aims to provide a secure method for non privileged users to create and mount their own filesystem implementations.

See http://sourceforge.net/projects/fuse/ for more information

This module maps the Fuse library more or less directly to pike.

In order to create a filesystem, create a subclass of the Operations class, clone it and pass it to the run method.

You do not need to implemnent all functions, but at least getattr, readdir and read are needed to make a useable filesystem.

A tip: ERRNO constants are available in the System module, and if one is missing /usr/include/asm[-generic]/errno.h can be included in pike programs on Linux.


Inherit"___Fuse"

inherit "___Fuse" : "___Fuse"


ConstantFUSE_MAJOR_VERSION
ConstantFUSE_MINOR_VERSION

constant Fuse.FUSE_MAJOR_VERSION
constant Fuse.FUSE_MINOR_VERSION

Description

The version of FUSE


Methodrun

voidrun(Operationshandler, array(string) args)

Description

Start fuse. Args is as in argv in main(). This function will not return.

The first argument (argv[0], program name) is used as the filesystem name. The first non-flag argument after argv[0] is used as the mountpoint. Otherwise these arguments are supported:

     -d                  enable debug output (implies -f)
     -f                  foreground operation
     -s                  disable multithreaded operation
     -r                  mount read only (equivalent to '-o ro')
     -o opt,[opt...]     mount options
     -h                  print help
 

Mount options:

     rootmode=M             permissions of the '/' directory in the filesystem (octal)
     user_id=N              user of '/' (numeric)
     group_id=N             group of '/' (numeric)
     default_permissions    enable permission checking

  By default FUSE doesn't check file access permissions, the
  filesystem is free to implement it's access policy or leave it to
  the underlying file access mechanism (e.g. in case of network
  filesystems).  This option enables permission checking,
  restricting access based on file mode.  It is usually useful
  together with the 'allow_other' mount option.

     allow_other            allow access to other users

 This option overrides the security measure restricting file access
 to the user mounting the filesystem.  This option is by default
 only allowed to root, but this restriction can be removed with a
 (userspace) configuration option (in fuse.ini).

     large_read             issue large read requests (2.4 only)
     max_read=N             set maximum size of read requests (default 128K)
     hard_remove            immediate removal (don't hide files)
     debug                  enable debug output
     fsname=NAME            set filesystem name in mtab (overrides argv[0])
 

Class Fuse.Operations

Description

This is the interface you have to implement to write a FUSE filesystem If something goes wrong in your callback, always return errno. Unless the function returns a specific value (Stat, string or similar), return 0 if all is well.

You do not have to implement all functions. Unimplemented functions have a default implementation that returns -ENOIMPL.


ConstantDT_BLK

final constantint Fuse.Operations.DT_BLK

Description

Block special directory entry


ConstantDT_CHR

final constantint Fuse.Operations.DT_CHR

Description

Character special directory entry


ConstantDT_DIR

final constantint Fuse.Operations.DT_DIR

Description

Directory directory entry


ConstantDT_FIFO

final constantint Fuse.Operations.DT_FIFO

Description

FIFO directory entry


ConstantDT_LNK

final constantint Fuse.Operations.DT_LNK

Description

Symlink directory entry


ConstantDT_REG

final constantint Fuse.Operations.DT_REG

Description

Normal file directory entry


ConstantDT_SOCK

final constantint Fuse.Operations.DT_SOCK

Description

Socket directory entry


ConstantDT_UNKNOWN

final constantint Fuse.Operations.DT_UNKNOWN

Description

Unkown directory entry type


ConstantF_GETLK
ConstantF_SETLK
ConstantF_SETLKW
ConstantF_RDLCK
ConstantF_WRLCK
ConstantF_UNLCK

final constant Fuse.Operations.F_GETLK
final constant Fuse.Operations.F_SETLK
final constant Fuse.Operations.F_SETLKW
final constant Fuse.Operations.F_RDLCK
final constant Fuse.Operations.F_WRLCK
final constant Fuse.Operations.F_UNLCK

Description

lock() mode operations.


ConstantO_ACCMODE

final constantint Fuse.Operations.O_ACCMODE

Description

Mask for read/write/rdwr


ConstantO_APPEND

final constantint Fuse.Operations.O_APPEND

Description

Open for append


ConstantO_RDONLY

final constantint Fuse.Operations.O_RDONLY

Description

Open read only


ConstantO_RDWR

final constantint Fuse.Operations.O_RDWR

Description

Open read/write only


ConstantO_WRONLY

final constantint Fuse.Operations.O_WRONLY

Description

Open write only


Methodaccess

intaccess(stringpath, intmode)

Description

Return if the user is allowed to access the path. If the 'default_permissions' mount option is given, this method is not called.


Methodchmod

intchmod(stringpath, intmode)

Description

Change the permission of a file or directory

Returns

errno or 0


Methodchown

intchown(stringpath, intuid, intgid)

Description

Change the owner of a file or directory

Returns

errno or 0


Methodcreat

intcreat(stringpath, intmode, intflag)

Description

Create and open or just open the given path


Methodflush

intflush(stringpath, intflags)

Description

Write unwritten data.


Methodfsync

intfsync(stringpath, intdatasync)

Description

Flush data and user-data to disk. Not required. If the datasync parameter is non-zero, then only the user data should be flushed, not the meta data.


Methodgetattr

Stdio.Stat|int(1..)getattr(stringpath)

Description

Stat a file.

Note

This function is required.

Returns

A Stdio.Stat object or an errno.


Methodgetxattr

stringgetxattr(stringpath, stringname)

Description

Get the extended attribute name on path


Methodlink

intlink(stringsource, stringdestination)

Description

Create a hard link from source to destination.

Returns

errno or 0


Methodlistxattr

array(string)|intlistxattr(stringpath)

Description

Return a list of all available extended attributes on path


Methodlock

mapping(string:int)|intlock(stringpath, intmode, mapping(string:int) how)

Description

Lock, unlock or test for the existence of record locks (POSIX file locking). The owner of the lock is identified by how->owner

If you only need local file-locking on the computer the filesystem is mounted on you do not need to implement this interface. This is only needed for network filesystems that want locking to work over the network.

The operation mode depends on the mode argument.

F_SETLK

Acquire a lock (when how->type is F_RDLCK or F_WRLCK) or release a lock (when how->type is F_UNLCK) on the bytes specified by the how->whence, how->start, and how->len fields of lock. If a conflicting lock is held by another process, you should return EACCES or EAGAIN.

F_SETLKW

Identical to SETLK, but if a lock is held on the file, wait for it to be released before returning. You are allowed to return EINTR, to signal that the waiting has been interrupted and must be restarted.

F_GETLK

Identical to SETLK, but do not actually aquire the lock if it can be aquired. If one or more incompatible locks would prevent this lock being placed, then fcntl() returns details about one of these locks in the type, whence, start, and len fields of how and set pid to be the PID of the process holding that lock. Then return the mapping.


Methodmkdir

intmkdir(stringpath, intmode)

Description

Create a directory.

Returns

errno or 0


Methodmknod

intmknod(stringpath, intmode, intrdev)

Description

Create a node (file, device special, or named pipe). See man 2 mknod

Returns

errno or 0


Methodopen

intopen(stringpath, intmode)

Description

Open path. mode is as for the system call open. (mode & O_ACCMODE) is one of O_RDONLY, O_WRONLY and O_RDWR. The mode can also contain other flags, most notably O_APPEND.

Note

You do not really have to implement this function. It's useful to start prefetch and to cache open files, and check that the user has permission to read/write the file.

Returns

errno or 0


Methodread

string|int(1..)read(stringpath, intlen, intoffset)

Description

Read data from a file. You have to return at most len bytes, wunless an error occurs, or there is less than len bytes of data still left to read.

Returns

errno or the data


Methodreaddir

intreaddir(stringpath, function(string:void) callback)

Description

Get directory contents.

Call the callback once per file in the directory with the filename as the argument.

Note

This function is required.

Returns

errno or 0


Methodreadlink

string|int(1..)readlink(stringpath)

Description

Read a symlink.

Returns

The symlink contents or errno


Methodrelease

intrelease(stringpath)

Description

The inverse of open.

Note

The file might very well be openend multiple times. Keep reference counts.


Methodremovexattr

intremovexattr(stringpath, stringname)

Description

Remove the extended attribute name from path


Methodrename

intrename(stringsource, stringdestination)

Description

Rename source to destination.

Returns

errno or 0


Methodrmdir

intrmdir(stringpath)

Description

Remove a directory

Returns

errno or 0


Methodsetxattr

intsetxattr(stringpath, stringname, stringvalue, intflags)

Description

Set the extended attrbiute name on path to value


Methodstatfs

mapping(string:int) statfs(stringpath)

Description

Stat a filesystem. Mapping as from filesystem_stat

Note

required for 'df' support, without this function there is an error each time 'df' is run.


Methodsymlink

intsymlink(stringsource, stringdestination)

Description

Create a symlink from source to destination.

Returns

errno or 0


Methodtruncate

inttruncate(stringpath, intnew_length)

Description

Shrink or enlarge a file

Returns

errno or 0


Methodunlink

intunlink(stringpath)

Description

Remove a file

Returns

errno or 0


Methodutime

intutime(stringpath, intatime, intmtime)

Description

Set access and modification time. The arguments are the number of seconds since jan 1 1970 00:00.

This function is deprecated, utimens is the recommended method.

Returns

errno or 0


Methodutimens

intutimens(stringpath, intatime, intmtime)

Description

Set access and modification time, with nanosecond resolution. The arguments are the number of nanoseconds since jan 1 1970 00:00.

Returns

errno or 0


Methodwrite

intwrite(stringpath, stringdata, intoffset)

Description

Write data to the file. Should write all data.

Returns

errno or amount written (bytes)

Module Geography

Class Geography.Position

Description

This class contains a geographical position, ie a point on the earths surface. The resulting position object implements comparision methods (__hash, `==, `< and `>) so that you can compare and sort positions as well as using them as index in mappings. Comparision is made primary on latidue and secondly on longitude. It does not currently take the ellipsoid into account.

It is possible to cast a position into an array, which will yield ({ float latitude, float longitude }), as well as into a string.


Constantellipsoids

constant Geography.Position.ellipsoids

Description

A mapping with reference ellipsoids, which can be fed to the UTM converter. The mapping maps the name of the ellipsoid to an array where the first element is a float describing the equatorial radius and the second element is a float describing the polar radius.


Variablealt

float Geography.Position.alt

Description

Altitud of the position, in meters. Positive numbers is up. Zero is the shell of the current ellipsoid.


Variableequatorial_radius

float Geography.Position.equatorial_radius

Description

The equatorial radius is how many meters the earth radius is at the equator (east-west direction).


Variablelat

float Geography.Position.lat

Description

Latitude (N--S) of the position, in degrees. Positive number is north, negative number is south.


Variablelong

float Geography.Position.long

Description

Longitude (W--E) of the position, in degrees. Positive number is east, negative number is west.


Variablepolar_radius

float Geography.Position.polar_radius

Description

The polar radius is how many meters the earth radius is at the poles (north-south direction).


MethodECEF

array(float) ECEF()

Description

Returns the current position as Earth Centered Earth Fixed Cartesian Coordinates.

Returns

({ X, Y, Z })


MethodGEOREF

stringGEOREF()

Description

Gives the full GEOREF position for the current position, e.g. "LDJA0511".


MethodRT38

array(float) RT38()


MethodUTM

stringUTM(intprecision)

Description

Returns the current UTM coordinates position. An example output is "32T 442063.562 5247479.500" where the parts are zone number + zone designator, easting and northing.


MethodUTM_offset

array(float) UTM_offset()

Description

Returns the offset within the present UTM cell. The result will be returned in an array of floats, containing easting and northing.


MethodUTM_zone_designator

stringUTM_zone_designator()

Description

Returns the UTM letter designator for the current latitude. Returns "Z" if latitude is outside the UTM limits of 84N to 80S.


MethodUTM_zone_number

intUTM_zone_number()

Description

Returns the UTM zone number for the current longitude, with correction for the Svalbard deviations.


Method__hash

inthash_value(Geography.Positionarg)


Method_sprintf

stringsprintf(stringformat, ... Geography.Positionarg ... )


Method`<

int res = Geography.Position() < pos


Method`==

int res = Geography.Position() == pos


Method`>

int res = Geography.Position() > pos


Methodapprox_height

floatapprox_height()

Description

Returns a very crude approximation of where the ground level is at the current position, compared against the ellipsoid shell. WGS-84 is assumed, but the approximation is so bad that it doesn't matter which of the standard ellipsoids is used.


Methodcreate

Geography.PositionGeography.Position(int|floatlat, int|floatlong, void|int|floatalt)
Geography.PositionGeography.Position(stringlat, stringlong)
Geography.PositionGeography.Position(stringposition)
Geography.PositionGeography.Position()

Description

Constructor for this class. If fed with strings, it will perform a dwim scan on the strings. If they fails to be understood, there will be an exception.


Methodeccentricity_squared

floateccentricity_squared()

Description

Returns the first eccentricity squared for the selected earth approximation ellipsoid.


Methodeuclidian_distance

floateuclidian_distance(this_programp)

Description

Calculate the euclidian distance between two Geography.Position. Result is in meter. This uses the ECEF function.


Methodflattening

floatflattening()

Description

Returns the flattening factor for the selected earth approximation ellipsoid.


Methodlatitude
Methodlongitude

stringlatitude(void|intn)
stringlongitude(void|intn)

Description

Returns the nicely formatted latitude or longitude.

0

"17°42.19'N" / "42°22.2'W"

1

"17.703°N" / "42.37°W"

2

"17°42.18'N" / "42°22.2'W"

3

"17°42'10.4"N" / "42°22'12"W"

-1

"17.703" / "-42.37"


Methodset_ellipsoid

boolset_ellipsoid(stringname)
boolset_ellipsoid(floatequatorial_radius, floatpolar_radius)

Description

Sets the equatorial and polar radius to the provided values. A name can also be provided, in which case the radius will be looked up in the ellipsoid mapping. The function returns 1 upon success, 0 on failure.

"Airy 1830"
"ATS77"
"Australian National"
"Bessel 1841"
"Bessel 1841 Namibia"
"Clarke 1866"
"Clarke 1880"
"Everest"
"Everest 1830"
"Everest 1848"
"Everest 1856"
"Everest 1869"
"Everest Pakistan"
"Fisher 1960"
"Fisher 1968"
"G R S 1967"
"G R S 1975"
"G R S 1980"
"Helmert 1906"
"Hough 1956"
"Indonesian 1974"
"Krassovsky 1940"
"Mercury"
"Modified Airy"
"Modified Fisher 1960"
"New International 1967"
"SGS 85"
"South American 1969"
"Sphere"
"WGS 60"
"WGS 66"
"WGS 72"
"WGS 84"
Note

The longitude and lattitude are not converted to the new ellipsoid.


Methodset_from_RT38

voidset_from_RT38(int|float|stringx_n, int|float|stringy_e)

Description

Sets the longitude and lattitude from the given RT38 coordinates.


Methodset_from_UTM

voidset_from_UTM(intzone_number, stringzone_designator, floatUTME, floatUTMN)

Description

Sets the longitude and lattitude from the given UTM coordinates.


Methodstandard_grid

stringstandard_grid()

Description

Returns the standard map grid system for the current position. Can either be "UPS" or "UTM".

Class Geography.PositionRT38

Description

Create a Position object from a RT38 coordinate


InheritPosition

inherit .Position : Position

Module Geography.Countries


Variablecountries

array(Country) Geography.Countries.countries

Description

All known countries.


Method`[]
Method`->

mixed`[](stringwhat)
mixed`->(stringwhat)

Description

Convenience functions for getting a country the name-space way; it looks up whatever it is in the name- and domain-space and returns that country if possible:

>Geography.Countries.se;
Result: Country(Sweden)>Geography.Countries.djibouti;
Result: Country(Djibouti)>Geography.Countries.com;
Result: Country(United States)>Geography.Countries.wallis_and_futuna_islands->iso2;
Result:"WF"

Methodcontinents

mapping(string:array(Country)) continents()

Description

Gives back a mapping from continent name to an array of the countries on that continent.

The continents are:

    	  "Europe"
    	  "Africa"
    	  "Asia"
    	  "North America"
    	  "South America"
    	  "Oceania"
	  "Antarctica"
	
Note

Some countries are considered to be on more than one continent.


Methodfrom_domain

Countryfrom_domain(stringdomain)

Description

Look up a country from a domain name. Returns zero if the domain doesn't map to a country. Note that there are some valid domains that don't:

INT

International

MIL

US Military

NET

Network

ORG

Non-Profit Organization

ARPA

Old style Arpanet

NATO

Nato field

And that US has five domains, Great Britain and france two: <dl compact> <dt>EDU <dd>US Educational <dt>MIL <dd>US Military <dt>GOV <dd>US Government <dt>UM <dd>US Minor Outlying Islands <dt>US <dd>US <dt>GB <dd>Great Britain (UK) <dt>UK <dd>United Kingdom <dt>FR <dd>France <dt>FX <dd>France, Metropolitan <dt>There's also three domains that for convinience maps to US: <dt>NET <dd>Network <dt>ORG <dd>Organization <dt>COM <dd>Commercial </dl>


Methodfrom_domain

Countryfrom_domain(stringname)

Description

Look up a country from its name or aka. The search is case-insensitive but regards whitespace and interpunctation.

Class Geography.Countries.Country

Description

Country


Variablename
Variableaka

string Geography.Countries.Country.name
array(string) Geography.Countries.Country.aka

Description

Country name and also-known-as, if any


Variablefips10

string|zero Geography.Countries.Country.fips10

Description

FIPS 10-character code; "Federal Information Processing Standards 10-4" etc, previously used by some goverments in the US.

Note

This character code is slightly different from iso2, and should only be used for compatibility with old code.

Deprecated

Replaced by iso2.

FIPS 10-4 was withdrawn by NIST 2008-09-02.


Variableformer

int Geography.Countries.Country.former

Description

Flag that is set if this country doesn't exist anymore. (eg USSR.)


Variableiso2

string|zero Geography.Countries.Country.iso2

Description

ISO-3166-1 2-character code aka domain name.

Note

May be zero in some obscure cases where the ISO-3166-1 grouping differs from the FIPS-10 grouping.


Methodcast

(string)Geography.Countries.Country()

Description

It is possible to cast a country to a string, which will be the same as performing country->name;.


Methodcontinent

stringcontinent()

Description

Returns the continent of the country.

Note

Some countries are geographically in more then one continent; any of the continents might be returned then, but probably the continent in which the capital is resident - Europe for Russia, for instance.

Module Geography.GeoIP


Methodparse_77

voidparse_77(stringline, objecttree)

Description

Parsing function for geoip databases in the format used my http://software77.net/.


Methodparse_maxmind

voidparse_maxmind(stringline, objecttree)

Description

Parsing function for geoip databases in the format used my http://www.maxmind.com/.

Class Geography.GeoIP.IP

Description

Base class for GeoIP lookups. Use Geography.GeoIP.IPv4.


Methodfrom_ip

mixedfrom_ip(stringip)

Description

Returns the geographical location of the given ip address ip. When this object has been created using one of the standard parsing functions the locations are instances of Geography.Countries.Country.

Class Geography.GeoIP.IPv4

Description

Class for GeoIP lookups of ipv4 addresses. Uses ADT.CritBit.IPv4Tree objects internally to map IPv4 addresses to a geographical region.


InheritIP

inherit IP : IP


Methodcreate

Geography.GeoIP.IPv4Geography.GeoIP.IPv4(stringfile_name, function(string, ADT.CritBit.IPv4Tree:void) fun)
Geography.GeoIP.IPv4Geography.GeoIP.IPv4(ADT.CritBit.IPv4Treetree)

Description

Objects of this class can either be created from a file file_name with an optional parsing function fun. When fun is omitted, it defaults to Geography.GeoIP.parse_maxmind. fun will be called for each line in file_name and the critbit tree to add the entry to.

Alternatively, an instance of ADT.CritBit.IPv4Tree can be passed. tree is expected to map the first address of each range to its geographical location.

Module Getopt

Description

Getopt is a group of functions which can be used to find command line options.

Command line options come in two flavors: long and short. The short ones consists of a dash followed by a character (-t), the long ones consist of two dashes followed by a string of text (--test). The short options can also be combined, which means that you can write -tda instead of -t -d -a.

Options can also require arguments, in which case they cannot be combined. To write an option with an argument you write -t argument or -targument or --test=argument.


ConstantHAS_ARG

constantint Getopt.HAS_ARG

Description

Used with find_all_options() to indicate that an option requires an argument.

See also

find_all_options()


ConstantMAY_HAVE_ARG

constantint Getopt.MAY_HAVE_ARG

Description

Used with find_all_options() to indicate that an option takes an optional argument.

See also

find_all_options()


ConstantNO_ARG

constantint Getopt.NO_ARG

Description

Used with find_all_options() to indicate that an option does not take an argument.

See also

find_all_options()


Methodfind_all_options

array(array) find_all_options(array(string|zero) argv, array(array(array(string)|string|int)) options, void|int(-1..1)posix_me_harder, void|intthrow_errors)

Description

This function does the job of several calls to find_option(). The main advantage of this is that it allows it to handle the POSIX_ME_HARDER environment variable better. When either the argument posix_me_harder or the environment variable POSIX_ME_HARDER is true, no arguments will be parsed after the first non-option on the command line.

Parameter argv

The should be the array of strings that was sent as the second argument to your main() function.

Parameter options

Each element in the array options should be an array on the following form:

Array
stringname

Name is a tag used to identify the option in the output.

inttype

Type is one of Getopt.HAS_ARG, Getopt.NO_ARG and Getopt.MAY_HAVE_ARG and it affects how the error handling and parsing works. You should use HAS_ARG for options that require a path, a number or similar. NO_ARG should be used for options that do not need an argument, such as --version. MAY_HAVE_ARG should be used for options that may or may not need an argument.

string|array(string) aliases

This is a string or an array of string of options that will be looked for. Short and long options can be mixed, and short options can be combined into one string. Note that you must include the dashes so that find_all_options() can distinguish between long and short options. Example: ({"-tT","--test"}) This would make find_all_options look for -t, -T and --test.

void|string|array(string) env_var

This is a string or an array of strings containing names of environment variables that can be used instead of the command line option.

void|mixeddefault

This is the default value a MAY_HAVE_ARG option will have in the output if it was set but not assigned any value.

Only the first three elements need to be included.

Parameter posix_me_harder

Don't scan for arguments after the first non-option.

Parameter throw_errors

If throw_errors has been specified find_all_options() will throw errors on failure. If it has been left out, or is 0 (zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.

Returns

The good news is that the output from this function is a lot simpler. find_all_options() returns an array where each element is an array on this form:

Array
stringname

Option identifier name from the input.

mixedvalue

Value given. If no value was specified, and no default has been specified, the value will be 1.

Note

find_all_options() modifies argv.

Index 0 (zero) of argv is not scanned for options, since it is reserved for the program name.

See also

Getopt.get_args(), Getopt.find_option()


Methodfind_option

void|string|boolfind_option(array(string|zero) argv, array(string)|stringshortform, array(string)|string|voidlongform, array(string)|string|voidenvvars, string|bool|voiddef, int|voidthrow_errors)

Description

This is a generic function to parse command line options of the type -f, --foo or --foo=bar.

Parameter argv

The first argument should be the array of strings that was sent as the second argument to your main() function.

Parameter shortform

The second is a string with the short form of your option. The short form must be only one character long. It can also be an array of strings, in which case any of the options in the array will be accepted.

Parameter longform

This is an alternative and maybe more readable way to give the same option. If you give "foo" as longform your program will accept --foo as argument. This argument can also be an array of strings, in which case any of the options in the array will be accepted.

Parameter envvars

This argument specifies an environment variable that can be used to specify the same option, to make it easier to customize program usage. It can also be an array of strings, in which case any of the mentioned variables in the array may be used.

Parameter def

This argument has two functions: It specifies if the option takes an argument or not, and it informs find_option() what to return if the option is not present.

The value may be one of:

int(0)|zero

The option does not require a value.

int(1)|string

The option requires a value, and def will be returned if the option is not present. If the option is present, but does not have an argument find_option() will fail.

Note that a set option will always return a string, so setting def to 1 can be used to detect whether the option is present or not.

Parameter throw_errors

If throw_errors has been specified find_option() will throw errors on failure. If it has been left out, or is 0 (zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.

Returns

Returns the value the option has been set to if any.

If the option is present, but has not been set to anything 1 will be returned.

Otherwise if any of the environment variables specified in envvars has been set, that value will be returned.

If all else fails, def will be returned.

Throws

If an option that requires an argument lacks an argument and throw_errors is set an error will be thrown.

Note

find_option() modifies argv. Parsed options will be removed from argv. Elements of argv that have been removed entirely will be replaced with zeroes.

This function reads options even if they are written after the first non-option on the line.

Index 0 (zero) of argv is not scanned for options, since it is reserved for the program name.

Only the first ocurrance of an option will be parsed. To parse multiple ocurrances, call find_option() multiple times.

See also

Getopt.get_args()


Methodget_args

array(string) get_args(array(string|zero) argv, void|int(-1..1)posix_me_harder, void|intthrow_errors)

Description

This function returns the remaining command line arguments after you have run find_option() or find_all_options() to find all the options in the argument list. If there are any options left not handled by find_option() or find_all_options() this function will fail.

If throw_errors has been specified get_args() will throw errors on failure. If it has been left out, or is 0 (zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.

Returns

On success a new argv array without the parsed options is returned.

See also

Getopt.find_option(), Getopt.find_all_options()

Module Git

Description

This is a module for interacting with the Git distributed version control system.


ConstantMODE_DIR

constantint Git.MODE_DIR

Description

A subdirectory.


ConstantMODE_EXE

constantint Git.MODE_EXE

Description

A normal, but executable file.


ConstantMODE_FILE

constantint Git.MODE_FILE

Description

A normal (non-executable) file.


ConstantMODE_GITLINK

constantint Git.MODE_GITLINK

Description

A gitlink (aka submodule reference).


ConstantMODE_SYMLINK

constantint Git.MODE_SYMLINK

Description

A symbolic link.


ConstantNULL_SHA1

constantstring Git.NULL_SHA1

Description

The NULL SHA1.


Variablegit_binary

string Git.git_binary

Description

The git binary to use.

Defaults to "git", but may be overridden to select a different binary.


Methodgit

stringgit(string|zerogit_dir, stringcommand, string ... args)

Description

Run a git command, and get the output.

Parameter git_dir

Directory containing the Git repository. May be UNDEFINED to specify the Git repository for the current directory.

Parameter command

Git subcommand to execute.

Parameter args

Arguemnts for command.

Returns

Returns the output on stdout from running the command on success, and throws an error on failure.

See also

try_git(), low_git()


Methodhash_blob

stringhash_blob(stringdata)

Description

Hash algorithm for blobs that is compatible with git.


Methodlow_git

Process.Processlow_git(mapping(string:mixed) options, string|zerogit_dir, stringcommand, string ... args)

Description

Start a git process.

Parameter options

Options for Process.Process().

Parameter git_dir

Directory containing the Git repository. May be UNDEFINED to specify the Git repository for the current directory.

Parameter command

Git subcommand to execute.

Parameter args

Arguemnts for command.

Returns

Returns the corresponding Process.Process object.

See also

git(), try_git()


Methodtry_git

string|zerotry_git(stringgit_dir, stringcommand, string ... args)

Description

Attempt to run a git command and get its output.

Parameter git_dir

Directory containing the Git repository. May be UNDEFINED to specify the Git repository for the current directory.

Parameter command

Git subcommand to execute.

Parameter args

Arguemnts for command.

Returns

Returns the output on stdout from running the command on success, and 0 (zero) on failure.

Note

This is a convenience function, and there is no way to get the specific cause for failures other than rerunning the command with e.g. git().

See also

git(), low_git()

Class Git.Export

Description

Framework for creating a command-stream suitable for git-fast-import.


Methodblob

voidblob(stringblob, string|voidmarker)

Description

Upload data.

Parameter blob

Data to upload.

Parameter marker

Optional export marker for referring to the data.


Methodcat_blob

voidcat_blob(stringdataref)

Description

Output a blob on the cat-blob-fd.

Parameter dataref

Reference to the blob to output.


Methodcheckpoint

voidcheckpoint()

Description

Flush state to disk.


Methodcommand

voidcommand(sprintf_formatcmd, sprintf_args ... args)

Description

Send a raw command.


Methodcommit

voidcommit(stringref, string|voidcommit_marker, string|voidauthor_info, stringcommitter_info, stringmessage, string|void ... parents)

Description

Create a new commit on a branch.

Parameter ref

Reference to add the commit to. Typically "refs/heads/" followed by a branchname, or "refs/notes/commits".

Parameter commit_marker

Optional export marker for referring to the new commit.

Parameter author_info

Optional author information. Defaults to committer_info.

Parameter committer_info

Name, email and timestamp for the committer. See format_author() for details.

Parameter message

Commit message.

Parameter parents

The ordered set of parents for the commit. Defaults to the current HEAD for ref, if it exists, and to the empty set otherwise.

The set of files for the commit defaults to the set for the first of the parents, and can be modified with filemodify, filedelete, filecopy, filerename, filedeleteall and notemodify.


Methodcreate

Git.ExportGit.Export()
Git.ExportGit.Export(Stdio.Filefd)
Git.ExportGit.Export(stringgit_dir)

Description

Create a new fast-import command-stream.

Parameter fd

File to write the command-stream to.

Parameter git_dir

Git directory to modify. If the directory doesn't exist, it will be created empty. A git-fast-import session will be started for the directory to receive the command-stream.

If neither fd nor git_dir has been specified, the command stream will be output to Stdio.stdout.

Parameter verbosity

The amount of verbosity on Stdio.stderr for various commands.


Methoddone

intdone()

Description

End the command-stream and wait for completion.


Methodexport

voidexport(stringfile_name, string|voidgit_name)

Description

Convenience funtion for exporting a filesystem file or directory (recursively) to git.

Parameter file_name

Name of the file on disc.

Parameter git_name

Name of the file in git. Defaults to file_name.


Methodfeature

voidfeature(stringfeature, string|voidarg)

Description

Require that the backend for the stream supports a certian feature.

Parameter feature

Feature to require support for. Typically one of:

"date-format"

Same as the corresponding command-line option.

"export-marks"
"relative-marks"
"no-relative-marks"
"force"
"import-marks"
"import-marks-if-exists"
"cat-blob"

Require the cat_blob and ls commands to be supported.

"ls"
"notes"

Require that the backend supports the notemodify subcommand.

"done"

Require the stream to terminate with a done command.


Methodfilecopy

voidfilecopy(stringfrom, stringto)

Description

Copy a file or directory.


Methodfiledelete

voidfiledelete(stringpath)

Description

Delete a file.


Methodfiledeleteall

voidfiledeleteall()

Description

Delete all files.

Used to start a commit from a clean slate.


Methodfilemodify

voidfilemodify(intmode, stringpath, string|voiddataref)

Description

Create or modify a file.

Parameter mode

Mode for the file. See the MODE_* constants.

Parameter path

Path to the file relative to the repository root.

Parameter dataref

Reference to the data for the file. One of:

string

A mark reference set by a prior blob command or a full 40-byte SHA-1 of an existing Git blob.

zero

Left out, UNDEFINED or "inline" in which case the filemodify command must be followed by a data command.


Methodfilerename

voidfilerename(stringfrom, stringto)

Description

Rename a file or directory.


Methodls

voidls(stringpath, string|voiddataref)

Description

Output a file to the cat-blob-fd.

Parameter path

Path to the file to output.

Parameter dataref

Marker, tag, commit or tree for the root. Defaults to the commit in progress.


Methodnotemodify

voidnotemodify(stringcommit, string|voiddataref)

Description

Annotate a commit.

Parameter commit

Commit to annotate.

Parameter dataref

Reference to the data for the annotation. One of:

string

A mark reference set by a prior blob command or a full 40-byte SHA-1 of an existing Git blob.

zero

Left out, UNDEFINED or "inline" in which case the notemodify command must be followed by a data command.

Note that this command is typically only used when a commit on a ref under "refs/notes/" is active.


Methodoption

voidoption(stringoption)

Description

Set backend options.


Methodprogress

voidprogress(stringmessage)

Description

Output a progress message.

Parameter message

Message to output.

Note

Note that each line of the message will be prefixed with "progress ".


Methodreset

voidreset(stringref, string|voidcommittish)

Description

Move a reference.

Parameter ref

Reference to move.

Parameter committish

Commit to reference.

This command can also be used to make light-weight tags.

See also

tag


Methodtag

voidtag(stringname, stringcommittish, stringtagger_info, stringmessage)

Description

Create an annotated tag referring to a specific commit.

Parameter name

Tag name. Note that it is automatically prefixed with "refs/tags/".

Parameter committish

Commit to tag.

Parameter tagger_info

Name, email and timestamp for the tagger. See format_author() for details.

Parameter message

Message for the tag.

See also

reset

Module Gmp

Description

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. http://www.swox.com/gmp/


Constantversion

constant Gmp.version

Description

The version of the current GMP library, e.g. "6.1.0".


Methodfac

Gmp.mpzfac(intx)

Description

Returns the factorial of x (x!).

Class Gmp.bignum

Description

This program is used by the internal auto-bignum conversion. It can be used to explicitly type integers that are too big to be INT_TYPE. Best is however to not use this program unless you really know what you are doing.

Due to the auto-bignum conversion, all integers can be treated as Gmp.mpz objects insofar as that they can be indexed with the functions in the Gmp.mpz class. For instance, to calculate the greatest common divisor between 51 and 85, you can do 51->gcd(85). In other words, all the functions in Gmp.mpz are also available here.

Class Gmp.mpf

Description

GMP floating point number.

The mantissa of each float has a user-selectable precision, limited only by available memory. Each variable has its own precision, and that can be increased or decreased at any time.

The exponent of each float is a fixed precision, one machine word on most systems. In the current implementation the exponent is a count of limbs, so for example on a 32-bit system this means a range of roughly 2^-68719476768 to 2^68719476736, or on a 64-bit system this will be greater.

Each variable keeps a size for the mantissa data actually in use. This means that if a float is exactly represented in only a few bits then only those bits will be used in a calculation, even if the selected precision is high.

All calculations are performed to the precision of the destination variable. Each function is defined to calculate with "infinite precision" followed by a truncation to the destination precision, but of course the work done is only what's needed to determine a result under that definition.

The precision selected for a variable is a minimum value, GMP may increase it a little to facilitate efficient calculation. Currently this means rounding up to a whole limb, and then sometimes having a further partial limb, depending on the high limb of the mantissa. But applications shouldn't be concerned by such details.

The mantissa in stored in binary, as might be imagined from the fact precisions are expressed in bits. One consequence of this is that decimal fractions like 0.1 cannot be represented exactly. The same is true of plain IEEE double floats. This makes both highly unsuitable for calculations involving money or other values that should be exact decimal fractions. (Suitably scaled integers, or perhaps rationals, are better choices.)

mpf functions and variables have no special notion of infinity or not-a-number, and applications must take care not to overflow the exponent or results will be unpredictable. This might change in a future release.

Note that the mpf functions are not intended as a smooth extension to IEEE P754 arithmetic. In particular results obtained on one computer often differ from the results on a computer with a different word size.

Note

This class will use mpfr if available, in which case the precision will be exact and IEEE rules will be followed.


Variablecatalan

mpf Gmp.mpf.catalan


Variableeuler

mpf Gmp.mpf.euler


Variableln2

mpf Gmp.mpf.ln2


Variablepi

mpf Gmp.mpf.pi


Method__hash

inthash_value(Gmp.mpfarg)


Method_is_type

bool res = is_type(Gmp.mpf())

Description

The Gmp.mpf object will claim to be a "float".

FIXME

Perhaps it should also return true for "object"?


Method_sprintf

stringsprintf(stringformat, ... Gmp.mpfarg ... )


Method`!

bool res = !Gmp.mpf()


Method`*

Gmp.mpf res = Gmp.mpf() * a


Method`+

Gmp.mpf res = Gmp.mpf() + a


Method`+=

Gmp.mpf() += a


Method`-

Gmp.mpf res = Gmp.mpf() - a


Method`/

Gmp.mpf res = Gmp.mpf() / a


Method`<

bool res = Gmp.mpf() < q


Method`==

bool res = Gmp.mpf() == q


Method`>

bool res = Gmp.mpf() > q


Method``*

Gmp.mpf res = a * Gmp.mpf()


Method``+

Gmp.mpf res = a + Gmp.mpf()


Method``-

Gmp.mpf res = sv - Gmp.mpf()


Method``/

Gmp.mpf res = sv / Gmp.mpf()


Method`~

Gmp.mpf res = ~Gmp.mpf()


Methodcast

(string)Gmp.mpf()
(int)Gmp.mpf()
(float)Gmp.mpf()


Methodceil

mpfceil()


Methodcreate

Gmp.mpfGmp.mpf(void|int|string|float|objectx, void|int(0..)precision)
Gmp.mpfGmp.mpf(stringx, int(0..)precision, int(2..36)base)


Methodexp

mpfexp()


Methodexp10

mpfexp10()


Methodexp2

mpfexp2()


Methodfloor

mpffloor()


Methodfrac

mpffrac()


Methodget_float

floatget_float()

Description

Returns the value of the object as a float.


Methodget_int

int|objectget_int()


Methodget_precision

int(0..)get_precision()

Description

Returns the current precision, in bits.


Methodget_string

stringget_string()


Methodlog

mpflog()


Methodlog10

mpflog10()


Methodlog2

mpflog2()


Methodpow

mpf res = pow([Gmp.mpf]a, b) or
mpfpow(int|float|Gmp.mpz|Gmp.mpfexp)


Methodrint

mpfrint()


Methodround

mpfround()


Methodset_precision

Gmp.mpfset_precision(int(0..)prec)

Description

Sets the precision of the current object to be at least prec bits. The precision is limited to 128Kb. The current object will be returned.


Methodsgn

intsgn()


Methodsqr

mpfsqr()


Methodsqrt

mpf res = sqrt([Gmp.mpf]a) or
mpfsqrt()


Methodtrunc

mpftrunc()

Class Gmp.mpq

Description

Rational number stored in canonical form. The canonical from means that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1. All functions canonicalize their result.


Method__hash

inthash_value(Gmp.mpqarg)


Method_is_type

bool res = is_type(Gmp.mpq())


Method_sprintf

stringsprintf(stringformat, ... Gmp.mpqarg ... )


Method`!

bool res = !Gmp.mpq()


Method`%

Gmp.mpq res = Gmp.mpq() % a

Description

a%b =  a -  floor(a/b)*b 


Method`*

Gmp.mpq res = Gmp.mpq() * a


Method`+

Gmp.mpq res = Gmp.mpq() + a


Method`+=

Gmp.mpq() += a


Method`-

Gmp.mpq res = Gmp.mpq() - a


Method`/

Gmp.mpq res = Gmp.mpq() / a


Method`<

bool res = Gmp.mpq() < q


Method`==

bool res = Gmp.mpq() == q


Method`>

bool res = Gmp.mpq() > q


Method``%

Gmp.mpq res = a % Gmp.mpq()


Method``*

Gmp.mpq res = a * Gmp.mpq()


Method``+

Gmp.mpq res = a + Gmp.mpq()


Method``-

Gmp.mpq res = sv - Gmp.mpq()


Method``/

Gmp.mpq res = sv / Gmp.mpq()


Method`~

Gmp.mpq res = ~Gmp.mpq()

Description

Defined as -1-x.


Methodcast

(int)Gmp.mpq()
(string)Gmp.mpq()
(float)Gmp.mpq()

Description

Casting to a string returns the number in the decimal fraction format, where both decimal point and quotient is included only if required. I.e. it is the same as calling get_string with 1 as argument.


Methodcreate

Gmp.mpqGmp.mpq(void|string|int|float|Gmp.mpz|Gmp.mpqx)
Gmp.mpqGmp.mpq(int|Gmp.mpznumerator, int|Gmp.mpzdenominator)
Gmp.mpqGmp.mpq(stringx, intbase)


Methodden

intden()

Description

Returns the denominator. It is always positive.


Methodget_float

floatget_float()


Methodget_int

intget_int()


Methodget_string

stringget_string(void|intdecimal_fraction)

Description

If decimal_fraction is zero or left out, the number is returned as a string on the form "numerator/denominator", where both parts are decimal integers. The numerator may be negative, but the denominator is always positive.

If decimal_fraction is set, then the number is returned as a (possibly negative) decimal fraction, i.e. a decimal number with a decimal point somewhere inside. There is always at least one digit before and after the decimal point.

If the number can be accurately described that way, i.e. without an infinite number of decimals, then no denominator is included. Otherwise the remaining denominator is added to the decimal fraction after a "/". For example, 4711/100 is returned as "47.11", 4711/200 as "23.555", and 4711/300 as "47.11/3".

If decimal_fraction is 1 then the decimal fraction contains a '.' only if there are decimals in it. If it is 2 or higher then the decimal fraction always contains a '.' with at least one digit before and after it.

Note

In any case, there are no unnecessary padding zeroes at the beginning or end of any decimal number.


Methodinvert

Gmp.mpqinvert()


Methodnum

intnum()

Description

Returns the numerator.


Methodsgn

int(-1..1)sgn()

Class Gmp.mpz

Description

Gmp.mpz implements very large integers. In fact, the only limitation on these integers is the available memory. The mpz object implements all the normal integer operations.

Note that the auto-bignum feature also makes these operations available "in" normal integers. For instance, to calculate the greatest common divisor between 51 and 85, you can do 51->gcd(85).


Method__hash

inthash_value(Gmp.mpzarg)

Description

Calculate a hash of the value.

Note

Prior to Pike 7.8.359 this function returned the low 32-bits as an unsigned integer. This could in some common cases lead to very unbalanced mappings.

See also

hash_value()


Method_decode

Gmp.mpzdecode_value(string(8bit)data)


Method_encode

string(8bit)encode_value(Gmp.mpzdata)


Method_random

Gmp.mpzrandom(Gmp.mpzarg)


Method_sprintf

stringsprintf(stringformat, ... Gmp.mpzarg ... )


Method`!

bool res = !Gmp.mpz()


Method`%

Gmp.mpz res = Gmp.mpz() % x


Method`&

Gmp.mpz res = Gmp.mpz() & x


Method`*

Gmp.mpz res = Gmp.mpz() * x


Method`+

Gmp.mpz res = Gmp.mpz() + x


Method`-

Gmp.mpz res = Gmp.mpz() - x


Method`/

Gmp.mpz res = Gmp.mpz() / x


Method`<

bool res = Gmp.mpz() < with


Method`<<

Gmp.mpz res = Gmp.mpz() << x


Method`==

bool res = Gmp.mpz() == with


Method`>

bool res = Gmp.mpz() > with


Method`>>

Gmp.mpz res = Gmp.mpz() >> x


Method`^

Gmp.mpz res = Gmp.mpz() ^ x


Method``%

Gmp.mpz res = x % Gmp.mpz()


Method``*

Gmp.mpz res = x * Gmp.mpz()


Method``**

Gmp.mpz|Gmp.mpq res = x ** Gmp.mpz()

Description

Return x raised to the value of this object. The case when zero is raised to zero yields one. When this object has a negative value and x is not a float, a Gmp.mpq object will be returned.

See also

pow


Method``+

Gmp.mpz res = x + Gmp.mpz()


Method``-

Gmp.mpz res = x - Gmp.mpz()


Method``/

Gmp.mpz res = x / Gmp.mpz()


Method``<<

Gmp.mpz res = x << Gmp.mpz()


Method``>>

Gmp.mpz res = x >> Gmp.mpz()


Method`|

Gmp.mpz res = Gmp.mpz() | x


Method`~

Gmp.mpz res = ~Gmp.mpz()


Methodbin

Gmp.mpzbin(intk)

Description

Return the binomial coefficient n over k, where n is the value of this mpz object. Negative values of n are supported using the identity

(-n)->bin(k) == (-1)->pow(k)*(n+k-1)->bin(k)

(See Knuth volume 1, section 1.2.6 part G.)

Throws

The k value can't be arbitrarily large. An error is thrown if it's too large.


Methodcast

(string)Gmp.mpz()
(int)Gmp.mpz()
(float)Gmp.mpz()

Description

Cast this mpz object to another type. Allowed types are string, int and float.


Methodcreate

Gmp.mpzGmp.mpz()
Gmp.mpzGmp.mpz(string|int|float|objectvalue)
Gmp.mpzGmp.mpz(stringvalue, int(2..62)|int(256)|int(-256)base)

Description

Create and initialize a Gmp.mpz object.

Parameter value

Initial value. If no value is specified, the object will be initialized to zero.

Parameter base

Base the value is specified in. The default base is base 10. The base can be either a value in the range [2..36] (inclusive), in which case the numbers are taken from the ASCII range 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ (case-insensitive), in the range [37..62] (inclusive), in which case the ASCII range will be case sensitive, or either of the values 256 or -256, in which case value is taken to be the unsigned binary representation in network byte order or reversed byte order respectively.

Values in base [2..62] can be prefixed with "+" or "-". If no base is given, values prefixed with "0b" or "0B" will be interpreted as binary. Values prefixed with "0x" or "0X" will be interpreted as hexadecimal. Values prefixed with "0" will be interpreted as octal.

Note

Leading zeroes in value are not significant when a base is explicitly given. In particular leading NUL characters are not preserved in the base 256 modes.

Before GMP 5.0 only bases 2-36 and 256 were supported.


Methoddigits

stringdigits(void|int(2..62)|int(256)|int(-256)base)

Description

Convert this mpz object to a string. If a base is given the number will be represented in that base. Valid bases are 2-62 and 256 and -256. The default base is 10.

Note

The bases 37 to 62 are not available when compiled with GMP earlier than version 5.

See also

cast


Methodencode_json

stringencode_json()


Methodfac

Gmp.mpzfac()

Description

Return the factorial of this mpz object.

Throws

Since factorials grow very quickly, only small integers are supported. An error is thrown if the value in this mpz object is too large.


Methodgcd

Gmp.mpzgcd(object|int|float|string ... args)

Description

Return the greatest common divisor between this mpz object and all the arguments.


Methodgcdext

array(Gmp.mpz) gcdext(int|float|Gmp.mpzx)

Description

Compute the greatest common divisor between this mpz object and x. An array ({g,s,t}) is returned where g is the greatest common divisor, and s and t are the coefficients that satisfies

this * s + x * t = g
See also

gcdext2, gcd


Methodgcdext2

array(Gmp.mpz) gcdext2(int|float|Gmp.mpzx)

Description

Compute the greatest common divisor between this mpz object and x. An array ({g,s}) is returned where g is the greatest common divisor, and s is a coefficient that satisfies

this * s + x * t = g

where t is some integer value.

See also

gcdext, gcd


Methodhamdist

inthamdist(intx)

Description

Calculates the hamming distance between this number and x.


Methodinvert

Gmp.mpzinvert(int|float|Gmp.mpzx)

Description

Return the inverse of this mpz value modulo x. The returned value satisfies 0 <= result < x.

Throws

An error is thrown if no inverse exists.


Methodnext_prime

Gmp.mpznext_prime()

Description

Returns the next higher prime for positive numbers and the next lower for negative.

The prime number testing is using Donald Knuth's probabilistic primality test. The chance for a false positive is pow(0.25,25).


Methodpopcount

intpopcount()

Description

For values >= 0, returns the population count (the number of set bits). For negative values (who have an infinite number of leading ones in a binary representation), -1 is returned.


Methodpow

Gmp.mpz res = pow([Gmp.mpz]a, b) or
Gmp.mpzpow(int|float|Gmp.mpzx)

Description

Return this mpz object raised to x. The case when zero is raised to zero yields one.

See also

powm


Methodpowm

Gmp.mpzpowm(int|string|float|Gmp.mpzexp, int|string|float|Gmp.mpzmod)

Description

Return ( this->pow(exp) ) % mod.

See also

pow


Methodprobably_prime_p

int(0..2)probably_prime_p(void|intcount)

Description

Return 2 if this mpz object is a prime, 1 if it probably is a prime, and 0 if it definitely is not a prime. Testing values below 1000000 will only return 2 or 0.

Parameter count

The prime number testing is using Donald Knuth's probabilistic primality test. The chance for a false positive is pow(0.25,count). Default value is 25 and resonable values are between 15 and 50.


Methodsgn

intsgn()

Description

Return the sign of the integer, i.e. 1 for positive numbers and -1 for negative numbers.


Methodsize

int(0..)size(void|intbase)

Description

Return how long this mpz would be represented in the specified base. The default base is 2.


Methodsmall_factor

intsmall_factor(void|int(1..)limit)


Methodsqrt

Gmp.mpz res = sqrt([Gmp.mpz]a) or
Gmp.mpzsqrt()

Description

Return the the truncated integer part of the square root of this mpz object.


Methodsqrtrem

array(Gmp.mpz) sqrtrem()

Module Gnome2

Module Graphics

Module Graphics.Graph


Inheritcreate_pie

protected inherit .create_pie : create_pie


Methodpie
Methodbars
Methodsumbars
Methodline
Methodnorm
Methodgraph

Image.Imagepie(mapping(string:mixed) diagram_data)
Image.Imagebars(mapping(string:mixed) diagram_data)
Image.Imagesumbars(mapping(string:mixed) diagram_data)
Image.Imageline(mapping(string:mixed) diagram_data)
Image.Imagenorm(mapping(string:mixed) diagram_data)
Image.Imagegraph(mapping(string:mixed) diagram_data)

Description

Generate a graph of the specified type. See check_mapping for an explanation of diagram_data.


Methodcheck_mapping

mapping(string:mixed) check_mapping(mapping(string:mixed) diagram_data, stringtype)

Description

This function sets all unset elements in diagram_data to its default value as well as performing some simple sanity checks. This function is called from within pie, bars, sumbars, line, norm and graph.

Parameter diagram_data
"drawtype" : mixed

Default: "linear"

Will be set to "2D" for pie below Only "linear" works for now.

"tone" : mixed

Default: 0

If present a Pie-chart will be toned.

"3Ddepth" : mixed

Default: 10

How much 3D-depth a graph will have in pixels Default is 10.

"data" : array(array(float))

Default: ({({1.0}), ({2.0}), ({4.0})})

Will be set to something else with graph An array of arrays. Each array describing a data-set. The graph-function however should be fed with an array of arrays with X,Y-pairs. Example: ({({1.0, 2.0, 3.0}),({1.2, 2.2, 3.8})}) draws stuff in yellow with the values (1.0, 2.0, 3.0), and (1.2, 2.2, 3.8) in blue.

"labels" : array(string)

Default: 0

Should have four elements ({xquantity, yquantity, xunit, yunit}). The strings will be written on the axes.

"xnames" : array(string)

Default: 0

An array(string) with the text that will be written under the X-axis. This should be the same size as sizeof(data).

"ynames" : array(string)

Default: 0

An array(string) with the text that will be written to the left of the Y-axis.

"fontsize" : mixed

Default: 10

The size of the text. Default is 10.

"graphlinewidth" : mixed

Default: 1.0

Width of the lines that draws data in Graph and line. Default is 1.0

"labelsize" : mixed

Default: same as fontsize

The size of the text for labels.

"legendfontsize" : mixed

Default: same as fontsize

The size of the text for the legend.

"legend_texts" : mixed

Default: 0

The texts that will be written the legend.

"values_for_xnames" : array(float)

Default: 0

An array(float) that describes where the ynames should be placed. The numbers are like the data-numbers. Default is equally distributed.

"values_for_ynames" : array(float)

Default: 0

An array(float) that describes where the ynames should be placed. The numbers are like the data-numbers. Default is equally distributed.

"xsize" : int

Default: 100

X-size of the graph in pixels.

"ysize" : int

Default: 100

Y-size of the graph in pixels.

"image" : mixed

Default: 0

An image that the graph will be drawn on.

"legendcolor" : mixed

Default: 0

The color of the text in the legend. Default is?

"legendimage" : mixed

Default: 0

I have no idea.

"bgcolor" : mixed

Default: 0

The bakground-color. If the the background is a image this color is used for antialias the texts.

"gbimage" : mixed

Default: 0

Some sort of image...

"axcolor" : mixed

Default: ({0,0,0})

The color of the axis.

"datacolors" : mixed

Default: 0

An array of colors for the datasets.

"backdatacolors" : mixed

Default: 0

An array of color that do something...

"textcolor" : mixed

Default: ({0,0,0})

Color of the text. Default is black.

"labelcolor" : mixed

Default: 0

Color of the labeltexts.

"orient" : string

Default: "hor"

Can be "hor" or "vert". Orientation of the graph.

"linewidth" : mixed

Default: 0

Width of lines (the axis and their like).

"backlinewidth" : mixed

Default: 0

Width of the outline-lines. Default is 0.

"vertgrid" : mixed

Default: 0

If the vertical grid should be present.

"horgrid" : mixed

Default: 0

If the horizontal grid should be present.

"gridwidth" : mixed

Default: 0

Width of the grid. Default is linewidth/4.

"rotate" : mixed

Default: 0

How much a the Pie in a Pie-shart should be rotated in degrees.

"center" : mixed

Default: 0

Makes the first Pie-slice be centered.

"bw" : mixed

Default: 0

Draws the graph black and white.

"eng" : mixed

Default: 0

Writes the numbers in eng format.

"neng" : mixed

Default: 0

Writes the numbers in engformat except for 0.1 < x < 1.0

"xmin" : mixed

Default: 0

Where the X-axis should start. This will be overrided by datavalues.

"ymin" : mixed

Default: 0

Where the Y-axis should start. This will be overridden by datavalues.

"name" : mixed

Default: 0

A string with the name of the graph that will be written at top of the graph.

"namecolor" : mixed

Default: 0

The color of the name.

"font" : mixed

Default: Image.Font()

The font that will be used.

"gridcolor" : mixed

Default: ({0,0,0}

The color of the grid. Default is black.

Class Graphics.Graph.create_bars

Description

Graph sub-module for drawing bars.


Inheritcreate_graph

inherit .create_graph : create_graph

Class Graphics.Graph.create_graph

Description

Graph sub-module for drawing graphs.

create_graph draws a graph but there are also some other functions used by create_pie and create_bars.


Inheritpolyline

inherit .polyline : polyline

Class Graphics.Graph.create_pie

Description

Graph sub-module for drawing pie-charts.


Inheritcreate_bars

inherit .create_bars : create_bars

Class Graphics.Graph.polyline

Description

Graph sub-module providing draw functions.

Module HTTPAccept

Description

High performance webserver optimized for somewhat static content.

HTTPAccept is a less capable WWW-server than the Protocols.HTTP.Server server, but for some applications it can be preferable. It is significantly more optimized, for most uses, and can handle a very high number of requests per second on even low end machines.

Class HTTPAccept.LogEntry


Variablefrom

string HTTPAccept.LogEntry.from


Variablemethod

string HTTPAccept.LogEntry.method


Variableprotocol

string HTTPAccept.LogEntry.protocol


Variableraw

string HTTPAccept.LogEntry.raw


Variablereceived_bytes

int HTTPAccept.LogEntry.received_bytes


Variablereply

int HTTPAccept.LogEntry.reply


Variablesent_bytes

int HTTPAccept.LogEntry.sent_bytes


Variabletime

int HTTPAccept.LogEntry.time


Variableurl

string HTTPAccept.LogEntry.url

Class HTTPAccept.Loop


Methodcache_status

mapping(string:int) cache_status()

Description

Returns information about the cache.

hits : int

The number of hits since start

misses : int

The number of misses since start

stale : int

The number of misses that were stale hits, and not used

size : int

The total current size

entries : int

The number of entries in the cache

max_size : int

The maximum size of the cache

sent_bytes : int

The number of bytes sent since the last call to cache_status

received_bytes : int

The number of bytes received since the last call to cache_status

num_requests : int

The number of requests received since the last call to cache_status


Methodcreate

HTTPAccept.LoopHTTPAccept.Loop(Stdio.Portport, RequestProgramprogram, function(RequestProgram:void) request_handler, intcache_size, boolkeep_log, inttimeout)

Description

Create a new HTTPAccept.

This will start a new thread that will listen for requests on the port, parse them and pass on requests, instanced from the program class (which has to inherit RequestProgram to the request_handler callback function.

cache_size is the maximum size of the cache, in bytes. keep_log indicates if a log of all requests should be kept. timeout if non-zero indicates a maximum time the server will wait for requests.


Methodlog_as_array

array(LogEntry) log_as_array()

Description

Return the current log as an array of LogEntry objects.


Methodlog_as_commonlog_to_file

intlog_as_commonlog_to_file(Stdio.Streamfd)

Description

Write the current log to the specified file in a somewhat common commonlog format.

Will return the number of bytes written.


Methodlog_size

intlog_size()

Description

Returns the number of entries waiting to be logged.


Methodlogp

boollogp()

Description

Returns true if logging is enabled

Class HTTPAccept.RequestProgram


Variableclient

string HTTPAccept.RequestProgram.client

Description

The user agent


Variabledata

string HTTPAccept.RequestProgram.data

Description

Any payload that arrived with the request


Variableheaders

mapping(string:array(string)) HTTPAccept.RequestProgram.headers

Description

All received headers


Variablemethod

string HTTPAccept.RequestProgram.method

Description

The method (GET, PUT etc)


Variablemy_fd

Stdio.NonblockingStream HTTPAccept.RequestProgram.my_fd

Description

The filedescriptor for this request.


Variablenot_query

string HTTPAccept.RequestProgram.not_query

Description

The part of the URL before the first '?'.


Variablepragma

multiset(string) HTTPAccept.RequestProgram.pragma

Description

Tokenized pragma headers


Variableprot

string HTTPAccept.RequestProgram.prot

Description

The protocol part of the request. As an example "HTTP/1.1"


Variablequery

string HTTPAccept.RequestProgram.query

Description

The part of the URL after the first '?'


Variableraw

string HTTPAccept.RequestProgram.raw

Description

The full request


Variableraw_url

string HTTPAccept.RequestProgram.raw_url

Description

The raw URL received, the part after the method and before the protocol.


Variablereferer

string HTTPAccept.RequestProgram.referer

Description

The referer header


Variableremoteaddr

string HTTPAccept.RequestProgram.remoteaddr

Description

The remote address


Variablerest_query

string HTTPAccept.RequestProgram.rest_query

Description

The part of the URL after the first '?' that does not seem to be query variables.


Variablesince

string HTTPAccept.RequestProgram.since

Description

The get-if-not-modified, if set.


Variabletime

int HTTPAccept.RequestProgram.time

Description

The time_t when the request arrived to the server


Variablevariables

mapping(string:string) HTTPAccept.RequestProgram.variables

Description

Parsed query variables


Methodoutput

voidoutput(stringdata)

Description

Send data directly to the remote side.


Methodreply

voidreply(stringdata)
voidreply(stringheaders, Stdio.Filefd, intlen)
voidreply(int(0)ignore, Stdio.Filefd, intlen)

Description

Send a reply to the remote side. In the first case the data will be sent. In the second case the headers will be sent, then len bytes from fd. In the last case len bytes from fd will be sent.


Methodreply_with_cache

voidreply_with_cache(stringdata, int(1..)stay_time)

Description

Send data as the reply, and keep it as a cache entry to requests to this URL for stay_time seconds.

Module Java


Inherit"___Java"

inherit "___Java" : "___Java"


Variablepkg

object Java.pkg

Description

Singleton 'package' object.

Usage: object cls = Java.pkg.java.lang.String;

or: object cls = Java.pkg["java/lang/String"];

cls is a jclass object; call it to create a jobject, which will have all the methods of the Java class.

Example: Java.pkg.FooClass()->getResult();


MethodJArray

jobjectJArray(arraya)


MethodJBoolean

jobjectJBoolean(inti)


MethodJFloat

jobjectJFloat(floatf)


MethodJHashMap

jobjectJHashMap(mappingm)


MethodJInteger

jobjectJInteger(inti)


MethodJString

jobjectJString(strings)

Class Java.jclass

Description

Interface to one Java class. Can be called to construct a jobject.

Obtained normally via Java.pkg.`[] and not created directly.

Class Java.jobject

Description

An instantiated Java object. Has methods for all the Java object's methods. Can be cast to string.

NOTE: Use indices(x) to get a list of the available methods.

Constructed from a jclass object.

Module Languages

Module Languages.PLIS

Description

PLIS, Permuted Lisp. A Lisp language somewhat similar to scheme.


Methoddefault_environment

Environmentdefault_environment()

Description

Creates a new environment on which it runs init_functions, init_specials and the following boot code.

(begin
  (defmacro (cddr x)
    (list (quote cdr) (list (quote cdr) x)))
  (defmacro (cadr x)
    (list (quote car) (list (quote cdr) x)))
  (defmacro (cdar x)
    (list (quote cdr) (list (quote car) x)))
  (defmacro (caar x)
    (list (quote car) (list (quote car) x)))

  (defmacro (when cond . body)
    (list (quote if) cond
	  (cons (quote begin) body)))

  (define (map fun list)
    (if (null? list) (quote ())
      (cons (fun (car list))
	         (map fun (cdr list)))))

  (defmacro (let decl . body)
    (cons (cons (quote lambda)
		(cons (map car decl) body))
	  (map cadr decl))))

Methodinit_functions

voidinit_functions(Environmentenvironment)

Description

Adds the functions +, *, -, =, <, >, concat, read-string, eval, apply, global-environment, var, cdr, null?, setcar!, setcdr!, cons and list to the environment.


Methodinit_specials

voidinit_specials(Environmentenvironment)

Description

Adds the special functions quote, set!, setq, while, define, defmacro, lambda, if, and, or, begin and catch to the environment.


Methodmain

voidmain()

Description

Instantiates a copy of the default environment and starts an interactive main loop that connects to standard I/O. The main loop is as follows:

(begin
   (define (loop)(let ((line (read-line 

Class Languages.PLIS.Binding


Variablevalue

object Languages.PLIS.Binding.value


Method__create__

protectedlocalvoid__create__(objectvalue)


Methodcreate

Languages.PLIS.BindingLanguages.PLIS.Binding(objectvalue)

Class Languages.PLIS.Builtin


InheritLObject

inherit LObject : LObject


Variableapply

function(:void) Languages.PLIS.Builtin.apply


Method__create__

protectedlocalvoid__create__(function(:void) apply)


Methodcreate

Languages.PLIS.BuiltinLanguages.PLIS.Builtin(function(:void) apply)

Class Languages.PLIS.Lambda


InheritLObject

inherit LObject : LObject


Variableformals
Variablelist

object Languages.PLIS.Lambda.formals
object Languages.PLIS.Lambda.list


Method__create__

protectedlocalvoid__create__(objectformals, objectlist)


Methodcreate

Languages.PLIS.LambdaLanguages.PLIS.Lambda(objectformals, objectlist)

Class Languages.PLIS.Number


InheritSelfEvaluating

inherit SelfEvaluating : SelfEvaluating


Variablevalue

int|float|object Languages.PLIS.Number.value


Method__create__

protectedlocalvoid__create__(int|float|objectvalue)


Methodcreate

Languages.PLIS.NumberLanguages.PLIS.Number(int|float|objectvalue)

Class Languages.PLIS.Parser


Variablebuffer

string Languages.PLIS.Parser.buffer


Method__create__

protectedlocalvoid__create__(stringbuffer)


Methodcreate

Languages.PLIS.ParserLanguages.PLIS.Parser(stringbuffer)

Class Languages.PLIS.SelfEvaluating


InheritLObject

inherit LObject : LObject


Variablename

string Languages.PLIS.SelfEvaluating.name


Method__create__

protectedlocalvoid__create__(stringname)


Methodcreate

Languages.PLIS.SelfEvaluatingLanguages.PLIS.SelfEvaluating(stringname)

Class Languages.PLIS.String


InheritSelfEvaluating

inherit SelfEvaluating : SelfEvaluating


Variablevalue

string Languages.PLIS.String.value


Method__create__

protectedlocalvoid__create__(stringvalue)


Methodcreate

Languages.PLIS.StringLanguages.PLIS.String(stringvalue)

Module Local

Description

Local gives a local module namespace used for locally installed pike modules.

Modules are searched for in the directory pike_modules which can be located in the user's home directory or profile directory, or in any of the system directories /opt/share, /usr/local/share, /opt or /usr/local/.

The user's home directory is determined by examining the environment variable HOME, and if that fails the environment variable USERPROFILE.

If the environment variable PIKE_LOCAL_PATH is set, the paths specified there will be searched first.

Example

If the user has installed the pike module Mine.pmod in the directory $HOME/pike_modules. it can be accessed as Local.Mine.

See also

Local.add_path(), Local.remove_path()


Inherit__joinnode

inherit __joinnode : __joinnode


Methodadd_path

booladd_path(stringpath)

Description

This function prepends path to the Local module searchpath.

Parameter path

The path to the directory to be added.

Returns

Returns 1 on success, otherwise 0.


Methodremove_path

voidremove_path(stringpath)

Description

This function removes path from the Local module searchpath. If path is not in the search path, this is a noop.

Parameter path

The path to be removed.

Module Locale

Description

The functions and classes in the top level of the Locale module implements a dynamic localization system, suitable for programs that need to change locale often. It is even possible for different threads to use different locales at the same time.

The highest level of the locale system is called projects. Usually one program consists of only one project, but for bigger applications, or highly modular applications it is possible for several projects to coexist.

Every project in turn contains several unique tokens, each one representing an entity that is different depending on the currently selected locale.

Example
// The following line tells the locale extractor what to// look for.// <locale-token project="my_project">LOCALE</locale-token>// The localization macro.#define LOCALE(X,Y)Locale.translate("my_project", \
   get_lang(), X, Y)string get_lang(){return random(2)?"eng":"swe";}int(0..0) main(){
   write(LOCALE(0,"This is a line.")+"\n");
   write(LOCALE(0,"This is another one.\n");return 0;}
Note

In order to update your code to actually use the locale strings you need to run the locale extractor.

This is available as pike -x extract_locale

Syntax: pike -x extract_locale [arguments] infile(s)
   Arguments: --project=name  default: first found in infile
              --config=file   default: [project].xml
              --out=file      default: [project]_eng.xml
              --nocopy        update infile instead of infile.new
              --notime        don't include dump time in xml files
              --wipe          remove unused ids from xml
              --sync          synchronize all locale projects
              --encoding=enc  default: ISO-8859-1
              --verbose       more informative text in xml

Methodcall

function(:void)|zerocall(stringproject, stringlang, stringname, void|function(:void)|stringfb)

Description

Returns a localized function If function not found, tries fallback function fb, or fallback language fb instead


Methodget_objects

mapping(string:object)|zeroget_objects(stringlang)

Description

Reads in and returns a mapping with all the registred projects' LocaleObjects in the language 'lang'


Methodlist_languages

array(string) list_languages(stringproject)

Description

Returns a list of all registered languages for a specific project.


Methodregister_project

voidregister_project(stringname, stringpath, void|stringpath_base)

Description

Make a connection between a project name and where its localization files can be found. The mapping from project name to locale file is stored in projects.


Methodset_default_project_path

voidset_default_project_path(stringpath)

Description

In the event that a translation is requested in an unregistered project, this path will be used as the project path. %P will be replaced with the requested projects name.


Methodtranslate

stringtranslate(stringproject, stringlang, string|intid, stringfallback)

Description

Returns a translation for the given id, or the fallback string

Class Locale.DeferredLocale

Description

This class simulates a multi-language "string". The actual language to use is determined as late as possible.


Variableproject
Variableget_lang
Variablekey
Variablefallback

protectedstring Locale.DeferredLocale.project
protectedfunction(:string) Locale.DeferredLocale.get_lang
protectedstring|int Locale.DeferredLocale.key
protectedstring Locale.DeferredLocale.fallback


Method__create__

protectedlocalvoid__create__(stringproject, function(:string) get_lang, string|intkey, stringfallback)


Methodcreate

Locale.DeferredLocaleLocale.DeferredLocale(stringproject, function(:string) get_lang, string|intkey, stringfallback)


Methodget_identifier

arrayget_identifier()

Description

Return the data nessesary to recreate this "string".

Class Locale.LanguageListObject


Variablelanguages

array(string) Locale.LanguageListObject.languages


Method__create__

protectedlocalvoid__create__(array(string) languages)


Methodcreate

Locale.LanguageListObjectLocale.LanguageListObject(array(string) languages)

Module Locale.Charset

Description

This is the old location for the predef::Charset module.

Deprecated

Replaced by predef::Charset.


InheritCharset

inherit predef::Charset : Charset

Module Locale.Gettext

Description

This module enables access to localization functions from within Pike.

Note

The message conversion functions in this module do not handle Unicode strings. They only provide thin wrappers to gettext(3) etc, which means strings are assumed to be encoded according to the LC_* and LANG variables. See the docs for gettext(3) for details.


ConstantLC_ALL

constant Locale.Gettext.LC_ALL

Description

Locale category for all of the locale.

Only supported as an argument to setlocale().


ConstantLC_COLLATE

constant Locale.Gettext.LC_COLLATE

Description

Locale category for the functions strcoll() and strxfrm() (used by pike, but not directly accessible).


ConstantLC_CTYPE

constant Locale.Gettext.LC_CTYPE

Description

Locale category for the character classification and conversion routines.


ConstantLC_MESSAGES

constant Locale.Gettext.LC_MESSAGES

FIXME

Document this constant.


ConstantLC_MONETARY

constant Locale.Gettext.LC_MONETARY

Description

Locale category for localeconv().


ConstantLC_NUMERIC

constant Locale.Gettext.LC_NUMERIC

Description

Locale category for the decimal character.


ConstantLC_TIME

constant Locale.Gettext.LC_TIME

Description

Locale category for strftime() (currently not accessible from Pike).


Methodbindtextdomain

stringbindtextdomain(string|voiddomainname, string|voiddirname)

Description

Binds the path predicate for a message domainname domainname to the directory name specified by dirname.

If domainname is a non-empty string and has not been bound previously, bindtextdomain() binds domainname with dirname.

If domainname is a non-empty string and has been bound previously, bindtextdomain() replaces the old binding with dirname.

The dirname argument can be an absolute or relative pathname being resolved when gettext(), dgettext() or dcgettext() are called.

If domainname is zero or an empty string, bindtextdomain() returns 0.

User defined domain names cannot begin with the string "SYS_". Domain names beginning with this string are reserved for system use.

Returns

The return value from bindtextdomain() is a string containing dirname or the directory binding associated with domainname if dirname is unspecified. If no binding is found, the default locale path is returned. If domainname is unspecified or is an empty string, bindtextdomain() takes no action and returns a 0.

See also

textdomain, gettext, setlocale, localeconv


Methoddcgettext

stringdcgettext(stringdomain, stringmsg, intcategory)

Description

Return a translated version of msg within the context of the specified domain and current locale for the specified category. Calling dcgettext with category Locale.Gettext.LC_MESSAGES gives the same result as dgettext.

If there is no translation available, msg is returned.

Deprecated

Replaced by gettext.

Obsoleted by gettext() in Pike 7.3.

See also

bindtextdomain, textdomain, gettext, setlocale, localeconv


Methoddgettext

stringdgettext(stringdomain, stringmsg)

Description

Return a translated version of msg within the context of the specified domain and current locale. If there is no translation available, msg is returned.

Deprecated

Replaced by gettext.

Obsoleted by gettext() in Pike 7.3.

See also

bindtextdomain, textdomain, gettext, setlocale, localeconv


Methodgettext

stringgettext(stringmsg)
stringgettext(stringmsg, stringdomain)
stringgettext(stringmsg, stringdomain, intcategory)

Parameter msg

Message to be translated.

Parameter domain

Domain from within the message should be translated. Defaults to the current domain.

Parameter category

Category from which the translation should be taken. Defaults to Locale.Gettext.LC_MESSAGES.

Return a translated version of msg within the context of the specified domain and current locale. If there is no translation available, msg is returned.

See also

bindtextdomain, textdomain, setlocale, localeconv


Methodlocaleconv

mappinglocaleconv()

Description

The localeconv() function returns a mapping with settings for the current locale. This mapping contains all values associated with the locale categories LC_NUMERIC and LC_MONETARY.

"decimal_point" : string

The decimal-point character used to format non-monetary quantities.

"thousands_sep" : string

The character used to separate groups of digits to the left of the decimal-point character in formatted non-monetary quantities.

"int_curr_symbol" : string

The international currency symbol applicable to the current locale, left-justified within a four-character space-padded field. The character sequences should match with those specified in ISO 4217 Codes for the Representation of Currency and Funds.

"currency_symbol" : string

The local currency symbol applicable to the current locale.

"mon_decimal_point" : string

The decimal point used to format monetary quantities.

"mon_thousands_sep" : string

The separator for groups of digits to the left of the decimal point in formatted monetary quantities.

"positive_sign" : string

The string used to indicate a non-negative-valued formatted monetary quantity.

"negative_sign" : string

The string used to indicate a negative-valued formatted monetary quantity.

"int_frac_digits" : int

The number of fractional digits (those to the right of the decimal point) to be displayed in an internationally formatted monetary quantity.

"frac_digits" : int

The number of fractional digits (those to the right of the decimal point) to be displayed in a formatted monetary quantity.

"p_cs_precedes" : bool

Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a non-negative formatted monetary quantity.

"p_sep_by_space" : bool

Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a non-negative formatted monetary quantity.

"n_cs_precedes" : bool

Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a negative formatted monetary quantity.

"n_sep_by_space" : bool

Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a negative formatted monetary quantity.

"p_sign_posn" : int(0..4)

Set to a value indicating the positioning of the positive_sign for a non-negative formatted monetary quantity. The value of p_sign_posn is interpreted according to the following:

0

Parentheses surround the quantity and currency_symbol.

1

The sign string precedes the quantity and currency_symbol.

2

The sign string succeeds the quantity and currency_symbol.

3

The sign string immediately precedes the currency_symbol.

4

The sign string immediately succeeds the currency_symbol.

"n_sign_posn" : int

Set to a value indicating the positioning of the negative_sign for a negative formatted monetary quantity. The value of n_sign_posn is interpreted according to the rules described under p_sign_posn.

See also

bindtextdomain, textdomain, gettext, dgettext, dcgettext, setlocale


Methodsetlocale

intsetlocale(intcategory, stringlocale)

Description

The setlocale() function is used to set the program's current locale. If locale is "C" or "POSIX", the current locale is set to the portable locale.

If locale is "", the locale is set to the default locale which is selected from the environment variable LANG.

The argument category determines which functions are influenced by the new locale are LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC and LC_TIME.

Returns

Returns 1 if the locale setting successed, 0 for failure

See also

bindtextdomain, textdomain, gettext, dgettext, dcgettext, localeconv


Methodtextdomain

stringtextdomain(void|stringdomain)

Description

The textdomain() function sets or queries the name of the current domain of the active LC_MESSAGES locale category. The domain argument is a string that can contain only the characters allowed in legal filenames. It must be non-empty.

The domain argument is the unique name of a domain on the system. If there are multiple versions of the same domain on one system, namespace collisions can be avoided by using bindtextdomain(). If textdomain() is not called, a default domain is selected. The setting of domain made by the last valid call to textdomain() remains valid across subsequent calls to setlocale(), and gettext().

Returns

The normal return value from textdomain() is a string containing the current setting of the domain. If domainname is void, textdomain() returns a string containing the current domain. If textdomain() was not previously called and domainname is void, the name of the default domain is returned.

See also

bindtextdomain, gettext, setlocale, localeconv

Module Locale.Language

Class Locale.Language.abstract

Description

Abstract language locale class, inherited by all the language locale classes.


Constantdays

constant Locale.Language.abstract.days

Description

Array(string) with the days of the week, beginning with Sunday.


Constantenglish_name

constantstring Locale.Language.abstract.english_name

Description

The name of the language in english.


Constantiso_639_1

optional constantint Locale.Language.abstract.iso_639_1

Description

String with the language code in ISO-639-1 (two character code). Note that all languages does not have a ISO-639-1 code.


Constantiso_639_2

constantint Locale.Language.abstract.iso_639_2

Description

String with the language code in ISO-639-2/T (three character code).


Constantiso_639_2B

constantint Locale.Language.abstract.iso_639_2B

Description

String with the language code in ISO-639-2/B (three character code). This is usually the same as the ISO-639-2/T code (iso_639_2).


Constantlanguages

constant Locale.Language.abstract.languages

Description

Mapping(string:string) that maps an ISO-639-2/T id code to the name of that language.


Constantmonths

constant Locale.Language.abstract.months

Description

Array(string) with the months of the year, beginning with January.


Constantname

constantstring Locale.Language.abstract.name

Description

The name of the langauge. E.g. "svenska" for Swedish.


Methoddate

stringdate(inttimestamp, string|voidmode)

Description

Returns the date for posix time timestamp as a textual string.

Parameter mode

Determines what kind of textual string should be produced.

"time"

I.e. "06:36"

"date"

I.e. "January the 17th in the year of 2002"

"full"

I.e. "06:37, January the 17th, 2002"

Example

> Locale.Language.eng()->date(time()); Result: "today, 06:36"


Methodday

stringday(int(1..7)num)

Description

Returns the name of weekday number num.


Methodmonth

stringmonth(int(1..12)num)

Description

Returns the name of month number num.


Methodnumber

stringnumber(inti)

Description

Returns the number i as a string.


Methodordered

stringordered(inti)

Description

Returns the ordered number i as a string.


Methodshort_day

stringshort_day(int(1..7)num)

Description

Returns an abbreviated weekday name from the weekday number num.


Methodshort_month

stringshort_month(int(1..12)num)

Description

Returns an abbreviated month name from the month number num.

Module Locale.Language.cat

Description

Catalan language locale.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.ces

Description

Czech language locale by Jan Petrous 16.10.1997, based on Slovenian language module by Iztok Umek.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.deu

Description

German language locale by Tvns Böker.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.eng

Description

English language locale.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.fin

Description

Finnish language locale created by Janne Edelman, Turku Unix Users Group ry, Turku, Finland


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.fra

Description

French language locale by Patrick Kremer.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.hrv

Description

Croatian language locale by Klara Makovac 1997/07/02


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.hun

Description

Hungarian language locale by Zsolt Varga.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.ita

Description

Italian language locale by Francesco Chemolli


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.jpn

Description

Japanese language locale.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.mri

Description

Maaori (New Zealand) language locale by Jason Rumney


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.nld

Description

Dutch language locale by Stephen R. van den Berg


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.nor

Description

Norwegian language locale


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.pol

Description

Polish language locale by Piotr Klaban <makler@man.torun.pl>.


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.por

Description

Portuguese language locale


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.rus

Description

Russian language locale


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.slv

Description

Slovenian language locale by Iztok Umek 7. 8. 1997


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.spa

Description

Spanish language locale


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.srp

Description

Serbian language locale by Goran Opacic 1996/12/11


Inherit"abstract"

inherit "abstract" : "abstract"

Module Locale.Language.swe

Description

Swedish language locale


Inherit"abstract"

inherit "abstract" : "abstract"

Module MIME

Description

RFC 1521, the Multipurpose Internet Mail Extensions memo, defines a structure which is the base for all messages read and written by modern mail and news programs. It is also partly the base for the HTTP protocol. Just like RFC 0822, MIME declares that a message should consist of two entities, the headers and the body. In addition, the following properties are given to these two entities:

Headers
  • A MIME-Version header must be present to signal MIME compatibility

  • A Content-Type header should be present to describe the nature of the data in the message body. Seven major types are defined, and an extensive number of subtypes are available. The header can also contain attributes specific to the type and subtype.

  • A Content-Transfer-Encoding may be present to notify that the data of the body is encoded in some particular encoding.

Body
  • Raw data to be interpreted according to the Content-Type header

  • Can be encoded using one of several Content-Transfer-Encodings to allow transport over non 8bit clean channels

The MIME module can extract and analyze these two entities from a stream of bytes. It can also recreate such a stream from these entities. To encapsulate the headers and body entities, the class MIME.Message is used. An object of this class holds all the headers as a mapping from string to string, and it is possible to obtain the body data in either raw or encoded form as a string. Common attributes such as message type and text char set are also extracted into separate variables for easy access.

The Message class does not make any interpretation of the body data, unless the content type is multipart. A multipart message contains several individual messages separated by boundary strings. The Message->create method of the Message class will divide a multipart body on these boundaries, and then create individual Message objects for each part. These objects will be collected in the array Message->body_parts within the original Message object. If any of the new Message objects have a body of type multipart, the process is of course repeated recursively.


Inherit___MIME

inherit ___MIME : ___MIME


ConstantTOKENIZE_KEEP_ESCAPES

constant MIME.TOKENIZE_KEEP_ESCAPES

Description

Don't unquote backslash-sequences in quoted strings during tokenizing. This is used for bug-compatibility with Microsoft...

See also

tokenize(), tokenize_labled()


Methoddecode

string|StringRangedecode(string|StringRangedata, void|stringencoding)

Description

Extract raw data from an encoded string suitable for transport between systems.

The encoding can be any of

"7bit"
"8bit"
"base64"
"binary"
"quoted-printable"
"x-uue"
"x-uuencode"

The encoding string is not case sensitive.

See also

MIME.encode()


Methoddecode_base32

stringdecode_base32(stringencoded_data)

Description

This function decodes data encoded using the base32 transfer encoding.

See also

MIME.encode_base32(), MIME.decode()


Methoddecode_base32hex

stringdecode_base32hex(stringencoded_data)

Description

Decode strings according to RFC 4648 base32hex encoding.

See also

MIME.decode_base32


Methoddecode_base64

stringdecode_base64(stringencoded_data)

Description

This function decodes data encoded using the base64 transfer encoding.

See also

MIME.encode_base64(), MIME.decode()


Methoddecode_base64url

stringdecode_base64url(stringencoded_data)

Description

Decode strings according to RFC 4648 base64url encoding.

See also

MIME.decode_base64


Methoddecode_crypt64

string(8bit)decode_crypt64(string(7bit)encoded_data)

Description

This function decodes data encoded using the crypt64 encoding.

This is an ad hoc encoding similar to base64 that several password hashing algorithms use for entries in the password database.

Note

This is NOT a MIME-compliant encoding, and MUST NOT be used as such.

See also

MIME.encode_crypt64()


Methoddecode_headerfield_params

array(ADT.OrderedMapping) decode_headerfield_params(strings)

Description

Decodes the given string as a key-value parameter cascade according to e.g. RFC 7239 section 4.

Note

This function will decode all conforming inputs, but it will also be forgiving when presented with non-conforming inputs.

See also

encode_headerfield_params


Methoddecode_qp

stringdecode_qp(stringencoded_data)

Description

This function decodes data encoded using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.

See also

MIME.encode_qp(), MIME.decode()


Methoddecode_uue

stringdecode_uue(stringencoded_data)

Description

This function decodes data encoded using the x-uue transfer encoding. It can also be used to decode generic UUEncoded files.

See also

MIME.encode_uue(), MIME.decode()


Methoddecode_word

array(string) decode_word(stringword)

Description

Extracts the textual content and character set from an encoded word as specified by RFC 1522/RFC 2047. The result is an array where the first element is the raw text, and the second element the name of the character set. If the input string is not an encoded word, the result is still an array, but the char set element will be set to 0.

Note

Note that this function can only be applied to individual encoded words.

See also

MIME.encode_word()


Methoddecode_words_text

array(array(string)) decode_words_text(stringtxt)

Description

Separates a header value containing text into units and calls MIME.decode_word() on them. The result is an array where each element is a result from decode_word().

See also

MIME.decode_words_tokenizedMIME.decode_words_text_remapped


Methoddecode_words_text_remapped

stringdecode_words_text_remapped(stringtxt)

Description

Like MIME.decode_words_text(), but the extracted strings are also remapped from their specified character encoding into UNICODE, and then pasted together. The result is thus a string in the original text format, without RFC 1522 escapes, and with all characters in UNICODE encoding.

See also

MIME.decode_words_tokenized_remapped


Methoddecode_words_tokenized

array(array(string)|int) decode_words_tokenized(stringphrase, int|voidflags)

Description

Tokenizes a header value just like MIME.tokenize(), but also converts encoded words using MIME.decode_word(). The result is an array where each element is either an int representing a special character, or an array as returned by decode_word() representing an atom or a quoted string.

See also

MIME.decode_words_tokenized_labledMIME.decode_words_tokenized_remappedMIME.decode_words_text


Methoddecode_words_tokenized_labled

array(array(string|int|array(array(string)))) decode_words_tokenized_labled(stringphrase, int|voidflags)

Description

Tokenizes and labels a header value just like MIME.tokenize_labled(), but also converts encoded words using MIME.decode_word(). The result is an array where each element is an array of two or more elements, the first being the label. The rest of the array depends on the label:

"special"

One additional element, containing the character code for the special character as an int.

"word"

Two additional elements, the first being the word, and the second being the character set of this word (or 0 if it did not originate from an encoded word).

"domain-literal"

One additional element, containing the domain literal as a string.

"comment"

One additional element, containing an array as returned by MIME.decode_words_text().

See also

MIME.decode_words_tokenized_labled_remapped


Methoddecode_words_tokenized_labled_remapped

array(array(string|int)) decode_words_tokenized_labled_remapped(stringphrase, int|voidflags)

Description

Like MIME.decode_words_tokenized_labled(), but the extracted words are also remapped from their specified character encoding into UNICODE. The result is identical to that of MIME.tokenize_labled(), but without RFC 1522 escapes, and with all characters in UNICODE encoding.


Methoddecode_words_tokenized_remapped

array(string|int) decode_words_tokenized_remapped(stringphrase, int|voidflags)

Description

Like MIME.decode_words_tokenized(), but the extracted atoms are also remapped from their specified character encoding into UNICODE. The result is thus identical to that of MIME.tokenize(), but without RFC 1522 escapes, and with all characters in UNICODE encoding.

See also

MIME.decode_words_tokenized_labled_remappedMIME.decode_words_text_remapped


Methodencode

stringencode(stringdata, void|stringencoding, void|stringfilename, void|intno_linebreaks)

Description

Encode raw data into something suitable for transport to other systems.

The encoding can be any of

"7bit"
"8bit"
"base64"
"binary"
"quoted-printable"
"x-uue"
"x-uuencode"

The encoding string is not case sensitive. For the x-uue encoding, an optional filename string may be supplied.

If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks (base64 and quoted-printable only).

See also

MIME.decode()


Methodencode_base32

stringencode_base32(stringdata, void|intno_linebreaks, void|intno_pad)

Description

Encode strings according to RFC 4648 base32 encoding.

If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks.

See also

MIME.decode_base32(), MIME.encode()


Methodencode_base32hex

stringencode_base32hex(stringdata, void|intno_linebreaks, void|intno_pad)

Description

Encode strings according to RFC 4648 base32hex encoding.

If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks.

See also

MIME.encode_base32hex


Methodencode_base64

stringencode_base64(stringdata, void|intno_linebreaks, void|intno_pad)

Description

This function encodes data using the base64 transfer encoding.

If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks.

See also

MIME.decode_base64(), MIME.encode()


Methodencode_base64url

stringencode_base64url(stringdata, void|intno_linebreaks, void|intno_pad)

Description

Encode strings according to RFC 4648 base64url encoding. No padding is performed and no_linebreaks defaults to true.

See also

MIME.encode_base64


Methodencode_crypt64

stringencode_crypt64(string(8bit)data)

Description

This function encodes data using the crypt64 encoding.

This is an ad hoc encoding similar to base64 that several password hashing algorithms use for entries in the password database.

Note

This is NOT a MIME-compliant encoding, and MUST NOT be used as such.

See also

MIME.decode_crypt64()


Methodencode_headerfield_params

stringencode_headerfield_params(array(mapping|ADT.OrderedMapping) params)

Description

Encodes the given key-value parameters as a string according to e.g. RFC 7239 section 4.

See also

decode_headerfield_params


Methodencode_qp

stringencode_qp(stringdata, void|intno_linebreaks)

Description

This function encodes data using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.

If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks.

Note

Please do not use this function. QP is evil, and there's no excuse for using it.

See also

MIME.decode_qp(), MIME.encode()


Methodencode_uue

string(7bit)encode_uue(string(8bit)encoded_data, void|string(7bit)filename)

Description

This function encodes data using the x-uue transfer encoding.

The optional argument filename specifies an advisory filename to include in the encoded data, for extraction purposes.

This function can also be used to produce generic UUEncoded files.

See also

MIME.decode_uue(), MIME.encode()


Methodencode_word

stringencode_word(string|array(string|zero) word, string|zeroencoding)

Description

Create an encoded word as specified in RFC 1522 from an array containing a raw text string and a char set name.

The text will be transfer encoded according to the encoding argument, which can be either "base64" or "quoted-printable" (or either "b" or "q" for short).

If either the second element of the array (the char set name), or the encoding argument is 0, the raw text is returned as is.

See also

MIME.decode_word()


Methodencode_words_quoted

stringencode_words_quoted(array(array(string)|int) phrase, stringencoding)

Description

The inverse of decode_words_tokenized(), this functions accepts an array like the argument to quote(), but instead of simple strings for atoms and quoted-strings, it will also accept pairs of strings to be passed to encode_word().

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).

See also

MIME.encode_words_quoted_remapped()MIME.encode_words_quoted_labled()


Methodencode_words_quoted_labled

stringencode_words_quoted_labled(array(array(string|int|array(string|array(string)))) phrase, stringencoding)

Description

The inverse of decode_words_tokenized_labled(), this functions accepts an array like the argument to quote_labled(), but "word" labled elements can optionally contain an additional string element specifying a character set, in which case an encoded-word will be used. Also, the format for "comment" labled elements is entirely different; instead of a single string, an array of strings or pairs like the first argument to encode_words_text() is expected.

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).

See also

MIME.encode_words_quoted()MIME.encode_words_quoted_labled_remapped()


Methodencode_words_quoted_labled_remapped

stringencode_words_quoted_labled_remapped(array(array(string|int)) phrase, stringencoding, string|function(string:string) charset, string|voidreplacement, function(string:string)|voidrepcb)

Description

The inverse of decode_words_tokenized_labled_remapped(), this function accepts an array equivalent to the argument of quote_labled(), but also performs on demand word encoding in the same way as encode_words_text_remapped().


Methodencode_words_quoted_remapped

stringencode_words_quoted_remapped(array(string|int) phrase, stringencoding, string|function(string:string) charset, string|voidreplacement, function(string:string)|voidrepcb)

Description

The inverse of decode_words_tokenized_remapped(), this functions accepts an array equivalent to the argument of quote(), but also performs on demand word encoding in the same way as encode_words_text_remapped().

See also

MIME.encode_words_text_remapped()MIME.encode_words_quoted_labled_remapped()


Methodencode_words_text

stringencode_words_text(array(string|array(string)) phrase, stringencoding)

Description

The inverse of decode_words_text(), this function accepts an array of strings or pairs of strings which will each be encoded by encode_word(), after which they are all pasted together.

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).

See also

MIME.encode_words_text_remapped


Methodencode_words_text_remapped

stringencode_words_text_remapped(stringtext, stringencoding, string|function(string:string) charset, string|voidreplacement, function(string:string)|voidrepcb)

Description

This is the reverse of MIME.decode_words_text_remapped(). A single UNICODE string is provided, which is separated into fragments and transcoded to selected character sets by this function as needed.

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).

Parameter charset

Either the name of a character set to use, or a function returning a character set to use given a text fragment as input.

Parameter replacement

The replacement argument to use when calling Charset.encoder

Parameter repcb

The repcb argument to use when calling Charset.encoder

See also

MIME.encode_words_tokenized_remapped


Methodext_to_media_type

stringext_to_media_type(stringextension)

Description

Returns the MIME media type for the provided filename extension. Currently 469 file extensions are known to this method. Zero will be returned on unknown file extensions.


Methodgenerate_boundary

stringgenerate_boundary()

Description

This function will create a string that can be used as a separator string for multipart messages. If a boundary prefix has been set using MIME.set_boundary_prefix(), the generated string will be prefixed with the boundary prefix.

The generated string is guaranteed not to appear in base64, quoted-printable, or x-uue encoded data. It is also unlikely to appear in normal text. This function is used by the cast method of the Message class if no boundary string is specified.

See also

MIME.set_boundary_prefix()


Methodget_boundary_prefix

string(8bit)get_boundary_prefix()

Description

Returns the boundary_prefix set via set_boundary_prefix().

See also

MIME.set_boundary_prefix(), MIME.Message.setboundary()


Methodguess_subtype

string|zeroguess_subtype(stringtype)

Description

Provide a reasonable default for the subtype field.

Some pre-RFC 1521 mailers provide only a type and no subtype in the Content-Type header field. This function can be used to obtain a reasonable default subtype given the type of a message. (This is done automatically by the MIME.Message class.)

Currently, the function uses the following guesses:

"text"

"plain"

"message"

"rfc822"

"multipart"

"mixed"


Methodparse_headers

array(mapping(string:string)|string) parse_headers(stringmessage)
array(mapping(string:array(string))|string) parse_headers(stringmessage, int(1)use_multiple)

Description

This is a low level function that will separate the headers from the body of an encoded message. It will also translate the headers into a mapping. It will however not try to analyze the meaning of any particular header. This means that the body is returned as is, with any transfer-encoding intact.

It is possible to call this function with just the header part of a message, in which case an empty body will be returned.

The result is returned in the form of an array containing two elements. The first element is a mapping containing the headers found. The second element is a string containing the body.

Headers that occur multiple times will have their contents NUL separated, unless use_multiple has been specified, in which case the contents will be arrays.

Note

Some headers (eg Subject) may include RFC 1522/RFC 2047 encoded words. To decode these, see decode_words_text and decode_words_tokenized and their friends.


Methodquote

stringquote(array(string|int) lexical_elements)

Description

This function is the inverse of the MIME.tokenize function.

A header field value is constructed from a sequence of lexical elements. Characters (ints) are taken to be special-characters, whereas strings are encoded as atoms or quoted-strings, depending on whether they contain any special characters.

Note

There is no way to construct a domain-literal using this function. Neither can it be used to produce comments.

See also

MIME.tokenize()


Methodquote_labled

stringquote_labled(array(array(string|int)) tokens)

Description

This function performs the reverse operation of tokenize_labled().

See also

MIME.quote(), MIME.tokenize_labled()


Methodreconstruct_partial

int|objectreconstruct_partial(array(object) collection)

Description

This function will attempt to reassemble a fragmented message from its parts.

The array collection should contain MIME.Message objects forming a complete set of parts for a single fragmented message. The order of the messages in the array is not important, but every part must exist at least once.

Should the function succeed in reconstructing the original message, a new MIME.Message object will be returned.

If the function fails to reconstruct an original message, an integer indicating the reason for the failure will be returned:

0

Returned if empty collection is passed in, or one that contains messages which are not of type message/partial, or parts of different fragmented messages.

(1..)

If more fragments are needed to reconstruct the entire message, the number of additional messages needed is returned.

-1

If more fragments are needed, but the function can't determine exactly how many.

Note

Note that the returned message may in turn be a part of another, larger, fragmented message.

See also

MIME.Message->is_partial()


Methodset_boundary_prefix

voidset_boundary_prefix(string(8bit)boundary_prefix)

Description

Set a message boundary prefix. The MIME.generate_boundary() will use this prefix when creating a boundary string.

Throws

An error is thrown if boundary_prefix doesn't adhere to RFC 1521.

See also

MIME.generate_boundary(), MIME.get_boundary_prefix()

Parameter boundary_prefix

This must adhere to RFC 1521 and can not be longer than 56 characters.


Methodtokenize

array(string|int) tokenize(stringheader, int|voidflags)

Description

A structured header field, as specified by RFC 0822, is constructed from a sequence of lexical elements.

Parameter header

The header value to parse.

Parameter flags

An optional set of flags. Currently only one flag is defined:

TOKENIZE_KEEP_ESCAPES

Keep backslash-escapes in quoted-strings.

The lexical elements parsed are:

individual special characters

quoted-strings

domain-literals

comments

atoms

This function will analyze a string containing the header value, and produce an array containing the lexical elements.

Individual special characters will be returned as characters (i.e. ints).

Quoted-strings, domain-literals and atoms will be decoded and returned as strings.

Comments are not returned in the array at all.

Note

As domain-literals are returned as strings, there is no way to tell the domain-literal [127.0.0.1] from the quoted-string "[127.0.0.1]". Hopefully this won't cause any problems. Domain-literals are used seldom, if at all, anyway...

The set of special-characters is the one specified in RFC 1521 (i.e. "<", ">", "@", ",", ";", ":", "\", "/", "?", "="), and not the set specified in RFC 0822.

See also

MIME.quote(), tokenize_labled(), decode_words_tokenized_remapped().


Methodtokenize_labled

array(array(string|int)) tokenize_labled(stringheader, int|voidflags)

Description

Similar to tokenize(), but labels the contents, by making arrays with two elements; the first a label, and the second the value that tokenize() would have put there, except for that comments are kept.

Parameter header

The header value to parse.

Parameter flags

An optional set of flags. Currently only one flag is defined:

TOKENIZE_KEEP_ESCAPES

Keep backslash-escapes in quoted-strings.

The following labels exist:

"encoded-word"

Word encoded according to =?...

"special"

Special character.

"word"

Word.

"domain-literal"

Domain literal.

"comment"

Comment.

See also

MIME.quote(), tokenize(), decode_words_tokenized_labled_remapped()

Class MIME.Message

Description

This class is used to hold a decoded MIME message.


Variablebody_parts

array(object) MIME.Message.body_parts

Description

If the message is of type multipart, this is an array containing one Message object for each part of the message. If the message is not a multipart, this field is 0 (zero).

See also

type, boundary


Variableboundary

string MIME.Message.boundary

Description

For multipart messages, this Content-Type parameter gives a delimiter string for separating the individual messages. As multiparts are handled internally by the module, you should not need to access this field.

See also

setboundary()


Variablecharset

string MIME.Message.charset

Description

One of the possible parameters of the Content-Type header is the charset attribute. It determines the character encoding used in bodies of type text.

If there is no Content-Type header, the value of this field is "us-ascii".

See also

type


Variabledata

string MIME.Message.data

Description

This variable contains the raw data of the message body entity.

The type and subtype attributes indicate how this data should be interpreted.

Note

In Pike 7.6 and earlier you had to use getdata() and setdata() to access this value.

See also

getdata(), setdata()


Variabledisp_params

mapping(string:string) MIME.Message.disp_params

Description

A mapping containing all the additional parameters to the Content-Disposition header.

See also

setdisp_param(), get_filename()


Variabledisposition

string MIME.Message.disposition

Description

The first part of the Content-Disposition header, hinting on how this part of a multipart message should be presented in an interactive application.

If there is no Content-Disposition header, this field is 0.


Variableheaders

mapping(string:string) MIME.Message.headers

Description

This mapping contains all the headers of the message.

The key is the header name (in lower case) and the value is the header value.

Although the mapping contains all headers, some particular headers get special treatment by the module and should not be accessed through this mapping. These fields are currently:

"content-type"
"content-disposition"
"content-length"
"content-transfer-encoding"

The contents of these fields can be accessed and/or modified through a set of variables and methods available for this purpose.

See also

type, subtype, charset, boundary, transfer_encoding, params, disposition, disp_params, setencoding(), setparam(), setdisp_param(), setcharset(), setboundary()

Note

Some headers (eg Subject) may include RFC 1522/RFC 2047 encoded words. To decode these, see decode_words_text and decode_words_tokenized and their friends.


Variableparams

mapping(string:string) MIME.Message.params

Description

A mapping containing all the additional parameters to the Content-Type header.

Some of these parameters have fields of their own, which should be accessed instead of this mapping wherever applicable.

See also

charset, boundary, setparam()


Variablesubtype

string MIME.Message.subtype

Description

The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the subtype attribute extracted from the header.

If there is no Content-Type header, the value of this field is "plain".

See also

type, params


Variabletransfer_encoding

string MIME.Message.transfer_encoding

Description

The contents of the Content-Transfer-Encoding header.

If no Content-Transfer-Encoding header is given, this field is 0 (zero).

Transfer encoding and decoding is done transparently by the module, so this field should be interesting only to applications wishing to do auto conversion of certain transfer encodings.

See also

setencoding()


Variabletype

string MIME.Message.type

Description

The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the type attribute extracted from the header.

If there is no Content-Type header, the value of this field is "text".

See also

subtype, params


Methodcast

(string)MIME.Message()

Description

Casting the message object to a string will yield a byte stream suitable for transmitting the message over protocols such as ESMTP and NNTP.

The body will be encoded using the current transfer encoding, and subparts of a multipart will be collected recursively. If the message is a multipart and no boundary string has been set, one will be generated using generate_boundary().

See also

create()


Methodcreate

MIME.MessageMIME.Message()
MIME.MessageMIME.Message(stringmessage)
MIME.MessageMIME.Message(stringmessage, mapping(string:string|array(string)) headers, array(object)|voidparts)
MIME.MessageMIME.Message(stringmessage, mapping(string:string|array(string)) headers, array(object)|voidparts, boolguess)

Description

There are several ways to call the constructor of the Message class:

  • With zero arguments, you will get a dummy message with neither headers nor body. Not very useful.

  • With one argument, the argument is taken to be a byte stream containing a message in encoded form. The constructor will analyze the string and extract headers and body.

  • With two or three arguments, the first argument is taken to be the raw body data, and the second argument a desired set of headers. The keys of this mapping are not case-sensitive. If the given headers indicate that the message should be of type multipart, an array of Message objects constituting the subparts should be given as a third argument.

  • With the guess argument set to 1 (headers and parts may be 0 if you don't want to give any), you get a more forgiving MIME Message that will do its best to guess what broken input data really meant. It won't always guess right, but for applications like mail archives and similar where you can't get away with throwing an error at the user, this comes in handy. Only use the guess mode only for situations where you need to process broken MIME messages silently; the abuse of overly lax tools is what poisons standards.

See also

cast()


Methodget_filename

stringget_filename()

Description

This method tries to find a suitable filename should you want to save the body data to disk.

It will examine the filename attribute of the Content-Disposition header, and failing that the name attribute of the Content-Type header. If neither attribute is set, the method returns 0.

Note

An interactive application should always query the user for the actual filename to use. This method may provide a reasonable default though.


Methodgetdata

stringgetdata()

Description

This method returns the raw data of the message body entity.

The type and subtype attributes indicate how this data should be interpreted.

See also

setdata(), getencoded(), data


Methodgetencoded

stringgetencoded()

Description

This method returns the data of the message body entity, encoded using the current transfer encoding.

You should never have to call this function.

See also

getdata()


Methodis_partial

array(string|int)|zerois_partial()

Description

If this message is a part of a fragmented message (i.e. has a Content-Type of message/partial), an array with three elements is returned.

The first element is an identifier string. This string should be used to group this message with the other fragments of the message (which will have the same id string).

The second element is the sequence number of this fragment. The first part will have number 1, the next number 2 etc.

The third element of the array is either the total number of fragments that the original message has been split into, or 0 of this information is not available.

If this method is called in a message that is not a part of a fragmented message, it will return 0.

See also

MIME.reconstruct_partial()


Methodparse_param

protectedvoidparse_param(mapping(string:string) params, array(string|int) entry, stringheader, int|voidguess, array(string|int)|voidentry2)

Description

Parse a Content-Type or Content-Disposition parameter.

Parameter params

Mapping to add parameters to.

Parameter entry

Array of tokens containing a parameter declaration.

Parameter header

Name of the header from which entry originated. This is only used to report errors.

Parameter guess

Make a best-effort attempt to parse broken entries.

Parameter entry2

Same as entry, but tokenized with MIME.TOKENIZE_KEEP_ESCAPES.

See also

create()


Methodsetboundary

voidsetboundary(stringboundary)

Description

Sets the boundary parameter of the Content-Type header.

This is equivalent of calling setparam("boundary", boundary).

See also

setparam()


Methodsetcharset

voidsetcharset(stringcharset)

Description

Sets the charset parameter of the Content-Type header.

This is equivalent of calling setparam("charset", charset).

See also

setparam()


Methodsetdata

voidsetdata(stringdata)

Description

Replaces the body entity of the data with a new piece of raw data.

The new data should comply to the format indicated by the type and subtype attributes.

Note

Do not use this method unless you know what you are doing.

See also

getdata(), setencoded, data


Methodsetdisp_param

voidsetdisp_param(stringparam, stringvalue)

Description

Set or modify the named parameter of the Content-Disposition header.

A common parameters is e.g. filename.

Note

It is not allowed to modify the Content-Disposition header directly, please use this function instead.

See also

setparam(), get_filename()


Methodsetencoding

voidsetencoding(stringencoding)

Description

Select a new transfer encoding for this message.

The Content-Transfer-Encoding header will be modified accordingly, and subsequent calls to getencoded will produce data encoded using the new encoding.

See MIME.encode() for a list of valid encodings.

See also

getencoded(), MIME.encode()


Methodsetparam

voidsetparam(stringparam, stringvalue)

Description

Set or modify the named parameter of the Content-Type header.

Common parameters include charset for text messages, and boundary for multipart messages.

Note

It is not allowed to modify the Content-Type header directly, please use this function instead.

See also

setcharset(), setboundary(), setdisp_param()

Class MIME.StringRange

Description

Class representing a substring of a larger string.

This class is used to reduce the number of string copies during parsing of MIME.Messages.

Module MIME.ext_to_media_type

Module MPI


MethodFinalize

voidFinalize()

Description

Cleans up the MPI stack. Will be called automatically upon termination of the Pike program, but can be called explicitly when it is required that some of the parallel processes continue running and some terminate.

See also

Init(), MPI_Finalize(3)


MethodInit

voidInit()

Description

Initializes MPI. MPI in Pike will auto-initialize once the first MPI-operation is called. You can call this function to initialize the parallel MPI at a specific time, since initialization is a collective operation and will block the process until all member processes of the parallel program are present.

Example

int main() { MPI.Init(); write("I am process %d of %d.\n", MPI.world->rank, MPI.world->size); MPI.Finalize(); return 0; }

See also

Finalize(), MPI_Init(3)


MethodOp_create

OpOp_create(function(object, object:void) ufun, intcommute)

Description

Creates a user-defined MPI operation.

Parameter ufun

The function that implements the MPI.Op to be created.

Parameter commute

Set to 1 if the operation commutes.

Example

void my_add_fun(object invec, object outvec) { for (int i = 0; i < sizeof(outvec); i++) { outvec[i] += invec[i]; }

int main() { MPI.Op myadd; MPI.IntArray ia = MPI.IntArray(10), results;

MPI.Init();

myadd = MPI.Op_create(my_add_fun, 1);

for (int i = 0; i < sizeof(ia); i++) ia[i] = random(1000);

if (!MPI.world->rank) results = MPI.IntArray(sizeof(ia)); MPI.world->Reduce(ia, results, 0); if (!MPI.world->rank) for (int i; i < sizeof(results); i++) write("%02d: %d\n", i, results[i]);

MPI.Finalize(); return 0; }

Note

User-defined MPI operations may not call any MPI operations themselves.

See also

MPI.Comm->Reduce(), MPI_Op_create(3)

Class MPI.Comm

Description

A communicator object holds a group of processes both relate messages between those processes as well as perform collective operations, in which all member processes of the communicator are involved.


MethodRecv

voidRecv(MPI.Pointerbuf, intsource, int|voidtag, MPI.Status|voidstatus)
voidRecv(MPI.IntArraybuf, intsource, int|voidtag, MPI.Status|voidstatus)
voidRecv(MPI.FloatArraybuf, intsource, int|voidtag, MPI.Status|voidstatus)
voidRecv(MPI.SingleArraybuf, intsource, int|voidtag, MPI.Status|voidstatus)
voidRecv(MPI.Sentinelbuf, intsource, int|voidtag, MPI.Status|voidstatus)

Description

Receives a message from source with matching tag into buf, storing the sender's rank and the tag used into the optionally given MPI.Status.

Note

The type of the buffer of the receiver site has to match the type of the buffer of the sender. Exception: If a string is sent, it has to be received into a MPI.Pointer.

Example

int main() { MPI.IntArray ia = MPI.IntArray(5);

MPI.Init();

write("This is rank %d, %d processes total.\n", MPI.world->rank, MPI.world->size);

if (MPI.world->rank) { for (int i = 0; i < sizeof(ia); i++) { ia[i] = MPI.world->rank + i; }

MPI.world->Send(ia, 0); // send to rank 0 } else { for (int i = 0; i < MPI.world->size; i++) { MPI.world->Recv(ia, i); write("Rank %d sent %O to rank 0.\n", i, (array)ia); } }

MPI.Finalize(); return 0; }

See also

MPI.Comm->Send(), MPI.Comm->Bcast(), MPI.ANY_SOURCE, MPI.ANY_TAG, MPI_Send(3).


MethodSend

voidSend(stringbuf, intdest, int|voidtag)
voidSend(MPI.IntArraybuf, intdest, int|voidtag)
voidSend(MPI.FloatArraybuf, intdest, int|voidtag)
voidSend(MPI.SingleArraybuf, intdest, int|voidtag)
voidSend(MPI.Sentinelbuf, intdest, int|voidtag)

Description

Sends the buffer buf to the process with rankdest, marked with tag.

See also

MPI.Comm()->Recv(), MPI.Comm()->Bcast(), MPI_Send(3).

Class MPI.FloatArray

Description

This class implements an array of double precision floats.

Note

Values will be converted to and from the Pike float type, which may introduce rounding errors if the types don't match in your installation.


Method_sizeof

intsizeof(MPI.FloatArrayarg)

Returns

The number of entries in this MPI_FloatArray .


Method_values

array(float) values(MPI.FloatArrayarg)

Returns

A Pike array copy of this array.

Example

array pike_array = values(typed_array);


Method`[]

float res = MPI.FloatArray()[ idx ]

Description

Gives the idxths element of the MPI_FloatArray .


Method`[]=

MPI.FloatArray()[ idx ] = val

Description

Sets the idxths element of the MPI_FloatArray to val.


Methodassign

voidassign(MPI_FloatArrayother)

Description

Assigns the first sizeof(other) entries from other to the respective entries in the current array.

Throws

If sizeof(other) > sizeof(this)


Methodcast

(int)MPI.FloatArray()
(float)MPI.FloatArray()
(string)MPI.FloatArray()
(array)MPI.FloatArray()
(mapping)MPI.FloatArray()
(multiset)MPI.FloatArray()

Description

Supports casting (by copy) this MPI_FloatArray to a Pike array.

Example

array pike_array = (array)typed_array;


Methodclear

voidclear()

Description

Sets all elements of the MPI_FloatArray to 0.


Methodcreate

MPI.FloatArrayMPI.FloatArray(int(0..)size)

Class MPI.IntArray

Description

This class implements an array of 32 bit integers.


Method_sizeof

intsizeof(MPI.IntArrayarg)

Returns

The number of entries in this MPI_IntArray .


Method_values

array(int) values(MPI.IntArrayarg)

Returns

A Pike array copy of this array.

Example

array pike_array = values(typed_array);


Method`[]

int res = MPI.IntArray()[ idx ]

Description

Gives the idxths element of the MPI_IntArray .


Method`[]=

MPI.IntArray()[ idx ] = val

Description

Sets the idxths element of the MPI_IntArray to val.


Methodassign

voidassign(MPI_IntArrayother)

Description

Assigns the first sizeof(other) entries from other to the respective entries in the current array.

Throws

If sizeof(other) > sizeof(this)


Methodcast

(int)MPI.IntArray()
(float)MPI.IntArray()
(string)MPI.IntArray()
(array)MPI.IntArray()
(mapping)MPI.IntArray()
(multiset)MPI.IntArray()

Description

Supports casting (by copy) this MPI_IntArray to a Pike array.

Example

array pike_array = (array)typed_array;


Methodclear

voidclear()

Description

Sets all elements of the MPI_IntArray to 0.


Methodcreate

MPI.IntArrayMPI.IntArray(int(0..)size)

Class MPI.Op

Description

Objects of this class represent MPI operations used in collective operations like MPI.Comm()->reduce(). You can use operations predefined by MPI or create your own.

Other than that, Ops are not that useful from Pike.

See also

MPI constants, MPI.Op_create(), MPI.Comm->Reduce().

Class MPI.Pointer

Description

A pointer like class. Because MPI.Comm->Recv() et al do not return "results" but take references/pointers to the target storage, you need to pass a Pointer to MPI.Comm()->recv() in order to receive the string.

Example

int main() { string s; MPI.Pointer p = MPI.Pointer();

MPI.Init();

if (MPI.world->rank()) MPI.world->Send(ctime(time(1)), 0); else for (int i = 1; i < MPI.world->size; i++) { MPI.world->Recv(p, i); write("Rank %03d says now is %s.\n", p()); }

MPI.Finalize(); return 0; }


Method`()

mixed res = MPI.Pointer()()
mixed res = MPI.Pointer()()

Description

If called with 0 arguments, returns the pointee. If called with argument m, now points to m.


Methodcreate

MPI.PointerMPI.Pointer()
MPI.PointerMPI.Pointer(mixedm)

Description

If m is given, point to m, else point to UNDEFINED.

Class MPI.Sentinel

Description

A Sentinel is a kind of handle that can be given out by objects if they want to allow MPI to send from/receive into the memory areas pointed to by the Sentinel.

Other than that, Sentinels are not that useful from Pike.

See also

Math.FMatrix()->get_sentinel(), Math.FMatrix

Class MPI.SingleArray

Description

This class implements an array of single precision floats.

Note

Values will be converted to and from the Pike float type, which may introduce rounding errors if the types don't match in your installation.


Method_sizeof

intsizeof(MPI.SingleArrayarg)

Returns

The number of entries in this MPI_SingleArray .


Method_values

array(float) values(MPI.SingleArrayarg)

Returns

A Pike array copy of this array.

Example

array pike_array = values(typed_array);


Method`[]

float res = MPI.SingleArray()[ idx ]

Description

Gives the idxths element of the MPI_SingleArray .


Method`[]=

MPI.SingleArray()[ idx ] = val

Description

Sets the idxths element of the MPI_SingleArray to val.


Methodassign

voidassign(MPI_SingleArrayother)

Description

Assigns the first sizeof(other) entries from other to the respective entries in the current array.

Throws

If sizeof(other) > sizeof(this)


Methodcast

(int)MPI.SingleArray()
(float)MPI.SingleArray()
(string)MPI.SingleArray()
(array)MPI.SingleArray()
(mapping)MPI.SingleArray()
(multiset)MPI.SingleArray()

Description

Supports casting (by copy) this MPI_SingleArray to a Pike array.

Example

array pike_array = (array)typed_array;


Methodclear

voidclear()

Description

Sets all elements of the MPI_SingleArray to 0.


Methodcreate

MPI.SingleArrayMPI.SingleArray(int(0..)size)

Class MPI.Status

Description

Objects of this class can be passed as the last argument to the receive operation of MPI.Comm communicators. After the operation has finished, they will contain information about the sender the message was received from and the tag used for communication.

Therefore, Status objects are particularly helpful in combination with MPI.ANY_SOURCE and MPI.ANY_TAG.

See also

MPI.Comm()->Recv()


VariableSOURCE

int MPI.Status.SOURCE

Description

Contains the source that the message was received from.

Example

int main() { if (MPI.world->rank) { sleep(random(MPI.world->size)/10.0); MPI.world->Send(gethostname(), MPI.world->rank), 0); } else { MPI.Status status; MPI.Pointer p;

for (int i = 0; i < MPI.world->size; i++) { MPI.world->Recv(p, MPI.ANY_SOURCE, 0, status); write("Rank %d has hostname %s.\n", status->SOURCE, p()); } }

return 0; }

See also

MPI.Comm()->Recv()


VariableTAG

int MPI.Status.TAG

Description

Contains the tag that was used in the MPI.Comm()->Recv operation.

See also

MPI.Comm()->Recv()

Module Math


Inherit"___Math"

inherit "___Math" : "___Math"


Constante

constant Math.e

Description

The constant e (2.7182818284590452354).


Constantinf

constant Math.inf

Description

Floating point infinity.


Constantnan

constant Math.nan

Description

Floating point not-a-number (e.g. inf/inf).

See also

Float.isnan()


Constantpi

constant Math.pi

Description

The constant pi (3.14159265358979323846).


Methodchoose

int(0..)choose(int(0..)n, int(0..)k)

Description

Calculate the binomial coefficient n choose k.

This is equal to n!/(k!*(n-k)!).


Methodconvert_angle

int|floatconvert_angle(int|floatangle, stringfrom, stringto)

Description

This function converts between degrees, radians and gons. The from and to arguments may be any of the follwoing strings: "deg", "rad", "gon" and "str" for degrees, radians, gon and streck respectivly. The output is not guaranteed to be within the first turn, e.g. converting 10 radians yields almost 573 degrees as output.


Methodfactor

array(int(-1..)) factor(intx)

Description

Factorize the integer x. The returned list of factors will be sorted biggest to smallest factor.

Note

In Pike versions prior to v8.0, only primes <= 8161 were considered.


Methodlog10

floatlog10(int|floatx)

Description

The 10-logarithm of x.


Methodlog2

floatlog2(int|floatx)

Description

The 2-logarithm of x.


Methodlogn

floatlogn(int|floatn, int|floatx)

Description

The n-logarithm of x.

Class Math.Angle

Description

Represents an angle.


Variableangle

int|float Math.Angle.angle

Description

The actual keeper of the angle value.


Variabletype

string Math.Angle.type

Description

The type of the angle value. Is either "deg", "rad", "gon" or "str".


Method__hash

inthash_value(Math.Anglearg)


Method`%

float|int|Angle res = Math.Angle() % _angle

Description

Returns this result of this angle modulo the provided value. If differenced with an angle, a new angle object is returned.


Method`*

float|int|Angle res = Math.Angle() * _angle

Description

Returns the product between this angle and the provided value. If differenced with an angle, a new angle object is returned.


Method`+

float|int|Angle res = Math.Angle() + _angle

Description

Returns the sum of this angle and what it is added with. If added with an angle, a new angle object is returnes.


Method`-

float|int|Angle res = Math.Angle() - _angle

Description

Returns the difference between this angle and the provided value. If differenced with an angle, a new angle object is returned.


Method`/

float|int|Angle res = Math.Angle() / _angle

Description

Returns the fraction between this angle and the provided value. If differenced with an angle, a new angle object is returned.


Method`<

int res = Math.Angle() < _angle

Description

Compares the unnormalized angle of two Angle objects.


Method`==

int res = Math.Angle() == _angle

Description

Compares the unnormalized angle of two Angle objects.


Method`>

int res = Math.Angle() > _angle

Description

Compares the unnormalized angle of two Angle objects.


Methodabout_face

voidabout_face()

Description

Turns the direction of the angle half a turn. Equal to add(180,"deg").


Methodadd

Angleadd(float|intangle)
Angleadd(float|intangle, stringtype)
Angleadd(Angleangle)

Description

Adds the provided angle to the current angle. The result is normalized within 360 degrees.


Methodcast

(float)Math.Angle()
(int)Math.Angle()
(string)Math.Angle()

Description

An angle can be casted to float, int and string.


Methodclone_me

Angleclone_me()

Description

Returns a copy of the object.


Methodcos

floatcos()

Description

Returns the cosinus for the angle.


Methodcreate

Math.AngleMath.Angle()
Math.AngleMath.Angle(int|floatradians)
Math.AngleMath.Angle(int|floatangle, stringtype)

Description

If an angle object is created without arguments it will have the value 0 radians.


Methoddegree

int|floatdegree()

Description

Returns the number of degrees, including minutes and seconds as decimals.


Methodformat_dms

stringformat_dms()

Description

Returns degrees, minutes and seconds as a string, e.g. 47°6'36.00".


Methodget

int|floatget(stringtype)

Description

Gets the value in the provided type.


Methodgon

int|floatgon()

Description

Returns the number of gons.


Methodleft_face

voidleft_face()

Description

Turns the direction of the angle a quarter of a turn to the left. Equal to add(90,"deg").


Methodminute

intminute()

Description

Returns the number of minute.


Methodnormalize

voidnormalize()

Description

Normalizes the angle to be within one turn.


Methodrad

floatrad()

Description

Returns the number of radians.


Methodright_face

voidright_face()

Description

Turns the direction of the angle a quarter of a turn to the right. Equal to subtract(90,"deg").


Methodsecond

floatsecond()

Description

Returns the number of seconds.


Methodset

Angleset(stringtype, int|float_angle)

Description

Sets the angle value and type to the given value and type.


Methodset_degree

Angleset_degree(int|floatdegree)

Description

Sets the angle to the provided degree. Alters the type to degrees. Returns the current object.


Methodset_dms

Angleset_dms(intdegrees)
Angleset_dms(intdegrees, intminutes)
Angleset_dms(intdegrees, intminutes, floatseconds)

Description

Set degrees, minues and seconds. Returns the current angle object.


Methodset_gon

Angleset_gon(int|floatgon)

Description

Set the angle to the provided gons. Alters the type to gons. Returns the current angle object.


Methodset_rad

Angleset_rad(int|floatrad)

Description

Set the angle to the provided radians. Alters the type to radians. Returns the current angle object.


Methodset_streck

Angleset_streck(int|floatstr)

Description

Set the angle to the provided strecks. Alters the type to streck. Returns the current angle object.


Methodsin

floatsin()

Description

Returns the sinus for the angle.


Methodstreck

float|intstreck()

Description

Returns the number of strecks.


Methodsubtract

Anglesubtract(float|intangle)
Anglesubtract(float|intangle, stringtype)
Anglesubtract(Angleangle)

Description

Subtracts the provided angle from the current angle. The result is normalized within 360 degrees.


Methodtan

floattan()

Description

Returns the tangen for the angle.

Class Math.FMatrix

Description

Matrix representation with single precision floating point values.


InheritMatrix

inherit Matrix : Matrix

Class Math.IMatrix

Description

Matrix representation with 32 bit integer values.


InheritMatrix

inherit Matrix : Matrix

Class Math.LMatrix

Description

Matrix representation with 64 bit integer values.


InheritMatrix

inherit Matrix : Matrix

Class Math.Matrix

Description

Matrix representation with double precision floating point values.


Method`*
Method``*
Methodmult

Matrix res = Math.Matrix() * with
Matrix res = with * Math.Matrix()
Matrixmult(objectwith)

Description

Matrix multiplication.


Method`+
Method``+
Methodadd

Matrix res = Math.Matrix() + with
Matrix res = with + Math.Matrix()
Matrixadd(objectwith)

Description

Add this matrix to another matrix. A new matrix is returned. The matrices must have the same size.


Method`-
Method``-
Methodsub

Matrix res = Math.Matrix() - x
Matrix res = Math.Matrix() - with
Matrix res = with - Math.Matrix()
Matrixsub(objectwith)

Description

Subtracts this matrix from another. A new matrix is returned. -m is equal to -1*m.


Methodcast

(array(array(float)))Math.Matrix()
(array(array(float)))Math.Matrix()

Description

It is possible to cast the matrix to an array and get back a double array of floats with the matrix values.

See also

vect


Methodconvolve

Matrixconvolve(objectwith)

Description

Convolve called matrix with the argument.


Methodcreate

Math.MatrixMath.Matrix(array(array(int|float)) matrix_2d)
Math.MatrixMath.Matrix(array(int|float) matrix_1d)

Description

Initializes the matrix as a 1D or 2D matrix, e.g. Math.Matrix( ({({1,2}),({3,4})}) ).


Methodcreate

Math.MatrixMath.Matrix(intn, intm)
Math.MatrixMath.Matrix(intn, intm, stringtype)
Math.MatrixMath.Matrix(intn, intm, float|intinit)

Description

Initializes the matrix as to be a n*m matrix with init in every value. If no third argument is given, or the third argument is "identity", the matrix will be initialized with all zeroes except for the diagonal which will be 1.


Methodcreate

Math.MatrixMath.Matrix(stringtype, intsize)

Description

When type is "identity" the matrix is initializes as a square identity matrix.


Methodcreate

Math.MatrixMath.Matrix(stringtype, intsize, floatrads, Matrixaxis)
Math.MatrixMath.Matrix(stringtype, intsize, floatrads, floatx, floaty, floatz)

Description

When type is "rotate" the matrix is initialized as a rotation matrix.


Methodcross

Matrixcross(objectwith)

Description

Matrix cross-multiplication.


Methoddot_product

floatdot_product(objectwith)

Description

Matrix dot product.


Methodmax
Methodmin

Matrixmax()
Matrixmin()

Description

Produces the maximum or minimum value of all the elements in the matrix.


Methodnorm
Methodnorm2
Methodnormv

floatnorm()
floatnorm2()
Matrixnormv()

Description

Norm of the matrix, and the square of the norm of the matrix. (The later method is because you may skip a square root sometimes.)

This equals |A| or sqrt( A02 + A12 + ... + An2 ).

It is only usable with 1xn or nx1 matrices.

m->normv() is equal to m*(1.0/m->norm()), with the exception that the zero vector will still be the zero vector (no error).


Methodsum

Matrixsum()

Description

Produces the sum of all the elements in the matrix.


Methodtranspose

Matrixtranspose()

Description

Returns the transpose of the matrix as a new object.


Methodvect

arrayvect()

Description

Return all the elements of the matrix as an array of numbers


Methodxsize

intxsize()

Description

Returns the width of the matrix.


Methodysize

intysize()

Description

Returns the height of the matrix.

Class Math.SMatrix

Description

Matrix representation with 16 bit integer values.


InheritMatrix

inherit Matrix : Matrix

Module Math.Transforms

Class Math.Transforms.FFT


Methodcreate

Math.Transforms.FFTMath.Transforms.FFT(void|intn, void|boolexact)

Description

Creates a new transform object. If n is specified, a plan is created for transformations of n-size arrays.

Parameter n

Size of the transform to be preformed. Note that the transform object will be initialized for this size, but if an array of different size is sent to the object, it will be reinitialized. This can be used to gain preformace if all transforms will be of a given size.

Parameter exact

If exact is 1, a "better" plan for the transform will be created. This will take more time though. Use only if preformance is needed.


MethodrFFT

array(array(float)) rFFT(array(int|float) real_input)

Description

Returns the FFT of the input array. The input must be real and the output is complex. The output consists of an array. It's first element is the amplitudes and the second element is the phases.

Parameter real_input

The array of floats and/or ints to transform.

Note

rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.

See also

rIFFT()


MethodrIFFT

array(float) rIFFT(array(array(float)) input)

Description

Returns the inverse FFT of the input array. The input must be complex and guaranteed to generate a real output.

The input is an array. It's first element is the amplitudes and the second element is the phases.

The output is an array of the real values for the iFFT.

Parameter real_input

The array of floats and/or ints to transform.

Note

rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.

See also

rFFT()

Module NetUtils

Description

Various networking-related utility functions.


Constantlocality

constant NetUtils.locality

Description

Mapping from NetworkType to an integer between 0 and 10 that describes how local that type of network is.


VariableANY

string|zero NetUtils.ANY

Description

Returns either 0 or "::" depending on whether or not this computer has IPv6 support.

The intent is to use this when binding addresses, like port->bind(portno,callback,NetUtils.ANY) to get ipv6 support if present.

The reason for the existence of this function is that using "::" on a computer that does not actually have any ipv6 addresses (and thus no support for ipv6), at least on linux, causes the bind call to fail entirely.

Note

Read only


Methodbroadcast_addresses

mapping(string:array(string)) broadcast_addresses()

Description

Returns a mapping from interface name to the broadcast addresses on that interface.


Methodcidr_to_netmask

array(int)|zerocidr_to_netmask(string|zerocidr)

Description

Converts a string with an IP address and mask (in CIDR notation) into a binary IP address and bitmask.

Parameter cidr

The CIDR-notation input string.

Returns

An array containing:

Array
intip

The binary representation of the IP address.

intmask

The bitmask.

Returns 0 if the string could not be parsed.


Methodclear_cache

voidclear_cache()

Description

Clear any caches. This might be needed if the network setup on the system changes.


Methodconnectable_network_types

array(NetworkType) connectable_network_types()

Description

Returns network types in priority order according to RFC 3484.

This function assumes a network category (ipv4 or ipv6) is available if the local host has a configured address (excluding localhost) of that network type.

This function will always list the v6 and non-v6 addresses separately.


Methodget_network_type

NetworkTypeget_network_type(int|stringipstr, bool|voidseparate_6)

Description

Determine the network type of a given host

Parameter ipstr

IP address in string or numerical form

Parameter separate_6

Adds a 'v6' to the category for ipv6 addresses (ie, "global" and "globalv6")

Returns

"localhost", "local", "private", "multicast", "teredo", "6to4" or "global"

"localhost" is the local computer.

"local" is the local network

"private" is a private network, such as 10.0.0.0/8 or fc00::/7 that is not also a local network.

"multicast" is a multicast address

"teredo" and "6to4" is an address in the teredo and 6to4 tunneling system, respectively.

"global" is a global address that does not match any other category


Methodhas_ipv4

boolhas_ipv4()

Description

Returns true if the local host has a public IPv4 address


Methodhas_ipv6

boolhas_ipv6()

Description

Returns true if the local host has a public IPv6 address


Methodhost_to_cidr

stringhost_to_cidr(int|stringip)

Description

Return the CIDR notation for the single host defined by x.

Parameter ip

The host ip in either string or raw form

Returns

either ip/128 or ip/32 depending on the IPV6-ness of the host IP.


Methodip_and_port_of

array(string)|zeroip_and_port_of(RemoteAddressObject|string|int(0)inc, bool|voidlocal_address)

Description

Similar to ip_of. Returns 2-element array containing IP address and port number. Second element will be 0 if no port number can be retrieved.

This function can return 0 if inc is a RemoteAddressObject and query_address throws an error or does not return a string.


Methodip_in_block

boolip_in_block(intnet, intmask, int|stringip)

Description

Checks whether an IP address is in a block.

The net and mask parameters should be as returned from cidr_to_netmask.

Throws an error if the IP address could not be parsed.

Parameter net

The network component of the block.

Parameter mask

The bitmask of the block.

Parameter ip

The IP address to check, in either string or binary representation.

Returns

true if the IP is in the given block, false otherwise.


Methodip_less_global

boolip_less_global(int|stringwhich, int|stringtowhat, bool|voidprefer_v4)

Description

Returns true if which is less globally accessible than towhat.


Methodip_of

stringip_of(RemoteAddressObject|string|int(0)inc, bool|voidlocal_address, string|voiddef)

Description

If the argument is an object with a query_address method, return the IP# part of the string returned by calling that function with local_address as the argument.

This means that for Stdio.File objects the remote address is returned by default, but if local_address is true the local address is returned.

If the argument is a string instead, the part of the string before the first space is returned.

If the argument is 0 the default def value is returned, UNDEFINED unless specified.

If def is supplied, it is used both when query_address() fails or something that is not a file descriptor object or a string is passed as the argument to this function.


Methodip_to_string

string|zeroip_to_string(intip, bool|voidv6_only)

Description

Converts a binary representation of an IP address into the IPv4 or IPv6 string representation.

The reverse of string_to_ip.

Parameter ip

The binary representation of the address.

Parameter v6_only

Always return IPV6 addresses. IPV4 addresses will be formatted as ::FFFF:<ipv4>

Returns

The string representation of the address, or 0 if the IP was invalid.


Methodis_ipv6

boolis_ipv6(int|stringip)

Description

Returns true if the IP ip is a IPV6 IP.


Methodis_local_host

boolis_local_host(RemoteAddressObject|string|inthost, bool|voidonly_localhost)

Description

Returns true if host points to the local host.

Parameter host

The host to check

Parameter only_localhost

Only check if it is ipv6 or ipv4 localhost, not if it is one of the public IP# of this host.

Returns

true if the given host is the local host, false otherwise


Methodis_local_network

stringis_local_network(RemoteAddressObject|int|stringhost)

Description

Returns non-zero if host is on one of the local networks, and if so which interface it is on.


Methodlocal_host

stringlocal_host()

Description

Returns either ::1 or 127.0.0.1 depending on the availability of IPV6.


Methodlocal_interfaces

mapping(string:array(string)) local_interfaces()

Description

Return a mapping from interface to address/netmask (only returns non link-local addresses for ipv6)


Methodlocal_ips

multiset(string) local_ips(bool|voidinclude_localhost)

Description

Return an array with locally configured IP-numbers, excluding the ones configured on the loopback inteface, unless include_localhost is specified.


Methodlocal_ips_raw

multiset(int) local_ips_raw(bool|voidinclude_localhost)

Description

Much like local_ips, but returns the IP:s parsed to the integer raw format.


Methodlocal_networks

IpRangeLookuplocal_networks()

Description

Returns an IpRangeLookup that can be used to find the interface for an IP address.


Methodnetmask_to_cidr

intnetmask_to_cidr(stringmask)

Description

Returns the CIDR of a given netmask. Only returns the correct value for netmasks with all-zeroes at the end (eg, 255.255.255.128 works, while 255.255.255.3 will give the wrong return value)

See also

http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation


Methodnormalize_address

string|zeronormalize_address(stringa)

Description

Normalize the IP specified in a. This normalizes IPv6 addresses and converts ::FFFF:<ipv4> and ::<ipv4> to "normal" IPV4 addresses.

Will return 0 if a is not a valid address.


Methodport_of

stringport_of(RemoteAddressObject|string|int(0)inc, bool|voidlocal_address, string|voiddef)

Description

Similar to ip_of but instead of IP returns port number.

If the argument is an object with a query_address method, return the port# part of the string returned by calling that function with local_address as the argument.

This means that for Stdio.File objects the remote address is returned by default, but if local_address is true the local address is returned.

If the argument is a string instead, the part of the string after the first space is returned.

If the argument is 0 the default def value is returned, UNDEFINED unless specified.

If def is supplied, it is used both when query_address() fails or something that is not a file descriptor object or a string is passed as the argument to this function.


Methodsort_addresses

array(string) sort_addresses(array(string) addresses, array(NetworkType)|voidexclude_types, bool|voidseparate_v6)

Description

Given a list of addresses, sort them according to connectable priority order (RFC 3484).

If exclude_types is specified, addresses that match any of the network types (({"local", "localhost"}) for the local network as an example) in the given array will be exluded from the result.

If separate_v6 is true, exclude_types separates v6 from v4. That is, you can disable "localhost" without also disabling "localhostv6".

The addresses inside each group will be returned in random order.


Methodspecial_networks

IpRangeLookupspecial_networks()

Description

Return an IpRangeLookup instance useful for finding out the address category of a ip. Basically like get_network_type without the "local" category.


Methodstring_to_ip

intstring_to_ip(stringips)

Description

Converts a string representation of an IPv4 address into the binary representation.

Parameter ips

The string representation of the address. For convenience this function accepts the notation returned from fd->query_adddress() ("ip port")

Returns

The binary representation of the address, or -1 if the string could not be parsed.


Methodvalid_domain_name

boolvalid_domain_name(stringhostname)

Description

Perform a basic sanity check on hostname based on total and subdomain label length. Does not test for invalid chars.

Parameter hostname

Domain name string to test.

Returns

True if hostname looks like a valid domain name

Enum NetUtils.NetworkType

Description

A list of all known network type/classes


ConstantLOCALHOST
ConstantLOCAL
ConstantMULTICAST
ConstantGLOBAL
ConstantPRIVATE

constant NetUtils.LOCALHOST
constant NetUtils.LOCAL
constant NetUtils.MULTICAST
constant NetUtils.GLOBAL
constant NetUtils.PRIVATE

Description

V4 and in non-v6-separate mode also used for V6


ConstantLOCALHOSTV6
ConstantLOCALV6
ConstantPRIVATEV6
ConstantMULTICASTV6
ConstantGLOBALV6

constant NetUtils.LOCALHOSTV6
constant NetUtils.LOCALV6
constant NetUtils.PRIVATEV6
constant NetUtils.MULTICASTV6
constant NetUtils.GLOBALV6

Description

V6 only versions


ConstantLINKLOCAL

constant NetUtils.LINKLOCAL


ConstantTEREDO
ConstantV6TO4

constant NetUtils.TEREDO
constant NetUtils.V6TO4

Description

Tunneling reserved addresses

Enum NetUtils.System


ConstantLinux
ConstantNT
ConstantOther
ConstantUnsupported

constant NetUtils.Linux
constant NetUtils.NT
constant NetUtils.Other
constant NetUtils.Unsupported

Class NetUtils.IpRangeLookup

Description

Class used for checking an IP against a list of IP ranges and looking up some associated information.


Methodcreate

NetUtils.IpRangeLookupNetUtils.IpRangeLookup(mapping(mixed:array(string)) ranges)

Description

Creates a new IpRangeLookup object and initialises the IP range table. Errors will be thrown if ranges contains invalid data.

Parameter ranges

A mapping from information data to arrays of IP ranges.

Each range can be a single addresses ("192.168.1.1"), a range of addresses ("192.168.1.1-192.168.1.5") or be written in CIDR notation ("192.168.1.0/24").


Methodget_ranges

mapping(string:array(Range)) get_ranges()

Description

Return a copy of the internal range to info mapping.


Methodlookup

mixedlookup(int|stringipstr)

Description

Looks up an IP address and returns the associated information, if any.

Parameter ipstr

The IP address in string or binary form.

Returns

The information associated with the most-specific IP range matching ipstr.


Methodlookup_range

Rangelookup_range(int|stringipstr)

Description

Looks up an IP address and returns the associated Range, if any.

Parameter ipstr

The IP address in string or binary form.

Returns

The matching net-range

Class NetUtils.IpRangeLookup.Range

Description

Represents a single range in a IpRangeLoopup.


InheritNetMask

inherit NetMask : NetMask


Variableinfo

mixed NetUtils.IpRangeLookup.Range.info

Class NetUtils.NetMask

Description

Persistent representation of a network + mask.


Variablemask

int NetUtils.NetMask.mask

Description

The network mask


Variablenet

int NetUtils.NetMask.net

Description

The network number


Methodcast

(int)NetUtils.NetMask()
(float)NetUtils.NetMask()
(string)NetUtils.NetMask()
(array)NetUtils.NetMask()
(mapping)NetUtils.NetMask()
(multiset)NetUtils.NetMask()

Description

Convert to either a string (back to CIDR notation) or an array (net,mask)


Methodcreate

NetUtils.NetMaskNetUtils.NetMask(stringcidr)

Description

Construct a new NetMask object from the given CIDR.

Parameter cidr

An IP and mask in CIDR notation.


Methodip_in

boolip_in(int|stringip)

Description

Match an IP number against the mask.

Returns

true if the ip is in the network, false otherwise.

Parameter ip

The IP address to check, in either string or binary representation.

Class NetUtils.RemoteAddressObject

Description

Interface for objects that can be sent to ip_of and friends.

This matches at least Stdio.File and Stdio.Port, Stdio.UDP and some other classes.

Module Object


ConstantDESTRUCT_EXPLICIT
ConstantDESTRUCT_NO_REFS
ConstantDESTRUCT_GC
ConstantDESTRUCT_CLEANUP

constant Object.DESTRUCT_EXPLICIT
constant Object.DESTRUCT_NO_REFS
constant Object.DESTRUCT_GC
constant Object.DESTRUCT_CLEANUP

Description

Flags passed to lfun::_destruct.

Note

Object.DESTRUCT_EXPLICIT is 0 and Object.DESTRUCT_CLEANUP is 1 for compatibility.


Methodsecure

objectsecure(objectstr)

Description

Marks the object as secure, which will clear the memory area before freeing the object.

See also

String.secure()

Module PDF


Constanta0_width
Constanta0_height
Constanta1_width
Constanta1_height
Constanta2_width
Constanta2_height
Constanta3_width
Constanta3_height
Constanta4_width
Constanta4_height
Constanta5_width
Constanta5_height
Constanta6_width
Constanta6_height
Constantb5_width
Constantb5_height
Constantletter_width
Constantletter_height
Constantlegal_width
Constantlegal_height
Constantledger_width
Constantledger_height
Constantp11x17_width
Constantp11x17_height

constant PDF.a0_width
constant PDF.a0_height
constant PDF.a1_width
constant PDF.a1_height
constant PDF.a2_width
constant PDF.a2_height
constant PDF.a3_width
constant PDF.a3_height
constant PDF.a4_width
constant PDF.a4_height
constant PDF.a5_width
constant PDF.a5_height
constant PDF.a6_width
constant PDF.a6_height
constant PDF.b5_width
constant PDF.b5_height
constant PDF.letter_width
constant PDF.letter_height
constant PDF.legal_width
constant PDF.legal_height
constant PDF.ledger_width
constant PDF.ledger_height
constant PDF.p11x17_width
constant PDF.p11x17_height

Class PDF.PDFgen

Description

Interface to the pdflib pdf generator. For more information see http://www.pdflib.com


Methodadd_bookmark

intadd_bookmark(stringtext, intparent, intopen)


Methodadd_launchlink

objectadd_launchlink(floatllx, floatlly, floaturx, floatury, stringfilename)


Methodadd_locallink

objectadd_locallink(floatllx, floatlly, floaturx, floatury, intpage, stringdest)


Methodadd_pdflink

objectadd_pdflink(floatllx, floatlly, floaturx, floatury, stringfilename, intpage, stringdest)


Methodadd_weblink

objectadd_weblink(floatllx, floatlly, floaturx, floatury, stringurl)


Methodarc

objectarc(floatx, floaty, floatr, floatstart, floatend)


Methodattach_file

objectattach_file(floatllx, floatlly, floaturx, floatury, stringfilename, stringdescription, stringauthor, stringmimetype, stringicon)


Methodbegin_page

PDFbegin_page()
PDFbegin_page(floatwidth, floatheight)

Description

note: Defaults to a4, portrait


Methodcircle

objectcircle(floatx, floaty, floatr)


Methodclose

PDFclose()


Methodclose_image

objectclose_image(intimage)


Methodconcat

objectconcat(floata, floatb, floatc, floatd, floate, floatf)


Methodcontinue_text

PDFcontinue_text(strings)


Methodcreate

PDF.PDFgenPDF.PDFgen()


Methodcurveto

objectcurveto(floatx1, floaty1, floatx2, floaty2, floatx3, floaty3)


Methodend_page

PDFend_page()


Methodfindfont

intfindfont(stringfontname)
intfindfont(stringfontname, void|stringencoding, void|intembed)


Methodget_parameter

stringget_parameter(stringkey)
stringget_parameter(stringkey, floatmodifier)


Methodget_value

floatget_value(stringkey)
floatget_value(stringkey, floatmodifier)


Methodlineto

objectlineto(floatx, floaty)


Methodmoveto

objectmoveto(floatx, floaty)


Methodopen_CCITT

intopen_CCITT(stringfilename, intwidth, intheight, intBitReverse, intK, intBlackIs1)


Methodopen_file

intopen_file(stringfilename)


Methodopen_image

intopen_image(stringtype, stringsource, stringdata, intwidth, intheight, intcomponents, intbpc, stringparams)


Methodopen_image_file

intopen_image_file(stringtype, stringfilename)
intopen_image_file(stringtype, stringfilename, void|stringstringparam, void|intintparam)


Methodplace_image

objectplace_image(intimage, floatx, floaty, floatscale)


Methodrect

objectrect(floatx, floaty, floatwidth, floatheight)


Methodrotate

objectrotate(floatphi)


Methodscale

objectscale(floatsx, floatsy)


Methodset_border_color

objectset_border_color(floatred, floatgreen, floatblue)


Methodset_border_dash

objectset_border_dash(floatb, floatw)


Methodset_border_style

objectset_border_style(stringstyle, floatwidth)


Methodset_info

floatset_info(stringkey, stringinfo)


Methodset_parameter

floatset_parameter(stringkey, stringparameter)


Methodset_text_pos

objectset_text_pos(floatx, floaty)


Methodset_value

floatset_value(stringkey, floatvalue)


Methodsetdash

objectsetdash(floatb, floatw)


Methodsetflat

objectsetflat(floatflatness)


Methodsetfont

PDFsetfont(intn, floatsize)


Methodsetgray

objectsetgray(floatgray)


Methodsetgray_fill

objectsetgray_fill(floatgray)


Methodsetgray_stroke

objectsetgray_stroke(floatgray)


Methodsetlinecap

objectsetlinecap(intlinecap)


Methodsetlinejoin

objectsetlinejoin(intlinejoin)


Methodsetlinewidth

objectsetlinewidth(floatwidth)


Methodsetmiterlimit

objectsetmiterlimit(floatmiter)


Methodsetrgbcolor

objectsetrgbcolor(floatred, floatgreen, floatblue)


Methodsetrgbcolor_fill

objectsetrgbcolor_fill(floatred, floatgreen, floatblue)


Methodsetrgbcolor_stroke

objectsetrgbcolor_stroke(floatred, floatgreen, floatblue)


Methodshow

PDFshow(strings)


Methodshow_boxed

intshow_boxed(stringtext, floatx, floaty, floatwidth, floatheight, stringmode)
intshow_boxed(stringtext, floatx, floaty, floatwidth, floatheight, stringmode, stringfeature)


Methodshowxy

PDFshowxy(strings, floatx, floaty)


Methodskew

objectskew(floatalpha, floatbeta)


Methodstringwidth

floatstringwidth(stringtext, intfont, floatsize)


Methodtranslate

objecttranslate(floattx, floatty)

Module Pango

Module Pike


ConstantINDEX_FROM_BEG
ConstantINDEX_FROM_END
ConstantOPEN_BOUND

local constant Pike.INDEX_FROM_BEG
local constant Pike.INDEX_FROM_END
local constant Pike.OPEN_BOUND

Description

Used with predef::`[..] and lfun::`[..] to specify how the corresponding index maps to an upper or lower range bound:

INDEX_FROM_BEG

The index is relative to the beginning of the string or array (or any other sequence implemented through an object). Sequences typically start at zero.

INDEX_FROM_END

The index is relative to the end of the sequence. In strings and arrays, the last element is at zero, the one before that at one, etc.

OPEN_BOUND

The range is open in the corresponding direction. The index is irrelevant in this case.


ConstantWEAK_INDICES
ConstantWEAK_VALUES
ConstantWEAK

local constant Pike.WEAK_INDICES
local constant Pike.WEAK_VALUES
local constant Pike.WEAK

Description

Flags for use together with set_weak_flag and get_weak_flag. See set_weak_flag for details.


Constant__HAVE_CPP_PREFIX_SUPPORT__

local constant Pike.__HAVE_CPP_PREFIX_SUPPORT__

Description

This constant exists and has the value 1 if cpp supports the prefix feature.

See also

cpp()


Methodcount_memory

intcount_memory(int|mapping(string:int) options, mixed ... things)

Description

In brief, if you call Pike.count_memory(0,x) you get back the number of bytes x occupies in memory.

The detailed story is a bit longer:

This function calculates the number of bytes that all things occupy. Or put another way, it calculates the number of bytes that would be freed if all those things would lose their references at the same time, i.e. not only the memory in the things themselves, but also in all the things that are directly and indirectly referenced from those things and not from anywhere else.

The memory counted is only that which is directly occupied by the things in question, including any overallocation for mappings, multisets and arrays. Other memory overhead that they give rise to is not counted. This means that if you would count the memory occupied by all the pike accessible things you would get a figure significantly lower than what the OS gives for the pike process.

Also, if you were to actually free the things, you should not expect the size of the pike process to drop the amount of bytes returned by this function. That since Pike often retains the memory to be reused later.

However, what you should expect is that if you actually free the things and then later allocates some more things for which this function returns the same size, there should be essentially no increase in the size of the pike process (some increase might occur due to internal fragmentation and memory pooling, but it should be small in general and over time).

The search for things only referenced from things can handle limited cyclic structures. That is done by doing a "lookahead", i.e. searching through referenced things that apparently have other outside references. You can control how long this lookahead should be through options (see below). If the lookahead is too short to cover the cycles in a structure then a too low value is returned. If the lookahead is made gradually longer then the returned value will eventually become accurate and not increase anymore. If the lookahead is too long then unnecessary time might be spent searching through things that really have external references.

Objects that are known to be part of cyclic structures are encouraged to have an integer constant or variable pike_cycle_depth that specifies the lookahead needed to discover those cycles. When Pike.count_memory visits such objects, it uses that as the lookahead when going through the references emanating from them. Thus, assuming objects adhere to this convention, you should rarely have to specify a lookahead higher than zero to this function.

Note that pike_cycle_depth can also be set to zero to effectively stop the lookahead from continuing through the object. That can be useful to put in objects you know have global references, to speed up the traversal.

Parameter options

If this is an integer, it specifies the maximum lookahead distance. -1 counts only the memory of the given things, without following any references. 0 extends the count to all their referenced things as long as there are no cycles (except if pike_cycle_depth is found in objects - see above). 1 makes it cover cycles of length 1 (e.g. a thing points to itself), 2 handles cycles of length 2 (e.g. where two things point at each other), and so on.

However, the lookahead is by default blocked by programs, i.e. it never follows references emanating from programs. That since programs seldom are part of dynamic data structures, and they also typically contain numerous references to global data which would add a lot of work to the lookahead search.

To control the search in more detail, options can be a mapping instead:

lookahead : int

The maximum lookahead distance, as described above. Defaults to 0 if missing.

block_arrays : int

When any of these are given with a nonzero value, the corresponding type is blocked when lookahead references are followed. They are unblocked if the flag is given with a zero value. Only programs are blocked by default.

These blocks are only active during the lookahead, so blocked things are still recursed and memory counted if they are given as arguments or only got internal references.

block_mappings : int
block_multisets : int
block_objects : int
block_programs : int
block_strings : int

If positive then strings are always excluded (except any given directly in things), if negative they are always included. Otherwise they are counted if they have no other refs, but note that since strings are shared they might get refs from other unrelated parts of the program.

block_pike_cycle_depth : int

Do not heed pike_cycle_depth values found in objects. This is implicit if the lookahead is negative.

return_count : int

Return the number of things that memory was counted for, instead of the byte count. (This is the same number internal contains if collect_stats is set.)

collect_internals : int

If this is nonzero then its value is replaced with an array that contains the things that memory was counted for.

collect_externals : int

If set then the value is replaced with an array containing the things that were visited but turned out to have external references (within the limited lookahead).

collect_direct_externals : int

If set then the value is replaced with an array containing the things found during the lookahead that (appears to) have direct external references. This list is a subset of the collect_externals list. It is useful if you get unexpected global references to your data structure which you want to track down.

collect_stats : int

If this is nonzero then the mapping is extended with more elements containing statistics from the search; see below.

When the collect_stats flag is set, the mapping is extended with these elements:

internal : int

Number of things that were marked internal and hence memory counted. It includes the things given as arguments.

cyclic : int

Number of things that were marked internal only after resolving cycles.

external : int

Number of things that were visited through the lookahead but were found to be external.

visits : int

Number of times things were visited in total. This figure includes visits to various internal things that aren't visible from the pike level, so it might be larger than what is apparently motivated by the numbers above.

revisits : int

Number of times the same things were revisited. This can occur in the lookahead when a thing is encountered through a shorter path than the one it first got visited through. It also occurs in resolved cycles. Like visits, this count can include things that aren't visible from pike.

rounds : int

Number of search rounds. This is usually 1 or 2. More rounds are necessary only when blocked types turn out to be (acyclic) internal, so that they need to be counted and recursed anyway.

work_queue_alloc : int

The number of elements that were allocated to store the work queue which is used to keep track of the things to visit during the lookahead. This is usually bigger than the maximum number of things the queue actually held.

size : int

The memory occupied by the internal things. This is the same as the normal return value, but it's put here too for convenience.

Parameter things

One or more things to count memory size for. Only things passed by reference are allowed, except for functions which are forbidden because a meaningful size calculation can't be done for them.

Integers are allowed because they are bignum objects when they become sufficiently large. However, passing an integer that is small enough to fit into the native integer type will return zero.

Returns

Returns the number of bytes occupied by the counted things. If the return_count option is set then the number of things are returned instead.

Note

The result of Pike.count_memory(0,a,b) might be larger than the sum of Pike.count_memory(0,a) and Pike.count_memory(0,b) since a and b together might reference things that aren't referenced from anywhere else.

Note

It's possible that a string that is referenced still isn't counted, because strings are always shared in Pike and the same string may be in use in some unrelated part of the program.


Methodgc_parameters

mapping(string:float) gc_parameters(void|mapping(string:mixed) params)

Description

Set and get various parameters that control the operation of the garbage collector. The passed mapping contains the parameters to set. If a parameter is missing from the mapping, the current value will be filled in instead. The same mapping is returned. Thus an empty mapping, or no argument at all, causes a mapping with all current settings to be returned.

The following parameters are recognized:

"enabled" : int

If this is 1 then the gc is enabled as usual. If it's 0 then all automatically scheduled gc runs are disabled and the parameters below have no effect, but explicit runs through the gc function still works as usual. If it's -1 then the gc is completely disabled so that even explicit gc calls won't do anything.

"garbage_ratio_low" : float

As long as the gc time is less than time_ratio below, aim to run the gc approximately every time the ratio between the garbage and the total amount of allocated things is this.

"time_ratio" : float

When more than this fraction of the time is spent in the gc, aim for garbage_ratio_high instead of garbage_ratio_low.

"garbage_ratio_high" : float

Upper limit for the garbage ratio - run the gc as often as it takes to keep it below this.

"min_gc_time_ratio" : float

This puts an upper limit on the gc interval, in addition to the factors above. It is specified as the minimum amount of time spent doing gc, as a factor of the total time. The reason for this limit is that the current amount of garbage can only be measured in a gc run, and if the gc starts to run very seldom due to very little garbage, it might get too slow to react to an increase in garbage generation. Set to 0.0 to turn this limit off.

"average_slowness" : float

When predicting the next gc interval, use a decaying average with this slowness factor. It should be a value between 0.0 and 1.0 that specifies the weight to give to the old average value. The remaining weight up to 1.0 is given to the last reading.

"pre_cb" : function(:void)

This function is called when the gc starts.

"post_cb" : function(:void)

This function is called when the mark and sweep pass of the gc is done.

"destruct_cb" : function(object, int, int:void)

This function is called once for each object that is part of a cycle just before the gc will destruct it. The arguments are:

The object to be destructed.

The reason for it being destructed. One of:

Object.DESTRUCT_CLEANUP

Destructed during exit.

Object.DESTRUCT_GC

Destructed during normal implicit or explicit gc().

The number of references it had.

"done_cb" : function(int:void)

This function is called when the gc is done and about to exit. The argument is the same value as will be returned by gc().

See also

gc, Debug.gc_status


Methodget_first_arg_type

type|zeroget_first_arg_type(typefun_type)

Description

Check if a function of the type fun_type may be called with an argument, and return the type of that argument.

Returns

Returns the expected type of the first argument to the function.

Returns 0 (zero) if a function of the type fun_type may not be called with any argument, or if it is not callable.


Methodget_return_type

type|zeroget_return_type(typefun_type)
type|zeroget_return_type(typefun_type, mappingstate)

Description

Check what a function of the type fun_type will return if called with no further arguments.

Parameter state

State mapping. This mapping may be used by attribute handlers to store state between different arguments. Note that attribute handlers may alter the contents of the mapping.

Returns

Returns the type of the returned value on success

Returns 0 (zero) on failure.


Methodget_runtime_info

mapping(string:int|string) get_runtime_info()

Description

Get information about the Pike runtime.

Returns

Returns a mapping with the following content:

"bytecode_method" : string

A string describing the bytecode method used by the Pike interpreter.

"abi" : int

The number of bits in the ABI. Usually 32 or 64.

"native_byteorder" : int

The byte order used by the native cpu. Usually 1234 (aka little endian) or 4321 (aka bigendian).

"int_size" : int

The number of bits in the native integer type. Usually 32 or 64.

"time_size" : int

The number of bits in the native time_t type. This is typically the same value as "int_size".

"float_size" : int

The number of bits in the native floating point type. Usually 32 or 64.

"auto_bignum" : int(1)

Integers larger than the native size are now always automatically converted into bignums.


Methodget_type_attributes

array(string) get_type_attributes(typet)

Description

Get the attribute markers for a type.

Returns

Returns an array with the attributes for the type t.

See also

get_return_type(), get_first_arg_type()


Methodidentify_cycle

array(mixed) identify_cycle(mixedx)

Description

Identify reference cycles in Pike datastructures.

This function is typically used to identify why certain datastructures need the gc to run to be freed.

Parameter x

Value that is believed to be involved in a reference cycle.

Returns
zero

Returns UNDEFINED if x is not member of a reference cycle.

array(mixed)

Otherwise returns an array identifying a cycle with x as the first element, and where the elements refer to each other in order, and the last element refers to the first.


Methodimplicit_gc_real_time

intimplicit_gc_real_time(void|intnsec)

Description

Returns the total amount of real time that has been spent in implicit GC runs. The time is normally returned in microseconds, but if the optional argument nsec is nonzero it's returned in nanoseconds.

See also

Debug.gc_status


Methodlow_check_call

type|zerolow_check_call(typefun_type, typearg_type)
type|zerolow_check_call(typefun_type, typearg_type, intflags)
type|zerolow_check_call(typefun_type, typearg_type, intflags, mappingstate)
type|zerolow_check_call(typefun_type, typearg_type, intflags, mappingstate, mixedval)

Description

Check whether a function of type fun_type may be called with a first argument of type arg_type.

Parameter flags

The following flags are currently defined:

1

Strict types. Fail if not all possible values in arg_type are valid as the first argument to fun_type.

2

Last argument. arg_type is the last argument to fun_type.

3

Both strict types and last argument as above.

Parameter state

State mapping. This mapping may be used by attribute handlers to store state between different arguments. Note that attribute handlers may alter the contents of the mapping.

Parameter val

Value of the argument if known.

Returns

Returns a continuation type on success.

Returns 0 (zero) on failure.


Methodsoft_cast

type|zerosoft_cast(typeto, typefrom)

Description

Return the resulting type from a soft cast of from to to.

Returns

Returns UNDEFINED if the cast is invalid.

Note

The return value for the invalid case may in the future change to __unknown__.


Methodswitch_lookup

intswitch_lookup(array|mappingswitch_table, mixedval)

Description

Lookup a switch-case.

Parameter switch_table

Lookup table as generated by the compiler.

Parameter val

Value to lookup.

Returns

Returns the entry number (ie >= 0) if val was found in switch_table, and the binary inverse of the next entry number (ie < 0) if it was not found.

Class Pike.Annotation

Description

This class describes the API that the compiler expects for the annotation syntax.

Note

Classes implementing this API typically need to be marked constant.

See also

Annotations


Methodend_pass

optionalvoidend_pass(intpass, programprog, CompilerEnvironment.PikeCompilercompiler)

Description

Callback called by the compiler when it is finishing a compilation pass.

Parameter pass

Compilation pass.

Parameter prog

Program being compiled.

Parameter compiler

CompilerEnvironment.PikeCompiler state for the compiler.

Class Pike.BacktraceFrame


Method_is_type

bool res = is_type(Pike.BacktraceFrame())

Description

This object claims to be an array for backward compatibility.


Method_sizeof

int(3..)sizeof(Pike.BacktraceFramearg)


Method_sprintf

stringsprintf(stringformat, ... Pike.BacktraceFramearg ... )


Method`[]

mixed res = Pike.BacktraceFrame()[ index ]

Description

The BacktraceFrame object can be indexed as an array.


Method`[]=

Pike.BacktraceFrame()[ index ] = value

Class Pike.DestructImmediate

Description

An empty class that can be inherited to get the PROGRAM_DESTRUCT_IMMEDIATE flag set.

See also

InhibitDestruct

Class Pike.FakeObject

Description

Used as a place holder in eg backtraces for objects that are unsuitable to have references to in backtraces.

Examples of such objects are instances of Thread.MutexKey, and Nettle.Cipher.State.

See also

backtrace()

Class Pike.InhibitDestruct

Description

This is a class that implements a way to temporarily inhibit destruction by explicit calls of destruct().

This is mostly useful as a mix-in for modules implemented in C or similar.

All symbols in the class are either protected or private in order to affect users minimally.

See also

DestructImmediate


Method_destruct

bool_destruct(int|voidreason)

Description

Returns 1 when inhibit_destruct() has been called more times than permit_destruct().

See also

inhibit_destruct(), permit_destruct(), destruct(), lfun::_destruct()


Methodinhibit_destruct

voidinhibit_destruct()

Description

Inhibit explicit destruction of this object.

See also

permit_destruct(), _destruct(), destruct(), lfun::_destruct()


Methodpermit_destruct

voidpermit_destruct()

Description

Allow explicit destruction of this object again.

See also

inhibit_destruct(), _destruct(), destruct(), lfun::_destruct()

Class Pike.LiveBacktraceFrame

Description

A BacktraceFrame which retains access to the running code.

This means that unless the corresponding thread running the code is halted (or similar), the values in the fields contained in this object may change at any time.

On the other hand it allows for inspection and altering of the local variables (if any) belonging to the frame. Typical use of this would be for debugging.

See also

BacktraceFrame


Method_is_type

bool res = is_type(Pike.LiveBacktraceFrame())

Description

This object claims to be an array for backward compatibility.


Method_sizeof

int(3..)sizeof(Pike.LiveBacktraceFramearg)


Method`[]

mixed res = Pike.LiveBacktraceFrame()[ index ]

Description

The BacktraceFrame object can be indexed as an array.

Class Pike.MasterCodec

Description

This is a bare-bones codec that is used when loading a dumped master.

See also

Codec


Methoddecode_object

objectdecode_object(objectobj, mixeddata)

Description

Calls obj->_decode(data).


Methodfunctionof

mixedfunctionof(mixedsymbol)

Description

Look up a function in all_constants().


Methodobjectof

mixedobjectof(mixedsymbol)

Description

Look up an object in all_constants().


Methodprogramof

mixedprogramof(mixedsymbol)

Description

Look up a program in all_constants().

Class Pike.PollBackend

Description

Backend implemented with poll(2) (SVr4, POSIX).

See also

Backend


Inherit__Backend

inherit __Backend : __Backend


Method`()

float|int(0) res = Pike.PollBackend()()

Description

Perform one pass through the backend.

Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.

Parameter sleep_time

Wait at most sleep_time seconds. The default when unspecified or the integer 0 is no time limit.

Returns

If the backend did call any callbacks or call outs then the time spent in the backend is returned as a float. Otherwise the integer 0 is returned.

See also

Pike.DefaultBackend, main()

Class Pike.PollDeviceBackend

Description

Backend implemented with /dev/poll (Solaris and OSF/1), epoll(2) (Linux) or kqueue(2) (MacOS X, FreeBSD, OpenBSD, etc).

See also

Backend


Inherit__Backend

inherit __Backend : __Backend


Method`()

float|int(0) res = Pike.PollDeviceBackend()()

Description

Perform one pass through the backend.

Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.

Parameter sleep_time

Wait at most sleep_time seconds. The default when unspecified or the integer 0 is no time limit.

Returns

If the backend did call any callbacks or call outs then the time spent in the backend is returned as a float. Otherwise the integer 0 is returned.

See also

Pike.DefaultBackend, main()


Methodenable_core_foundation

intenable_core_foundation(boolenable)

Description

On systems with CoreFoundation (OSX, iOS, etc), use CoreFoundation to poll for events. This enables system level technologies that rely on CoreFoundation Runloops to function properly.

Parameter enable

enable or disable this functionality

Returns

the previous value of this setting.


Methodenable_external_runloop

intenable_external_runloop(boolenable)

Description

On systems with CoreFoundation (OSX, iOS, etc), delegate running of the Pike Backend to the main runloop of the process (such as a Cocoa application's NSRunLoop).

Enabling the external runloop allows Pike callouts and callback-based I/O to function normally while greatly reducing cpu utilization compared to running the external runloop manually.

Parameter enable

enable or disable this functionality

Returns

the previous value of this setting.


Methodquery_core_foundation_enabled

intquery_core_foundation_enabled()

Description

On systems with CoreFoundation (OSX, iOS, etc), indicate whether CoreFoundation is being used by this backend to poll for events.

Returns

the current state of CoreFoundation polling: 1=enabled, 0=disabled


Methodset_signal_event_callback

optionalvoidset_signal_event_callback(intsignum, function(:void) cb)

Description

Request cb to be called from the backend when the signal signum is received.

Note

This function is a noop except for the kqueue case.

Note

Caveat emptor: Unlikely to work.

See also

signal()

Class Pike.SelectBackend

Description

Backend based on the classic select(2) system call from BSD.


Inherit__Backend

inherit __Backend : __Backend


Method`()

float|int(0) res = Pike.SelectBackend()()

Description

Perform one pass through the backend.

Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.

Parameter sleep_time

Wait at most sleep_time seconds. The default when unspecified or the integer 0 is no time limit.

Returns

If the backend did call any callbacks or call outs then the time spent in the backend is returned as a float. Otherwise the integer 0 is returned.

See also

Pike.DefaultBackend, main()

Class Pike.SmallBackend

Annotations
@@Pike.Annotations.Implements(Pike.__Backend)
Description

This is the most suitable backend implementation if you only want to monitor a small number of Stdio.File objects.


Inherit__Backend

inherit Pike.__Backend : __Backend

Class Pike.Watchdog

Description

A Watchdog that ensures that the process is not hung for an extended period of time. The definition of 'hung' is: Has not used the default backend.

An important and useful side-effect of this class is that the process will start to respond to kill -QUIT by printing a lot of debug information to stderr, including memory usage, and if pike is compiled with profiling, the CPU used since the last time kill -QUIT was called.


Methodadd_debug

voidadd_debug(function(void:void) f)

Description

The function f will be called if the watchdog triggers, before the normal watchdog output is written.


Methodadd_probe

voidadd_probe(function(void:bool) f)

Description

Add additional functions to be called each time the watchdog is checked. If any of the probes return false, the watchdog will trigger.


Methodalarm_alarm_alarm

voidalarm_alarm_alarm()

Description

Explicitly trigger the watchdog, if enough CPU time has been used. This is not normally called manually.


Methodcreate

Pike.WatchdogPike.Watchdog(intt)

Description

Create a new watchdog, with the intended delay.

Even though the actual watchdog functionality is currently not available on systems without sigalarm, such as Windows, the functionality can still be triggered by adding probe functions

See also

add_probe() and set_delay()


Methodping

voidping()

Description

Tell the watchdog that all is well, and the CPU is not really blocked. Can be used during long calculations that block the normal backend, note that this basically bypasses the main functionality of the watchdog, that is, detecting blocked backend threads.


Methodprint_debug

voidprint_debug()

Description

Output thread stacktraces, memory and profiling (if available) debug information to stderr.


Methodreally_trigger_watchdog_promise

voidreally_trigger_watchdog_promise()

Description

Really trigger the watchdog, killing the current process. This is not normally called manually.


Methodset_delay

voidset_delay(intt)

Description

Set the watchdog interval to t seconds.

The change will not take effect until the previous probe has been triggered.

Class Pike.__Backend

Description

Base class for the various backend implementations.

Implements callback registration functions and defines the main backend APIs.


Variablebefore_callback
Variableafter_callback

function(Backend:void) Pike.__Backend.before_callback
function(Backend:void) Pike.__Backend.after_callback

Description

If set, these are called just before and after the backend waits for an event.

If an error is thrown from these callbacks then it is reported using master()->handle_error() - it doesn't interrupt the operation of the backend.


Method_do_call_outs

int_do_call_outs()

Description

Do all pending call_outs.

This function runs all pending call_outs that should have been run if Pike returned to the backend. It should not be used in normal operation.

As a side-effect, this function sets the value returned by time(1) to the current time.

Returns

Zero if no call outs were called, nonzero otherwise.

See also

call_out(), find_call_out(), remove_call_out()


Method`()

float|int(0) res = Pike.__Backend()()

Description

Perform one pass through the backend.

Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.

Parameter sleep_time

Wait at most sleep_time seconds. The default when unspecified or the integer 0 is no time limit.

Returns

If the backend did call any callbacks or call outs then the time spent in the backend is returned as a float. Otherwise the integer 0 is returned.

Note

If multiple threads concurrently call this function, then:

  • One of the threads will be the controlling thread.

  • All callbacks will be called from the controlling thread.

  • All threads will be woken up when the controlling thread is done. This may be prematurely if the controlling thread had a shorter timeout.

Note

The backend may also be woken up prematurely if the set of events to monitor is changed.

Note

Multiple concurrent calls was not supported prior to Pike 8.0.

See also

Pike.DefaultBackend, main()


Methodadd_file

voidadd_file(Stdio.File|Stdio.FILEf)

Description

Register a file to be handled by this backend.

Parameter f

File to register.

Registers f to be handled by this backend. This simply does f->set_backend(backend) where backend is this object.

See also

Pike.DefaultBackend, main()


Methodcall_out

arraycall_out(function(:void) f, float|intdelay, mixed ... args)

Description

Make a delayed call to a function.

call_out() places a call to the function f with the argument args in a queue to be called in about delay seconds.

If f returns -1, no other call out or callback will be called by the backend in this round. I.e. `() will return right away. For the main backend that means it will immediately start another round and check files and call outs anew.

Returns

Returns a call_out identifier that identifies this call_out. This value can be sent to eg find_call_out() or remove_call_out().

See also

remove_call_out(), find_call_out(), call_out_info(), CallOut


Methodcall_out_info

array(array) call_out_info()

Description

Get info about all call_outs.

This function returns an array with one entry for each entry in the call out queue. The first in the queue will be at index 0. Each index contains an array that looks like this:

Array
inttime_left

Time remaining in seconds until the call_out is to be performed.

int(0)zero

Used to be the object that scheduled the call_out.

function(:void) fun

Function to be called.

mixed ... args

Arguments to the function.

See also

call_out(), find_call_out(), remove_call_out()


Methodcreate

Pike.__BackendPike.__Backend()


Methodexecuting_thread

Thread.Threadexecuting_thread()
intexecuting_thread()

Description

Return the thread currently executing in the backend. I.e. the thread that has called `() and hasn't exited from that call. Zero is returned if there's no thread in the backend.

If Pike is compiled without thread support then 1 is returned if we're inside the backend, 0 otherwise.


Methodfind_call_out

intfind_call_out(function(:void) f)
intfind_call_out(arrayid)

Description

Find a call out in the queue.

This function searches the call out queue. If given a function as argument, it looks for the first call out scheduled to that function.

The argument can also be a call out id as returned by call_out(), in which case that call_out will be found (Unless it has already been called).

Returns

find_call_out() returns the remaining time in seconds before that call_out will be executed. If no call_out is found, zero_type(find_call_out(f)) will return 1.

See also

call_out(), remove_call_out(), call_out_info()


Methodget_stats

mapping(string:int) get_stats()

Description

Get some statistics about the backend.

Returns

Returns a mapping with the follwoing content:

"num_call_outs" : int

The number of active call-outs.

"call_out_bytes" : int

The amount of memory used by the call-outs.


Methodid

intid()

Description

Return an integer that uniquely identifies this backend. For the default backend that integer is 0.


Methodremove_call_out

intremove_call_out(function(:void) f)
intremove_call_out(arrayid)

Description

Remove a call out from the call out queue.

This function finds the first call to the function f in the call_out queue and removes it. You can also give a call out id as argument (as returned by call_out()).

Returns

The remaining time in seconds left to that call out will be returned. If no call_out was found, zero_type(remove_call_out(f)) will return 1.

See also

call_out_info(), call_out(), find_call_out()

Class Pike.__Backend.CallOut

Description

Represents a single call_out in the call_out list.

See also

call_out()


Variableargs

protectedarray Pike.__Backend.CallOut.args

Description

The array containing the function and arguments.


Methodcreate

Pike.__Backend.CallOutPike.__Backend.CallOut(int|floatseconds, mixedfun, mixed ... args)

Description

Start a new call out.

This is the low-level implementation of call_out().

call_out() is essentially implemented as:

array call_out(mixed fun,int|float seconds,mixed ... args){return CallOut(seconds, fun, @args)->args;}
See also

call_out()

Module Pike.Annotations

Description

This module contains the set of annotations that the compiler and runtime care about.


ConstantAutoCodec

constant Pike.Annotations.AutoCodec

Description

This Annotation causes the compiler to automatically add an implementation of _encode() that returns an array with suitable arguments to lfun::create.

Note

This annotation is only useful for classes that use the implicit create()-syntax, or have a create() that doesn't need any arguments.


ConstantInherited

constant Pike.Annotations.Inherited

Description

This Annotation informs the compiler that any Annotation marked with it is to be inherited. The default is that annotations on classes are not inherited.


ConstantOverride

constant Pike.Annotations.Override

Description

This Annotation informs the compiler that any symbol marked with it is expected to also have been inherited.

Class Pike.Annotations.AutoCodecClass

Description

This is the class that implements the AutoCodec annotation.


InheritAnnotation

inherit Annotation : Annotation

Class Pike.Annotations.Implements

Description

This annotation causes the compiler to validate that the annotated class implements the specified API.


InheritAnnotation

inherit Pike.Annotation : Annotation

Class Pike.Annotations.InheritedClass

Description

This is the class for the Inherited annotation.


InheritAnnotation

inherit Pike.Annotation : Annotation

Class Pike.Annotations.OverrideClass

Description

This is the class for the Override annotation.


InheritAnnotation

inherit Pike.Annotation : Annotation

Module Pike.DefaultBackend

Description

This is the Backend object that files and call_outs are handled by by default.

This is also the Backend object that will be used if main() returns -1.

See also

Backend, Stdio.File()->set_nonblocking(), call_out()

Module Pike.Lazy

Description

This module provides lazy resolving of functions.

Example

The expression Pike.Lazy.Standards.JSON.decode will evaluate to Standards.JSON.decode, but the resolution (and associated compilation) of Standards.JSON will be delayed until the first time that the expression is evaluated.

Note

Note that this destroys type information and delays resolver errors.

Typical use is to break circular compilation dependencies between modules.

Class Pike.Lazy.LazyValue


Variablepath

string Pike.Lazy.LazyValue.path


Method__create__

protectedlocalvoid__create__(stringpath)


Methodcreate

Pike.Lazy.LazyValuePike.Lazy.LazyValue(stringpath)

Module Pipe

Description

Single socket output.

Regular file output and (multiple, adding) socket output with no mmap input.

Multiple socket output without regular file output illegal.

Note

It is preferable to use the Shuffler API, it is significantly more flexible.

Class Pipe.pipe

Description

Concatenation pipe.


Methodbytes_sent

intbytes_sent()

Description

Return the number of bytes sent.


Methodfinish

voidfinish()

Description

Terminate and reinitialize the pipe.


Methodinput

voidinput(objectobj)

Description

Add an input file to this pipe.


Methodoutput

voidoutput(objectobj, int|voidstart_pos)

Description

Add an output file object.


Methodset_done_callback

voidset_done_callback(void|function(mixed:mixed) done_cb, void|mixedid)

Description

Set the callback function to be called when all the outputs have been sent.


Methodset_output_closed_callback

voidset_output_closed_callback(void|function(mixed, object:mixed) close_cb, void|mixedid)

Description

Set the callback function to be called when one of the outputs has been closed from the other side.


Methodstart

voidstart()

Description

Start sending the input(s) to the output(s).


Methodversion

stringversion()

Description

Return the version of the module.


Methodwrite

voidwrite(stringbytes)

Description

Add an input string to this pipe.

Module Process


Methoddaemon

voiddaemon(intnochdir, intnoclose, void|mapping(string:string|Stdio.File) modifiers)

Description

A function to run current program in the background.

Parameter nochdir

If 0 the process will continue to run in / or the directory dictadet by modifiers.

Parameter noclose

If this is not 0 the process will keep current file descriptors open.

Parameter modifiers

Optional extra arguments. The parameters passed in this mapping will override the arguments nochdir and noclose.

"cwd" : string

Change current working directory to this directory.

"stdin" : string|Stdio.File

If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard input to the process. If this is a Stdio.File object the process will use this as standard input.

"stdout" : string|Stdio.File

If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard output to the process. If this is a Stdio.File object the process will use this as standard output.

"stderr" : string|Stdio.File

If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard error to the process. If this is a Stdio.File object the process will use this as standard error.

See also

System.daemon

Note

This function only works on UNIX-like operating systems.

Example

/* close all fd:s and cd to '/' */ Process.daemon(0, 0);

/* Do not change working directory. Write stdout to a file called access.log and stderr to error.log. */ Process.daemon(1, 0, ([ "stdout": "access.log", "stderr": "error.log" ]) );


Methodexec

intexec(stringfile, string ... foo)


Methodget_forkd_default

boolget_forkd_default()

Description

Get the default value for the "forkd" modifier to Process.

Note

The default default value is 0 (zero).

See also

set_forkd_default(), Process()->create()


Methodpopen

stringpopen(stringcommand)

Description

Executes command as a shell statement ("/bin/sh -c  command" for Unix, "cmd /c command" for Windows), waits until it has finished and returns the result as a string.

See also

system, spawn

Deprecated

Replaced by Process.Process.


Methodpopen

Stdio.FILEpopen(stringcommand, stringmode)

Description

Open a "process" for reading or writing. The command is executed as a shell statement ("/bin/sh -c command" for Unix, "cmd /c command" for Windows). The parameter mode should be one of the following letters:

"r"

Open for reading. Data written by the process to stdout is available for read.

"w"

Open for writing. Data written to the file is available to the process on stdin.

See also

system, spawn

Deprecated

Replaced by Process.Process.


Methodrun

mappingrun(string|array(string) cmd, mapping|voidmodifiers)

Description

Easy and lazy way of using Process.Process that runs a process and returns a mapping with the output and exit code without having to make sure you read nonblocking yourself.

Parameter args

Either a command line array, as the command_args argument to create_process(), or a string that will be splitted into a command line array by calling split_quoted_string() in an operating system dependant mode.

Parameter modifiers

It takes all the modifiers Process.Process accepts, with the exception of stdout and stderr. Each must be either absent, or a function accepting a string; if present, the functions will be called whenever output is made on the corresponding stream, otherwise the data will be collected and returned in the result mapping.

If modifiers->stdin is set to a string it will automatically be converted to a pipe that is fed to stdin of the started process.

See also

Process.Processcreate_process

Returns
"stdout" : string

Everything the process wrote on stdout, unless a stdout function was provided.

"stderr" : string

Everything the process wrote on stderr, similarly.

"exitcode" : int

The process' exitcode.

Note

As the entire output of stderr and stdout is stored in the returned mapping it could potentially grow until memory runs out. It is therefore advisable to set up rlimits if the output has a potential to be very large, or else provide functions to handle partial data.

Example

Process.run( ({ "ls", "-l" }) ); Process.run( ({ "ls", "-l" }), ([ "cwd":"/etc" ]) ); Process.run( "ls -l" ); Process.run( "awk -F: '{print $2}'", ([ "stdin":"foo:2\nbar:17\n" ]) ); Process.run( ({ "echo Output will be immediately written to stdout" }), ([ "stdout": lambda(string s) { write(s); }, "stderr": lambda(string e) { werror(e); } ]) );


Methodsearch_path

stringsearch_path(stringcommand)

Description

Search for the path to an executable.

Parameter command

Executable to search for.

Searches for command in the directories listed in the environment variable $PATH.

Returns

Returns the path to command if found, and 0 (zero) on failure.

Note

This function is NOT thread safe if the environment variable $PATH is being changed concurrently.

Note

In Pike 7.8.752 and earlier the environment variable $PATH was only read once.


Methodset_forkd_default

voidset_forkd_default(boolmode)

Description

Set the default value for the "forkd" modifier to Process.

Note

The default default value is 0 (zero).

See also

get_forkd_default(), Process()->create()


Methodsh_quote

stringsh_quote(strings)


Methodspawn

__deprecated__Processspawn(stringcommand, void|Stdio.Streamstdin, void|Stdio.Streamstdout, void|Stdio.Streamstderr)

Description

Spawns a process that executes command as a command shell statement ("/bin/sh -c command" for Unix, "cmd /c  command" for Windows).

Parameter stdin
Parameter stdout
Parameter stderr

Stream objects to use as standard input, standard output and standard error, respectively, for the created process. The corresponding streams for this process are used for those that are left out.

Returns

Returns a Process.Process object for the created process.

See also

system, popen

Deprecated

Replaced by Process.Process.


Methodspawn_pike

Processspawn_pike(array(string) argv, void|mapping(string:mixed) options, array(string)|voidlauncher)

Description

Spawn a new pike process similar to the current.

Parameter argv

Arguments for the new process.

Parameter options

Process creation options. See Process.Process for details. May also specify "add_predefines", "add_program_path", or "add_include_path" in order to include these components in command path (module path is included by default.)

Parameter launcher

Optional launcher prefix command used to spawn the pike binary.

When used this is typically something like ({ "/usr/bin/valgrind" }).

Defaults to the empty array.

See also

Process.Process


Methodsplit_quoted_string

array(string) split_quoted_string(strings, bool|voidnt_mode)

Description

Splits the given string into a list of arguments, according to common (i.e. /bin/sh-based) command line quoting rules:

  • Sequences of whitespace, i.e. space, tab, \n or \r, are treated as argument separators by default.

  • Single or double quotes (' or ") can be used around an argument to avoid whitespace splitting inside it. If such quoted strings are used next to each other then they get concatenated to one argument; e.g. a"b"'c' becomes a single argument abc.

  • Backslash (\) can be used in front of one of the space or quote characters mentioned above to treat them literally. E.g. x\ y is a single argument with a space in the middle, and x\"y is a single argument with a double quote in the middle.

  • A backslash can also be used to quote itself; i.e. \\ becomes \.

  • Backslashes in front of other characters are removed by default. However, if the optional nt_mode flag is set then they are retained as-is, to work better with Windows style paths.

  • Backslashes are treated literally inside quoted strings, with the exception that \" is treated as a literal " inside a "-quoted string. It's therefore possible to include a literal " in a "-quoted string, as opposed to '-quoted strings which cannot contain a '.


Methodsystem

__deprecated__intsystem(stringcommand, void|Stdio.Streamstdin, void|Stdio.Streamstdout, void|Stdio.Streamstderr)

Description

Executes command as a shell statement ("/bin/sh -c  command" for Unix, "cmd /c command" for Windows), waits until it has finished and returns its return value.

Parameter stdin
Parameter stdout
Parameter stderr

Stream objects to use as standard input, standard output and standard error, respectively, for the created process. The corresponding streams for this process are used for those that are left out.

Returns

Returns the exit code for the subprocess on normal completion. Returns the negation of the last signal code if it terminated due to a signal.

Note

In Pike 8.0 and earlier this function returned the result straight from Process.Process()->wait().

Deprecated

Replaced by Process.Process.

See also

spawn, popen

Class Process.ForkdDecoder

Description

Decoder for data received by Tools.Standalone.forkd.

See also

ForkdEncoder


Variablefds

array(Stdio.Fd) Process.ForkdDecoder.fds


Method__create__

protectedlocalvoid__create__(array(Stdio.Fd) fds)


Methodcreate

Process.ForkdDecoderProcess.ForkdDecoder(array(Stdio.Fd) fds)

Class Process.ForkdEncoder

Description

Encoder for data to be sent to Tools.Standalone.forkd.

See also

ForkdDecoder


Variableremote_fd

Stdio.File Process.ForkdEncoder.remote_fd


Method__create__

protectedlocalvoid__create__(Stdio.Fileremote_fd)


Methodcreate

Process.ForkdEncoderProcess.ForkdEncoder(Stdio.Fileremote_fd)

Class Process.Process

Description

Slightly polished version of create_process.

In addition to the features supported by create_process, it also supports:

  • Callbacks on timeout and process termination.

  • Using Tools.Standalone.forkd via RPC to spawn the new process.

See also

create_process, Tools.Standalone.forkd


Inheritcreate_process

inherit create_process : create_process

Description

Based on create_process.


Methodcreate

Process.ProcessProcess.Process(string|array(string) command_args, mapping(string:mixed)|voidmodifiers)

Parameter command_args

Either a command line array, as the command_args argument to create_process(), or a string that will be splitted into a command line array by calling split_quoted_string() in an operating system dependant mode.

Parameter modifiers

In addition to the modifiers that create_process accepts, this object also accepts

"read_callback" : function(Process:void)

This callback is called when there is data to be read from the process.

"timeout_callback" : function(Process:void)

This callback is called if the process times out.

"timeout" : int

The time it takes for the process to time out. Default is 15 seconds.

"forkd" : bool

Use Tools.Standalone.forkd to actually spawn the process.

Note

The default value for the "forkd" modifier may be set via set_forkd_default().

See also

create_process, create_process()->create(), split_quoted_string(), Tools.Standalone.forkd, set_forkd_default(), get_forkd_default()

Class Process.Spawn


Methodcreate

Process.SpawnProcess.Spawn(stringcmd, void|array(string) args, void|mapping(string:string) env, string|voidcwd, void|array(Stdio.File|void) ownpipes, void|array(Stdio.File|void) fds_to_close)


Methodkill

intkill(intsignal)


Methodwait

intwait()

Class Process.TraceProcess

Description

Class that enables tracing of processes.

The new process will be started in stopped state. Use cont() to let it start executing.

Note

This class currently only exists on systems that implement ptrace().


Inheritcreate_process

inherit create_process : create_process


Methodcont

voidcont(int|voidsignal)

Description

Allow a traced process to continue.

Parameter signal

Deliver this signal to the process.

Note

This function may only be called for stopped processes.

See also

wait()


Methodexit

voidexit()

Description

Cause the traced process to exit.

Note

This function may only be called for stopped processes.

See also

cont(), wait()


Methodwait

intwait()

Description

Waits for the process to stop.

Returns
(0..)

The exit code of the process.

-1

The process was killed by a signal.

-2

The process has stopped.

See also

create_process::wait()

Class Process.TraceProcess.Registers

Description

Interface to the current register contents of a stopped process.

See also

TraceProcess


Method`[]

int res = Process.TraceProcess.Registers()[ regno ]

Description

Get the contents of register regno.

Class Process.create_process

Description

This is the recommended and most portable way to start processes in Pike. The process object is a pike abstraction of the running system process, with methods for various process housekeeping.

See also

Process


Constantlimit_value

constant Process.create_process.limit_value

Description

Each limit_value may be either of:

integer

sets current limit, max is left as it is.

mapping

([ "hard":int, "soft":int ]) Both values are optional, hard <= soft.

array

({ hard, soft }), both can be set to the string "unlimited". A value of -1 means 'keep the old value'.

string

The string "unlimited" sets both the hard and soft limit to unlimited


Methodcreate

Process.create_processProcess.create_process(array(string) command_args, void|mappingmodifiers)

Parameter command_args

The command name and its command-line arguments. You do not have to worry about quoting them; pike does this for you.

Parameter modifiers

This optional mapping can can contain zero or more of the following parameters:

"callback" : function(Process.Process:void)

Function called when the created process changes state.

Note that this function is called in a signal handler context, which means that it may be called by any thread at any time after the child process has changed state, and is thus not only called by the main thread when the main backend is idle. Indeed, you can specify a callback even if your program does not use a backend.

"cwd" : string|Stdio.Fd

Execute the command in another directory than the current directory of this process. Please note that if the command is given is a relative path, it will be relative to this directory rather than the current directory of this process.

Note also that the path is relative to the "chroot" if used.

Note that support for the Stdio.Fd variant is not present prior to Pike 9.0, and is only present on some OSes.

"chroot" : string|Stdio.Fd

Chroot to this directory before executing the command.

Note that the current directory will be changed to "/" in the chroot environment, unless "cwd" above has been set.

Note that support for the Stdio.Fd variant is not present prior to Pike 9.0, and is only present on some OSes.

"stdin" : Stdio.File

These parameters allows you to change the standard input, output and error streams of the newly created process. This is particularly useful in combination with Stdio.File.pipe.

"stdout" : Stdio.File
"stderr" : Stdio.File
"env" : mapping(string:string)

This mapping will become the environment variables for the created process. Normally you will want to only add or change variables which can be achived by getting the environment mapping for this process with getenv. See the examples section.

"uid" : int|string

This parameter changes which user the new process will execute as. Note that the current process must be running as UID 0 to use this option. The uid can be given either as an integer as a string containing the login name of that user.

The "gid" and "groups" for the new process will be set to the right values for that user unless overriden by options below.

(See setuid and getpwuid for more info.)

"gid" : int|string

This parameter changes the primary group for the new process. When the new process creates files, they will will be created with this group. The group can either be given as an int or a string containing the name of the group. (See setuid and getgrgid for more info.)

"setsid" : bool|Stdio.File

Set this to 1 to create a new session group. It is also possible to set it to a File object, in which case a new session group will be created with this file as the controlling terminal.

"setgroups" : array(int|string)

This parameter allows you to the set the list of groups that the new process belongs to. It is recommended that if you use this parameter you supply at least one and no more than 16 groups. (Some system only support up to 8...) The groups can be given as gids or as strings with the group names.

"noinitgroups" : bool

This parameter overrides a behaviour of the "uid" parameter. If this parameter is used, the gid and groups of the new process will be inherited from the current process rather than changed to the approperiate values for that uid.

"priority" : string

This sets the priority of the new process, see set_priority for more info.

"nice" : int

This sets the nice level of the new process; the lower the number, the higher the priority of the process. Note that only UID 0 may use negative numbers.

"keep_signals" : bool

This prevents Pike from restoring all signal handlers to their default values for the new process. Useful to ignore certain signals in the new process.

"fds" : array(Stdio.File|int(0))

This parameter allows you to map files to filedescriptors 3 and up. The file fds[0] will be remapped to fd 3 in the new process, etc.

"rlimit" : mapping(string:limit_value)

There are two values for each limit, the soft limit and the hard limit. Processes that do not have UID 0 may not raise the hard limit, and the soft limit may never be increased over the hard limit. The indices of the mapping indicate what limit to impose, and the values dictate what the limit should be. (See also System.setrlimit)

"core" : limit_value

maximum core file size in bytes

"cpu" : limit_value

maximum amount of cpu time used by the process in seconds

"data" : limit_value

maximum heap (brk, malloc) size in bytes

"fsize" : limit_value

maximum size of files created by the process in bytes

"map_mem" : limit_value

maximum size of the process's mapped address space (mmap() and heap size) in bytes

"mem" : limit_value

maximum size of the process's total amount of available memory (mmap, heap and stack size) in bytes

"nofile" : limit_value

maximum number of file descriptors the process may create

"stack" : limit_value

maximum stack size in bytes

"conpty" : Stdio.File

Bind the process to the console associated with this pty slave. NT only.

Example

Process.create_process(({ "/usr/bin/env" }), (["env" : getenv() + (["TERM":"vt100"]) ]));

Example

//! Spawn a new process with the args @[args] and optionally a //! standard input if you provide such a @[Stdio.File] object. //! @returns //! Returns the new process and a pipe from which you can read //! its output. array(Process.Process|Stdio.File) spawn(Stdio.File|void stdin, string ... args) { Stdio.File stdout = Stdio.File(); mapping opts = ([ "stdout" : stdout->pipe() ]); if( stdin ) opts->stdin = stdin; return ({ Process.create_process( args, opts ), stdout }); }

Note

All parameters that accept both string or int input can be noticeably slower using a string instead of an integer; if maximum performance is an issue, please use integers.

Note

On NT the only supported modifiers are: "cwd", "conpty", "stdin", "stdout", "stderr" and "env". All other modifiers are silently ignored.

Note

Support for "callback" was added in Pike 7.7.

Note

Chroot changing directory to "/" was added in Pike 7.9.


Methodkill

boolkill(intsignal)

Description

Send a signal to the process.

Returns
1

Success.

0

Failure. errno() is set to EINVAL, EPERM or ESRCH.

Note

This function is only available on platforms that support signals.

See also

predef::kill()


Methodlast_signal

int(0..)last_signal()

Description

Returns the last signal that was sent to the process.


Methodpid

intpid()

Description

Returns the process identifier of the process.


Methodset_priority

intset_priority(stringpriority)

Description

Sets the priority of the process. priority is one of the strings

"realtime"
"highest"
"higher"
"high"
"normal"
"low"
"lowest"

Methodstatus

int(-1..2)status()

Description

Returns the status of the process:

-1

Unknown

0

Running

1

Stopped

2

Exited


Methodwait

intwait()

Description

Waits for the process to end.

Returns
(0..)

The exit code of the process.

-1

The process was killed by a signal.

-2

The process is stopped.

See also

TraceProcess()->wait()

Module Random

Class Random.AES128_CTR_DRBG

Description

Implements NIST SP800-90Ar1 pseudo random number generator CTR_DRBG using AES-128.

https://csrc.nist.gov/publications/detail/sp/800-90a/rev-1/final


InheritAES128_CTR_DRBG

inherit Nettle.AES128_CTR_DRBG : AES128_CTR_DRBG


InheritRandomInterface

inherit Builtin.RandomInterface : RandomInterface


Methodcreate

Random.AES128_CTR_DRBGRandom.AES128_CTR_DRBG(string(8bit)entropy, void|string(8bit)personalization)

Description

Instantiate a random generator without derivation function, with the given initial entropy and personalization.


Methodentropy_underflow

protectedvoidentropy_underflow()

Description

This method is called when a reseed is forced. By default new entropy is gethered from Random.System. Overload to change the default behaviour.

Class Random.Deterministic

Description

This class implements a detministic random generator by combining a Fortuna random generator with the Random.Interface. The generator is not reseeded after the initial seed.

In case of a process fork the random generators in both processes will continue to generate identical results.


InheritFortuna

inherit Nettle.Fortuna : Fortuna


InheritRandomInterface

inherit Builtin.RandomInterface : RandomInterface


Methodcreate

Random.DeterministicRandom.Deterministic(string(8bit)|intseed)

Description

Initialize the random generator with seed. The internal state is 256 bits, but all seed sizes are allowed.

Class Random.Fast

Description

This class implements a fast and secure random generator. The generator is a Fortuna PRNG that is fed additional entropy from the system RNG (or hardware RNG, if available) for every generated megabyte of data.

If a hardware RNG is present it will be used instead of Fortuna for random strings shorter than 48 bytes.

In case of a process fork it is possible that the random generators will produce identical results for up to one megabyte of generated data.


InheritFortuna

inherit Nettle.Fortuna : Fortuna


InheritRandomInterface

inherit Builtin.RandomInterface : RandomInterface

Class Random.Hardware

Description

This class implements a random generator based on the hardware generator available on some system. Currently only supports Intel RDRAND CPU extension.

In case of a process fork the generators in the two processes will generate independent random values.


InheritRandomInterface

inherit Builtin.RandomInterface : RandomInterface

Class Random.Interface

Description

This class implements the Pike predef::random API on top of a byte stream random source. This source should be implemented in the random_string method and will be called by random(int) for random input. random(int) is in turned called by all the other variants of random and applied to their use cases.

While it is possible to overload the random variants, care must be taken to not introduce any bias. The default implementation gathers enough bits to completely reach the limit value, and discards them if the result overshoots the limit.


InheritRandomInterface

inherit Builtin.RandomInterface : RandomInterface


Methodrandom

int(0..)random(int(0..)max)
floatrandom(floatmax)
mixedrandom(array|multisetx)
arrayrandom(mappingm)
mixedrandom(objecto)

Description

Implementation of predef::random.


Methodrandom_string

string(8bit)random_string(intlength)

Description

Prototype for the random source stream function. Must return exactly length bytes of random data.

Class Random.System

Description

This is the default implementation of the random functions. This is the Random.Interface combined with a system random source. On Windows this is the default crypto service while on Unix systems it is /dev/urandom.

In case of a process fork the generators in the two processes will generate independent random values.


InheritRandomSystem

inherit Builtin.RandomSystem : RandomSystem

Module Regexp


Inherit"___Regexp"

inherit "___Regexp" : "___Regexp"


Method`()

protectedSimpleRegexp`()(void|stringregexp)

Description

Convenience/compatibility method to get a SimpleRegexp object.


Methodmatch

boolmatch(stringregexp, stringdata)

Description

Calls Regexp.PCRE.Plain.match in a temporary regexp object. Faster to type but slower to run...


Methodreplace

stringreplace(stringregexp, stringdata, string|function(string:string) transform)

Description

Calls Regexp.PCRE.Plain.replace in a temporary regexp object. Faster to type but slower to run...


Methodsplit

arraysplit(stringregexp, stringdata)

Description

Calls Regexp.PCRE.Plain.split in a temporary regexp object. Faster to type but slower to run...


Methodsplit2

arraysplit2(stringregexp, stringdata)

Description

Calls Regexp.PCRE.Plain.split2 in a temporary regexp object. Faster to type but slower to run...

Class Regexp.SimpleRegexp

Description

This class implements the interface to a simple regexp engine with the following capabilities:

.Matches any character.
[abc]Matches a, b or c.
[a-z]Matches any character a to z inclusive.
[^ac]Matches any character except a and c.
(x)Matches x (x might be any regexp) If used with split, this also puts the string matching x into the result array.
x*Matches zero or more occurances of 'x' (x may be any regexp).
x+Matches one or more occurances of 'x' (x may be any regexp).
x|yMatches x or y. (x or y may be any regexp).
xyMatches xy (x and y may be any regexp).
^Matches beginning of string (but no characters).
$Matches end of string (but no characters).
\<Matches the beginning of a word (but no characters).
\>Matches the end of a word (but no characters).

Note that \ can be used to quote these characters in which case they match themselves, nothing else. Also note that when quoting these something in Pike you need two \ because Pike also uses this character for quoting.


Inherit_SimpleRegexp

inherit _SimpleRegexp : _SimpleRegexp


Method_encode
Method_decode

string(8bit)encode_value(Regexp.SimpleRegexpdata)
Regexp.SimpleRegexpdecode_value(string(8bit)data)

Description

Regexp objects can be encoded and decoded.

See also

encode_value, decode_value


Methodcreate

Regexp.SimpleRegexpRegexp.SimpleRegexp(stringre)

Description

When create is called, the current regexp bound to this object is cleared. If a string is sent to create(), this string will be compiled to an internal representation of the regexp and bound to this object for laters calls to e.g. match or split. Calling create() without an argument can be used to free up a little memory after the regexp has been used.


Methodmatch

intmatch(stringstr)

Description

Returns 1 if str matches the regexp bound to the regexp object. Zero otherwise.


Methodmatch

array(string) match(array(string) strs)

Description

Returns an array containing strings in strs that match the regexp bound to the regexp object.

Bugs

The current implementation doesn't support searching in strings containing the NUL character or any wide character.

See also

split


Methodreplace

stringreplace(stringin, string|function(string:string) transform)


Methodsplit

array(string) split(strings)

Description

Works as match, but returns an array of the strings that matched the subregexps. Subregexps are those contained in "( )" in the regexp. Subregexps that were not matched will contain zero. If the total regexp didn't match, zero is returned.

Bugs

You can currently only have 39 subregexps.

Bugs

The current implementation doesn't support searching in strings containing the NUL character or any wide character.

See also

match

Module Regexp.PCRE


Inherit"____Regexp_PCRE"

inherit "____Regexp_PCRE" : "____Regexp_PCRE"


Constantbuildconfig_LINK_SIZE

constant Regexp.PCRE.buildconfig_LINK_SIZE

Description

(from the pcreapi man-page) "The output is an integer that contains the number of bytes used for internal linkage in compiled regular expressions. The value is 2, 3, or 4. Larger values allow larger regular expressions to be compiled, at the expense of slower match- ing. The default value of 2 is sufficient for all but the most massive patterns, since it allows the compiled pattern to be up to 64K in size." This constant is calculated when the module is initiated by using pcre_config(3).


Constantbuildconfig_MATCH_LIMIT

constant Regexp.PCRE.buildconfig_MATCH_LIMIT

Description

(from the pcreapi man-page) "The output is an integer that gives the default limit for the number of internal matching function calls in a pcre_exec() execution. Further details are given with pcre_exec() below." This constant is calculated when the module is initiated by using pcre_config(3).


Constantbuildconfig_NEWLINE

constant Regexp.PCRE.buildconfig_NEWLINE

Description

(from the pcreapi man-page) "The output is an integer that is set to the value of the code that is used for the newline character. It is either linefeed (10) or carriage return (13), and should normally be the standard character for your operating system." This constant is calculated when the module is initiated by using pcre_config(3).


Constantbuildconfig_POSIX_MALLOC_THRESHOLD

constant Regexp.PCRE.buildconfig_POSIX_MALLOC_THRESHOLD

Description

(from the pcreapi man-page) "The output is an integer that contains the threshold above which the POSIX interface uses malloc() for output vectors. Further details are given in the pcreposix documentation." This constant is calculated when the module is initiated by using pcre_config(3).


Constantbuildconfig_UTF8

constant Regexp.PCRE.buildconfig_UTF8

Description

(from the pcreapi man-page) "The output is an integer that is set to one if UTF-8 support is available; otherwise it is set to zero." This constant is calculated when the module is initiated by using pcre_config(3).


Method`()

StudiedWidestring`()(stringpattern, void|intoptions, void|objecttable)

Description

Convenience function to create a suitable PCRE Regexp object; will create a StudiedWidestring from the arguments.

That means the result will be able to handle widestrings, and will produce fast matchings by studying the pattern, but the widestring wrapping will on the other hand add overhead.

If you need a faster regexp and doesn't use widestring, create a Regexp.PCRE.Studied instead.

Widestring support will not be used if the linked libpcre lacks UTF8 support. This can be tested with checking that the Regexp.PCRE.Widestring class exist.


Methodsplit_subject

array(string) split_subject(stringsubject, array(int) previous_result)

Description

Convenience function that splits a subject string on the result from _pcre->exec()

equal to map(previous_result/2, lambda(array v) { return subject[v[0]..v[1]-1]; })

Class Regexp.PCRE.Plain

Description

The main regexp class. Will provide anything needed for matching regexps.

There are subclasses that adds wrappers for widestrings, and to optimize the regexp pattern.


Inherit_pcre

inherit _pcre : _pcre


Methodmatch

boolmatch(stringsubject, void|intstartoffset)

Description

returns true (1) if a match is found, false otherwise

example:

>Regexp.PCRE.Plain("is fun")->match("pike is fun");
Result: 1
>Regexp.PCRE.Plain("is fun")->match("pike isn't fun");
Result: 0

Methodmatchall

this_programmatchall(stringsubject, function(array(string)|void, array(int)|void:mixed|void) callback)

Description

Will give a callback for each match in a subject. Called arguments will be matching patterns and subpatterns in an array and as second argument the exec result array.

returns called object

example:

>Regexp.PCRE("b(a*)([^-\1234]*)(\1234*)m")
    ->matchall("abam-boom-fooabado\1234m",lambda(mixed s){ werror("%O\n",s);return"gurka";});({/* 4 elements */"bam","a","",""})({/* 4 elements */"boom","","oo",""})({/* 4 elements */"bado\1234m","a","do","\1234"})
Result:Regexp.PCRE.StudiedWidestring("b(a*)([^-Ê\234]*)(Ê\234*)m")

Methodreplace

stringreplace(stringsubject, string|function(:void) with, mixed ... args)

Description

replace all occurances of a pattern in a subject; callbacks and replacements will be from the first occurance, not from the last as in Regexp.Builtin.replace.

if with is a function, the first argument will be the total match string, and the subsequent arguments will contain any submatches

example:

>Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom","gurka");
Result:"agurka-gurka-fooagurka">Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom",lambda(string s){ werror("%O\n",s);return"gurka";});"bam""boom""badoom"
Result:"agurka-gurka-fooagurka"

example:

>Regexp.PCRE("([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})")
  ->replace("foo@bar.org",lambda(string whole,string user,string loc,string domain){return user +" from "+ loc +" dot "+ domain;});(4) Result:"foo from bar dot org"

Methodreplace1

stringreplace1(stringsubject, string|function(string:string) with)

Description

replace one (first) occurance of a pattern in a subject

example:

>Regexp.PCRE("b[^-]*m")->replace1("abam-boom-fooabadoom","gurka");
Result:"agurka-boom-fooabadoom"

Methodreplace_positional

stringreplace_positional(stringsubject, stringsubst)

Description

replaces matches in a string, with support for backreferences (matched groups)

Parameter subject

the string to be tested against the regular expression

Parameter subst

string to be inserted in place of each match. backreferences can be inserted into the string to be substituted using the syntax %[n]s where n is the nth matching string group, and 0 (zero) is the full match.

example:

>Regexp.PCRE.Plain("my name is ([a-zA-Z]+)")
      ->replace_positional("allow me to introduce myself: my name is john","%[0]s is my name");(1) Result:"allow me to introduce myself: john is my name"

Methodsplit

array(string)|int(0)split(stringsubject, void|intstartoffset)

Description

Matches a subject against the pattern, compatible with the old split method: returns an array of the subpatterns, or if there are no subpattern but still a match, ({0}). Returns 0 if there was no match.

example:

>Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split("pike is fun");(1) Result:({"ke","f"})>Regexp.PCRE.Plain("is fun")->split("pike is fun");(4) Result:({
                0
            })

Methodsplit2

array(string)|int(0)split2(stringsubject, void|intstartoffset)

Description

Matches a subject against the pattern, returns an array where the first element are the whole match, and the subsequent are the matching subpatterns. Returns 0 if there was no match.

example:

>Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split2("pike is fun");
Result:({"ike is fu","ke","f"})

Class Regexp.PCRE.Studied

Description

Same as Plain, but will be studied to match faster; useful if you're doing many matches on the same pattern


InheritPlain

inherit Plain : Plain

Class Regexp.PCRE.StudiedWidestring

Description

Same as Widestring, but will be studied to match faster; useful if you're doing many matches on the same pattern


InheritWidestring

inherit Widestring : Widestring

Class Regexp.PCRE.Widestring

Description

Wrapper class around Plain, that will allow widestring patterns and subjects.

Widestring support and this class will not be implemented if the linked libpcre lacks UTF8 support.


InheritPlain

inherit Plain : Plain


Methodexec

array(int)|intexec(stringsubject, void|intstartoffset)

Description

The exec function is wrapped to give the correct indexes for the widestring.

Class Regexp.PCRE._pcre


Method_sprintf

stringsprintf(stringformat, ... Regexp.PCRE._pcrearg ... )


Methodcreate

Regexp.PCRE._pcreRegexp.PCRE._pcre(stringpattern, void|intoptions, void|objecttable)

Description

The option bits are:

OPTION.ANCHORED

Force pattern anchoring

OPTION.CASELESS

Do caseless matching

OPTION.DOLLAR_ENDONLY

$ not to match newline at end

OPTION.DOTALL

. matches anything including NL

OPTION.EXTENDED

Ignore whitespace and # comments

OPTION.EXTRA

PCRE extra features (not much use currently)

OPTION.MULTILINE

^ and $ match newlines within data

OPTION.NO_AUTO_CAPTURE

Disable numbered capturing parentheses (named ones available)

OPTION.UNGREEDY

Invert greediness of quantifiers

OPTION.UTF8

Run in UTF-8 mode


Methodexec

int|arrayexec(stringsubject, void|intstartoffset)

Description

Matches the regexp against subject, starting at startoffset if it is given.

If the match is successful, the return value is an array that holds the offsets of all matches:

Elements 0 and 1 have the start and end offsets, respectively, of the match for the whole regexp. The start offset is inclusive while the end is exclusive, i.e. the matching string is subject[res[0]..res[1]-1].

Elements 2 and 3 have the offsets of the first capturing submatch (if any) in the same way, elements 4 and 5 are for the second capturing submatch, etc. If a submatch didn't match anything, the corresponding elements are set to -1. If a submatch has matched successfully several times, the offsets of the last match are returned.

The returned array is always of length 2*n + 1, where n is the total number of capturing submatches in the regexp.

If there is an error, an integer error code is returned:

ERROR.NOMATCH

The subject string did not match the pattern.

ERROR.NULL

Either code or subject was passed as NULL, or ovector was NULL and oversize was not zero.

ERROR.BADOPTION

An unrecognized bit was set in the options argument.

ERROR.BADMAGIC

PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch the case when it is passed a junk pointer. This is the error it gives when the magic number isn't present.

ERROR.UNKNOWN_NODE

While running the pattern match, an unknown item was encountered in the compiled pattern. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern.

ERROR.NOMEMORY

If a pattern contains back references, but the ovector that is passed to pcre_exec() is not big enough to remember the referenced substrings, PCRE gets a block of memory at the start of matching to use for this purpose. If the call via pcre_malloc() fails, this error is given. The memory is freed at the end of matching.

ERROR.NOSUBSTRING

This error is used by the pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() functions (see below). It is never returned by pcre_exec().

ERROR.MATCHLIMIT

The recursion and backtracking limit, as specified by the match_limit field in a pcre_extra structure (or defaulted) was reached. See the description above.

ERROR.CALLOUT

This error is never generated by pcre_exec() itself. It is provided for use by callout functions that want to yield a distinctive error code. See the pcrecallout documentation for details.


Methodget_stringnumber

intget_stringnumber(stringstringname)

Description

returns the number of a named subpattern


Methodinfo

mappinginfo()

Description

Returns additional information about a compiled pattern. Only available if PCRE was compiled with Fullinfo.

Returns
"backrefmax" : int

Return the number of the highest back reference in the pattern. The fourth argument should point to an int variable. Zero is returned if there are no back references.

"capturecount" : int

Return the number of capturing subpatterns in the pattern. The fourth argument should point to an int variable.

"firstbyte" : int

Return information about the first byte of any matched string, for a non-anchored pattern. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name is still recognized for backwards compatibility.)

If there is a fixed first byte, e.g. from a pattern such as (cat|cow|coyote), it is returned in the integer pointed to by where. Otherwise, if either

(a) the pattern was compiled with the PCRE_MULTILINE option, and every branch starts with "^", or

(b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not set (if it were set, the pattern would be anchored),

-1 is returned, indicating that the pattern matches only at the start of a subject string or after any newline within the string. Otherwise -2 is returned. For anchored patterns, -2 is returned.

"lastliteral" : int

Return the value of the rightmost literal byte that must exist in any matched string, other than at its start, if such a byte has been recorded. The fourth argument should point to an int variable. If there is no such byte, -1 is returned. For anchored patterns, a last literal byte is recorded only if it follows something of variable length. For example, for the pattern /^a\d+z\d+/ the returned value is "z", but for /^a\dz\d/ the returned value is -1.

"namecount" : int 
"nameentrysize" : int 
"options" : int

Return a copy of the options with which the pattern was compiled. The fourth argument should point to an unsigned long int variable. These option bits are those specified in the call to pcre_compile(), modified by any top-level option settings within the pattern itself.

A pattern is automatically anchored by PCRE if all of its top-level alternatives begin with one of the following:

^unless PCRE_MULTILINE is set
\Aalways
\Galways
.*if PCRE_DOTALL is set and there are no back references to the subpattern in which .* appears

For such patterns, the PCRE_ANCHORED bit is set in the options returned.

"size" : int

Return the size of the compiled pattern, that is, the value that was passed as the argument to pcre_malloc() when PCRE was getting memory in which to place the compiled data. The fourth argument should point to a size_t variable.

"studysize" : int

Returns the size of the data block pointed to by the study_data field in a pcre_extra block. That is, it is the value that was passed to pcre_malloc() when PCRE was getting memory into which to place the data created by pcre_study(). The fourth argument should point to a size_t variable.


Methodstudy

objectstudy()

Description

(from the pcreapi man-page) "When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for match- ing."

Module Regexp.PCRE.ERROR


ConstantNOMATCH
ConstantNULL
ConstantBADOPTION
ConstantBADMAGIC
ConstantUNKNOWN_NODE
ConstantNOMEMORY
ConstantNOSUBSTRING
ConstantMATCHLIMIT
ConstantCALLOUT

constant Regexp.PCRE.ERROR.NOMATCH
constant Regexp.PCRE.ERROR.NULL
constant Regexp.PCRE.ERROR.BADOPTION
constant Regexp.PCRE.ERROR.BADMAGIC
constant Regexp.PCRE.ERROR.UNKNOWN_NODE
constant Regexp.PCRE.ERROR.NOMEMORY
constant Regexp.PCRE.ERROR.NOSUBSTRING
constant Regexp.PCRE.ERROR.MATCHLIMIT
constant Regexp.PCRE.ERROR.CALLOUT

Description

Documented in exec.

Module Regexp.PCRE.OPTION

Description

contains all option constants


ConstantANCHORED

constant Regexp.PCRE.OPTION.ANCHORED

Description

(from the pcreapi manpage) If this bit is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.


ConstantCASELESS

constant Regexp.PCRE.OPTION.CASELESS

Description

(from the pcreapi manpage) If this bit is set, letters in the pattern match both upper and lower case letters. It is equivalent to Perl's /i option, and it can be changed within a pattern by a (?i) option setting.


ConstantDOLLAR_ENDONLY

constant Regexp.PCRE.OPTION.DOLLAR_ENDONLY

Description

(from the pcreapi manpage) If this bit is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. There is no equivalent to this option in Perl, and no way to set it within a pattern.


ConstantDOTALL

constant Regexp.PCRE.OPTION.DOTALL

Description

(from the pcreapi manpage) If this bit is set, a dot metacharater in the pattern matches all characters, including newlines. Without it, newlines are excluded. This option is equivalent to Perl's /s option, and it can be changed within a pattern by a (?s) option setting. A negative class such as [^a] always matches a newline character, independent of the setting of this option.


ConstantEXTENDED

constant Regexp.PCRE.OPTION.EXTENDED

Description

(from the pcreapi manpage) If this bit is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT character (code 11). In addition, characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x option, and it can be changed within a pattern by a (?x) option setting.

This option makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.


ConstantEXTRA

constant Regexp.PCRE.OPTION.EXTRA

Description

(from the pcreapi manpage) This option was invented in order to turn on additional functionality of PCRE that is incompatible with Perl, but it is currently of very little use. When set, any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this option. It can also be set by a (?X) option setting within a pattern.


ConstantMULTILINE

constant Regexp.PCRE.OPTION.MULTILINE

Description

(from the pcreapi manpage) By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless PCRE_DOL- LAR_ENDONLY is set). This is the same as Perl.

When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs match immediately following or immediately before any new- line in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no "\n" charac- ters in a subject string, or no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect.


ConstantNO_AUTO_CAPTURE

constant Regexp.PCRE.OPTION.NO_AUTO_CAPTURE

Description

(from the pcreapi manpage) If this option is set, it disables the use of numbered capturing paren- theses in the pattern. Any opening parenthesis that is not followed by ? behaves as if it were followed by ?: but named parentheses can still be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl.


ConstantUNGREEDY

constant Regexp.PCRE.OPTION.UNGREEDY

Description

(from the pcreapi manpage) This option inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) option setting within the pattern.


ConstantUTF8

constant Regexp.PCRE.OPTION.UTF8

Description

(from the pcreapi manpage) This option causes PCRE to regard both the pattern and the subject as strings of UTF-8 characters instead of single-byte character strings. However, it is available only if PCRE has been built to include UTF-8 support. If not, the use of this option provokes an error. Details of how this option changes the behaviour of PCRE are given in the section on UTF-8 support in the main pcre page.

Module Remote

Description

Remote RPC system.

Class Remote.Call

Description

Wrapper for a remote function.


Method`()

mixed res = Remote.Call()()

Description

Call the wrapped function.

Parameter args

Arguments to pass to the wrapped function.

This function can operate in two modes depending on whether asynchronous mode has been activated or not. If it has it is equivalent to a call of async() and if not of sync() with the same arguments.

See also

async(), sync(), is_async(), set_async()


Methodasync

voidasync(mixed ... args)

Description

Call the wrapped remote function asynchronously.

Parameter args

Arguments to send to the remote function.

See also

sync(), `()()


Methodcreate

Remote.CallRemote.Call(string|zeroobjectid, stringname, objectconnection, objectcontext, intasync)


Methodexists

intexists()

Description

Check whether the wrapped function actually exists at the other end.


Methodis_async

intis_async()

Returns

Whether asynchronous mode is active or not.

See also

set_async()


Methodset_async

voidset_async(inta)

Description

Change to/from asynchronous mode.

See also

is_async()


Methodsync

mixedsync(mixed ... args)

Description

Call the wrapped remote function synchronously.

Parameter args

Arguments to send to the remote function.

Returns

Returns (the possibly wrapped) result from the remote function.

See also

async(), `()()

Class Remote.Client

Description

Remote RPC Client.


Variablecon

Remote.Connection Remote.Client.con

Description

Connection to the Remote.Server.


Methodclose

voidclose()

Description

Close the connection.


Methodclosed

intclosed()

Description

Check if the connection is closed.


Methodcreate

Remote.ClientRemote.Client(stringhost, intport, void|intnice, void|inttimeout, void|intmax_call_threads)

Description

Connect to a Remote.Server.

Parameter host
Parameter port

Hostname and port for the Remote.Server.

Parameter nice

If set, inhibits throwing of errors from call_sync().

Parameter timeout

Connection timeout in seconds.

Parameter max_call_threads

Maximum number of concurrent threads.


Methodget

objectget(stringname)

Description

Get a named object from the remote server.


Methodprovide

voidprovide(stringname, mixedthing)

Description

Provide a named thing to the Remote.Server.

Parameter name

Name to provide thing under.

Parameter thing

Thing to provide.


Methodset_close_callback

voidset_close_callback(function(:void) f)

Description

Set the callback to call when the connection is closed.

Class Remote.Connection


Methodadd_close_callback

voidadd_close_callback(function(:void) f, mixed ... args)

Description

Add a function that is called when the connection is closed.


Methodcall_async

voidcall_async(arraydata)

Description

Make a call but don't wait for the result


Methodcall_sync

mixedcall_sync(arraydata)

Description

Make a call and wait for the result


Methodclose

voidclose()

Description

Closes the connection nicely, after waiting in outstanding calls in both directions.


Methodconnect

intconnect(stringhost, intport, void|inttimeout)

Description

This function is called by clients to connect to a server.


Methodcreate

Remote.ConnectionRemote.Connection(void|intnice, void|intmax_call_threads)

Parameter nice

If set, no errors will be thrown.


Methoderror_message

string|zeroerror_message()

Description

Returns an error message for the last error, in case connect returns zero. Returns zero if the last connect call was successful.


Methodget_named_object

objectget_named_object(stringname)

Description

Get a named object provided by the server.


Methodremove_close_callback

voidremove_close_callback(arrayf)

Description

Remove a function that is called when the connection is closed.


Methodstart_server

voidstart_server(objectc, objectcx)

Description

This function is called by servers when they have got a connection from a client. The first argument is the connection file object, and the second argument is the context to be used.

Class Remote.Context

Description

Remote context tracker.

This class keeps track of what local things correspond to what remote things, and the reverse.


Methodadd

voidadd(objecto, stringid)


Methodcreate

Remote.ContextRemote.Context(stringb, object|voidcn)


Methoddecode

mixeddecode(arraya)


Methoddecode_call

function(:void)|objectdecode_call(arraydata)


Methoddecode_existp

intdecode_existp(arraydata)


Methoddescribe

stringdescribe(arraydata)


Methodencode

arrayencode(mixedval)


Methodencode_call

arrayencode_call(object|stringo, string|function(:void) f, arrayargs, inttype)


Methodfunction_for

objectfunction_for(stringid)


Methodid_for

stringid_for(mixedthing)


Methodobject_for

object|zeroobject_for(stringid)


Methodset_server_context

voidset_server_context(objectctx, objectcn)

Class Remote.Obj

Description

Wrapper for a remote object.


Method`->

mixed res = Remote.Obj()->X


Method`[]

mixed res = Remote.Obj()[ f ]


Methodcreate

Remote.ObjRemote.Obj(stringid, objectconnection, objectcontext)


Methodexists

intexists()


Methodget_function

mixedget_function(stringf)

Class Remote.Server

Description

Remote RPC server.


Variableconnections

array(Connection) Remote.Server.connections

Description

Open connections.


Variableport

Stdio.Port Remote.Server.port

Description

Port for the Remote.Server.


Variablesctx

Minicontext Remote.Server.sctx

Description

Server context.


Methodclose

voidclose()

Description

Shut down the Remote.Server for new connections.


Methodclose_all

voidclose_all()

Description

Shut down the Remote.Server and terminate all current clients.


Methodclosed

intclosed()

Description

Check if the Remote.Server is closed.


Methodcreate

Remote.ServerRemote.Server(stringhost, intport, void|intmax_call_threads)

Description

Create a Remote.Server.

Parameter host
Parameter port

Hostname and port for the Remote.Server.

Parameter max_call_threads

Maximum number of concurrent threads.


Methodprovide

voidprovide(stringname, mixedthing)

Description

Provide a named thing to the Remote.Client(s).

Parameter name

Name to provide thing under.

Parameter thing

Thing to provide.

Class Remote.Server.Minicontext

Description

The server Context class.

Module SANE

Description

This module enables access to the SANE (Scanner Access Now Easy) library from pike


ConstantFrameGray
ConstantFrameRGB
ConstantFrameRed
ConstantFrameGreen
ConstantFrameBlue

constant SANE.FrameGray
constant SANE.FrameRGB
constant SANE.FrameRed
constant SANE.FrameGreen
constant SANE.FrameBlue


Methodlist_scanners

array(mapping) list_scanners()

Description

Returns an array with all available scanners.

Example

Pike v0.7 release 120 running Hilfe v2.0 (Incremental Pike Frontend) > SANE.list_scanners(); Result: ({ ([ "model":"Astra 1220S ", "name":"umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]), ([ "model":"Astra 1220S ", "name":"net:lain.idonex.se:umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]) })

Class SANE.Scanner


Methodcancel_scan

voidcancel_scan()


Methodcreate

SANE.ScannerSANE.Scanner(stringname)


Methodget_option

mixedget_option(stringname)


Methodget_parameters

mapping(string:int) get_parameters()

Returns
"format" : int
"last_frame" : int
"lines" : int
"depth" : int
"pixels_per_line" : int
"bytes_per_line" : int

Methodlist_options

array(mapping) list_options()

Description

This method returns an array where every element is a mapping, layed out as follows.

"name" : string 
"title" : string 
"desc" : string 
"type" : string
"boolean"
"int"
"float"
"string"
"button"
"group"
"unit" : string
"none"
"pixel"
"bit"
"mm"
"dpi"
"percent"
"microsend"
"size" : int 
"cap" : multiset
"soft_select"
"hard_select"
"emulate"
"automatic"
"inactive"
"advanced"
"constraint" : int(0)|mapping

Constraints can be of three different types; range, word list or string list. Constraint contains 0 if there are no constraints.

"type" : string

Contains the value "range".

"max" : int 
"min" : int 
"quant" : int 
"type" : string

Contains the value "list".

"list" : array(float|int) 
"type" : string

Contains the value "list".

"list" : array(string) 

Methodnonblocking_row_scan

voidnonblocking_row_scan(function(Image.Image, int, Scanner, int:void) callback)


Methodrow_scan

voidrow_scan(function(Image.Image, int, Scanner:void) callback)


Methodset_option

voidset_option(stringname, mixednew_value)
voidset_option(stringname)

Description

If no value is specified, the option is set to it's default value


Methodsimple_scan

Image.Imagesimple_scan()

Module SDL

Description

SDL or Simple DirectMedia Layer is a cross-platform multimedia library designed to provide fast access to the graphics framebuffer, audio device, input and other devices. This module implements a wrapper for SDL and other relevant libraries like SDL_mixer. The interface is similar to the C one, but using generally accepted Pike syntax.

This means that classes are used when appropriate and that method names use all lowercase letters with words separated by _. For example SDL_SetVideoMode is named SDL.set_video_mode. Also note that unless otherwise noted, errors result in an error being thrown rather than returning -1 or 0, as commonly done in SDL methods.


Methodblit_surface

intblit_surface(SDL.Surfacesrc, SDL.Surfacedst, SDL.Rect|voidsrcrect, SDL.Rect|voiddstrect)

Description

Peforms a fast blit from the source surface to the destination surface.

The final blit rectangle is stored in dstrect. This may differ from srcrect if there was clipping.

This function should not be called on a locked surface.

Parameter src

The surface to be copied.

Parameter dst

The destination surface. This will usually be your main screen, initialized with a call to SDL.set_video_mode().

Parameter srcrect

The rectangular section of src to copy. If the whole surface is to be copied, you can set this to 0.

Parameter dstrect

Where the source surface should be copied to on the destination surface. Only the x and y fields of the SDL.Rect object are used. To copy src to the top-left corner of dst, i.e. at coordinates <0,0>, you can set this to 0.

Returns

If successful, 0, otherwise -1.

See also

SDL.Surface()->blit()


Methodcd_name

string|voidcd_name(intdrive)

Description

Returns a human-readable and system-dependent name for the given drive.

Parameter drive

The CD drive index.

Returns

A human-readable and system-dependent name for the given drive, or 0 if no name is available.

See also

SDL.cd_num_drives()


Methodcd_num_drives

intcd_num_drives()

Returns

The number of CD-ROM drives on the system.

See also

SDL.cd_name()


Methodenable_unicode

intenable_unicode(intenable)

Description

Enables/Disables UNICODE keyboard translation.

If you wish to translate a keysym to its printable representation, you need to enable UNICODE translation using this function and then look in the unicode member of the SDL.Keysym class. This value will be zero for keysyms that do not have a printable representation. UNICODE translation is disabled by default as the conversion can cause a slight overhead.

Parameter enable

A value of 1 enables Unicode translation, 0 disables it and -1 leaves it unchanged (useful for querying the current translation mode).

Returns

The previous translation mode (1 enabled, 0 disabled). If enable is -1, the return value is the current translation mode.

See also

SDL.Keysym


Methodflip

intflip(SDL.Surface|voidscreen)

Description

On hardware that supports double-buffering, this function sets up a flip and returns. The hardware will wait for vertical retrace, and then swap video buffers before the next video surface blit or lock will return. On hardware that doesn't support double-buffering, this is equivalent to calling SDL.update_rect(screen, 0, 0, 0, 0)

The SDL.DOUBLEBUF flag must have been passed to SDL.set_video_mode() when setting the video mode for this function to perform hardware flipping.

Parameter screen

The screen object to flip. If missing, the default screen is used.

Returns

This function returns 1 if successful, or 0 if there was an error.

See also

SDL.update_rect()


Methodget_caption

array(string) get_caption()

Returns

A 2-element array holding the window title and icon name.

See also

SDL.set_caption()


Methodget_error

string|zeroget_error()

Description

Get the last internal SDL error.

Returns

The error string, or zero if there was no error.


Methodget_key_state

stringget_key_state()

Description

Gets a snapshot of the current keyboard state.

Returns

The current state is returned as a string.

The string is indexed by the SDL.K_* symbols. A value of 1 means the key is pressed and a value of 0 means it's not.

Note

Call SDL.pump_events() to update the state array.

See also

SDL.get_mod_state(), SDL.pump_events()

Example
// Test if the 'Escape' key is pressed.SDL.pump_events();string ks =SDL.get_key_state();if( ks[SDL.K_ESCAPE]){// handle key press...

Methodget_mod_state

intget_mod_state()

Description

Returns the current state of the modifier keys (CTRL, ALT, etc.).

Returns

The return value can be an OR'd combination of the following: SDL.KMOD_NONE, SDL.KMOD_LSHIFT, SDL.KMOD_RSHIFT, SDL.KMOD_LCTRL, SDL.KMOD_RCTRL, SDL.KMOD_LALT, SDL.KMOD_RALT, SDL.KMOD_LMETA, SDL.KMOD_RMETA, SDL.KMOD_NUM, SDL.KMOD_CAPS, and SDL.KMOD_MODE.

For convenience, the following are also defined: SDL.KMOD_CTRL, SDL.KMOD_SHIFT, SDL.KMOD_ALT and SDL.KMOD_META

See also

SDL.get_key_state(), SDL.pump_events()


Methodget_video_info

objectget_video_info()

Returns

Returns an SDL.VideoInfo object, which holds information about the video hardware, or 0 if the video device has not yet been initialized (with a call to SDL.init()).


Methodget_video_surface

objectget_video_surface()

Description

Returns the current display surface.

If SDL is doing format conversion on the display surface, this method returns the publicly visible surface, not the real video surface.

Returns

The current display surface, or 0 if there is no display surface.

See also

SDL.set_video_mode()


Methodgl_get_attribute

intgl_get_attribute(intattribute)

Description

Returns the value of the given SDL/OpenGL attribute. You might want to call this after SDL.set_video_mode() to check that attributes have been set as you expected.

Parameter attribute

The SDL/OpenGL attribute to query.

Returns

The value of the given attribute.

Example
// Has double-buffering been set?int db =SDL.gl_get_attribute(SDL.GL_DOUBLEBUFFER );if( db ){// yes...

Methodgl_set_attribute

voidgl_set_attribute(intattribute, intvalue)

Description

Sets an SDL/OpenGL attribute to the given value.

This won't take effect until after a call to SDL.set_video_mode().

Parameter attribute

The attribute to set. This will be one of SDL.GL_RED_SIZE, SDL.GL_GREEN_SIZE, SDL.GL_BLUE_SIZE, SDL.GL_DEPTH_SIZE or SDL.GL_DOUBLEBUFFER.

Parameter value

The value to set for this attribute.

See also

SDL.gl_get_attribute()


Methodgl_swap_buffers

voidgl_swap_buffers()

Description

Swaps the OpenGL buffers on a double-buffered screen.

See also

SDL.gl_set_attribute(), SDL.gl_get_attribute(), SDL.set_video_mode()


Methodgrab_input

intgrab_input(intmode)

Description

Sets or queries the current 'grab' mode.

Grabbing input means asking that all mouse activity be confined to this application window and that nearly all keyboard events are passed directly to the application, bypassing the window manager.

Parameter mode

One of the following constants:

SDL.GRAB_ON

SDL.GRAB_OFF

SDL.GRAB_QUERY

Returns

The current grab mode, either SDL.GRAB_ON or SDL.GRAB_OFF.


Methodiconify_window

inticonify_window()

Description

Attempts to iconify (i.e. minimize) the application window.

If the call is successful, the application will receive an SDL.APPACTIVE loss event.

Returns

Non-zero if successful, otherwise 0.


Methodinit

voidinit(intflags)

Description

Initializes SDL. This should be called before all other SDL functions.

Parameter flags

The flags parameter specifies what part(s) of SDL to initialize. It can be one of many of the following ORed together.

SDL.INIT_TIMER

Initializes the timer subsystem.

SDL.INIT_AUDIO

Initializes the audio subsystem.

SDL.INIT_VIDEO

Initializes the video subsystem.

SDL.INIT_CDROM

Initializes the cdrom subsystem.

SDL.INIT_JOYSTICK

Initializes the joystick subsystem.

SDL.INIT_EVERYTHING

Initialize all of the above.

SDL.INIT_NOPARACHUTE

Prevents SDL from catching fatal signals.

SDL.INIT_EVENTTHREAD

Run event polling in a separate thread. Not always supported.

See also

SDL.quit(), SDL.init_sub_system(), SDL.quit_sub_system()


Methodinit_sub_system

voidinit_sub_system(intflags)

Description

After SDL has been initialized with SDL.init() you may initialize uninitialized subsystems with this method.

Parameter flags

The same as what is used in SDL.init().

See also

SDL.init(), SDL.quit(), SDL.quit_sub_system()


Methodjoystick_event_state

intjoystick_event_state(intstate)

Description

Enables, disables or queries the state of joystick event processing.

Parameter state

One of the following constants:

SDL.ENABLE

Enables joystick event processing.

SDL.IGNORE

Disables joystick event processing.

SDL.QUERY

Queries the current state and returns it.

Returns

The current state of joystick event processing. If state was SDL.ENABLE or SDL.IGNORE, then processing will now be enabled or disabled, respectively.


Methodjoystick_name

stringjoystick_name(intdevice_index)

Description

Returns the implementation-dependent name of the nth joystick device available to the system.

Parameter device_index

The nth joystick device.

Returns

The implementation-dependent name of the given joystick device.

See also

SDL.Joystick->name()


Methodjoystick_opened

intjoystick_opened(intdevice_index)

Description

Determines whether the given joystick device has already been opened.

Parameter device_index

The nth joystick device.

Returns

1 if this device has already been opened, otherwise 0.


Methodjoystick_update

voidjoystick_update()

Description

Updates the state of all open joysticks attached to the system.


Methodnum_joysticks

intnum_joysticks()

Returns

The number of joysticks available to the system.

See also

SDL.Joystick


Methodopen_audio

voidopen_audio(intfrequency, intformat, intchannels, intbufsize)

Description

Initializes the audio API.

Throws an exception if audio can't be initialized.

Parameter frequency

Output sampling frequency, measured in samples per second (Hz). A value of 44100 provides CD-quality playback. A less CPU-intensive value for games is 22050.

Parameter format

Output sample format. One of the following constants:

SDL.AUDIO_U8

Unsigned 8-bit samples.

SDL.AUDIO_S8

Signed 8-bit samples.

SDL.AUDIO_U16LSB

Unsigned 16-bit samples in little-endian byte order.

SDL.AUDIO_S16LSB

Signed 16-bit samples in little-endian byte order.

SDL.AUDIO_U16MSB

Unsigned 16-bit samples in big-endian byte order.

SDL.AUDIO_S16MSB

Signed 16-bit samples in big-endian byte order.

SDL.AUDIO_U16

Same as SDL.AUDIO_U16LSB.

SDL.AUDIO_S16

Same as SDL.AUDIO_S16LSB.

SDL.AUDIO_U16SYS

Unsigned 16-bit samples in system byte order.

SDL.AUDIO_S16SYS

Signed 16-bit samples in system byte order. If in doubt, try this one first.

Parameter channels

Number of sound channels in output: 1 for mono, 2 for stereo.

Parameter bufsize

How many bytes to use per output sample. 1024 is a typical value for games. If just playing music you might set this to 4096 or higher.


Methodpump_events

voidpump_events()

Description

Pumps the event loop, gathering events from the input devices.

Normally you won't need to call this method, as it's called implicitly by SDL.Event->poll().

See also

get_key_state(), get_mod_state()


Methodquit

voidquit()

Description

Shuts down all SDL subsystems and frees the resources allocated to them. This should always be called before you exit.

Note

You can use the atexit() method to ensure that this method is always called when Pike exits normally.

See also

SDL.init(), SDL.init_sub_system(), SDL.quit_sub_system()


Methodquit_sub_system

voidquit_sub_system(intflags)

Description

After an SDL subsystem has been initialized with SDL.init() or SDL.init_sub_system(), it may be shut down with this method.

Parameter flags

A bitwise OR'd combination of the subsystems you wish to shut down (see SDL.init() for a list of subsystem flags).

See also

SDL.init(), SDL.init_sub_system(), SDL.quit()


Methodset_caption

voidset_caption(stringtitle, stringicon)

Description

Sets the window's title and icon name. Icon name refers to the text that appears next to the application's icon in its minimized window.

Parameter title

The window's title.

Parameter icon

The minimized window's icon name.

See also

SDL.get_caption()


Methodset_gamma

intset_gamma(floatred, floatgreen, floatblue)

FIXME

Document this function


Methodset_video_mode

objectset_video_mode(intwidth, intheight, intbpp, intflags)

Description

Sets up a video mode with the specified width, height and bits per pixel.

Parameter width

The desired width. Setting this to <= 0 results in an SDL error.

Parameter height

The desired height. Setting this to <= 0 results in an SDL error.

Parameter bpp

The bits per pixel. This should be either 0, 8, 16, 24 or 32. If you set this to 0, the bits-per-pixel value of the current display will be used.

Parameter flags

An OR'd combination of the desired SDL.Surface flags.

Returns

The framebuffer surface. An error is thrown if the video mode can't be set.

See also

SDL.Surface, SDL.video_mode_ok()


Methodshow_cursor

intshow_cursor(intshow)

Description

Sets the state of the mouse cursor on the SDL screen (visible or hidden), or queries its current state.

By default, the cursor is visible.

Parameter show

One of these constants:

SDL.ENABLE

Show the cursor.

SDL.DISABLE

Hide the cursor.

SDL.QUERY

Determine the current state of the cursor.

Returns

The current state of the mouse cursor, either SDL.ENABLE or SDL.DISABLE.


Methodtoggle_fullscreen

inttoggle_fullscreen(void|SDL.Surfacescreen)

Description

Toggles the application between windowed and fullscreen mode, if supported. X11 is the only target currently supported.

Parameter screen

The framebuffer surface, as returned by SDL.set_video_mode().

Returns

Returns 1 on success or 0 on failure.


Methodupdate_rect

voidupdate_rect(intx, inty, intw, inth, SDL.Surface|voidscreen)

Description

Makes sure the given area is updated on the given screen. The rectangle must be confined within the screen boundaries (no clipping is done).

If 'x', 'y', 'w' and 'h' are all 0, SDL.update_rect() will update the entire screen.

This function should not be called while screen is locked.

Parameter x
Parameter y

Top left corner of the rectangle to update.

Parameter w
Parameter h

Width and height of the rectangle to update.

Parameter screen

The screen object to flip. If missing, the default screen is used.

See also

SDL.flip()


Methodvideo_driver_name

stringvideo_driver_name()

Description

Obtains the name of the video driver. This is a simple one-word identifier such as 'x11' or 'windib'.

Returns

The name of the video driver, or 0 if video has not yet been initialized (with a call to SDL.init()).


Methodvideo_mode_ok

intvideo_mode_ok(intwidth, intheight, intbpp, intflags)

Description

Checks to see if a particular video mode is supported.

Returns

Returns 0 if the requested mode isn't supported under any bit depth, or the bits-per-pixel of the closest available mode with the given width, height and SDL.Surface flags.

See also

SDL.Surface, SDL.set_video_mode(), SDL.get_video_info()


Methodwarp_mouse

voidwarp_mouse(intxpos, intypos)

Description

Sets the position of the mouse cursor to the given coordinates. This generates an SDL.MOUSEMOTION event.

Parameter xpos

Requested position of the mouse cursor along the x-axis.

Parameter ypos

Requested position of the mouse cursor along the y-axis.


Methodwas_init

intwas_init(intflags)

Description

This method allows you to see which SDL subsytems have been initialized.

Parameter flags

A bitwise OR'd combination of the subsystems you wish to check (see SDL.init() for a list of subsystem flags).

Returns

A bitwised OR'd combination of the initialized subsystems

See also

SDL.init(), SDL.init_sub_system()

Class SDL.CD


Variablecurrent_frame

int SDL.CD.current_frame

FIXME

Document this variable


Variablecurrent_track

int SDL.CD.current_track

FIXME

Document this variable


Variableid

int SDL.CD.id

FIXME

Document this variable


Variablenumtracks

int SDL.CD.numtracks

FIXME

Document this variable


Methodcreate

SDL.CDSDL.CD(intdrive)

FIXME

Document this function


Methodeject

inteject()

FIXME

Document this function


Methodpause

intpause()

FIXME

Document this function


Methodplay

intplay(intstart, intlength)

FIXME

Document this function


Methodplay_tracks

intplay_tracks(intstart_track, intstart_frame, intntracks, intnframes)

FIXME

Document this function


Methodresume

intresume()

FIXME

Document this function


Methodstatus

intstatus()

FIXME

Document this function


Methodstop

intstop()

FIXME

Document this function


Methodtrack

CDTracktrack(inttrack)

FIXME

Document this function

Class SDL.CDTrack


Variableid
Variablelength
Variableoffset
Variabletype

int SDL.CDTrack.id
int SDL.CDTrack.length
int SDL.CDTrack.offset
int SDL.CDTrack.type

FIXME

Document this variable

Class SDL.Event


Variableaxis
Variableball
Variablebutton
Variablecode
Variablegain
Variableh
Variablehat
Variablekeysym
Variablestate
Variabletype
Variablevalue
Variablew
Variablewhich
Variablex
Variablexrel
Variabley
Variableyrel

int SDL.Event.axis
int SDL.Event.ball
int SDL.Event.button
int SDL.Event.code
int SDL.Event.gain
int SDL.Event.h
int SDL.Event.hat
Keysym SDL.Event.keysym
int SDL.Event.state
int SDL.Event.type
int SDL.Event.value
int SDL.Event.w
int SDL.Event.which
int SDL.Event.x
int SDL.Event.xrel
int SDL.Event.y
int SDL.Event.yrel


Methodget

intget()

Description

Removes the next event (if any) from the queue and stores it in this SDL.Event object.

Returns

1 if there was an event to 'get', otherwise 0.


Methodpoll

intpoll()

Description

Polls for currently pending events.

Returns

1 if there are currently pending events, otherwise 0.


Methodwait

intwait()

Description

Waits indefinitely for the next available event, which is then removed from the queue and stored in this SDL.Event object.

Returns

Returns 1 on success, or 0 if there was an error while waiting for the next event.

Class SDL.Joystick

Description

Represents a joystick, gamepad or other similar input device attached to the system.

You must call SDL.init() with the SDL.INIT_JOYSTICK flag to enable joystick support.

All index numbers count from 0.

All SDL.Joystick methods throw an exception if they are called on an uninitialized object.


Methodcreate

SDL.JoystickSDL.Joystick(intdevice_index)

Description

Opens the given joystick device for use.

Parameter device_index

The nth joystick device available to the system.

See also

SDL.num_joysticks()


Methodget_axis

floatget_axis(intaxis)

Description

Returns the current position of the given axis.

The returned value is a float between -1.0 and 1.0.

Parameter axis

The axis index.

Returns

The current position of the given axis.

See also

num_axes()


Methodget_ball

array(int) get_ball(intball)

Description

Returns the axis change of the given trackball.

This is its relative motion along both axes since the last call to get_ball(). It is returned as a 2-element array holding the values of dx and dy (- the motion deltas).

Returns

The axis change of the given trackball.

See also

num_balls()


Methodget_button

intget_button(intbutton)

Description

Returns the current state of the given button.

This is 1 if the button is pressed, otherwise 0.

Parameter button

The button index.

Returns

The current state of the given button.

See also

num_buttons()


Methodget_hat

intget_hat(inthat)

Description

Returns the current state of the given hat.

This is represented as an OR'd combination of one or more of the following constants:

SDL.HAT_CENTERED

SDL.HAT_UP

SDL.HAT_RIGHT

SDL.HAT_DOWN

SDL.HAT_LEFT

SDL.HAT_RIGHTUP

SDL.HAT_RIGHTDOWN

SDL.HAT_LEFTUP

SDL.HAT_LEFTDOWN

Parameter hat

The hat index.

Returns

The current state of the given hat.

See also

num_hats()


Methodindex

intindex()

Returns

The index of this joystick.


Methodname

stringname()

Returns

The implementation-dependent name of this joystick.

See also

SDL.joystick_name()


Methodnum_axes

intnum_axes()

Returns

The number of axes available for this joystick.


Methodnum_balls

intnum_balls()

Returns

The number of trackballs available for this joystick.


Methodnum_buttons

intnum_buttons()

Returns

The number of buttons available for this joystick.


Methodnum_hats

intnum_hats()

Returns

The number of hats available for this joystick.

Class SDL.Keysym

Description

The Keysym class is used to report key presses and releases. It's available from the SDL.Event class for keyboard events.


Variablemod

int SDL.Keysym.mod

Description

Current key modifiers

mod stores the current state of the keyboard modifiers as explained in SDL.get_mod_state().


Variablescancode

int SDL.Keysym.scancode

Description

Hardware specific scancode

The scancode field should generally be left alone - it is the hardware dependent scancode returned by the keyboard.


Variablesym

int SDL.Keysym.sym

Description

SDL virtual keysym

The sym field is extremely useful. It is the SDL-defined value of the key. This field is very useful when you are checking for certain key presses.


Variableunicode

int SDL.Keysym.unicode

Description

Translated character

The unicode field is only used when UNICODE translation has beed enabled with SDL.enable_unicode(). If unicode is non-zero then this the UNICODE character corresponding to the keypress.

Note

UNICODE translation does have a slight overhead so don't enable it unless its needed.

Class SDL.Music

Description

Use an SDL.Music object to load in a music file or sample and then play it back using an internal player.

You must call SDL.init() with the SDL.INIT_AUDIO flag for audio support to be available. You must also first set up some audio parameters with a call to SDL.open_audio().

See also

SDL.open_audio()


Methodcreate

SDL.MusicSDL.Music(stringfname)

Description

Loads in the given music file and initializes the object ready for playback.

Supported formats are OGG, MP3, MOD, MID and WAV.

An exception is thrown if the file fails to load.

Parameter fname

The name of the music file to be loaded.


Methodfade_in

objectfade_in(intms, int|voidloops)

Description

Fades the music in over the given number of milliseconds. Playback is repeated loops number of times.

The fade-in will only happen on the first play, not on subsequent loops. Likewise, calling this method on an object that is already playing has the same effect as rewind(): playback will start over at the beginning but without fading in.

Parameter ms

Music fades in over this number of milliseconds.

Parameter loops

How many times the music should be repeated (looped). Passing a value of 0 here means the music plays once over - i.e. no repeats. A value of -1 loops the music indefinitely. This is the default if you don't specify a value.

Returns

The SDL.Music object.

See also

fade_out(), fading()


Methodfade_out

objectfade_out(intms)

Description

Fades the music out over the given number of milliseconds.

After ms milliseconds have passed, the music will be stopped; i.e. playing() will return 0.

Parameter ms

The number of milliseconds it will take to fade out the music, starting from now.

Returns

The SDL.Music object.


Methodfading

intfading()

Description

Determines the current state of fading for this SDL.Music object.

Returns

One of the following constants:

SDL.MIX_NO_FADING

SDL.MIX_FADING_IN

SDL.MIX_FADING_OUT

See also

fade_in(), fade_out()


Methodhalt

objecthalt()

Description

Stops music playback immediately, including any fader effects.

Returns

The SDL.Music object.


Methodpause

objectpause()

Description

Pauses the music playback.

It is safe to call this method when the music is already paused.

Returns

The SDL.Music object.

See also

resume(), paused()


Methodpaused

intpaused()

Description

Determines if the music is already paused.

Returns

1 if the music is paused, otherwise 0.


Methodplay

objectplay(int|voidloops)

Description

Starts playback. Repeats loops number of times.

Parameter loops

The number of times the music should be looped (i.e. repeated). If loops is -1 or omitted, the music will repeat indefinitely.

Returns

The SDL.Music object.


Methodplaying

intplaying()

Description

Determines if the music is already playing.

This method will return 1 even if the music has been paused.

Returns

1 if the music is playing, otherwise 0.


Methodresume

objectresume()

Description

Resume music playback after a call to pause().

It is safe to call this method when the music isn't paused.

Returns

The SDL.Music object.

See also

pause(), paused()


Methodrewind

objectrewind()

Description

Rewinds the music to the start and resumes playback.

If the music was paused at the time of this call, you will still need to call resume() to restart playback.

This function works only for MOD, OGG, MP3 and Native MIDI streams.

Returns

The SDL.Music object.


Methodset_volume

floatset_volume(floatvol)

Description

Sets the volume for music playback.

Parameter vol

The volume to set. This is a float value from 0.0 (silent) to 1.0 (full volume). Values above and below these limits will be clamped.

Returns

The previous volume setting.


Methodvolume

floatvolume()

Returns

The current volume setting. This is a float value from 0.0 (silent) to 1.0 (full volume).

Class SDL.PixelFormat

Description

This describes the format of the pixel data stored at the pixels field of a SDL.Surface. Every surface stores a PixelFormat in the format field.


Variablerloss
Variablegloss
Variablebloss
Variablealoss

int SDL.PixelFormat.rloss
int SDL.PixelFormat.gloss
int SDL.PixelFormat.bloss
int SDL.PixelFormat.aloss

Description

Precision loss of each color component.


Variablealpha

int SDL.PixelFormat.alpha

Description

Overall surface alpha value.


Variablermask
Variablegmask
Variablebmask
Variableamask

int SDL.PixelFormat.rmask
int SDL.PixelFormat.gmask
int SDL.PixelFormat.bmask
int SDL.PixelFormat.amask

Description

Binary mask used to retrieve individual color values.


Variablershift
Variablegshift
Variablebshift
Variableashift

int SDL.PixelFormat.rshift
int SDL.PixelFormat.gshift
int SDL.PixelFormat.bshift
int SDL.PixelFormat.ashift

Description

Binary left shift of each color component in the pixel value.


Variablebits_per_pixel

int SDL.PixelFormat.bits_per_pixel

Description

The number of bits used to represent each pixel in a surface. Usually 8, 16, 24 or 32.


Variablebytes_per_pixel

int SDL.PixelFormat.bytes_per_pixel

Description

The number of bytes used to represent each pixel in a surface. Usually one to four.


Variablecolorkey

int SDL.PixelFormat.colorkey

Description

Pixel value of transparent pixels.


Methodget_rgb

Image.Color.Colorget_rgb(intpixel)

Description

Get RGB component values from a pixel stored in this pixel format.

Parameter pixel

A pixel retrieved from a surface with this pixel format or a color previously mapped with map_rgb() or map_rgba().

Returns

A Image.Color.Color object with the RGB components of the pixel.

See also

map_rgb(), map_rgba(), get_rgba()


Methodget_rgba

mapping(string:Image.Color.Color|int) get_rgba(intpixel)

Description

Get RGB component values from a pixel stored in this pixel format.

Parameter pixel

A pixel retrieved from a surface with this pixel format or a color previously mapped with map_rgb() or map_rgba().

Returns

A mapping containing the RGBA components of the pixel:

"color" : Image.Color.Color

The RGB color value of the pixel.

"alpha" : int

The alpha value of the pixel in the range 0-255.

See also

map_rgb(), map_rgba(), get_rgb()


Methodlosses

array(int) losses()

Description

Convenience method returning the RGBA precision loss as an array.


Methodmap_rgb

intmap_rgb(intr, intg, intb)
intmap_rgb(Image.Color.Colorcolor)

Description

Maps the RGB color value to the specified pixel format and returns the pixel value as an integer.

If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.

If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).

Parameter r
Parameter g
Parameter b

The red, green and blue components specified as an integer between 0 and 255.

Parameter color

The color as represented by an Image.Color.Color object.

Returns

A pixel value best approximating the given RGB color value for a given pixel format.

See also

map_rgba(), get_rgb(), get_rgba()


Methodmap_rgba

intmap_rgba(intr, intg, intb, inta)
intmap_rgba(Image.Color.Colorcolor, inta)

Description

Maps the RGBA color value to the specified pixel format and returns the pixel value as an integer.

If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.

If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).

Parameter r
Parameter g
Parameter b
Parameter a

The red, green and blue components specified as an integer between 0 and 255.

Parameter color

The color as represented by an Image.Color.Color object.

Returns

A pixel value best approximating the given RGB color value for a given pixel format.

See also

map_rgb(), get_rgb(), get_rgba()


Methodmasks

array(int) masks()

Description

Convenience method returning the RGBA masks as an array.


Methodshifts

array(int) shifts()

Description

Convenience method returning the RGBA shifts as an array.

Class SDL.Rect

Description

Used in SDL to define a rectangular area. It is sometimes also used to specify only points or sizes (i.e only one of the position and dimension is used).


Variablew
Variableh

int(16bit) SDL.Rect.w
int(16bit) SDL.Rect.h

Description

The width and height of the rectangle. Internally these are 16 bit unsigned integers. A runtime error will be generated when integer values are used that are too big.


Variablex
Variabley

int(-32768..32767) SDL.Rect.x
int(-32768..32767) SDL.Rect.y

Description

Position of the upper-left corner of the rectangle. Internally these are 16 bit signed integers. A runtime error will be generated when integer values are used that are too big.


Methodcast

(array)SDL.Rect()
(mapping)SDL.Rect()

Description

It is possible to cast a Rect object to an array or to a mapping. The array will have the values in the order x, y, w, h and the mapping will have the values associated with the corresponding names.


Methodcreate

SDL.RectSDL.Rect()
SDL.RectSDL.Rect(int(-32768..32767)x, int(-32768..32767)y)
SDL.RectSDL.Rect(int(-32768..32767)x, int(-32768..32767)y, int(16bit)w, int(16bit)h)

Description

Create a new Rect.

Parameter x
Parameter y

Optional initial values for Rect()->x and Rect()->y.

Parameter w
Parameter h

Optional initial values for Rect()->w and Rect()->h.

Class SDL.Surface

Description

Surface's represent areas of "graphical" memory, memory that can be drawn to. The video framebuffer is returned as a SDL.Surface by SDL.set_video_mode() and SDL.get_video_surface().


Variableclip_rect

SDL.Rect SDL.Surface.clip_rect

Description

This is the clipping rectangle as set by set_clip_rect().


Variableflags

int SDL.Surface.flags

Description

The following are supported in the flags field.

SDL.SWSURFACE

Surface is stored in system memory

SDL.HWSURFACE

Surface is stored in video memory

SDL.ASYNCBLIT

Surface uses asynchronous blits if possible.

SDL.ANYFORMAT

Allows any pixel-format (Display surface).

SDL.HWPALETTE

Surface has exclusive palette.

SDL.DOUBLEBUF

Surface is double buffered (Display surface).

SDL.FULLSCREEN

Surface is full screen (Display Sur face).

SDL.OPENGL

Surface has an OpenGL context (Display Surface).

SDL.OPENGLBLIT

Surface supports OpenGL blitting (Display Surface).

SDL.RESIZABLE

Surface is resizable (Display Surface).

SDL.HWACCEL

Surface blit uses hardware acceleration.

SDL.SRCCOLORKEY

Surface use colorkey blitting.

SDL.RLEACCEL

Colorkey blitting is accelerated with RLE.

SDL.SRCALPHA

Surface blit uses alpha blending.

SDL.PREALLOC

Surface uses preallocated memory.


Variableformat

SDL.PixelFormat SDL.Surface.format

Description

The pixel format of this surface.


Variablew
Variableh

int SDL.Surface.w
int SDL.Surface.h

Description

The width and height of the surface in pixels.


Methodblit

objectblit(SDL.Surfacedst, SDL.Rect|voidsrcrect, SDL.Rect|voiddstrect)

Description

Perform a blit from this surface to the dst surface.

Parameter dst

Destination Surface for the blit.

Parameter srcrect

Optional source Rect. If UNDEFINED the entire source Surface will be copied.

Parameter dstrect

Optional destination Rect. Only the position fields x and y values are used. If UNDEFINED the blit will be performed to position 0, 0.


Methodconvert_surface

objectconvert_surface(SDL.PixelFormatfmt, intflags)

FIXME

Document this function


Methoddisplay_format

SDL.Surfacedisplay_format()

Description

This function takes a surface and copies it to a new surface of the pixel format and colors of the video framebuffer, suitable for fast blitting onto the display surface. It calls convert_surface().

If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.

If you want an alpha channel, see display_format_alpha().

Returns

The new surface. An error is thrown if the conversion fails.


Methoddisplay_format_alpha

SDL.Surfacedisplay_format_alpha()

Description

This function takes a surface and copies it to a new surface of the pixel format and colors of the video framebuffer, suitable for fast blitting onto the display surface. It calls convert_surface().

If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.

This function can be used to convert a colourkey to an alpha channel, if the SDL.SRCCOLORKEY flag is set on the surface. The generated surface will then be transparent (alpha=0) where the pixels match the colourkey, and opaque (alpha=255) elsewhere.

Returns

The new surface. An error is thrown if the conversion fails.


Methodfill

objectfill(intcolor)

Description

Fill the entire surface with a solid color.

See also

fill_rect()


Methodfill_rect

objectfill_rect(intcolor, SDL.Rectdstrect)

Description

Fill a rectangle with a solid color.

See also

fill()


Methodget_pixel

intget_pixel(intx, inty)

Description

Get the value of the specified pixel. The surface needs to be locked before this method can be used.

Parameter x
Parameter y

Pixel coordinate to get.

Returns

The value of the specified pixel.

See also

set_pixel(), unlock(), lock()


Methodinit

SDL.Surfaceinit(intflags, intwidth, intheight, intdepth, intRmask, intGmask, intBmask, intAmask)

Description

This (re)initializes this surface using the specified parameters.

Any previously allocated data will be freed.

Parameter depth
Parameter Rmask
Parameter Gmask
Parameter Bmask
Parameter Amask

If depth is 8 bits an empty palette is allocated for the surface, otherwise a 'packed-pixel' SDL.PixelFormat is created using the [RGBA]mask's provided.

Parameter width
Parameter height

width and height specify the desired size of the image.

Parameter flags

flags specifies the type of surface that should be created. It is an OR'd combination of the following possible values:

SDL.SWSURFACE

SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.

SDL.HWSURFACE

SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).

SDL.SRCCOLORKEY

This flag turns on colourkeying for blits from this surface. If SDL.HWSURFACE is also specified and colourkeyed blits are hardware-accelerated, then SDL will attempt to place the surface in video memory. Use set_color_key() to set or clear this flag after surface creation.

SDL.SRCALPHA

This flag turns on alpha-blending for blits from this surface. If SDL.HWSURFACE is also specified and alpha blending blits are hardware-accelerated, then the surface will be placed in video memory if possible. Use set_alpha() to set or clear this flag after surface creation.

Note

If an alpha-channel is specified (that is, if Amask is nonzero), then the SDL.SRCALPHA flag is automatically set. You may remove this flag by calling set_alpha() after surface creation.

Returns

A reference to itself.

Note

If this method fails, the surface will become uninitialized.

See also

set_image()


Methodlock

intlock()

Description

This methods locks the surface to allow direct access to the pixels using the get_pixel() and set_pixel() methods.

Note

Note that although all surfaces in SDL don't require locking, you still need to call this method to enable the set/get pixel methods. You should unlock the surface when you're doing modifying it.

Note

Calling this method multiple times means that you need to call unlock an equal number of times for the surface to become unlocked.

Returns

1 for success or 0 if the surface couldn't be locked.

See also

unlock(), set_pixel(), get_pixel()


Methodset_alpha

objectset_alpha(intflag, intalpha)

FIXME

Document this function


Methodset_clip_rect

objectset_clip_rect(SDL.Rectrect)

FIXME

Document this function


Methodset_color_key

objectset_color_key(intflag, intkey)

Description

Set or clear the color key (aka transparent pixel) for a the surface. Also control whether RLE-accelleration is enabled or not.

Parameter flag
FIXME

Document this function


Methodset_image

SDL.Surfaceset_image(Image.Imageimage, int|voidflags)
SDL.Surfaceset_image(Image.Imageimage, Image.Imagealpha, int|voidflags)

Description

This (re)initializes this surface from the Image.Image in image.

Any previously allocated data will be freed.

If initialization is successful, this surface will use RGBA8888 format. For good blitting performance, it should be converted to the display format using display_format().

Parameter image

The source image.

Parameter alpha

Optional alpha channel. In Pike, the alpha channel can have different alpha values for red, green and blue. Since SDL doesn't support this, only the alpha value of the red color is used in the conversion. When this calling convention is used, the surface alpha value of image is ignored.

Parameter flags

When present this specifies the type of surface that should be created. It is an OR'd combination of the following possible values:

SDL.SWSURFACE

SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.

SDL.HWSURFACE

SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).

SDL.SRCCOLORKEY

This flag turns on colourkeying for blits from this surface. If SDL.HWSURFACE is also specified and colourkeyed blits are hardware-accelerated, then SDL will attempt to place the surface in video memory. Use set_color_key() to set or clear this flag after surface creation.

SDL.SRCALPHA

This flag turns on alpha-blending for blits from this surface. If SDL.HWSURFACE is also specified and alpha blending blits are hardware-accelerated, then the surface will be placed in video memory if possible. Note that if this surface has an alpha value specified, this flag is enabled automatically. Use set_alpha() to modify this flag at a later point.

Note

If this method fails, the surface will become uninitialized.

Returns

A reference to itself.

See also

init()


Methodset_pixel

intset_pixel(intx, inty, intpixel)

Description

Set the value of the specified pixel. The surface needs to be locked before this method can be used.

Parameter x
Parameter y

Pixel coordinate to modify.

Parameter pixel

Pixel value to set to the specified pixel.

Returns

A reference to the surface itself.

See also

get_pixel(), unlock(), lock()


Methodunlock

voidunlock()

Description

Surfaces that were previously locked using lock() must be unlocked with unlock().

Surfaces should be unlocked as soon as possible.

See also

lock()

Class SDL.VideoInfo

Description

This (read-only) class is returned by SDL.get_video_info(). It contains information on either the 'best' available mode (if called before SDL.set_video_mode()) or the current video mode.


Variableblit_fill

int SDL.VideoInfo.blit_fill

Description

Are color fills accelerated?


Variableblit_hw

int SDL.VideoInfo.blit_hw

Description

Are hardware to hardware blits accelerated?


Variableblit_hw_a

int SDL.VideoInfo.blit_hw_a

Description

Are hardware to hardware alpha blits accelerated?


Variableblit_hw_cc

int SDL.VideoInfo.blit_hw_cc

Description

Are hardware to hardware colorkey blits accelerated?


Variableblit_sw

int SDL.VideoInfo.blit_sw

Description

Are software to hardware blits accelerated?


Variableblit_sw_a

int SDL.VideoInfo.blit_sw_a

Description

Are software to hardware alpha blits accelerated?


Variableblit_sw_cc

int SDL.VideoInfo.blit_sw_cc

Description

Are software to hardware colorkey blits accelerated?


Variableformat

SDL.PixelFormat SDL.VideoInfo.format

Description

Pixel format of the video device.


Variablehw_available

int SDL.VideoInfo.hw_available

Description

Is it possible to create hardware surfaces?


Variablevideo_mem

int SDL.VideoInfo.video_mem

Description

Total amount of video memory in KB.


Variablewm_available

int SDL.VideoInfo.wm_available

Description

Is there a window manager available

Module Search


Methoddo_query_and

ResultSetdo_query_and(array(string) words, array(int) field_coefficients, array(int) proximity_coefficients, intcutoff, function(string, int, int:string) blobfeeder)

Parameter words

Arrays of word ids. Note that the order is significant for the ranking.

Parameter field_coefficients

An array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:

Array
int0

body

int1..64

Special field 0..63.

Parameter proximity_coefficients

An array of ranking coefficients for the different proximity categories. Always has 8 elements, in the range of [0x0000-0xffff].

Array
int0

spread: 0 (Perfect hit)

int1

spread: 1-5

int2

spread: 6-10

int3

spread: 11-20

int4

spread: 21-40

int5

spread: 41-80

int6

spread: 81-160

int7

spread: 161-

Parameter blobfeeder

This function returns a Pike string containing the word hits for a certain word. Call repeatedly until it returns 0.


Methoddo_query_or

ResultSetdo_query_or(array(string) words, array(int) field_coefficients, array(int) proximity_coefficients, intcutoff, function(string, int, int:string) blobfeeder)

Parameter words

Arrays of word ids. Note that the order is significant for the ranking.

Parameter field_coefficients

An array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:

Array
int0

body

int1..64

Special field 0..63.

Parameter proximity_coefficients

An array of ranking coefficients for the different proximity categories. Always has 8 elements, in the range of [0x0000-0xffff].

Array
int0

spread: 0 (Perfect hit)

int1

spread: 1-5

int2

spread: 6-10

int3

spread: 11-20

int4

spread: 21-40

int5

spread: 41-80

int6

spread: 81-160

int7

spread: 161-

Parameter blobfeeder

This function returns a Pike string containing the word hits for a certain word. Call repeatedly until it returns 0.


Methoddo_query_phrase

ResultSetdo_query_phrase(array(string) words, array(int) field_coefficients, function(string, int, int:string) blobfeeder)

Parameter words

Arrays of word ids. Note that the order is significant for the ranking.

Parameter field_coefficients

An array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:

Array
int0

body

int1..64

Special field 0..63.

Parameter blobfeeder

This function returns a Pike string containing the word hits for a certain word. Call repeatedly until it returns 0.


Methodget_filter

Search.Filer.Baseget_filter(stringmime_type)

Description

Returns the appropriate filter object for the given mime type. This will be one of the objects in Search.Filter.


Methodget_filter_fields

array(string) get_filter_fields()

Description

Returns an array of field types supported by the available set of media plugins.


Methodget_filter_mime_types

mapping(string:Search.Filter.Base) get_filter_mime_types()

Description

Returns a mapping from mime-type to filter objects. The filter objects are from Search.Filter.

Class Search.Blob


Methodadd

voidadd(intdocid, intfield, intoffset)


Methodcreate

Search.BlobSearch.Blob(void|stringinitial)


Methoddata

stringdata()


Methodmemsize

intmemsize()


Methodmerge

voidmerge(stringdata)


Methodremove

voidremove(intdoc_id)


Methodremove_list

voidremove_list(array(int) docs)

Class Search.Blobs


Methodadd_words

voidadd_words(intdocid, array(string) words, intfield_id)

Description

Add all the words in the 'words' array to the blobs


Methodmemsize

intmemsize()

Description

Returns the in-memory size of the blobs


Methodread

arrayread()

Description

returns ({ string word_id, string blob }) or ({0,0}) As a side-effect, this function frees the blob and the word_id, so you can only read the blobs struct once. Also, once you have called read, add_words will no longer work as expected.


Methodread_all_sorted

array(array(string)) read_all_sorted()

Description

Returns ({({ string word1_id, string blob1 }),...}), sorted by word_id in octet order.

Note

This function also frees the blobs and the word_ids, so you can only read the blobs struct once. Also, once you have called read or read_all_sorted, add_words will no longer work as expected.

Class Search.LinkFarm


Methodadd

voidadd(int, array, int, int)


Methodmemsize

intmemsize()

Description

Returns the in-memory size of the linkfarm


Methodread

arrayread()

Description

returns ({ int word_id, Blob b }) or 0

Class Search.MergeFile


Methodcreate

Search.MergeFileSearch.MergeFile(Stdio.File_fd)


Methodmerge_mergefiles

voidmerge_mergefiles(Search.MergeFilea, Search.MergeFileb)


Methodwrite_blobs

voidwrite_blobs(_WhiteFish.Blobsblobs)

Class Search.RankingProfile


Variablecutoff

int Search.RankingProfile.cutoff


Variablefield_ranking

array(int) Search.RankingProfile.field_ranking


Variableproximity_ranking

array(int) Search.RankingProfile.proximity_ranking


Methodcopy

this_programcopy()

Description

Returns a copy of this object.


Methodcreate

Search.RankingProfileSearch.RankingProfile(void|intcutoff, void|array(int) proximity_ranking)
Search.RankingProfileSearch.RankingProfile(intcutoff, array(int) proximity_ranking, Search.Database.Basedb, array(int)|mapping(string:int) field_ranking)

Parameter cutoff

Defaults to 8

Parameter proximity_ranking

Defaults to ({ 8, 7, 6, 5, 4, 3, 2, 1, })

Parameter field_ranking

Defaults to ({ 17, 0, 147 }) + allocate(62).

Parameter db

Only needed if field_ranking is provided as a mapping.

Class Search.ResultSet

Description

A resultset is basically an array of hits from the search.

Note: inheriting this class is _not_ supported (for performance reasons)


Method_sizeof
Methodsize

intsizeof(Search.ResultSetarg)
intsize()

Description

Return the size of this resultset, in entries.


Methodintersect
Method`&

ResultSetintersect(ResultSeta)
ResultSet res = Search.ResultSet() & a

Description

Return a new resultset with all entries that are present in _both_ sets. Only the document_id is checked, the resulting ranking is the sum of the rankings if the two sets.


Method`|
Method`+
Methodor

ResultSet res = Search.ResultSet() | a
ResultSet res = Search.ResultSet() + a
ResultSetor(ResultSeta)

Description

Add the given resultsets together, to generate a resultset with both sets included. The rankings will be added if a document exists in both resultsets.


Methodsub
Method`-

ResultSetsub(ResultSeta)
ResultSet res = Search.ResultSet() - a

Description

Return a new resultset with all entries in a removed from the current ResultSet.

Only the document_id is checked, the ranking is irrelevalt.


Methodadd_ranking

ResultSetadd_ranking(ResultSeta)

Description

Return a new resultset. All entries are the same as in this set, but if an entry exists in a, the ranking from a is added to the ranking of the entry


Methodcast

(array)Search.ResultSet()

Description

Only works when type == "array". Returns the resultset data as a array.


Methoddup

ResultSetdup()

Description

Return a new resultset with the same contents as this one.


Methodmemsize

intmemsize()

Description

Return the size of this resultset, in bytes.


Methodoverhead

intoverhead()

Description

Return the size of the memory overhead, in bytes.

You can minimize the overhead by calling dup(), which will create a new resultset with the exact size needed.


Methodslice

array(array(int)) slice(intfirst, intnelems)

Description

Return nelems entries from the result-set, starting with first. If 'first' is outside the resultset, or nelems is 0, 0 is returned.


Methodsort

voidsort()

Description

Sort this ResultSet according to ranking.


Methodsort

voidsort()

Description

Sort this ResultSet according to ranking.


Methodsort_docid

voidsort_docid()

Description

Sort this ResultSet according to document id.


Methodtest

ResultSettest(intnelems, intstart, intincr)

Description

Fills the resulttest with nelems entries, the document IDs are strictly raising, starting with start, ending with start+nelems*incr.

Used for debug and testing.

Module Search.Database

Class Search.Database.Base

Description

Base class for Search database storage abstraction implementations.


Methodallocate_field_id

intallocate_field_id(stringfield)

Description

Allocate a field id.

Parameter field

The (possibly wide string) field name wanted.

Returns

An allocated numeric id, or -1 if the allocation failed.


Methodcreate

Search.Database.BaseSearch.Database.Base(stringdb_url)

Description

Initialize the database object.

Parameter path

The URL that identifies the underlying database storage


Methodget_blob

stringget_blob(stringword, intnum, void|mapping(string:mapping(int:string)) blobcache)

Description

Retrieves a blob from the database.

Parameter word

The wanted word. Possibly in wide-string format. (Not UTF-8 encoded.)

Parameter num
Parameter blobcache
Returns

The blob requested, or 0 if there's no more blobs.


Methodget_database_size

intget_database_size()

Description

Returns the size, in bytes, of the search database.


Methodget_document_id

intget_document_id(stringuri, void|stringlanguage, void|intdo_not_create)

Description

Retrieve and possibly creates the document id corresponding to the given URI and language code.

Parameter uri

The URI to be retrieved or created.

Parameter language

A two letter ISO-639-1 language code, or 0 if the document is language neutral.

Parameter do_not_create

If non-zero, do not create the document.

Returns

The non-zero numeric identifier if the document identified by uri and language_code exists, or 0 otherwise.


Methodget_field_id

intget_field_id(stringfield, void|intdo_not_create)

Description

Retrieve and possibly creates the numeric id of a field

Parameter field

The (possibly wide string) field name wanted.

Parameter do_not_create

If non-zero, do not allocate a field id for this field

Returns

An allocated numeric id, or -1 if it did not exist, or allocation failed.


Methodget_language_stats

mapping(string|int:int) get_language_stats()

Description

Retrieve statistics about the number of documents in different languages.

Returns

A mapping with the the language code in the index part, and the corresponding number of documents as values.


Methodget_lastmodified

intget_lastmodified(Standards.URI|string|array(Standards.URI|string) uri, void|stringlanguage)

Description

Get last modification time for uri, language.

Returns

Returns modification time in seconds since 1970-01-01T00:00:00 UTC) if known, and 0 (zero) otherwise.


Methodget_metadata

mapping(string:string) get_metadata(int|Standards.URI|stringuri, void|stringlanguage, void|array(string) wanted_fields)

Description

Retrieve a metadata collection for a document.

Parameter uri

The URI of the resource being indexed.

Parameter language

A two letter ISO-639-1 language code, or 0 if the document is language neutral.

Parameter wanted_fields

An array containing the wanted metadata field names, or 0.

Returns

The metadata fields in wanted_fields or all existing fields if wanted_fields is 0.


Methodget_most_common_words

array(array) get_most_common_words(void|intcount)

Description

Returns a list of the count most common words in the database. count defaults to 10.


Methodget_num_deleted_documents

intget_num_deleted_documents()

Description

Returns the number of deleted documents in the database.


Methodget_num_words

intget_num_words()

Description

Returns the number of distinct words in the database.


Methodget_uri_and_language

mappingget_uri_and_language(int|array(int) doc_id)

Description

Retrieve the URI and language code associated with doc_id.

Returns
"uri" : string

The URI of the document.

"language" : void|string

The ISO-639-1 language code of the document, or 0 if not set.


Methodget_uri_id

intget_uri_id(stringuri, void|intdo_not_create)

Description

Retrieve and possibly creates the URI id corresponding to the given URI.

Parameter uri

The URI to be retrieved or created.

Parameter do_not_create

If non-zero, do not create the URI.

Returns

The non-zero numeric identifier if uri exists, or 0 otherwise.


Methodinsert_words

voidinsert_words(Standards.URI|stringuri, void|stringlanguage, stringfield, array(string) words)

Description

Index words into the database. The data may be buffered until the next sync call.

Parameter uri

The URI of the resource being indexed.

Parameter language

A two letter ISO-639-1 language code, or 0 if the document is language neutral.

Parameter field

The field name for the words being indexed.

Parameter words

The words being indexed. Possibly in wide-string format. (Not UTF8 encoded.)


Methodlist_fields

mapping(string:int) list_fields()

Description

Lists all fields in the search database.

Returns

A mapping with the fields in the index part, and the corresponding numeric field id as values.


Methodlist_url_by_prefix

voidlist_url_by_prefix(stringurl_prefix, function(string:void) cb)

Description

Calls cb for all uri:s that match uri_prefix.


Methodremove_document

voidremove_document(string|Standards.URIuri, void|stringlanguage)

Description

Remove a document from the database.

Parameter uri

The URI of the resource being indexed.

Parameter language

A two letter ISO-639-1 language code. If zero, delete all existing language forks with the URI of uri.


Methodremove_document_prefix

voidremove_document_prefix(string|Standards.URIuri)

Description

Removes all documents that matches the provided uri prefix.

Parameter uri

The URI prefix of the documents to delete.


Methodremove_field

voidremove_field(stringfield)

Description

Remove a field from the database. Also removes all stored metadata with this field, but not all indexed words using this field id.

Parameter field

The (possibly wide string) field name to be removed.


Methodremove_metadata

voidremove_metadata(Standards.URI|stringuri, void|stringlanguage)

Description

Remove all metadata for a document

Parameter uri

The URI of the resource whose metadata should be removed.

Parameter language

A two letter ISO-639-1 language code, or 0 if the document is language neutral.


Methodremove_uri

voidremove_uri(string|Standards.URIuri)

Description

Remove URI from the database.

Parameter uri

The URI of the resource being removed.


Methodremove_uri_prefix

voidremove_uri_prefix(string|Standards.URIuri)

Description

Remove URI prefix from the database.

Parameter uri

The URI prefix of the resource being removed.


Methodsafe_remove_field

voidsafe_remove_field(stringfield)

Description

Remove a field from the database if it isn't used by the filters. Also removes all stored metadata with this field, but not all indexed words using this field id.

Parameter field

The (possibly wide string) field name to be removed.


Methodset_lastmodified

voidset_lastmodified(Standards.URI|stringuri, void|stringlanguage, intwhen)

Description

Set last modification time for uri, language to mtime (seconds since 1970-01-01T00:00:00 UTC).


Methodset_metadata

voidset_metadata(Standards.URI|stringuri, void|stringlanguage, mapping(string:string) metadata)

Description

Set a metadata collection for a document.

Parameter uri

The URI of the resource being indexed.

Parameter language

A two letter ISO-639-1 language code, or 0 if the document is language neutral.

Parameter metadata

A collection of metadata strings to be set for a document. The strings may be wide. The "body" metadata may be cut off at 64K.


Methodset_sync_callback

voidset_sync_callback(function(:void) f)

Description

Sets a function to be called when sync has been completed.


Methodsync

voidsync()

Description

Writes the data stored in temporary buffers to permanent storage. Calls the function set by set_sync_callback] when done.

Module Search.Filter

Class Search.Filter.Base


Constantcontenttypes

constantarray(string) Search.Filter.Base.contenttypes

Description

The MIME content types this object can filter.


Constantfields

optional constantarray(string) Search.Filter.Base.fields

Description

The different fields this object can extract from the media. The list can contain any of the following values.

"body"
"title"
"keywords"
"description"
"robots"
"headline"
"modified"
"author"
"summary"

Methodfilter

.Outputfilter(Standards.URIuri, string|Stdio.Filedata, stringcontent_type, mixed ... more)

Class Search.Filter.Output

Description

This object is returned from Search.Filter plugins.


Variabledocument_size

int Search.Filter.Output.document_size

Description

The size of the document.


Variablefields

mapping(string:string) Search.Filter.Output.fields

Description

Data extracted from input, grouped by type. Standard fields are "body", "title", "description", "keywords" and "mtime".

Note

Note that all field values (even "mtime") are strings.


Variablelinks

array(Standards.URI|string) Search.Filter.Output.links

Description

All links collected from the document.


Variableuri_anchors

mapping(string:string) Search.Filter.Output.uri_anchors

Description

Maps un-normalized URLs to raw text, e.g.  ([ "http://pike.lysator.liu.se": "Pike language" ]) .


Methodfix_relative_links

voidfix_relative_links(Standards.URIbase_uri)

Description

Modifies relative links in links to be relative to base_uri.

Module Search.Grammar


MethodgetDefaultFields

multiset(string) getDefaultFields()


Methodoptimize

ParseNode|zerooptimize(ParseNodenode, string|voidparentOp)


Methodremove_stop_words

voidremove_stop_words(ParseNodenode, array(string) stop_words)

Class Search.Grammar.AbstractParser


Methodcreate

Search.Grammar.AbstractParserSearch.Grammar.AbstractParser(void|mapping(string:mixed) options)

Parameter options
"implicit" : string

Either of the strings: "and", "or". If not supplied, default to "or".

"fields" : multiset(string)

The words that should be recognized as fields. If not supplied, it should default to Search.Grammar.getDefaultFields()

Class Search.Grammar.AndNode

Description

And node.


InheritParseNode

inherit ParseNode : ParseNode

Class Search.Grammar.DateNode

Description

Date node.


InheritParseNode

inherit ParseNode : ParseNode

Class Search.Grammar.DefaultParser


InheritAbstractParser

protected inherit .AbstractParser : AbstractParser


InheritLexer

protected inherit .Lexer : Lexer


Variableoptions

mapping(string:mixed) Search.Grammar.DefaultParser.options


Methodcreate

Search.Grammar.DefaultParserSearch.Grammar.DefaultParser(mapping(string:mixed)|voidopt)


Methodparse

ParseNodeparse(stringq)

Class Search.Grammar.OrNode

Description

Or node.


InheritParseNode

inherit ParseNode : ParseNode

Class Search.Grammar.ParseNode

Description

Abstract parse tree node.

Class Search.Grammar.TextNode

Description

Text node.


InheritParseNode

inherit ParseNode : ParseNode

Module Search.Grammar.Lexer


Methodtokenize

string|array(array(Token|string)) tokenize(stringquery)

Description

Tokenizes a query into tokens for later use by a parser.

Parameter query

The query to tokenize.

Returns

An array containing the tokens: ({ ({ TOKEN_WORD, "foo" }), ... }) Or, in case of an error, a string with the error message.

Enum Search.Grammar.Lexer.Token


ConstantTOKEN_AND
ConstantTOKEN_OR

constant Search.Grammar.Lexer.TOKEN_AND
constant Search.Grammar.Lexer.TOKEN_OR


ConstantTOKEN_PLUS
ConstantTOKEN_MINUS
ConstantTOKEN_COLON

constant Search.Grammar.Lexer.TOKEN_PLUS
constant Search.Grammar.Lexer.TOKEN_MINUS
constant Search.Grammar.Lexer.TOKEN_COLON


ConstantTOKEN_END

constant Search.Grammar.Lexer.TOKEN_END


ConstantTOKEN_EQUAL
ConstantTOKEN_LESSEQUAL
ConstantTOKEN_GREATEREQUAL
ConstantTOKEN_NOTEQUAL
ConstantTOKEN_LESS
ConstantTOKEN_GREATER

constant Search.Grammar.Lexer.TOKEN_EQUAL
constant Search.Grammar.Lexer.TOKEN_LESSEQUAL
constant Search.Grammar.Lexer.TOKEN_GREATEREQUAL
constant Search.Grammar.Lexer.TOKEN_NOTEQUAL
constant Search.Grammar.Lexer.TOKEN_LESS
constant Search.Grammar.Lexer.TOKEN_GREATER


ConstantTOKEN_LPAREN
ConstantTOKEN_RPAREN

constant Search.Grammar.Lexer.TOKEN_LPAREN
constant Search.Grammar.Lexer.TOKEN_RPAREN


ConstantTOKEN_TEXT

constant Search.Grammar.Lexer.TOKEN_TEXT


ConstantTOKEN_UNKNOWN

constant Search.Grammar.Lexer.TOKEN_UNKNOWN

Module Search.Indexer


Methodextension_to_type

stringextension_to_type(stringextension)


Methodfilename_to_type

stringfilename_to_type(stringfilename)


Methodfilter_and_index

Search.Filter.Output|zerofilter_and_index(Search.Database.Basedb, string|Standards.URIuri, void|stringlanguage, string|Stdio.Filedata, stringcontent_type, void|mappingheaders, void|stringdefault_charset)


Methodindex_document

voidindex_document(Search.Database.Basedb, string|Standards.URIuri, void|stringlanguage, mappingfields)


Methodremove_document

voidremove_document(Search.Database.Basedb, string|Standards.URIuri, void|stringlanguage)

Module Search.Query


Methodexecute

array(Search.ResultSet|array(string)) execute(Search.Database.Basedb, Search.Grammar.AbstractParserparser, stringquery, Search.RankingProfileranking, void|array(string) stop_words, search_order|voidorder)

Parameter query

The query string entered by user.

Parameter db

The search database.

Parameter defaultRanking

Used when searching in the field "any:".

Returns

An array with three elements:

Array
Search.ResultSet0

The ResultSet containing the hits.

array(string) 1

All wanted words in the query. (I.e. not the words that were preceded by minus.)

array(mapping) 2

All wanted globs in the query. (I.e. not the globs that were preceded by minus.)

Enum Search.Query.search_order


ConstantRELEVANCE
ConstantDATE_ASC
ConstantDATE_DESC
ConstantNONE
ConstantPUBL_DATE_ASC
ConstantPUBL_DATE_DESC

constant Search.Query.RELEVANCE
constant Search.Query.DATE_ASC
constant Search.Query.DATE_DESC
constant Search.Query.NONE
constant Search.Query.PUBL_DATE_ASC
constant Search.Query.PUBL_DATE_DESC

Module Search.Queue

Class Search.Queue.Base

Description

Virtual base class for the Search crawler state.


InheritQueue

inherit Web.Crawler.Queue : Queue


Methodadd_uri

voidadd_uri(Standards.URIuri, intrecurse, stringtemplate, void|intforce)

Description

Add an URI to be crawled.


Methodclear

voidclear()

Description

Clear and empty the entire queue.


Methodclear_cache

voidclear_cache()

Description

Clear any RAM caches.


Methodclear_md5

voidclear_md5(int ... stages)

Description

Clear the content MD5 for all URIs at the specified stages.


Methodclear_stage

voidclear_stage(int ... stages)

Description

Reset all URIs at the specified stage to stage 0 (zero).


Methodget

int|Standards.URIget()


Methodget_extra

mappingget_extra(Standards.URIuri)

Returns

Returns a mapping with the current state for the URI.

"md5" : string
"recurse" : string|int
"stage" : string|int
"template" : string
FIXME

Currently this function always returns a mapping(string:string), but this may change to the above in the future.


Methodget_uris

array(Standards.URI) get_uris(void|intstage)

Returns

Returns all URIs if no stage is specified, otherwise returns the URIs at the specified stage.

FIXME

State 0 (zero) is a special case, and returns all URIs. This may change in the future.


Methodnum_with_stage

intnum_with_stage(int ... stage)

Returns

Returns the number of URIs at the specified stage(s).


Methodput

voidput(string|array(string)|Standards.URI|array(Standards.URI) uri)

Description

Add one or multiple URIs to the queue.

All the URIs will be added with recursion enabled and an empty template.


Methodremove_stage

voidremove_stage(intstage)

Description

Remove all URIs at the specified stage.


Methodremove_uri

voidremove_uri(string|Standards.URIuri)

Description

Remove an URI from the queue.


Methodremove_uri_prefix

voidremove_uri_prefix(string|Standards.URIuri)

Description

Remove all URIs with the specified prefix from the queue.


Methodset_md5

voidset_md5(Standards.URIuri, stringmd5)

Description

Set the content MD5 for an URI.


Methodset_recurse

voidset_recurse(Standards.URIuri, intrecurse)

Description

Set the recurse mode for an URI.


Methodset_stage

voidset_stage(Standards.URIuri, intstage)

Description

Set the stage for a single URI.

Enum Search.Queue.Base.Stage

Description

The queue stage levels.


ConstantSTAGE_WAITING
ConstantSTAGE_FETCHING
ConstantSTAGE_FETCHED
ConstantSTAGE_FILTERED
ConstantSTAGE_INDEXED
ConstantSTAGE_COMPLETED
ConstantSTAGE_ERROR

constant Search.Queue.Base.STAGE_WAITING
constant Search.Queue.Base.STAGE_FETCHING
constant Search.Queue.Base.STAGE_FETCHED
constant Search.Queue.Base.STAGE_FILTERED
constant Search.Queue.Base.STAGE_INDEXED
constant Search.Queue.Base.STAGE_COMPLETED
constant Search.Queue.Base.STAGE_ERROR

Class Search.Queue.MySQL

Description

Search crawler state stored in a Mysql database.


InheritBase

inherit .Base : Base


Methodcreate

Search.Queue.MySQLSearch.Queue.MySQL(Web.Crawler.Stats_stats, Web.Crawler.Policy_policy, string_url, string_table, void|Web.Crawler.RuleSet_allow, void|Web.Crawler.RuleSet_deny)

Parameter _url

Sql.Sql URL for the database to store the queue.

Parameter _table

Sql.Sql table name to store the queue in.

If the table doesn't exist it will be created.


Methodget_schemes

array(string) get_schemes()

Returns

Returns an array with all URI schemes currently used in the queue.


Methodget_stage

intget_stage(Standards.URIuri)

Returns

Returns the current stage for the specified URI.

See also

set_stage()


Methodreset_stage

voidreset_stage(string|voiduri_prefix)

Description

Reset the stage to 0 (zero) for all URIs with the specified uri_prefix. If no uri_prefix is specified reset the stage for all URIs.

Module Search.Utils


Methodflush_profile

voidflush_profile(intp)

Description

Flushes the profile p from all ProfileCache objects obtained with get_profile_cache.


Methodget_profile_cache

ProfileCacheget_profile_cache(stringdb_name)

Description

Returns a ProfileCache for the profiles stored in the database db_name.


Methodget_profile_storage

mappingget_profile_storage(stringdb_name)

Description

Returns a profile storage mapping, which will be shared between all callers with the same db_name given.


Methodget_scheduler

Schedulerget_scheduler(stringdb_name)

Description

Returns a scheduler for the given profile database.


Methodnormalize

stringnormalize(stringin)

Description

Normalize the input string. Performs unicode NFKD normalization and then lowercases the whole string


Methodtokenize

array(string) tokenize(stringin)

Description

Tokenize the input string (Note: You should first call normalize on it)


Methodtokenize_and_normalize

array(string) tokenize_and_normalize(stringwhat)

Description

This can be optimized quite significantly when compared to tokenize( normalize( x ) ) in the future, currently it's not all that much faster, but still faster.

Class Search.Utils.Logger


Methodadd_program_name

intadd_program_name(intcode, stringname)


Methodcreate

Search.Utils.LoggerSearch.Utils.Logger(Sql.Sqldb_object, intprofile, intstderr_logging)
Search.Utils.LoggerSearch.Utils.Logger(stringdb_url, intprofile, intstderr_logging)


Methodget_log

array(array(string|int)) get_log(intprofile, array(string) types, intfrom, intto)


Methodlog_error

voidlog_error(intcode, void|stringextra, void|intlog_profile)


Methodlog_event

voidlog_event(intcode, stringtype, void|stringextra, void|intlog_profile)


Methodlog_notice

voidlog_notice(intcode, void|stringextra, void|intlog_profile)


Methodlog_warning

voidlog_warning(intcode, void|stringextra, void|intlog_profile)

Class Search.Utils.ProfileCache


Variabledb_name

string Search.Utils.ProfileCache.db_name


Method__create__

protectedlocalvoid__create__(stringdb_name)


Methodcreate

Search.Utils.ProfileCacheSearch.Utils.ProfileCache(stringdb_name)


Methodflush_cache

voidflush_cache()

Description

Empty the whole cache.


Methodflush_profile

voidflush_profile(intp)

Description

Flushes profile entry p from the profile cache.


Methodget_db_profile_number

intget_db_profile_number(stringname)

Description

Returns the profile number for the given database profile.


Methodget_profile_entry

ProfileEntryget_profile_entry(stringdb_name, void|stringquery_name)

Description

Returns a ProfileEntry object with the states needed for commiting searches in the database profile db_name with the rules from query profile query_name.


Methodget_query_profile_number

intget_query_profile_number(stringname)

Description

Returns the profile number for the given query profile.


Methodget_value_mapping

mappingget_value_mapping(intprofile)

Description

Returns the value mapping for the given profile.


Methodlist_db_profiles

array(string) list_db_profiles()

Description

Returns a list of available database profiles.


Methodlist_query_profiles

array(string) list_query_profiles()

Description

Returns a list of available query profiles.


Methodup_to_datep

int(-1..1)up_to_datep(intprofile_id)

Description

Checks if the profile profile_id has been changed, and clears related caches if so.

Returns
-1

The profile is deleted.

0

The profile is not up to date.

1

The profile is up to date.

Class Search.Utils.ProfileEntry

Description

A result entry from the ProfileCache.


Methodcheck_timeout

boolcheck_timeout()

Description

Checks if it is time to check if the profile values are to old.


Methodcreate

Search.Utils.ProfileEntrySearch.Utils.ProfileEntry(intdatabase_profile_id, intquery_profile_id, ProfileCachecache)

Parameter cache

The parent cache object.


Methodget_database

Search.Database.MySQLget_database()

Description

Returns a cached search database for the current database profile.


Methodget_database_value

mixedget_database_value(stringindex)

Description

Returns the database profile value index.


Methodget_query_value

mixedget_query_value(stringindex)

Description

Returns the query profile value index.


Methodget_ranking

Search.RankingProfileget_ranking()

Description

Returns a cached ranking profile for the current database and query profile.


Methodget_stop_words

array(string) get_stop_words()

Description

Returns a cached array of stop words for the current query profile.

Class Search.Utils.Scheduler


Methodnew_entry

voidnew_entry(intlatency, array(int) profiles)

Description

Call this method to indicate that a new entry has been added to the queue. The scheduler will delay indexing with at most latency minutes.

Module Serializer

Description

Serialization interface.

This module contains APIs to simplify serialization and deserialization of objects.

See also

serialize(), deserialize()


Methoddeserialize

voiddeserialize(objecto, function(function(mixed:void), string, type:void) deserializer)

Description

Call lfun::_deserialize() in o.

See also

serialize(), lfun::_deserialize(), Serializable()->_deserialize()


Methodserialize

voidserialize(objecto, function(mixed, string, type:void) serializer)

Description

Call lfun::_serialize() in o.

See also

deserialize(), lfun::_serialize(), Serializable()->_serialize()

Class Serializer.Encodeable

Description

Simple base for an object that can be serialized by encode_value. Also supports decoding.

Uses Serializable as it's base.

Simply inherit this class in the classes you want to have encoded and decoded.

Note that it's not automatically recursive, objects assigned to variables in this object have to be Encodeable on their own for encode to work.

When decoding only variables that existed at the time the object was encoded are assigned, that is, if the class now has more variables they new variables will be set to 0.


InheritSerializable

inherit Serializable : Serializable


Method_decode

Serializer.Encodeabledecode_value(string(8bit)data)

Description

Callback for decoding the object. Sets variables in the object from the values in the mapping.

Called automatically by decode_value, not normally called manually.


Method_encode

string(8bit)encode_value(Serializer.Encodeabledata)

Description

Callback for encoding the object. Returns a mapping from variable name to value.

Called automatically by encode_value, not normally called manually.

Class Serializer.Serializable

Description

The base class for serializable objects.

Inherit this class in classes that need to be serializable.

See also

Serializer.serialize(), Serializer.deserialize()


Method_deserialize

protectedvoid_deserialize(objecto, function(function(mixed:void), string, type:void) deserializer)

Description

Dispatch function for deserialization.

Parameter o

Object to serialize. Always a context of the current object.

Parameter deserializer

Function to typically be called once for every variable in the inheriting class.

This function calls _deserialize_variable() once for every variable in the inheriting class, which in turn will call deserializer with the arguments:

Argument 1

The setter for the variable.

Argument 2

The name of the variable.

Argument 3

The declared type of the variable.

Note

The symbols will be listed in the order they were defined in the class.

Note

This function is typically called via Serializer.deserialize().

See also

Serializer.deserialize(), _deserialize_variable(), _serialize(), Builtin.Setter


Method_deserialize_variable

protectedvoid_deserialize_variable(function(function(mixed:void), string, type:void) deserializer, function(mixed:void) setter, stringsymbol, typesymbol_type)

Description

Default deserialization function for variables.

Parameter deserializer

Function to be called in turn.

Parameter setter

Function that sets the value of the variable.

Parameter symbol

Variable name.

Parameter symbol_type

Type of the variable.

This function is typically called from _deserialize(), and does something like:

if(object_typep(symbol_type)){program p = program_from_type(symbol_type);if(p && !needs_parent(p) && is_deserializable(p)){object value = p();
        setter(value);Serializer.deserialize(value, deserializer);return;}}
    deserializer(setter, symbol, symbol_type);
Note

The above takes care of the most common cases, but

  • Does not support anonymous object types.

  • Does not support objects needing a parent.

  • Does not support non-serializable objects.

  • Selects one of the object types in case of a complex symbol_type. The selected type is NOT deterministic in case there are multiple choices that satisfy the above.

  • Is likely to throw errors if p() requires arguments.

These issues can all be solved by overloading this function.

See also

_deserialize(), _serialize_variable(), Builtin.Setter


Method_serialize

protectedvoid_serialize(objecto, function(mixed, string, type:void) serializer)

Description

Dispatch function for serialization.

Parameter o

Object to serialize. Always a context of the current object.

Parameter serializer

Function to typically be called once for every variable in the inheriting class.

This function calls _serialize_variable() once for every variable in the inheriting class, which in turn will call serializer with the arguments:

Argument 1

The value of the variable.

Argument 2

The name of the variable.

Argument 3

The declared type of the variable.

Note

The symbols will be listed in the order they were defined in the class.

Note

This function is typically called via Serializer.serialize().

See also

Serializer.serialize(), _serialize_variable(), _deserialize()


Method_serialize_variable

protectedvoid_serialize_variable(function(mixed, string, type:void) serializer, mixedvalue, stringsymbol, typesymbol_type)

Description

Default serialization function for variables.

Parameter serializer

Function to be called in turn.

Parameter value

Value of the variable.

Parameter symbol

Variable name.

Parameter symbol_type

Type of the variable.

This function is typically called from _serialize(), and just does

serializer(value, symbol, symbol_type);

It is provided for overloading for eg filtering or validation purposes.

See also

_serialize(), _deserialize_variable()

Module Shuffler

Description

Module implementing sending to and from nonblocking streams and other sources.

Most useful when implementing sending of data from strings, files and other sources to a network connection. The module also supports generic bandwidth throttling.

Multiple Shuffler object can be created, each optionally with their own backend.

This makes it easier to use more than one CPU for pure data transmission, just have multiple backends each in their own thread, with their own shuffle object.


ConstantINITIAL
ConstantRUNNING
ConstantPAUSED
ConstantDONE
ConstantWRITE_ERROR
ConstantREAD_ERROR
ConstantUSER_ABORT

constant Shuffler.INITIAL
constant Shuffler.RUNNING
constant Shuffler.PAUSED
constant Shuffler.DONE
constant Shuffler.WRITE_ERROR
constant Shuffler.READ_ERROR
constant Shuffler.USER_ABORT

Description

The state of an individual Shuffle object.

Class Shuffler.Shuffle

Description

This class contains the state for one ongoing data shuffling operation. To create a Shuffle instance, use the Shuffler()->shuffle method.


Variableshuffler

Shuffler Shuffler.Shuffle.shuffler

Description

The Shuffler that owns this Shuffle object


Variablethrottler

Throttler Shuffler.Shuffle.throttler

Description

The Throttler that is associated with this Shuffle object, if any.


Methodadd_source

voidadd_source(mixedsource, int|voidstart, int|voidlength)
voidadd_source(mixedsource, function(Shuffle, int:array(string)|zero) wrap_cb)
voidadd_source(arraysource)
voidadd_source(arraysource, function(Shuffle, int:array(string)|zero) wrap_cb)

Description

Add a new source to the list of data sources. The data from the sources will be sent in order.

If start and length are not specified, the whole source will be sent, if start but not length is specified, the whole source, excluding the first start bytes will be sent.

Currently supported sources

int

An ordinary 8-bit wide byte.

string

An ordinary 8-bit wide pike string.

System.Memory

An initialized instance of the System.Memory class.

Stdio.Buffer

A Stdio.Buffer object which will be called once with read_buffer() to acquire the data.

Stdio.File

Stdio.File instance pointing to a normal file.

Stdio.Stream

Stdio.File instance pointing to a stream of some kind (network socket, named pipe, stdin etc). Blocking or nonblocking.

Stdio.NonblockingStream|Stdio.Stream

An object implementing the callback based reading (set_read_callback and set_close_callback).

array

An array of any of the supported sources. Note that neither start nor length can be specified then.


Methodcreate

Shuffler.ShuffleShuffler.Shuffle(objectfd, objectshuffler, mixedthrottler, mixedbackend, void|intstart, void|intlength)

Description

This object is normally not created directly, instead use Shuffler()->shuffle


Methodpause

voidpause()

Description

Temporarily pause all data transmission


Methodsent_data

intsent_data()

Description

Returns the amount of data that has been sent so far.


Methodset_done_callback

voidset_done_callback(function(Shuffle, int:void) cb)

Description

Sets the done callback. This function will be called when all sources have been processed, or if an error occurs.


Methodset_request_arg

voidset_request_arg(mixedarg)

Description

Sets the extra argument sent to Throttler()->request() and Throttler()->give_back.


Methodset_throttler

voidset_throttler(Throttlert)

Description

Calling this function overrides the Shuffler global throttler.


Methodstart

voidstart(void|intautopause, void|intfreerun)

Description

Start sending data from the sources.

Parameter autopause

If true, automatically pause the shuffler when all sources have been consumed. Everytime this happens, the done_callback will ben called.

Parameter freerun

If true, do not attempt to coalesce output by using bulkmode.


Methodstate

intstate()

Description

Returns the current state of the shuffler. This is one of the following: INITIAL, RUNNING, PAUSED, DONE, WRITE_ERROR, READ_ERROR and USER_ABORT


Methodstop

voidstop()

Description

Stop all data transmission, and then call the done callback

Class Shuffler.Shuffler

Description

A data shuffler. An instance of this class handles a list of Shuffle objects. Each Shuffle object can send data from one or more sources to a destination in the background.


Methodpause

voidpause()

Description

Pause all Shuffle objects associated with this Shuffler


Methodset_backend

voidset_backend(Pike.Backendb)

Description

Set the backend that will be used by all Shuffle objects created from this shuffler.


Methodset_throttler

voidset_throttler(Throttlert)

Description

Set the throttler that will be used in all Shuffle objects created from this shuffler, unless overridden in the Shuffle objects.


Methodshuffle

Shuffleshuffle(Stdio.NonblockingStreamdestination, int|voidstart, int|voidlength)

Description

Create a new Shuffle object.

The destination has to support nonblocking I/O through set_nonblocking_keep_callbacks and set_write_callback member functions.

Note

For destinations that connect directly to a kernel-filedescriptor please note that the filedescriptor will be dup()ed for the duration of the shuffle. This means that if the original destination object is kept, we temporarily use two filedescriptors for it.


Methodstart

voidstart()

Description

Unpause all Shuffle objects associated with this Shuffler

Class Shuffler.Throttler

Note

This is an interface that all Throttlers must implement. It's not an actual class in this module.


Methodgive_back

voidgive_back(Shuffleshuffle, intamount)

Description

This function will be called by the Shuffle object to report that some data assigned to it by this throttler was unused, and can be given to another Shuffle object instead.


Methodrequest

voidrequest(Shuffleshuffle, intamount, function(int:void) callback)

Description

This function is called when the Shuffle wants to send some data to a client.

When data can be sent, the callback function should be called with the amount of data that can be sent as the argument.

Module Standards

Class Standards.URI

Description

This class implements URI parsing and resolving of relative references to absolute form, as defined in RFC 2396 and RFC 3986.


Variableauthority

string|zero Standards.URI.authority

Description

Authority component of URI (formerly called net_loc, from RFC 2396 known as authority)


Variablebase_uri

this_program|zero Standards.URI.base_uri

Description

The base URI object, if present


Variablefragment

string|zero Standards.URI.fragment

Description

The fragment part of URI. May be 0 if not present.


Variablehost
Variableuser
Variablepassword

string|zero Standards.URI.host
string|zero Standards.URI.user
string|zero Standards.URI.password

Description

Certain classes of URI (e.g. URL) may have these defined


Variablepath

string Standards.URI.path

Description

Path component of URI. May be empty, but not undefined.


Variableport

int Standards.URI.port

Description

If no port number is present in URI, but the scheme used has a default port number, this number is put here.


Variablequery

string|zero Standards.URI.query

Description

Query component of URI. May be 0 if not present.


Variablescheme

string|zero Standards.URI.scheme

Description

Scheme component of URI


Method`->=
Method`[]=

Standards.URI()->X = value
Standards.URI()[ property ] = value

Description

Assign a new value to a property of URI

Parameter property

When any of the following properties are used, properties that depend on them are recalculated: user, password, host, port, authority, base_uri.

Parameter value

The value to assign to property


Method`==

int res = Standards.URI() == something

Description

Compare this URI to something, in a canonical way.

Parameter something

Compare the URI to this


Methodadd_query_variable

voidadd_query_variable(stringname, stringvalue)

Description

Adds the provided query variable to the already existing ones. Will overwrite an existing variable with the same name.


Methodadd_query_variables

voidadd_query_variables(mapping(string:string) vars)

Description

Appends the provided set of query variables with the already existing ones. Will overwrite all existing variables with the same names.


Methodcast

(string)Standards.URI()
(mapping)Standards.URI()

Description

When cast to string, return the URI (in a canonicalized form). When cast to mapping, return a mapping with scheme, authority, user, password, host, port, path, query, fragment, raw_uri, base_uri as documented above.


Methodcreate

Standards.URIStandards.URI(URIuri)
Standards.URIStandards.URI(URIuri, URIbase_uri)
Standards.URIStandards.URI(URIuri, stringbase_uri)
Standards.URIStandards.URI(stringuri)
Standards.URIStandards.URI(stringuri, URIbase_uri)
Standards.URIStandards.URI(stringuri, stringbase_uri)

Parameter base_uri

When supplied, will root the URI a the given location. This is needed to correctly verify relative URIs, but may be left out otherwise. If left out, and uri is a relative URI, an error is thrown.

Parameter uri

When uri is another URI object, the created URI will inherit all properties of the supplied uri except, of course, for its base_uri.

Throws

An exception is thrown if the uri is a relative URI or only a fragment, and missing a base_uri.


Methodget_http_path_query

stringget_http_path_query()

Description

Return the path and query part of the URI, coded according to RFC 1738.


Methodget_http_query

string|zeroget_http_query()

Description

Return the query part, coded according to RFC 1738, or zero.


Methodget_path_query

stringget_path_query()

Description

Returns path and query part of the URI if present.


Methodget_query_variables

mapping(string:string) get_query_variables()

Description

Returns the query variables as a mapping(string:string).


Methodreparse_uri

voidreparse_uri()
voidreparse_uri(URIbase_uri)
voidreparse_uri(stringbase_uri)

Description

Reparse the URI with respect to a new base URI. If no base_uri was supplied, the old base_uri is thrown away. The resolving is performed according to the guidelines outlined by RFC 2396, Uniform Resource Identifiers (URI): Generic Syntax.

Parameter base_uri

Set the new base URI to this.

Throws

An exception is thrown if the uri is a relative URI or only a fragment, and missing a base_uri.


Methodset_query_variables

voidset_query_variables(mapping(string:string) vars)

Description

Sets the query variables from the provided mapping.

Module Standards.ASN1


Methoddecode_der_oid

stringdecode_der_oid(stringder_oid)

Description

Convenience function to convert a DER/BER encoded oid (object identifier) to the human readable dotted-decimal form.

See also

encode_der_oid


Methodencode_der_oid

stringencode_der_oid(stringdotted_decimal)

Description

Convenience function to convert an oid (object identifier) on dotted-decimal form (e.g. "1.3.6.1.4.1.1466.115.121.1.38") to its DER (and hence also BER) encoded form.

See also

decode_der_oid

Module Standards.ASN1.Decode

Description

Decodes a DER object.


Methodder_decode

.Types.Objectder_decode(Stdio.Bufferdata, mapping(int:program) types, void|boolsecure)

Parameter data

An instance of Stdio.Buffer containing the DER encoded data.

Parameter types

A mapping from combined tag numbers to classes from or derived from Standards.ASN1.Types. Combined tag numbers may be generated using Standards.ASN1.Types.make_combined_tag.

Parameter secure

Will fail if the encoded ASN.1 isn't in its canonical encoding.

Returns

An object from Standards.ASN1.Types or, either Standards.ASN1.Decode.Primitive or Standards.ASN1.Decode.constructed, if the type is unknown. Throws an exception if the data could not be decoded.

FIXME

Handling of implicit and explicit ASN.1 tagging, as well as other context dependence, is next to non_existant.


Methodsecure_der_decode

.Types.Object|zerosecure_der_decode(string(8bit)data, mapping(int:program)|voidtypes)

Description

Works just like simple_der_decode, except it will return 0 on errors, including if there is leading or trailing data in the provided ASN.1 data.

See also

simple_der_decode


Methodsimple_der_decode

.Types.Objectsimple_der_decode(string(8bit)data, mapping(int:program)|voidtypes)

Description

decode a DER encoded object using universal data types

Parameter data

a DER encoded object

Parameter types

An optional set of application-specific types. Should map combined tag numbers to classes from or derived from Standards.ASN1.Types. Combined tag numbers may be generated using Standards.ASN1.Types.make_combined_tag. This set is used to extend universal_types.

Returns

an object from Standards.ASN1.Types or either Standards.ASN1.Decode.Primitive or Standards.ASN1.Decode.Constructed if the type is unknown.

Class Standards.ASN1.Decode.Constructed

Description

Constructed type


InheritCompound

inherit .Types.Compound : Compound


Variablecls
Variabletag
Variableraw
Variableelements

int Standards.ASN1.Decode.Constructed.cls
int Standards.ASN1.Decode.Constructed.tag
string(8bit) Standards.ASN1.Decode.Constructed.raw
array(.Types.Object) Standards.ASN1.Decode.Constructed.elements


Method__create__

protectedlocalvoid__create__(intcls, inttag, string(8bit)raw, array(.Types.Object) elements)


Methodcreate

Standards.ASN1.Decode.ConstructedStandards.ASN1.Decode.Constructed(intcls, inttag, string(8bit)raw, array(.Types.Object) elements)


Methodget_der_content

string(8bit)get_der_content()

Description

Get raw encoded contents of object

Class Standards.ASN1.Decode.Primitive

Description

Primitive unconstructed ASN1 data type.


InheritObject

inherit Types.Object : Object


Variablecls
Variabletag
Variableraw

int Standards.ASN1.Decode.Primitive.cls
int Standards.ASN1.Decode.Primitive.tag
string(8bit) Standards.ASN1.Decode.Primitive.raw


Method__create__

protectedlocalvoid__create__(intcls, inttag, string(8bit)raw)


Methodcreate

Standards.ASN1.Decode.PrimitiveStandards.ASN1.Decode.Primitive(intcls, inttag, string(8bit)raw)


Methodget_der_content

string(8bit)get_der_content()

Description

Get raw encoded contents of object

Module Standards.ASN1.Types

Description

Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)


VariableTaggedType0
VariableTaggedType1
VariableTaggedType2
VariableTaggedType3

MetaExplicit Standards.ASN1.Types.TaggedType0
MetaExplicit Standards.ASN1.Types.TaggedType1
MetaExplicit Standards.ASN1.Types.TaggedType2
MetaExplicit Standards.ASN1.Types.TaggedType3

Description

Some common explicit tags for convenience.

These are typically used to indicate which of several optional fields are present.

Example

Eg RFC 5915 section 3:

ECPrivateKey ::= SEQUENCE {
      version        INTEGER { ecPrivkeyVer1(1)}(ecPrivkeyVer1),
      privateKey     OCTET STRING,
      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
      publicKey  [1] BIT STRING OPTIONAL
    }

The presence of the fields parameters and publicKey above are indicated with TaggedType0 and TaggedType1 respectively.


Methodasn1_IA5_valid

boolasn1_IA5_valid(strings)


Methodasn1_bmp_valid

boolasn1_bmp_valid(strings)


Methodasn1_broken_teletex_valid

boolasn1_broken_teletex_valid(strings)


Methodasn1_printable_valid

boolasn1_printable_valid(strings)

Description

Checks if a Pike string can be encoded as a PrintableString.


Methodasn1_universal_valid

int(0)asn1_universal_valid(strings)


Methodasn1_utf8_valid

int(1)asn1_utf8_valid(strings)

Description

Checks if a Pike string can be encoded with UTF8. That is always the case...


Methodextract_cls

int(2bit)extract_cls(int(0..)i)

Description

Extract ASN1 type class from a combined tag.

See also

make_combined_tag


Methodextract_tag

int(0..)extract_tag(int(0..)i)

Description

Extract ASN1 type tag from a combined tag.

See also

make_combined_tag


Methodmake_combined_tag

int(0..)make_combined_tag(int(2bit)cls, int(0..)tag)

Description

Combines tag and class to a single integer, for internal uses.

Parameter cls

ASN1 type class.

Parameter tag

ASN1 type tag.

Returns

The combined tag.

See also

extract_tag, extract_cls

Class Standards.ASN1.Types.BMPString

Annotations
@Pike.Annotations.Implements(Object)
Description

BMP String object

Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 2 octets per character.

FIXME: The encoding is very likely UCS-2, but that's not yet verified.


InheritOctetString

inherit OctetString : OctetString

Class Standards.ASN1.Types.BitString

Annotations
@Pike.Annotations.Implements(Object)
Description

Bit string object


InheritObject

inherit Object : Object


Variablevalue

string(8bit) Standards.ASN1.Types.BitString.value

Description

value of object


Methodset_from_ascii

this_programset_from_ascii(string(8bit)s)

Description

Set the bitstring value as a string with "1" and "0".


Methodset_length

this_programset_length(intlen)

Description

Sets the length of the bit string to len number of bits. Will only work correctly on strings longer than len bits.

Class Standards.ASN1.Types.Boolean

Annotations
@Pike.Annotations.Implements(Object)
Description

boolean object


InheritObject

inherit Object : Object


Variablevalue

int Standards.ASN1.Types.Boolean.value

Description

value of object

Class Standards.ASN1.Types.BrokenTeletexString

Annotations
@Pike.Annotations.Implements(Object)
Description

(broken) TeletexString object

Encodes and decodes latin1, but labels it TeletexString, as is common in many broken programs (e.g. Netscape 4.0X).


InheritString

inherit String : String

Class Standards.ASN1.Types.Compound

Annotations
@Pike.Annotations.Implements(Object)
Description

Compound object primitive


InheritObject

inherit Object : Object


Constantconstructed

constantint Standards.ASN1.Types.Compound.constructed


Variableelements

array(Object) Standards.ASN1.Types.Compound.elements

Description

Contents of compound object.

Class Standards.ASN1.Types.Enumerated

Annotations
@Pike.Annotations.Implements(Object)
Description

Enumerated object


InheritInteger

inherit Integer : Integer

Class Standards.ASN1.Types.GeneralizedTime

Annotations
@Pike.Annotations.Implements(UTC)

InheritUTC

inherit UTC : UTC


Methodget_posix

intget_posix()


Methodset_posix

variantthis_programset_posix(Calendar.ISO_UTC.Secondsecond)

Class Standards.ASN1.Types.IA5String

Annotations
@Pike.Annotations.Implements(Object)
Description

IA5 String object

Character set: ASCII. Fixed width encoding with 1 octet per character.


InheritString

inherit String : String

Class Standards.ASN1.Types.Identifier

Annotations
@Pike.Annotations.Implements(Object)
Description

Object identifier object


InheritObject

inherit Object : Object


Variableid

array(int) Standards.ASN1.Types.Identifier.id

Description

value of object


Methodappend

this_programappend(int ... args)

Description

Returns a new Identifier object with args appended to the ID path.

Class Standards.ASN1.Types.Integer

Annotations
@Pike.Annotations.Implements(Object)
Description

Integer object All integers are represented as bignums, for simplicity


InheritObject

inherit Object : Object


Variablevalue

Gmp.mpz Standards.ASN1.Types.Integer.value

Description

value of object

Class Standards.ASN1.Types.MetaExplicit

Description

Meta-instances handle a particular explicit tag and set of types. Once cloned this object works as a factory for Compound objects with the cls and tag that the meta object was initialized with.

Example

MetaExplicit m = MetaExplicit(1,2); Compound c = m(Integer(3));


Methodcreate

Standards.ASN1.Types.MetaExplicitStandards.ASN1.Types.MetaExplicit(int(2bit)cls, int(0..)tag, mapping(int:program)|voidtypes)

Class Standards.ASN1.Types.MetaExplicit.`()

Annotations
@Pike.Annotations.Implements(Object)

InheritCompound

inherit Compound : Compound

Class Standards.ASN1.Types.Null

Annotations
@Pike.Annotations.Implements(Object)
Description

Null object


InheritObject

inherit Object : Object

Class Standards.ASN1.Types.Object

Description

Generic, abstract base class for ASN1 data types.


Constantconstructed

constantint Standards.ASN1.Types.Object.constructed

Description

Flag indicating whether this type is a constructed (aka Compound) type or not.


Constanttype_name

constantstring Standards.ASN1.Types.Object.type_name

Description

ASN1 type name.


Variablecls

int(2bit) Standards.ASN1.Types.Object.cls

Description

ASN1 type class.


Variabletag

int(0..) Standards.ASN1.Types.Object.tag

Description

ASN1 type tag.


Methodget_cls

int(2bit)get_cls()

Description

Get the class of this object.

Returns

The class of this object.


Methodget_combined_tag

int(0..)get_combined_tag()

Description

Get the combined tag (tag + class) for this object.

Returns

the combined tag header


Methodget_der

string(8bit)get_der()

Description

Get the DER encoded version of this object.

Returns

DER encoded representation of this object.


Methodget_tag

int(0..)get_tag()

Description

Get the tag for this object.

Returns

The tag for this object.

Class Standards.ASN1.Types.OctetString

Annotations
@Pike.Annotations.Implements(Object)
Description

Octet string object


InheritString

inherit String : String

Class Standards.ASN1.Types.PrintableString

Annotations
@Pike.Annotations.Implements(Object)
Description

PrintableString object


InheritString

inherit String : String

Class Standards.ASN1.Types.Real

Annotations
@Pike.Annotations.Implements(Object)

InheritObject

inherit Object : Object

Class Standards.ASN1.Types.Sequence

Annotations
@Pike.Annotations.Implements(Object)
Description

Sequence object


InheritCompound

inherit Compound : Compound

Class Standards.ASN1.Types.Set

Annotations
@Pike.Annotations.Implements(Object)
Description

Set object


InheritCompound

inherit Compound : Compound

Class Standards.ASN1.Types.String

Annotations
@Pike.Annotations.Implements(Object)
Description

string object primitive


InheritObject

inherit Object : Object


Variablevalue

string Standards.ASN1.Types.String.value

Description

value of object

Class Standards.ASN1.Types.UTC

Annotations
@Pike.Annotations.Implements(Object)
Description

UTCTime

RFC 2459 section 4.1.2.5.1


InheritString

inherit String : String


Methodget_posix

intget_posix()


Methodset_posix

variantthis_programset_posix(Calendar.ISO_UTC.Secondsecond)

Class Standards.ASN1.Types.UTF8String

Annotations
@Pike.Annotations.Implements(Object)
Description

UTF8 string object

Character set: ISO/IEC 10646-1 (compatible with Unicode).

Variable width encoding, see RFC 2279.


InheritString

inherit String : String

Class Standards.ASN1.Types.UniversalString

Annotations
@Pike.Annotations.Implements(Object)
Description

Universal String object

Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.

FIXME

The encoding is very likely UCS-4, but that's not yet verified.


InheritOctetString

inherit OctetString : OctetString

Class Standards.ASN1.Types.VisibleString

Annotations
@Pike.Annotations.Implements(Object)

InheritString

inherit String : String

Module Standards.BSON

Description

Tools for handling the BSON structured data format. See http://www.bsonspec.org/.


Inherit_BSON

inherit Standards._BSON : _BSON


VariableMaxKey

object Standards.BSON.MaxKey


VariableMinKey

object Standards.BSON.MinKey


Methoddecode

mixeddecode(stringbson)

Description

Decode a BSON formatted document string into a native Pike data structure.


Methoddecode_array

arraydecode_array(stringbsonarray)

Description

Decode a BSON formatted string containing multiple data structures


Methodencode

stringencode(array|mappingm, int|voidquery_mode)

Description

Encode a data structure as a BSON document.

Parameter query_mode

if set to true, encoding will allow "$" and "." in key names, which would normally be disallowed.

Class Standards.BSON.Binary


Methodcreate

Standards.BSON.BinaryStandards.BSON.Binary(stringdata, int|voidsubtype)

Class Standards.BSON.Javascript


Methodcreate

Standards.BSON.JavascriptStandards.BSON.Javascript(string_data, void|mapping_scope)

Class Standards.BSON.ObjectId


Methodcreate

Standards.BSON.ObjectIdStandards.BSON.ObjectId(string|void_id)

Class Standards.BSON.Regex


Methodcreate

Standards.BSON.RegexStandards.BSON.Regex(stringregex, void|stringoptions)

Class Standards.BSON.Symbol


Methodcreate

Standards.BSON.SymbolStandards.BSON.Symbol(string_data)

Class Standards.BSON.Timestamp


Methodcreate

Standards.BSON.TimestampStandards.BSON.Timestamp()

Module Standards.EXIF

Description

This module implements EXIF (Exchangeable image file format for Digital Still Cameras) 2.2 parsing.


Methodget_properties

mapping(string:mixed) get_properties(Stdio.BlockFilefile, void|mappingtags)

Description

Parses and returns all EXIF properties.

Parameter file

A JFIF file positioned at the start.

Parameter tags

An optional list of tags to process. If given, all unknown tags will be ignored.

Returns

A mapping with all found EXIF properties.

Module Standards.FIPS10_4

Description

This module implements the FIPS10-4 standard for short-form codes of "Countries, Dependencies, Areas of Special Sovereignty, and Their Principal Administrative Divisions."

This is a list of two-letter country codes used by the US government until 2008-10-02, when GENC, based on ISO 3166 replaced it as the prefered standard. The subdivisions are named using the main region name followed by two digits.

This list is similar to, but not entirely compatible with, ISO-3166 alpha-2.


Methoddivision_code_to_line

array(string) division_code_to_line(stringcode)

Description

Convert a division code to the information about the division. As an example division_code_to_line("sw16") would return

({"SW","SW16","Ostergotlands Lan","province/lan"})
Returns
Array
stringregion
stringdivision
stringname
stringtype

Methoddivision_code_to_name

stringdivision_code_to_name(stringcode)

Description

Similar to division_code_to_line(), but only returns the name


Methoddivision_guess_to_codes

array(string) division_guess_to_codes(stringcode)

Description

Return an array of possible division codes given a division name.

Returns
Array
array(string) regions
Array
stringregion
stringdivision
stringname
stringtype

Methoddivision_guess_to_lines

array(array(string)) division_guess_to_lines(stringname)

Description

Return an array of possible divisions given a division name.

Returns
Array
array(string) regions
Array
stringregion
stringdivision
stringname
stringtype

Methoddivision_name_to_line
Methoddivision_name_to_code

array(string) division_name_to_line(stringname)
stringdivision_name_to_code(stringcode)

Description

Lookup a division by name.

These aren't really all that useful, since there might very well be multiple divisions with the same name.

division_guess_to_lines() and division_guess_to_codes() are more useful.


Methodregion_code_to_name

stringregion_code_to_name(stringcode)

Description

Convert a region (country etc) code to the name of the region. As an example, region_code_to_name("se") would return "SEYCHELLES".


Methodregion_name_to_code

stringregion_name_to_code(stringcode)

Description

The reverse of region_code_to_name(), region_name_to_code("Sweden") would return "SW".


Methodregion_to_division_codes

array(string) region_to_division_codes(stringregion)

Description

Given a region (country etc) return all divisions codes in that region


Methodregion_to_divisions

array(array(string)) region_to_divisions(stringregion)

Description

Given a region (country etc) return all divisions in that region

Returns
Array
array(string) regions
Array
stringregion
stringdivision
stringname
stringtype

Module Standards.ID3

Description

ID3 decoder/encoder. Supports versions 1.0, 1.1, 2.2-2.4. For more info see http://www.id3.org

Note

Note that this implementation is far from complete and that interface changes might be necessary during the implementation of the full standard.


Methoddecode_string

stringdecode_string(stringin, inttype)

Description

Decodes the string in from the type, according to ID3v2.4.0-structure section 4, into a wide string.

See also

encode_string


Methodencode_string

array(string|int) encode_string(stringin)

Description

Encodes the string in to an int-string pair, where the integer is the encoding mode, according to ID3v2.4.0-structure, and the string is the encoded string. This function tries to minimize the size of the encoded string by selecting the most apropriate encoding method.

See also

decode_string, encode_strings


Methodencode_strings

array(string|int) encode_strings(array(string) in)

Description

Encodes several strings in the same way as encode_string, but encodes all the strings with the same method, selected as in encode_string. The first element in the resulting array is the selected method, while the following elements are the encoded strings.

See also

decode_string, encode_string


Methodint_to_synchsafe

array(int) int_to_synchsafe(intin, void|intno_bytes)

Description

Encodes a integer to a synchsafe integer according to ID3v2.4.0-structure section 6.2.

See also

synchsafe_to_int


Methodresynchronise

stringresynchronise(stringin)

Description

Reverses the effects of unsyncronisation done according to ID3v2.4.0-structure section 6.1.

See also

unsynchronise


Methodsynchsafe_to_int

intsynchsafe_to_int(array(int) bytes)

Description

Decodes a synchsafe integer, generated according to ID3v2.4.0-structure section 6.2.

See also

int_to_synchsafe


Methodunsynchronise

stringunsynchronise(stringin)

Description

Unsynchronises the string according to ID3v2.4.0-structure section 6.1.

See also

resynchronise

Class Standards.ID3.Buffer

Description

A wrapper around a Stdio.File object that provides a read limit capability.


Variablebuffer

Stdio.File Standards.ID3.Buffer.buffer


Method__create__

protectedlocalvoid__create__(Stdio.Filebuffer)


Methodbytes_left

intbytes_left()

Description

The number of bytes left before reaching the limit set by set_limit.


Methodcreate

Standards.ID3.BufferStandards.ID3.Buffer(Stdio.Filebuffer)


Methodpeek

stringpeek()

Description

Preview the next byte. Technically it is read from the encapsulated buffer and put locally to avoid seeking.


Methodread

stringread(intbytes)

Description

Read bytes bytes from the buffer. Throw an exception if bytes is bigger than the number of bytes left in the buffer before reaching the limit set by set_limit.


Methodset_limit

voidset_limit(intbytes)

Description

Set an artificial EOF bytes bytes further into the buffer.

Class Standards.ID3.ExtendedHeader


Methodcreate

Standards.ID3.ExtendedHeaderStandards.ID3.ExtendedHeader(void|Bufferbuffer)


Methoddecode

voiddecode(Bufferbuffer)


Methodencode

stringencode()

Class Standards.ID3.Frame

Description

Manages the common frame information.


Methodcreate

Standards.ID3.FrameStandards.ID3.Frame(string|Bufferin, TagHeaderthd)

Class Standards.ID3.FrameData

Description

Abstract class for frame data.


Methodchanged

boolchanged()

Description

Is the content altered?


Methodcreate

Standards.ID3.FrameDataStandards.ID3.FrameData(void|stringdata)

Class Standards.ID3.Tag

Description

This is a ID3 tag super object, which encapsulates all versions ID3 tags. This is useful if you are only interested in the metadata of a file, and care not about how it is stored or have no interest in changing the data.

Note

Version 1 tag is searched only if version 2 isn't found.

See also

Tagv2, Tagv1


Constantversion

constant Standards.ID3.Tag.version

Description

The version of the encapsulated tag in the form "%d.%d.%d".


Method_indices

arrayindices(Standards.ID3.Tagarg)

Description

Indices will return the indices of the tag object.


Method_values

arrayvalues(Standards.ID3.Tagarg)

Description

Values will return the values of the tag object.


Method`[]
Method`->

mixed res = Standards.ID3.Tag()[ index ]
mixed res = Standards.ID3.Tag()->X

Description

The index operators are overloaded to index the encapsulated Tagv1 or Tagv2 object.


Methodcreate

Standards.ID3.TagStandards.ID3.Tag(Stdio.Filefd)

Description

The file object fd is searched for version 2 tags, and if not found, version 1 tags.

Throws

If no tag was found in the file an error is thrown.


Methodfriendly_values

mapping(string:string) friendly_values()

Description

Returns tag values in a mapping. Only tag values that exists in ID3v1.1 is used. Nonexisting or undefined values will not appear in the mapping.

"artist" : string

Takes its value from TPE1 or TP1 frames.

"album" : string

Takes its value from TALB or TAL frames.

"title" : string

Takes its value from TIT2 or TT2 frames.

"genre" : string

Takes its value from TCON or TCM frames.

"year" : string

Takes its value from TYER or TYE frames.

"track" : string

Takes its value from TRCK or TRK frames. The string may be either in the "%d" form or in the "%d/%d" form.

Class Standards.ID3.TagHeader

Description

Represents an ID3v2 header.


Methodcreate

Standards.ID3.TagHeaderStandards.ID3.TagHeader(void|Bufferbuffer)


Methoddecode

voiddecode(Bufferbuffer)

Description

Decode a tag header from buffer and store its data in this object.


Methodencode

stringencode()

Description

Encode the data in this tag and return as a string.


Methodset_flag_unsynchronisation

boolset_flag_unsynchronisation(array(Frame) frames)

Description

Should the unsynchronisation flag be set or not?

Class Standards.ID3.Tagv1

Description

ID3 version 1.0 or 1.1 tag. This is really a clumsy way of reading ID3v1 tags, but it has the same interface as the v2 reader.

Class Standards.ID3.Tagv2

Description

ID3 version 2 (2.2, 2.3, 2.4) Tags


Methodcreate

Standards.ID3.Tagv2Standards.ID3.Tagv2(void|Buffer|Stdio.Filebuffer, void|bool_best_effort)

Module Standards.IDNA

Description

This module implements various algorithms specified by the Internationalizing Domain Names in Applications (IDNA) memo by the Internet Engineering Task Force (IETF), see RFC 3490.


VariablePunycode

object Standards.IDNA.Punycode

Description

Punycode transcoder, see RFC 3492. Punycode is used by to_ascii as an "ASCII Compatible Encoding" when needed.


Methodnameprep

stringnameprep(strings, bool|voidallow_unassigned)

Description

Prepare a Unicode string for ACE transcoding. Used by to_ascii. Nameprep is a profile of Stringprep, which is described in RFC 3454.

Parameter s

The string to prep.

Parameter allow_unassigned

Set this flag the the string to transform is a "query string", and not a "stored string". See RFC 3454.


Methodto_ascii

string(7bit)to_ascii(strings, bool|voidallow_unassigned, bool|voiduse_std3_ascii_rules)

Description

The to_ascii operation takes a sequence of Unicode code points that make up one label and transforms it into a sequence of code points in the ASCII range (0..7F). If to_ascci succeeds, the original sequence and the resulting sequence are equivalent labels.

Parameter s

The sequence of Unicode code points to transform.

Parameter allow_unassigned

Set this flag if the the string to transform is a "query string", and not a "stored string". See RFC 3454.

Parameter use_std3_ascii_rules

Set this flag to enforce the restrictions on ASCII characters in host names imposed by STD3.


Methodto_unicode

stringto_unicode(strings)

Description

The to_unicode operation takes a sequence of Unicode code points that make up one label and returns a sequence of Unicode code points. If the input sequence is a label in ACE form, then the result is an equivalent internationalized label that is not in ACE form, otherwise the original sequence is returned unaltered.

Parameter s

The sequence of Unicode code points to transform.


Methodzone_to_ascii

string(7bit)zone_to_ascii(strings, bool|voidallow_unassigned, bool|voiduse_std3_ascii_rules)

Description

Takes a sequence of labels separated by '.' and applies to_ascii on each.


Methodzone_to_unicode

stringzone_to_unicode(strings)

Description

Takes a sequence of labels separated by '.' and applies to_unicode on each.

Module Standards.IIM

Description

IPTC Information Interchange Model data (aka "IPTC header") extraction.

http://www.iptc.org/IIM/


Methodget_information

mapping(string(7bit):array(string)) get_information(Stdio.InputStreamfd)

Description

Get IPTC information from an open file.

Supported embedding formats are:

  • PhotoShop Document (aka PSD).

  • Postscript and Embedded Postscript.

  • Joint Picture Experts Group (aka JPEG).

Returns

Returns a mapping containing any found IPTC IIM data.

Module Standards.ISO639_2


Methodconvert_b_to_t

string|zeroconvert_b_to_t(stringcode)

Description

Converts an ISO 639-2/B code to an ISO 639-2/T code.


Methodconvert_t_to_b

string|zeroconvert_t_to_b(stringcode)

Description

Converts an ISO 639-2/T code to an ISO 639-2/B code.


Methodget_language

stringget_language(stringcode)

Description

Look up the language name given an ISO 639-2 code in lower case. It will first be looked up in the ISO 639-2/T table and then in ISO 639-2/B if the first lookup failed. Returns zero typed zero on failure.


Methodget_language_b

stringget_language_b(stringcode)

Description

Look up the language name given an ISO 639-2/B code in lower case. Returns zero typed zero on failure.


Methodget_language_t

stringget_language_t(stringcode)

Description

Look up the language name given an ISO 639-2/T code in lower case. Returns zero typed zero on failure.


Methodlist_639_1

mapping(string:string) list_639_1()

Description

Return a mapping from ISO 639-1 code to ISO 639-2/T code.


Methodlist_languages

mapping(string:string) list_languages()

Description

Return a mapping from ISO 639-2/T + ISO 639-2/B codes to language names.


Methodlist_languages_b

mapping(string:string) list_languages_b()

Description

Return a mapping from ISO 639-2/B codes to language names.


Methodlist_languages_t

mapping(string:string) list_languages_t()

Description

Return a mapping from ISO 639-2/T codes to language names.


Methodmap_639_1

stringmap_639_1(stringcode)

Description

Look up the ISO 639-2/T code given an ISO 639-1 code in lower case.


Methodmap_to_639_1

stringmap_to_639_1(stringcode)

Description

Look up the ISO 639-1 code given an ISO 639-2/T code in lower case.

Module Standards.JSON

Description

Tools for handling the JSON structured data format. See http://www.json.org/ and RFC 4627.


ConstantASCII_ONLY
ConstantHUMAN_READABLE
ConstantPIKE_CANONICAL
ConstantCANONICAL

constant Standards.JSON.ASCII_ONLY
constant Standards.JSON.HUMAN_READABLE
constant Standards.JSON.PIKE_CANONICAL
constant Standards.JSON.CANONICAL

Description

Bit field flags for use with encode:

Standards.JSON.ASCII_ONLY

Use \uxxxx escapes for all non-ascii characters and DEL (U+007f). The default is to escape only the characters that must be escaped. The flag value is 1.

Characters above U+FFFF are encoded using escaped surrogate pairs, as per RFC 4627.

Standards.JSON.HUMAN_READABLE

Pretty print with indentation to make the result easier on human eyes. The default is to use no extra whitespace at all. The flag value is 2.

Standards.JSON.PIKE_CANONICAL

Make the output canonical, so that the same value always generates the same char-by-char equal string. In practice this means that mapping elements are sorted on their indices. Note that the other flags take precedence, so e.g. the canonical form with HUMAN_READABLE is not the same as the canonical form without it. The flag value is 4.

This canonical form is stable for the encode function, providing floats aren't used (their formatting is currently affected by float size and libc formatting code). In the future there may be a standardized canonical form which quite likely will be different from this one. In that case a separate flag has to be added so this one doesn't change - hence the name PIKE_CANONICAL. See also CANONICAL below.

Standards.JSON.CANONICAL

Make the output canonical as per RFC 8785, so that the same value always generates the same char-by-char equal string. The flag value is 8.

Note that RFC 8785-compliant output will only be generated if this is the only flag that has been set and no indentation has been requested, and Pike.get_runtime_info()->float_size    == 64. In other cases a best effort attempt to comply with RFC 8785 will be performed, but deviations may occur.


ConstantNO_OBJECTS

constant Standards.JSON.NO_OBJECTS

Description

Bit field flags for use with decode:

Standards.JSON.NO_OBJECTS

Do not decode "true", "false" and "null" into Val.true, Val.false and Val.null, but instead 1, 0 and UNDEFINED.


Variabletrue
Variablefalse
Variablenull

Val.True Standards.JSON.true
Val.False Standards.JSON.false
Val.Null Standards.JSON.null

Description

Compat aliases for the corresponding Val objects. These are used to represent the three JSON literals true, false and null.

Deprecated

Replaced by Val.true, Val.false and Val.null.


Methoddecode

array|mapping|string|float|int|objectdecode(strings, void|intflags)

Description

Decodes a JSON string.

Parameter flags

The flag NO_OBJECTS can be used to output 1, 0 and UNDEFINED instead of Val.true, Val.false and Val.null.

Throws

Throws an exception in case the data contained in s is not valid JSON.


Methoddecode_utf8

array|mapping|string|float|int|objectdecode_utf8(strings)

Description

Decodes an utf8 encoded JSON string. Should give the same result as Standards.JSON.decode(utf8_to_string(s)).

Throws

Throws an exception in case the data contained in s is not valid JSON.


Methodencode

stringencode(int|float|string|array|mapping|objectval, void|intflags, void|function(:void)|object|program|stringcallback)

Description

Encodes a value to a JSON string.

Parameter val

The value to encode. It can contain integers, floats (except the special numbers NaN and infinity), strings, arrays, mappings with string indices, and the special object values null, true and false defined in this module (or really any object that implements an encode_json callback or is handled by the supplied callback argument).

Parameter flags

Flag bit field to control formatting. See ASCII_ONLY, HUMAN_READABLE and PIKE_CANONICAL for further details.

Parameter callback

A function that will be called for types that can not be encoded otherwise. It will be called with the value to be encoded as the first argument, and optionally with flags and indent arguments. If a string is supplied, it will be used to replace the value verbatim. The callback must return a string or throw an error.

Note

8-bit and wider characters in input strings are neither escaped nor utf-8 encoded by default. string_to_utf8 can be used safely on the returned string to get a valid transport encoded JSON string. See escape_string for further details on string escaping.

See also

escape_string


Methodescape_string

stringescape_string(stringstr, void|intflags)

Description

Escapes string data for use in a JSON string.

8-bit and wider characters in input strings are neither escaped nor utf-8 encoded by default. string_to_utf8 can be used safely on the returned string to get a valid transport encoded JSON string.

The characters U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) are exceptions - they are encoded with \u escapes for compatibility. The reason is that those characters are not allowed in Javascript strings, so JSON parsers built in Javascript may have trouble with them otherwise.

Parameter val

The string to escape.

Parameter flags

Flag bit field to control formatting. ASCII_ONLY is the only flag that has any effect for this function.

Note

The difference between using this function and encode on a string is that encode returns quotations marks around the result.

See also

encode


Methodvalidate

intvalidate(strings)

Description

Checks if a string is valid JSON.

Returns

In case the string contains valid JSON -1 is returned. It is then guaranteed to be parsed without errors by decode(). In case the string is not valid JSON, the error position is returned.


Methodvalidate_utf8

intvalidate_utf8(strings)

Description

Checks if a string is valid utf8 encoded JSON.

Returns

In case the string contains valid JSON -1 is returned. It is then guaranteed to be parsed without errors by decode(). In case the string is not valid JSON, the integer position inside the string where the error occurs is returned.

Class Standards.JSON.DecodeError

Description

Error thrown when JSON decode fails.


InheritGeneric

inherit Error.Generic : Generic


Variableerr_pos

int Standards.JSON.DecodeError.err_pos

Description

The failing position in err_str.


Variableerr_str

string Standards.JSON.DecodeError.err_str

Description

The string that failed to be decoded.

Class Standards.JSON.Validator

Description

An instance of this class can be used to validate a JSON object against a JSON schema.

Example

string schema_s = "{\n" + " \"name\": \"SomeExample\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": { \"type\": \"string\" },\n" + " \"id\": {\n" + " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " }\n" + " }\n" + "}"; string example_s = "{\n" + " \"name\": \"An Example\",\n" + " \"id\": 17\n" + "}"; mixed schema = Standards.JSON.decode(schema_s); mixed example = Standards.JSON.decode(example_s); if (string error = Standards.JSON.Validator(schema).validate(example)) werror("Error: JSON string %O did not validate: %s\n", example_s, error); else write("JSON ok\n");

Note

This class validates only a subset of the JSON schema specification. Currently dependencies and references are not handled and regular expressions (for pattern properties) are limited to those that can be handled by Regexp.SimpleRegexp.

For more information of JSON schema look at http://json-schema.org/documentation.html "The home of JSON Schema".


Methodcreate

Standards.JSON.ValidatorStandards.JSON.Validator(mixed_schema)

Description

Create a JSON validator for some JSON schema.

Parameter _schema

The JSON schema to use in validate(). This must be a valid JSON object.

Throws

Throws an error if the schema is invalid.


Methodhas_schema_array

privateboolhas_schema_array(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an array.

Throws

Throws an error if the value of the property is no array.

Returns

1 if the schema has the specified property.


Methodhas_schema_array_mapping

privateboolhas_schema_array_mapping(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an array(mapping).

Throws

Throws an error if the value of the property is no array(mapping).

Returns

1 if the schema has the specified property.


Methodhas_schema_array_string

privateboolhas_schema_array_string(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an array(string).

Throws

Throws an error if the value of the property is no array(string).

Returns

1 if the schema has the specified property.


Methodhas_schema_boolean

privateboolhas_schema_boolean(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a boolean (with values Standards.JSON.true or Standards.JSON.false).

Throws

Throws an error if the value of the property is no boolean.

Returns

1 if the schema has the specified property.


Methodhas_schema_integer

privateboolhas_schema_integer(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an integer.

Throws

Throws an error if the value of the property is no integer.

Returns

1 if the schema has the specified property.


Methodhas_schema_mapping

privateboolhas_schema_mapping(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a mapping.

Throws

Throws an error if the value of the property is no mapping.

Returns

1 if the schema has the specified property.


Methodhas_schema_mapping_mapping

privateboolhas_schema_mapping_mapping(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a mapping(string:mapping).

Throws

Throws an error if the value of the property is no mapping(string:mapping).

Returns

1 if the schema has the specified property.


Methodhas_schema_number

privateboolhas_schema_number(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a number (integer or float).

Throws

Throws an error if the value of the property is no number.

Returns

1 if the schema has the specified property.


Methodhas_schema_string

privateboolhas_schema_string(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a string.

Throws

Throws an error if the value of the property is no string.

Returns

1 if the schema has the specified property.


Methodis_JSON_boolean

privateboolis_JSON_boolean(mixedvalue)

Returns

1 if the specified value is either Standards.JSON.true or Standards.JSON.false.


Methodvalidate

string|zerovalidate(mixedjson)

Description

This function validates a JSON object against the JSON schema that was specified in the Validator's constructor. If the JSON object is not valid, a string with an error-message is returned. If the JSON object is valid, 0 is returned.

Parameter json

The JSON object to validate.

Returns

0, if the json object is valid, and an error-message if it is not valid.


Methodvalidate_array

privatestring|zerovalidate_array(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is an array according to the specified schema. The following properties of schema are verified:

minItems

If schema has the property "minItems", then the array must have at least the specified number of items.

maxItems

If schema has the property "maxItems", then the array must not have more than the specified number of items.

items

If schema has the property "items", which is an array of schema objects, then each element in the value array must be valid according the corresponding schema in the "items" array.


Methodvalidate_integer

privatestring|zerovalidate_integer(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is an integer according to the specified schema. This is the similar to validate_number(), but the value must be an int and not a float. The following properties of schema are verified:

minimum

If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.

exclusiveMinimum

If the schema has the properties "minimum" and "exclusiveMinimum" is Standards.JSON.true, then the value must be greater than the specified minimum.

maximum

If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.

exclusiveMaximum

If the schema has the properties "maximum" and "exclusiveMaximum" is Standards.JSON.true, then the value must be lower than the specified minimum.

multipleOf

If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.


Methodvalidate_item_type

privatestring|zerovalidate_item_type(stringkey, mixedvalue, mappingschema)

Description

Verify that the specified value has the correct type that is defined by schema->type. schema->type can be any of

  • "boolean",

  • "integer",

  • "number",

  • "string",

  • "array",

  • "object",

  • "null",

or an array of these.


Methodvalidate_number

privatestring|zerovalidate_number(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is a number (integer or float) according to the specified schema. The following properties of schema are verified:

minimum

If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.

exclusiveMinimum

If the schema has the properties "minimum" and "exclusiveMinimum" is Standards.JSON.true, then the value must be greater than the specified minimum.

maximum

If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.

exclusiveMaximum

If the schema has the properties "maximum" and "exclusiveMaximum" is Standards.JSON.true, then the value must be lower than the specified minimum.

multipleOf

If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.


Methodvalidate_object

privatestring|zerovalidate_object(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is an object according to the specified schema. The following properties of schema are verified:

minProperties

If schema has the property "minProperties", then the object must have at least the specified number of properties.

maxProperties

If schema has the property "maxProperties", then the object must not have more than the specified number of items.

required

If schema has the property "required", which is an array of strings, then the object must have all properties that are listed in the specified array.

properties

If schema has the property "properties", which is a mapping of property-name to a schema, then each property of the object that has a corresponding schema in "properties" must be valid according to that schema.

patternProperties

If schema has the property "properties", which is a mapping of property-name-pattern to a schema, then each property of the object must be valid according to all schema objects for which the pattern matches the property-name.

additionalProperties

If schema has the property "additionalProperties", it can be either a boolean value, or a schema.

  • If it is a boolean with value Standards.JSON.false, then all properties of the object must be validated either by a schema from "properties" or "patternProperties".

  • If it is a boolean with value Standards.JSON.true, then the object is allowed to have additional properties without validation.

  • If it is a schema, then any propery of the object that is not validated by a schema from "properties" or "patternProperties" must be validated by the specified schema.

Note

TODO: We use Regexp.SimpleRegexp to handle schema->patternProperties, but that covers only some part of the possible regular expressions.


Methodvalidate_properties

privatestring|zerovalidate_properties(stringkey, mixedvalue, mappingschema)

Description

Verify that the specified value matches the specified schema. The following properties of schema are verified:

type

If the schema has a property "type", then the value must match the specified type (see validate_item_type()).

allOf

If the schema has a property "allOf", which is an array of schema objects, then the value must match each schema specified in that array (via another call to validate_properties()).

anyOf

If the schema has a property "anyOf", which is an array of schema objects, then the value must match at least one schema specified in that array (via another call to validate_properties()).

oneOf

If the schema has a property "oneOf", which is an array of schema objects, then the value must match exactly one schema specified in that array (via another call to validate_properties()).

not

If the schema has a property "not", then the value must not match the schema specified by that property (via another call to validate_properties()).

enum

If the schema has a property "enum", then the value must be equal to any of the values specified in the enum array.

Note

If the schema is empty (i.e., it has none of the above specified properties, then the value is valid).


Methodvalidate_string

privatestring|zerovalidate_string(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is a string according to the specified schema. The following properties of schema are verified:

minLength

If schema has the property "minLength", then the value must not be shorter than the specified length.

maxLength

If schema has the property "maxLength", then the value must not be longer than the specified length.

pattern

If schema has the property "pattern", then the value must match the specified pattern.

Note

TODO: We use Regexp.SimpleRegexp to handle schema->pattern, but that covers only some part of the possible regular expressions.

Module Standards.JSON5

Description

Tools for handling the JSON5 structured data format. See http://www.json5.org/ and RFC 4627.


ConstantASCII_ONLY
ConstantHUMAN_READABLE
ConstantPIKE_CANONICAL
ConstantUNQUOTED_IDENTIFIERS
ConstantSINGLE_QUOTED_STRINGS

constant Standards.JSON5.ASCII_ONLY
constant Standards.JSON5.HUMAN_READABLE
constant Standards.JSON5.PIKE_CANONICAL
constant Standards.JSON5.UNQUOTED_IDENTIFIERS
constant Standards.JSON5.SINGLE_QUOTED_STRINGS

Description

Bit field flags for use with encode:

Standards.JSON5.ASCII_ONLY

Use \uxxxx escapes for all non-ascii characters and DEL (U+007f). The default is to escape only the characters that must be escaped. The flag value is 1.

Characters above U+FFFF are encoded using escaped surrogate pairs, as per RFC 4627.

Standards.JSON5.HUMAN_READABLE

Pretty print with indentation to make the result easier on human eyes. The default is to use no extra whitespace at all. The flag value is 2.

Standards.JSON5.PIKE_CANONICAL

Make the output canonical, so that the same value always generates the same char-by-char equal string. In practice this means that mapping elements are sorted on their indices. Note that the other flags take precedence, so e.g. the canonical form with HUMAN_READABLE is not the same as the canonical form without it. The flag value is 4.

This canonical form is stable for the encode function, providing floats aren't used (their formatting is currently affected by float size and libc formatting code). In the future there may be a standardized canonical form which quite likely will be different from this one. In that case a separate flag has to be added so this one doesn't change - hence the name PIKE_CANONICAL.

Standards.JSON5.UNQUOTED_IDENTIFIERS

When producing mapping keys, permit keys which are identifiers to be expressed without surrounding quotation marks.

Standards.JSON5.SINGLE_QUOTED_STRINGS

Use single quotation marks rather than double quotation marks when encoding string values.


Variabletrue
Variablefalse
Variablenull

Val.True Standards.JSON5.true
Val.False Standards.JSON5.false
Val.Null Standards.JSON5.null

Description

Compat aliases for the corresponding Val objects. These are used to represent the three JSON5 literals true, false and null.

Deprecated

Replaced by Val.true, Val.false and Val.null.


Methoddecode

array|mapping|string|float|int|objectdecode(strings)

Description

Decodes a JSON5 string.

Throws

Throws an exception in case the data contained in s is not valid JSON5.


Methoddecode_utf8

array|mapping|string|float|int|objectdecode_utf8(strings)

Description

Decodes an utf8 encoded JSON5 string. Should give the same result as Standards.JSON5.decode(utf8_to_string(s)).

Throws

Throws an exception in case the data contained in s is not valid JSON5.


Methodencode

stringencode(int|float|string|array|mapping|objectval, void|intflags, void|function(:void)|object|program|stringcallback)

Description

Encodes a value to a JSON5 string.

Parameter val

The value to encode. It can contain integers, floats (except the special numbers NaN and infinity), strings, arrays, mappings with string indices, and the special object values null, true and false defined in this module (or really any object that implements an encode_json5 callback or is handled by the supplied callback argument).

Parameter flags

Flag bit field to control formatting. See ASCII_ONLY, HUMAN_READABLE and PIKE_CANONICAL for further details.

Parameter callback

A function that will be called for types that can not be encoded otherwise. It will be called with the value to be encoded as the first argument, and optionally with flags and indent arguments. If a string is supplied, it will be used to replace the value verbatim. The callback must return a string or throw an error.

Note

8-bit and wider characters in input strings are neither escaped nor utf-8 encoded by default. string_to_utf8 can be used safely on the returned string to get a valid transport encoded JSON5 string. See escape_string for further details on string escaping.

See also

escape_string


Methodescape_string

stringescape_string(stringstr, void|intflags)

Description

Escapes string data for use in a JSON5 string.

8-bit and wider characters in input strings are neither escaped nor utf-8 encoded by default. string_to_utf8 can be used safely on the returned string to get a valid transport encoded JSON5 string.

The characters U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) are exceptions - they are encoded with \u escapes for compatibility. The reason is that those characters are not allowed in Javascript strings, so JSON5 parsers built in Javascript may have trouble with them otherwise.

Parameter val

The string to escape.

Parameter flags

Flag bit field to control formatting. ASCII_ONLY is the only flag that has any effect for this function.

Note

The difference between using this function and encode on a string is that encode returns quotations marks around the result.

See also

encode


Methodvalidate

intvalidate(strings)

Description

Checks if a string is valid JSON5.

Returns

In case the string contains valid JSON5 -1 is returned. It is then guaranteed to be parsed without errors by decode(). In case the string is not valid JSON5, the error position is returned.


Methodvalidate_utf8

intvalidate_utf8(strings)

Description

Checks if a string is valid utf8 encoded JSON5.

Returns

In case the string contains valid JSON5 -1 is returned. It is then guaranteed to be parsed without errors by decode(). In case the string is not valid JSON5, the integer position inside the string where the error occurs is returned.

Class Standards.JSON5.DecodeError

Description

Error thrown when JSON5 decode fails.


InheritGeneric

inherit Error.Generic : Generic


Variableerr_pos

int Standards.JSON5.DecodeError.err_pos

Description

The failing position in err_str.


Variableerr_str

string Standards.JSON5.DecodeError.err_str

Description

The string that failed to be decoded.

Class Standards.JSON5.Validator

Description

An instance of this class can be used to validate a JSON5 object against a JSON5 schema.

Example

string schema_s = "{\n" + " \"name\": \"SomeExample\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": { \"type\": \"string\" },\n" + " \"id\": {\n" + " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " }\n" + " }\n" + "}"; string example_s = "{\n" + " \"name\": \"An Example\",\n" + " \"id\": 17\n" + "}"; mixed schema = Standards.JSON5.decode(schema_s); mixed example = Standards.JSON5.decode(example_s); if (string error = Standards.JSON5.Validator(schema).validate(example)) werror("Error: JSON5 string %O did not validate: %s\n", example_s, error); else write("JSON5 ok\n");

Note

This class validates only a subset of the JSON5 schema specification. Currently dependencies and references are not handled and regular expressions (for pattern properties) are limited to those that can be handled by Regexp.SimpleRegexp.

For more information of JSON5 schema look at http://json5-schema.org/documentation.html "The home of JSON5 Schema".


Methodcreate

Standards.JSON5.ValidatorStandards.JSON5.Validator(mixed_schema)

Description

Create a JSON5 validator for some JSON5 schema.

Parameter _schema

The JSON5 schema to use in validate(). This must be a valid JSON5 object.

Throws

Throws an error if the schema is invalid.


Methodhas_schema_array

privateboolhas_schema_array(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an array.

Throws

Throws an error if the value of the property is no array.

Returns

1 if the schema has the specified property.


Methodhas_schema_array_mapping

privateboolhas_schema_array_mapping(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an array(mapping).

Throws

Throws an error if the value of the property is no array(mapping).

Returns

1 if the schema has the specified property.


Methodhas_schema_array_string

privateboolhas_schema_array_string(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an array(string).

Throws

Throws an error if the value of the property is no array(string).

Returns

1 if the schema has the specified property.


Methodhas_schema_boolean

privateboolhas_schema_boolean(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a boolean (with values Standards.JSON5.true or Standards.JSON5.false).

Throws

Throws an error if the value of the property is no boolean.

Returns

1 if the schema has the specified property.


Methodhas_schema_integer

privateboolhas_schema_integer(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is an integer.

Throws

Throws an error if the value of the property is no integer.

Returns

1 if the schema has the specified property.


Methodhas_schema_mapping

privateboolhas_schema_mapping(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a mapping.

Throws

Throws an error if the value of the property is no mapping.

Returns

1 if the schema has the specified property.


Methodhas_schema_mapping_mapping

privateboolhas_schema_mapping_mapping(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a mapping(string:mapping).

Throws

Throws an error if the value of the property is no mapping(string:mapping).

Returns

1 if the schema has the specified property.


Methodhas_schema_number

privateboolhas_schema_number(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a number (integer or float).

Throws

Throws an error if the value of the property is no number.

Returns

1 if the schema has the specified property.


Methodhas_schema_string

privateboolhas_schema_string(mapping(string:mixed) schema, stringproperty)

Description

Test if the schema has the specified property and the value of the property is a string.

Throws

Throws an error if the value of the property is no string.

Returns

1 if the schema has the specified property.


Methodis_JSON5_boolean

privateboolis_JSON5_boolean(mixedvalue)

Returns

1 if the specified value is either Standards.JSON5.true or Standards.JSON5.false.


Methodvalidate

string|zerovalidate(mixedjson5)

Description

This function validates a JSON5 object against the JSON5 schema that was specified in the Validator's constructor. If the JSON5 object is not valid, a string with an error-message is returned. If the JSON5 object is valid, 0 is returned.

Parameter json5

The JSON5 object to validate.

Returns

0, if the json5 object is valid, and an error-message if it is not valid.


Methodvalidate_array

privatestring|zerovalidate_array(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is an array according to the specified schema. The following properties of schema are verified:

minItems

If schema has the property "minItems", then the array must have at least the specified number of items.

maxItems

If schema has the property "maxItems", then the array must not have more than the specified number of items.

items

If schema has the property "items", which is an array of schema objects, then each element in the value array must be valid according the corresponding schema in the "items" array.


Methodvalidate_integer

privatestring|zerovalidate_integer(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is an integer according to the specified schema. This is the similar to validate_number(), but the value must be an int and not a float. The following properties of schema are verified:

minimum

If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.

exclusiveMinimum

If the schema has the properties "minimum" and "exclusiveMinimum" is Standards.JSON5.true, then the value must be greater than the specified minimum.

maximum

If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.

exclusiveMaximum

If the schema has the properties "maximum" and "exclusiveMaximum" is Standards.JSON5.true, then the value must be lower than the specified minimum.

multipleOf

If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.


Methodvalidate_item_type

privatestring|zerovalidate_item_type(stringkey, mixedvalue, mappingschema)

Description

Verify that the specified value has the correct type that is defined by schema->type. schema->type can be any of

  • "boolean",

  • "integer",

  • "number",

  • "string",

  • "array",

  • "object",

  • "null",

or an array of these.


Methodvalidate_number

privatestring|zerovalidate_number(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is a number (integer or float) according to the specified schema. The following properties of schema are verified:

minimum

If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.

exclusiveMinimum

If the schema has the properties "minimum" and "exclusiveMinimum" is Standards.JSON5.true, then the value must be greater than the specified minimum.

maximum

If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.

exclusiveMaximum

If the schema has the properties "maximum" and "exclusiveMaximum" is Standards.JSON5.true, then the value must be lower than the specified minimum.

multipleOf

If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.


Methodvalidate_object

privatestring|zerovalidate_object(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is an object according to the specified schema. The following properties of schema are verified:

minProperties

If schema has the property "minProperties", then the object must have at least the specified number of properties.

maxProperties

If schema has the property "maxProperties", then the object must not have more than the specified number of items.

required

If schema has the property "required", which is an array of strings, then the object must have all properties that are listed in the specified array.

properties

If schema has the property "properties", which is a mapping of property-name to a schema, then each property of the object that has a corresponding schema in "properties" must be valid according to that schema.

patternProperties

If schema has the property "properties", which is a mapping of property-name-pattern to a schema, then each property of the object must be valid according to all schema objects for which the pattern matches the property-name.

additionalProperties

If schema has the property "additionalProperties", it can be either a boolean value, or a schema.

  • If it is a boolean with value Standards.JSON5.false, then all properties of the object must be validated either by a schema from "properties" or "patternProperties".

  • If it is a boolean with value Standards.JSON5.true, then the object is allowed to have additional properties without validation.

  • If it is a schema, then any propery of the object that is not validated by a schema from "properties" or "patternProperties" must be validated by the specified schema.

Note

TODO: We use Regexp.SimpleRegexp to handle schema->patternProperties, but that covers only some part of the possible regular expressions.


Methodvalidate_properties

privatestring|zerovalidate_properties(stringkey, mixedvalue, mappingschema)

Description

Verify that the specified value matches the specified schema. The following properties of schema are verified:

type

If the schema has a property "type", then the value must match the specified type (see validate_item_type()).

allOf

If the schema has a property "allOf", which is an array of schema objects, then the value must match each schema specified in that array (via another call to validate_properties()).

anyOf

If the schema has a property "anyOf", which is an array of schema objects, then the value must match at least one schema specified in that array (via another call to validate_properties()).

oneOf

If the schema has a property "oneOf", which is an array of schema objects, then the value must match exactly one schema specified in that array (via another call to validate_properties()).

not

If the schema has a property "not", then the value must not match the schema specified by that property (via another call to validate_properties()).

enum

If the schema has a property "enum", then the value must be equal to any of the values specified in the enum array.

Note

If the schema is empty (i.e., it has none of the above specified properties, then the value is valid).


Methodvalidate_string

privatestring|zerovalidate_string(stringkey, mixedvalue, mapping(string:mixed) schema)

Description

Verify that the specified value is a string according to the specified schema. The following properties of schema are verified:

minLength

If schema has the property "minLength", then the value must not be shorter than the specified length.

maxLength

If schema has the property "maxLength", then the value must not be longer than the specified length.

pattern

If schema has the property "pattern", then the value must match the specified pattern.

Note

TODO: We use Regexp.SimpleRegexp to handle schema->pattern, but that covers only some part of the possible regular expressions.

Module Standards.MsgPack

Description

Tools for handling the MsgPack data format. MsgPack is a binary serialization format with applications similar to JSON. However, MsgPack is more versatile and is able to serialize arbitrary objects using an extension format. The following table shows how some special Pike data types are encoded in the MsgPack format. All basic types, namely int, string, float, array and mapping are mapped onto their natural MsgPack counterparts. Note that the encoder does not use all integer and floating point lengths and in particular integers are never encoded as unsigned.

  • binary

    Stdio.Buffer

  • nil

    Val.null

  • true

    Val.true

  • false

    Val.false

All other types can be encoded and decoded using extension handlers.


Typedefdecode_handler

typedeffunction(int(-127..128), Stdio.Buffer:mixed) Standards.MsgPack.decode_handler

Description

Function prototype for decode extension handlers. The first argument is the extension type identifier. The second argument is a Stdio.Buffer containing the payload.

See also

decode, decode_from


Typedefencode_handler

typedeffunction(Stdio.Buffer, mixed:void) Standards.MsgPack.encode_handler

Description

Function prototype for encode extension handlers. The first argument is the Stdio.Buffer, the second the value to encode. Use add_extension_header to generate the correct extension header.

See also

decode, decode_from


Methodadd_extension_header

voidadd_extension_header(Stdio.Bufferb, int(-128..127)type, int(0..)len)

Description

Adds an extension header to b for given type and payload length.


Methoddecode

mixeddecode(string(8bit)data, void|decode_handler|objecthandler)

Description

Decode one MsgPack encoded value from data.


Methoddecode_from

mixeddecode_from(Stdio.Bufferbuffer, void|decode_handler|objecthandler)

Description

Decode one MsgPack encoded value from the buffer.


Methoddefault_handler

voiddefault_handler(Stdio.Bufferb, function(:void)|object|programv)

Description

Default encoding handler. Encodes Val.null, Val.true and Val.false.


Methodencode

string(8bit)encode(mixedv, void|encode_handler|objecthandler)

Description

Encode v into a string.


Methodencode_to

voidencode_to(Stdio.Bufferbuf, mixedv, void|encode_handler|objecthandler)

Description

Encode v into buf. If handler is not specified, it defaults to default_handler.

Class Standards.MsgPack.DecodeError

Description

Error thrown when MsgPack decoding fails.


InheritGeneric

inherit Error.Generic : Generic


Variablebuffer

Stdio.Buffer Standards.MsgPack.DecodeError.buffer

Description

The data which failed to be decoded.


Variableerr_pos

int Standards.MsgPack.DecodeError.err_pos

Description

The failing position in buffer.

Module Standards.PEM

Description

Support for parsing PEM-style messages, defined in RFC 1421. Encapsulation defined in RFC 0934.


Methodbuild

stringbuild(stringtag, stringdata, void|mapping(string:string) headers, void|stringchecksum)

Description

Creates a PEM message, wrapped to 64 character lines.

Parameter tag

The encapsulation boundary string.

Parameter data

The data to be encapsulated.

Parameter headers

Optional mapping containing encapsulated headers as name value pairs.

Parameter checksum

Optional checksum string, added as per RFC 4880.


Methoddecrypt_body

string(8bit)decrypt_body(string(8bit)dek_info, string(8bit)body, string(8bit)password)

Description

Decrypt a PEM body.

Parameter dek_info

"dek-info" header from the Message.

Parameter body

Encypted PEM body.

Parameter password

Decryption password.

Returns

Returns the decrypted body text.


Methoddecrypt_fragment

string(8bit)|zerodecrypt_fragment(Messagem, string(8bit)pwd)

Description

Decrypt a PEM Message.

Parameter body

Fragment with encypted PEM body.

Parameter password

Decryption password.

Returns

Returns the decrypted body text.


Methodderive_key

string(8bit)derive_key(string(8bit)password, string(8bit)salt, intbytes)

Description

Key derivation function used in PEM.

FIXME

Derived from OpenSSL. Is there any proper specification?

It seems to be related to PBKDF1 from RFC 2898.


Methodsimple_decode

string(8bit)|zerosimple_decode(string(8bit)pem)

Description

Convenience function that decodes a PEM message containing only one part, and returns it as a string. Returns 0 for indata containing no or multiple parts.

Class Standards.PEM.Message

Description

Represents a PEM-style message.


Variablebody

string(8bit)|zero Standards.PEM.Message.body

Description

The decode message body.


Variableheaders

mapping(string(8bit):string(8bit))|zero Standards.PEM.Message.headers

Description

Encapsulated headers. If headers occur multiple times, they will be concatenated separated by delimiting NUL characters.


Variablepost

string|zero Standards.PEM.Message.post

Description

Post-encapsulation boundary string.

Usually the same value as pre.


Variablepre

string|zero Standards.PEM.Message.pre

Description

Pre-encapsulation boundary string.

Typically a string like "CERTIFICATE" or "PRIVATE KEY".


Variabletrailer

string(8bit)|zero Standards.PEM.Message.trailer

Description

Message trailer, like RFC 4880 checksum.

Class Standards.PEM.Messages

Description

The Messages class acts as an envelope for a PEM message file or stream.


Variablefragments

array(string(8bit)|Message) Standards.PEM.Messages.fragments

Description

The fragments array contains the different message fragments, as Message objects for decoded messages and strings for non-messages or incomplete messages.


Variableparts

mapping(string(8bit):array(Message)) Standards.PEM.Messages.parts

Description

This is a mapping from encapsulation boundary string to Message objects. All message objects and surrounding text will be listed, in order, in fragments.


Methodcreate

Standards.PEM.MessagesStandards.PEM.Messages(string(8bit)data)

Description

A Messages object is created with the file or stream data.


Methodget_certificate

stringget_certificate()

Description

Convenience wrapper for get_certificates that returns the first available certificate, or 0.


Methodget_certificates

array(string) get_certificates()

Description

Returns an array of all the bodies of "CERTIFICATE" and "X509 CERTIFICATE" fragments.


Methodget_encrypted_private_key

string|zeroget_encrypted_private_key(string(8bit)pwd)

Description

Returns the first key, decoded by the pwd password.


Methodget_fragment_bodies

array(string) get_fragment_bodies(multisetlabels)

Description

Returns an array of the string bodies of all fragments with any of the given labels in the boundy preamble.


Methodget_fragments

array(Message) get_fragments(multisetlabels)

Description

Returns an array of all fragments with any of the given labels in the boundy preamble.


Methodget_private_key

stringget_private_key()

Description

Convenience wrapper for get_private_key that returns the first available key, or 0.


Methodget_private_keys

array(string) get_private_keys()

Description

Returns an array of all the bodies of "RSA PRIVATE KEY", "DSA PRIVATE KEY", "EC PRIVATE KEY" and "ANY PRIVATE KEY" fragments.

Module Standards.PKCS

Description

Public-Key Cryptography Standards (PKCS).

This is the Pike API for dealing with a set of standards initially published by RSA Security Inc, and later by IETF and others in various RFCs.

See also

Standards.ASN1, Crypto, RFC 2314, RFC 2459, RFC 2986, RFC 3279, RFC 3280, RFC 4055, RFC 4985, RFC 5208, RFC 5280, RFC 5480, RFC 5639, RFC 5915, RFC 5958, RFC 7292, RFC 7468


Methodparse_private_key

Crypto.Sign.Stateparse_private_key(Sequenceseq)

Description

Parse a PKCS#8 PrivateKeyInfo (cf RFC 5208 section 5).

See also

parse_public_key(), RSA.parse_private_key(), DSA.parse_private_key()


Methodparse_public_key

Crypto.Sign.Stateparse_public_key(Sequenceseq)

Description

Parse a PKCS#10 SubjectPublicKeyInfo (cf RFC 5280 section 4.1 and RFC 7468 section 13).

See also

parse_private_key(), RSA.parse_public_key(), DSA.parse_public_key()

Module Standards.PKCS.CSR

Description

Handling of Certificate Signing Requests (PKCS-10, RFC 2314, RFC 2986)


Methodbuild_csr

Sequencebuild_csr(Crypto.Signsign, Sequencename, mapping(string:array(Object)) attributes, Crypto.Hash|voidhash)

Description

Build a Certificate Signing Request.

Parameter sign

Signature algorithm for the certificate. Both private and public keys must be set.

Parameter name

The distinguished name for the certificate.

Parameter attributes

Attributes from PKCS #9 to add to the certificate.

Parameter hash

Hash algoritm to use for the CSR signature. Defaults to Crypto.SHA256.

Note

Prior to Pike 8.0 this function only supported signing with Crypto.RSA and the default (and only) hash was Crypto.MD5.


Methodsign_cri

Sequencesign_cri(CRIcri, Crypto.Signsign, Crypto.Hashhash)

Description

Sign a CRI to generate a Certificate Signing Request.

Parameter cri

CertificationRequestInfo to sign.

Parameter sign

Signature to use. Must have a private key set that matches the public key in the keyinfo in cri.

Parameter hash

Hash algorithm to use for the signature.

Class Standards.PKCS.CSR.CRI

Description

CertificationRequestInfo

This is the data that is signed by sign_cri().


InheritSequence

inherit Sequence : Sequence


Variableattributes

void Standards.PKCS.CSR.CRI.attributes

Description

Subject attributes.


Variablekeyinfo

void Standards.PKCS.CSR.CRI.keyinfo

Description

Public key information.


Variablesubject

void Standards.PKCS.CSR.CRI.subject

Description

Certificate subject.


Variableversion

void Standards.PKCS.CSR.CRI.version

Class Standards.PKCS.CSR.CRIAttributes


InheritAttributes

inherit .Certificate.Attributes : Attributes

Module Standards.PKCS.Certificate

Description

Handle PKCS-6 and PKCS-10 certificates and certificate requests.


Methodbuild_distinguished_name

variantSequencebuild_distinguished_name(arrayargs)

Description

Creates an ASN.1 Sequence with the distinguished name of the list of pairs given in args. Supported identifiers are

commonName
surname
countryName
localityName
stateOrProvinceName
organizationName
organizationUnitName
title
name
givenName
initials
generationQualifier
dnQualifier
emailAddress
Parameter args

Either a mapping that lists from id string to string or ASN.1 object, or an array with mappings, each containing one pair. No type validation is performed.


Methoddecode_distinguished_name

array(mapping(string(7bit):string)) decode_distinguished_name(Sequencedn)

Description

Perform the reverse operation of build_distinguished_name().

See also

build_distinguished_name()


Methodget_dn_string

stringget_dn_string(Sequencednsequence)

Description

Converts an RDN (relative distinguished name) Seqeunce object to a human readable string in X500 format.

Returns

A string containing the certificate issuer Distinguished Name (DN) in human readable X500 format.

Note

We don't currently handle attributes with multiple values, not all attribute types are understood.

Module Standards.PKCS.DSA

Description

DSA operations as defined in RFC 2459.


Methodalgorithm_identifier

Sequencealgorithm_identifier(Crypto.DSA|voiddsa)

Description

Returns the AlgorithmIdentifier as defined in RFC 5280 section 4.1.1.2. Optionally the DSA parameters are included, if a DSA object is given as argument.


Methodbuild_private_key

Sequencebuild_private_key(Crypto.DSAdsa)

Description

Creates a PrivateKeyInfo ASN.1 sequence for the given rsa object. See RFC 5208 section 5.


Methodbuild_public_key

Sequencebuild_public_key(Crypto.DSAdsa)

Description

Creates a SubjectPublicKeyInfo ASN.1 sequence for the given dsa object. See RFC 5280 section 4.1.2.7.


Methodparse_private_key

Crypto.DSAparse_private_key(Sequenceseq)


Methodparse_private_key

variantCrypto.DSAparse_private_key(stringkey)


Methodparse_public_key

Crypto.DSA|zeroparse_public_key(stringkey, Gmp.mpzp, Gmp.mpzq, Gmp.mpzg)

Description

Decodes a DER-encoded DSAPublicKey structure.

Parameter key

DSAPublicKey provided in ASN.1 DER-encoded format

Parameter p

Public parameter p, usually transmitted in the algoritm identifier.

Parameter q

Public parameter q, usually transmitted in the algoritm identifier.

Parameter g

Public parameter g, usually transmitted in the algoritm identifier.

Returns

Crypto.DSA object


Methodprivate_key

stringprivate_key(Crypto.DSAdsa)


Methodpublic_key

stringpublic_key(Crypto.DSAdsa)

Description

Generates the DSAPublicKey value, as specified in RFC 2459.


Methodsignature_algorithm_id

Sequence|zerosignature_algorithm_id(Crypto.Hashhash)

Description

Returns the PKCS-1 algorithm identifier for DSA and the provided hash algorithm. One of SHA1, SHA224 or SHA256.

Module Standards.PKCS.ECDSA

Description

ECDSA operations.


Variablecurve_lookup

protectedmapping(string:Crypto.ECC.Curve) Standards.PKCS.ECDSA.curve_lookup

Description

Lookup from ASN.1 DER encoded ECC named curve identifier to the corresponding Crypto.ECC.Curve.


Methodparse_ec_parameters

Crypto.ECC.Curve|zeroparse_ec_parameters(stringec_parameters)

Description

Get the ECC curve corresponding to an ASN.1 DER encoded named curve identifier.

Returns

Returns UNDEFINED if the curve is unsupported.


Methodparse_private_key

Crypto.ECC.SECP_521R1.ECDSA|zeroparse_private_key(Sequencea, Crypto.ECC.Curve|voidc)

Description

Get an initialized ECDSA object from an ECC curve and an ASN.1 ec private key sequence.

As specified in RFC 5915 section 3.


Methodparse_private_key

variantCrypto.ECC.SECP_521R1.ECDSA|zeroparse_private_key(string(8bit)ec_private_key, Crypto.ECC.Curve|voidc)

Description

Get an initialized ECDSA object from an ECC curve and an ASN.1 DER encoded ec private key.

As specified in RFC 5915 section 3.


Methodparse_public_key

Crypto.ECC.SECP_521R1.ECDSAparse_public_key(string(8bit)key, Crypto.ECC.Curvec)

Description

Get an initialized ECDSA object from an ECC curve and an ec public key.

See RFC 5280 section 4.1.2.7 and RFC 5480 section 2.2.


Methodprivate_key

string(8bit)private_key(Crypto.ECC.SECP_521R1.ECDSAecdsa)

Description

Create a DER-coded ECPrivateKey structure

Parameter ecdsa

Crypto.ECC.Curve()->ECDSA object.

Returns

ASN.1 coded ECPrivateKey structure as specified in RFC 5915 section 3.


Methodpublic_key

string(8bit)public_key(Crypto.ECC.SECP_521R1.ECDSAecdsa)

Description

Create a DER-coded ECPublicKey structure

Parameter ecdsa

Crypto.ECC.Curve()->ECDSA object.

Returns

ASN.1 coded ECPublicKey structure as specified in RFC 5480 section 2.

Module Standards.PKCS.Identifiers

Description

Various ASN.1 identifiers used by PKCS.

See also

RFC 2459, RFC 3279, RFC 3280, RFC 3447, RFC 4055, RFC 4985, RFC 5480, RFC 5639, RFC 8410

Module Standards.PKCS.PFX

Description

PKCS #12: Personal Information Exchange Syntax v1.1, RFC 7292.

Module Standards.PKCS.RSA

Description

RSA operations and types as described in PKCS-1.


Methodalgorithm_identifier

Sequencealgorithm_identifier()

Description

Returns the AlgorithmIdentifier as defined in RFC 5280 section 4.1.1.2.


Methodbuild_private_key

Sequencebuild_private_key(Crypto.RSArsa)

Description

Creates a PrivateKeyInfo ASN.1 sequence for the given rsa object. See RFC 5208 section 5.


Methodbuild_public_key

Sequencebuild_public_key(Crypto.RSArsa)

Description

Creates a SubjectPublicKeyInfo ASN.1 sequence for the given rsa object. See RFC 5280 section 4.1.2.7.


Methodoaep_algorithm_id

Sequenceoaep_algorithm_id(Crypto.Hashhash, string(8bit)|voidlabel)

Description

Returns the PKCS-1 algorithm identifier for RSAES-OAEP and the provided hash algorithm and label.

See also

RFC 3447 appendix A.2.1


Methodparse_private_key

Crypto.RSA.Stateparse_private_key(Sequenceseq)

Description

Decode a RSAPrivateKey structure

Parameter key

RSAPrivateKey provided in ASN.1 format

Returns

Crypto.RSA object


Methodparse_private_key

variantCrypto.RSA.Stateparse_private_key(stringkey)

Description

Decode a DER-coded RSAPrivateKey structure

Parameter key

RSAPrivateKey provided in ASN.1 DER-encoded format

Returns

Crypto.RSA object


Methodparse_public_key

Crypto.RSA.Stateparse_public_key(stringkey)

Description

Decode a DER-coded RSAPublicKey structure

Parameter key

RSAPublicKey provided in ASN.1 DER-encoded format

Returns

Crypto.RSA object


Methodprivate_key

stringprivate_key(Crypto.RSArsa)

Description

Create a DER-coded RSAPrivateKey structure

Parameter rsa

Crypto.RSA object

Returns

ASN1 coded RSAPrivateKey structure


Methodpss_signature_algorithm_id

Sequencepss_signature_algorithm_id(Crypto.Hashhash, int(0..)|voidsaltlen)

Description

Returns the PKCS-1 algorithm identifier for RSASSA-PSS and the provided hash algorithm and saltlen.

See also

RFC 3447 appendix A.2.3


Methodpublic_key

stringpublic_key(Crypto.RSArsa)

Description

Create a DER-coded RSAPublicKey structure

Parameter rsa

Crypto.RSA object

Returns

ASN1 coded RSAPublicKey structure


Methodsignature_algorithm_id

Sequence|zerosignature_algorithm_id(Crypto.Hashhash)

Description

Returns the PKCS-1 algorithm identifier for RSA and the provided hash algorithm. One of MD2, MD5, SHA1, SHA256, SHA384 or SHA512.

Module Standards.PKCS.Signature


Methodbuild_digestinfo

stringbuild_digestinfo(stringmsg, Crypto.Hashhash)

Description

Construct a PKCS-1 digestinfo.

Parameter msg

message to digest

Parameter hash

crypto hash object such as Crypto.SHA1 or Crypto.MD5

See also

Crypto.RSA()->sign


Methodsign

Signedsign(Sequencetbs, Crypto.Signsign, Crypto.Hashhash)

Description

Generic PKCS signing.

Parameter tbs

Standards.ASN1 structure to be signed.

Parameter sign

Signature to use. Must have a private key set.

Parameter hash

Hash algorithm to use for the signature. Must be valid for the signature algorithm.

Returns

Returns a Standards.ASN1.Types.Sequence with the signature.

Class Standards.PKCS.Signature.Signed

Description

This is an ASN.1 structure from PKCS #10 v1.7 and others, which represents a signed block of data.

See also

sign(), Standards.X509.sign_tbs().


InheritSequence

inherit Sequence : Sequence


Variablealgorithm

Sequence Standards.PKCS.Signature.Signed.algorithm

Description

Getting

Signing algorithm that was used to sign with.

Setting

Signing algorithm that was used to sign with.


Variablesignature

BitString Standards.PKCS.Signature.Signed.signature

Description

Getting

The signature.

Setting

The signature.


Variabletbs

Object Standards.PKCS.Signature.Signed.tbs

Description

Getting

ASN.1 structure that has been signed.

Setting

ASN.1 structure that has been signed.


Methodsign

this_programsign(Crypto.Signsign, Crypto.Hashhash)

Description

Sign tbs with the provided sign and hash.

Sets algorithm and signature.

Returns

Returns the Signed object.

Module Standards.TLD


Constantcc

constant Standards.TLD.cc

Description

A mapping between country TLDs and the name of the country.


Variablegeneric

multiset Standards.TLD.generic

Description

A multiset containing the generic TLDs, such as "com" and "info".

Module Standards.UUID

Description

Support for Universal Unique Identifiers (UUID) and Globally Unique Identifiers (GUID).

See also

RFC 4122

A Universally Unique IDentifier (UUID) URN Namespace.

ITU-T X.667

Generation and registration of Universally Unique Identifiers (UUIDs) and their use as ASN.1 object identifier components.


ConstantNameSpace_DNS

constantstring Standards.UUID.NameSpace_DNS

Description

Name space UUID for DNS.


ConstantNameSpace_OID

constantstring Standards.UUID.NameSpace_OID

Description

Name space UUID for OID.


ConstantNameSpace_URL

constantstring Standards.UUID.NameSpace_URL

Description

Name space UUID for URL.


ConstantNameSpace_X500

constantstring Standards.UUID.NameSpace_X500

Description

Name space UUID for X500.


ConstantNil_UUID

constantstring Standards.UUID.Nil_UUID

Description

The Nil UUID.


Methodformat_uuid

stringformat_uuid(stringuuid)

Description

Returns the string representation of the binary UUID uuid.


Methodget_clock_state

array(int) get_clock_state()

Description

Returns the internal clock state. Can be used for persistent storage when an application is terminated.

See also

set_clock_state


Methodmake_dns

UUIDmake_dns(stringname)

Description

Creates a DNS UUID with the given DNS name.


Methodmake_dns

UUIDmake_dns(stringname)

Description

Creates a DNS UUID with the given DNS name.


Methodmake_null

UUIDmake_null()

Description

Creates a null UUID object.


Methodmake_oid

UUIDmake_oid(stringname)

Description

Creates an OID UUID with the given OID.


Methodmake_oid

UUIDmake_oid(stringname)

Description

Creates an OID UUID with the given OID.


Methodmake_url

UUIDmake_url(stringname)

Description

Creates a URL UUID with the given URL.


Methodmake_url

UUIDmake_url(stringname)

Description

Creates a URL UUID with the given URL.


Methodmake_version1

UUIDmake_version1(intnode)

Description

Creates a new version 1 UUID.

Parameter node

Either the 48 bit IEEE 802 (aka MAC) address of the system or -1.


Methodmake_version3

UUIDmake_version3(stringname, string|UUIDnamespace)

Description

Creates a version 3 UUID with a name string and a binary representation of a name space UUID.


Methodmake_version4

UUIDmake_version4()

Description

Creates a version 4 (random) UUID.


Methodmake_version5

UUIDmake_version5(stringname, string|UUIDnamespace)

Description

Creates a version 5 UUID with a name string and a binary representation of a name space UUID.


Methodmake_x500

UUIDmake_x500(stringname)

Description

Creates an X500 UUID with the gived X500 address.


Methodmake_x500

UUIDmake_x500(stringname)

Description

Creates an X500 UUID with the gived X500 address.


Methodparse_uuid

stringparse_uuid(stringuuid)

Description

Returns the binary representation of the UUID uuid.


Methodset_clock_state

voidset_clock_state(intlast_time, intseq)

Description

Sets the internal clock state.

See also

get_clock_state

Class Standards.UUID.UUID

Description

Represents an UUID


Variableclk_seq

int Standards.UUID.UUID.clk_seq

Description

The clock sequence. Should be 13 to 15 bits depending on UUID version.


Variablenode

int Standards.UUID.UUID.node

Description

The UUID node. Should be 48 bit.


Variabletimestamp

int Standards.UUID.UUID.timestamp

Description

60 bit value representing the time stamp.


Variablevar

int Standards.UUID.UUID.var

Description

The variant of the UUID.


Variableversion

int Standards.UUID.UUID.version

Description

The version of the UUID.


Methodcreate

Standards.UUID.UUIDStandards.UUID.UUID(void|stringin)

Description

Optionally created with a string or binary representation of a UUID.


Methodencode

stringencode()

Description

Encodes a binary representation of the UUID.


Methodposix_time

intposix_time()

Description

Returns the posix time of the UUID.


Methodstr

stringstr()

Description

Creates a string representation of the UUID.


Methodstr_variant

stringstr_variant()

Description

Returns a string representation of the variant, e.g. "IETF draft variant".


Methodstr_version

stringstr_version()

Description

Returns a string representation of the version, e.g. "Name-based (MD5)".


Methodtime_hi_and_version

inttime_hi_and_version()

Description

Returns the time_hi_and_version field.


Methodtime_low

inttime_low()

Description

Returns the time_low field.


Methodtime_mid

inttime_mid()

Description

Returns the time_mid field.


Methodurn

stringurn()

Description

Creates a URN representation of the UUID.


Methodvalidate

voidvalidate()

Description

Validates the current UUID.

Module Standards.X509

Description

Functions to generate and validate RFC 2459 style X.509 v3 certificates.


Methoddecode_certificate

TBSCertificate|zerodecode_certificate(string|.PKCS.Signature.Signedcert)

Description

Decodes a certificate and verifies that it is structually sound. Returns a TBSCertificate object if ok, otherwise 0.


Methodget_algorithms

mapping(Identifier:Crypto.Hash) get_algorithms()

Description

Returns the mapping of signature algorithm to hash algorithm supported by Verifier and thus verify_ca_certificate(), verify_certificate(), and verify_certificate_chain().


Methodget_letsencrypt_cert

arrayget_letsencrypt_cert(stringhost)

Description

Read and decode certificate chain for the given host from the letsencrypt directory (/etc/letsencrypt/live/{host}/). Note that the process has to have read privileges for the directory.

The resulting array can be used directly as input to the SSL.Context()->add_cert() method.

Returns
Array
Crypto.Sign.State0

A signing object using the private key.

array(string) 1

An array of DER encoded certificates representing the certificate chain.


Methodload_authorities

mapping(string:array(Verifier)) load_authorities(string|array(string)|voidroot_cert_dirs, bool|voidcache)

Description

Convenience function for loading known root certificates.

Parameter root_cert_dirs

Directory/directories containing the PEM-encoded root certificates to load. Defaults to a rather long list of directories, including "/etc/ssl/certs", "/etc/pki/tls/certs" and "/System/Library/OpenSSL/certs", which seem to be the most common locations.

Parameter cache

A flag to control if the answer should be given from an internal cache or always scan the directories. If a cache is used, it will refresh when any certificate expires (which typically is measured in years) or when asked for in unchached mode.

Returns

Returns a mapping from DER-encoded issuer to Verifiers compatible with eg verify_certificate()

Note

If a certificate directory contains a file named "ca-certificates.crt", "ca-bundle.crt" or "ca-bundle.trust.crt", it is assumed to contain a concatenation of all the certificates in the directory.

See also

verify_certificate(), verify_certificate_chain()


Methodmake_extension

Sequencemake_extension(Identifierid, Objectext, void|intcritical)

Description

Creates a certificate extension with the id as identifier and ext as the extension payload. If the critical flag is set the extension will be marked as critical.


Methodmake_selfsigned_certificate

stringmake_selfsigned_certificate(Crypto.Sign.Statec, intttl, mapping|arrayname, mapping(Identifier:Sequence)|voidextensions, Crypto.Hash|voidh, int|voidserial)

Description

Creates a selfsigned certificate, i.e. where issuer and subject are the same entity. This entity is derived from the list of pairs in name, which is encoded into an distinguished_name by Standards.PKCS.Certificate.build_distinguished_name.

Parameter c

The public key cipher used for the certificate, Crypto.RSA, Crypto.DSA or Crypto.ECC.Curve.ECDSA. The object should be initialized with both public and private keys.

Parameter ttl

The validity of the certificate, in seconds, starting from creation date.

Parameter name

List of properties to create distinguished name from.

Parameter extensions

Mapping with extensions as ASN.1 structures, as produced by make_extension. The extensions subjectKeyIdentifier, keyUsage (flagged critical) and basicConstraints (flagged critical) will automatically be added if not present.

Parameter h

The hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto. By default Crypto.SHA256 is selected for both RSA and DSA.

Parameter serial

Serial number of the certificate. Defaults to generating a UUID version1 value with random node. Some browsers will refuse different certificates from the same signer with the same serial number.

See also

sign_key(), sign_tbs()


Methodmake_tbs

TBSCertificatemake_tbs(Sequenceissuer, Sequencealgorithm, Sequencesubject, Sequencekeyinfo, Integerserial, Sequencevalidity, array|int(0)|voidextensions)

Description

Creates the ASN.1 TBSCertificate sequence (see RFC 2459 section 4.1) to be signed (TBS) by the CA. version is explicitly set to v3, and extensions is optionally added to the sequence. issuerUniqueID and subjectUniqueID are not supported.


Methodmake_tbs

variantTBSCertificatemake_tbs(Sequenceissuer, Sequencealgorithm, Sequencesubject, Sequencekeyinfo, Integerserial, intttl, array|int(0)|voidextensions)

Description

Creates the ASN.1 TBSCertificate sequence (see RFC 2459 section 4.1) to be signed (TBS) by the CA. version is explicitly set to v3, validity is calculated based on time and ttl, and extensions is optionally added to the sequence. issuerUniqueID and subjectUniqueID are not supported.

Note

Prior to Pike 8.0 this function returned a plain Sequence object.


Methodparse_private_key

Crypto.Sign.Stateparse_private_key(Sequenceseq)

Description

DWIM-parse the ASN.1-sequence for a private key.


Methodparse_private_key

variantCrypto.Sign.Stateparse_private_key(string(8bit)private_key)

Description

DWIM-parse the DER-sequence for a private key.


Methodsign_key

stringsign_key(Sequenceissuer, Crypto.Sign.Statec, Crypto.Sign.Stateca, Crypto.Hashh, Sequencesubject, intserial, intttl, array|mapping|voidextensions)

Description

Low-level function for creating a signed certificate.

Parameter issuer

Distinguished name for the issuer. See Standards.PKCS.Certificate.build_distinguished_name.

Parameter c

RSA, DSA or ECDSA parameters for the subject. Only the public key needs to be set. See Crypto.RSA, Crypto.DSA and Crypto.ECC.Curve.ECDSA.

Parameter ca

RSA, DSA or ECDSA parameters for the issuer. Only the private key needs to be set. See Crypto.RSA, Crypto.DSA and Crypto.ECC.Curve.ECDSA.

Parameter h

The hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto.

Parameter subject

Distinguished name for the subject. See Standards.PKCS.Certificate.build_distinguished_name.

Parameter public_key

DER-encoded RSAPublicKey structure. See Standards.PKCS.RSA.public_key().

Parameter serial

Serial number for this key and subject.

Parameter ttl

Validity time in seconds for this signature to be valid.

Parameter extensions

Set of extensions.

Returns

Returns a DER-encoded certificate.

See also

make_selfsigned_certificate(), make_tbs(), sign_tbs()


Methodsign_tbs

Sequencesign_tbs(TBSCertificatetbs, Crypto.Sign.Statesign, Crypto.Hashhash)

Description

Sign the provided TBSCertificate.

Parameter tbs

A TBSCertificate as returned by decode_certificate() or make_tbs().

Parameter sign

RSA, DSA or ECDSA parameters for the issuer. See Crypto.RSA, Crypto.DSA and Crypto.ECC.Curve.ECDSA. Must be initialized with the private key.

Parameter hash

The hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto.

See also

decode_certificate(), make_tbs()


Methodverify_ca_certificate

TBSCertificate|zeroverify_ca_certificate(string|TBSCertificatetbs)

Description

Verifies that all extensions mandated for certificate signing certificates are present and valid.


Methodverify_certificate

TBSCertificate|zeroverify_certificate(strings, mapping(string:Verifier|array(Verifier)) authorities, mapping(Standards.ASN1.Types.Identifier:Crypto.Hash)|voidoptions)

Description

Decodes a certificate, checks the signature. Returns the TBSCertificate structure, or 0 if decoding or verification fails. The valid time range for the certificate is not checked.

Parameter authorities

A mapping from (DER-encoded) names to a verifiers.

Parameter options
"verifier_algorithms" : mapping(Standards.ASN1.Types.Identifier:Crypto.Hash)

A mapping of verifier algorithm identifier to hash algorithm implementation.

Note

This function allows self-signed certificates, and it doesn't check that names or extensions make sense.


Methodverify_certificate_chain

mappingverify_certificate_chain(array(string|.PKCS.Signature.Signed) cert_chain, mapping(string:Verifier|array(Verifier)) authorities, int|voidrequire_trust, mapping(string:mixed)|bool|voidoptions)

Description

Decodes a certificate chain, ordered from leaf to root, and checks the signatures. Verifies that the chain can be decoded correctly, is unbroken, and that all certificates are in effect (time-wise.) and allowed to sign its child certificate.

No verifications are done on the leaf certificate to determine what it can and can not be used for.

Returns a mapping with the following contents, depending on the verification of the certificate chain:

"error_code" : int

Error describing type of verification failures, if verification failed. May be one of the following, OR:ed together: CERT_TOO_NEW, CERT_TOO_OLD, CERT_ROOT_UNTRUSTED, CERT_BAD_SIGNATURE, CERT_INVALID, CERT_CHAIN_BROKEN, CERT_UNAUTHORIZED_CA or CERT_EXCEEDED_PATH_LENGTH.

"error_cert" : int

Index number of the certificate that caused the verification failure.

"self_signed" : bool

Non-zero if the certificate is self-signed.

"verified" : bool

Non-zero if the certificate is verified.

"authority" : Standards.ASN1.Sequence

The authority RDN that verified the chain.

"cn" : Standards.ASN1.Sequence

The common name RDN of the leaf certificate.

"certificates" : array(TBSCertificate)

An array with the decoded certificates, ordered from root to leaf.

Parameter cert_chain

An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate, or decoded as a Standards.PKCS.Signature.Signed object.

Parameter authorities

A mapping from (DER-encoded) names to verifiers.

Parameter require_trust

Require that the certificate be traced to an authority, even if it is self signed.

Parameter strict

By default this function only requires that the certificates are in order, it ignores extra certificates we didn't need to verify the leaf certificate.

If you specify strict, this will change, each certificate has to be signed by the next in the chain.

Some https-servers send extraneous intermediate certificates that aren't used to validate the leaf certificate. So strict mode will be incompatible with such srevers.

Parameter options
"verifier_algorithms" : mapping(Standards.ASN1.Types.Identifier:Crypto.Hash)

A mapping of verifier algorithm identifier to hash algorithm implementation.

"strict" : int

See strict above.

See also

get_algorithms()

See Standards.PKCS.Certificate.get_dn_string for converting the RDN to an X500 style string.

Enum Standards.X509.CertFailure


ConstantCERT_BAD_SIGNATURE

constant Standards.X509.CERT_BAD_SIGNATURE


ConstantCERT_CHAIN_BROKEN

constant Standards.X509.CERT_CHAIN_BROKEN


ConstantCERT_EXCEEDED_PATH_LENGTH

constant Standards.X509.CERT_EXCEEDED_PATH_LENGTH

Description

The certificate chain is longer than allowed by a certificate in the chain.


ConstantCERT_INVALID

constant Standards.X509.CERT_INVALID


ConstantCERT_ROOT_UNTRUSTED

constant Standards.X509.CERT_ROOT_UNTRUSTED


ConstantCERT_TOO_NEW

constant Standards.X509.CERT_TOO_NEW


ConstantCERT_TOO_OLD

constant Standards.X509.CERT_TOO_OLD


ConstantCERT_UNAUTHORIZED_CA

constant Standards.X509.CERT_UNAUTHORIZED_CA

Description

A CA certificate is not allowed by basic constraints to sign another certificate.


ConstantCERT_UNAUTHORIZED_SIGNING

constant Standards.X509.CERT_UNAUTHORIZED_SIGNING

Description

The certificate is not allowed by its key usage to sign data.

Enum Standards.X509.keyUsage


ConstantKU_digitalSignature
ConstantKU_nonRepudiation
ConstantKU_keyEncipherment
ConstantKU_dataEncipherment
ConstantKU_keyAgreement
ConstantKU_keyCertSign
ConstantKU_cRLSign
ConstantKU_encipherOnly
ConstantKU_decipherOnly
ConstantKU_last_keyUsage

constant Standards.X509.KU_digitalSignature
constant Standards.X509.KU_nonRepudiation
constant Standards.X509.KU_keyEncipherment
constant Standards.X509.KU_dataEncipherment
constant Standards.X509.KU_keyAgreement
constant Standards.X509.KU_keyCertSign
constant Standards.X509.KU_cRLSign
constant Standards.X509.KU_encipherOnly
constant Standards.X509.KU_decipherOnly
constant Standards.X509.KU_last_keyUsage

Class Standards.X509.IssuerId

Description

Unique identifier for the certificate issuer.

X.509v2 (deprecated).


InheritBitString

inherit BitString : BitString

Class Standards.X509.SubjectId

Description

Unique identifier for the certificate subject.

X.509v2 (deprecated).


InheritBitString

inherit BitString : BitString

Class Standards.X509.TBSCertificate

Description

Represents a TBSCertificate.

Note

Was not compatible with Standards.ASN1.Types.Sequence prior to Pike 8.0.


InheritSequence

inherit Sequence : Sequence


Variablealgorithm

void Standards.X509.TBSCertificate.algorithm

Description

Algorithm Identifier.


Variablecritical

multiset Standards.X509.TBSCertificate.critical

Note

optional

Note

Read only


Variableder

void Standards.X509.TBSCertificate.der


Variableext_authorityKeyIdentifier

bool Standards.X509.TBSCertificate.ext_authorityKeyIdentifier

Description

Set if the certificate contains a valid authorityKeyIdentifier extension. RFC 3280 section 4.2.1.1.


Variableext_authorityKeyIdentifier_authorityCertSerialNumber

Gmp.mpz Standards.X509.TBSCertificate.ext_authorityKeyIdentifier_authorityCertSerialNumber

Description

Set to the CertificateSerialNumber, if set in the extension.


Variableext_authorityKeyIdentifier_keyIdentifier

string Standards.X509.TBSCertificate.ext_authorityKeyIdentifier_keyIdentifier

Description

Set to the KeyIdentifier, if set in the extension.


Variableext_basicConstraints

bool Standards.X509.TBSCertificate.ext_basicConstraints

Description

Set if the certificate contains a valid basicConstraints extension. RFC 3280 section 4.2.1.10.


Variableext_basicConstraints_cA

bool Standards.X509.TBSCertificate.ext_basicConstraints_cA

Description

If set, the certificate may be used as a CA certificate, i.e. sign other certificates.


Variableext_basicConstraints_pathLenConstraint

int Standards.X509.TBSCertificate.ext_basicConstraints_pathLenConstraint

Description

The maximum number of certificates that may follow this certificate in a certificate chain. 0 in case no limit is imposed. Note that this variable is off by one compared to the RFC 3280 definition, which only counts intermediate certificates (i.e. 0 intermediates means this variable would be 1, as in one following certificate).


Variableext_extKeyUsage

array(Identifier) Standards.X509.TBSCertificate.ext_extKeyUsage

Description

Set to the list of extended key usages from anyExtendedKeyUsage, if the certificate contains the extKeyUsage extensions. These Identifier objects are typically found in .PKCS.Identifiers.reverse_kp_ids. RFC 3280 section 4.2.1.13.


Variableext_keyUsage

keyUsage Standards.X509.TBSCertificate.ext_keyUsage

Description

Set to the value of the KeyUsage if the certificate contains the keyUsage extension. RFC 3280 section 4.2.1.3.


Variableext_subjectKeyIdentifier

string Standards.X509.TBSCertificate.ext_subjectKeyIdentifier

Description

Set to the value of the SubjectKeyIdentifier if the certificate contains the subjectKeyIdentifier extension. RFC 3280 section 4.2.1.2.


Variableextensions

mapping(Identifier:Object) Standards.X509.TBSCertificate.extensions

Note

optional

Note

Read only


Variablehash

Crypto.Hash Standards.X509.TBSCertificate.hash

Description

Algorithm hash if known and supported. Otherwise UNDEFINED.

Note

Read only


Variableinternal_critical

protectedmultiset Standards.X509.TBSCertificate.internal_critical

Note

optional


Variableinternal_extensions

protectedmapping(Identifier:Object) Standards.X509.TBSCertificate.internal_extensions

Note

optional


Variableissuer

void Standards.X509.TBSCertificate.issuer

Description

Certificate issuer.


Variableissuer_id

void Standards.X509.TBSCertificate.issuer_id

Note

optional


Variablekeyinfo

void Standards.X509.TBSCertificate.keyinfo


Variablenot_after

void Standards.X509.TBSCertificate.not_after


Variablenot_before

void Standards.X509.TBSCertificate.not_before


Variablepublic_key

void Standards.X509.TBSCertificate.public_key


Variableraw_extensions

void Standards.X509.TBSCertificate.raw_extensions

Description

The raw ASN.1 objects from which extensions and critical have been generated.

Note

optional


Variableserial

void Standards.X509.TBSCertificate.serial


Variablesubject

void Standards.X509.TBSCertificate.subject


Variablesubject_id

void Standards.X509.TBSCertificate.subject_id

Note

optional


Variablevalidity

void Standards.X509.TBSCertificate.validity


Variableversion

void Standards.X509.TBSCertificate.version


Methoddn_str

stringdn_str(Sequencedn)

Description

Try to extract a readable name from dn. This is one of commonName, organizationName or organizationUnitName. The first that is found is returned. Suitable for subjects and issuer sequences.


Methodinit

this_programinit(array|Objectasn1)

Description

Populates the object from a certificate decoded into an ASN.1 Object. Returns the object on success, otherwise 0. You probably want to call decode_certificate or even verify_certificate.


Methodissuer_str

stringissuer_str()

Description

Return the issuer of the certificate as a human readable string. Mainly useful for debug.


Methodlow_set

protectedvoidlow_set(intindex, Sequence|Integerval)

Parameter index

Index in a v1 certificate.

Parameter val

New value for index.


Methodsubject_str

stringsubject_str()

Description

Attempt to create a presentable string from the subject DER.

Class Standards.X509.Verifier


Methodverify

boolverify(Sequencealgorithm, string(8bit)msg, string(8bit)signature, mapping(Identifier:Crypto.Hash)|voidverifier_algorithms)

Description

Verifies the signature of the certificate msg using the indicated hash algorithm, choosing from verifier_algorithms.

See also

get_algorithms()

Module Standards.XML

Module Standards.XML.Wix

Description

Helper module for generating Windows Installer XML structures.

See also

Parser.XML.Tree.SimpleNode


Methodget_module_xml

WixNodeget_module_xml(Directorydir, stringid, stringversion, string|voidmanufacturer, string|voiddescription, string|voidguid, string|voidcomments, string|voidinstaller_version)

Note

Modifies dir if it contains files at the root level.

Module Standards._BSON


Methoddecode

mappingdecode(Stdio.Bufferdocument)


Methoddecode

mappingdecode(string(8bit)document)

Module Sybase

Class Sybase.sybase


InheritConnection

inherit __builtin.Sql.Connection : Connection

Module System

Description

This module embodies common operating system calls, making them available to the Pike programmer.


Inherit_system

inherit _system : _system


ConstantCPU_TIME_IMPLEMENTATION

constantstring System.CPU_TIME_IMPLEMENTATION

Description

This string constant identifies the internal interface used to get the CPU time. It is an implementation detail - see rusage.c for possible values and their meanings.

See also

gethrvtime, gauge


ConstantCPU_TIME_IS_THREAD_LOCAL

constantstring System.CPU_TIME_IS_THREAD_LOCAL

Description

This string constant tells whether or not the CPU time, returned by e.g. gethrvtime, is thread local or not. The value is "yes" if it is and "no" if it isn't. The value is also "no" if there is no thread support.

See also

gethrvtime, gauge


ConstantCPU_TIME_RESOLUTION

constantint System.CPU_TIME_RESOLUTION

Description

The resolution of the CPU time, returned by e.g. gethrvtime, in nanoseconds. It is -1 if the resolution isn't known.

See also

gethrvtime, gauge


ConstantHKEY_CLASSES_ROOT
ConstantHKEY_LOCAL_MACHINE
ConstantHKEY_CURRENT_USER
ConstantHKEY_USERS

constantint System.HKEY_CLASSES_ROOT
constantint System.HKEY_LOCAL_MACHINE
constantint System.HKEY_CURRENT_USER
constantint System.HKEY_USERS

Description

Root handles in the Windows registry.

Note

These constants are only available on Win32 systems.

See also

RegGetValue(), RegGetValues(), RegGetKeyNames()


ConstantITIMER_PROF

constant System.ITIMER_PROF

Description

Identifier for a timer that decrements both when the process is executing and when the system is executing on behalf of the process.

See also

setitimer, getitimer


ConstantITIMER_REAL

constant System.ITIMER_REAL

Description

Identifier for a timer that decrements in real time.

See also

setitimer, getitimer


ConstantITIMER_VIRTUAL

constant System.ITIMER_VIRTUAL

Description

Identifier for a timer that decrements only when the process is executing.

See also

setitimer, getitimer


ConstantREAL_TIME_IMPLEMENTATION

constantstring System.REAL_TIME_IMPLEMENTATION

Description

This string constant identifies the internal interface used to get the high resolution real time. It is an implementation detail - see rusage.c for possible values and their meanings.

See also

gethrtime


ConstantREAL_TIME_IS_MONOTONIC

constantstring System.REAL_TIME_IS_MONOTONIC

Description

This string constant tells whether or not the high resolution real time returned by gethrtime, is monotonic or not. The value is "yes" if it is and "no" if it isn't.

Monotonic time is not affected by clock adjustments that might happen to keep the calendaric clock in synch. It's therefore more suited to measure time intervals in programs.

See also

gethrtime


ConstantREAL_TIME_RESOLUTION

constantint System.REAL_TIME_RESOLUTION

Description

The resolution of the real time returned by gethrtime, in nanoseconds. It is -1 if the resolution isn't known.

See also

gethrtime


MethodAllocConsole

intAllocConsole()

Description

Allocates a new console for the calling process.

Note

Only available on certain Windows systems.

Returns

0 on success, non-zero otherwise.


MethodAttachConsole

intAttachConsole(intpid)

Description

Attaches calling process to a specific console.

Parameter pid
Note

Only available on certain Windows systems.

Returns

0 on success, non-zero otherwise.


MethodFreeConsole

intFreeConsole()

Description

Detaches the calling process from its console.

Note

Before calling this function, Stdio.stderr, Stdio.stdout and Stdio.stdin must be closed.

Note

Only available on certain Windows systems.

Returns

0 on success, non-zero otherwise.


MethodGetComputerName

stringGetComputerName()

Description

Retrieves the NetBIOS name of the local computer.

Note

This function is Windows specific, and is not available on all systems.


MethodGetFileAttributes

intGetFileAttributes(string(8bit)filename)

Description

Get the file attributes for the specified file.

Note

This function is only available on Win32 systems.

See also

SetFileAttributes()


MethodGetNamedSecurityInfo

mapping(string:mixed) GetNamedSecurityInfo(stringname, int|voidtype, int|voidflags)

Note

This function is only available on some Win32 systems.

See also

SetNamedSecurityInfo()


MethodGetUserName

stringGetUserName()

Description

Retrieves the name of the user associated with the current thread.

Note

This function is Windows specific, and is not available on all systems.


MethodLogonUser

UserTokenLogonUser(stringusername, string|zerodomain, string|zeropassword, int|voidlogon_type, int|voidlogon_provider)

Description

Logon a user.

Parameter username

User name of the user to login.

Parameter domain

Domain to login on, or zero if local logon.

Parameter password

Password to login with (if required).

Parameter logon_type

One of the following values:

LOGON32_LOGON_BATCH 
LOGON32_LOGON_INTERACTIVE 
LOGON32_LOGON_SERVICE 
LOGON32_LOGON_NETWORK

This is the default.

Parameter logon_provider

One of the following values:

LOGON32_PROVIDER_DEFAULT

This is the default.

Returns

Returns a login UserToken object on success, and zero on failure.

Note

This function is only available on some Win32 systems.


MethodLookupAccountName

array(mixed) LookupAccountName(string|int(0)sys, stringaccount)

Returns

Returns 0 (zero) if the account was not found, and an array containing the following on success:

Array
SID0

SID object representing the account.

string1

Domain name.

int2

Account type.

Note

This function is only available on some Win32 systems.


MethodNetGetAnyDCName

stringNetGetAnyDCName(string|int(0)server, stringdomain)

Description

Get name of a domain controller from a server.

Parameter server

Server the domain exists on.

Parameter domain

Domain to get a domain controller for.

Returns

Returns the name of a domain controller on success. Throws errors on failure.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName()


MethodNetGetDCName

stringNetGetDCName(string|int(0)server, stringdomain)

Description

Get name of the domain controller from a server.

Parameter server

Server the domain exists on.

Parameter domain

Domain to get the domain controller for.

Returns

Returns the name of the domain controller on success. Throws errors on failure.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetAnyDCName()


MethodNetGroupEnum

array(string|array(string|int)) NetGroupEnum(string|int(0)|voidserver, int|voidlevel)

Description

Get information about network groups.

Parameter server

Server the groups exist on.

Parameter level

Information level. One of:

0
1
2
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetGroupGetUsers

array(string|array(int|string)) NetGroupGetUsers(string|int(0)server, stringgroup, int|voidlevel)

Description

Get information about group membership for a network group.

Parameter server

Server the groups exist on.

Parameter group

Group to retrieve members for.

Parameter level

Information level. One of:

0
1
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetLocalGroupEnum

array(array(string|int)) NetLocalGroupEnum(string|int(0)|voidserver, int|voidlevel)

Description

Get information about local network groups.

Parameter server

Server the groups exist on.

Parameter level

Information level. One of:

0
1
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetLocalGroupGetMembers

array(string|array(int|string)) NetLocalGroupGetMembers(string|int(0)server, stringgroup, int|voidlevel)

Description

Get information about group membership for a network group.

Parameter server

Server the groups exist on.

Parameter group

Group to retrieve members for.

Parameter level

Information level. One of:

0
1
2
3
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetGetDCName(), NetGetAnyDCName()


MethodNetSessionEnum

array(int|string) NetSessionEnum(string|int(0)server, string|int(0)client, string|int(0)user, intlevel)

Description

Get session information.

Parameter level

One of

0
1
2
10
502
Note

This function is only available on some Win32 systems.


MethodNetUserEnum

array(string|array(string|int)) NetUserEnum(string|int(0)|voidserver, int|voidlevel, int|voidfilter)

Description

Get information about network users.

Parameter server

Server the users exist on.

Parameter level

Information level. One of:

0
1
2
3
10
11
20
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetGroupEnum()NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetUserGetGroups

array(array(string|int)) NetUserGetGroups(string|int(0)server, stringuser, int|voidlevel)

Description

Get information about group membership for a network user.

Parameter server

Server the groups exist on.

Parameter user

User to retrieve groups for.

Parameter level

Information level. One of:

0
1
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetLocalGroupEnum(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetUserGetInfo

string|array(string|int) NetUserGetInfo(stringusername, string|int(0)server, int|voidlevel)

Description

Get information about a network user.

Parameter username

User name of the user to get information about.

Parameter server

Server the user exists on.

Parameter level

Information level. One of:

0
1
2
3
10
11
20
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserEnum(), NetGroupEnum()NetLocalGroupEnum(), NetUserGetGroups(), NetUserGetLocalGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetUserGetLocalGroups

array(string) NetUserGetLocalGroups(string|int(0)server, stringuser, int|voidlevel, int|voidflags)

Description

Get information about group membership for a local network user.

Parameter server

Server the groups exist on.

Parameter user

User to retrieve groups for.

Parameter level

Information level. One of:

0
Parameter flags

Zero, of one of the following:

LG_INCLUDE_INDIRECT
Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo(), NetUserEnum(), NetGroupEnum(), NetLocalGroupEnum(), NetUserGetGroups(), NetGroupGetUsers(), NetLocalGroupGetMembers(), NetGetDCName(), NetGetAnyDCName()


MethodNetWkstaUserEnum

array(mixed) NetWkstaUserEnum(string|int(0)server, intlevel)

Parameter level

One of

0
1
Note

This function is only available on some Win32 systems.


MethodSetFileAttributes

intSetFileAttributes(string(8bit)filename)

Description

Set the file attributes for the specified file.

Note

This function is only available on Win32 systems.

See also

GetFileAttributes()


MethodSetNamedSecurityInfo

intSetNamedSecurityInfo(stringname, mapping(string:mixed) options)

Note

This function is only available on some Win32 systems.

See also

GetNamedSecurityInfo()


Methodchmod

voidchmod(stringpath, intmode)

Description

Sets the protection mode of the specified path.

Note

Throws errors on failure.

See also

Stdio.File->open(), errno()


Methodchown

voidchown(stringpath, intuid, intgid, void|intsymlink)

Description

Sets the owner and group of the specified path.

If symlink is set and path refers to a symlink, then the owner and group for the symlink are set. Symlinks are dereferenced otherwise.

Note

Throws errors on failure.

This function is not available on all platforms. On some platforms the symlink flag isn't supported. In that case, the function does nothing if path is a symlink.


Methodchroot

intchroot(stringnewroot)
intchroot(Stdio.Filenewroot)

Description

Changes the root directory for this process to the indicated directory.

Returns

A nonzero value is returned if the call is successful. If there's an error then zero is returned and errno is set appropriately.

Note

Since this function modifies the directory structure as seen from Pike, you have to modify the environment variables PIKE_MODULE_PATH and PIKE_INCLUDE_PATH to compensate for the new root-directory.

This function only exists on systems that have the chroot(2) system call.

The second variant only works on systems that also have the fchroot(2) system call.

Note

On success the current working directory will be changed to the new "/". This behavior was added in Pike 7.9.

Note

This function could be interrupted by signals prior to Pike 7.9.


Methodcleargroups

voidcleargroups()

Description

Clear the supplemental group access list.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

setgroups(), initgroups(), getgroups()


Methodclonefile

voidclonefile(stringfrom, stringto)

Description

Copy a file from with copy-on-write semantics to the destination named to.

Note

This function is currently only available on macOS and Linux, and then only when from and to reference a common file system with copy-on-write support (e.g. an APFS volume).

See also

hardlink(), symlink()


Methodcloselog

voidcloselog()

FIXME

Document this function.


Methoddaemon

intdaemon(intnochdir, intnoclose)

Description

Low level system daemon() function, see also Process.daemon()


Methoddrop_privs

voiddrop_privs(stringuser, void|stringgroup, void|intexception)

Description

Drops the process privileges to the provided user and optionally group. If no group is provided the default group for the user is used.

Parameter exception

If true, an error exception will be thrown if


Methoddumpable

booldumpable(bool|voidval)

Description

Get and/or set whether this process should be able to dump core.

Parameter val

Optional argument to set the core dumping state.

0

Disable core dumping for this process.

1

Enable core dumping for this process.

Returns

Returns 1 if this process currently is capable of dumping core, and 0 (zero) if not.

Note

This function is currently only available on some versions of Linux.


Methodendgrent

intendgrent()

Description

Closes the /etc/groups file after using the getgrent function.

See also

get_all_groups()getgrent()setgrent()


Methodendpwent

intendpwent()

Description

Closes the passwd source opened by getpwent function using the systemfunction endpwent(3).

Returns

Always 0 (zero)

See also

get_all_users()getpwent()setpwent()


Methodget_home

string|zeroget_home()

Description

Get the full path for the current user's home directory

Returns

the full path to the current user's home directory, or zero if the appropriate environment variables have not been set.

Note

This method uses the standard environment variables for various systems to determine the home directory.


Methodget_netinfo_property

array(string) get_netinfo_property(stringdomain, stringpath, stringproperty)

Description

Queries a NetInfo server for property values at the given path.

Parameter domain

NetInfo domain. Use "." for the local domain.

Parameter path

NetInfo path for the property.

Parameter property

Name of the property to return.

Returns

An array holding all property values. If the path or property cannot be not found 0 is returned instead. If the NetInfo domain is not found or cannot be queried an exception is thrown.

Example

system.get_netinfo_property(".", "/locations/resolver", "domain"); ({ "idonex.se" })

Note

Only available on operating systems which have NetInfo libraries installed.


Methodget_user

string|zeroget_user()

Description

Get the username of the user that started the process.

Returns

the username of the user "associated" with the current process, or zero if a method to find this information does not exist on the current system.

Note

On NT systems, this returns the user the current thread is running as, while on Unix-like systems this function returns the user that started the process (rather than the effective user)..


Methodgetegid

intgetegid()

Description

Get the effective group ID.

See also

setuid, getuid, setgid, getgid, seteuid, geteuid, setegid


Methodgeteuid

intgeteuid()

Description

Get the effective user ID.

See also

setuid, getuid, setgid, getgid, seteuid, getegid, setegid


Methodgetgid

intgetgid()

Description

Get the real group ID.

See also

setuid, getuid, setgid, seteuid, geteuid, getegid, setegid


Methodgetgrent

array(int|string|array(string)) getgrent()

Description

Get a group entry from /etc/groups file. getgrent interates thru the groups source and returns one entry per call using the systemfunction getgrent(3).

Always call endgrent when done using getgrent!

Returns

An array with the information about the group

Array
string0

Group name

string1

Group password (encrypted)

int2

ID of the group

array3..

Array with UIDs of group members

See also

get_all_groups()getgrnam()getgrgid()


Methodgetgroups

array(int) getgroups()

Description

Get the current supplemental group access list for this process.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

setgroups(), cleargroups(), initgroups(), getgid(), getgid(), getegid(), setegid()


Methodgethostbyaddr

array(string|array(string)) gethostbyaddr(stringaddr)

Description

Returns an array with information about the specified IP address.

Returns

The returned array contains the same information as that returned by gethostbyname().

Note

This function only exists on systems that have the gethostbyaddr(2) or similar system call.

See also

gethostbyname()


Methodgethostbyname

array(string|array(string)) gethostbyname(stringhostname)

Description

Returns an array with information about the specified host.

Returns

The returned array contains the following:

Array
stringhostname

Name of the host.

array(string) ips

Array of IP numbers for the host.

array(string) aliases

Array of alternative names for the host.

Note

This function only exists on systems that have the gethostbyname(2) or similar system call.

See also

gethostbyaddr()


Methodgethostname

stringgethostname()

Description

Returns a string with the name of the host.

Note

This function only exists on systems that have the gethostname(2) or uname(2) system calls.


Methodgetitimer

array(float) getitimer(inttimer)

Description

Shows the state of the selected timer.

Returns
Array
float0

The interval of the timer.

float1

The value of the timer.

Parameter timer

One of ITIMER_REAL, ITIMER_VIRTUAL and ITIMER_PROF.


Methodgetloadavg

array(float) getloadavg()

Description

Get system load averages.

Returns
Array
float0

Load average over the last minute.

float1

Load average over the last 5 minutes.

float2

Load average over the last 15 minutes.


Methodgetpgrp

intgetpgrp(int|voidpid)

Description

Get the process group id for the process pid. With no argguments or with 'pid' equal to zero, returns the process group ID of this process.

Note

Not all platforms support getting the process group for other processes.

Not supported on all platforms.

See also

getpid, getppid


Methodgetpid

intgetpid()

Description

Returns the process ID of this process.

See also

getppid, getpgrp


Methodgetppid

intgetppid()

Description

Returns the process ID of the parent process.

See also

getpid, getpgrp


Methodgetpwent

array(int|string) getpwent()

Description

When first called, the getpwent function opens the passwd source and returns the first record using the systemfunction getpwent(3). For each following call, it returns the next record until EOF.

Call endpwent when done using getpwent.

Returns

An array with the information about the user

Array
string0

Users username (loginname)

string1

User password (encrypted)

int2

Users ID

int3

Users primary group ID

string4

Users real name an possibly some other info

string5

Users home directory

string6

Users shell

0 if EOF.

See also

get_all_users()getpwnam()getpwent()setpwent()endpwent()


Methodgetrlimit

array(int) getrlimit(stringresource)

Description

Returns the current process limitation for the selected resource.

Parameter resource
cpu

The CPU time limit in seconds.

fsize

The maximum size of files the process may create.

data

The maximum size of the process's data segment.

stack

The maximum size of process stack, in bytes.

core 
rss

Specifies the limit of pages the process's resident set.

nproc

The maximum number of processes that can be created for the real user ID of the calling process.

nofile

The maximum number of file descriptors the process can open, +1.

memlock

The maximum number of bytes of virtual memory that may be locked into RAM.

as 
vmem 
Returns
Array
int0

The soft limit for the resource. -1 means no limit.

int1

The hard limit for the resource. -1 means no limit.

Note

This function nor all the resources are available on all systems.

See also

getrlimits, setrlimit


Methodgetrlimits

mapping(string:array(int)) getrlimits()

Description

Returns all process limits in a mapping.

See also

getrlimit, setrlimit


Methodgetrusage

mapping(string:int) getrusage()

Description

Return resource usage about the current process. An error is thrown if it isn't supported or if the system fails to return any information.

Returns

Returns a mapping describing the current resource usage:

"utime" : int

Time in milliseconds spent in user code.

"stime" : int

Time in milliseconds spent in system calls.

"maxrss" : int

Maximum used resident size in kilobytes. [1]

"ixrss" : int

Quote from GNU libc: An integral value expressed in kilobytes times ticks of execution, which indicates the amount of memory used by text that was shared with other processes. [1]

"idrss" : int

Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for data. [1]

"isrss" : int

Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for stack space. [1]

"minflt" : int

Minor page faults, i.e. TLB misses which required no disk I/O.

"majflt" : int

Major page faults, i.e. paging with disk I/O required.

"nswap" : int

Number of times the process has been swapped out entirely.

"inblock" : int

Number of block input operations.

"oublock" : int

Number of block output operations.

"msgsnd" : int

Number of IPC messsages sent.

"msgrcv" : int

Number of IPC messsages received.

"nsignals" : int

Number of signals received.

"nvcsw" : int

Number of voluntary context switches (usually to wait for some service).

"nivcsw" : int

Number of preemptions, i.e. context switches due to expired time slices, or when processes with higher priority were scheduled.

"sysc" : int

Number of system calls. [2]

"ioch" : int

Number of characters read and written. [2]

"rtime" : int

Elapsed real time (ms). [2]

"ttime" : int

Elapsed system trap (system call) time (ms). [2]

"tftime" : int

Text page fault sleep time (ms). [2]

"dftime" : int

Data page fault sleep time (ms). [2]

"kftime" : int

Kernel page fault sleep time (ms). [2]

"ltime" : int

User lock wait sleep time (ms). [2]

"slptime" : int

Other sleep time (ms). [2]

"wtime" : int

Wait CPU (latency) time (ms). [2]

"stoptime" : int

Time spent in stopped (suspended) state. [2]

"brksize" : int

Heap size. [3]

"stksize" : int

Stack size. [3]

Note

[1] Not if /proc rusage is used.

[2] Only from (Solaris?) /proc rusage.

[3] Only from /proc PRS usage.

On some systems, only utime will be filled in.

See also

gethrvtime()


Methodgetsid

intgetsid(int|voidpid)

Description

Get the process session ID for the given process. If pid is not specified, the session ID for the current process will be returned.

Note

This function is not available on all platforms.

Throws

Throws an error if the system call fails.

See also

getpid, getpgrp, setsid


Methodgettimeofday

array(int) gettimeofday()

Description

Calls gettimeofday(); the result is an array of seconds, microseconds, and possible tz_minuteswes, tz_dstttime as given by the gettimeofday(2) system call (read the man page).

See also

time(), gethrtime()


Methodgetuid

intgetuid()

Description

Get the real user ID.

See also

setuid, setgid, getgid, seteuid, geteuid, setegid, getegid


Methodhardlink

voidhardlink(stringfrom, stringto)

Description

Create a hardlink named to from the file from.

Note

This function is not available on all platforms.

See also

symlink(), clonefile(), mv(), rm()


Methodhw_random

string(8bit)hw_random(int(0..)length)

Description

Read a specified number of bytes from the hardware random generator, if available. This function will not exist if hardware random is not available. Currently only supports Intel RDRAND CPU instruction.


Methodinitgroups

voidinitgroups(stringname, intbase_gid)

Description

Initializes the supplemental group access list according to the system group database. base_gid is also added to the group access list.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

setuid(), getuid(), setgid(), getgid(), seteuid(), geteuid(), setegid(), getegid(), getgroups(), setgroups()


Methodinnetgr

boolinnetgr(stringnetgroup, string|voidmachine, string|voiduser, string|voiddomain)

Description

Searches for matching entries in the netgroup database (usually /etc/netgroup). If any of the machine, user or domain arguments are zero or missing, those fields will match any value in the selected netgroup.

Note

This function isn't available on all platforms.


Methodnanosleep

floatnanosleep(int|floatseconds)

Description

Call the system nanosleep() function.

This is not to be confused with the global function predef::sleep() that does more elaborate things and can sleep with better precision (although dependant on a normal functioning system clock).

Returns the remaining time to sleep (as the system function does).

See also

predef::sleep()sleep()usleep()

Note

May not be present; only exists if the function exists in the current system.


Methodnormalize_path

utf8_stringnormalize_path(string(8bit)path)

Description

Normalize an existing Windows file system path.

The following transformations are currently done:

  • If the path is not valid UTF-8, it will be converted into UTF-8.

  • Forward slashes ('/') are converted to backward slashes ('\').

  • Trailing slashes are removed, except a single slash after a drive letter (e.g. "C:\" is returned instead of "C:").

  • Extraneous empty extensions are removed.

  • Short filenames are expanded to their corresponding long variants.

  • Relative paths are expanded to absolute paths.

  • Current- and parent-directory path components ("." and "..") are followed, similar to combine_path.

  • Case-information in directory and file names is restored.

  • Drive letters are returned in uppercase.

  • The host and share parts of UNC paths are returned in lowercase.

Returns

A normalized absolute path without trailing slashes.

Throws errors on failure, e.g. if the file or directory doesn't exist.

Note

File fork information is currently not supported (invalid data).

Note

In Pike 7.6 and earlier, this function didn't preserve a single slash after drive letters, and it didn't convert the host and share parts of an UNC path to lowercase.

See also

combine_path(), combine_path_nt()


Methodopenlog

voidopenlog(stringident, intoptions, intfacility)

Description

Initializes the connection to syslogd.

Parameter ident.

The ident argument specifies an identifier to tag all logentries with.

Parameter options

A bitfield specifying the behaviour of the message logging. Valid options are:

LOG_PID

Log the process ID with each message.

LOG_CONS

Write messages to the console if they can't be sent to syslogd.

LOG_NDELAY

Open the connection to syslogd now and not later.

LOG_NOWAIT

Do not wait for subprocesses talking to syslogd.

Parameter facility

Specifies what subsystem you want to log as. Valid facilities are:

LOG_AUTH

Authorization subsystem

LOG_AUTHPRIV 
LOG_CRON

Crontab subsystem

LOG_DAEMON

System daemons

LOG_KERN

Kernel subsystem (NOT USABLE)

LOG_LOCAL

For local use

LOG_LOCAL1
LOG_LOCAL2
LOG_LOCAL3
LOG_LOCAL4
LOG_LOCAL5
LOG_LOCAL6
LOG_LOCAL7
LOG_LPR

Line printer spooling system

LOG_MAIL

Mail subsystem

LOG_NEWS

Network news subsystem

LOG_SYSLOG 
LOG_USER 
LOG_UUCP

UUCP subsystem

Note

Only available on systems with syslog(3).

Bugs

LOG_NOWAIT should probably always be specified.

See also

syslog, closelog


Methodrdtsc

intrdtsc()

Description

Executes the rdtsc (clock pulse counter) instruction and returns the result.


Methodreadlink

stringreadlink(stringpath)

Description

Returns what the symbolic link path points to.

Note

This function is not available on all platforms.

See also

symlink()


Methodresolvepath

stringresolvepath(stringpath)

Description

Resolve all symbolic links of a pathname.

This function resolves all symbolic links, extra ``/'' characters and references to /./ and /../ in pathname, and returns the resulting absolute path, or 0 (zero) if an error occurs.

Note

This function is not available on all platforms.

See also

readlink(), symlink()


Methodsetegid

intsetegid(integid)

Description

Set the effective group ID to egid. If egid is -1 the uid for "nobody" will be used.

Returns

Returns the current errno.

Throws

Throws an error if there is no "nobody" user when egid is -1.

Note

This function isn't available on all platforms.


Methodseteuid

intseteuid(inteuid)

Description

Set the effective user ID to euid. If euid is -1 the uid for "nobody" will be used.

Returns

Returns the current errno.

Throws

Throws an error if there is no "nobody" user when euid is -1.

Note

This function isn't available on all platforms.


Methodsetgid

intsetgid(intgid)

Description

Sets the real group ID, effective group ID and saved group ID to gid. If gid is -1 the uid for "nobody" will be used.

Throws

Throws an error if no "nobody" user when gid is -1.

Returns

Returns the current errno.

Note

This function is not available on all platforms.

See also

getuid(), setuid(), getgid(), seteuid(), geteuid(), setegid(), getegid()


Methodsetgrent

intsetgrent()

Description

Rewinds the getgrent pointer to the first entry

See also

get_all_groups()getgrent()endgrent()


Methodsetgroups

voidsetgroups(array(int) gids)

Description

Set the supplemental group access list for this process.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

initgroups(), cleargroups(), getgroups(), getgid(), getgid(), getegid(), setegid()


Methodsetitimer

floatsetitimer(inttimer, int|floatvalue)

Description

Sets the timer to the supplied value. Returns the current timer interval.

Parameter timer

One of ITIMER_REAL, ITIMER_VIRTUAL and ITIMER_PROF.


Methodsetpgrp

intsetpgrp()

Description

Make this process a process group leader.

Note

Not supported on all platforms.


Methodsetproctitle

voidsetproctitle(stringtitle, mixed ... extra)

Description

Sets the processes title.


Methodsetpwent

intsetpwent()

Description

Resets the getpwent function to the first entry in the passwd source using the systemfunction setpwent(3).

Returns

Always 0 (zero)

See also

get_all_users()getpwent()endpwent()


Methodsetresgid

intsetresgid(intrgid, integid, intsgid)

Description

Sets the real, effective and saved group ID to rgid, egid and sgid respectively.

Returns

Returns zero on success and errno on failure.


Methodsetresuid

intsetresuid(intruid, inteuid, intsuid)

Description

Sets the real, effective and saved set-user-ID to ruid, euid and suid respectively.

Returns

Returns zero on success and errno on failure.


Methodsetrlimit

boolsetrlimit(stringresource, intsoft, inthard)

Description

Sets the soft and the hard process limit on a resource.

See also

getrlimit, getrlimits


Methodsetsid

intsetsid()

Description

Set a new process session ID for the current process, and return it.

Note

This function isn't available on all platforms.

Throws

Throws an error if the system call fails.

See also

getpid, setpgrp, getsid


Methodsetuid

intsetuid(intuid)

Description

Sets the real user ID, effective user ID and saved user ID to uid.

Returns

Returns the current errno.

Note

This function isn't available on all platforms.

See also

getuid(), setgid(), getgid(), seteuid(), geteuid(), setegid(), getegid()


Methodsleep

intsleep(intseconds)

Description

Call the system sleep() function.

This is not to be confused with the global function predef::sleep() that does more elaborate things and can sleep with better precision (although dependant on a normal functioning system clock).

Note

The system's sleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.

If you don't need it to be independant of the system clock, use predef::sleep() instead.

May not be present; only exists if the function exists in the current system.

See also

predef::sleep()usleep()nanosleep()


Methodsymlink

voidsymlink(stringfrom, stringto)

Description

Create a symbolic link named to that points to from.

Note

This function is not available on all platforms.

See also

hardlink(), readlink(), clonefile(), mv(), rm()


Methodsync

voidsync()

Description

Flush operating system disk buffers to permanent storage.

Note

On some operating systems this may require administrative privileges.


Methodsyslog

voidsyslog(intpriority, stringmsg)

Description

Writes the message msg to the log with the priorities in priority.

Parameter priority

Priority is a bit vector with the wanted priorities or:ed together.

0

LOG_EMERG, system is unusable.

1

LOG_ALERT, action must be taken immediately.

2

LOG_CRIT, critical conditions.

3

LOG_ERR, error conditions.

4

LOG_WARNING, warnind conditions.

5

LOG_NOTICE, normal, but significant, condition.

6

LOG_INFO, informational message.

7

LOG_DEBUG, debug-level message.


Methodumask

intumask(void|intmask)

Description

Set the current umask to mask.

If mask is not specified the current umask will not be changed.

Returns

Returns the old umask setting.


Methoduname

mapping(string:string) uname()

Description

Get operating system information.

Returns

The resulting mapping contains the following fields:

"sysname" : string

Operating system name.

"nodename" : string

Hostname.

"release" : string

Operating system release.

"version" : string

Operating system version.

"machine" : string

Hardware architecture.

"architecture" : string

Basic instruction set architecture.

"isalist" : string

List of upported instruction set architectures. Usually space-separated.

"platform" : string

Specific model of hardware.

"hw provider" : string

Manufacturer of the hardware.

"hw serial" : string

Serial number of the hardware.

"srpc domain" : string

Secure RPC domain.

Note

This function only exists on systems that have the uname(2) or sysinfo(2) system calls.

Only the first five elements are always available.


Methodusleep

voidusleep(intusec)

Description

Call the system usleep() function.

This is not to be confused with the global function predef::sleep() that does more elaborate things and can sleep with better precision (although dependant on a normal functioning system clock).

Note

The system's usleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.

If you don't need it to be independant of the system clock, use predef::sleep() instead.

May not be present; only exists if the function exists in the current system.

See also

predef::sleep()sleep()nanosleep()


Methodutime

voidutime(stringpath, intatime, intmtime, void|intsymlink)

Description

Set the last access time and last modification time for the path path to atime and mtime repectively. They are specified as unix timestamps with 1 second resolution.

If symlink is set and path refers to a symlink, then the timestamps for the symlink are set. Symlinks are dereferenced otherwise.

Note

Throws errors on failure.

This function is not available on all platforms. On some platforms the symlink flag isn't supported. In that case, the function does nothing if path is a symlink.

See also

System.set_file_atime, System.set_file_mtime

Class System.Memory

Description

A popular demand is a class representing a raw piece of memory or a mmap'ed file. This is usually not the most effective way of solving a problem, but it might help in rare situations.

Using mmap can lead to segmentation faults in some cases. Beware, and read about mmap before you try anything. Don't blame Pike if you shoot your foot off.


Method_sizeof

intsizeof(System.Memoryarg)

Description

returns the size of the memory (bytes). note: throws if not allocated


Method`[]

int res = System.Memory()[ pos ]
string res = System.Memory()[ pos1 ]


Method`[]=

System.Memory()[ pos ] = char


Methodallocate

voidallocate(intbytes)
voidallocate(intbytes, int(8bit)fill)


Methodcast

(string)System.Memory()
(array)System.Memory()

Description

Cast to string or array.

Note

Throws if not allocated.


Methodcreate

System.MemorySystem.Memory()
System.MemorySystem.Memory(string|Stdio.Filefilename_to_mmap)
System.MemorySystem.Memory(intshmkey, intshmsize, intshmflg)
System.MemorySystem.Memory(intbytes_to_allocate)

Description

Will call mmap() or allocate() depending on argument, either mmap'ing a file (in shared mode, writeable if possible) or allocating a chunk of memory.


Methodfree

voidfree()

Description

Free the allocated or <tt>mmap</tt>ed memory.


Methodmmap
Methodmmap_private

intmmap(string|Stdio.Filefile)
intmmap(string|Stdio.Filefile, intoffset, intsize)
intmmap_private(string|Stdio.Filefile)
intmmap_private(string|Stdio.Filefile, intoffset, intsize)

Description

mmap a file. This will always try to mmap the file in PROT_READ|PROT_WRITE, readable and writable, but if it fails it will try once more in PROT_READ only.


Methodpread
Methodpread16
Methodpread32
Methodpread16i
Methodpread32i
Methodpread16n
Methodpread32n

string(8bit)pread(int(0..)pos, int(0..)len)
string(16bit)pread16(int(0..)pos, int(0..)len)
stringpread32(int(0..)pos, int(0..)len)
string(16bit)pread16i(int(0..)pos, int(0..)len)
stringpread32i(int(0..)pos, int(0..)len)
string(16bit)pread16n(int(0..)pos, int(0..)len)
stringpread32n(int(0..)pos, int(0..)len)

Description

Read a string from the memory. The 16 and 32 variants reads widestrings, 16 or 32 bits (2 or 4 bytes) wide, the i variants in intel byteorder, the normal in network byteorder, and the n variants in native byteorder.

len is the number of characters, wide or not. pos is the byte position (!).


Methodpwrite
Methodpwrite16
Methodpwrite32
Methodpwrite16i
Methodpwrite32i

intpwrite(int(0..)pos, stringdata)
intpwrite16(int(0..)pos, stringdata)
intpwrite32(int(0..)pos, stringdata)
intpwrite16i(int(0..)pos, stringdata)
intpwrite32i(int(0..)pos, stringdata)

Description

Write a string to the memory (and to the file, if it's mmap()ed). The 16 and 32 variants writes widestrings, 16 or 32 bits (2 or 4 bytes) wide, the 'i' variants in intel byteorder, the other in network byteorder.

returns the number of bytes (not characters) written


Methodvalid

boolvalid()

Description

returns 1 if the memory is valid, 0 if not allocated


Methodwriteable

boolwriteable()

Description

returns 1 if the memory is writeable, 0 if not

Class System.SID

Description

Security Identifier.

Objects of this class are returned by LookupAccountName().

See also

LookupAccountName()


Method`==

bool res = System.SID() == x


Methodaccount

array(string|int) account(string|voidsys)

Returns

Returns an array with the following content:

Array
string0

Account name.

string1

Domain name.

int(0..)2

Account type.

Returns an array with three zeroes on failure.

Note

This function is only available on some Win32 systems.

Class System.SecurityContext


Methodcreate

System.SecurityContextSystem.SecurityContext(stringpkgName)


Methodgen_context

array(string|int) gen_context(string)


Methodget_last_context

array(string|int) get_last_context()


Methodget_last_error

intget_last_error()


Methodget_username

stringget_username()


Methodis_done

intis_done()


Methodtype

stringtype()

Class System.TM

Description

A wrapper for the system struct tm time keeping structure. This can be used as a (very) lightweight alternative to Calendar.


Variablegmtoff

int System.TM.gmtoff

Description

The offset from GMT for the time in this tm-struct


Variablesec
Variablemin
Variablehour
Variablemday
Variablemon
Variableyear

int(0..60) System.TM.sec
int(0..59) System.TM.min
int(0..59) System.TM.hour
int(1..31) System.TM.mday
int(0..11) System.TM.mon
int System.TM.year

Description

The various fields in the structure. Note that setting these might cause other fields to be recalculated, as an example, adding 1000 to the hour field would advance the 'mday', 'mon' and possibly 'year' fields.

When read the fields are always normalized.

Unlike the system struct tm the 'year' field is not year-1900, instead it is the actual year.


Variableisdst

int System.TM.isdst

Description

True if daylight-saving is in effect. If this field is -1 (the default) it (and the timezone info) will be updated automatically using the timezone rules.


Variablewday

int System.TM.wday

Description

The day of the week, sunday is 0, saturday is 6. This is calculated from the other fields and can not be changed directly.


Variableyday

int System.TM.yday

Description

The day of the year, from 0 (the first day) to 365 This is calculated from the other fields and can not be changed directly.


Variablezone

string|zero System.TM.zone

Description

The timezone of this structure


Methodasctime

stringasctime()

Description

Return a string representing the time. Mostly useful for debug purposes.

Note

In versions of Pike prior to Pike 8.0.1866 the exact format was very locale (see Gettext.setlocale) and OS dependent.


Methodcast

(int)System.TM()
(string)System.TM()

Description

Casted to an integer unix_time will be returned.

Casting to a string will call asctime.


Methodcreate

System.TMSystem.TM()

Description

Construct a new TM, all fields will be set to 0.


Methodcreate

System.TMSystem.TM(int|Gmp.mpzt)

Description

Create a new TM initialized from a unix time_t. The timezone will always be UTC when using this function.


Methodcreate

System.TMSystem.TM(intyear, int(0..11)mon, int(1..31)mday, int(0..24)hour, int(0..59)min, int(0..59)sec, string|voidtimezone)

Description

Construct a new time using the given values. Slightly faster than setting them individually.


Methodgmtime

boolgmtime(inttime)

Description

Initialize the struct tm to the UTC time for the specified unix time_t.


Methodgmtime

boolgmtime(Gmp.mpztime)

Description

Initialize the struct tm to the UTC time for the specified unix time_t.


Methodlocaltime

boollocaltime(inttime)

Description

Initialize the struct tm to the local time for the specified unix time_t.


Methodstrftime

string(1..255)strftime(string(1..255)format)

Description

Format the timestamp into a string.

See predef::strftime() for details.

See also

strptime(), predef::strftime(), predef::strptime(), Gettext.setlocale()


Methodstrptime

boolstrptime(string(1..255)format, string(1..255)data)

Note

The order of format and data are reversed compared to predef::strptime().

See also

strftime(), predef::strftime(), predef::strptime()


Methodunix_time

intunix_time()

Description

Return the unix time corresponding to this time_t. If no time can be parsed from the structure -1 is returned.

Class System.Time

Description

The current time as a structure containing a sec and a usec member.


Variablesec
Variableusec

int System.Time.sec
int System.Time.usec

Description

The number of seconds and microseconds since the epoch and the last whole second, respectively. (See also predef::time())

Note

Please note that these variables will continually update when they are requested, there is no need to create new Time() objects.


Variableusec_full

int System.Time.usec_full

Description

The number of microseconds since the epoch. Please note that pike needs to have been compiled with bignum support for this variable to contain sensible values.


Methodcreate

System.TimeSystem.Time(intfast)

Description

If fast is true, do not request a new time from the system, instead use the global current time variable.

This will only work in callbacks, but can save significant amounts of CPU.

Class System.Timer


Methodcreate

System.TimerSystem.Timer(int|voidfast)

Description

Create a new timer object. The timer keeps track of relative time with sub-second precision.

If fast is specified, the timer will not do system calls to get the current time but instead use the one maintained by pike. This will result in faster but more or less inexact timekeeping. The pike maintained time is only updated when a Pike.Backend object stops waiting and starts executing code.


Methodget

floatget()

Description

Return the time in seconds since the last time get was called. The first time this method is called the time since the object was created is returned instead.


Methodpeek

floatpeek()

Description

Return the time in seconds since the last time get was called.

Module System.FSEvents


Inherit_FSEvents

inherit System._FSEvents : _FSEvents

Description

The System.FSEvents module provides an interface to FSEvents. FSEvents is an API in Mac OS X which allows an application to register for notifications of changes to a given directory tree without forcing the application to continously poll the directory tree.

This module is designed for use in asynchronous, or backend mode. That is, rather than polling for changes, a function you specify will be called when events of interest occur.

Note

This module requires the presence and use of a CFRunLoop based Backend object, otherwise this module will not receive events from the OS. CFRunLoop based backends are avilable on Mac OS X 10.5 and higher.

See also

Pike.PollDeviceBackend.enable_core_foundation


ConstantkFSEventStreamCreateFlagFileEvents

constant System.FSEvents.kFSEventStreamCreateFlagFileEvents

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamCreateFlagIgnoreSelf

constant System.FSEvents.kFSEventStreamCreateFlagIgnoreSelf

Description

Available in MacOS X 10.6 and newer.


ConstantkFSEventStreamCreateFlagNoDefer

constant System.FSEvents.kFSEventStreamCreateFlagNoDefer


ConstantkFSEventStreamCreateFlagNone

constant System.FSEvents.kFSEventStreamCreateFlagNone


ConstantkFSEventStreamCreateFlagWatchRoot

constant System.FSEvents.kFSEventStreamCreateFlagWatchRoot


ConstantkFSEventStreamEventFlagChangeOwner

constant System.FSEvents.kFSEventStreamEventFlagChangeOwner

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagEventIdsWrapped

constant System.FSEvents.kFSEventStreamEventFlagEventIdsWrapped


ConstantkFSEventStreamEventFlagFinderInfoMod

constant System.FSEvents.kFSEventStreamEventFlagFinderInfoMod

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagHistoryDone

constant System.FSEvents.kFSEventStreamEventFlagHistoryDone


ConstantkFSEventStreamEventFlagInodeMetaMod

constant System.FSEvents.kFSEventStreamEventFlagInodeMetaMod

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagIsDir

constant System.FSEvents.kFSEventStreamEventFlagIsDir

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagIsFile

constant System.FSEvents.kFSEventStreamEventFlagIsFile

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagIsSymlink

constant System.FSEvents.kFSEventStreamEventFlagIsSymlink

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagItemCreated

constant System.FSEvents.kFSEventStreamEventFlagItemCreated

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagItemModified

constant System.FSEvents.kFSEventStreamEventFlagItemModified

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagItemRemoved

constant System.FSEvents.kFSEventStreamEventFlagItemRemoved

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagKernelDropped

constant System.FSEvents.kFSEventStreamEventFlagKernelDropped


ConstantkFSEventStreamEventFlagMount

constant System.FSEvents.kFSEventStreamEventFlagMount


ConstantkFSEventStreamEventFlagMustScanSubDirs

constant System.FSEvents.kFSEventStreamEventFlagMustScanSubDirs


ConstantkFSEventStreamEventFlagNone

constant System.FSEvents.kFSEventStreamEventFlagNone


ConstantkFSEventStreamEventFlagRenamed

constant System.FSEvents.kFSEventStreamEventFlagRenamed

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventFlagRootChanged

constant System.FSEvents.kFSEventStreamEventFlagRootChanged


ConstantkFSEventStreamEventFlagUnmount

constant System.FSEvents.kFSEventStreamEventFlagUnmount


ConstantkFSEventStreamEventFlagUserDropped

constant System.FSEvents.kFSEventStreamEventFlagUserDropped


ConstantkFSEventStreamEventFlagXattrMod

constant System.FSEvents.kFSEventStreamEventFlagXattrMod

Description

Available in MacOS X 10.7 and newer.


ConstantkFSEventStreamEventIdSinceNow

constant System.FSEvents.kFSEventStreamEventIdSinceNow


Methoddescribe_event_flag

stringdescribe_event_flag(intmask)

Description

describe the event flags associated with an event.

Returns

a string describing the flags set.

Class System.FSEvents.BlockingEventStream

Description

A variation of EventStream that provides a blocking interface.

Note

A quirk of the underlying IO subsystem in CoreFoundation is that there is exactly one runloop per thread. Because FSEvents uses CoreFoundation, this means that there's no meaningful way to specify which backend should process these events. Therefore, always make sure that the thread you create the EventStream object is the same one you read events from, otherwise read_event will run not run the EventLoop that this EventStream is registered with, resulting in events never being delivered.


InheritEventStream

inherit .EventStream : EventStream


Methodcreate

System.FSEvents.BlockingEventStreamSystem.FSEvents.BlockingEventStream(array(string) paths, floatlatency, int|voidsince_when, int|voidflags)


Methodread_event

mixedread_event(void|floattimeout)

Description

wait for an event to be received, and return it.

Parameter timeout

an optional limit to the amount of time we're willing to wait

Class System.FSEvents.EventStream


Methodadd_path

voidadd_path(stringpath)

Description

Add a path to the monitor list.

Parameter path
Note

this can only be called when the monitor is stopped.


Methodcreate

System.FSEvents.EventStreamSystem.FSEvents.EventStream(array(string) paths, floatlatency, int|voidsince_when, int|voidflags)

Description

Creates a new Public.System.FSEvents.EventStream object

Parameter paths

An array with each element containing a path to a directory, signifying the root of a filesystem hierarchy to be watched for modifications.

Additional paths may be added later using add_path(), though only if the stream is stopped.

Parameter latency

The number of seconds the service should wait after hearing about an event from the kernel before passing it along to the client via its callback. Specifying a larger value may result in more effective temporal coalescing, resulting in fewer callbacks and greater overall efficiency.

Parameter since_when

The service will supply events that have happened after the given event ID. To ask for events "since now" pass the constant kFSEventStreamEventIdSinceNow. Do not pass zero for this value unless you want to receive events for the requested directories "since the beginning of time".

Parameter flags

Flags that modify the behavior of the stream being created. See Apple's FSEvents documentation for details of the various flags available.


Methodflush_async

voidflush_async()

Description

Requests that the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created.

This flushing occurs asynchronously -- events most likely will not have been delivered by the time this call returns.

Note

Only call this function after the stream has been started, via start().


Methodflush_sync

voidflush_sync()

Description

Requests that the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created.

Flushing synchronously when using this method; clients will have received all the callbacks by the time this call returns to them.

Note

Only call this function after the stream has been started, via start().


Methodis_started

intis_started()

Description

Has start() been called?


Methodset_callback

voidset_callback(function(:void) callback)

Description

Sets the function that will be called when a file notification event is received.

The method signature for the callback is:

void event_callback(string path, int flags, int event_id)


Methodstart

voidstart()

Description

Requests that new events be delivered to this EventStream.

If a value was supplied for the since_when parameter then "historical" events will be sent via your callback first, then a HistoryDone event, then "contemporary" events will be sent on an ongoing basis.


Methodstop

voidstop()

Description

Stops watching for new events.

Module System.Inotify

Description

This module implements an API to linux inotify. It is available on all kernels from version 2.6.13 onwards. Inotify offers fast and scalable file notifications.


ConstantIN_ACCESS
ConstantIN_ATTRIB
ConstantIN_CLOSE
ConstantIN_CLOSE_WRITE
ConstantIN_CLOSE_NOWRITE
ConstantIN_CREATE
ConstantIN_DELETE
ConstantIN_DELETE_SELF
ConstantIN_MODIFY
ConstantIN_MOVE_SELF
ConstantIN_MOVED_FROM
ConstantIN_MOVED_TO
ConstantIN_OPEN
ConstantIN_MOVE
ConstantIN_DONT_FOLLOW
ConstantIN_MASK_ADD
ConstantIN_ONESHOT
ConstantIN_ONLYDIR
ConstantIN_IGNORED
ConstantIN_ISDIR
ConstantIN_Q_OVERFLOW
ConstantIN_UNMOUNT

constant System.Inotify.IN_ACCESS
constant System.Inotify.IN_ATTRIB
constant System.Inotify.IN_CLOSE
constant System.Inotify.IN_CLOSE_WRITE
constant System.Inotify.IN_CLOSE_NOWRITE
constant System.Inotify.IN_CREATE
constant System.Inotify.IN_DELETE
constant System.Inotify.IN_DELETE_SELF
constant System.Inotify.IN_MODIFY
constant System.Inotify.IN_MOVE_SELF
constant System.Inotify.IN_MOVED_FROM
constant System.Inotify.IN_MOVED_TO
constant System.Inotify.IN_OPEN
constant System.Inotify.IN_MOVE
constant System.Inotify.IN_CLOSE
constant System.Inotify.IN_DONT_FOLLOW
constant System.Inotify.IN_MASK_ADD
constant System.Inotify.IN_ONESHOT
constant System.Inotify.IN_ONLYDIR
constant System.Inotify.IN_IGNORED
constant System.Inotify.IN_ISDIR
constant System.Inotify.IN_Q_OVERFLOW
constant System.Inotify.IN_UNMOUNT

Description

Please have a look at the inotify(7) manpage for information about these constants.

Note

Some constants may not be available when the module has been compiled on a machine with linux kernel before 2.6.15. See the manpage for more details.


ConstantIN_ALL_EVENTS

constant System.Inotify.IN_ALL_EVENTS

Description

This is a derived constant that is not part of the standard inotify API. It is the union of all other constants.


Methoddescribe_mask

stringdescribe_mask(intmask)

Description

Turn an event mask into a human readable representation. This is used for debugging purpose.


Methodparse_event

array(string|int) parse_event(stringdata)

Description

Parses one inotify_event struct from data.

Returns

Returns an array consisting of

Array
int0

The watch descriptor returned by _Instance()->add_watch() when the watch for this file was added.

int1

An integer that describes the event that occured. See the inotify manpage for a list of possible events and their numerical identifiers.

int2

An integer cookie that can be used to group together different events that were triggered by moving a file from one location to another.

string3

The name of the file. This will only be present if the event happened to a file in a directory that was watched, e.g. with System.Inotify.IN_CREATE. Otherwise this will be 0.

int4

The length of the data that has been parsed. If the data string contains more than one inotify event, this parse function needs to be called again with the remainder as an argument.

Class System.Inotify.Instance

Description

More convenient interface to inotify(7). Automatically reads events from the inotify file descriptor and parses them.

Note

Objects of this class will be destructed when they go out of external references. As such they behave differently from other classes which use callbacks, e.g. Stdio.File.

Note

The number of inotify instances is limited by ulimits.


Inherit_Instance

inherit _Instance : _Instance


Methodadd_watch

intadd_watch(stringfilename, intmask, function(int, int, string, mixed ... :void) callback, mixed ... extra)

Description

Add a watch for a certain file and a set of events specified by mask. The function callback will be called when such an event occurs. The arguments to the callback will be the events mask, the cookie, the filename and extra.

Returns

Returns a watch descriptor which can be used to remove the watch.

Note

When adding a second watch for the same file the old one will be removed unless System.Inotify.IN_MASK_ADD is contained in mask.

Note

The mask of an event may be a subset of the mask given when adding the watch.

Note

In case the watch is added for a regular file, the filename will be passed to the callback. In case the watch is added for a directory, the name of the file to which the event happened inside the directory will be concatenated.

Class System.Inotify._Instance

Description

Simple wrapper class that gives direct access to the inotify(7) interface. On create an inotify instance is initiated by calling inotify_init(2). Every object of this class has its own inotify file descriptor. Use this class only if you want direct access to the file descriptor to read from it manually. For a more user friendly interface use System.Inotify.Instance.

See also

System.Inotify.Instance


Variableevent_callback

privatefunction(int, int, int, string:void) System.Inotify._Instance.event_callback

Description

Callback function that is called when an event is triggered.

See also

set_event_callback(), query_event_callback()


Methodadd_watch

intadd_watch(stringpath, intmask)

Description

Add a watch for a certain file or directory and specific events.

Adding more than one watch for a path will overwrite the previous watch unless System.Inotify.IN_MASK_ADD is contained in the mask.

Parameter path

Path of the file or directory.

Parameter mask

Integer mask specifying the event type. This can be a combination of different event types using bitwise OR. See the inotify manpage for possible values and their description. The values defined by the inotify header file are exported by System.Inotify as constants using the same names (e.g. System.Inotify.IN_CREATE).

Returns

Returns a watch descriptor on success, and -1 on filesystem-related failures, in which case errno() will indicate the cause. These typically indicate time of check, time of use race conditions. For other failures errors are thrown.

Note

Subdirectories are not watched. If you want to watch subdirectories as well, you need to add watches for them individually.

Note

At creation of a watch for a directory, simulated IN_CREATE-events with cookie 0x7fffffff will be added for the initial contents of the directory. This is to reduce the risk of losing state changes due to races. Note that is is not known whether these paths are in flux or not. Note also that there may be multiple notifications for content that is created at the moment the watch is created.

Note

In old versions of Pike errors were thrown for all failures.

See also

rm_watch(), parse_event()


Methodget_event_callback

function(int, int, int, string:void) get_event_callback()

Description

Get the current event_callback.

See also

set_event_callback(), event_callback, poll()


Methodpoll

voidpoll()

Description

Check for any pending events.

Any pending events will be read and parsed, and event_callback will be called once for each event. The arguments to the event_callback will be:

Array
int1

The watch descriptor that was triggered.

int2

The event that was triggerend (one of IN_*).

int3

An integer cookie used to identify grouped events.

string4

The name of the path segment (if any).

Note

This function is called by the backend when there are events pending.

See also

set_event_callback()


Methodquery_fd

intquery_fd()

Returns

Returns the file descriptor associated with this inotify instance.


Methodrm_watch

intrm_watch(intwd)

Description

Remove a watch.

Parameter wd

The watch descriptor that was returned by add_watch().


Methodset_backend

voidset_backend(Pike.Backendbackend)

Description

Set the backend used for callbacks.

See also

set_event_callback(), set_nonblocking(), poll()


Methodset_blocking

voidset_blocking()

Description

Disable backend callback mode.

The configured backend will stop calling poll(), so poll() will need to be called by hand.

See also

set_blocking(), poll()


Methodset_event_callback

voidset_event_callback(function(int, int, int, string:void) cb)

Description

Set the event_callback.

See also

get_event_callback(), event_callback, poll()


Methodset_nonblocking

voidset_nonblocking()

Description

Enable backend callback mode.

The configured backend will call poll() automatically as soon as there are events pending.

See also

set_blocking(), poll()

Module System.Wnotify

Description

An interface to Windows filesystem change information.


ConstantFILE_NOTIFY_CHANGE_ATTRIBUTES

constant System.Wnotify.FILE_NOTIFY_CHANGE_ATTRIBUTES


ConstantFILE_NOTIFY_CHANGE_DIR_NAME

constant System.Wnotify.FILE_NOTIFY_CHANGE_DIR_NAME


ConstantFILE_NOTIFY_CHANGE_FILE_NAME

constant System.Wnotify.FILE_NOTIFY_CHANGE_FILE_NAME


ConstantFILE_NOTIFY_CHANGE_LAST_WRITE

constant System.Wnotify.FILE_NOTIFY_CHANGE_LAST_WRITE


ConstantFILE_NOTIFY_CHANGE_SECURITY

constant System.Wnotify.FILE_NOTIFY_CHANGE_SECURITY


ConstantFILE_NOTIFY_CHANGE_SIZE

constant System.Wnotify.FILE_NOTIFY_CHANGE_SIZE

Class System.Wnotify.EventPoller


Methodadd_handle

voidadd_handle(NotificationHandlehandle)


Methodpoll

NotificationHandle|intpoll(void|floattimeout)

Class System.Wnotify.NotificationHandle


Methodcreate

System.Wnotify.NotificationHandleSystem.Wnotify.NotificationHandle(stringpath, intwatch_subtree, intfilter)


Methodget_error

intget_error()

Module Tools

Class Tools.PV

Description

Display a image on the screen. Requires GTK.


InheritWindow

inherit GTK.Window : Window


TypedefPVImage

typedefStandards.URI|string|Image.Image|Image.Layer|array(Image.Layer) Tools.PV.PVImage

Description

The image types accepted. If the image is a string, it is assumed to be a filename of a image that can be loaded with Image.load. This includes URLs.


Methodget_as_image

Image.Imageget_as_image(PVImagei)

Description

Return the current image as a Image object, with the alpha combining done.


Methodsave

voidsave(stringfilename, string|voidformat)

Description

Write the image to a file. If no format is specified, PNG is used. The alpha combination is done on the image before it's saved.


Methodscale

voidscale(floatfactor)

Description

Scale the image before display with the specified factor.


Methodset_alpha_colors

voidset_alpha_colors(Image.Color.Colorc1, Image.Color.Color|voidc2)

Description

Set the colors used for the alpha combination. c2 is only used for the Squares alpha mode.

See also

set_alpha_mode()


Methodset_alpha_mode

voidset_alpha_mode(AlphaModem)

Description

Set the alpha combining mode. m is one of Squares, Solid, None and AlphaOnly.


Methodset_image

voidset_image(PVImagei)

Description

Change the image.

Enum Tools.PV.AlphaMode

Description

The alpha combination modes.

Use set_alpha_mode() to change the mode.


ConstantAlphaOnly

constant Tools.PV.AlphaOnly

Description

Only show the alpha channel (if any).


ConstantNone

constant Tools.PV.None

Description

Ignore alpha.


ConstantSolid

constant Tools.PV.Solid

Description

Solid color.


ConstantSquares

constant Tools.PV.Squares

Description

Checkerboard pattern (default).

Module Tools.AutoDoc

Enum Tools.AutoDoc.Flags

Description

Flags affecting autodoc extractor behaviour.

See also

ProcessXML.extractXML(), MirarDocParser, Tools.Standalone.extract_autodoc()


ConstantFLAG_COMPAT

constant Tools.AutoDoc.FLAG_COMPAT

Description

Attempt to be compatible with old Pike.


ConstantFLAG_DEBUG

constant Tools.AutoDoc.FLAG_DEBUG

Description

Full verbosity.


ConstantFLAG_KEEP_GOING

constant Tools.AutoDoc.FLAG_KEEP_GOING

Description

Attempt to keep going after errors.


ConstantFLAG_NORMAL

constant Tools.AutoDoc.FLAG_NORMAL

Description

Normal verbosity.


ConstantFLAG_NO_DYNAMIC

constant Tools.AutoDoc.FLAG_NO_DYNAMIC

Description

Reduce the amount of dynamic information in the generated files (line numbers, extractor version, extraction time, etc).


ConstantFLAG_QUIET

constant Tools.AutoDoc.FLAG_QUIET

Description

Keep quiet about non-fatal errors.


ConstantFLAG_VERBOSE

constant Tools.AutoDoc.FLAG_VERBOSE

Description

Extra verbosity.


ConstantFLAG_VERB_MASK

constant Tools.AutoDoc.FLAG_VERB_MASK

Description

Verbosity mask.

Class Tools.AutoDoc.AutoDocError

Description

Base class for errors generated by the autodoc extraction system.


Variablemessage

string Tools.AutoDoc.AutoDocError.message

Description

Error message.


Variablepart

string Tools.AutoDoc.AutoDocError.part

Description

Which part of the autodoc system.


Variableposition

SourcePosition Tools.AutoDoc.AutoDocError.position


Method__create__

protectedlocalvoid__create__(SourcePositionposition, stringpart, stringmessage)


Methodcreate

Tools.AutoDoc.AutoDocErrorTools.AutoDoc.AutoDocError(SourcePositionposition, stringpart, stringmessage)

Class Tools.AutoDoc.BMMLParser


Inheritis_example

inherit Regexp.SimpleRegexp : is_example


Inheritlastident

protected inherit Regexp.SimpleRegexp : lastident


Inheritmegamagic

protected inherit Regexp.SimpleRegexp : megamagic


Methodmagic

stringmagic(strings, intquote)

Description

Convert a block of tab-indented text to a set of paragraphs.

Class Tools.AutoDoc.PikeParser

Description

A very special purpose Pike parser that can parse some selected elements of the Pike language...


InheritPikeObjects

protected inherit .PikeObjects : PikeObjects


ConstantEOF

constantstring Tools.AutoDoc.PikeParser.EOF

Description

The end of file marker.


ConstantWITH_NL

constantint Tools.AutoDoc.PikeParser.WITH_NL

Description

Newline indicator flag value.


VariablecurrentPosition

SourcePosition Tools.AutoDoc.PikeParser.currentPosition

Description

The current position in the source.


Methodcreate

Tools.AutoDoc.PikeParserTools.AutoDoc.PikeParser(string|voids, string|SourcePosition|void_filename, int|voidline, .Flags|voidflags)


Methodeat

stringeat(multiset(string)|stringtoken)

Description

Consume one token, error if not (one of) the expected in token.


MethodeatIdentifier

stringeatIdentifier(void|intallowScopePrefix)

Description

Expect an identifier.

Note

Also ::ident, scope::ident.

Note

This function also converts old-style getters and setters into new-style.


MethodeatLiteral

stringeatLiteral()

Description

Expect a literal constant.

See also

parseLiteral()


MethodgetReadDocComments

intgetReadDocComments()

Returns

Returns the number of documentation comments that have been returned by readToken().


MethodliteralType

Type|zeroliteralType(stringliteral)

Description

Returns the type of a literal. Currently only recognizes the top level type. Currently does not thoroughly check that the literal is syntactically valid.


MethodlookAhead

stringlookAhead(intoffset, int|voidwith_newlines)

Description

Peek offset tokens ahead, skipping newlines, unless with_newlines is set.

See also

peekToken()


MethodparseAnnotation

Annotation|zeroparseAnnotation()

Description

Parse a single annotation from the token stream.


MethodparseAnnotations

array(Annotation) parseAnnotations()

Description

Parse a set of annotations from the token stream.


MethodparseArgList

arrayparseArgList(int|voidallowLiterals)

Description

Parse the list of arguments in a function declaration.

Parameter allowLiterals

If allowLiterals != 0 then you can write a literal or Pike idents as an argument, like:

void convert("jpeg",Image image,float quality)

For a literal arg, the argname[] string contains the literal and the corresponding argtypes element is 0

Note

Expects that the arglist is followed by a ")".


MethodparseArray

ArrayTypeparseArray()

Description

Parse an array type.


MethodparseDecl

PikeObject|array(PikeObject)|AnnotationparseDecl(mapping|voidargs)

Description

Parse the next Pike declaration from the token stream.

Note

parseDecl() reads ONLY THE HEAD, NOT the ";" or "{" .. "}" !!!


MethodparseFunction

FunctionTypeparseFunction()

Description

Parse a function type.


MethodparseIdents

string|voidparseIdents()

Description

Parse a '.'-separated identitifer string.

Note

Also parses stuff preceded by "scope::" or "::"


MethodparseInt

IntTypeparseInt()

Description

Parse an integer type.


MethodparseLiteral

string|zeroparseLiteral()

Description

Parse the next literal constant (if any) from the token stream.


MethodparseMapping

MappingTypeparseMapping()

Description

Parse a mapping type.


MethodparseModifiers

array(string) parseModifiers()

Description

Parse a set of modifiers from the token stream.


MethodparseMultiset

MultisetTypeparseMultiset()

Description

Parse a multiset type.


MethodparseOrType

TypeparseOrType()

Description

Parse a union type.


MethodparseString

StringTypeparseString()

Description

Parse a string type.


MethodpeekToken

stringpeekToken(int|voidwith_newlines)

Description

Peek at the next token in the stream without advancing.

Parameter with_newlines

If set will return "\n" tokens, these will otherwise silently be skipped.

Returns

Returns the next token.

See also

readToken(), lookAhead()


MethodreadToken

stringreadToken(int|voidwith_newlines)

Description

Read the next token from the stream and advance.

Parameter with_newlines

If set will return "\n" tokens, these will otherwise silently be skipped.

Returns

Returns the next token.

See also

peekToken()


MethodsetTokens

voidsetTokens(array(string) t, array(int) p)


Methodskip

voidskip(multiset(string)|stringtokens)

Description

Skip the next token if it is a member of the tokens set.

Note

The newline token ("\n") is not skipped implicitly by this function.

See also

readToken(), peekToken(), eat(), skipUntil()


MethodskipBlock

array(string) skipBlock()

Description

Skip passed a matched pair of parenthesis, brackets or braces.


MethodskipNewlines

voidskipNewlines()

Description

Skip past any newlines.


MethodskipUntil

array(string) skipUntil(multiset(string)|stringtokens)

Description

Skip tokens until one of tokens is the next to read.

Note

The newline token ("\n") is not skipped implicitly by this function.

See also

skip()


Methodtokenize

array(array(string)|array(int)) tokenize(strings, intline)

Description

Tokenize a string of Pike code.

Class Tools.AutoDoc.SourcePosition

Description

Class used to keep track of where in the source a piece of documentation originated.


Variablefilename

string Tools.AutoDoc.SourcePosition.filename


Variablefirstline
Variablelastline

int Tools.AutoDoc.SourcePosition.firstline
int Tools.AutoDoc.SourcePosition.lastline

Description

Range of lines.


Methodcopy

SourcePositioncopy()

Returns

Returns a copy of the current object.


Methodcreate

Tools.AutoDoc.SourcePositionTools.AutoDoc.SourcePosition(stringfilename, intfirstline, int|voidlastline)


Methodxml

stringxml(Flags|voidflags)

Returns

Returns a string with an XML-fragment describing the source position.

Module Tools.AutoDoc.DocParser


InheritPikeObjects

inherit .PikeObjects : PikeObjects


ConstantEOF

constant Tools.AutoDoc.DocParser.EOF

Description

End of file marker.


Variablekeywordtype

mapping(string:DocTokenType) Tools.AutoDoc.DocParser.keywordtype

Description

The DocTokenTypes for the documentation @-keywords.


MethodsplitDocBlock

array(array(Token)) splitDocBlock(stringblock, SourcePositionposition)

Description

Split a block of documentation text into segments of Tokens split on METAKEYWORDs.

Returns

Each of the arrays in the returned array can be fed to Parse::create()

Enum Tools.AutoDoc.DocParser.DocTokenType

Description

Enum of documentation token types.


ConstantBRACEKEYWORD

constant Tools.AutoDoc.DocParser.BRACEKEYWORD

Description

eg @i{@}


ConstantCONTAINERKEYWORD

constant Tools.AutoDoc.DocParser.CONTAINERKEYWORD

Description

eg @mapping


ConstantDELIMITERKEYWORD

constant Tools.AutoDoc.DocParser.DELIMITERKEYWORD

Description

eg @param


ConstantENDKEYWORD

constant Tools.AutoDoc.DocParser.ENDKEYWORD

Description

eg @endmapping


ConstantENDTOKEN

constant Tools.AutoDoc.DocParser.ENDTOKEN

Description

End of documentation marker.


ConstantERRORKEYWORD

constant Tools.AutoDoc.DocParser.ERRORKEYWORD

Description

eg @invalid


ConstantMETAKEYWORD

constant Tools.AutoDoc.DocParser.METAKEYWORD

Description

eg @decl


ConstantSINGLEKEYWORD

constant Tools.AutoDoc.DocParser.SINGLEKEYWORD

Description

None existant.


ConstantTEXTTOKEN

constant Tools.AutoDoc.DocParser.TEXTTOKEN

Description

Documentation text.

Class Tools.AutoDoc.DocParser.DocParserClass

Description

Internal class for parsing documentation markup.


VariableargHandlers

mapping(string:function(string, string:string)|function(string, string:mapping(string:string))) Tools.AutoDoc.DocParser.DocParserClass.argHandlers

Description

Contains functions that handle keywords with non-standard arg list syntax. The function for each keyword can return a mapping or a string:

mapping(string:string)

If a mapping(string:string) is returned, it is interpreted as the attributes to put in the tag.

string

If a string is returned, it is an XML fragment that gets inserted inside the tag.


VariablecurrentPosition

SourcePosition Tools.AutoDoc.DocParser.DocParserClass.currentPosition


MethodgetDoc

stringgetDoc(stringcontext)

Returns

Returns the documentation corresponding to the context as an XML string.

Note

getMetaData() must be called before this function.


MethodgetMetaData

MetaDatagetMetaData()

Returns

Returns the MetaData for the documentation string.

Class Tools.AutoDoc.DocParser.MetaData

Description

Metadata about a Documentation object.


Variablebelongs
Variableappears

string Tools.AutoDoc.DocParser.MetaData.belongs
string Tools.AutoDoc.DocParser.MetaData.appears

Description

Relocation information.


Variabledecls

array(PikeObject) Tools.AutoDoc.DocParser.MetaData.decls

Description

Set of declarations.


Variableinherits

array(PikeObject) Tools.AutoDoc.DocParser.MetaData.inherits

Description

Set of inherits.


Variablename

string Tools.AutoDoc.DocParser.MetaData.name

Description

If type is one of "class", "module", "endmodule", or "endclass".


Variabletype

string Tools.AutoDoc.DocParser.MetaData.type

Description

Type of documented entity.

Class Tools.AutoDoc.DocParser.Parse

Description

Documentation markup parser.

This is a class, because you need to examine the meta lines before you can determine which context to parse the actual doc lines in.


InheritDocParserClass

inherit DocParserClass : DocParserClass


Methodcreate

Tools.AutoDoc.DocParser.ParseTools.AutoDoc.DocParser.Parse(string|array(Token) s, SourcePosition|voidsp, .Flags|voidflags)

Description

Parse a documentation string s.


Methoddoc

string|zerodoc(stringcontext)

Returns

Returns the documentation corresponding to the context as an XML string.

Note

metadata() must be called before this function.


Methodmetadata

MetaDatametadata()

Returns

Returns the MetaData for the documentation string.

Class Tools.AutoDoc.DocParser.Token


Variabletype
Variablekeyword
Variablearg
Variabletext
Variableposition

int Tools.AutoDoc.DocParser.Token.type
string|zero Tools.AutoDoc.DocParser.Token.keyword
string|zero Tools.AutoDoc.DocParser.Token.arg
string|zero Tools.AutoDoc.DocParser.Token.text
SourcePosition|zero Tools.AutoDoc.DocParser.Token.position


Method__create__

protectedlocalvoid__create__(inttype, string|zerokeyword, string|zeroarg, string|zerotext, SourcePosition|zeroposition)


Methodcreate

Tools.AutoDoc.DocParser.TokenTools.AutoDoc.DocParser.Token(inttype, string|zerokeyword, string|zeroarg, string|zerotext, SourcePosition|zeroposition)

Module Tools.AutoDoc.PikeExtractor


InheritDocParser

protected inherit .DocParser : DocParser


MethodextractClass

voidextractClass(AutoDocroot, Moduleparent, strings, void|stringfilename, void|stringclassName, void|.Flagsflags)

Description

Extract documentation for a Pike class (aka program).

See also

extractNamespace(), extractModule()


MethodextractModule

voidextractModule(AutoDocroot, Moduleparent, strings, void|stringfilename, void|stringmoduleName, void|.Flagsflags)

Description

Extract documentation for a Pike module.

See also

extractNamespace(), extractClass()


MethodextractNamespace

voidextractNamespace(AutoDocroot, strings, void|stringfilename, void|stringnamespaceName, void|.Flagsflags)

Description

Extract documentation for a Pike namespace.

See also

extractModule(), extractClass()

Module Tools.AutoDoc.PikeObjects

Description

This module contains classes to represent Pike objects such as classes, modules, methods, variables ... The classes can produce XML representations of themselves.


Inherit"module.pmod"

protected inherit "module.pmod" : "module.pmod"


InheritTree

protected inherit Parser.XML.Tree : Tree


VariableEmptyDoc

protectedDocumentation Tools.AutoDoc.PikeObjects.EmptyDoc

Description

The empty Documentation.

Class Tools.AutoDoc.PikeObjects.Annotation

Description

Class representing an annotation.

Class Tools.AutoDoc.PikeObjects.ArrayType

Description

The class for representing array types.

See also

Type


InheritType

inherit Type : Type


Variablelength

Type Tools.AutoDoc.PikeObjects.ArrayType.length

Description

The length of the array.


Variablevaluetype

Type Tools.AutoDoc.PikeObjects.ArrayType.valuetype

Description

The Type of the array elements.


Methodcreate

Tools.AutoDoc.PikeObjects.ArrayTypeTools.AutoDoc.PikeObjects.ArrayType()

Class Tools.AutoDoc.PikeObjects.AttributeType

Description

The class for representing attributed types.

See also

Type


InheritType

inherit Type : Type


Variableattribute

string Tools.AutoDoc.PikeObjects.AttributeType.attribute

Description

The name of the attribute.


Variableprefix

int Tools.AutoDoc.PikeObjects.AttributeType.prefix

Description

Flag indicating:

0

The attribute is on the type.

1

The attribute is a prefix and acts as a modifier. This is only used for functions.


Variablesubtype

Type Tools.AutoDoc.PikeObjects.AttributeType.subtype

Description

The type that is attributed.


Methodcreate

Tools.AutoDoc.PikeObjects.AttributeTypeTools.AutoDoc.PikeObjects.AttributeType()

Class Tools.AutoDoc.PikeObjects.AutoDoc

Description

The top-level container. This container should only contain namespaces, and they in turn contain modules etc.


Inherit_Class_or_Module

inherit _Class_or_Module : _Class_or_Module


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.AutoDoc.objtype

Class Tools.AutoDoc.PikeObjects.Class

Description

Represents a class.


Inherit_Class_or_Module

inherit _Class_or_Module : _Class_or_Module


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Class.objtype

Class Tools.AutoDoc.PikeObjects.Constant

Description

Represents a named constant.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Constant.objtype


Variabletype

Type Tools.AutoDoc.PikeObjects.Constant.type

Description

The type of the constant, if known.


VariabletypedefType

Type Tools.AutoDoc.PikeObjects.Constant.typedefType

Description

Typedef Type if it is a typedef.

Class Tools.AutoDoc.PikeObjects.CppDirective

Description

Representation of an inherit.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.CppDirective.objtype

Class Tools.AutoDoc.PikeObjects.DocGroup

Description

A class associating a piece of Documentation with a set of PikeObjects.


Variableappears
Variablebelongs

string Tools.AutoDoc.PikeObjects.DocGroup.appears
string Tools.AutoDoc.PikeObjects.DocGroup.belongs

Description

Relocation information.


Variabledocumentation

Documentation Tools.AutoDoc.PikeObjects.DocGroup.documentation

Description

The Documentation for the objects.


Variableobjects

array(PikeObject) Tools.AutoDoc.PikeObjects.DocGroup.objects

Description

The set of PikeObjects that are documented.


Methodcreate

Tools.AutoDoc.PikeObjects.DocGroupTools.AutoDoc.PikeObjects.DocGroup(array(PikeObject) objs, Documentation|voiddoc)


Methodxml

stringxml(.Flags|voidflags)

Returns

Returns a string with an XML representation of the documentation.

Class Tools.AutoDoc.PikeObjects.Documentation

Description

The base class for documentation strings.

See also

DocGroup


Variabletext
Variablexml
Variableposition

string|void Tools.AutoDoc.PikeObjects.Documentation.text
string|void Tools.AutoDoc.PikeObjects.Documentation.xml
SourcePosition|void Tools.AutoDoc.PikeObjects.Documentation.position


Method__create__

protectedlocalvoid__create__(string|voidtext, string|voidxml, SourcePosition|voidposition)


Methodcreate

Tools.AutoDoc.PikeObjects.DocumentationTools.AutoDoc.PikeObjects.Documentation(string|voidtext, string|voidxml, SourcePosition|voidposition)

Class Tools.AutoDoc.PikeObjects.Enum

Description

The enum container.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Enum.objtype


Variablechildren

array(DocGroup) Tools.AutoDoc.PikeObjects.Enum.children

Description

The set of children.


Variabledocumentation

Documentation Tools.AutoDoc.PikeObjects.Enum.documentation

Description

Mimic the class { ... } behaviour.


MethodaddChild

voidaddChild(DocGroupc)

Description

Adds c to the set of children.


MethodaddGroup

voidaddGroup(DocGroupc)

Description

Adds c to the set of children.


MethodcontainsDoc

intcontainsDoc()

Returns

Returns 1 if there is any documentation at all for this entity.

Class Tools.AutoDoc.PikeObjects.EnumConstant

Description

The values inside enum Foo { ... }

These are currently handled identically to normal constants.


InheritConstant

inherit Constant : Constant

Class Tools.AutoDoc.PikeObjects.FloatType

Description

The class for representing the float type.

See also

Type


InheritType

inherit Type : Type


Methodcreate

Tools.AutoDoc.PikeObjects.FloatTypeTools.AutoDoc.PikeObjects.FloatType()

Class Tools.AutoDoc.PikeObjects.FunctionType

Description

The class for representing function types.

See also

Type


InheritType

inherit Type : Type


Variableargtypes

array(Type) Tools.AutoDoc.PikeObjects.FunctionType.argtypes

Description

An array with types for the arguments to the function.


Variablereturntype

Type Tools.AutoDoc.PikeObjects.FunctionType.returntype

Description

The type for the return value of the function.


Methodcreate

Tools.AutoDoc.PikeObjects.FunctionTypeTools.AutoDoc.PikeObjects.FunctionType()

Class Tools.AutoDoc.PikeObjects.Generic

Description

Represents a generic.


InheritTypedef

inherit Typedef : Typedef


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Generic.objtype


Variabledefault_type

Type Tools.AutoDoc.PikeObjects.Generic.default_type

Description

Default Type.


Variablegeneric_argument_number

int Tools.AutoDoc.PikeObjects.Generic.generic_argument_number

Class Tools.AutoDoc.PikeObjects.Import

Description

Representation of an import.


InheritInherit

inherit Inherit : Inherit


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Import.objtype

Class Tools.AutoDoc.PikeObjects.Inherit

Description

Representation of an inherit.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Inherit.objtype


Variablebindings

array(Type) Tools.AutoDoc.PikeObjects.Inherit.bindings

Description

Bindings (if any).


Variableclassname

string Tools.AutoDoc.PikeObjects.Inherit.classname

Description

Name of the class that is inherited.

Class Tools.AutoDoc.PikeObjects.IntType

Description

The class for representing integer types.

See also

Type


InheritType

inherit Type : Type


Variablemin
Variablemax

string Tools.AutoDoc.PikeObjects.IntType.min
string Tools.AutoDoc.PikeObjects.IntType.max

Description

The minimum and maximum range limits for the integer type.


Methodcreate

Tools.AutoDoc.PikeObjects.IntTypeTools.AutoDoc.PikeObjects.IntType()

Class Tools.AutoDoc.PikeObjects.MappingType

Description

The class for representing mapping types.

See also

Type


InheritType

inherit Type : Type


Variableindextype
Variablevaluetype

Type Tools.AutoDoc.PikeObjects.MappingType.indextype
Type Tools.AutoDoc.PikeObjects.MappingType.valuetype

Description

The types for the indices and values of the mapping.


Methodcreate

Tools.AutoDoc.PikeObjects.MappingTypeTools.AutoDoc.PikeObjects.MappingType()

Class Tools.AutoDoc.PikeObjects.Method

Description

Represents a function.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Method.objtype


Variableargnames

array(string) Tools.AutoDoc.PikeObjects.Method.argnames

Description

The names of the arguments.


Variableargtypes

array(Type) Tools.AutoDoc.PikeObjects.Method.argtypes

Description

The types for the arguments.


Variablereturntype

Type Tools.AutoDoc.PikeObjects.Method.returntype

Description

The return type for the function.

Class Tools.AutoDoc.PikeObjects.MixedType

Description

The class for representing the mixed type.

See also

Type


InheritType

inherit Type : Type


Methodcreate

Tools.AutoDoc.PikeObjects.MixedTypeTools.AutoDoc.PikeObjects.MixedType()

Class Tools.AutoDoc.PikeObjects.Modifier

Description

A modifier range, e.g.:

finalprotected{
  ...
  <<declarations>>
  ...
}

Inherit_Class_or_Module

inherit _Class_or_Module : _Class_or_Module


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Modifier.objtype

Class Tools.AutoDoc.PikeObjects.Module

Description

Represents a module.


Inherit_Class_or_Module

inherit _Class_or_Module : _Class_or_Module


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Module.objtype

Class Tools.AutoDoc.PikeObjects.MultisetType

Description

The class for representing multiset types.

See also

Type


InheritType

inherit Type : Type


Variableindextype

Type Tools.AutoDoc.PikeObjects.MultisetType.indextype

Description

The type for the indices of the multiset.


Methodcreate

Tools.AutoDoc.PikeObjects.MultisetTypeTools.AutoDoc.PikeObjects.MultisetType()

Class Tools.AutoDoc.PikeObjects.NameSpace

Description

Represents a name space, eg: predef:: or lfun::.


Inherit_Class_or_Module

inherit _Class_or_Module : _Class_or_Module


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.NameSpace.objtype

Class Tools.AutoDoc.PikeObjects.ObjectType

Description

The class for representing object types.

See also

Type


InheritType

inherit Type : Type


Variableclassname

string Tools.AutoDoc.PikeObjects.ObjectType.classname

Description

The name of the class for the object.


Methodcreate

Tools.AutoDoc.PikeObjects.ObjectTypeTools.AutoDoc.PikeObjects.ObjectType()

Class Tools.AutoDoc.PikeObjects.OrType

Description

The class for representing union types.

See also

Type


InheritType

inherit Type : Type


Variabletypes

array(Type) Tools.AutoDoc.PikeObjects.OrType.types

Description

An array with the types that are member of the union.


Methodcreate

Tools.AutoDoc.PikeObjects.OrTypeTools.AutoDoc.PikeObjects.OrType()

Class Tools.AutoDoc.PikeObjects.PikeObject

Description

Base class for representing a documentable Pike lexical entity.

This class is inherited by classes for representing classes, functions, variables, etc.

See also

Inherit, Import, Class, Module, NameSpace, AutoDoc, Modifier, Method, Constant, Typedef, EnumConstant, Enum, Variable


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.PikeObject.objtype

Description

The object type identifier.


Variableappears
Variablebelongs

string Tools.AutoDoc.PikeObjects.PikeObject.appears
string Tools.AutoDoc.PikeObjects.PikeObject.belongs

Description

Relocation information.


Variablemodifiers

array(string) Tools.AutoDoc.PikeObjects.PikeObject.modifiers

Description

The set of modifiers affecting this entity.


Variablename

string Tools.AutoDoc.PikeObjects.PikeObject.name

Description

The name of the entity.


Variableposition

SourcePosition Tools.AutoDoc.PikeObjects.PikeObject.position

Description

The source position where the entity was found.


VariablesqueezedInDoc

Documentation Tools.AutoDoc.PikeObjects.PikeObject.squeezedInDoc


Methodprint

stringprint()

Returns

Returns a string with a Pike syntax representation of the entity.


Methodxml

stringxml(.Flags|voidflags)

Returns

Returns a string with an XML representation of the entity.

Class Tools.AutoDoc.PikeObjects.ProgramType

Description

The class for representing program (aka class) types.

See also

Type


InheritType

inherit Type : Type


Variableclassname

string Tools.AutoDoc.PikeObjects.ProgramType.classname

Description

The name of the class (if any).


Methodcreate

Tools.AutoDoc.PikeObjects.ProgramTypeTools.AutoDoc.PikeObjects.ProgramType()

Class Tools.AutoDoc.PikeObjects.StringType

Description

The class for representing string types.

See also

Type


InheritType

inherit Type : Type


Variablemax

string Tools.AutoDoc.PikeObjects.StringType.max

Description

The maximum value for characters in the string.


Variablemin

string Tools.AutoDoc.PikeObjects.StringType.min

Description

The minimum value for characters in the string.


Methodcreate

Tools.AutoDoc.PikeObjects.StringTypeTools.AutoDoc.PikeObjects.StringType()

Class Tools.AutoDoc.PikeObjects.Type

Description

The base class for representing types.


Variablename

string Tools.AutoDoc.PikeObjects.Type.name


Method__create__

protectedlocalvoid__create__(stringname)


Methodcreate

Tools.AutoDoc.PikeObjects.TypeTools.AutoDoc.PikeObjects.Type(stringname)


Methodprint

stringprint()

Returns

Returns a string with a Pike-syntax representation of the type.


Methodxml

stringxml(.Flags|voidflags)

Returns

Returns a string with an XML representation of the type.

Class Tools.AutoDoc.PikeObjects.TypeType

Description

The class for representing type types.

See also

Type


InheritType

inherit Type : Type


Variablesubtype

Type Tools.AutoDoc.PikeObjects.TypeType.subtype

Description

The subtype of the type.


Methodcreate

Tools.AutoDoc.PikeObjects.TypeTypeTools.AutoDoc.PikeObjects.TypeType()

Class Tools.AutoDoc.PikeObjects.Typedef

Description

Represents a typedef.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Typedef.objtype


Variabletype

Type Tools.AutoDoc.PikeObjects.Typedef.type

Description

Typedef Type.

Class Tools.AutoDoc.PikeObjects.UnknownType

Description

The class for representing the unknown type.

See also

Type


InheritType

inherit Type : Type


Methodcreate

Tools.AutoDoc.PikeObjects.UnknownTypeTools.AutoDoc.PikeObjects.UnknownType()

Class Tools.AutoDoc.PikeObjects.VarargsType

Description

The class for representing varargs types.

See also

Type


InheritType

inherit Type : Type


Variabletype

Type Tools.AutoDoc.PikeObjects.VarargsType.type

Description

The type that is varargs.


Methodcreate

Tools.AutoDoc.PikeObjects.VarargsTypeTools.AutoDoc.PikeObjects.VarargsType(Typet)

Class Tools.AutoDoc.PikeObjects.Variable

Annotations
@Pike.Annotations.Implements(PikeObject)
Description

Represents a variable.


InheritPikeObject

inherit PikeObject : PikeObject


Constantobjtype

constantstring Tools.AutoDoc.PikeObjects.Variable.objtype


Variabletype

Type Tools.AutoDoc.PikeObjects.Variable.type

Description

Type of the variable.

Class Tools.AutoDoc.PikeObjects.VoidType

Description

The class for representing the void type.

See also

Type


InheritType

inherit Type : Type


Methodcreate

Tools.AutoDoc.PikeObjects.VoidTypeTools.AutoDoc.PikeObjects.VoidType()

Class Tools.AutoDoc.PikeObjects.ZeroType

Description

The class for representing the zero type.

See also

Type


InheritType

inherit Type : Type


Methodcreate

Tools.AutoDoc.PikeObjects.ZeroTypeTools.AutoDoc.PikeObjects.ZeroType()

Class Tools.AutoDoc.PikeObjects._Class_or_Module

Description

Base class for representing classes, modules and namespaces.

See also

Class, Module, NameSpace, AutoDoc, Modifier


InheritPikeObject

inherit PikeObject : PikeObject


Variablechildren

array(_Class_or_Module) Tools.AutoDoc.PikeObjects._Class_or_Module.children

Description

Entities that are children to this entity.


VariabledocGroups

array(DocGroup) Tools.AutoDoc.PikeObjects._Class_or_Module.docGroups

Description

Documented entities that are children to this entity.


Variabledocumentation

Documentation Tools.AutoDoc.PikeObjects._Class_or_Module.documentation

Note

The documentation appears as a child of the <class> or <module>


Variablegenerics

array(array(string|PikeObject)) Tools.AutoDoc.PikeObjects._Class_or_Module.generics

Description

Array of symbol followed by type and default type triples.


Variableinherits

array(Inherit|Import) Tools.AutoDoc.PikeObjects._Class_or_Module.inherits

Description

Inherits and Imports that affect the symbol lookup for the entity.


MethodaddChild

voidaddChild(_Class_or_Modulec)

Description

Adds c to the set of children.


MethodaddGroup

voidaddGroup(DocGroupd)

Description

Adds d to the set of docGroups.


MethodaddInherit

voidaddInherit(PikeObjectp)

Description

Adds p to the set of inherits.


MethodcontainsDoc

intcontainsDoc()

Returns

Returns 1 if there is any documentation at all for this entity.


MethodfindChild

PikeObject|zerofindChild(stringname)

Returns

Returns the first child with the name name if any.


MethodfindObject

DocGroup|zerofindObject(stringname)

Returns

Returns the first DocGroup that documents an entity with the name name if any.

Module Tools.AutoDoc.ProcessXML


Inherit"module.pmod"

protected inherit "module.pmod" : "module.pmod"


InheritTree

protected inherit Parser.XML.Tree : Tree


MethodextractXML

stringextractXML(stringfilename, int|voidpikeMode, string|voidtype, string|voidname, array(string)|voidparentModules, void|.Flagsflags)

Description

This function extracts documentation from a file. The parameters type, name, and parentModules are used only when pikeMode != 0 and no C-style doc comments are present.

Parameter filename

The file to extract from.

Parameter pikeMode

Non-zero if it is a Pike file. If the file contains style doc comments, C-mode is used despite pikeMode != 0.

Parameter type

"class", "module" or "namespace".

Parameter name

The name of the class/module/namespace.

Parameter parentModules

The ancestors of the class/module/namespace.

Parameter flags

Flags adjusting the extractor behaviour. Defaults to FLAG_NORMAL.

Example

// To extract doc for Foo.Bar.Ippa: string xml = extractXML("lib/modules/Foo.pmod/Bar.pmod/Ippa.pike", 1, "class", "Ippa", ({ "Foo", "Bar" }));


MethodhandleAppears

voidhandleAppears(SimpleNoderoot, .Flags|voidflags)

Description

Take care of all the @appears and @belongs directives everywhere, and rearranges the nodes in the tree accordingly

Parameter root

The root (<autodoc>) node of the documentation tree.


MethodmergeTrees

voidmergeTrees(SimpleNodedest, SimpleNodesource)

Description

Puts all children of source into the tree dest, in their correct place module-hierarchically.

Used to merge the results of extractions of different Pike and C files.

Some minor effort is expended to normalize the result to some sort of canonical order.

Parameter source
Parameter dest

The nodes source and dest are <class>, <module>, <namespace> or <autodoc> nodes that are identical in the sense that they represent the same module, class or namespace. Typically they both represent <autodoc> nodes.

Note

Both source and dest are modified destructively.

Note

After calling this method, any <class> or <module> nodes that have been marked with @appears or @belongs, are still in the wrong place in the tree, so handleAppears() (or postProcess()) must be called on the whole documentation tree to relocate them once the tree has been fully merged.


MethodmoveImages

stringmoveImages(stringdocXMLFile, stringimageSourceDir, stringimageDestDir, int|voidquiet)

Description

Copy all images to canonical files in a flat directory.

Parameter docXMLFile

The contents of the XML file. The XML file is the result of extraction from a single C or Pike file, for example the result of calling extractXML.

Parameter imageSourceDir

The directory that is the base of the relative paths to images. This should be the directory of the source file that was the input to extract the XML file.

Parameter imageDestDir

The directory where the images should be copied.

Parameter quiet

Quiet operation.

Returns

The XML file contents (with decorated <image>-tags)


MethodpostProcess

voidpostProcess(SimpleNoderoot, string|voidlogfile, .Flags|voidflags)

Description

Perform the last steps on a completed documentation tree.

Parameter root

Root <autodoc> node of the completed documentation tree.

Calls handleAppears(), cleanUndocumented() and resolveRefs() in turn.

See also

handleAppears(), cleanUndocumented(), resolveRefs()

Class Tools.AutoDoc.ProcessXML.DummyNScope


Variablename

string Tools.AutoDoc.ProcessXML.DummyNScope.name


Method__create__

protectedlocalvoid__create__(stringname)


Methodcreate

Tools.AutoDoc.ProcessXML.DummyNScopeTools.AutoDoc.ProcessXML.DummyNScope(stringname)

Class Tools.AutoDoc.ProcessXML.NScope

Description

A symbol lookup scope.


MethodaddImplicitInherits

voidaddImplicitInherits(string|voidfallback_namespace)

Description

This function improves the symbol resolution by adding implicit inherits for modules in compatibility namespaces.

Class Tools.AutoDoc.ProcessXML.ReOrganizeTask


Variablen
Variableparent

SimpleNode Tools.AutoDoc.ProcessXML.ReOrganizeTask.n
SimpleNode Tools.AutoDoc.ProcessXML.ReOrganizeTask.parent


Method__create__

protectedlocalvoid__create__(SimpleNoden, SimpleNodeparent)


Methodcreate

Tools.AutoDoc.ProcessXML.ReOrganizeTaskTools.AutoDoc.ProcessXML.ReOrganizeTask(SimpleNoden, SimpleNodeparent)

Class Tools.AutoDoc.ProcessXML.Scope


Variabletype
Variablename

string|void Tools.AutoDoc.ProcessXML.Scope.type
string|void Tools.AutoDoc.ProcessXML.Scope.name


Method__create__

protectedlocalvoid__create__(string|voidtype, string|voidname)


Methodcreate

Tools.AutoDoc.ProcessXML.ScopeTools.AutoDoc.ProcessXML.Scope(string|voidtype, string|voidname)

Module Tools.Hilfe


Methodformat_hr_time

stringformat_hr_time(inti)

Description

Helper function that formats a time span in nanoseconds to something more human readable (ns, ms or s).

Class Tools.Hilfe.Command

Description

Abstract class for Hilfe commands.


Methoddoc

stringdoc(stringwhat, stringwith)

Description

A more elaborate documentation of the command. This should be less than 68 characters per line.


Methodexec

voidexec(Evaluatore, stringline, array(string) words, array(string) tokens)

Description

The actual command callback. Messages to the user should be written out by using the safe_write method in the Evaluator object.


Methodhelp

stringhelp(string|zerowhat)

Description

Returns a one line description of the command. This help should be shorter than 54 characters.

Class Tools.Hilfe.CommandReset

Description

Variable reset command. Put ___Hilfe->commands->reset = Tools.Hilfe.CommandReset(); in your .hilferc to have this command defined when you open Hilfe.


InheritCommand

inherit Command : Command

Class Tools.Hilfe.CommandSet


InheritCommand

inherit Command : Command

Class Tools.Hilfe.CommandSet.Intwriter


Variabletype
Variablefallback

string Tools.Hilfe.CommandSet.Intwriter.type
function(:void) Tools.Hilfe.CommandSet.Intwriter.fallback


Method__create__

protectedlocalvoid__create__(stringtype, function(:void) fallback)


Methodcreate

Tools.Hilfe.CommandSet.IntwriterTools.Hilfe.CommandSet.Intwriter(stringtype, function(:void) fallback)

Class Tools.Hilfe.CommandSet.Reswriter


Variableformat

string Tools.Hilfe.CommandSet.Reswriter.format


Method__create__

protectedlocalvoid__create__(stringformat)


Methodcreate

Tools.Hilfe.CommandSet.ReswriterTools.Hilfe.CommandSet.Reswriter(stringformat)

Class Tools.Hilfe.Evaluator

Description

This class implements the actual Hilfe interpreter. It is accessible as ___Hilfe from Hilfe expressions.


Variableassembler_debug_level

int Tools.Hilfe.Evaluator.assembler_debug_level

Description

The current assembler debug level. Only available if Pike is compiled with RTL debug.


Variablecommands

mapping(string:Command) Tools.Hilfe.Evaluator.commands

Description

This mapping contains the available Hilfe commands, including the built in ones (dump, exit, help, new, quit), so it is possible to replace or remove them. The name of a command should be 10 characters or less.


Variablecompiler_trace_level

int Tools.Hilfe.Evaluator.compiler_trace_level

Description

The current compiler trace level. Only available if Pike is compiled with RTL debug.


Variableconstants

mapping(string:mixed) Tools.Hilfe.Evaluator.constants

Description

The locally defined constants (name:value).


Variabledebug_level

int Tools.Hilfe.Evaluator.debug_level

Description

The current debug level. Only available if Pike is compiled with RTL debug.


Variablefunctions

mapping(string:function(:void)) Tools.Hilfe.Evaluator.functions

Description

The locally defined functions (name:value).


Variablehistory

HilfeHistory Tools.Hilfe.Evaluator.history

Description

The current result history.


Variableimports

array(string) Tools.Hilfe.Evaluator.imports

Description

The current imports.


Variableinherits

array(string) Tools.Hilfe.Evaluator.inherits

Description

The current inherits.


Variablelast_compile_time

int(0..) Tools.Hilfe.Evaluator.last_compile_time

Description

The last compile time;


Variablelast_compiled_expr

string Tools.Hilfe.Evaluator.last_compiled_expr

Description

The last created wrapper in which an expression was evaluated.


Variablelast_else

bool Tools.Hilfe.Evaluator.last_else

Description

Should an else expression be carried out?


Variablelast_eval_time

int(0..) Tools.Hilfe.Evaluator.last_eval_time

Description

The last evaluation time;


Variableprograms

mapping(string:program) Tools.Hilfe.Evaluator.programs

Description

The locally defined programs (name:value).


Variablereswrite

function(:void) Tools.Hilfe.Evaluator.reswrite

Description

The function used to write results. Gets as arguments in order: The safe_write function (function(string, mixed ...:int), the result as a string (string), the history entry number (int), the result (mixed), the compilation time (int) and the evaluation time (int). If the evaluated expression didn't return anything (e.g. a for loop) then 0 will be given as the result string.


Variablestate

ParserState Tools.Hilfe.Evaluator.state

Description

Keeps the state, e.g. multiline input in process etc.


Variablestrict_types

bool Tools.Hilfe.Evaluator.strict_types

Description

Strict types?


Variabletrace_level

int Tools.Hilfe.Evaluator.trace_level

Description

The current trace level.


Variabletypes

mapping(string:string) Tools.Hilfe.Evaluator.types

Description

The types of the locally defined variables (name:type).


Variablevariables

mapping(string:mixed) Tools.Hilfe.Evaluator.variables

Description

The locally defined variables (name:value).


Variablewarnings

bool Tools.Hilfe.Evaluator.warnings

Description

Show warnings?


Variablewrite

array|object|function(string:int(0..)) Tools.Hilfe.Evaluator.write

Description

The function to use when writing to the user.


Methodadd_buffer

voidadd_buffer(strings)

Description

Add buffer tokenizes the input string and determines if the new line is a Hilfe command. If not, it updates the current state with the new tokens and sends any and all complete expressions to evaluation in parse_expression.


Methodadd_input_hook

voidadd_input_hook(function(:void)|objectnew)

Description

Adds a function to the input hook, making all user data be fed into the function.

See also

remove_input_hook


Methodadd_input_line

voidadd_input_line(strings)

Description

Input a line of text into Hilfe. It checks if s is ".", in which case it calls state->flush(). Otherwise just calls add_buffer.


Methodadd_writer

voidadd_writer(object|function(string:int(0..)) new)

Description

Adds another output function.


Methodevaluate

voidevaluate(stringa, boolshow_result)

Description

Compiles the Pike code a and evaluates it by calling ___HilfeWrapper in the generated object. If show_result is set the result will be displayed and the result buffer updated with its value.


Methodhilfe_compile

object|zerohilfe_compile(stringf, void|stringnew_var)

Description

Creates a wrapper and compiles the pike code f in it. If a new variable is compiled to be tested, its name should be given in new_var so that magically defined entities can be undefined and a warning printed.


Methodparse_expression

string|zeroparse_expression(Expressionexpr)

Description

Parses a Pike expression. Returns 0 if everything went well, or a string with an error message otherwise.


Methodprint_version

voidprint_version()

Description

Displays the current version of Hilfe.


Methodremove_input_hook

voidremove_input_hook(function(:void)|objectold)

Description

Removes a function from the input hook.

See also

add_input_hook


Methodremove_writer

voidremove_writer(object|function(:void) old)

Description

Removes an output function.


Methodreset_evaluator

voidreset_evaluator()

Description

Clears the current state, history and removes all locally defined variables, constants, functions and programs. Removes all imports and inherits. It does not reset the command mapping nor reevaluate the .hilferc file.


Methodsafe_write

intsafe_write(array(string)|stringin, mixed ... args)

Description

An output method that shouldn't crash.


Methodstd_reswrite

voidstd_reswrite(function(:void) w, stringsres, intnum, mixedres)

Description

The standard reswrite function.

Class Tools.Hilfe.Evaluator.HilfeCompileHandler


Variablestack_level

int Tools.Hilfe.Evaluator.HilfeCompileHandler.stack_level


Method__create__

protectedlocalvoid__create__(intstack_level)

Class Tools.Hilfe.Expression

Description

Represents a Pike expression


Method_sizeof

intsizeof(Tools.Hilfe.Expressionarg)

Description

The number of non-whitespace tokens in the expression.


Method`[]

string|zero res = Tools.Hilfe.Expression()[ f ]

Description

Returns a token or a token range without whitespaces.


Method`[]=

Tools.Hilfe.Expression()[ f ] = v

Description

Replaces a token with a new token.


Methodcast

(int)Tools.Hilfe.Expression()
(float)Tools.Hilfe.Expression()
(string)Tools.Hilfe.Expression()
(array)Tools.Hilfe.Expression()
(mapping)Tools.Hilfe.Expression()
(multiset)Tools.Hilfe.Expression()

Description

An Expression object can be cast to an array or a string. In both forms all tokens, including white spaces will be returned.


Methodcheck_modifiers

string|zerocheck_modifiers()

Description

See if there are any forbidden modifiers used in the expression, e.g. "private int x;" is not valid inside Hilfe.

Returns

Returns an error message as a string if the expression contains a forbidden modifier, otherwise 0.


Methodcode

stringcode()

Description

Returns the expression verbatim.


Methodcreate

Tools.Hilfe.ExpressionTools.Hilfe.Expression(array(string) t)

Parameter t

An array of Pike tokens.


Methoddepth

intdepth(intf)

Description

Return the parenthesis depth at the given position.


Methodendoftype

int(-1..)endoftype(int(-1..)position)

Description

Returns at which position the type declaration that begins at position position ends. A return value of -1 means that the token or tokens from position can not be a type declaration.


Methodfind_matching

int(-1..)find_matching(stringtoken, int(0..)|voidpos)

Description

Returns the position of the matching parenthesis of the given kind, starting from the given position. The position should be the position after the opening parenthesis, or later. Assuming balanced code. Returns -1 on failure.


Methodin_sscanf

boolin_sscanf(intf)

Description

Returns 1 if the current position is within a sscanf expression.


Methodis_block

boolis_block(intpos)

Description

Is there a block starting at pos?

Class Tools.Hilfe.GenericAsyncHilfe


InheritEvaluator

inherit Evaluator : Evaluator


Variableinfile
Variableoutfile

Stdio.File Tools.Hilfe.GenericAsyncHilfe.infile
Stdio.File Tools.Hilfe.GenericAsyncHilfe.outfile


Method__create__

protectedlocalvoid__create__(Stdio.Fileinfile, Stdio.Fileoutfile)

Class Tools.Hilfe.GenericHilfe


InheritEvaluator

inherit Evaluator : Evaluator


Methodcreate

Tools.Hilfe.GenericHilfeTools.Hilfe.GenericHilfe(Stdio.FILEin, Stdio.Fileout)

Class Tools.Hilfe.HilfeHistory

Description

In every Hilfe object (Evaluator) there is a HilfeHistory object that manages the result history. That history object is accessible both from __ and ___Hilfe->history in Hilfe expressions.


InheritHistory

inherit ADT.History : History

Class Tools.Hilfe.ParserState

Description

In every Hilfe object (Evaluator) there is a ParserState object that manages the current state of the parser. Essentially tokens are entered in one end and complete expressions are output in the other. The parser object is accessible as ___Hilfe->state from Hilfe expressions.


Variableevaluator

Evaluator Tools.Hilfe.ParserState.evaluator


Method__create__

protectedlocalvoid__create__(Evaluatorevaluator)


Methodcreate

Tools.Hilfe.ParserStateTools.Hilfe.ParserState(Evaluatorevaluator)


Methoddatap

intdatap()

Description

Returns true if there is any waiting expression that can be fetched with read.


Methodfeed

voidfeed(array(string) tokens)

Description

Feed more tokens into the state.


Methodfinishedp

boolfinishedp()

Description

Are we in the middle of an expression. Used e.g. for changing the Hilfe prompt when entering multiline expressions.


Methodflush

voidflush()

Description

Clear the current state.


Methodpush_string

array(string)|zeropush_string(stringline)

Description

Sends the input line to Parser.Pike for tokenization, but keeps a state between each call to handle multiline /**/ comments and multiline #"" strings.


Methodread

array(Expression) read()

Description

Read out completed expressions. Returns an array where every element is an expression represented as an array of tokens.


Methodshow_error

voidshow_error(function(array(string)|string, mixed ... :int) w)

Description

Prints out any error that might have occurred while push_string was executed. The error will be printed with the print function w.


Methodstatus

stringstatus()

Description

Returns the current parser state. Used by "dump state".

Class Tools.Hilfe.StdinHilfe

Description

This is a wrapper containing a user interface to the Hilfe Evaluator so that it can actually be used. This wrapper uses the Stdio.Readline module to interface with the user. All input history is handled by that module, and as a consequence loading and saving .hilfe_history is handled in this class. Also .hilferc is handled by this class.


InheritEvaluator

inherit Evaluator : Evaluator


Variablereadline

Stdio.Readline Tools.Hilfe.StdinHilfe.readline

Description

The readline object,


Methodcreate

Tools.Hilfe.StdinHilfeTools.Hilfe.StdinHilfe(void|array(string) init)

Description

Any hilfe statements given in the init array will be executed once .hilferc has been executed.


Methodsave_history

voidsave_history()

Description

Saves the user input history, if possible, when called.

Class Tools.Hilfe.SubSysLogger

Class Tools.Hilfe.SubSysLogger.Logger


Variablee
Variablelogfile

Evaluator Tools.Hilfe.SubSysLogger.Logger.e
Stdio.File Tools.Hilfe.SubSysLogger.Logger.logfile


Method__create__

protectedlocalvoid__create__(Evaluatore, Stdio.Filelogfile)

Module Tools.Install

Description

Common routines which are useful for various install scripts based on Pike.


Methodfeatures

array(string) features()

Description

Return an array of enabled features.

Note

Used by the master when given the option --features.

See also

Tools.Standalone.features


Methodmake_absolute_path

stringmake_absolute_path(stringpath, string|voidcwd)

Class Tools.Install.ProgressBar

Description

A class keeping some methods and state to conveniently render ASCII progress bars to stdout.


Methodcreate

Tools.Install.ProgressBarTools.Install.ProgressBar(stringname, intcur, intmax, float|voidphase_base, float|voidphase_size)

Parameter name

The name (printed in the first 13 columns of the row)

Parameter cur

How much progress has been made so far

Parameter max

The amount of progress signifying 100% done. Must be greater than zero.


Methodset_current

voidset_current(int_cur)

Description

Change the amount of progress without updating on stdout.


Methodset_name

voidset_name(string_name)

Description

Change the name of the progress bar without updating on stdout.


Methodset_phase

voidset_phase(float_phase_base, float_phase_size)


Methodupdate

intupdate(intincrement)

Description

Write the current look of the progressbar to stdout.

Parameter increment

the number of increments closer to completion since last call

Returns

the length (in characters) of the line with the progressbar

Class Tools.Install.Readline


InheritReadline

inherit Stdio.Readline : Readline


Methodabsolute_path

stringabsolute_path(stringpath)


Methodedit

stringedit(mixed ... args)


Methodedit_directory

stringedit_directory(mixed ... args)


Methodedit_filename

stringedit_filename(mixed ... args)


Methodset_cwd

voidset_cwd(string_cwd)


Methodtrap_signal

voidtrap_signal(intn)

Module Tools.Legal

Module Tools.Legal.Copyright

Description

Contains functions and information to store and present copyright information about Pike and it's components.


Methodadd

voidadd(stringwhat, array(string) holders)

Description

Adds a copyright message for the copyright holders for the component what.

Throws

An error is thrown if the copyrighted component what is already in the list of copyrights.


Methodget_all

mapping(string:array(string)) get_all()

Description

Returns a mapping containing all the stored copyrights. The mapping maps component name to an array of copyright holders.


Methodget_latest_pike

stringget_latest_pike()

Description

Return the latest copyright holder of Pike.


Methodget_text

stringget_text()

Description

Returns the copyrights as a string, suitable for saving as a file.

Module Tools.Legal.License


Methodget_text

stringget_text()

Description

Returns all the licenses as a string, suitable for saving as a file.

Module Tools.Markdown

Description

This is a small stub entrypoint to Parser.Markdown - it is exactly equivalent to calling Parser.Markdown.parse().

Module Tools.MasterHelp

Description

This module contains usage strings for the master()->_main().


Constantenvironment_help

constant Tools.MasterHelp.environment_help

Description

The set of environment variables that the default master looks at.


Constantkladdkaka_help

constant Tools.MasterHelp.kladdkaka_help

Description

Useful recipe for when all else fails.


Constantopt_summary

constant Tools.MasterHelp.opt_summary

Description

Summary of the options for the Pike interpreter binary, and the default master.


Constantoptions_help

constant Tools.MasterHelp.options_help

Description

Complete set of options for the Pike interpreter binary, and the default master.


Methoddo_help

stringdo_help(string|intwhat)

Description

Select a suitable help message.

Module Tools.Monger

Class Tools.Monger.MongerDeveloper


Methodadd_new_version

intadd_new_version(stringmodule_name, stringversion, stringchanges, stringlicense)


Methoddelete_dependency

intdelete_dependency(stringmodule_name, stringversion, stringdependency, stringmin_version, stringmax_version)


Methodget_dependencies

arrayget_dependencies(stringmodule_name, stringversion)


Methodset_auth

voidset_auth(string_username, string_password)

Description

set the username and password for accessing the remote repository.


Methodset_default_directory

voidset_default_directory()

Description

sets the default directory for working and storing configurations ($HOME/.monger)


Methodset_default_repository

voidset_default_repository()

Description

sets the default repository location (modules.gotpike.org)


Methodset_dependency

intset_dependency(stringmodule_name, stringversion, stringdependency, stringmin_version, stringmax_version, boolrequired)


Methodset_directory

voidset_directory(string_directory)

Description

sets the monger directory to use for working and storing configurations.


Methodset_module_source

intset_module_source(stringmodule_name, stringversion, stringfilename)


Methodset_repository

voidset_repository(string_repository)

Description

specify an alternate repository location.

this should be a URL specifying the XMLRPC endpoint for the repository.


Methodset_version_active

intset_version_active(stringmodule_name, stringversion, intactive)


Methodupdate_version

intupdate_version(stringmodule_name, stringversion, string|voidchanges, string|voidlicense)


Methoduser_change_email

intuser_change_email(string|void_username, string_newemail)


Methoduser_change_password

intuser_change_password(string|void_username, string_newpassword)

Class Tools.Monger.MongerDeveloper.xmlrpc_handler

Class Tools.Monger.MongerDeveloper.xmlrpc_handler._caller


Variablen

string Tools.Monger.MongerDeveloper.xmlrpc_handler._caller.n


Method__create__

protectedlocalvoid__create__(stringn)


Methodcreate

Tools.Monger.MongerDeveloper.xmlrpc_handler._callerTools.Monger.MongerDeveloper.xmlrpc_handler._caller(stringn)

Module Tools.Shoot

Class Tools.Shoot.Test


Constantname

constantstring Tools.Shoot.Test.name

Description

The name of the test.


Methodperform

intperform(mixed|voidcontext)

Description

perform() is the function called in the tests, when it returns the test is complete.

The function returns the number of whatever the test did.


Methodprepare

optionalmixedprepare()

Description

If this function exists, it computes the context to pass to the perform() function. The time consumed by this function will not count towards the test.

Module Tools.Standalone

Class Tools.Standalone.autodoc_to_html

Description

AutoDoc XML to HTML converter.

See also

tree_split


Variablelay

mapping Tools.Standalone.autodoc_to_html.lay

Description

Layout template headers and trailers.


Methodimage_prefix

stringimage_prefix()

Description

Path to where in the destination filesystem the images are.


Methodparse_text

stringparse_text(Noden, void|String.Bufferret, array(string)|voidsection_path)

Description

Typically called with a <group/> node or a sub-node that is a container.

Class Tools.Standalone.forkd

Description

Fork Daemon

This is a light-weight daemon that can be used via Process.Process to spawn new processes (by specifying the "forkd" modifier).

The typical use is when the main program is large and/or when it has lots of open file descriptors. This can cause considerable overhead in process creation.

See also

Process.RemoteProcess, Process.create_process

Class Tools.Standalone.forkd.FdStream

Description

This is the main control Stdio.Fd and is always on fd number 3.

To spawn a new process, a new Stdio.PROP_SEND_FD capable Stdio.Fd is sent over this fd, and a single byte of data is sent as payload.

The sent fd will become a ForkFd inside a ForkStream.


InheritFile

inherit Stdio.File : File

Class Tools.Standalone.forkd.ForkStream

Description

This class maps 1 to 1 to Process.RemoteProcess, and implements the daemon side of the RPC protocol.

It contains an array (fds) with the file descriptors that have been received so far from the remote.


InheritFile

inherit Stdio.File : File


Variablefds

array(Stdio.Fd) Tools.Standalone.forkd.ForkStream.fds

Description

The remote file descriptors received so far in order.

Class Tools.Standalone.git_export_autodoc

Description

Tool for converting the Pike git repository to a corresponding git repository containing the extracted autodoc.xml and documentation.

It supports incremental operation, so that it can be used to keep track with the source.

Typical use: pike -x git_export_autodoc -v --git-dir=Autodoc.git


Variableautodoc_hash

mapping(string:string) Tools.Standalone.git_export_autodoc.autodoc_hash

Description

Mapping from doc commit sha1 or export reference to sha1 for the autodoc.xml blob.


Variabledoc_refs

mapping(string:string) Tools.Standalone.git_export_autodoc.doc_refs

Description

Mapping from doc reference to doc commit sha1 or export reference.


Variabledoc_to_parents

mapping(string:array(string)) Tools.Standalone.git_export_autodoc.doc_to_parents

Description

Mapping from doc commit sha1 or export reference to array of same for its direct parents.


Variabledoc_to_src

mapping(string:array(string)) Tools.Standalone.git_export_autodoc.doc_to_src

Description

Mapping from doc commit sha1 or export reference to the corresponding list of source commit sha1s.


Variablerefdoc_hash

mapping(string:string) Tools.Standalone.git_export_autodoc.refdoc_hash

Description

Mapping from source commit to refdoc sha1.


Variablerev_refs

mapping(string:multiset(string)) Tools.Standalone.git_export_autodoc.rev_refs

Description

Lookup from source commit sha1 to the corresponding references (if any).


Variablesrc_refs

mapping(string:string) Tools.Standalone.git_export_autodoc.src_refs

Description

Mapping from source reference to source commit sha1.


Variablesrc_to_doc

mapping(string:string) Tools.Standalone.git_export_autodoc.src_to_doc

Description

Mapping from source commit sha1 to doc commit sha1 or export reference.


Methodget_version

stringget_version()

Description

Attempt to get the version for the Pike source tree.

Class Tools.Standalone.pike_to_html

Description

Convert Pike code to HTML with syntax highlighting

pike -x pike_to_html /path/to/file.pike > file.html

Methodconvert

stringconvert(stringcode)

Description

Turn code into HTML.

The following css classes will be used:

  • Delimiters: delim

  • Reserved words: lang

  • Data types: type

  • Constants: const

  • Modifiers: mods

  • Root namespaces: ns

  • Strings: string

  • Comments: comment

  • Macros: macro

Parameter code

Class Tools.Standalone.pmar_install

Description

a prototype installer for prepackaged modules

note: portions of this code are highly inefficient (wrt tar filehandling). we assume that this will be used infrequently enough that this is not going to be a problem.

a package file is a tar file that contains the following structure:

ROOTDIR/ METADATA.TXT a file containing metadata about the package format: KEY=value, where values include: PLATFORM, in the form of os/processor (either can be "any") MODULE, the name of the module, in Module.Submodule format. VERSION, the version of this module. MODULE/ any files that need to be installed in the module directory MODREF/ ??? documentation suitable for inclusion in the modref INCLUDE/ ??? any pike language include files to be installed SCRIPTS/ standalone (no bundled dependencies) scripts used to perform custom actions they receive the installer object (this) and the System.Filesystem object of the package archive as arguments to the constructor. The method "run()" should perform the actual action. The run() method should return true or false to indicate success or failure. preinstall.pike postinstall.pike

Class Tools.Standalone.precompile

Description

Convert .cmod-files to .c files.

Class Tools.Standalone.precompile.ArgCheckFunction


Variabletokens

array Tools.Standalone.precompile.ArgCheckFunction.tokens


Method__create__

protectedlocalvoid__create__(arraytokens)


Methodcreate

Tools.Standalone.precompile.ArgCheckFunctionTools.Standalone.precompile.ArgCheckFunction(arraytokens)

Class Tools.Standalone.process_files

Description

Boilerplate to quickly whip up rsif-like hacks for creating file processing to churn away at stdin, or files and/or directories provided on the command line, recursively or not, creating backup files or not, listing the paths of all files action was taken for, and returning an exit status of how many files that would have been taken action on which could not be written back.

The all-round quickest way of making one of these tools is nicking the top portion of lib/modules/Tools.pmod/Standalone.pmod/process_files.pike or copying rsif.pike from the same directory. (The latter is 20 lines long, including docs, or about four lines of code.) Inherit process_files, and define your own version, description, usage, process, and, if you want arguments, want_args.


Inheritprocess_files

inherit Toole.Standalone.process_files : process_files


Variabledefault_flag_docs

string Tools.Standalone.process_files.default_flag_docs

Description

Flag docs to append to your usage description. Explains default options.


Variabledescription

string Tools.Standalone.process_files.description

Description

One-liner that gets shown for this tool when running pike -x without additional options. (Assuming your tool resides in Standalone.pmod.) Does not include the name of the tool itself; just provide a nice, terse description, ending with a period for conformity.


Variableoverwrite

bool Tools.Standalone.process_files.overwrite

Description

0 to make backups, 1 to overwrite (default)


Variablerecursive

bool Tools.Standalone.process_files.recursive

Description

1 to recurse into directories, 0 not to (default)


Variableusage

string Tools.Standalone.process_files.usage

Description

Long description of the purpose and usage of your tool, for --help and the case where not enough options are given on the command line. Its invocation mode (for instance "pike -x yourtool", when invoked that way) is prepended, and a list of available flags appended to this description.


Variableverbosity

int(0..) Tools.Standalone.process_files.verbosity

Description

0 in quiet mode, 1 by default, above = more output


Variableversion

string Tools.Standalone.process_files.version

Description

Your hack's version number. If you version control your file with cvs, we suggest you set the contents of this variable to something that that will automatically expand to a number for every new revision, for instance

Example

string version = sprintf("%d.%d.%d",(int)__REAL_VERSION__,__REAL_MINOR__,__REAL_BUILD__);


Variablewant_args

int Tools.Standalone.process_files.want_args

Description

The number of (mandatory) command-line options your hack needs and which your process callback wants (beside the input file). By default 0.


Methodmain

int(0..)main(intargc, array(string) argv)

Description

Base implementation of main program, handling basic flags and returning an exit status matching the number of failures during operation.

FIXME

No easy way of adding your own command-line flags implemented yet. This would be a rather natural next feature to add, once somebody needs some.


Methodprocess

stringprocess(stringinput, string ... args)

Description

Gets called with the contents of a file (or stdin). Return your output, or 0 if you didn't do anything. args are the first want_args command-line options provided, before the list of files to process.


Methodprocess_file

boolprocess_file(stringpath, string ... args)

Description

Takes the path to a file and the first want_args command-line options provided, before the list of files to process. You might want to override this method if your tool needs to see file paths.

See also

process_path


Methodprocess_path

int(0..)process_path(stringpath, string ... args)

Description

Takes the path to a file or directory and the first want_args first command-line options provided, before the list of files to process. You might want to override this method if your tool needs to see all paths.

See also

process_file

Module Tools.Testsuite


Methodlog_msg

voidlog_msg(stringmsg, mixed ... args)

Description

Logs a testsuite message to stderr. The message is shown regardless of the verbosity level. If the previous message was logged without a trailing newline then a newline is inserted first.

The message should normally have a trailing newline - no extra newline is added to it. Use log_status to log a message intended to be overwritten.


Methodlog_msg_cont

voidlog_msg_cont(stringmsg, mixed ... args)

Description

Similar to log_msg, but doesn't insert a newline first if the previous message didn't end with one. Does however insert a newline if the previous message was logged "in place" by log_status.


Methodlog_status

voidlog_status(stringmsg, mixed ... args)

Description

Logs a testsuite status message to stdout. This is suitable for nonimportant progress messages.

  • If the verbosity is 0 then nothing is logged, but the message is saved and will be logged if the next call is to log_msg.

  • If the verbosity is 1, the message is "in place" on the current line without a trailing line feed, so that the next log_status message will replace this one.

  • If the verbosity is 2 or greater, the message is logged with a trailing line feed.

The message should be short and not contain newlines, to work when the verbosity is 1, but if it ends with a newline then it's logged normally. It can be an empty string to just clear the last "in place" logged message - it won't be logged otherwise.

See also

log_twiddler


Methodlog_twiddler

voidlog_twiddler()

Description

Logs a rotating bar for showing progress. Only output at the end of an "in place" message written by log_status on verbosity level 1.


Methodreport_result

voidreport_result(intsucceeded, intfailed, void|intskipped)

Description

Use this to report the number of successful, failed, and skipped tests in a script started using run_script. Can be called multiple times - the counts are accumulated.


Methodrun_script

array(int) run_script(string|array(string) pike_script)

Description

Runs an external pike script from a testsuite. Use Tools.Testsuite.report_result in the script to report how many tests succeeded, failed, and were skipped. Those numbers are returned in the array from this function.

Class Tools.Testsuite.CompatPlugin

Annotations
@Pike.Annotations.Implements(Plugin)
Description

A source code plugin for running code in different Pike compat modes. Instantiated with the pike compat version to run in, e.g. "7.8".


InheritPlugin

inherit Plugin : Plugin


Variablepike_compat

string Tools.Testsuite.CompatPlugin.pike_compat


Method__create__

protectedlocalvoid__create__(stringpike_compat)


Methodcreate

Tools.Testsuite.CompatPluginTools.Testsuite.CompatPlugin(stringpike_compat)


Methodpreprocess

stringpreprocess(stringsource)

Description

Modifies the source code to add "#pike" and the version at the top of the code, followed by "#pragma no_deprecation_warnings".


Methodprocess_name

stringprocess_name(stringname)

Description

Modifies the name by adding the version and "compat" after the test name, e.g. "testsuite:1: Test 1 (7.8 compat)".

Class Tools.Testsuite.M4Testsuite

Description

Represents a "testsuite" file, after m4 processing.


InheritTestsuite

inherit Testsuite : Testsuite

Class Tools.Testsuite.M4Testsuite.M4Test

Description

Represents a test case from a "testsuite" file, after m4 processing.


InheritTest

inherit Test : Test


Methodcreate

Tools.Testsuite.M4Testsuite.M4TestTools.Testsuite.M4Testsuite.M4Test(stringdata)

Parameter data

The data from a testsuite file, after start/stop markers have been stripped and the file splitted on "...." tokens. From this the conditions, file, line, number, type and source will be parsed.

Class Tools.Testsuite.Plugin

Description

Interface for source code plugins, added to a Test by calling add_plugin.


Methodactive

boolactive(Testt)

Description

Returns 1 if the plugin is active (i.e. should be called by the test), otherwise 0. Defaults to 1.


Methodpreprocess

stringpreprocess(stringsource)

Description

Called by the test to modify the source code. By default just returns the unmodified source.


Methodprocess_name

stringprocess_name(stringname)

Description

Allows for modifications of the name of the test. By default just returns the name unmodified.

Class Tools.Testsuite.Test

Description

Rerpesents a test in a testsuite.


Variableconditions

array(string) Tools.Testsuite.Test.conditions

Description

The list of conditions that has to be met for this test to not be skipped. Each condition should be an expression.


Variablefile

string Tools.Testsuite.Test.file

Description

The file the testsuite (source) resides in.


Variableinhibit_errors

bool|object Tools.Testsuite.Test.inhibit_errors

Description

This value will be sent to MasterObject.set_inhibit_errors before compilation by compile().


Variableline

int(1..) Tools.Testsuite.Test.line

Description

The line number offset to this test in the file.


Variablenumber

int(1..) Tools.Testsuite.Test.number

Description

The test number in this file.


Variablesource

string Tools.Testsuite.Test.source

Description

The source code that is to be compiled and evaluated.


Variabletype

string Tools.Testsuite.Test.type

Description

The type of the test. Any of

"COMPILE"

Compiles the source and make verifies there are no warnings or errors.

"COMPILE_ERROR"

Compiles the source and expects to get a compilation error.

"COMPILE_WARNING"

Compiles the source and expects to get a compilation warning.

"EVAL_ERROR"

Evaluates the method a of the source source and expects an evaluation error.

"FALSE"

Verifies that the response from method a of the source is false.

"TRUE"

Verifies that the response from method a of the source is true.

"PUSH_WARNING"

Evaluate the method a and take the resulting string and push it to the set of ignored warnings. The same warning can be pushed multiple times, but must be popped multiple times.

"POP_WARNING"

Evaluate the method a and take the resulting string and pop the warning from the set of ignored warnings. When popped the same number of times as it has been pushed, the warning is no longer ignored.

"RUN"

Compiles and evaluates method a of the source, but ignores the result.

"RUNCT"

Compiles and evaluates method a od source, and expects an array(int) of two or three elements back.

Array
int0

The number of successful tests performed.

int1

The number of failed tests,

int2

Optionally the number of skipped tests.

"EQ"

Compares the result of the method a and b with ==.

"EQUAL"

Compares the result of the method a and b with equal.


Methodadd_plugin

voidadd_plugin(Pluginp)

Description

Add a Plugin object to the test, allowing the source code to be modified.


Methodcompile

programcompile(stringsrc)

Description

Compile the source code src in the context of the file this test belongs. Note that no changes in error mode is done and compilation errors are not caught.


Methodcompile

variantprogramcompile()

Description

Set the error mode according to inhibi_errors, applies any source code plugins by calling prepare_source and finally compiles the result. Any resulting compilation errors will be stored in compilation_error. The error mode will be set to 0 after compiltion is done.


Methodcreate

Tools.Testsuite.TestTools.Testsuite.Test(stringfile, intline, intnumber, stringtype, stringsource, void|array(string) cond)


Methodname

stringname()

Description

The name of this test, in the form of filename:line:" Test "number. The result is then processed by any code plugins.


Methodprepare_source

stringprepare_source()

Description

Applies all the plugins on the source code contained in this test and returns the result.

Class Tools.Testsuite.Test.AdjustLine


Method__create__

protectedlocalvoid__create__()


Methodcreate

Tools.Testsuite.Test.AdjustLineTools.Testsuite.Test.AdjustLine()

Module Tools.sed

Description

edit commands supported:

 <firstline>,<lastline><edit command>
    ^^ numeral (17) ^^
       or relative (+17, -17)
       or a search regexp (/regexp/)
       or multiple (17/regexp//regexp/+2)
 
CommandAction
DDelete first line in space
GInsert hold space
HAppend current space to hold space
PPrint current data
a<string>Insert
c<string>Change current space
dDelete current space
hCopy current space to hold space
i<string>Print string
lPrint current space
pPrint first line in data
qQuit evaluating
s/regexp/with/xReplace
y/chars/chars/Replace chars

where line is numeral, first 'line'==0


Method`()

protectedstring|array`()(string|array(string) commands, string|array(string) data, void|intsuppress)

Module Unicode


Constantversion

constant Unicode.version

Description

Contains the version of the current Unicode database as a string, e.g. "5.0.0".


Methodis_rtlchar

intis_rtlchar(intc)

Description

Returns 1 if the character is a RTL character or indicator, otherwise 0.


Methodis_rtlstring

intis_rtlstring(strings)

Description

Returns 1 if the string contains RTL characters or RTL indicators, otherwise 0.


Methodis_whitespace

boolis_whitespace(intc)

Description

Returns 1 if the character is a white space character, otherwise 0.


Methodis_wordchar

intis_wordchar(intc)

Description

Returns whether a unicode character c is a word, part of a word or not.

Returns
2

The character is an ideograph (a CJK single-word character)

1

The character is a letter, number or non-spacing mark, as defined by its unicode (general category) specification

0

Any other character (such as symbols, punctuation and separators)


Methodnormalize

stringnormalize(stringdata, stringmethod)

Description

Normalize the given unicode string according to the specified method.

The methods are:

NFC, NFD, NFKC and NFKD.

The methods are described in detail in the UAX #15 document, which can currently be found at http://www.unicode.org/unicode/reports/tr15/tr15-21.html

A short description:

C and D specifies whether to decompose (D) complex characters to their parts, or compose (C) single characters to complex ones.

K specifies whether or not do a canonical or compatibility conversion. When K is present, compatibility transformations are performed as well as the canonical transformations.

In the following text, 'X' denotes the single character 'X', even if there is more than one character inside the quotation marks. The reson is that it's somewhat hard to describe unicode in iso-8859-1.

The Unicode Standard defines two equivalences between characters: canonical equivalence and compatibility equivalence. Canonical equivalence is a basic equivalency between characters or sequences of characters.

'Å' and 'A' '° (combining ring above)' are canonically equivalent.

For round-trip compatibility with existing standards, Unicode has encoded many entities that are really variants of existing nominal characters. The visual representations of these character are typically a subset of the possible visual representations of the nominal character. These are given compatibility decompositions in the standard. Because the characters are visually distinguished, replacing a character by a compatibility equivalent may lose formatting information unless supplemented by markup or styling.

Examples of compatibility equivalences:

  • Font variants (thin, italic, extra wide characters etc)

  • Circled and squared characters

  • super/subscript ('²' -> '2')

  • Fractions ('½' -> '1/2')

  • Other composed characters ('fi' -> 'f' 'i', 'kg' -> 'k' 'g')


Methodsplit_words

array(string) split_words(stringinput)

Description

Splits the input string into an array of words, on the boundaries between the different kinds of word characters as defined by is_wordchar. The result is an array of words, with the non-word characters between them thrown away.


Methodsplit_words_and_normalize

array(string) split_words_and_normalize(stringinput)

Description

A less wasteful equivalent of split_words(normalize(input, "NFKD")).

Module VCDiff

Description

Pike glue for the open-vcdiff differential compression library. http://code.google.com/p/open-vcdiff/

Encoding and decoding relies on a common string that the differences are computed against - this string is called the dictionary.

Basic usage:

string dict ="abcdef";VCDiff.Encoder encoder =VCDiff.Encoder (dict);string encoded = encoder->encode ("abcdefghijklmnopqrstuvwxyz");VCDiff.Decoder decoder =VCDiff.Decoder (dict);string decoded = decoder->decode (encoded);

Module Val

Description

This module contains special values used by various modules, e.g. a null value used both by Sql and Standards.JSON.

In many ways these values should be considered constant, but it is possible for a program to replace them with extended versions, provided they don't break the behavior of the base classes defined here. Since there is no good mechanism to handle such extending in several steps, pike libraries should preferably ensure that the base classes defined here provide required functionality directly.

Note

Since resolving using the dot operator in e.g. Val.null is done at compile time, replacement of these values often must take place very early (typically in a loader before the bulk of the pike code is compiled) to be effective in such cases. For this reason, pike libraries should use dynamic resolution through e.g. -> or master()->resolv() instead.


Variabletrue
Variablefalse

Boolean Val.true
Boolean Val.false

Description

Objects that represent the boolean values true and false. In a boolean context these evaluate to true and false, respectively.

They produce 1 and 0, respectively, when cast to integer, and "1" and "0" when cast to string. They do however not compare as equal to the integers 1 and 0, or any other values. Val.true only compares (and hashes) as equal with other instances of True (although there should be as few as possible). Similarly, Val.false is only considered equal to other False instances.

Protocols.JSON uses these objects to represent the JSON literals true and false.

Note

The correct way to programmatically recognize these values is something like

if(objectp(something) && ([object]something)->is_val_true) ...

and

if(objectp(something) && ([object]something)->is_val_false) ...

respectively. See Val.null for rationale.

Note

Pike natively uses integers (zero and non-zero) as booleans. These objects don't change that, and unless there's a particular reason to use these objects it's better to stick to e.g. 0 and 1 for boolean values - that is both more efficient and more in line with existing coding practice. These objects are intended for cases where integers and booleans occur in the same place and it is necessary to distinguish them.


Variablelocal_timezone

int Val.local_timezone

Description

The local timezone without daylight-saving correction.

Note

This value is determined once at process start, and cached for the lifetime of the process.


Variablenull

Null Val.null

Description

Object that represents a null value.

In general, null is a value that represents the lack of a real value in the domain of some type. For instance, in a type system with a null value, a variable of string type typically can hold any string and also null to signify no string at all (which is different from the empty string). Pike natively uses the integer 0 (zero) for this, but since 0 also is a real integer it is sometimes necessary to have a different value for null, and then this object is preferably used.

This object is false in a boolean context. It does not cast to anything, and it is not equal to anything else but other instances of Null (which should be avoided).

This object is used by the Sql module to represent SQL NULL, and it is used by Protocols.JSON to represent the JSON literal null.

Note

Do not confuse the null value with UNDEFINED. Although UNDEFINED often is used to represent the lack of a real value, and it can be told apart from an ordinary zero integer with some effort, it is transient in nature (for instance, it automatically becomes an ordinary zero when inserted in a mapping). That makes it unsuitable for use as a reliable null value.

Note

The correct way to programmatically recognize Val.null is something like

if(objectp(something) && ([object]something)->is_val_null) ...

That way it's possible for other code to replace it with an extended class, or create their own variants which needs to behave like Val.null.

FIXME

The Oracle glue currently uses static null objects which won't be affected if this object is replaced.


Methodiso_time

stringiso_time(mapping(string:int) tm)

Parameter tm

Standard tm mapping, optionally extended with nsec for nanoseconds.

Returns

ISO formatted time.

See also

mktime()


Methodiso_timezone

finalstringiso_timezone(inttimezone)

Parameter timezone

Timezone in seconds west from UTC (must include daylight-saving time adjustment).

Returns

ISO formatted timezone east from UTC.

See also

localtime()

Class Val.Boolean

Description

Common base class for Val.True and Val.False, mainly to facilitate typing. Do not create any instances of this.


Constantis_val_boolean

constantint Val.Boolean.is_val_boolean

Description

Nonzero recognition constant that can be used to recognize both Val.true and Val.false.

Class Val.Date

Description

Lightweight date type. Stores internally in days since epoch. Supports arithmetic with Interval, Timestamp, Time and TimeTZ objects. Cast it to int or float to obtain unix_time.

See also

Interval, Timestamp, Time, TimeTZ, Range


Variabledays

int Val.Date.days

Description

Since 1970-01-01 (epoch).


Methodcreate

Val.DateVal.Date(intyear, intmonth, intday)
Val.DateVal.Date(this_programcopy)
Val.DateVal.Date(Timestampcopy)
Val.DateVal.Date(mapping(string:int) tm)
Val.DateVal.Date(intunix_time)
Val.DateVal.Date(floatunix_time)
Val.DateVal.Date()

Class Val.False

Description

Type for the Val.false object. Do not create more instances of this - use Val.false instead.


InheritBoolean

inherit Boolean : Boolean


Constantis_val_false

constantint Val.False.is_val_false

Description

Nonzero recognition constant.

Class Val.Inet

Description

Lightweight IPv4 and IPv6 address type that stores the netmask and allows simple arithmetic and comparison operators.


Variableaddress

int Val.Inet.address

Description

IP address converted to an integer. IPv4 addresses will be 32-bit or less.


Variablemasklen

int Val.Inet.masklen

Description

Defines the netmask. For both IPv4 and IPv6 addresses, masklen will be 128 in case of full addresses.


Method`<<

bool res = Val.Inet() << that

Description

Is contained by.


Method`>>

bool res = Val.Inet() >> that

Description

Contains.


Methodcreate

Val.InetVal.Inet(intip, void|intmasklen)
Val.InetVal.Inet()

Parameter ip

An IPv4 or IPv6 ip address.

Parameter masklen

Defines the netmask, always in the range between 0 and 128; i.e. for IPv4 addresses you should add 12 * 8 to the actual IPv4-masklen.


Methodcreate

Val.InetVal.Inet(stringip)

Parameter ip

A string defining an IPv4 or IPv6 address with an optional masklen attached. If the address is in IPv6 notation, the range of the masklen is expected to be between 0 and 128. If the address is in IPv4 notation, the range of the masklen is expected to be between 0 and 32.

Class Val.Interval

Description

Lightweight time and date interval type. It stores the interval in integers of nanoseconds, days and months. Supports arithmetic with Time, TimeTZ, Timestamp and Date objects. Cast it to int or float to obtain seconds.

Note

Depending on daylight-saving time, a day may not equal 24 hours.

Note

The number of days in a month depends on the the time of the year.

See also

Timestamp, Date, Time


InheritTime

inherit Time : Time


Variabledays

int Val.Interval.days

Description

Number of days; may not be equal to 24 hours per day, depending on daylight-saving time.


Variablemonths

int Val.Interval.months

Description

Number of months; the number of days per month varies accordingly.


Methodcast

(int)Val.Interval()
(float)Val.Interval()
(string)Val.Interval()
(array)Val.Interval()
(mapping)Val.Interval()
(multiset)Val.Interval()

Description

Casting intervals with days or months to int or float is not possible since the units are not constant. Casting an interval to string will return a value which is SQL-compliant.


Methodtm

mapping(string:int) tm()

Returns

A tm-like mapping which describes the interval. The mapping will include an extra nsec component, and optionally isnegative = 1 if the interval is a negative time interval.

See also

mktime(), gmtime()

Class Val.Null

Description

Type for the Val.null object. Do not create more instances of this - use Val.null instead.


InheritNull

inherit Builtin.Null : Null

Class Val.Range

Description

Generic lightweight range type. Supports any values for lower and upper boundaries that implement lfun::`<() and lfun::`-(), and preferrably also cast to int and string.

Note

Can only contain a single contiguous range.

Note

The empty range must be stored as (Math.inf, -Math.inf) if assigned directly to from and till.


Variablefrom

value_type Val.Range.from

Description

The lower inclusive boundary.


Variabletill

value_type Val.Range.till

Description

The upper exclusive boundary.


Method`!

bool res = !Val.Range()

Returns

True if range is empty.

See also

isempty()


Method`&

bool res = Val.Range() & that

Description

Overlap: have points in common.


Method`*

this_program res = Val.Range() * that

Description

Intersection


Method`+

this_program res = Val.Range() + that

Description

Union


Method`-

this_program res = Val.Range() - that

Description

Difference


Method`<<

bool res = Val.Range() << that

Description

Strictly left of


Method`>>

bool res = Val.Range() >> that

Description

Strictly right of


Method`|

bool res = Val.Range() | that

Description

Is adjacent to

FIXME

This does NOT seem like a good operator for this operation.


Methodcontains

boolcontains(this_program|value_typeother)

Returns

True if this range fully contains another range or element.


Methodcreate

Val.RangeVal.Range(value_typefrom, value_typetill)
Val.RangeVal.Range(this_programcopy)
Val.RangeVal.Range()

Parameter from

Lower inclusive boundary for the range. Specify no lower-boundary by filling in -Math.inf.

Parameter till

Upper exclusive boundary for the range. Specify no upper-boundary by filling in Math.inf.

See also

Math.inf


Methodinterval

mixedinterval()

Returns

Calculates the value of the interval: till - from. Returns 0 if the range is empty.


Methodisempty

localboolisempty()

Returns

True if range is empty.

See also

`!()


Methodmerge

this_programmerge(this_program ... other)

Parameter other

Extends the current range to the smallest range which encompasses itself and all other given ranges.

FIXME

This seems like the operation that `|() ought to do.


Methodsql

finalstringsql()

Returns

A string representing the range using SQL-compliant syntax.

Class Val.Time

Description

Lightweight time type. Stores absolute times in a day with nanosecond resolution. Normalised value range is between 00:00:00.000000000 and 23:59:59.999999999. Values outside this range are accepted, and have arithmetically sound results. Supports arithmetic with Interval and Date objects. Cast it to int or float to obtain seconds since 00:00.

See also

Interval, Date, TimeTZ, Range


InheritTimebase

inherit Timebase : Timebase


Methodcreate

Val.TimeVal.Time(inthour, intmin, void|intsec, void|intnsec)
Val.TimeVal.Time(intsec)

Parameter hour

Hours since epoch.

Parameter min

Minutes since epoch.

Parameter sec

Seconds since epoch.

Parameter nsec

Nanoseconds since epoch.


Methodcreate

Val.TimeVal.Time(mapping(string:int) tm)

Parameter tm

Standard tm mapping, optionally extended with nsec for nanoseconds. Passed values will not be normalised. Days/months/years are ignored.


Methodtm

mapping(string:int) tm()

Returns

A tm-like mapping which describes the time. The mapping will include an extra nsec component.

See also

mktime(), gmtime()

Class Val.TimeTZ

Description

Lightweight time type with timezone. Equivalent to Time, but stores a timezone offset as well. Cast it to int or float to obtain seconds since 00:00.

See also

Time, Date, Interval, Range


InheritTime

inherit Time : Time


Variabletimezone

int Val.TimeTZ.timezone

Description

Timezone offset in seconds west from UTC (includes daylight-saving time adjustment).

Note

ISO time format displays the timezone in seconds east from UTC.

See also

localtime()


Methodcreate

Val.TimeTZVal.TimeTZ(mapping(string:int) tm)

Parameter tm

Standard tm mapping, optionally extended with nsec for nanoseconds. Any specified timezone is used as is. Passed values will not be normalised. Days/months/years are ignored.


Methodcreate

Val.TimeTZVal.TimeTZ(intyear, intmonth, intday, inthour, intmin, void|intsec, void|intnsec)

Description

Stores just the time of the day components, but including the correct timezone offset with any daylight-saving correction active on the date specified.

Parameter year

Absolute year (e.g. 1900 == 1900, 2000 = 2000, 2017 == 2017).

Parameter month

Month of the year (January == 1 ... December == 12).

Parameter day

Day of the month (typically between 1 and 31).

Parameter hour

Hour of the day (typically between 0 and 23).

Parameter min

Minutes (typically between 0 and 59).

Parameter sec

Seconds (typically between 0 and 59).

Parameter nsec

Nanoseconds (typically between 0 and 999999999).

Note

Specified values are expected in the localised time (i.e. relative to the current timezone locale, including daylight-saving correction).

Note

If any of these values are offered in a denormalised range, they will be normalised relative to the startdate offered.

See also

Timestamp, Date, Interval, Time

Class Val.Timebase

Description

Base class for time related objects. Supports arithmetic with Interval objects.

Note

Should not be used by itself.

See also

Timestamp, Time, Interval


Variablensecs

int Val.Timebase.nsecs

Description

Nanoseconds since epoch (for absolute time classes, epoch equals 1970/01/01 00:00:00 UTC).


Variableusecs

int|float Val.Timebase.usecs

Description

Getting

Microseconds since epoch; reflects the equivalent value as the basic member nsecs.

Setting

Microseconds since epoch; reflects the equivalent value as the basic member nsecs.


Methodcast

(int)Val.Timebase()
(float)Val.Timebase()
(string)Val.Timebase()
(array)Val.Timebase()
(mapping)Val.Timebase()
(multiset)Val.Timebase()

Description

Can be casted to string, float and int. Casting it to float and int return unix-time values.

See also

mktime(), gmtime()


Methodcreate

Val.TimebaseVal.Timebase(void|mapping(string:int) tm)
Val.TimebaseVal.Timebase(this_programcopy)
Val.TimebaseVal.Timebase(int|floatsec, void|intnsec)

Parameter sec

Seconds since epoch.

Parameter nsec

Nanoseconds since epoch.

Class Val.Timestamp

Description

Lightweight time and date type. The values point at absolute points in time. The values are stored internally with nanosecond resolution since epoch (1970/01/01 00:00:00 UTC). Supports arithmetic with Interval objects. Cast it to int or float to obtain unix_time.

See also

Interval, Date, Range, localtime(), mktime()


InheritTimebase

inherit Timebase : Timebase


Methodcast

(int)Val.Timestamp()
(float)Val.Timestamp()
(string)Val.Timestamp()
(array)Val.Timestamp()
(mapping)Val.Timestamp()
(multiset)Val.Timestamp()

Description

When cast to string it returns an ISO formatted timestamp that includes daylight-saving and timezone corrections.


Methodcreate

Val.TimestampVal.Timestamp(intyear, intmonth, intday, void|inthour, void|intmin, void|intsec, void|intnsec)
Val.TimestampVal.Timestamp(intunix_time, void|intnsec)

Parameter year

Absolute year (e.g. 1900 == 1900, 2000 = 2000, 2017 == 2017).

Parameter month

Month of the year (January == 1 ... December == 12).

Parameter day

Day of the month (typically between 1 and 31).

Parameter hour

Hour of the day (typically between 0 and 23).

Parameter min

Minutes (typically between 0 and 59).

Parameter sec

Seconds (typically between 0 and 59).

Parameter nsec

Nanoseconds (typically between 0 and 999999999).

Note

Specified values are expected in the localised time (i.e. relative to the current timezone locale, including daylight-saving correction).

Note

If any of these values are offered in a denormalised range, they will be normalised relative to the startdate offered. I.e. it allows primitive year/month/day/hour/minute/second/nanosecond arithmetic. For more advanced arithmetic you must use Interval objects.

See also

localtime(), mktime()


Methodtm

mapping(string:int) tm()

Returns

The same as localtime(), but augmented by an extra member called nsec.

See also

localtime()

Class Val.True

Description

Type for the Val.true object. Do not create more instances of this - use Val.true instead.


InheritBoolean

inherit Boolean : Boolean


Constantis_val_true

constantint Val.True.is_val_true

Description

Nonzero recognition constant.

Module Web

Description

Modules implementing various web standards.


Methoddecode_jwk

Crypto.Sign.State|Crypto.MAC.Statedecode_jwk(mapping(string(7bit):string(7bit)) jwk)

Description

Decode a JSON Web Key (JWK).

Returns

Returns an initialized Crypto.Sign.State or Crypto.MAC.State on success and UNDEFINED on failure.


Methoddecode_jwk

variantCrypto.Sign.State|Crypto.MAC.Statedecode_jwk(string(8bit)jwk)

Description

Decode a JSON Web Key (JWK).

Returns

Returns an initialized Crypto.Sign.State or Crypto.MAC.State on success and UNDEFINED on failure.


Methoddecode_jwk_set

array(Crypto.Sign.State|Crypto.MAC.State) decode_jwk_set(mapping(string(8bit):array(mapping(string(7bit):string(7bit)))) jwk_set)

Description

Decode a JSON Web Key (JWK) Set.

See also

RFC 7517 section 5, decode_jwk()


Methoddecode_jwk_set

variantarray(Crypto.Sign.State|Crypto.MAC.State) decode_jwk_set(string(7bit)jwk_set)

Description

Decode a JSON Web Key (JWK) Set.

See also

RFC 7517 section 5, decode_jwk()


Methoddecode_jws

array|zerodecode_jws(array(Crypto.Sign.State|Crypto.MAC.State)|Crypto.Sign.State|Crypto.MAC.Statesign, string(7bit)jws)

Description

Decode a JSON Web Signature (JWS).

Parameter sign

The asymetric public or MAC key(s) to validate the jws against.

Parameter jws

A JWS as eg returned by encode_jws().

Returns

Returns 0 (zero) on validation failure.

Returns an array with two elements on success:

Array
mapping(string(7bit):string(7bit)|int) 0

The JOSE header.

mixed1

The JWS payload.

See RFC 7515 section 3.

See also

encode_jws(), decode_jwt(), Crypto.Sign.State()->jose_decode(), RFC 7515


Methoddecode_jwt

mapping(string:string|int)|zerodecode_jwt(array(Crypto.Sign.State|Crypto.MAC.State)|Crypto.Sign.State|Crypto.MAC.Statesign, string(7bit)jwt)

Description

Decode a JSON Web Token (JWT).

Parameter sign

The asymetric public or MAC key(s) to validate the jwt against.

Parameter jwt

A JWT as eg returned by encode_jwt().

Returns

Returns 0 (zero) on validation failure (this includes validation of expiry times).

Returns a mapping of the claims for the token on success. See RFC 7519 section 4.

Note

The time check of the "nbf" value has a hard coded 60 second grace time (as allowed by RFC 7519 section 4.1.5).

See also

encode_jwt(), decode_jws(), RFC 7519 section 4


Methodencode_jwk

string(7bit)encode_jwk(mapping(string(7bit):string(7bit)) jwk)

Description

Encode a JSON Web Key (JWK).


Methodencode_jwk

variantstring(7bit)encode_jwk(Crypto.Sign.State|Crypto.MAC.Statesign, bool|voidprivate_key)

Description

Encode a JSON Web Key (JWK).

Parameter sign

The initialized Crypto.Sign.State or Crypto.MAC.State for which a JWK is to be generated.

Parameter private_key

If true the private fields of sign will also be encoded into the result.

Returns

Returns the corresponding JWK.


Methodencode_jws

string(7bit)encode_jws(Crypto.Sign.State|Crypto.MAC.Statesign, mixedtbs, string(7bit)|voidmedia_type)

Description

Encode a JSON Web Signature (JWS).

Parameter sign

The asymetric private or MAC key to use for signing the result.

Parameter tbs

The value to sign.

Parameter media_type

The media type of tbs, cf RFC 7515 section 4.1.9.

Returns

Returns 0 (zero) on encoding failure (usually that sign doesn't support JWS.

Returns a corresponding JWS on success.

See also

decode_jwt(), RFC 7515


Methodencode_jwt

string(7bit)encode_jwt(Crypto.Sign.State|Crypto.MAC.Statesign, mapping(string:string|int) claims)

Description

Encode a JSON Web Token (JWT). Automatically adds the optional "issued at" timestamp and JWD ID (using UUID v4).

Parameter sign

The asymetric private or MAC key to use for signing the result.

Parameter claims

The set of claims for the token. See RFC 7519 section 4.

Returns

Returns 0 (zero) on encoding failure (usually that sign doesn't support JWS.

Returns a corresponding JWT on success.

Note

The claim "iat" (RFC 7519 section 4.1.6 is added unconditionally, and the claim "jti" (RFC 7519 section 4.1.7) is added if not already present.

See also

decode_jwt(), RFC 7519 section 4

Class Web.OWL

Description

Represents an RDF tuple set from an OWL perspective.


InheritRDFS

inherit .RDFS : RDFS

Class Web.RDF

Description

Represents an RDF domain which can contain any number of complete statements.


Constantrdf_ns

constantstring Web.RDF.rdf_ns

Description

The RDF XML namespace.


Variablerdf_Seq

RDFResource Web.RDF.rdf_Seq

Description

Seq resource.


Variablerdf_Statement

RDFResource Web.RDF.rdf_Statement

Description

Statement resource.


Variablerdf_first

RDFResource Web.RDF.rdf_first

Description

first resource.


Variablerdf_nil

RDFResource Web.RDF.rdf_nil

Description

nil resource.


Variablerdf_object

RDFResource Web.RDF.rdf_object

Description

object resource.


Variablerdf_predicate

RDFResource Web.RDF.rdf_predicate

Description

predicate resource.


Variablerdf_rest

RDFResource Web.RDF.rdf_rest

Description

rest resource.


Variablerdf_subject

RDFResource Web.RDF.rdf_subject

Description

subject resource.


Variablerdf_type

RDFResource Web.RDF.rdf_type

Description

type resource.


Method_sizeof

intsizeof(Web.RDFarg)

Description

Returns the number of statements in the RDF domain.


Method`|

Web.RDF res = Web.RDF() | x

Description

Modifies the current object to create a union of the current object and the object x.


Methodadd_statement

this_programadd_statement(Resource|string|multiset(string) subj, Resource|string|multiset(string) pred, Resource|string|multiset(string) obj)

Description

Adds a statement to the RDF set. If any argument is a string, it will be converted into a LiteralResource. If any argument is a multiset with one string in it, it will be converted into a URIResource.

Throws

Throws an exception if any argument couldn't be converted into a Resouce object.


Methoddecode_n_triple_string

stringdecode_n_triple_string(stringin)

Description

Decodes a string that has been encoded for N-triples serialization.

Bugs

Doesn't correctly decode backslashes that has been encoded with with \u- or \U-notation.


Methoddereify

booldereify(Resourcer)

Description

Turns the reified statement r into a normal statement, if possible.

Returns

1 for success, 0 for failure.


Methoddereify_all

int(0..)dereify_all()

Description

Dereifies as many statements as possible. Returns the number of dereified statements.


Methodencode_n_triple_string

stringencode_n_triple_string(stringin)

Description

Encodes a string for use as tring in N-triples serialization.


Methodfind_statements

array(array(Resource)) find_statements(Resource|int(0)subj, Resource|int(0)pred, Resource|int(0)obj)

Description

Returns an array with the statements that matches the given subject subj, predicate pred and object obj. Any and all of the resources may be zero to disregard from matching that part of the statement, i.e. find_statements(0,0,0) returns all statements in the domain.

Returns

An array with arrays of three elements.

Array
Resource0

The subject of the statement

Resource1

The predicate of the statement

Resource2

The object of the statement


Methodget_3_tuples

stringget_3_tuples()

Description

Returns a 3-tuple serialization of all the statements in the RDF set.


Methodget_n_triples

stringget_n_triples()

Description

Returns an N-triples serialization of all the statements in the RDF set.


Methodget_properties

array(Resource) get_properties()

Description

Returns all properties in the domain, e.g. all resources that has been used as predicates.


Methodget_reify

Resource|zeroget_reify(Resourcesubj, Resourcepred, Resourceobj)

Description

Returns a resource that is the subject of the reified statement {subj, pred, obj}, if such a resource exists in the RDF domain.


Methodget_resource

URIResource|zeroget_resource(stringuri)

Description

Returns an RDF resource with the given URI as identifier, or zero.


Methodget_subject_map

mapping(Resource:mapping(Resource:array(Resource))) get_subject_map()

Description

Returns a mapping with all the domains subject resources as indices and a mapping with that subjects predicates and objects as value.


Methodget_xml

stringget_xml(void|intno_optimize)

Description

Serialize the RDF domain as an XML string.

Parameter no_optimize

If set, the XML serializer will refrain from doing most (size) optimizations of the output.


Methodhas_statement

boolhas_statement(Resourcesubj, Resourcepred, Resourceobj)

Description

Returns 1 if the RDF domain contains the relation {subj, pred, obj}, otherwise 0.


Methodis_object

boolis_object(Resourcer)

Description

Returns 1 if resource r is used as an object, otherwise 0.


Methodis_predicate

boolis_predicate(Resourcer)

Description

Returns 1 if resource r is used as a predicate, otherwise 0.


Methodis_subject

boolis_subject(Resourcer)

Description

Returns 1 if resource r is used as a subject, otherwise 0.


Methodmake_resource

URIResourcemake_resource(stringuri)

Description

Returns an RDF resource with the given URI as identifier, or if no such resrouce exists, creates it and returns it.


Methodparse_n_triples

intparse_n_triples(stringin)

Description

Parses an N-triples string and adds the found statements to the RDF set. Returns the number of added relations.

Throws

The parser will throw errors on invalid N-triple input.


Methodparse_xml

Web.RDFparse_xml(string|Parser.XML.NSTree.NSNodein, void|stringbase)

Description

Adds the statements represented by the string or tree in to the RDF domain. If in is a tree the in-node should be the RDF node of the XML serialization. RDF documents take its default namespace from the URI of the document, so if the RDF document relies such ingenious mechanisms, pass the document URI in the base variable.


Methodreify

Resourcereify(Resourcesubj, Resourcepred, Resourceobj)

Description

Returns the result of get_reify, if any. Otherwise calls reify_low followed by remove_statement of the provided statement {subj, pred, obj}.

Returns

The subject of the reified statement.


Methodreify_low

Resourcereify_low(Resourcesubj, Resourcepred, Resourceobj)

Description

Reifies the statement { pred, subj, obj } and returns the resource that denotes the reified statement. There will not be any check to see if the unreified statement is already in the domain, making it possible to define the relation twice. The original statement will not be removed.

Returns

The subject of the reified statement.


Methodremove_statement

boolremove_statement(Resourcesubj, Resourcepred, Resourceobj)

Description

Removes the relation from the RDF set. Returns 1 if the relation did exist in the RDF set.

Class Web.RDF.LiteralResource

Description

Resource identified by literal.


InheritResource

inherit Resource : Resource


Variabledatatype

string Web.RDF.LiteralResource.datatype

Description

Used to contain rdf:datatype value.


Methodcreate

Web.RDF.LiteralResourceWeb.RDF.LiteralResource(stringliteral)

Description

The resource will be identified by literal.


Methodget_literal

stringget_literal()

Description

Returns the literal string.


Methodget_xml

stringget_xml()

Description

Returns the literal as an XML string.

Class Web.RDF.RDFResource

Description

Resource used for RDF-technical reasons like reification.


InheritURIResource

inherit URIResource : URIResource


Methodcreate

Web.RDF.RDFResourceWeb.RDF.RDFResource(stringrdf_id)

Description

The resource will be identified by the identifier rdf_id


Methodget_qname

stringget_qname(void|stringns)

Description

Returns the qualifying name.

Class Web.RDF.Resource

Description

Instances of this class represents resources as defined in RDF: All things being described by RDF expressions are called resources. A resource may be an entire Web page; such as the HTML document "http://www.w3.org/Overview.html" for example. A resource may be a part of a Web page; e.g. a specific HTML or XML element within the document source. A resource may also be a whole collection of pages; e.g. an entire Web site. A resource may also be an object that is not directly accessible via the Web; e.g. a printed book. This general resource is anonymous and has no URI or literal id.

Note

Resources instantiated from this class should not be used in other RDF domain objects.

See also

URIResource, LiteralResource


Methodget_3_tuple_name

stringget_3_tuple_name()

Description

Returns the nodes' 3-tuple serialized ID.


Methodget_n_triple_name

stringget_n_triple_name()

Description

Returns the nodes' N-triple serialized ID.

Class Web.RDF.URIResource

Description

Resource identified by URI.


InheritResource

inherit Resource : Resource


Methodcreate

Web.RDF.URIResourceWeb.RDF.URIResource(stringuri)

Description

Creates an URI resource with the uri as identifier.

Throws

Throws an error if another resource with the same URI already exists in the RDF domain.


Methodget_namespace

stringget_namespace()

Description

Returns the namespace this resource URI references to.


Methodget_qname

string|zeroget_qname(void|stringns)

Description

Returns the qualifying name, or zero.


Methodget_uri

stringget_uri()

Description

Returns the URI the resource references to.

Class Web.RDFS

Description

RDF Schema.


InheritRDF

inherit .RDF : RDF


Constantrdfs_ns

constantstring Web.RDFS.rdfs_ns

Description

The RDF Schema XML-namespace.


Variablerdfs_Class
Variablerdfs_subClassOf
Variablerdfs_Literal
Variablerdfs_subPropertyOf
Variablerdfs_domain
Variablerdfs_range

RDFSResource Web.RDFS.rdfs_Class
RDFSResource Web.RDFS.rdfs_subClassOf
RDFSResource Web.RDFS.rdfs_Literal
RDFSResource Web.RDFS.rdfs_subPropertyOf
RDFSResource Web.RDFS.rdfs_domain
RDFSResource Web.RDFS.rdfs_range


Methodadd_Class

voidadd_Class(Resourcec)


Methodadd_subClassOf

voidadd_subClassOf(Resourcea, Resourceb)


Methodadd_subPropertyOf

voidadd_subPropertyOf(Resourcea, Resourceb)

Class Web.RDFS.RDFSResource


InheritURIResource

inherit URIResource : URIResource

Module Web.Api

Description

The Web.Api has modules and classes for communicating with various (RESTful) web api's such as Web.Api.Facebook, Web.Api.Instagram, Web.Api.Twitter etc.

Example
string api_key ="......";string api_secret =".......";string redirect_uri ="http://localhost/insta/";Web.Api.Instagram api;string cookie_file ="my-cookie.txt";int main(int argc,array(string) argv){
  api =Web.Api.Instagram(api_key, api_secret, redirect_uri);// If a stored authentication cookie exists, populate the auth object.if(Stdio.exist(cookie_file)){
    api->auth->set_from_cookie(Stdio.read_file(cookie_file));}if(!api->auth->is_authenticated()){// A cookie existed but the authentication has expiredif(api->auth->is_renewable()){
      write("Trying to refresh token...");if(string data = api->auth->refresh_token())Stdio.write_file(cookie_file, data);
        write("done ok!\n");}else{
        werror("failed!\n");}}// No previous authentication exists. Create a new one...else{// Get the uri to the authentication endpointstring uri = api->auth->get_auth_uri();

      write("Opening \"%s\" in browser.\nCopy the contents of the address ""bar and paste here: ",Standards.URI(uri));

      sleep(2);// For MacProcess.create_process(({"open", uri }));string resp =Stdio.Readline()->read();mapping p =Web.Auth.query_to_mapping(Standards.URI(resp)->query);string code;// If the auth object is OAuth and not OAuth2 this step is required.// Instagram is OAuth2, but Twitter is OAuth1if(p->oauth_token){
        auth->set_authentication(p->oauth_token);
        code = p->oauth_verifier;}else{
        code = p->code;}// Now, get an access tokenif(string data = auth->request_access_token(code)){Stdio.write_file(cookie, data);}else{
        werror("Failed getting an access token. Aborting!\n");return 1;}}}if(api->auth->is_authenticated()){// No UID (arg1) means get the authenticated users stuff// No additional params (arg2)// Run async (arg3)mapping m = api->users->recent(0, 0,lambda(mixed m){
      werror("Insta: %O\n", m);
      exit(0);});return-1;}else{
    werror("No authentication was aquired!\n");return 1;}}

ConstantUSER_AGENT

constantstring Web.Api.USER_AGENT

Description

Default user agent in HTTP calls

Class Web.Api.Api

Description

Base class for implementing a (RESTful) WebApi like Facebook's Graph API, Instagram's API, Twitter's API and so on.

Note: This class is useless in it self, and is intended to be inherited by classes implementing a given Web.Api.

Look at the code in Web.Api.Github, Web.Api.Instagram, Web.Api.Linkedin etc to see some examples of implementations.


TypedefCallback

typedeffunction(mixed, Protocols.HTTP.Query, mixed ... :void) Web.Api.Api.Callback

Description

Typedef for the async callback method signature.


TypedefCallback

typedeffunction(mixed, Protocols.HTTP.Query|Protocols.HTTP.Promise.Result, mixed ... :void) Web.Api.Api.Callback

Description

Typedef for the async callback method signature.


TypedefParamsArg

typedefmapping|Web.Auth.Params Web.Api.Api.ParamsArg

Description

Typedef for a parameter argument


ConstantACCESS_TOKEN_PARAM_NAME

protected constantstring Web.Api.Api.ACCESS_TOKEN_PARAM_NAME

Description

In some API's (LinkedIn f ex) this is named something else so it needs to be overridden i cases where it has a different name than the standard one.

Note

Obsolete.

This is only used if AUTHORIZATION_METHOD has been set to "".


ConstantAPI_URI

constantstring Web.Api.Api.API_URI

Description

The default URI to the remote API


ConstantAUTHORIZATION_METHOD

protected constantstring Web.Api.Api.AUTHORIZATION_METHOD

Description

Authorization header prefix.

This is typically "Bearer" as per RFC 6750, but some apis use the older "token".


ConstantAuthClass

constant Web.Api.Api.AuthClass

Description

Authentication class to use


ConstantDECODE_UTF8

protected constantint Web.Api.Api.DECODE_UTF8

Description

If 1Standards.JSON.decode_utf8() will be used when JSON data is decoded.


Variable_auth

protectedWeb.Auth.OAuth2.Client Web.Api.Api._auth

Description

Authorization object.

See also

Web.Auth.OAuth2


Variable_query_objects

protectedmapping(int:array(Protocols.HTTP.Query|Callback)) Web.Api.Api._query_objects

Description

The HTTP query objects when running async.


Variableauth

Web.Auth.OAuth2.Client Web.Api.Api.auth

Description

Getter for the authentication object. Most likely this will be a class derived from Web.Auth.OAuth2.Client.

See also

Web.Auth.OAuth2.Client or Web.Auth.OWeb.Auth.Client

Note

Read only


Variablehttp_request_timeout

int(0..) Web.Api.Api.http_request_timeout

Description

Request timeout in seconds. Only affects async queries.


Variableutf8_decode

bool Web.Api.Api.utf8_decode

Description

If 1Standards.JSON.decode_utf8() will be used when JSON data is decoded.


Methodcall

mixedcall(stringapi_method, void|ParamsArgparams, void|stringhttp_method, void|stringdata, void|Callbackcb, mixed ... rest)

Description

Calls a remote API method.

Throws

An exception is thrown if the response status code is other than 200, 301 or 302.

Parameter api_method

The remote API method to call! This should be a Fully Qualified Domain Name

Parameter params

Additional params to send in the request

Parameter http_method

HTTP method to use. GET is default

Parameter data

Inline data to send in a POST request for instance.

Parameter cb

Callback function to get into in async mode

Returns

If JSON is available the JSON response from servie will be decoded and returned. If not, the raw response (e.g a JSON string) will be returned. The exception to this is if the status code in the response is a 30x (a redirect), then the response headers mapping will be returned.


Methodclose_connections

voidclose_connections()

Description

Forcefully close all HTTP connections. This only has effect in async mode.


Methodcreate

Web.Api.ApiWeb.Api.Api(void|stringclient_id, void|stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Creates a new Api instance

Parameter client_id

The application ID

Parameter client_secret

The application secret

Parameter redirect_uri

Where the authorization page should redirect back to. This must be fully qualified domain name.

Parameter scope

Extended permissions to use for this authentication.


Methoddefault_params

protectedmappingdefault_params()

Description

Return default params


Methoddelete

mixeddelete(stringapi_method, void|ParamsArgparams, void|Callbackcb, mixed ... rest)

Description

Invokes a call with a DELETE method

Parameter api_method

The remote API method to call

Parameter params
Parameter cb

Callback function to get into in async mode


Methodget

mixedget(stringapi_method, void|ParamsArgparams, void|Callbackcb, mixed ... rest)

Description

Invokes a call with a GET method

Parameter api_method

The remote API method to call

Parameter params
Parameter cb

Callback function to get into in async mode


Methodget_encoding

protectedstringget_encoding(mappingh)

Description

Returns the encoding from a response

Parameter h

The headers mapping from a HTTP respose


Methodget_uri

protectedstringget_uri(stringmethod)

Description

Convenience method for getting the URI to a specific API method

Parameter method

Methodmake_multipart_message

protectedarray(string) make_multipart_message(mappingp, stringbody)

Description

Creates the body of an Upload request

Parameter p

The API request parameters

Parameter body

Data of the document to upload

Returns

An array with two indices:

  • The value for the main Content-Type header

  • The request body


Methodparse_canonical_url

mapping(string:string|mapping) parse_canonical_url(stringurl)

Description

This can be used to parse a link resource returned from a REST api. Many API returns stuff like:

{
  ...
  "pagination":{"next":"/api/v1/method/path?some=variables&page=2&per_page=20"}}

If pagination->next is passed to this method it will return a path of /method/path, given that the base URI of the web api is something along the line of https://some.url/api/v1, and a mapping containing the query variables (which can be passed as a parameter to any of the get, post, delete, put methods.

Parameter url
Returns
"path" : string
"params" : mapping

Methodpatch

mixedpatch(stringapi_method, void|ParamsArgparams, void|Callbackcb, mixed ... rest)

Description

Invokes a call with a PATCH method

Parameter api_method

The remote API method to call

Parameter params
Parameter cb

Callback function to get into in async mode


Methodpost

mixedpost(stringapi_method, void|ParamsArgparams, void|stringdata, void|Callbackcb, mixed ... rest)

Description

Invokes a call with a POST method

Parameter api_method

The remote API method to call

Parameter params
Parameter data

Eventual inline data to send

Parameter cb

Callback function to get into in async mode


Methodput

mixedput(stringapi_method, void|ParamsArgparams, void|Callbackcb, mixed ... rest)

Description

Invokes a call with a PUT method

Parameter api_method

The remote API method to call

Parameter params
Parameter cb

Callback function to get into in async mode


Methodunescape_forward_slashes

protectedstringunescape_forward_slashes(strings)

Description

Unescapes escaped forward slashes in a JSON string

Class Web.Api.Api.Method

Description

Internal class meant to be inherited by implementing Api's classes that corresponds to a given API endpoint.


ConstantMETHOD_PATH

protected constantint Web.Api.Api.Method.METHOD_PATH

Description

API method location within the API

https://api.instagram.com/v1/media/search
............................^^^^^^^

Method_delete

protectedmixed_delete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_get

protectedmixed_get(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_patch

protectedmixed_patch(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_post

protectedmixed_post(strings, void|ParamsArgp, void|stringdata, void|Callbackcb)

Description

Internal convenience method


Method_put

protectedmixed_put(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodcreate

Web.Api.Api.MethodWeb.Api.Api.Method()

Description

Hidden constructor. This class can not be instantiated directly

Module Web.Api.Facebook


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Facebook API. See Web.Api.Api() for further information.

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

Class Web.Api.Facebook.Graph


Inheritparent

inherit Web.Api.Api : parent


ConstantAPI_URI

constantstring Web.Api.Facebook.Graph.API_URI

Description

The base uri to the Graph API


Variableany

Any Web.Api.Facebook.Graph.any

Description

Getter for the Any object which is a generic object for making request to the Facebook Graph API

See also

Any

Note

Read only


Methoddelete

mappingdelete(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic DELETE request to the Facebook Graph API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodget

mappingget(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic GET request to the Facebook Graph API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodpost

mappingpost(stringpath, void|ParamsArgparams, void|stringdata, void|Callbackcb)

Description

Make a generic POST request to the Facebook Graph API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter data
Parameter cb

Callback for async requests


Methodput

mappingput(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic PUT request to the Facebook Graph API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests

Class Web.Api.Facebook.Graph.Any

Description

A generic wrapper around Method


InheritMethod

inherit Method : Method

Class Web.Api.Facebook.Graph.Method


InheritMethod

inherit Web.Api.Api.Method : Method


Methoddelete

mixeddelete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodget

mixedget(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodpost

mixedpost(strings, void|ParamsArgp, void|stringdata, void|Callbackcb)

Description

Internal convenience method


Methodput

mixedput(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method

Module Web.Api.Github


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Github API. See Web.Api.Api() for further information.

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

Class Web.Api.Github.Github


Inheritparent

inherit Web.Api.Api : parent


ConstantAPI_URI

constantstring Web.Api.Github.Github.API_URI

Description

The base uri to the Github API


Variableany

Any Web.Api.Github.Github.any

Description

Getter for the Any object which is a generic object for making request to the Github API

See also

Any

Note

Read only


Methoddelete

mappingdelete(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic DELETE request to the Github API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodget

mappingget(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic GET request to the Github API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodpost

mappingpost(stringpath, void|ParamsArgparams, void|stringdata, void|Callbackcb)

Description

Make a generic POST request to the Github API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter data
Parameter cb

Callback for async requests


Methodput

mappingput(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic PUT request to the Github API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests

Class Web.Api.Github.Github.Any

Description

A generic wrapper around Method


InheritMethod

inherit Method : Method

Class Web.Api.Github.Github.Method


InheritMethod

inherit Web.Api.Api.Method : Method


Methoddelete

mixeddelete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodget

mixedget(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodpost

mixedpost(strings, void|ParamsArgp, void|stringdata, void|Callbackcb)

Description

Internal convenience method


Methodput

mixedput(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method

Module Web.Api.Google


Methoddiscover

Basediscover(stringapi, stringversion, void|stringclient_id, void|stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Get a Google API object

Example

This example shows how you can use the Google API to find out all the compute zones that exist at Google Compute Engine.

#define SECRET_FILE     "googleserviceaccount.json"#define PROJECT         "somegoogleproject"#define TOKENTIME       3600

string jwt_secret =Stdio.File(SECRET_FILE,"r").read();Web.Api.Google.Base api =Web.Api.Google.discover("compute","v1");void authenticated(){if(!api->auth->is_authenticated()
   || api->auth->expires->unix_time()- time(1)< TOKENTIME / 2)
    api->auth->get_token_from_jwt(jwt_secret);};

authenticated();mixed allzones = api->resrc->zones->list((["project":PROJECT ]));

Class Web.Api.Google.Api

Description

Internal class meant to be inherited by other Google API's


Inheritparent

inherit Web.Api.Api : parent

Class Web.Api.Google.Api.Method


InheritMethod

inherit Web.Api.Api.Method : Method


Method_delete

protectedmixed_delete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_get

protectedmixed_get(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_post

protectedmixed_post(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method

Class Web.Api.Google.Base


Inheritparent

inherit Api : parent


Variableresrc

resource Web.Api.Google.Base.resrc

Note

Read only


Variablevalid_scopes

array(string) Web.Api.Google.Base.valid_scopes

Note

Read only


Methodcreate

Web.Api.Google.BaseWeb.Api.Google.Base(mappingdiscovered, mixed ... rest)


Methodset_scope

voidset_scope(stringscope)

Class Web.Api.Google.Discovery


Inheritparent

inherit Api : parent


ConstantAPI_URI

protected constantstring Web.Api.Google.Discovery.API_URI

Description

API base URI.


Variable_apis

protectedApis Web.Api.Google.Discovery._apis

Description

Internal singleton objects. Retrieve an apis via apis.


Variableapis

Apis Web.Api.Google.Discovery.apis

Description

Getter for the Apis API

Note

Read only

Class Web.Api.Google.Discovery.Apis

Description

Interface to the Google Discovery Service API


InheritMethod

inherit Method : Method


MethodgetRest

mixedgetRest(mappingparams, void|Callbackcb)

Description

Retrieve the description of a particular version of an API

Parameter params
Parameter cb

Methodlist

mixedlist(void|mappingparams, void|Callbackcb)

Description

Retrieve the list of APIs supported at this endpoint

Parameter params
Parameter cb

Module Web.Api.Google.Analytics


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Analytics API. See Web.Api.Api() for further information.

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

Class Web.Api.Google.Analytics.V3


Inheritparent

inherit Web.Api.Google.Api : parent


ConstantAPI_URI

protected constantstring Web.Api.Google.Analytics.V3.API_URI

Description

API base URI.


Variable_core
Variable_realtime
Variable_management

protectedCore Web.Api.Google.Analytics.V3._core
protectedRealTime Web.Api.Google.Analytics.V3._realtime
protectedManagement Web.Api.Google.Analytics.V3._management

Description

Internal singleton objects. Retrieve an instance via core, realtime and management.


Variablecore

Core Web.Api.Google.Analytics.V3.core

Description

Getter for the Core API

Note

Read only


Variablemanagement

Management Web.Api.Google.Analytics.V3.management

Description

Getter for the Management API

Note

Read only


Variablerealtime

RealTime Web.Api.Google.Analytics.V3.realtime

Description

Getter for the RealTime API

Note

Read only

Class Web.Api.Google.Analytics.V3.Core

Description

Interface to the Google Analytics core API


InheritMethod

inherit Method : Method


Methodget

mixedget(mappingparams, void|Callbackcb)

Description

Get data from the core api

Parameter params
Parameter cb

Class Web.Api.Google.Analytics.V3.Management

Description

Interface to the Google Analytics managment API


InheritMethod

inherit Method : Method


Methodaccount_summaries

mixedaccount_summaries(void|ParamsArgparams, void|Callbackcb)

Description

Get account summaries

Parameter params
Parameter cb

Class Web.Api.Google.Analytics.V3.RealTime

Description

Interface to the Google Analytics realtime API


InheritMethod

inherit Method : Method


Methodget

mixedget(mappingparams, void|Callbackcb)

Description

Get data from the realtime api

Parameter params
Parameter cb

Module Web.Api.Google.Plus


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Google+ API. See Web.Api.Api() for further information.

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

Class Web.Api.Google.Plus.V1


InheritApi

inherit Web.Api.Google.Api : Api


ConstantAPI_URI

protected constantstring Web.Api.Google.Plus.V1.API_URI

Description

API base URI.


Variable_people
Variable_activities

privatePeople Web.Api.Google.Plus.V1._people
privateActivities Web.Api.Google.Plus.V1._activities

Description

Internal singleton objects. Get an instance via people and activities.


Variableactivities

Activities Web.Api.Google.Plus.V1.activities

Description

Getter for the Activities object which has methods for all activities related Google+ API methods.

See also

https://developers.google.com/+/api/latest/activities

Note

Read only


Variablepeople

People Web.Api.Google.Plus.V1.people

Description

Getter for the People object which has methods for all people related Google+ API methods.

See also

https://developers.google.com/+/api/latest/people

Note

Read only

Class Web.Api.Google.Plus.V1.Activities

Description

Class implementing the Google+ Activities API. https://developers.google.com/+/api/latest/activities

Retreive an instance of this class through the activities property


InheritMethod

inherit Method : Method

Class Web.Api.Google.Plus.V1.People

Description

Class implementing the Google+ People API. https://developers.google.com/+/api/latest/people

Retreive an instance of this class through the Social.Google.Plus()->people property


InheritMethod

inherit Method : Method


Methodget

mappingget(void|stringuser_id, void|Callbackcb)

Description

Get info ablut a person.

Parameter user_id

If empty the currently authenticated user will be fetched.

Parameter cb

Callback for async request


Methodlist

mappinglist(void|stringuser_id, void|stringcollection, void|ParamsArgparams, void|Callbackcb)

Description

List all of the people in the specified collection.

Parameter user_id

If empty the currently authenticated user will be used.

Parameter collection

If empty "public" activities will be listed. Acceptable values are:

  • "public"

    The list of people who this user has added to one or more circles, limited to the circles visible to the requesting application.

Parameter params
"maxResult" : int

Max number of items ti list

"orderBy" : string

The order to return people in. Acceptable values are:

  • "alphabetical"

    Order the people by their display name.

  • "best"

    Order people based on the relevence to the viewer.

"pageToken" : string

The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of nextPageToken from the previous response.

Parameter cb

Callback for async request

Module Web.Api.Instagram

Description

Instagram API implementation. https://instagram.com/developer/


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Instagram API. See Web.Api.Api() for further information.

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

Class Web.Api.Instagram.V1

Description

Class for communicating with version 1 of the Instagram API.


Inheritparent

inherit Web.Api.Api : parent


ConstantAPI_URI

protected constantstring Web.Api.Instagram.V1.API_URI

Description

The URI to the Instagram API


Variable_any

privateAny Web.Api.Instagram.V1._any

Description

Singleton Any object. Will be instantiated first time requested.


Variable_comments

privateComments Web.Api.Instagram.V1._comments

Description

Singleton Comments object. Will be instantiated first time requested.


Variable_likes

privateLikes Web.Api.Instagram.V1._likes

Description

Singleton Likes object. Will be instantiated first time requested.


Variable_locations

privateLocations Web.Api.Instagram.V1._locations

Description

Singleton Locations object. Will be instantiated first time requested.


Variable_media

privateMedia Web.Api.Instagram.V1._media

Description

Singleton Media object. Will be instantiated first time requested.


Variable_tags

privateTags Web.Api.Instagram.V1._tags

Description

Singleton Tags object. Will be instantiated first time requested.


Variable_users

privateUsers Web.Api.Instagram.V1._users

Description

Singleton User object. Will be instantiated first time requested.


Variableany

Any Web.Api.Instagram.V1.any

Description

Getter for the Any object which can be used to query any method in the Instagram web api. The METHOD_PATH is set to / in this object.

Note

Read only


Variablecomments

Comments Web.Api.Instagram.V1.comments

Description

Getter for the Comments object which has methods for all comments related Instagram API methods.

See also

http://instagram.com/developer/endpoints/comments/

Note

Read only


Variablelikes

Likes Web.Api.Instagram.V1.likes

Description

Getter for the Likes object which has methods for all likes related Instagram API methods.

See also

http://instagram.com/developer/endpoints/likes/

Note

Read only


Variablelocations

Locations Web.Api.Instagram.V1.locations

Description

Getter for the Locations object which has methods for all locations related Instagram API methods.

See also

http://instagram.com/developer/endpoints/locations/

Note

Read only


Variablemedia

Media Web.Api.Instagram.V1.media

Description

Getter for the Media object which has methods for all media related Instagram API methods.

See also

http://instagram.com/developer/endpoints/media/

Note

Read only


Variabletags

Tags Web.Api.Instagram.V1.tags

Description

Getter for the Tags object which has methods for all tags related Instagram API methods.

See also

http://instagram.com/developer/endpoints/tags/

Note

Read only


Variableusers

Users Web.Api.Instagram.V1.users

Description

Getter for the Users object which has methods for all users related Instagram API methods.

See also

http://instagram.com/developer/endpoints/users/

Note

Read only


Methoddelete

mappingdelete(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic DELETE request to the Instagram API.

Parameter path

What to request. Like me, users/self, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodget

mappingget(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic GET request to the Instagram API.

Parameter path

What to request. Like me, users/self, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodpost

mappingpost(stringpath, void|ParamsArgparams, string|zerodata, void|Callbackcb)

Description

Make a generic POST request to the Instagram API.

Parameter path

What to request. Like me, users/self, [some_id]/something.

Parameter params
Parameter data

Ignored.

Parameter cb

Callback for async requests


Methodput

mappingput(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic PUT request to the Instagram API.

Parameter path

What to request. Like me, users/self, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests

Class Web.Api.Instagram.V1.Any

Description

A generic wrapper around Method. This will query the root of the API, and can be used to query methods not implemented in this module.


InheritMethod

inherit Method : Method


Methoddelete

mixeddelete(strings, void|ParamsArgp, void|Callbackcb)

Description

DELETE data

Parameter s

The path to the Instagram API to query

Parameter p

Parameters to the query

Parameter cb

Async callback


Methodget

mixedget(strings, void|ParamsArgp, void|Callbackcb)

Description

GET data

Parameter s

The path to the Instagram API to query

Parameter p

Parameters to the query

Parameter cb

Async callback


Methodpost

mixedpost(strings, void|ParamsArgp, string|zerodata, void|Callbackcb)

Description

POST data

Parameter s

The path to the Instagram API to query

Parameter p

Parameters to the query

Parameter cb

Async callback


Methodput

mixedput(strings, void|ParamsArgp, void|Callbackcb)

Description

PUT data

Parameter s

The path to the Instagram API to query

Parameter p

Parameters to the query

Parameter cb

Async callback

Class Web.Api.Instagram.V1.Comments

Description

Class implementing the Instagram Comments API. http://instagram.com/developer/endpoints/comments/

Retreive an instance of this class via the comments property.


InheritMethod

inherit Method : Method


Methodadd

mappingadd(stringmedia_id, stringcomment, void|Callbackcb)

Description

Get a full list of comments on a media.

Note

This method is not allowed by default. You have to contact Instagram in order to activate this method. http://bit.ly/instacomments

Note

Required scope: comments

Parameter media_id

The media to retreive comments for

Parameter cb

Callback for async mode


Methodlist

mappinglist(stringmedia_id, void|Callbackcb)

Description

Get a full list of comments on a media.

Note

Required scope: comments

Parameter media_id

The media to retreive comments for

Parameter cb

Callback for async mode


Methodremove

mappingremove(stringmedia_id, stringcomment_id, void|Callbackcb)

Description

Remove a comment either on the authenticated user's media or authored by the authenticated user.

Note

Required scope: comments

Parameter media_id

The media the comment is for

Parameter comment_id

The comment to remove

Parameter cb

Callback for async mode

Class Web.Api.Instagram.V1.Likes

Description

Class implementing the Instagram Likes API. http://instagram.com/developer/endpoints/likes/

Retreive an instance of this class via the likes property.


InheritMethod

inherit Method : Method


Methodadd

mappingadd(stringmedia_id, void|Callbackcb)

Description

Set a like on this media by the currently authenticated user.

See also

http://instagram.com/developer/endpoints/likes/#post_likes

Note

Required scope: likes

Parameter media_id
Parameter cb

Methodlist

mappinglist(stringmedia_id, void|Callbackcb)

Description

Get a list of users who have liked this media.

See also

http://instagram.com/developer/endpoints/likes/#get_media_likes

Note

Required scope: likes

Parameter media_id
Parameter cb

Methodremove

mappingremove(stringmedia_id, void|Callbackcb)

Description

Remove a like on this media by the currently authenticated user.

See also

http://instagram.com/developer/endpoints/likes/#delete_likes

Note

Required scope: likes

Parameter media_id
Parameter cb

Class Web.Api.Instagram.V1.Locations

Description

Class implementing the Instagram Likes API. http://instagram.com/developer/endpoints/likes/

Retreive an instance of this class via the locations property.


InheritMethod

inherit Method : Method


Methodlocation

mappinglocation(stringlocation_id, void|Callbackcb)

Description

Get information about a location.

See also

http://instagram.com/developer/endpoints/locations/#get_locations

Parameter location_id
Parameter cb

Methodrecent_media

mappingrecent_media(stringlocation_id, void|ParamsArgparams, void|Callbackcb)

Description

Get a list of recent media objects from a given location. May return a mix of both image and video types.

See also

http://instagram.com/developer/endpoints/locations/#get_locations_media_recent

Parameter location_id
Parameter params
"min_timestamp" : int

Return media after this UNIX timestamp

"min_id" : string

Return media before this min_id.

"max_id" : string

Return media after this max_id.

"max_timestamp" : int

Return media before this UNIX timestamp

Parameter cb

Methodsearch

mappingsearch(ParamsArgparams, void|Callbackcb)

Description

Search for a location by geographic coordinate.

See also

http://instagram.com/developer/endpoints/locations/#get_locations_search

Parameter params
"lat" : float

Latitude of the center search coordinate. If used, lng is required.

"distance" : int

Default is 1000m (distance=1000), max distance is 5000.

"lng" : float

Longitude of the center search coordinate. If used, lat is required.

"foursquare_v2_id" : string|int

Returns a location mapped off of a foursquare v2 api location id. If used, you are not required to use lat and lng.

"foursquare_id" : string|int

Returns a location mapped off of a foursquare v1 api location id. If used, you are not required to use lat and lng. Note that this method is deprecated; you should use the new foursquare IDs with V2 of their API.

Parameter cb

Class Web.Api.Instagram.V1.Media

Description

Class implementing the Instagram Media API. http://instagram.com/developer/endpoints/media/

Retreive an instance of this class via the media property


InheritMethod

inherit Method : Method


Methoditem

mappingitem(stringmedia_id, void|Callbackcb)

Description

Get information about a media object. The returned type key will allow you to differentiate between image and video media. Note: if you authenticate with an OAuth Token, you will receive the user_has_liked key which quickly tells you whether the current user has liked this media item.

See also

http://instagram.com/developer/endpoints/media/#get_media

Parameter media_id
Parameter cb

Callback function when in async mode


Methodpopular

mappingpopular(void|Callbackcb)

Description

Get a list of what media is most popular at the moment. Can return a mix of image and video types.

Parameter cb

Callback function when in async mode


Methodsearch

mappingsearch(void|ParamsArgparams, void|Callbackcb)

Description

Search for media in a given area. The default time span is set to 5 days. The time span must not exceed 7 days. Defaults time stamps cover the last 5 days. Can return mix of image and video types.

Parameter params

Can have:

"lat" : string|float

Latitude of the center search coordinate. If used, lng is required.

"min_timestamp" : int

A unix timestamp. All media returned will be taken later than this timestamp.

"lng" : string|float

Longitude of the center search coordinate. If used, lat is required.

"max_timestamp" : int

A unix timestamp. All media returned will be taken earlier than this timestamp.

"distance" : int

Default is 1km (distance=1000), max distance is 5km.

Parameter cb

Callback function when in async mode

Class Web.Api.Instagram.V1.Method

Description

Internal convenience class.


InheritMethod

inherit Web.Api.Api.Method : Method


Method_delete

protectedmixed_delete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_get

protectedmixed_get(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Method_post

protectedmixed_post(strings, void|ParamsArgp, string|zerodata, void|Callbackcb)

Description

Internal convenience method


Method_put

protectedmixed_put(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method

Class Web.Api.Instagram.V1.Tags

Description

Class implementing the Instagram Tags API. http://instagram.com/developer/endpoints/tags/

Retreive an instance of this class via the tags property.


InheritMethod

inherit Method : Method


Methodrecent

mappingrecent(stringtag_name, void|ParamsArgparams, void|Callbackcb)

Description

Get a list of recently tagged media. Note that this media is ordered by when the media was tagged with this tag, rather than the order it was posted. Use the max_tag_id and min_tag_id parameters in the pagination response to paginate through these objects. Can return a mix of image and video types.

See also

http://instagram.com/developer/endpoints/tags/#get_tags_media_recent

Parameter tag_name
Parameter params

Can be:

"min_id" : string

Return media before this min_id.

"max_id" : string

Return media after this max_id.

Parameter cb

Callback function when in async mode


Methodsearch

mappingsearch(stringtag_name, Callbackcb)

Description

Search for tags by name. Results are ordered first as an exact match, then by popularity. Short tags will be treated as exact matches.

See also

http://instagram.com/developer/endpoints/tags/#get_tags_search

Parameter tag_name
Parameter cb

Callback function when in async mode


Methodtag

mappingtag(stringtag_name, void|Callbackcb)

Description

Get information about a tag object.

See also

http://instagram.com/developer/endpoints/tags/#get_tags

Parameter tag_name
Parameter cb

Callback function when in async mode

Class Web.Api.Instagram.V1.Users

Description

Class implementing the Instagram Users API. http://instagram.com/developer/endpoints/users/

Retreive an instance of this class via the users property


InheritMethod

inherit Method : Method


Methodfeed

mappingfeed(void|ParamsArgparams, void|Callbackcb)

Description

Get the currently authenticated users feed. http://instagram.com/developer/endpoints/users/#get_users

Parameter params

Valida parameters are:

"count" : string|int

Number of items to return. Default is 20.

"min_id" : string

Return media later than this min_id

"max_id" : string

Return media earlier than this max_id

Parameter cb

Callback function when in async mode


Methodfollowed_by

mappingfollowed_by(string|voiduser_id, void|Callbackcb)

Description

Get the list of users this user is followed by.

Note

Required scope: relationships

See also

http://instagram.com/developer/endpoints/relationships/#get_users_followed_by

Parameter user_id
Parameter cb

Callback function when in async mode


Methodfollows

mappingfollows(void|stringuser_id, void|Callbackcb)

Description

Get the list of users this user follows.

Note

Required scope: relationships

See also

http://instagram.com/developer/endpoints/relationships/#get_users_follows

Parameter user_id
Parameter cb

Callback function when in async mode


Methodliked

mappingliked(void|ParamsArgparams, void|Callbackcb)

Description

See the authenticated user's list of media they've liked. May return a mix of both image and video types. Note: This list is ordered by the order in which the user liked the media. Private media is returned as long as the authenticated user has permission to view that media. Liked media lists are only available for the currently authenticated user.

http://instagram.com/developer/endpoints/users/#get_users_feed_liked

Parameter params

Valida parameters are:

"count" : string|int

Number of items to return. Default is 20.

"max_like_id" : string

Return media liked before this id.

Parameter cb

Callback function when in async mode


Methodrecent

mappingrecent(void|stringuid, void|ParamsArgparams, void|Callbackcb)

Description

Get the most recent media published by a user. May return a mix of both image and video types. http://instagram.com/developer/endpoints/users/get_users_media_recent

Parameter uid

An Instagram user ID

Parameter params

Valida parameters are:

"count" : string|int

Number of items to return. Default is 20.

"min_id" : string

Return media later than this min_id

"max_id" : string

Return media earlier than this max_id

"max_timestamp" : int

Return media before this UNIX timestamp.

"min_timestamp" : int

Return media after this UNIX timestamp.

Parameter cb

Callback function when in async mode


Methodrelationship

mappingrelationship(stringuser_id, void|Callbackcb)

Description

Get information about a relationship to another user.

Note

Required scope: relationships

See also

http://instagram.com/developer/endpoints/relationships/#get_relationship

Parameter user_id
Parameter cb

Callback function when in async mode


Methodrelationship_change

mappingrelationship_change(stringuser_id, stringaction, void|Callbackcb)

Description

Modify the relationship between the current user and the target user.

Note

Required scope: relationships

Parameter user_id

The user to change the relationship to

Parameter action

How to change the relationship. Can be:

  • "follow"
  • "unfollow"
  • "block"
  • "unblock"
  • "approve"
  • "deny"
Parameter cb

Callback function if in async mode


Methodrequested_by

mappingrequested_by(void|Callbackcb)

Description

List the users who have requested this user's permission to follow.

Note

Required scope: relationships

See also

http://instagram.com/developer/endpoints/relationships/#get_incoming_requests

Parameter cb

Callback function when in async mode


Methodsearch

mappingsearch(stringquery, void|intcount, void|Callbackcb)

Description

Search for a user by name.

http://instagram.com/developer/endpoints/users/#get_users_search

Parameter query

A query string.

Parameter count

Max number of users to return

Parameter cb

Callback function when in async mode


Methoduser

mappinguser(void|stringuid, void|Callbackcb)

Description

Get basic information about a user.

Parameter uid

An Instagram user ID. If not given the currently authenticated user will be fetched

Parameter cb

Callback function when in async mode

Module Web.Api.Linkedin


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Github API. See Web.Api.Api() for further information about the arguments

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

Class Web.Api.Linkedin.V1


Inheritparent

inherit Web.Api.Api : parent


ConstantAPI_URI

constantstring Web.Api.Linkedin.V1.API_URI

Description

The base uri to the API


Variableany

Any Web.Api.Linkedin.V1.any

Description

Getter for the Any object which is a generic object for making request to the Linkedin API

See also

Any

Note

Read only


Methoddefault_params

protectedmappingdefault_params()

Description

Default parameters that goes with every call


Methoddelete

mappingdelete(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic DELETE request to the Linkedin API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodget

mappingget(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic GET request to the Linkedin API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodpost

mappingpost(stringpath, void|ParamsArgparams, void|stringdata, void|Callbackcb)

Description

Make a generic POST request to the Linkedin API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter data
Parameter cb

Callback for async requests


Methodput

mappingput(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic PUT request to the Linkedin API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests

Class Web.Api.Linkedin.V1.Any

Description

A generic wrapper around Method


InheritMethod

inherit Method : Method

Class Web.Api.Linkedin.V1.Method


InheritMethod

inherit Web.Api.Api.Method : Method


Methoddelete

mixeddelete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodget

mixedget(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodpost

mixedpost(strings, void|ParamsArgp, void|stringdata, void|Callbackcb)

Description

Internal convenience method


Methodput

mixedput(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method

Module Web.Api.Twitter


Method`()

protectedthis_program`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiates the default Twitter API. See https://dev.twitter.com/rest/public for further information.

Parameter client_id

Your application key/id

Parameter client_secret

Your application secret

Parameter redirect_uri

The redirect URI after an authentication

Parameter scope

The application scopes to grant access to

See also

Web.Api.Api

Class Web.Api.Twitter.V1_1


Inheritparent

inherit Web.Api.Api : parent


Variableany

Any Web.Api.Twitter.V1_1.any

Description

Getter for the Any object which is a generic object for making request to the Twitter API

See also

Any

Note

Read only


Methoddefault_params

protectedmappingdefault_params()

Description

Default parameters that goes with every call


Methoddelete

mappingdelete(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic DELETE request to the Twitter API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodget

mappingget(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic GET request to the Twitter API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests


Methodpost

mappingpost(stringpath, void|ParamsArgparams, void|stringdata, void|Callbackcb)

Description

Make a generic POST request to the Twitter API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter data
Parameter cb

Callback for async requests


Methodput

mappingput(stringpath, void|ParamsArgparams, void|Callbackcb)

Description

Make a generic PUT request to the Twitter API.

Parameter path

What to request. Like me, me/pictures, [some_id]/something.

Parameter params
Parameter cb

Callback for async requests

Class Web.Api.Twitter.V1_1.Any

Description

A generic wrapper around Method


InheritMethod

inherit Method : Method

Class Web.Api.Twitter.V1_1.Method


InheritMethod

inherit Web.Api.Api.Method : Method


Methoddelete

mixeddelete(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodget

mixedget(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method


Methodpost

mixedpost(strings, void|ParamsArgp, void|stringdata, void|Callbackcb)

Description

Internal convenience method


Methodput

mixedput(strings, void|ParamsArgp, void|Callbackcb)

Description

Internal convenience method

Module Web.Auth

Description

Various authentication modules and classes.

constant GOOGLE_KEY ="some-key-911bnn5s.apps.googleusercontent.com";constant GOOGLE_SECRET ="5arQDOugDrtIOVklkIet2q2i";Web.Auth.Google.Authorization auth;int main(int argc,array(string) argv){
  auth =Web.Auth.Google.Authorization(GOOGLE_KEY, GOOGLE_SECRET,"http://localhost");// The generated access token will be saved on disk.string progname = replace(sprintf("%O", object_program(auth)),".","_");string cookie = progname +".cookie";// If the cookie exists, set the authentication from the saved valuesif(Stdio.exist(cookie)){
    auth->set_from_cookie(Stdio.read_file(cookie));}// Not authenticated, can mean no previous authentication is done, or that// the authentication has expired. Some services have persistent access tokens// some don'tif(!auth->is_authenticated()){// Try to renew the access token of it's renewableif(auth->is_renewable()){
      write("Trying to refresh token...\n");string data = auth->refresh_access_token();Stdio.write_file(cookie, data);}else{// No argument, start the authentication processif(argc == 1){// Get the uri to the authentication pagestring uri = auth->get_auth_uri();

        write("Opening \"%s\" in browser.\nCopy the contents of the address ""bar into here: ",Standards.URI(uri));

        sleep(1);string open_app;// Macif(Process.run(({"which","open"}))->exitcode == 0){
          open_app ="open";}// Linuxelseif(Process.run(({"which","xdg-open"}))->exitcode == 0){
          open_app ="xdg-open";}// ???else{
          open_app ="open";}Process.create_process(({ open_app, uri }));// Wait for the user to paste the string from the address barstring resp =Stdio.Readline()->read();mapping p =Web.Auth.query_to_mapping(Standards.URI(resp)->query);string code;// This is if the service is OAuth1if(p->oauth_token){
          auth->set_authentication(p->oauth_token);
          code = p->oauth_verifier;}// OAuth2else{
          code = p->code;}// Get the access token and save the response to disk for later use.string data = auth->request_access_token(code);Stdio.write_file(cookie, data);}// If the user gives the access code from command line.else{string data = auth->request_access_token(argv[1]);Stdio.write_file(cookie, data);}}}if(!auth->is_authenticated()){
    werror("Authentication failed");}else{
    write("Congratulations you are now authenticated\n");}}

Methodquery_to_mapping

mappingquery_to_mapping(stringquery)

Description

Turns a query string into a mapping

Parameter query

Class Web.Auth.Facebook

Description

This class is used to OAuth2 authenticate agains Facebook


InheritClient

inherit .OAuth2.Client : Client

Enum Web.Auth.Facebook.Scopes


ConstantSCOPE_EMAIL
ConstantSCOPE_PUBLISH_ACTIONS
ConstantSCOPE_ABOUT_ME
ConstantSCOPE_ACTIONS_BOOKS
ConstantSCOPE_ACTIONS_MUSIC
ConstantSCOPE_ACTIONS_NEWS
ConstantSCOPE_ACTIONS_VIDEO
ConstantSCOPE_ACTIVITIES
ConstantSCOPE_BIRTHDAY
ConstantSCOPE_EDUCATION_HISTORY
ConstantSCOPE_EVENTS
ConstantSCOPE_FRIENDS
ConstantSCOPE_GAMES_ACTIVITY
ConstantSCOPE_GROUPS
ConstantSCOPE_HOMETOWN
ConstantSCOPE_INTERESTS
ConstantSCOPE_LIKES
ConstantSCOPE_LOCATION
ConstantSCOPE_NOTES
ConstantSCOPE_PHOTOS
ConstantSCOPE_QUESTIONS
ConstantSCOPE_RELATIONSHIP_DETAILS
ConstantSCOPE_RELATIONSHIPS
ConstantSCOPE_RELIGION_POLITICS
ConstantSCOPE_STATUS
ConstantSCOPE_SUBSCRIPTIONS
ConstantSCOPE_VIDEOS
ConstantSCOPE_WEBSITE
ConstantSCOPE_WORK_HISTORY

constant Web.Auth.Facebook.SCOPE_EMAIL
constant Web.Auth.Facebook.SCOPE_PUBLISH_ACTIONS
constant Web.Auth.Facebook.SCOPE_ABOUT_ME
constant Web.Auth.Facebook.SCOPE_ACTIONS_BOOKS
constant Web.Auth.Facebook.SCOPE_ACTIONS_MUSIC
constant Web.Auth.Facebook.SCOPE_ACTIONS_NEWS
constant Web.Auth.Facebook.SCOPE_ACTIONS_VIDEO
constant Web.Auth.Facebook.SCOPE_ACTIVITIES
constant Web.Auth.Facebook.SCOPE_BIRTHDAY
constant Web.Auth.Facebook.SCOPE_EDUCATION_HISTORY
constant Web.Auth.Facebook.SCOPE_EVENTS
constant Web.Auth.Facebook.SCOPE_FRIENDS
constant Web.Auth.Facebook.SCOPE_GAMES_ACTIVITY
constant Web.Auth.Facebook.SCOPE_GROUPS
constant Web.Auth.Facebook.SCOPE_HOMETOWN
constant Web.Auth.Facebook.SCOPE_INTERESTS
constant Web.Auth.Facebook.SCOPE_LIKES
constant Web.Auth.Facebook.SCOPE_LOCATION
constant Web.Auth.Facebook.SCOPE_NOTES
constant Web.Auth.Facebook.SCOPE_PHOTOS
constant Web.Auth.Facebook.SCOPE_QUESTIONS
constant Web.Auth.Facebook.SCOPE_RELATIONSHIP_DETAILS
constant Web.Auth.Facebook.SCOPE_RELATIONSHIPS
constant Web.Auth.Facebook.SCOPE_RELIGION_POLITICS
constant Web.Auth.Facebook.SCOPE_STATUS
constant Web.Auth.Facebook.SCOPE_SUBSCRIPTIONS
constant Web.Auth.Facebook.SCOPE_VIDEOS
constant Web.Auth.Facebook.SCOPE_WEBSITE
constant Web.Auth.Facebook.SCOPE_WORK_HISTORY


ConstantSCOPE_ADS_MANAGEMENT
ConstantSCOPE_ADS_READ
ConstantSCOPE_CREATE_EVENT
ConstantSCOPE_CREATE_NOTE
ConstantSCOPE_EXPORT_STREAM
ConstantSCOPE_FRIENDS_ONLINE_PRESENCE
ConstantSCOPE_MANAGE_FRIENDLISTS
ConstantSCOPE_MANAGE_NOTIFICATIONS
ConstantSCOPE_MANAGE_PAGES
ConstantSCOPE_PHOTO_UPLOAD
ConstantSCOPE_PUBLISH_STREAM
ConstantSCOPE_READ_FRIENDLISTS
ConstantSCOPE_READ_INSIGHTS
ConstantSCOPE_READ_MAILBOX
ConstantSCOPE_READ_PAGE_MAILBOXES
ConstantSCOPE_READ_REQUESTS
ConstantSCOPE_READ_STREAM
ConstantSCOPE_RSVP_EVENT
ConstantSCOPE_SHARE_ITEM
ConstantSCOPE_SMS
ConstantSCOPE_STATUS_UPDATE
ConstantSCOPE_USER_ONLINE_PRESENCE
ConstantSCOPE_VIDEO_UPLOAD
ConstantSCOPE_XMPP_LOGIN

constant Web.Auth.Facebook.SCOPE_ADS_MANAGEMENT
constant Web.Auth.Facebook.SCOPE_ADS_READ
constant Web.Auth.Facebook.SCOPE_CREATE_EVENT
constant Web.Auth.Facebook.SCOPE_CREATE_NOTE
constant Web.Auth.Facebook.SCOPE_EXPORT_STREAM
constant Web.Auth.Facebook.SCOPE_FRIENDS_ONLINE_PRESENCE
constant Web.Auth.Facebook.SCOPE_MANAGE_FRIENDLISTS
constant Web.Auth.Facebook.SCOPE_MANAGE_NOTIFICATIONS
constant Web.Auth.Facebook.SCOPE_MANAGE_PAGES
constant Web.Auth.Facebook.SCOPE_PHOTO_UPLOAD
constant Web.Auth.Facebook.SCOPE_PUBLISH_STREAM
constant Web.Auth.Facebook.SCOPE_READ_FRIENDLISTS
constant Web.Auth.Facebook.SCOPE_READ_INSIGHTS
constant Web.Auth.Facebook.SCOPE_READ_MAILBOX
constant Web.Auth.Facebook.SCOPE_READ_PAGE_MAILBOXES
constant Web.Auth.Facebook.SCOPE_READ_REQUESTS
constant Web.Auth.Facebook.SCOPE_READ_STREAM
constant Web.Auth.Facebook.SCOPE_RSVP_EVENT
constant Web.Auth.Facebook.SCOPE_SHARE_ITEM
constant Web.Auth.Facebook.SCOPE_SMS
constant Web.Auth.Facebook.SCOPE_STATUS_UPDATE
constant Web.Auth.Facebook.SCOPE_USER_ONLINE_PRESENCE
constant Web.Auth.Facebook.SCOPE_VIDEO_UPLOAD
constant Web.Auth.Facebook.SCOPE_XMPP_LOGIN


ConstantSCOPE_FRIENDS_ABOUT_ME
ConstantSCOPE_FRIENDS_ACTIONS_BOOKS
ConstantSCOPE_FRIENDS_ACTIONS_MUSIC
ConstantSCOPE_FRIENDS_ACTIONS_NEWS
ConstantSCOPE_FRIENDS_ACTIONS_VIDEO
ConstantSCOPE_FRIENDS_ACTIVITIES
ConstantSCOPE_FRIENDS_BIRTHDAY
ConstantSCOPE_FRIENDS_EDUCATION_HISTORY
ConstantSCOPE_FRIENDS_EVENTS
ConstantSCOPE_FRIENDS_GAMES_ACTIVITY
ConstantSCOPE_FRIENDS_GROUPS
ConstantSCOPE_FRIENDS_HOMETOWN
ConstantSCOPE_FRIENDS_INTERESTS
ConstantSCOPE_FRIENDS_LIKES
ConstantSCOPE_FRIENDS_LOCATION
ConstantSCOPE_FRIENDS_NOTES
ConstantSCOPE_FRIENDS_PHOTOS
ConstantSCOPE_FRIENDS_QUESTIONS
ConstantSCOPE_FRIENDS_RELATIONSHIP_DETAILS
ConstantSCOPE_FRIENDS_RELATIONSHIPS
ConstantSCOPE_FRIENDS_RELIGION_POLITICS
ConstantSCOPE_FRIENDS_STATUS
ConstantSCOPE_FRIENDS_SUBSCRIPTIONS
ConstantSCOPE_FRIENDS_VIDEOS
ConstantSCOPE_FRIENDS_WEBSITE
ConstantSCOPE_FRIENDS_WORK_HISTORY

constant Web.Auth.Facebook.SCOPE_FRIENDS_ABOUT_ME
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_BOOKS
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_MUSIC
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_NEWS
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_VIDEO
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIVITIES
constant Web.Auth.Facebook.SCOPE_FRIENDS_BIRTHDAY
constant Web.Auth.Facebook.SCOPE_FRIENDS_EDUCATION_HISTORY
constant Web.Auth.Facebook.SCOPE_FRIENDS_EVENTS
constant Web.Auth.Facebook.SCOPE_FRIENDS_GAMES_ACTIVITY
constant Web.Auth.Facebook.SCOPE_FRIENDS_GROUPS
constant Web.Auth.Facebook.SCOPE_FRIENDS_HOMETOWN
constant Web.Auth.Facebook.SCOPE_FRIENDS_INTERESTS
constant Web.Auth.Facebook.SCOPE_FRIENDS_LIKES
constant Web.Auth.Facebook.SCOPE_FRIENDS_LOCATION
constant Web.Auth.Facebook.SCOPE_FRIENDS_NOTES
constant Web.Auth.Facebook.SCOPE_FRIENDS_PHOTOS
constant Web.Auth.Facebook.SCOPE_FRIENDS_QUESTIONS
constant Web.Auth.Facebook.SCOPE_FRIENDS_RELATIONSHIP_DETAILS
constant Web.Auth.Facebook.SCOPE_FRIENDS_RELATIONSHIPS
constant Web.Auth.Facebook.SCOPE_FRIENDS_RELIGION_POLITICS
constant Web.Auth.Facebook.SCOPE_FRIENDS_STATUS
constant Web.Auth.Facebook.SCOPE_FRIENDS_SUBSCRIPTIONS
constant Web.Auth.Facebook.SCOPE_FRIENDS_VIDEOS
constant Web.Auth.Facebook.SCOPE_FRIENDS_WEBSITE
constant Web.Auth.Facebook.SCOPE_FRIENDS_WORK_HISTORY

Class Web.Auth.Github

Description

This class is used to OAuth2 authenticate against Github


InheritClient

inherit .OAuth2.Client : Client

Enum Web.Auth.Github.Scopes


ConstantSCOPE_REPO
ConstantSCOPE_GIST
ConstantSCOPE_USER
ConstantSCOPE_USER_EMAIL
ConstantSCOPE_USER_FOLLOW
ConstantSCOPE_PUBLIC_REPO
ConstantSCOPE_REPO_DEPLOYMENT
ConstantSCOPE_REPO_STATUS
ConstantSCOPE_DELETE_REPO
ConstantSCOPE_NOTIFICATIONS
ConstantSCOPE_READ_REPO_HOOK
ConstantSCOPE_WRITE_REPO_HOOK
ConstantSCOPE_ADMIN_REPO_HOOK
ConstantSCOPE_READ_ORG
ConstantSCOPE_WRITE_ORG
ConstantSCOPE_ADMIN_ORG
ConstantSCOPE_READ_PUBLIC_KEY
ConstantSCOPE_WRITE_PUBLIC_KEY
ConstantSCOPE_ADMIN_PUBLIC_KEY

constant Web.Auth.Github.SCOPE_REPO
constant Web.Auth.Github.SCOPE_GIST
constant Web.Auth.Github.SCOPE_USER
constant Web.Auth.Github.SCOPE_USER_EMAIL
constant Web.Auth.Github.SCOPE_USER_FOLLOW
constant Web.Auth.Github.SCOPE_PUBLIC_REPO
constant Web.Auth.Github.SCOPE_REPO_DEPLOYMENT
constant Web.Auth.Github.SCOPE_REPO_STATUS
constant Web.Auth.Github.SCOPE_DELETE_REPO
constant Web.Auth.Github.SCOPE_NOTIFICATIONS
constant Web.Auth.Github.SCOPE_READ_REPO_HOOK
constant Web.Auth.Github.SCOPE_WRITE_REPO_HOOK
constant Web.Auth.Github.SCOPE_ADMIN_REPO_HOOK
constant Web.Auth.Github.SCOPE_READ_ORG
constant Web.Auth.Github.SCOPE_WRITE_ORG
constant Web.Auth.Github.SCOPE_ADMIN_ORG
constant Web.Auth.Github.SCOPE_READ_PUBLIC_KEY
constant Web.Auth.Github.SCOPE_WRITE_PUBLIC_KEY
constant Web.Auth.Github.SCOPE_ADMIN_PUBLIC_KEY

Class Web.Auth.Instagram

Description

This class is used to OAuth2 authenticate agains Instagram


InheritClient

inherit .OAuth2.Client : Client


ConstantOAUTH_AUTH_URI

constantstring Web.Auth.Instagram.OAUTH_AUTH_URI

Description

Instagram authorization URI


ConstantOAUTH_TOKEN_URI

constantstring Web.Auth.Instagram.OAUTH_TOKEN_URI

Description

Instagram request access token URI


Variable_scope

protectedstring Web.Auth.Instagram._scope

Description

Default scope


Variablevalid_scopes

protectedmultiset(string) Web.Auth.Instagram.valid_scopes

Description

Valid Instagram scopes

Class Web.Auth.Linkedin

Description

This class is used to OAuth2 authenticate against LinkedIn


InheritClient

inherit .OAuth2.Client : Client


ConstantDEFAULT_SCOPE

protected constant Web.Auth.Linkedin.DEFAULT_SCOPE

Description

Default scope to use if none is set explicitly


ConstantSTATE

protected constantint Web.Auth.Linkedin.STATE

Description

Adds the state parameter to the request which will have the value of a random string

Enum Web.Auth.Linkedin.Scopes


ConstantSCOPE_R_BASIC
ConstantSCOPE_R_NETWORK
ConstantSCOPE_RW_GROUPS
ConstantSCOPE_R_FULLPROFILE
ConstantSCOPE_R_CONTACTINFO
ConstantSCOPE_W_MESSAGES
ConstantSCOPE_R_EMAILADDRESS
ConstantSCOPE_RW_NUS

constant Web.Auth.Linkedin.SCOPE_R_BASIC
constant Web.Auth.Linkedin.SCOPE_R_NETWORK
constant Web.Auth.Linkedin.SCOPE_RW_GROUPS
constant Web.Auth.Linkedin.SCOPE_R_FULLPROFILE
constant Web.Auth.Linkedin.SCOPE_R_CONTACTINFO
constant Web.Auth.Linkedin.SCOPE_W_MESSAGES
constant Web.Auth.Linkedin.SCOPE_R_EMAILADDRESS
constant Web.Auth.Linkedin.SCOPE_RW_NUS

Class Web.Auth.Param

Description

Representation of a parameter.

Many Social web services use a RESTful communication and have similiar API's. This class is suitable for many RESTful web services and if this class doesn't suite a particular service, just inherit this class and rewrite the behaviour where needed.

See also

Params


Variablename

protectedstring Web.Auth.Param.name

Description

The name of the parameter


Variablevalue

protectedstring Web.Auth.Param.value

Description

The value of the parameter


Method_sprintf

stringsprintf(stringformat, ... Web.Auth.Paramarg ... )

Description

String format method

Parameter t

Method`<

bool res = Web.Auth.Param() < other

Description

Checks if this object is less than other

Parameter other

Method`==

bool res = Web.Auth.Param() == other

Description

Comparer method. Checks if other equals this object

Parameter other

Method`>

bool res = Web.Auth.Param() > other

Description

Checks if this object is greater than other

Parameter other

Methodcreate

Web.Auth.ParamWeb.Auth.Param(stringname, mixedvalue)

Description

Creates a new instance of Param

Parameter name
Parameter value

Methodget_name

stringget_name()

Description

Getter for the parameter name


Methodget_value

stringget_value()

Description

Getter for the parameter value


Methodlow_set_value

privatevoidlow_set_value(stringv)

Description

Makes sure v to set as value is in UTF-8 encoding

Parameter v

Methodname_value

stringname_value()

Description

Returns the name and value as querystring key/value pair


Methodname_value_encoded

stringname_value_encoded()

Description

Same as name_value() except this URL encodes the value.


Methodset_name

voidset_name(stringname)

Description

Setter for the parameter name

Parameter name

Methodset_value

voidset_value(mixedvalue)

Description

Setter for the parameter value

Parameter value

Class Web.Auth.Params

Description

Parameter collection class

See also

Param


Variableparams

protectedarray(Param) Web.Auth.Params.params

Description

The parameters.


Method_indices

array(string) indices(Web.Auth.Paramsarg)

Description

Parameter keys


Method_sprintf

stringsprintf(stringformat, ... Web.Auth.Paramsarg ... )

Description

String format method

Parameter t

Method_values

array(string) values(Web.Auth.Paramsarg)

Description

Parameter values


Method`+

this_program res = Web.Auth.Params() + p

Description

Add p to the array of Parameters

Parameter p
Returns

A new Params object


Method`-

this_program res = Web.Auth.Params() - p

Description

Remove p from the Parameters array of the current object.

Parameter p

Method`[]

Param|zero res = Web.Auth.Params()[ key ]

Description

Index lookup

Parameter key

The name of a Paramerter to find.


Methodadd_mapping

this_programadd_mapping(mappingvalue)

Description

Add a mapping of key/value pairs to the current instance

Parameter value
Returns

The object being called


Methodcast

(int)Web.Auth.Params()
(float)Web.Auth.Params()
(string)Web.Auth.Params()
(array)Web.Auth.Params()
(mapping)Web.Auth.Params()
(multiset)Web.Auth.Params()

Description

Casting method

Parameter how

Methodclone

this_programclone()

Description

Clone the current instance


Methodcreate

Web.Auth.ParamsWeb.Auth.Params(Param ... args)

Description

Creates a new instance of Params

Parameter args

Methodget_params

array(Param) get_params()

Description

Returns the array of Parameters


Methodsign

stringsign(stringsecret)

Description

Sign the parameters

Parameter secret

The API secret


Methodto_mapping

mapping(string:mixed) to_mapping()

Description

Turns the parameters into a mapping


Methodto_query

stringto_query()

Description

Turns the parameters into a query string

Class Web.Auth.Tumblr

Description

Tumblr authentication class


InheritAuthentication

inherit .OAuth.Authentication : Authentication


ConstantACCESS_TOKEN_URL

constantstring Web.Auth.Tumblr.ACCESS_TOKEN_URL

Description

The endpoint to send request for an access token


ConstantREQUEST_TOKEN_URL

constantstring Web.Auth.Tumblr.REQUEST_TOKEN_URL

Description

The endpoint to send request for a request token


ConstantUSER_AUTH_URL

constantstring Web.Auth.Tumblr.USER_AUTH_URL

Description

The enpoint to redirect to when authenticating an application

Class Web.Auth.Twitter

Description

Twitter authentication class


InheritAuthentication

inherit Web.Auth.OAuth.Authentication : Authentication


ConstantACCESS_TOKEN_URL

constantstring Web.Auth.Twitter.ACCESS_TOKEN_URL

Description

The endpoint to send request for an access token


ConstantREQUEST_TOKEN_URL

constantstring Web.Auth.Twitter.REQUEST_TOKEN_URL

Description

The endpoint to send request for a request token


ConstantUSER_AUTH_URL

constantstring Web.Auth.Twitter.USER_AUTH_URL

Description

The enpoint to redirect to when authenticating an application

Module Web.Auth.Google

Description

Google authentication classes.

Class Web.Auth.Google.Analytics

Description

Google Analytics authorization class


InheritAuthorization

inherit Authorization : Authorization


ConstantSCOPE_RO
ConstantSCOPE_RW
ConstantSCOPE_EDIT
ConstantSCOPE_MANAGE_USERS
ConstantSCOPE_MANAGE_USERS_RO

constantstring Web.Auth.Google.Analytics.SCOPE_RO
constantstring Web.Auth.Google.Analytics.SCOPE_RW
constantstring Web.Auth.Google.Analytics.SCOPE_EDIT
constantstring Web.Auth.Google.Analytics.SCOPE_MANAGE_USERS
constantstring Web.Auth.Google.Analytics.SCOPE_MANAGE_USERS_RO

Description

Authentication scopes


Variable_scope

protectedstring Web.Auth.Google.Analytics._scope

Description

Default scope


Variablevalid_scopes

multiset(string) Web.Auth.Google.Analytics.valid_scopes

Description

All valid scopes

Class Web.Auth.Google.Authorization

Description

Default Google authorization class


InheritClient

inherit Web.Auth.OAuth2.Client : Client


ConstantOAUTH_AUTH_URI

constantstring Web.Auth.Google.Authorization.OAUTH_AUTH_URI


ConstantSCOPE_EMAIL

constantstring Web.Auth.Google.Authorization.SCOPE_EMAIL


ConstantSCOPE_OPENID

constantstring Web.Auth.Google.Authorization.SCOPE_OPENID


ConstantSCOPE_PROFILE

constantstring Web.Auth.Google.Authorization.SCOPE_PROFILE


Variablevalid_scopes

multiset(string) Web.Auth.Google.Authorization.valid_scopes

Description

All valid scopes

Class Web.Auth.Google.Plus

Description

Google+ authorization class


InheritAuthorization

inherit Authorization : Authorization


ConstantSCOPE_ME
ConstantSCOPE_LOGIN

constantstring Web.Auth.Google.Plus.SCOPE_ME
constantstring Web.Auth.Google.Plus.SCOPE_LOGIN

Description

Authentication scopes


Variable_scope

protectedstring Web.Auth.Google.Plus._scope

Description

Default scope


Variablevalid_scopes

protectedmultiset(string) Web.Auth.Google.Plus.valid_scopes

Description

All valid scopes

Module Web.Auth.OAuth

Description

OAuth module

Example

importWeb.Auth.OAuth;string endpoint ="http://twitter.com/users/show.xml";

 Consumer consumer = Consumer(my_consumer_key, my_consumer_secret);
 Token    token    = Token(my_access_token_key, my_access_token_secret);
 Params   params   = Params(Param("user_id", 12345));
 Request  request  = request(consumer, token, params);

 request->sign_request(Signature.HMAC_SHA1, consumer, token);Protocols.HTTP.Query query = request->submit();if(query->status != 200)
   error("Bad response status: %d\n", query->status);

 werror("Data is: %s\n", query->data());

ConstantCALLBACK_KEY

constantstring Web.Auth.OAuth.CALLBACK_KEY

Description

Query string variable name for a callback URL.


ConstantCONSUMER_KEY_KEY

constantstring Web.Auth.OAuth.CONSUMER_KEY_KEY

Description

Query string variable name for the consumer key.


ConstantNONCE_KEY

constantstring Web.Auth.OAuth.NONCE_KEY

Description

Query string variable name for the nonce.


ConstantSIGNATURE_KEY

constantstring Web.Auth.OAuth.SIGNATURE_KEY

Description

Query string variable name for the signature.


ConstantSIGNATURE_METHOD_KEY

constantstring Web.Auth.OAuth.SIGNATURE_METHOD_KEY

Description

Query string variable name for the signature method.


ConstantTIMESTAMP_KEY

constantstring Web.Auth.OAuth.TIMESTAMP_KEY

Description

Query string variable name for the timestamp.


ConstantTOKEN_KEY

constantstring Web.Auth.OAuth.TOKEN_KEY

Description

Query string variable name for the token key.


ConstantTOKEN_SECRET_KEY

constantstring Web.Auth.OAuth.TOKEN_SECRET_KEY

Description

Query string variable name for the token secret.


ConstantVERSION

constantstring Web.Auth.OAuth.VERSION

Description

Verion


ConstantVERSION_KEY

constantstring Web.Auth.OAuth.VERSION_KEY

Description

Query string variable name for the version.


Methodget_default_params

Paramsget_default_params(Consumerconsumer, Tokentoken)

Description

Returns the default params for authentication/signing.


Methodnonce

stringnonce()

Description

Generates a nonce.


Methodnormalize_uri

stringnormalize_uri(string|Standards.URIuri)

Description

Normalizes uri

Parameter uri

A string or Standards.URI.


Methodquery_to_params

Paramsquery_to_params(string|Standards.URI|mappingq)

Description

Converts a query string, or a mapping, into a Params object.


Methodrequest

Requestrequest(string|Standards.URIuri, Consumerconsumer, Tokentoken, void|Paramsparams, void|stringhttp_method)

Description

Helper method to create a Request object.

Throws

An error if consumer is null.

Parameter http_method

Defaults to GET.

Class Web.Auth.OAuth.Authentication

Description

The purpose of this class is to streamline OAuth1 with OAuth2. This class will not do much on it's own, since its purpose is to be inherited by some other class implementing a specific authorization service.


Inheritoauth

inherit .Client : oauth


Inheritoauth2

inherit Web.Auth.OAuth2.Client : oauth2


ConstantACCESS_TOKEN_URL

constantstring Web.Auth.OAuth.Authentication.ACCESS_TOKEN_URL

Description

The endpoint to send request for an access token.


ConstantREQUEST_TOKEN_URL

constantstring Web.Auth.OAuth.Authentication.REQUEST_TOKEN_URL

Description

The endpoint to send request for a request token.


ConstantUSER_AUTH_URL

constantstring Web.Auth.OAuth.Authentication.USER_AUTH_URL

Description

The enpoint to redirect to when authorize an application.


Methodcall

stringcall(string|Standards.URIurl, void|mapping|.Paramsargs, void|stringmethod)

Description

Does the low level HTTP call to a service.

Throws

An error if HTTP status != 200

Parameter url

The full address to the service e.g: http://twitter.com/direct_messages.xml

Parameter args

Arguments to send with the request

Parameter mehod

The HTTP method to use


Methodcreate

Web.Auth.OAuth.AuthenticationWeb.Auth.OAuth.Authentication(stringclient_id, stringclient_secret, void|stringredir, void|string|array(string)|multiset(string) scope)

Description

Creates an OAuth object.

Parameter client_id

The application ID.

Parameter client_secret

The application secret.

Parameter redirect_uri

Where the authorization page should redirect back to. This must be a fully qualified domain name. This can be set/overridden in get_request_token().

Parameter scope

Extended permissions to use for this authentication. This can be set/overridden in get_auth_uri().


Methodget_access_token

.Tokenget_access_token(void|stringoauth_verifier)

Description

Fetches an access token.


Methodget_auth_uri

stringget_auth_uri(void|mappingargs)


Methodget_request_token

.Tokenget_request_token(void|string|Standards.URIcallback_uri, void|boolforce_login)

Description

Fetches a request token.

Parameter callback_uri

Overrides the callback uri in the application settings.

Parameter force_login

If 1 forces the user to provide its credentials at the Twitter login page.


Methodis_authenticated

boolis_authenticated()

Description

Returns true if authenticated.


Methodlow_get_access_token

protectedstringlow_get_access_token(void|stringoauth_verifier)

Description

Fetches an access token.


Methodnormalize_method

protectedstringnormalize_method(stringmethod)

Description

Normalizes and verifies the HTTP method to be used in a HTTP call.


Methodparse_error_xml

mappingparse_error_xml(stringxml)

Description

Parses an error xml tree.

Returns

A mapping:

"request" : string
"error" : string

Methodrequest_access_token

stringrequest_access_token(stringcode)

Description

Same as get_access_token except this returns a string to comply with the OAuth2 authentication process.


Methodset_authentication

voidset_authentication(stringkey, void|stringsecret)

Description

Set authentication.


Methodset_from_cookie

this_programset_from_cookie(stringencoded_value)

Description

Populate this object with the result from request_access_token().

Returns

The object being called.

Class Web.Auth.OAuth.Client

Description

OAuth client class.

Note

This class is of no use by it self. It's intended to be inherited by classes that uses OAuth authorization.


Variableaccess_token_url

protectedstring Web.Auth.OAuth.Client.access_token_url

Description

The endpoint to send request for an access token.


Variableconsumer

protectedConsumer Web.Auth.OAuth.Client.consumer

Description

The consumer object.


Variablerequest_token_url

protectedstring Web.Auth.OAuth.Client.request_token_url

Description

The endpoint to send request for a request token.


Variabletoken

protectedToken Web.Auth.OAuth.Client.token

Description

The token object.


Variableuser_auth_url

protectedstring Web.Auth.OAuth.Client.user_auth_url

Description

The enpoint to redirect to when authorize an application.


Methodcreate

Web.Auth.OAuth.ClientWeb.Auth.OAuth.Client(Consumerconsumer, Tokentoken)

Description

Create a new Client.

Note

This class must be inherited


Methodget_access_token_url

stringget_access_token_url()

Description

Returns the url for requesting an access token.


Methodget_consumer

Consumerget_consumer()

Description

Returns the consumer.


Methodget_request_token_url

stringget_request_token_url()

Description

Returns the url for requesting a request token.


Methodget_token

Tokenget_token()

Description

Returns the token.


Methodget_user_auth_url

stringget_user_auth_url()

Description

Returns the url for authorizing an application.


Methodset_token

voidset_token(Tokentoken)
voidset_token(stringtoken_key, stringtoken_secret)

Description

Set the Token.

Parameter key

Either a Token object or a token key.

Parameter secret

The token secret if key is a token key.

Class Web.Auth.OAuth.Consumer

Description

An OAuth user


Variablecallback

string|Standards.URI Web.Auth.OAuth.Consumer.callback

Description

Callback url that the remote verifying page will return to.


Variablekey

string Web.Auth.OAuth.Consumer.key

Description

Consumer key


Variablesecret

string Web.Auth.OAuth.Consumer.secret

Description

Consumer secret


Methodcreate

Web.Auth.OAuth.ConsumerWeb.Auth.OAuth.Consumer(stringkey, stringsecret, void|string|Standards.URIcallback)

Description

Creates a new Consumer object.

Parameter callback

NOTE: Has no effect in this implementation.

Class Web.Auth.OAuth.Param

Description

Represents a query string parameter, i.e. key=value.


Variablename

protectedstring Web.Auth.OAuth.Param.name

Description

Param name


Variablevalue

protectedstring Web.Auth.OAuth.Param.value

Description

Param value


Method`==

bool res = Web.Auth.OAuth.Param() == other

Description

Comparer method. Checks if other equals this object.


Method`>

bool res = Web.Auth.OAuth.Param() > other

Description

Checks if this object is greater than other.


Method`[]

object|zero res = Web.Auth.OAuth.Param()[ key ]

Description

Index lookup.


Methodcreate

Web.Auth.OAuth.ParamWeb.Auth.OAuth.Param(stringname, mixedvalue)

Description

Creates a new Param.


Methodget_encoded_value

stringget_encoded_value()

Description

Returns the value encoded.


Methodget_name

stringget_name()

Description

Getter for the name attribute.


Methodget_signature

stringget_signature()

Description

Returns the name and value for usage in a signature string.


Methodget_value

stringget_value()

Description

Getter for the value attribute.


Methodset_name

voidset_name(stringvalue)

Description

Setter for the value attribute.


Methodset_value

voidset_value(mixed_value)

Description

Setter for the value attribute.

Class Web.Auth.OAuth.Params

Description

Collection of Param


Variableparams

privatearray(Param) Web.Auth.OAuth.Params.params

Description

Storage for Params of this object.


Method_sizeof

int(0..)sizeof(Web.Auth.OAuth.Paramsarg)

Description

Returns the size of the params array.


Method_values

mixedvalues(Web.Auth.OAuth.Paramsarg)

Description

Returns the params.


Method`+

this_program res = Web.Auth.OAuth.Params() + p

Description

Append p to the internal array.

Returns

The object being called.


Method`-

this_program res = Web.Auth.OAuth.Params() - p

Description

Removes p from the internal array.

Returns

The object being called.


Method`[]

mixed res = Web.Auth.OAuth.Params()[ key ]

Description

Index lookup

Returns

If no Param is found returns 0. If multiple Params with name key is found a new Params object with the found params will be retured. If only one Param is found that param will be returned.


Methodadd_mapping

this_programadd_mapping(mappingargs)

Description

Append mapping args as Param objects.

Returns

The object being called.


Methodcast

(mapping)Web.Auth.OAuth.Params()

Description

Supports casting to mapping, which will map parameter names to their values.


Methodcreate

Web.Auth.OAuth.ParamsWeb.Auth.OAuth.Params(Param ... params)

Description

Create a new Params

Parameter params

Arbitrary number of Param objects.


Methodget_auth_header

stringget_auth_header()

Description

Returns the params for usage in an authentication header.


Methodget_encoded_variables

mappingget_encoded_variables()

Description

Returns the parameters as a mapping with encoded values.

See also

get_variables()


Methodget_query_string

stringget_query_string()

Description

Returns the parameters as a query string.


Methodget_signature

stringget_signature()

Description

Returns the parameters for usage in a signature base string.


Methodget_variables

mappingget_variables()

Description

Returns the parameters as a mapping.

Class Web.Auth.OAuth.Request

Description

Class for building a signed request and querying the remote service.


Variablebase_string

protectedstring Web.Auth.OAuth.Request.base_string

Description

The signature basestring.


Variablemethod

protectedstring Web.Auth.OAuth.Request.method

Description

String representation of the HTTP method.


Variableparams

protectedParams Web.Auth.OAuth.Request.params

Description

The parameters to send.


Variableuri

protectedStandards.URI Web.Auth.OAuth.Request.uri

Description

The remote endpoint.


Methodadd_param

this_programadd_param(Param|stringname, void|stringvalue)

Description

Add a param.

Returns

The object being called.


Methodadd_params

voidadd_params(Paramsparams)

Description

Add a Params object.


Methodcast

(string)Web.Auth.OAuth.Request()

Description

It is possible to case the Request object to a string, which will be the request URL.


Methodcreate

Web.Auth.OAuth.RequestWeb.Auth.OAuth.Request(string|Standards.URIuri, stringhttp_method, void|Paramsparams)

Description

Creates a new Request.

See also

request()

Parameter uri

The uri to request.

Parameter http_method

The HTTP method to use. Either "GET" or "POST".


Methodget_param

Param|zeroget_param(stringname)

Description

Get param with name name.


Methodget_params

Paramsget_params()

Description

Returns the Params collection.


Methodget_signature_base

stringget_signature_base()

Description

Generates a signature base.


Methodsign_request

voidsign_request(intsignature_type, Consumerconsumer, Tokentoken)

Description

Signs the request.

Parameter signature_type

One of the types in Signature.


Methodsubmit

Protocols.HTTP.Querysubmit(void|mappingextra_headers)

Description

Send the request to the remote endpoint.

Class Web.Auth.OAuth.Token

Description

Token class.


Variablekey
Variablesecret

string|zero Web.Auth.OAuth.Token.key
string|zero Web.Auth.OAuth.Token.secret


Method__create__

protectedlocalvoid__create__(string|zerokey, string|zerosecret)


Methodcast

(string)Web.Auth.OAuth.Token()

Description

Only supports casting to string wich will return a query string of the object.


Methodcreate

Web.Auth.OAuth.TokenWeb.Auth.OAuth.Token(string|zerokey, string|zerosecret)

Module Web.Auth.OAuth.Signature

Description

Module for creating OAuth signatures


ConstantHMAC_SHA1

constantint Web.Auth.OAuth.Signature.HMAC_SHA1

Description

Signature type for hmac sha1 signing.


ConstantNONE

protected constantint Web.Auth.OAuth.Signature.NONE

Description

Signature type for the Base class.


ConstantPLAINTEXT

constantint Web.Auth.OAuth.Signature.PLAINTEXT

Description

Signature type for plaintext signing.


ConstantRSA_SHA1

constantint Web.Auth.OAuth.Signature.RSA_SHA1

Description

Signature type for rsa sha1 signing.


ConstantSIGTYPE

constant Web.Auth.OAuth.Signature.SIGTYPE

Description

Signature types to signature key mapping.


Methodget_object

Baseget_object(inttype)

Description

Returns a signature class for signing with type.

Throws

An error if type is unknown

Parameter type

Either PLAINTEXT, HMAC_SHA1 or RSA_SHA1.

Class Web.Auth.OAuth.Signature.Base

Description

Base signature class.


Variablemethod

protectedstring Web.Auth.OAuth.Signature.Base.method

Description

String representation of signature type.


Variabletype

protectedint Web.Auth.OAuth.Signature.Base.type

Description

Signature type.


Methodbuild_signature

stringbuild_signature(Requestrequest, Consumerconsumer, Tokentoken)

Description

Builds the signature string.


Methodget_method

stringget_method()

Description

Returns the method.


Methodget_type

intget_type()

Description

Returns the type.

Class Web.Auth.OAuth.Signature.HmacSha1

Description

HMAC_SHA1 signature.


InheritBase

inherit Base : Base


Methodbuild_signature

stringbuild_signature(Requestrequest, Consumerconsumer, Tokentoken)

Description

Builds the signature string.

Class Web.Auth.OAuth.Signature.Plaintext

Description

Plaintext signature.


InheritBase

inherit Base : Base


Methodbuild_signature

stringbuild_signature(Requestrequest, Consumerconsumer, Tokentoken)

Description

Builds the signature string.

Class Web.Auth.OAuth.Signature.RsaSha1

Description

RSA_SHA1 signature. Currently not implemented.


InheritBase

inherit Base : Base


Methodbuild_signature

stringbuild_signature(Requestrequest, Consumerconsumer, Tokentoken)

Description

Builds the signature string.

Module Web.Auth.OAuth2

Description

OAuth2 client

A base OAuth2 class can be instantiated either via `() (Web.Auth.OAuth2(params...)) or via Web.Auth.OAuth2.Base().


Method`()

protectedBase`()(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Instantiate a generic OAuth2 Base class.

Parameter client_id

The application ID.

Parameter client_secret

The application secret.

Parameter redirect_uri

Where the authorization page should redirect back to. This must be a fully qualified domain name. This can be set/overridden in Base()->get_auth_uri() and/or Base()->set_redirect_uri().

Parameter scope

Extended permissions to use for this authentication. This can be set/overridden in Base()->get_auth_uri().

Class Web.Auth.OAuth2.Base

Description

Generic OAuth2 client class.


ConstantSTATE

protected constantint Web.Auth.OAuth2.Base.STATE

Description

Some OAuth2 verifiers need the STATE parameter. If this is not 0 a random string will be generated and the state parameter will be added to the request.


ConstantUSER_AGENT

protected constantstring Web.Auth.OAuth2.Base.USER_AGENT

Description

User agent string.


ConstantVERSION

protected constantstring Web.Auth.OAuth2.Base.VERSION

Description

Version of this implementation.


Variable_access_type

protectedstring Web.Auth.OAuth2.Base._access_type

Description

Access type of the request.


Variable_client_id

protectedstring Web.Auth.OAuth2.Base._client_id

Description

The application ID.


Variable_client_secret

protectedstring Web.Auth.OAuth2.Base._client_secret

Description

The application secret.


Variable_grant_type

protectedstring Web.Auth.OAuth2.Base._grant_type

Description
  • GRANT_TYPE_AUTHORIZATION_CODE for apps running on a web server

  • GRANT_TYPE_IMPLICIT for browser-based or mobile apps

  • GRANT_TYPE_PASSWORD for logging in with a username and password

  • GRANT_TYPE_CLIENT_CREDENTIALS for application access


Variable_redirect_uri

protectedstring Web.Auth.OAuth2.Base._redirect_uri

Description

Where the authorization page should redirect to.


Variable_response_type

protectedstring Web.Auth.OAuth2.Base._response_type

Description
  • RESPONSE_TYPE_CODE for apps running on a webserver

  • RESPONSE_TYPE_TOKEN for apps browser-based or mobile apps


Variable_scope

protectedstring|array(string)|multiset(string) Web.Auth.OAuth2.Base._scope

Description

The scope of the authorization. Limits the access.


Variableaccess_token

string Web.Auth.OAuth2.Base.access_token

Description

Getting

Getter for access_token.

Setting

Getter for access_token.


Variablecreated

Calendar.Second Web.Auth.OAuth2.Base.created

Description

Getter for when the authentication was created.

Note

Read only


Variableexpires

Calendar.Second Web.Auth.OAuth2.Base.expires

Description

Getter for when the authentication expires.

Note

Read only


Variablehttp_request_timeout

int(1..) Web.Auth.OAuth2.Base.http_request_timeout

Description

Request timeout in seconds. Only affects async queries.


Variablerefresh_token

string Web.Auth.OAuth2.Base.refresh_token

Description

Getter for refresh_token.

Note

Read only


Variablerequest_headers

protectedmapping Web.Auth.OAuth2.Base.request_headers

Description

Default request headers.


Variabletoken_type

string Web.Auth.OAuth2.Base.token_type

Description

Getter for token_type.

Note

Read only


Variableuser

mapping Web.Auth.OAuth2.Base.user

Description

Getter for the user mapping which may or may not be set.

Note

Read only


Variablevalid_scopes

protectedmultiset(string) Web.Auth.OAuth2.Base.valid_scopes

Description

A mapping of valid scopes for the API.


Methodcast

(int)Web.Auth.OAuth2.Base()
(float)Web.Auth.OAuth2.Base()
(string)Web.Auth.OAuth2.Base()
(array)Web.Auth.OAuth2.Base()
(mapping)Web.Auth.OAuth2.Base()
(multiset)Web.Auth.OAuth2.Base()

Description

If casted to string the access_token will be returned. If casted to int the expires timestamp will be returned.


Methodcreate

Web.Auth.OAuth2.BaseWeb.Auth.OAuth2.Base(stringclient_id, stringclient_secret, void|stringredirect_uri, void|string|array(string)|multiset(string) scope)

Description

Creates an OAuth2 object.

Parameter client_id

The application ID.

Parameter client_secret

The application secret.

Parameter redirect_uri

Where the authorization page should redirect back to. This must be a fully qualified domain name. This can be set/overridden in get_auth_uri() and/or set_redirect_uri().

Parameter scope

Extended permissions to use for this authentication. This can be set/overridden in get_auth_uri().


Methoddecode_access_token_response

protectedbooldecode_access_token_response(stringr)

Description

Decode the response from an authentication call. If the response was ok the internal mapping gettable will be populated with the members/variables in r.

Parameter r

The response from do_query()


Methoddo_query

protectedstring|zerodo_query(string|zerooauth_token_uri, Web.Auth.Paramsp, void|function(bool, string:void) async_cb)

Description

Send a request to oauth_token_uri with params p

Parameter async_cb

If given an async request will be made and this function will be called when the request is finished. The first argument passed to the callback will be true or false depending on if the request was successfull or not. The second argument will be a string. If the request failed it will be an error message. If it succeeded it will be the result as a string encoded with predef::encode_value().


Methodget_access_type

stringget_access_type()

Description

Getter for the access type, if any.


Methodget_auth_uri

stringget_auth_uri(string|zeroauth_uri, void|mappingargs)

Description

Returns an authorization URI.

Parameter auth_uri

The URI to the remote authorization page

Parameter args

Additional argument.


Methodget_client_id

stringget_client_id()

Description

Returns the application ID.


Methodget_client_secret

stringget_client_secret()

Description

Returns the application secret.


Methodget_default_params

protectedWeb.Auth.Paramsget_default_params(void|stringgrant_type)

Description

Returns a set of default parameters.


Methodget_grant_type

stringget_grant_type()

Description

Returns the grant_type of the object.


Methodget_redirect_uri

stringget_redirect_uri()

Description

Returns the redirect uri.


Methodget_scope

mixedget_scope()

Description

Returns the scope/scopes set, if any.


Methodget_token_from_jwt

string|zeroget_token_from_jwt(stringjwt, void|stringtoken_endpoint, string|voidsub, void|function(bool, string:void) async_cb)

Description

Get an access_token from a JWT. http://jwt.io/

Parameter jwt

JSON string.

Parameter token_endpoint

URI to the request access_token endpoint.

Parameter sub

Email/id of the requesting user.

Parameter async_callback

If given the request will be made asynchronously. The signature is callback(bool, string). If successful the second argument will be the result encoded with predef::encode_value(), which can be stored and later used to populate an instance via set_from_cookie().

See also

Web.encode_jwt()


Methodget_valid_scopes

protectedstringget_valid_scopes(string|array(string)|multiset(string) s)

Description

Returns a space separated list of all valid scopes in s. s can be a comma or space separated string or an array or multiset of strings. Each element in s will be matched against the valid scopes set in the module inheriting this class.


Methodhas_scope

boolhas_scope(stringscope)

Description

Check if scope exists in this object.


Methodis_authenticated

boolis_authenticated()

Description

Do we have a valid authentication.


Methodis_expired

boolis_expired()

Description

Checks if this authorization has expired.


Methodis_renewable

boolis_renewable()

Description

Checks if the authorization is renewable. This is true if the Web.Auth.OAuth2.Base() object has been populated from Web.Auth.OAuth2.Base()->set_from_cookie(), i.e the user has been authorized but the session has expired.


Methodlist_valid_scopes

multisetlist_valid_scopes()

Description

Returns the valid scopes.


Methodrefresh_access_token

string|zerorefresh_access_token(string|zerooauth_token_uri, void|function(bool, string:void) async_cb)

Description

Refreshes the access token, if a refresh token exists in the object.

Parameter oauth_token_uri

Endpoint of the authentication service.

Parameter async_cb

If given an async request will be made and this function will be called when the request is finished. The first argument passed to the callback will be true or false depending on if the request was successfull or not. The second argument will be a string. If the request failed it will be an error message. If it succeeded it will be the result as a string encoded with predef::encode_value().


Methodrequest_access_token

string|zerorequest_access_token(string|zerooauth_token_uri, stringcode, void|function(bool, string:void) async_cb)

Description

Requests an access token.

Throws

An error if the access token request fails.

Parameter oauth_token_uri

An URI received from get_auth_uri().

Parameter code

The code returned from the authorization page via get_auth_uri().

Parameter async_cb

If given an async request will be made and this function will be called when the request is finished. The first argument passed to the callback will be true or false depending on if the request was successfull or not. The second argument will be a string. If the request failed it will be an error message. If it succeeded it will be the result as a string encoded with predef::encode_value().

Returns

If OK a Pike encoded mapping (i.e it's a string) is returned which can be used to populate an Web.Auth.OAuth2 object at a later time.

The mapping looks like

"access_token" : string
"expires" : int
"created" : int
"refresh_token" : string
"token_type" : string

Depending on the authorization service it might also contain more members.


Methodset_access_type

voidset_access_type(stringaccess_type)

Description

Set access_type explicilty.

Parameter access_type

Like: offline


Methodset_from_cookie

this_programset_from_cookie(stringencoded_value)

Description

Populate this object with the result from request_access_token().

Throws

An error if the decoding of encoded_value fails.

Parameter encoded_value

The value from a previous call to request_access_token() or refresh_access_token().

Returns

The object being called.


Methodset_grant_type

voidset_grant_type(GrantTypetype)

Description

Set the grant type to use.


Methodset_redirect_uri

voidset_redirect_uri(stringuri)

Description

Setter for the redirect uri.


Methodset_scope

voidset_scope(stringscope)

Description

Set scopes.


Methodtry_get_error

privatemixedtry_get_error(stringdata)

Description

Try to get an error message from data. Only successful if data is a JSON string and contains the key error.

Enum Web.Auth.OAuth2.Base.GrantType

Description

Grant types.


ConstantGRANT_TYPE_AUTHORIZATION_CODE

constant Web.Auth.OAuth2.Base.GRANT_TYPE_AUTHORIZATION_CODE


ConstantGRANT_TYPE_CLIENT_CREDENTIALS

constant Web.Auth.OAuth2.Base.GRANT_TYPE_CLIENT_CREDENTIALS


ConstantGRANT_TYPE_IMPLICIT

constant Web.Auth.OAuth2.Base.GRANT_TYPE_IMPLICIT


ConstantGRANT_TYPE_JWT

constant Web.Auth.OAuth2.Base.GRANT_TYPE_JWT


ConstantGRANT_TYPE_PASSWORD

constant Web.Auth.OAuth2.Base.GRANT_TYPE_PASSWORD


ConstantGRANT_TYPE_REFRESH_TOKEN

constant Web.Auth.OAuth2.Base.GRANT_TYPE_REFRESH_TOKEN

Enum Web.Auth.OAuth2.Base.ResponseType

Description

Response types.


ConstantRESPONSE_TYPE_CODE

constant Web.Auth.OAuth2.Base.RESPONSE_TYPE_CODE


ConstantRESPONSE_TYPE_TOKEN

constant Web.Auth.OAuth2.Base.RESPONSE_TYPE_TOKEN

Class Web.Auth.OAuth2.Client

Description

This class is intended to be extended by classes implementing different OAuth2 services.


InheritBase

inherit Base : Base


ConstantDEFAULT_SCOPE

protected constantint Web.Auth.OAuth2.Client.DEFAULT_SCOPE

Description

Scope to set if none is set.


ConstantOAUTH_AUTH_URI

constantint Web.Auth.OAuth2.Client.OAUTH_AUTH_URI

Description

Authorization URI.


ConstantOAUTH_TOKEN_URI

constantint Web.Auth.OAuth2.Client.OAUTH_TOKEN_URI

Description

Request access token URI.


Methodget_auth_uri

stringget_auth_uri(void|mappingargs)

Description

Returns an authorization URI.

Parameter args

Additional argument.


Methodget_token_from_jwt

stringget_token_from_jwt(stringjwt, void|stringsub, void|function(bool, string:void) async_cb)

Description

Make a JWT (JSON Web Token) authentication.


Methodrefresh_access_token

stringrefresh_access_token(void|function(bool, string:void) async_cb)

Description

Refreshes the access token, if a refresh token exists in the object.

Parameter async_cb

If given an async request will be made and this function will be called when the request is finished. The first argument passed to the callback will be true or false depending on if the request was successfull or not. The second argument will be a string. If the request failed it will be an error message. If it succeeded it will be the result as a string encoded with predef::encode_value().


Methodrequest_access_token

stringrequest_access_token(stringcode, void|function(bool, string:void) async_cb)

Description

Requests an access token.

Throws

An error if the access token request fails.

Parameter code

The code returned from the authorization page via get_auth_uri().

Parameter async_cb

If given an async request will be made and this function will be called when the request is finished. The first argument passed to the callback will be true or false depending on if the request was successfull or not. The second argument will be a string. If the request failed it will be an error message. If it succeeded it will be the result as a string encoded with predef::encode_value().

Returns

If OK a Pike encoded mapping (i.e it's a string) is returned which can be used to populate an Base object at a later time.

The mapping looks like

"access_token" : string
"expires" : int
"created" : int
"refresh_token" : string
"token_type" : string

Depending on the authorization service it might also contain more members.

Module Web.CGI

Class Web.CGI.Request

Description

Retrieves information about a CGI request from the environment and creates an object with the request information easily formatted.


Variableclient

array(string) Web.CGI.Request.client


Variableconfig

multiset(string) Web.CGI.Request.config

Description

If used with Roxen or Caudium webservers, this field will be populated with "config" information.


Variablecookies

mapping(string:string) Web.CGI.Request.cookies


Variabledata

string Web.CGI.Request.data


Variablemethod

string Web.CGI.Request.method


Variablemisc

mapping(string:int|string|array(string)) Web.CGI.Request.misc


Variablepragma

multiset(string) Web.CGI.Request.pragma


Variableprestate

multiset(string) Web.CGI.Request.prestate

Description

If used with Roxen or Caudium webservers, this field will be populated with "prestate" information.


Variableprot

string Web.CGI.Request.prot


Variablequery
Variablerest_query

string Web.CGI.Request.query
string Web.CGI.Request.rest_query


Variablereferer

array(string) Web.CGI.Request.referer


Variableremoteaddr
Variableremotehost

string Web.CGI.Request.remoteaddr
string Web.CGI.Request.remotehost


Variablesupports

multiset(string) Web.CGI.Request.supports

Description

If used with Roxen or Caudium webservers, this field will be populated with "supports" information.


Variablevariables

mapping(string:array(string)) Web.CGI.Request.variables


Methodcreate

Web.CGI.RequestWeb.CGI.Request()

Description

creates the request object. To use, create a Request object while running in a CGI environment. Environment variables will be parsed and inserted in the appropriate fields of the resulting object.

Module Web.Crawler

Description

This module implements a generic web crawler.

Features:

Fully asynchronous operation (Several hundred simultaneous requests)

Supports the /robots.txt exclusion standard

Extensible

URI Queues

Allow/Deny rules

Configurable

Number of concurrent fetchers

Bits per second (bandwidth throttling)

Number of concurrent fetchers per host

Delay between fetches from the same host

Supports HTTP and HTTPS

Class Web.Crawler.ComplexQueue


InheritQueue

inherit Queue : Queue


Variablestats
Variablepolicy

Stats Web.Crawler.ComplexQueue.stats
Policy Web.Crawler.ComplexQueue.policy


Method__create__

protectedlocalvoid__create__(Statsstats, Policypolicy)


Methodcreate

Web.Crawler.ComplexQueueWeb.Crawler.ComplexQueue(Statsstats, Policypolicy)

Class Web.Crawler.Crawler


Methodcreate

Web.Crawler.CrawlerWeb.Crawler.Crawler(Queue_queue, function(:void) _page_cb, function(:void) _error_cb, function(:void) _done_cb, function(:void) _prepare_cb, string|array(string)|Standards.URI|array(Standards.URI) start_uri, mixed ... _args)

Parameter _page_cb

function called when a page is retreived. Arguments are: Standards.URI uri, mixed data, mapping headers, mixed ... args. should return an array containing additional links found within data that will be analyzed for insertion into the crawler queue (assuming they are allowed by the allow/deny rulesets.

Parameter _error_cb

function called when an error is received from a server. Arguments are: Standards.URI real_uri, int status_code, mapping headers, mixed ... args. Returns void.

Parameter _done_cb

function called when crawl is complete. Accepts mixed ... args and returns void.

Parameter _prepare_cb

argument called before a uri is retrieved. may be used to alter the request. Argument is Standards.URI uri. Returns array with element 0 of Standards.URI uri, element 1 is a header mapping for the outgoing request.

Parameter start_uri

location to start the crawl from.

Parameter _args

optional arguments sent as the last argument to the callback functions.

Class Web.Crawler.GlobRule

Description

A rule that uses glob expressions

Parameter pattern

a glob pattern that the rule will match against.

Example

GlobRule("http://pike.lysator.liu.se/*.xml");


InheritRule

inherit Rule : Rule


Variablepattern

string Web.Crawler.GlobRule.pattern


Method__create__

protectedlocalvoid__create__(stringpattern)


Methodcreate

Web.Crawler.GlobRuleWeb.Crawler.GlobRule(stringpattern)

Class Web.Crawler.MemoryQueue

Description

Memory queue


InheritQueue

inherit Queue : Queue


Methodcreate

Web.Crawler.MemoryQueueWeb.Crawler.MemoryQueue(Stats_stats, Policy_policy, RuleSet_allow, RuleSet_deny)


Methodget

int|Standards.URIget()

Description

Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling, outstanding requests and other limits. Returns 0 if there are no more URIs to index.


Methodput

voidput(string|array(string)|Standards.URI|array(Standards.URI) uri)

Description

Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.

Class Web.Crawler.MySQLQueue


InheritQueue

inherit Queue : Queue


Methodcreate

Web.Crawler.MySQLQueueWeb.Crawler.MySQLQueue(Stats_stats, Policy_policy, string_host, string_table, void|RuleSet_allow, void|RuleSet_deny)

Class Web.Crawler.Policy

Description

The crawler policy object.


Variablebandwidth_throttling_floating_window_width

int Web.Crawler.Policy.bandwidth_throttling_floating_window_width

Description

Bandwidth throttling floating window width. Defaults to 30.


Variablemax_bits_per_second_per_host

int Web.Crawler.Policy.max_bits_per_second_per_host

Description

Maximum number of bits per second, per host. Defaults to off (0).


Variablemax_bits_per_second_total

int Web.Crawler.Policy.max_bits_per_second_total

Description

Maximum number of bits per second. Defaults to off (0).


Variablemax_concurrent_fetchers

int Web.Crawler.Policy.max_concurrent_fetchers

Description

Maximum number of fetchers. Defaults to 100.


Variablemax_concurrent_fetchers_per_host

int Web.Crawler.Policy.max_concurrent_fetchers_per_host

Description

Maximum concurrent fetchers per host. Defaults to 1.


Variablemin_delay_per_host

int Web.Crawler.Policy.min_delay_per_host

Description

Minimum delay per host. Defaults to 0.

Class Web.Crawler.Queue

Description

A crawler queue. Does not need to be reentrant safe. The Crawler always runs in just one thread.


Methodget

int|Standards.URIget()

Description

Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling and other limits. Returns 0 if there are no more URIs to index.


Methodput

voidput(string|array(string)|Standards.URI|array(Standards.URI) uri)

Description

Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.

Class Web.Crawler.RegexpRule

Description

A rule that uses Regexp expressions


InheritRule

inherit Rule : Rule


Methodcreate

Web.Crawler.RegexpRuleWeb.Crawler.RegexpRule(stringre)

Parameter re

a string describing the Regexp expression

Class Web.Crawler.Rule

Description

Abstract rule class.


Methodcheck

intcheck(string|Standards.URIuri)

Class Web.Crawler.RuleSet

Description

A set of rules


Methodadd_rule

voidadd_rule(Rulerule)

Description

add a rule to the ruleset


Methodremove_rule

voidremove_rule(Rulerule)

Description

remove a rule from the ruleset

Class Web.Crawler.Stats

Description

Statistics.


Variablewindow_width
Variablegranularity

int Web.Crawler.Stats.window_width
int Web.Crawler.Stats.granularity


Method__create__

protectedlocalvoid__create__(intwindow_width, intgranularity)


Methodbytes_read_callback

voidbytes_read_callback(Standards.URIuri, intnum_bytes_read)

Description

This callback is called when data has arrived for a presently crawled URI, but no more often than once a second.


Methodclose_callback

voidclose_callback(Standards.URIuri)

Description

This callback is called whenever the crawling of a URI is finished or fails.


Methodcreate

Web.Crawler.StatsWeb.Crawler.Stats(intwindow_width, intgranularity)

Module Web.EngineIO

Description

This is an implementation of the Engine.IO server-side communication's driver. It basically is a real-time bidirectional packet-oriented communication's protocol for communicating between a webbrowser and a server.

The driver mainly is a wrapper around Protocols.WebSocket with the addition of two fallback mechanisms that work around limitations imposed by firewalls and/or older browsers that prevent native Protocols.WebSocket connections from functioning.

This module supports the following features:

  • It supports both UTF-8 and binary packets.

  • If both sides support Protocols.WebSocket, then packet sizes are essentially unlimited. The fallback methods have a limit on packet sizes from browser to server, determined by the maximum POST request size the involved network components allow.

In most cases, Engine.IO is not used directly in applications. Instead one uses Socket.IO instead.

Example

Sample small implementation of an EngineIO server farm:

class mysocket {inheritWeb.EngineIO.Socket;void echo(string|Stdio.Buffer msg){
    write(0, msg);}}void wsrequest(array(string) protocols,object req){
  httprequest(req);}void httprequest(object req){switch(req.not_query){case"/engine.io/":
      mysocket client =Web.EngineIO.farm(mysocket, req);if(client){
        client.open(client.echo);
        client.write(0,"Hello world!");}break;}}int main(int argc,array(string) argv){Protocols.WebSocket.Port(httprequest, wsrequest, 80);return-1;}
See also

farm, Web.SocketIO, Protocols.WebSocket, http://github.com/socketio/engine.io-protocol, http://socket.io/


Constantprotocol

constantint Web.EngineIO.protocol

Description

Engine.IO protocol version.


Variableoptions

finalmapping Web.EngineIO.options

Description

Global options for all EngineIO instances.

See also

Socket.create(), Gz.compress()


Methodfarm

finalSocket|zerofarm(programcreatetype, Protocols.WebSocket.Requestreq, void|mapping(string:mixed) options)

Parameter options

Optional options to override the defaults. This parameter is passed down as is to the underlying Socket.

See also

Socket.create()

Enum Web.EngineIO.


ConstantBASE64
ConstantOPEN
ConstantCLOSE
ConstantPING
ConstantPONG
ConstantMESSAGE
ConstantUPGRADE
ConstantNOOP
ConstantACK
ConstantSENDQEMPTY
ConstantSHUTDOWN

constant Web.EngineIO.BASE64
constant Web.EngineIO.OPEN
constant Web.EngineIO.CLOSE
constant Web.EngineIO.PING
constant Web.EngineIO.PONG
constant Web.EngineIO.MESSAGE
constant Web.EngineIO.UPGRADE
constant Web.EngineIO.NOOP
constant Web.EngineIO.ACK
constant Web.EngineIO.SENDQEMPTY
constant Web.EngineIO.SHUTDOWN

Class Web.EngineIO.Socket

Description

Runs a single Engine.IO session.


Variablerequest

finalProtocols.WebSocket.Request Web.EngineIO.Socket.request

Description

Contains the last request seen on this connection. Can be used to obtain cookies etc.


Variablesid

finalstring Web.EngineIO.Socket.sid

Description

The unique session identifier (in the Engine.IO docs referred to as simply: id).


Methodclose

finalvoidclose()

Description

Close the socket signalling the other side.


Methodcreate

Web.EngineIO.SocketWeb.EngineIO.Socket(Protocols.WebSocket.Requestreq, void|mappingoptions)

Parameter options

Optional options to override the defaults.

"pingTimeout" : int

If, the connection is idle for longer than this, the connection is terminated, unit in ms.

"pingInterval" : int

The browser-client will send a small ping message every pingInterval ms.

"allowUpgrades" : int

When true (default), it allows the server to upgrade the connection to a real Protocols.WebSocket connection.

"compressionLevel" : int

The gzip compressionlevel used to compress packets.

"compressionThreshold" : int

Packets smaller than this will not be compressed.


Methodonrequest

finalvoidonrequest(Protocols.WebSocket.Requestreq)

Description

Handle request, and returns a new Socket object if it's a new connection.


Methodopen

finalvoidopen(void|function(string|Stdio.Buffer:void) _read_cb, void|function(:void) _close_cb, void|function(:void) _lowmark_cb)

Description

Set callbacks and open socket.


Methodwrite

finalvoidwrite(mapping(string:mixed) options, string|Stdio.Buffer ... msgs)

Description

Send text string or binary Stdio.Buffer messages.

Enum Web.EngineIO.Socket.


ConstantRUNNING
ConstantPAUSED
ConstantSCLOSING
ConstantRCLOSING

constant Web.EngineIO.Socket.RUNNING
constant Web.EngineIO.Socket.PAUSED
constant Web.EngineIO.Socket.SCLOSING
constant Web.EngineIO.Socket.RCLOSING

Class Web.EngineIO.Socket.Transport


Methodclose

voidclose()

Description

Close the transport properly, notify the far end.


Methodshutdown

voidshutdown()

Description

Shutdown the transport silently.

Module Web.RSS

Description

Represents a RSS (RDF Site Summary) file.


Methodparse_xml

Indexparse_xml(string|Parser.XML.Tree.Noden, void|stringbase)

Description

Returns an Index object, populated with the rss information given in the rss file n.

Class Web.RSS.Channel

Description

Represents an RSS channel.


InheritThing

inherit Thing : Thing


Variabletitle
Variablelink
Variabledescription
Variableimage
Variabletextinput
Variableitems

string Web.RSS.Channel.title
string Web.RSS.Channel.link
string Web.RSS.Channel.description
string|Standards.URI Web.RSS.Channel.image
string|Standards.URI Web.RSS.Channel.textinput
array(Item) Web.RSS.Channel.items


Methodadd_item

voidadd_item(Itemi)

Description

Adds the Itemi to the Channel.


Methodremove_item

voidremove_item(Itemi)

Description

Removes the Itemi from the Channel.

Class Web.RSS.Image

Description

Represents an RSS image resource.


InheritThing

inherit Thing : Thing


Variabletitle
Variableurl
Variablelink

string Web.RSS.Image.title
string Web.RSS.Image.url
string Web.RSS.Image.link

Class Web.RSS.Index

Description

Represents the top level of an RSS index.


Variablechannels

array(Channel) Web.RSS.Index.channels

Description

The RSS channels.


Variableimages

array(Image) Web.RSS.Index.images

Description

The RSS images.


Variableitems

array(Item) Web.RSS.Index.items

Description

The RSS items.


Variablerdf

.RDF Web.RSS.Index.rdf

Description

The underlying RDF representation of the RSS index.


Variabletextinputs

array(Textinput) Web.RSS.Index.textinputs

Description

The RSS textinputs.


Methodcreate

Web.RSS.IndexWeb.RSS.Index(.RDF|void_rdf)

Class Web.RSS.Item

Description

Represents an RSS item resource.


InheritThing

inherit Thing : Thing


Variabletitle
Variablelink
Variabledescription

string Web.RSS.Item.title
string Web.RSS.Item.link
string Web.RSS.Item.description

Class Web.RSS.Textinput

Description

Represents an RSS textinput resource.


InheritThing

inherit Thing : Thing


Variabletitle
Variabledescription
Variablename
Variablelink

string Web.RSS.Textinput.title
string Web.RSS.Textinput.description
string Web.RSS.Textinput.name
string Web.RSS.Textinput.link

Class Web.RSS.Thing

Description

The base class for the RSS resources.


Methodcreate

Web.RSS.ThingWeb.RSS.Thing(stringabout, mappingattributes)
Web.RSS.ThingWeb.RSS.Thing(.RDF.Resourceme)

Description

Creates an RSS resource.


Methodget_id

.RDF.Resourceget_id()

Description

Returns the RDF.Resource that identifies this RSS resource.

Module Web.SOAP

Description

This is a limited SOAP wsdl parser using Promises.

Example
Web.SOAP.Promise("https://foo.bar/Logon.svc?wsdl").on_success(lambda(Web.SOAP.Client soap){Web.SOAP.Arguments args, sh;
  args               = soap->get_arguments("Logon");
  sh                 = args->LogonRequestMsg;
  sh->Username       ="foo";
  sh->Password       ="bar";
  sh->WebServiceType ="Publisher";

  soap->call(args).on_success(lambda(mapping resp){string token = resp->CredentialToken;});});

MethodPromise

finalConcurrent.FuturePromise(stringwsdlurl, void|mappingheaders)

Returns

A Concurrent.Future that eventually delivers a Client.

See also

Client()

Class Web.SOAP.Client


Methodcall

finalConcurrent.Futurecall(Argumentsargs)

Description

Calls the SOAP method you most recently addressed using get_arguments().

Returns

A Concurrent.Future that eventually delivers a result mapping.

See also

get_arguments()


Methodcreate

Web.SOAP.ClientWeb.SOAP.Client(Protocols.HTTP.Promise.Resultresp)

Description

Usually not called directly.

See also

Promise()


Methodget_arguments

finalArgumentsget_arguments(stringmethod)

Description

Primes the Client to perform the call() later. Use the returned structure to pass parameters. Only assigned parameters will be passed to the call.

Returns

A structure describing all arguments for the specified method.

See also

call()


Methodget_methods

finalArgumentsget_methods()

Returns

A structure describing all available methods on the current wsdl.

Module Web.Sass

Description

Sass is a scripting language that is interpreted into Cascading Style Sheets (CSS). This module is a glue for libsass.

See also

SASS http://sass-lang.com/


Typedefs8

protected typedefstring(8bit) Web.Sass.s8

Description

Shorthand for string(8bit)


ConstantHTTP_IMPORT_NONE
ConstantHTTP_IMPORT_GREEDY
ConstantHTTP_IMPORT_ANY

constantint Web.Sass.HTTP_IMPORT_NONE
constantint Web.Sass.HTTP_IMPORT_GREEDY
constantint Web.Sass.HTTP_IMPORT_ANY

Description

Description:

HTTP_IMPORT_NONE

Default value of Compiler.http_import. Prohibits imports over HTTP.

HTTP_IMPORT_GREEDY

Allow imports over HTTP only if the returned content type is text/scss.

HTTP_IMPORT_ANY

Anything goes.


ConstantLIBSASS_VERSION

constantstring Web.Sass.LIBSASS_VERSION

Description

The libsass version, as a string, this module was compiled agains.


ConstantSASS2SCSS_KEEP_COMMENT
ConstantSASS2SCSS_STRIP_COMMENT
ConstantSASS2SCSS_CONVERT_COMMENT

constantint Web.Sass.SASS2SCSS_KEEP_COMMENT
constantint Web.Sass.SASS2SCSS_STRIP_COMMENT
constantint Web.Sass.SASS2SCSS_CONVERT_COMMENT

Description

Constants that can be given as option to sass2scss().


ConstantSTYLE_NESTED
ConstantSTYLE_EXPANDED
ConstantSTYLE_COMPACT
ConstantSTYLE_COMPRESSED

constantint Web.Sass.STYLE_NESTED
constantint Web.Sass.STYLE_EXPANDED
constantint Web.Sass.STYLE_COMPACT
constantint Web.Sass.STYLE_COMPRESSED

Description

Styling of output. Use as argument to Compiler.set_output_style()

STYLE_NESTED

The default setting. The output will look like:

a {
  property: value;
  other-property: value;}
  a:hover {
    property: value;}
b {
  property: value;}
STYLE_EXPANDED

Fully expanded output:

a {
  property: value;
  other-property: value;}
a:hover {
  property: value;}
b {
  property: value;}
STYLE_COMPACT

Somewhat minified output:

a { property: value; other-prop: value }
a:hover { property: value;}
b { property: value;}
STYLE_COMPRESSED

Minified output

a{property:value;other-property:value}a:hover{property:value}b{property:value}

Methodlibsass_language_version

stringlibsass_language_version()

Description

Returns the language version of Sass this module was compiled against


Methodlibsass_version

stringlibsass_version()

Description

Returns the libsass version this module was compiled against


Methodsass2scss

string(8bit)sass2scss(string(8bit)data)
string(8bit)sass2scss(string(8bit)data, intoptions)

Description

Convert Sass syntax (i.e. indented syntax) to SCSS syntax.

Parameter data

Sass syntax text to convert to SCSS syntax.

Parameter options

This is a bitwise union of compression level (STYLE_NESTED, STYLE_EXPANDED, STYLE_COMPACT and $[STYLE_COMPRESSED]) and the SASS2SCSS_* constants SASS2SCSS_KEEP_COMMENT, SASS2SCSS_STRIP_COMMENT and SASS2SCSS_CONVERT_COMMENT. It defaults to STYLE_NESTED|SASS2SCSS_KEEP_COMMENT.

Returns

data converted to SCSS syntax.


Methodsass2scss_version

stringsass2scss_version()

Description

Returns the sass2scss version this module was compiled against

Class Web.Sass.Api

Description

Low-level Sass/SCSS compiler.

You probably want to use Compiler instead of this class.

See also

Compiler


Variableinclude_path

string(8bit) Web.Sass.Api.include_path

Description

The base path of @imports. Note! This needs to be set when compile_string() is used.


Variableomit_source_map_url

bool Web.Sass.Api.omit_source_map_url

Description

Set whether writing the sourceMappingUrl=# or not.


Variableoutput_style

int(2bit) Web.Sass.Api.output_style

Description

Determines the level of compression on the generated output.

See also

STYLE_NESTED, STYLE_EXPANDED, STYLE_COMPACT and STYLE_COMPRESSED.


Variableprecision

int Web.Sass.Api.precision

Description

Set the precision of fractional numbers. Default is 5.


Variablesass_syntax

bool Web.Sass.Api.sass_syntax

Description

Set whether the code is Sass syntax, i.e. indented syntax or not. Only necessary when using compile_string()


Variablesource_comments

bool Web.Sass.Api.source_comments

Description

Emit comments in the generated CSS indicating the corresponding source line. Default is false.


Variablesource_map_embed

bool Web.Sass.Api.source_map_embed

Description

Set whether embedding sourceMappingUrl=# as data uri or not.


Variablesource_map_file

string(8bit) Web.Sass.Api.source_map_file

Description

Set the path of the source map file.


Variablesource_map_root

string(8bit) Web.Sass.Api.source_map_root

Description

Set the root path of the source files, relative to where the source.map file is written.


Methodcompile_string

string(8bit)compile_string(string(8bit)source)

Description

Compiles the string source and returns the generated CSS.

Parameter source

The string to compile

Returns

A mapping with the generated CSS and source mapping file if such is set to be generated

"css" : string(8bit)

The generated CSS

"map" : string(8bit)

The generated source mapping data

Note

If the source contain @import directives you have to explicitly set the include path via include_path.

Class Web.Sass.Compiler

Description

Sass/SCSS compiler.

Example
Web.Sass.Compiler compiler =Web.Sass.Compiler();// Allow for HTTP imports, disallowed by default.
compiler->http_import =Web.Sass.HTTP_IMPORT_ANY;// Minify the output and create a source map file.
compiler->set_options((["output_style":Web.Sass.STYLE_COMPRESSED,"source_map_file":"path/to/write/source.map"]));if(mixed e =catch(compiler->compile_file("input.scss","output.css"))){
  werror("Failed compiling input.scss to output.css\n");}

InheritApi

inherit Api : Api


Variablecheck_file_access

bool Web.Sass.Compiler.check_file_access

Description

Should file access be tested right away when paths are set or should that be left to Sass to handle? The default value is true.


Variablehttp_import

int(0..2) Web.Sass.Compiler.http_import

Description

If a Sass file is importing an external URI this flag determines if thats allowed at all, or if the content type of the imported file has to be in http_import_allow_ct, or if anything goes. Default is HTTP_IMPORT_NONE.

See also

HTTP_IMPORT_NONE, HTTP_IMPORT_GREEDY and HTTP_IMPORT_ANY.


Variablehttp_import_allow_ct

multiset(s8) Web.Sass.Compiler.http_import_allow_ct

Description

List of allowed content types if http_import is set to HTTP_IMPORT_GREEDY. The default is to allow text/scss and text/sass.


Methodcompile_file

mapping(s8:s8) compile_file(s8input_file)

Description

Compile the file input_file and return the result

Parameter input_file

The SCSS file to compile

Returns

A mapping with the generated CSS and source mapping file if such is set to be generated

"css" : string(8bit)

The generated CSS

"map" : string(8bit)

The generated source mapping data


Methodcompile_file

variantvoidcompile_file(s8input_file, s8output_file)

Description

Compile the file input_file and write the result to output_file. If a source mapping file is set to be generated either via set_options() or source_map_file it will be written as per the value set in the option.

Parameter input_file

The SCSS file to compile

Parameter output_file

The name of the CSS file to save the result in.


Methodhandle_sass_import

protectedstring|array(string(8bit)) handle_sass_import(string(8bit)path, void|string(8bit)absolute_path, void|string(8bit)relative_path)

Description

Resolve imports in sass/scss files.

Note

In general this method doesn't need to overloaded. In principle it's only necessary if the Sass files reside in a non-standard filesystem.

Note

If overloaded abs_path and rel_path is the absolute and relaive paths of the file containing the import statement path. If the Sass/SCSS files are located in a normal filesystem this method can return the contents of path as a string and libsass will resolve the paths to the imports by itself.

However, if the files are not located in a normal filesystem this function should return an array of two indices, where the first index should be the contents of path and the second the calculated absolute path of path.

Parameter path

This is the value of `path` in @import 'path'.

Parameter absolute_path

This is the absolute path of the file containing the @import statement.

Parameter relative_path

The relative path of absolute_path in relation to the prevoius absolute_path

Returns
int(0)

If undefined is returned the import resolution is given back to libsass.

string(8bit)

The contents of path

array(string(8bit))

if an array is returned it should contain two indices, where the first if the contents of path and the second should be the absolute path path. This is only useful (needed) if the Sass files doesn't reside in a normal filesystem that libsass can read.


Methodset_options

voidset_options(mapping(s8:s8|int) opts)

Description

Set options to the SASS compiler.

Parameter opts
"output_style" : int

Any of the STYLE_NESTED, STYLE_EXPANDED, STYLE_COMPACT or STYLE_COMPRESSED constants. See also output_style.

"include_path" : string(8bit)

Path to root of incude files. See also include_path.

"source_map_file" : string(8bit)

File to write source map file to. See also source_map_file.

"source_comments" : bool

Turn on/off comments in the output containing info about the source file - line numbers and such. Default of false. See also source_comments.

"source_map_embed" : bool

Turn on/off if a source map should be embedded in the output or not. Default is false. See also source_map_embed.

"source_map_root" : string(8bit)

Set the root path of the source files, relative to where the source.map file is written. See also source_map_root

"omit_source_map_url" : bool

Omit the #sourceMappingURL or not. See also omit_source_map_url

"sass_syntax" : bool

Turn on/off Sass syntax, i.e. indented syntax. Only necessary when using compile_string()

"precision" : int

Floating point precision. See also precision.

Module Web.SocketIO

Description

This is an implementation of the Socket.IO server-side communication's driver. It basically is a real-time bidirectional object-oriented communication's protocol for communicating between a webbrowser and a server.

This module supports the following features:

  • Passing any arbitrarily deep nested data object which can be represented in basic JavaScript datatypes.

  • In addition to the normal JavaScript datatypes, it also supports passing (nested) binary blobs in an efficient manner.

  • Every message/event sent, allows for a callback acknowledge to be specified.

  • Acknowledge callbacks which will be called when the other side actively decides to acknowledge it (not automatically upon message reception).

  • Acknowledgement messages can carry an arbitrary amount of data.

The driver uses Web.EngineIO as the underlying protocol.

Example

Sample minimal implementation of a SocketIO server farm:

Web.SocketIO.Universe myuniverse;class myclient {inheritWeb.SocketIO.Client;}void echo(myclient id,function sendack,string namespace,string event,mixed ... data){
  id->emit(event, @data);if(sendack)
    sendack("Ack","me","harder");}void wsrequest(array(string) protocols,object req){
  httprequest(req);}void httprequest(object req){switch(req.not_query){case"/socket.io/":
      myclient client = myuniverse.farm(myclient, req);if(client)
        client->emit("Hello world!");break;}}int main(int argc,array(string) argv){
  myuniverse =Web.SocketIO.Universe();// Create universe
  myuniverse.register("", echo);// Register root namespaceProtocols.WebSocket.Port(httprequest, wsrequest, 80);return-1;}
See also

farm, Web.EngineIO, Protocols.WebSocket, http://github.com/socketio/socket.io-protocol, http://socket.io/


Variableoptions

finalmapping(string:mixed) Web.SocketIO.options

Description

Global options for all SocketIO instances.

See also

SocketIO.Universe.farm()


Methodsendackcb

finalvoidsendackcb(function(mixed ... :void) fn, mixedarg)

Description

Convenience function to aid assist in sending the acknowledgment callback.

Enum Web.SocketIO.


ConstantCONNECT
ConstantDISCONNECT
ConstantEVENT
ConstantACK
ConstantERROR
ConstantBINARY_EVENT
ConstantBINARY_ACK

constant Web.SocketIO.CONNECT
constant Web.SocketIO.DISCONNECT
constant Web.SocketIO.EVENT
constant Web.SocketIO.ACK
constant Web.SocketIO.ERROR
constant Web.SocketIO.BINARY_EVENT
constant Web.SocketIO.BINARY_ACK


ConstantCONTAINER

constant Web.SocketIO.CONTAINER

Class Web.SocketIO.Client

Description

Runs a single Socket.IO session.


Variableonclose

function(void:void) Web.SocketIO.Client.onclose


Variablerequest

Protocols.WebSocket.Request Web.SocketIO.Client.request

Description

Contains the last request seen on this connection. Can be used to obtain cookies etc.

Note

Read only


Variablesid

string Web.SocketIO.Client.sid

Description

This session's unique session id.

Note

Read only


Methodclose

voidclose()

Description

Close the socket signalling the other side.


Methodemit

finalvariantvoidemit(function(Client, mixed ... :void) ack_cb, stringevent, mixed ... data)
finalvariantvoidemit(stringevent, mixed ... data)
finalvariantvoidemit(function(Client, mixed ... :void) ack_cb, mapping(string:mixed) options, stringevent, mixed ... data)
finalvariantvoidemit(mapping(string:mixed) options, stringevent, mixed ... data)

Description

Send text or binary events to the client.


Methodwrite

finalvoidwrite(arraydata, void|function(Client, mixed ... :void) ack_cb, void|mapping(string:mixed) options)

Description

Send text or binary messages to the client. When in doubt use the emit() interface instead. write() allows messages to be sent which do not have a string event-name up front.

Enum Web.SocketIO.Client.


ConstantRUNNING
ConstantSDISCONNECT
ConstantRDISCONNECT

constant Web.SocketIO.Client.RUNNING
constant Web.SocketIO.Client.SDISCONNECT
constant Web.SocketIO.Client.RDISCONNECT

Class Web.SocketIO.Universe


Variableclients

finalmultiset(object) Web.SocketIO.Universe.clients

Description

All SocketIO sessions in this universe.


Methodconnect

mixedconnect(Clientclient, void|stringnewnamespace)

Description

Connects and disconnects clients.

Returns

0 upon success, the error itself otherwise.


Methodfarm

Clientfarm(objectcreatetype, Protocols.WebSocket.Requestreq, void|mappingoptions)

Parameter options

Optional options to override the defaults. This parameter is passed down as-is to the underlying EngineIO.Socket.

See also

EngineIO.farm()


Methodlookupcb

protectedstring|function(:void) lookupcb(stringnamespace, arraydata)


Methodread

mixedread(stringnamespace, mixedid, function(mixed ... :void) sendackcb, mixed ... data)


Methodregister

variantvoidregister(stringnamespace, stringevent, void|function(Client, function(mixed ... :void), string, string, mixed ... :void) fn)
variantvoidregister(stringnamespace, void|function(Client, function(mixed ... :void), string, mixed ... :void) fn)

Description

Register worker callback on namespace and event. There can be only one worker per tuple. Workers can be unregistered by omitting fn. Having a default worker per namespace in addition zero or more event specific ones, is supported.


Methodseed

protected.EngineIO.Socketseed(Protocols.WebSocket.Requestreq, void|mappingoptions)

Description

Seed farm with EngineIO connection.

Module Yp

Description

This module is an interface to the Yellow Pages functions. Yp is also known as NIS (Network Information System) and is most commonly used to distribute passwords and similar information within a network.


Inherit"___Yp"

inherit "___Yp" : "___Yp"


Methoddefault_domain

stringdefault_domain()

Description

Returns the default yp-domain.

Class Yp.Domain


Methodall

mapping(string:string) all(stringmap)

Description

Returns the whole map as a mapping.

map is the YP-map to search in. This must be the full map name, you have to use passwd.byname instead of just passwd.


Methodcreate
Methodbind

Yp.DomainYp.Domain(string|voiddomain)
voidbind(stringdomain)

Description

If domain is not specified , the default domain will be used. (As returned by Yp.default_domain()).

If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. This timeout is not configurable.

See also

Yp.default_domain()


Methodmap

voidmap(stringmap, function(string, string:void) fun)

Description

For each entry in map, call the function specified by fun.

fun will get two arguments, the first being the key, and the second the value.

map is the YP-map to search in. This must be the full map name. eg passwd.byname instead of just passwd.


Methodmatch

stringmatch(stringmap, stringkey)

Description

Search for the key key in the Yp-map map.

Returns

If there is no key in the map, 0 (zero) will be returned, otherwise the string matching the key will be returned.

Note

key must match exactly, no pattern matching of any kind is done.


Methodorder

intorder(stringmap)

Description

Returns the 'order' number for the map map.

This is usually the number of seconds since Jan 1 1970 (see time()). When the map is changed, this number will change as well.

map is the YP-map to search in. This must be the full map name. eg passwd.byname instead of just passwd.


Methodserver

stringserver(stringmap)

Description

Returns the hostname of the server serving the map map. map is the YP-map to search in. This must be the full map name. eg passwd.byname instead of just passwd.

Class Yp.Map

Description

Network Information Service aka YP map.


Method_indices

array(string) indices(Yp.Maparg)

Description

Return the keys of the map.


Method_sizeof

intsizeof(Yp.Maparg)

Description

Return the number of entries in this map.


Method_values

array(string) values(Yp.Maparg)

Description

Return the values of the map.


Methodmatch
Method`[]

stringmatch(stringkey)
string res = Yp.Map()[ key ]

Description

Search for the key key. If there is no key in the map, 0 (zero) will be returned, otherwise the string matching the key will be returned.

Note

key must match exactly, no pattern matching of any kind is done.


Methodall

mapping(string:string) all()

Description

Returns the whole map as a mapping.


Methodcast

(mapping)Yp.Map()

Description

Convert the map to a mapping


Methodcreate

Yp.MapYp.Map(stringmap, string|voiddomain)

Description

Create a new YP-map object.

map is the YP-map to bind to. This may be a nickname, such as passwd instead of just passwd.byname.

If domain is not specified, the default domain will be used.

Note

If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. The timeout is not configurable.


Methodmap

voidmap(function(string, string:void) fun)

Description

Call a function for each entry in the map.

For each entry in the map, call the function fun.

The function will be called like void fun(string key, string value).


Methodorder

intorder()

Description

Return the order number for this map.


Methodserver

stringserver()

Description

Return the server that provides this map.

Module _Charset

Description

Low-level tables and code for the Charset module.

This is probably not the module you want; try the Charset module.

See also

Charset


Methodrfc1345

objectrfc1345(stringcharset, bool|voidencoder, string|voidrep, function(string:string)|voidrepcb)

Description

Low-level charset codec factory.

Parameter charset

Canonical name of character set to look up.

Parameter encoder

Flag indicating that an encoder and not a decoder is wanted.

Parameter rep

String to use for characters not representable in the charset. Only used for encoders.

Parameter repcb

Function to call for characters not representable in the charset. Only used for encoders.

This is the main entrypoint into the low-level _Charset module.

Returns

Returns a suitable encoder or decoder on success and 0 (zero) on failure.

See also

Charset.encoder(), Charset.decoder()

Module _Ffmpeg


ConstantCODEC_ID_NONE
ConstantCODEC_ID_AC3
ConstantCODEC_ID_ADPCM_IMA_QT
ConstantCODEC_ID_ADPCM_IMA_WAV
ConstantCODEC_ID_ADPCM_MS
ConstantCODEC_ID_H263
ConstantCODEC_ID_H263I
ConstantCODEC_ID_H263P
ConstantCODEC_ID_MJPEG
ConstantCODEC_ID_MPEG1VIDEO
ConstantCODEC_ID_MPEG4
ConstantCODEC_ID_MP2
ConstantCODEC_ID_MP3LAME
ConstantCODEC_ID_MSMPEG4V1
ConstantCODEC_ID_MSMPEG4V2
ConstantCODEC_ID_MSMPEG4V3
ConstantCODEC_ID_PCM_ALAW
ConstantCODEC_ID_PCM_MULAW
ConstantCODEC_ID_PCM_S16BE
ConstantCODEC_ID_PCM_S16LE
ConstantCODEC_ID_PCM_S8
ConstantCODEC_ID_PCM_U16BE
ConstantCODEC_ID_PCM_U16LE
ConstantCODEC_ID_PCM_U8
ConstantCODEC_ID_RAWVIDEO
ConstantCODEC_ID_RV10
ConstantCODEC_ID_SVQ1
ConstantCODEC_ID_VORBIS
ConstantCODEC_ID_WMV1
ConstantCODEC_ID_WMV2

constant _Ffmpeg.CODEC_ID_NONE
constant _Ffmpeg.CODEC_ID_AC3
constant _Ffmpeg.CODEC_ID_ADPCM_IMA_QT
constant _Ffmpeg.CODEC_ID_ADPCM_IMA_WAV
constant _Ffmpeg.CODEC_ID_ADPCM_MS
constant _Ffmpeg.CODEC_ID_H263
constant _Ffmpeg.CODEC_ID_H263I
constant _Ffmpeg.CODEC_ID_H263P
constant _Ffmpeg.CODEC_ID_MJPEG
constant _Ffmpeg.CODEC_ID_MPEG1VIDEO
constant _Ffmpeg.CODEC_ID_MPEG4
constant _Ffmpeg.CODEC_ID_MP2
constant _Ffmpeg.CODEC_ID_MP3LAME
constant _Ffmpeg.CODEC_ID_MSMPEG4V1
constant _Ffmpeg.CODEC_ID_MSMPEG4V2
constant _Ffmpeg.CODEC_ID_MSMPEG4V3
constant _Ffmpeg.CODEC_ID_PCM_ALAW
constant _Ffmpeg.CODEC_ID_PCM_MULAW
constant _Ffmpeg.CODEC_ID_PCM_S16BE
constant _Ffmpeg.CODEC_ID_PCM_S16LE
constant _Ffmpeg.CODEC_ID_PCM_S8
constant _Ffmpeg.CODEC_ID_PCM_U16BE
constant _Ffmpeg.CODEC_ID_PCM_U16LE
constant _Ffmpeg.CODEC_ID_PCM_U8
constant _Ffmpeg.CODEC_ID_RAWVIDEO
constant _Ffmpeg.CODEC_ID_RV10
constant _Ffmpeg.CODEC_ID_SVQ1
constant _Ffmpeg.CODEC_ID_VORBIS
constant _Ffmpeg.CODEC_ID_WMV1
constant _Ffmpeg.CODEC_ID_WMV2

Description

Various audio and video codecs.

Note

The list of supported codecs depends on Ffmpeg library.


ConstantCODEC_TYPE_AUDIO
ConstantCODEC_TYPE_VIDEO

constant _Ffmpeg.CODEC_TYPE_AUDIO
constant _Ffmpeg.CODEC_TYPE_VIDEO

Description

Type of codec.

Class _Ffmpeg.ffmpeg

Description

Implements support of all codecs from a nice project Ffmpeg. You can find more info about it at http://ffmpeg.sf.net/.


Methodcreate

_Ffmpeg.ffmpeg_Ffmpeg.ffmpeg(intcodec_name, intencoder)

Description

Create decoder or encoder object.

Parameter codec_name

Internal number of codec, eg. CODEC_ID_MP2.

Parameter encoder

If true, encoder object will be created, decoder object otherwise.


Methoddecode

mapping|intdecode(stringdata)

Description

Returns a mapping with the new decoded frame and lenght of data which was used for decoding.


Methoddecode

intdecode(stringdata, function(:void) shuffler)

Description

Decode all data buffer and pass result to shuffler. Returns 1 on success, 0 otherwise.

Note

Shuffler variant isn't implemented, yet.

Note

Usable only in decoder.

See also

create()


Methodencode

mapping|intencode(stringdata)

Description

Returns mapping with new encoded frame and length of data which was used for encoding.


Methodencode

intencode(stringdata, function(:void) shuffler)

Description

Returns 1 on success, 0 otherwise.

Note

Usable only in encoder

See also

create()


Methodget_codec_info

mapping|intget_codec_info()

Description

Returns mapping with info of used codec.

See also

list_codecs()


Methodget_codec_status

mapping|intget_codec_status()

Description

Returns a mapping with the actual codec parameters.

See also

set_codec_param()


Methodlist_codecs

array(mapping) list_codecs()

Description

Gets all supported codecs.

Returns

Array of mapping with codec features.


Methodset_codec_param

intset_codec_param(stringname, mixedvalue)

Description

Sets one codec parameter

Parameter name

The name of parameter. One of "sample_rate", "bit_rate", "channels".

Returns

Returns 1 on success, 0 otherwise (parameter not known).

See also

get_codec_params()

Module _Stdio

Description

Low-level I/O.

This is usually NOT the module you want. Try Stdio instead.

See also

Stdio


ConstantIPPROTO_IP

constant _Stdio.IPPROTO_IP

Description

Used in File.setsockopt() to set IP-level options


ConstantIPPROTO_TCP

constant _Stdio.IPPROTO_TCP

Description

Used in File.setsockopt() to set TCP-level options


ConstantIP_TOS

constant _Stdio.IP_TOS

Description

Used in File.setsockopt() to set Type Of Service


ConstantNOTE_ATTRIB

constantint _Stdio.NOTE_ATTRIB

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for attribute changes on a file.

Note

Available on systems that use kqueue.


ConstantNOTE_DELETE

constantint _Stdio.NOTE_DELETE

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for deletion of a file.

Note

Available on systems that use kqueue.


ConstantNOTE_EXTEND

constantint _Stdio.NOTE_EXTEND

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for extension events on a file.

Note

Available on systems that use kqueue.


ConstantNOTE_LINK

constantint _Stdio.NOTE_LINK

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for changes to a file's link count.

Note

Available on systems that use kqueue.


ConstantNOTE_RENAME

constantint _Stdio.NOTE_RENAME

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for move or rename events on a file.

Note

Available on systems that use kqueue.


ConstantNOTE_REVOKE

constantint _Stdio.NOTE_REVOKE

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for access revokation (unmount, etc).

Note

Available on systems that use kqueue.


ConstantNOTE_WRITE

constantint _Stdio.NOTE_WRITE

Description

Used with Stdio.File()->set_fs_event_callback() to monitor for writes to a file.

Note

Available on systems that use kqueue.


ConstantPROP_BIDIRECTIONAL

constantint _Stdio.PROP_BIDIRECTIONAL

Description

The file is bi-directional.

See also

Stdio.File()->pipe()


ConstantPROP_BUFFERED

constantint _Stdio.PROP_BUFFERED

Description

The file is buffered (usually 4KB).

See also

Stdio.File()->pipe()


ConstantPROP_IPC

constantint _Stdio.PROP_IPC

Description

The file may be used for inter process communication.

See also

Stdio.File()->pipe()


ConstantPROP_NONBLOCK

constantint _Stdio.PROP_NONBLOCK

Description

The file supports nonblocking I/O.

See also

Stdio.File()->pipe()


ConstantPROP_REVERSE

constantint _Stdio.PROP_REVERSE

Description

Request reversed operation.

Used as argument to Stdio.File()->pipe(), when PROP_BIDIRECTIONAL hasn't been specified, to request the direction of the resulting pipe to reversed.

See also

Stdio.File()->pipe()


ConstantPROP_SEND_FD

constantint _Stdio.PROP_SEND_FD

Description

The Stdio.File object might support the Stdio.File()->send_fd() operation.

See also

Stdio.File()->pipe(), Stdio.File()->send_fd(), Stdio.File()->receive_fd()


ConstantPROP_SHUTDOWN

constantint _Stdio.PROP_SHUTDOWN

Description

The file supports shutting down transmission in either direction.

See also

Stdio.File()->close(), Stdio.File()->pipe()


ConstantPROP_TTY

constantint _Stdio.PROP_TTY

Description

The Stdio.File object supports tty operations.

Note

This constant is only present on platforms where pseudo tty (aka pty) operations are available, and may thus be used to detect whether such operations should be attempted.

See also

Stdio.File()->pipe()


ConstantSOL_SOCKET

constant _Stdio.SOL_SOCKET

Description

Used in File.setsockopt() to set socket-level options


ConstantSO_KEEPALIVE

constant _Stdio.SO_KEEPALIVE

Description

Used in File.setsockopt() to control TCP/IP keep-alive packets.


ConstantTCP_NODELAY

constant _Stdio.TCP_NODELAY

Description

Used in File.setsockopt() to control Nagle's Algorithm.


ConstantXATTR_CREATE

constant _Stdio.XATTR_CREATE

Description

Used by setxattr function and method to signify a pure create, which will fail if the attribute already exists.


ConstantXATTR_REPLACE

constant _Stdio.XATTR_REPLACE

Description

Used by setxattr function and method to signify a replace, which will fail the the attribute does not already exists.


Constant__HAVE_OOB__

constant _Stdio.__HAVE_OOB__

Description

Exists and has the value 1 if OOB operations are available.

Note

In Pike 7.5 and later OOB operations are always present.


Constant__HAVE_SEND_FD__

constant _Stdio.__HAVE_SEND_FD__

Description

Support for sending of file descriptors over Stdio.File()->pipe() objects with PROP_SEND_FD capability is supported.

See also

Stdio.File()->send_fd(), Stdio.File()->receive_fd(), Stdio.File()->read(), Stdio.File()->write(), Stdio.File()->pipe()


Constant__OOB__

constant _Stdio.__OOB__

Description

Implementation level of nonblocking I/O OOB support.

0

Nonblocking OOB support is not supported.

1

Nonblocking OOB works a little.

2

Nonblocking OOB almost works.

3

Nonblocking OOB works as intended.

-1

Unknown level of nonblocking OOB support.

This constant only exists when OOB operations are available, i.e. when __HAVE_OOB__ is 1.


Methodget_all_active_fd

array(int) get_all_active_fd()

Description

Returns the id of all the active file descriptors.


Methodgethostip

mapping(string:mapping) gethostip()

Description

Returns the IP addresses of the host.

Returns

Returns a mapping that maps interface name to a mapping with more information about that interface. That information mapping looks as follows.

"ips" : array(string)

A list of all IP addresses bound to this interface.


Methodgetprotobyname

intgetprotobyname(string(8bit)name)

Description

Returns the protocol number of the protocol name. This calls the POSIX function getprotobyname. If the protocol cannot be found an error is thrown.

Enum _Stdio.FileModeFlags

Description

File mode flags returned by Fd()->mode().


ConstantFILE_APPEND

constantint _Stdio.FILE_APPEND

Description

File open for appending.


ConstantFILE_CREATE

constantint _Stdio.FILE_CREATE

Description

Create a new file if it didn't exist earlier.


ConstantFILE_EXCLUSIVE

constantint _Stdio.FILE_EXCLUSIVE

Description

Exclusive access to the file.


ConstantFILE_NONBLOCKING

constantint _Stdio.FILE_NONBLOCKING

Description

File opened in nonblocking mode.


ConstantFILE_READ

constantint _Stdio.FILE_READ

Description

File open for reading.


ConstantFILE_TRUNC

constantint _Stdio.FILE_TRUNC

Description

Truncate the file on open.


ConstantFILE_WRITE

constantint _Stdio.FILE_WRITE

Description

File open for writing.

Enum _Stdio.FilePropertyFlags

Description

File properties for use with eg Fd()->pipe(), and returned by eg Fd()->mode().


ConstantPROP_BIDIRECTIONAL

constantint _Stdio.PROP_BIDIRECTIONAL

Description

File supports both sending and receiving.


ConstantPROP_BUFFERED

constantint _Stdio.PROP_BUFFERED

Description

File has internal buffering.


ConstantPROP_IPC

constantint _Stdio.PROP_IPC

Description

File can be used for interprocess communication.


ConstantPROP_NONBLOCK

constantint _Stdio.PROP_NONBLOCK

Description

File supports nonblocking operation.


ConstantPROP_SEND_FD

constantint _Stdio.PROP_SEND_FD

Description

File is capable of sending open file descriptors.


ConstantPROP_SHUTDOWN

constantint _Stdio.PROP_SHUTDOWN

Description

File supports unidirectional close.


ConstantPROP_TTY

constantint _Stdio.PROP_TTY

Description

File supports tty operations.

Class _Stdio.Buffer

Description

A buffer to use as input or buffering when doing I/O. It is similar to String.Buffer, but can only contain 8bit data and is designed for protocol parsing. It is optimized for reading from the beginning and adding to the end, and will try to minimise the amount of data copying that is done.

The class maintains two separate offsets, one for reading and one for writing. The functions that add data all do so at the write offset (the end of the buffer), and reading is done from the read offset (the start of the buffer).

The class can also be used to directly read from and write to filedescriptors if so desired. This eliminates at least one memory copy.

Note

The "avoid copy" part means that a Buffer will never shrink unless you call the trim function.


Method__set_on_write

void__set_on_write(function(:void) write_callback)

Description

This tells the buffer to trigger the write callback for the specified file descriptor when data is added to the buffer.

Note

This is used internally by Stdio.File and SSL.File to handle nonblocking buffered mode, and is not necessarily intended to be used directly by anything but implementations of File or Stream like programs. Do not use this yourself on buffers with Files or Streams in buffer modes.


Method_encode
Method_decode

string(8bit)encode_value(_Stdio.Bufferdata)
_Stdio.Bufferdecode_value(string(8bit)data)

Description

Encode and decode Stdio.Buffer objects. Only the buffer data is kept, no other state is saved.


Method_search

int(-1..)search(_Stdio.Bufferfrom, int(8bit)character, int|voidstart, int(0..)|voidend)

Description

Search forward from the indicated start position for the specified character.

Parameter character

Character to search for.

Parameter start

Start position relative to the current read position of the buffer.

Negative start values are supported and indicate positions prior to the current read position.

Parameter end

Don't search past this position of the buffer.

Returns

Returns the first found position of character relative to the current read position of the buffer on success, and UNDEFINED on not found. The read position is not advanced.

See also

read_cstring(), search(), lfun::_search()


Method_search

int(-1..)search(_Stdio.Bufferfrom, string(8bit)substring, int|voidstart, int|voidend)

Description

Search forward from the indicated start position for the specified substring.

Parameter substring

Substring to search for.

Parameter start

Start position relative to the current read position of the buffer.

Negative start values are supported and indicate positions prior to the current read position.

Parameter end

Don't search past this position of the buffer.

Returns

Returns the first found position of substring relative to the current read position of the buffer on success, and UNDEFINED on not found. The read position is not advanced.

See also

read_cstring(), search(), lfun::_search()


Method_sizeof

intsizeof(_Stdio.Bufferarg)

Description

Returns the buffer size, in bytes. This is how much you can read from the buffer until it runs out of data.


Method`[..]

string(8bit) res = _Stdio.Buffer()[start..end]

Description

Range operator.

Returns

Returns a string of the characters at offset low through high. Returns the empty string if no data is available in the range.


Method`[]

int(-1..255) res = _Stdio.Buffer()[ off ]

Description

Return the character at the specified offset.

Returns

Returns the character at offset off on success, and -1 otherwise.

Note

Indexing with negative offsets was not supported in Pike 8.0 and earlier.


Method`[]=

_Stdio.Buffer()[ off ] = char

Description

Set the character at the specified offset to char.

Note

Indexing with negative offsets was not supported in Pike 8.0 and earlier.


Methodadd

Bufferadd(AddArgument ... data)

Description
private typedef System.Memory|Stdio.Buffer|String.Buffer BufferObject;
 private typedef BufferObject|string(8bit)|int(8bit)|array(AddArgument) AddArgument;

Add the items in data to the end of the buffer.

The supported argument types are:

string(8bit)

An eight bit string.

int(8bit)

A single byte

System.Memory

A chunk of memory. The whole memory area is added.

Stdio.Buffer

A chunk of memory. The whole memory area is added.

String.Buffer

A chunk of memory. The whole memory area is added.

array(AddArgument)

Add all elements in the array individually. Each element may be any one of the types listed here.

See also

sprintf, add_int8, add_int16, add_int32, add_int and add_hstring


Methodadd_hint

Bufferadd_hint(inti, int(0..)size_width)

Description

First add the size of the integer when encoded to base 256 as a size_width integer, then add the integer to the buffer, both in network byte order.

size_width must be less than Int.NATIVE_MAX.


Methodadd_hstring

Bufferadd_hstring(string(8bit)data, int(0..)size_size)
Bufferadd_hstring(Stdio.Bufferdata, int(0..)size_size)
Bufferadd_hstring(System.Memorydata, int(0..)size_size)
Bufferadd_hstring(String.Bufferdata, int(0..)size_size)
Bufferadd_hstring(int(8bit)data, int(0..)size_size)
Bufferadd_hstring(arraydata, int(0..)size_size)
Bufferadd_hstring(int|string(8bit)|Stdio.Buffer|System.Memory|arraydata, int(0..)size_size, int(0..)offset)

Description

Adds length of data followed by data to the buffer.

This is identical to sprintf("%"+size_size+"H",(string)Stdio.Buffer(data)) but significantly faster.

size_size is the number of bytes used to represent the length of the data. It must be less than Int.NATIVE_MAX.

offset is added to the length of the data prior to writing out the length. Typical usage involves adding size_size to account for the room used by the size.

The supported data argument types are

int(8bit)

An eight bit character.

string(8bit)

An eight bit string.

System.Memory

A chunk of memory. The whole memory area is added.

Stdio.Buffer

A chunk of memory. The whole memory area is added.

String.Buffer

A chunk of memory. The whole memory area is added.

array

Add all elements in the array individually. Each element may be any one of the types listed here.


Methodadd_int

Bufferadd_int(inti, int(0..)width)

Description

Adds a generic integer to the buffer as an (width*8)bit network byteorder number.

width must be less than Int.NATIVE_MAX.


Methodadd_int16

Bufferadd_int16(int(16bit))

Description

Add a 16-bit network byte order value to the buffer


Methodadd_int16

Bufferadd_int16(Gmp.mpz)

Description

Add a 16-bit network byte order value to the buffer


Methodadd_int32

Bufferadd_int32(inti)

Description

Adds a 32 bit network byte order value to the buffer


Methodadd_int32

Bufferadd_int32(Gmp.mpzi)

Description

Adds a 32 bit network byte order value to the buffer


Methodadd_int8

Bufferadd_int8(int(8bit))

Description

Adds a single byte to the buffer.


Methodadd_int8

Bufferadd_int8(Gmp.mpz)

Description

Adds a single byte to the buffer.


Methodadd_ints

Bufferadd_ints(array(int) integers, int(8bit)len)

Description

Add the integers in the specified array, len bytes per int. Equivalent to calling add_int for each integer, but faster, and if an error occurs the buffer will contain no new data. Either all or none of the integers will be added.

Errors can occur if one of the elements in integers is not actually an integer, if sizeof(integers)*len is bigger than can be represented in a size_t, or if the buffer cannot grow due to an out of memory condition.


Methodadd_padding

Bufferadd_padding(int(0..)nbytes, int(8bit)|voidbyte)

Description

Add nbytes bytes of padding, if byte is not specified the area will be filled with 0's, otherwise the specified byte will be repeated.


Methodallocate

voidallocate(int(0..)n)

Description

Make sure that at least n bytes of space are available in this buffer.


Methodcast

(string(8bit))_Stdio.Buffer()

Description

Convert the buffer to a string.

Note

This only works for buffers whose length is less than 0x7fffffff.


Methodclear

voidclear()

Description

Clear the buffer.


Methodconsume

int(0..)|int(-1)consume(int(0..)n)

Description

Discard the first n bytes from the buffer

Returns -1 on error and the amount of space still left otherwise.


Methodcreate

_Stdio.Buffer_Stdio.Buffer(int|voidlen)
_Stdio.Buffer_Stdio.Buffer(string(8bit)contents)
_Stdio.Buffer_Stdio.Buffer(System.Memory|String.Buffercontents)

Description

If passed an integer or no argument, create a buffer of that size, or if no argument is given, 226 bytes.

If contents are specified a new buffer with the contents of the given string/System.Memory or String.Buffer will be created.

Note

In the String.Buffer case the data has to be copied unless there is only one reference to the String.Buffer object, since modifications of the String.Buffer would cause the Buffer to point into invalid memory.

In all other cases this will not copy the string data, instead data will be read from the source until it needs to be modified, so the buffer creation is fast regardless of the length of the string.

However, as an example, if the buffer is created with a 100Gb System.Memory mmap:ed file as the contents and you later on try to modify the buffer using one of the add functions (or sprintf and similar) the old contents will be copied.

You can use read_only() to avoid accidents.


Methodinput_from

int(-1..)input_from(Stdio.Streamf, int|voidnbytes)

Description

Read data from f into this buffer. If nbytes is not specified, read until there is no more data to read (currently).

Returns the amount of data that was read, or -1 on read error.

Note

Please note that this funcition will read all data from the filedescriptor unless it's set to be non-blocking.


Methodlock

objectlock()

Description

Makes this buffer read only until the returned object is released.

Note

This currently simply returns a 0-length subbuffer.


Methodmatch

__deprecated__string(8bit)|int|float|arraymatch(string(8bit)format)

Description

Reads data from the beginning of the buffer to match the specifed format, then return the match.

The non-matching data will be left in the buffer.

This function is very similar to sscanf, but the result is the sum of the matches. Most useful to match a single value.

Returns

Returns the sum of the matching %-expressions, "" if a prefix (but no %-expression) matches and UNDEFINED on mismatch. Note that the addition may throw errors.

Note

Prior to Pike 9.0 0 was returned on mismatch and format was returned on a prefix match.

Example
// Get the next whitespace separated word from the buffer.
    buffer->match("%*[ \t\r\n]%[^ \t\r\n]");// Get the next integer as a string.
    buffer->match("%0s%d");
Deprecated

Replaced by sscanf.

See also

sscanf(), predef::sscanf(), array_sscanf()


Methodoutput_to

int(-1..)output_to(Stdio.Stream|function(string(8bit):int) fun, int(0..)|voidnbytes)

Description

Write data from the buffer to the indicated file.

Parameter fun

Write function. Either one of:

Stdio.Stream

A file object in which the function write() will be called.

function(string(8bit):int)

A function which will be called with a string(8bit) to write and is expected to return an int indicating the number of bytes successfully written or -1 on failure.

Parameter nbytes

If nbytes is not specified the whole buffer will be written if possible. Otherwise at most nbytes will be written.

Returns

Will return the number of bytes that have been written successfully.

If no bytes have been written successfully and fun() failed with an error, -1 will be returned.

Deprecated

This function is going to get deprecated. In case you want to use it against an Stdio.File like object, please consider using the f->write(buf) API. If you want to use it against a custom write function, please consider supporting the f->write(buf) API in it.


Methodrange_error

protectedboolrange_error(inthowmuch)

Description

This function is called when an attempt is made to read out of bounds.

The default implementation simply returns 0 (zero).

Override this function to change the behavior.

Parameter howmuch

The argument howmuch indicates how much data is needed:

(1..)

Need howmuch bytes more

0

The amount of data needed is not certain. This most often happens when sscanf or read_json is used

(..-1)

Tried to unread -howmuch bytes. There is usually no way to satisfy the requested range.

The only supported way is to extract the data from the buffer, add the requested amount of "go backbuffer", add the data back, and forward -howmuch bytes.

Returns

true if the operation should be retried, false otherwise.

Do not return true unless you have added data to the buffer, doing so could result in an infinite loop (since no data is added, the range_error will be called again immediately).


Methodread

string(8bit)read()

Description

Read all data from the buffer.

If there is not enough data available this returns 0.

This is basically equivalent to (string)buffer, but it also removes the data from the buffer.

See also

try_read()


Methodread

string(8bit)read(int(0..)n)

Description

Read n bytes of data from the buffer.

If there is not enough data available this returns 0.

See also

try_read()


Methodread_buffer

Bufferread_buffer(int(0..)n)
Bufferread_buffer(int(0..)n, boolcopy)

Description

Same as read, but returns the result as an Buffer.

No data is copied unless copy is specified and true, the new buffer points into the old one.

Note

As long as the subbuffer exists the main buffer is locked in memory.

Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.


Methodread_cstring

string(8bit)read_cstring(void|int(8bit)sentinel, void|int(8bit)escape)

Description

Reads a \0 terminated C-string and returns the string excluding the terminating \0.

If there is not enough data available return UNDEFINED.

Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).

Parameter sentinel

A different character can be used as end sentinel of the string.

Parameter escape

An optional character used as a prefix to quote the following character. UNDEFINED and the same value as sentinel mean that there is no escape character.

Note

Escape characters (if any) are left untouched in the returned string.

See also

_search()


Methodread_hbuffer

Bufferread_hbuffer(intn)
Bufferread_hbuffer(intn, boolcopy)

Description

Same as read_hstring, but returns the result as an Buffer.

No data is copied unless copy is specified and true, the new buffer points into the old one.

Note

As long as the subbuffer exists no data can be added to the main buffer.

Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.

If you need to unlink the new buffer after it has been created, call trim in it.


Methodread_hint

intread_hint(int(0..)n)

Description

Read a network byte order unsigned number of size n*8 bits, then read another network byte order number of the size indicated by the first size.

Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.


Methodread_hstring

string(8bit)read_hstring(int(0..)n, void|intoffset)

Description

Identical in functionality to read(read_number(n)) but faster.

Read a network byte order number of size n*8 bits, then return the indicated number of bytes as a string.

offset is substracted from the specified length prior to reading the string. Typical usage involves substracting n to account for the room used by the size.

If there is not enough data available return 0.

Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).


Methodread_int

intread_int(int(0..)n)

Description

Read a network byte order unsigned number of size n*8 bits, then return it.

Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.

See also

read_le_int


Methodread_int16

int(16bit)read_int16()


Methodread_int24

int(24bit)read_int24()


Methodread_int32

int(32bit)read_int32()


Methodread_int8

int(8bit)read_int8()


Methodread_ints

array(int) read_ints(intn, int(8bit)width)

Description

Read a list of n network byte order unsigned numbers each of size width*8 bits, then return it.

Will return 0 if there is not enough buffer space available unless error mode is set to throw errors.


Methodread_json

mixedread_json(int|voidrequire_whitespace_separator)

Description

Read a single JSON expression from the buffer and return it.

If require_whitespace_separator is true there must be a whitespace after each json value (as an example, newline or space).

The JSON is assumed to be utf-8 encoded.

Returns

UNDEFINED if no data is available to read. The read value otherwise.

Note

Unless whitespaces are required this function only really work correctly with objects, arrays and strings.

There is really no way to see where one value starts and the other ends for most other cases


Methodread_le_int

intread_le_int(int(0..)n)

Description

Read a little endian byte order unsigned number of size n*8 bits, then return it.

Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.

See also

read_int


Methodread_only

voidread_only()

Description

This makes the existing data in the buffer permanently read only.

Note

You can use lock() to do this temporarily.


Methodread_sint

intread_sint(intsize)

Description

Read a network byte order two:s complement signed number of size n*8 bits, then return it.

Will return UNDEFINED if there is not enough buffer space available unless error mode is set to throw errors.


Methodrewind_on_error
Methodrewind_key

RewindKeyrewind_on_error()
RewindKeyrewind_key()

Description

These functions are very similar. The rewind_on_error variant will create an object that, when it goes out of scope without having been destructed explicitly, will cause the buffer to rewind to the location it had when this function is called.

This will happen if you throw an error or otherwise let the object fall out of scope.

Use destruct(RewindKey) or RewindKey.release to stop the buffer from being rewound.

The second version (rewind_key) requires you to explicitly call RewindKey.rewind to do the rewind.

Take some care with these objects, if you create multiple ones at once the results might be somewhat confusing if you do not release them in the reverse order they were created in (then again, you almost certainly really only need one)

You can call RewindKey.update in the generated object to change where it will be rewound to.

The typical use-case of this functionality is when parsing a packet protocol with variable length packets where the length is not immediately known. It saves you from keeping track of how much to rewind if you had not actually gotten the whole packet yet.

Example
void parse_packet(Stdio.Buffer b ){Stdio.Buffer.RewindKey rewind = b->rewind_on_error();
  b->set_error_mode(1);switch( b->read_int8())// packet type{case DATA:int channel = b->read_int8();Stdio.Buffer data = b->read_hbuffer( 4 );// we have read the whole packet, so no longer rewind on error.
      rewind->release();return handle_data_packet( channel, data );}}
Note

Just calling rewind_on_error without assigning the return value to something will not do anything. You need to keep the object around while the rewind-to position is still valid.

Keeping the object around forbids the buffer from moving data inside itself, this means that it can only grow. So do not keep the rewind key when it is not needed.


Methodset_error_mode

Bufferset_error_mode(intm)
Bufferset_error_mode(programm)

Description

Set the error mode of this buffer to m.

If true operations that would normally return 0 (like trying to read too much) will instead throw an error. If m is a program a clone of it will be thrown on error.

This is useful when parsing received data, you do not have to verify that each and every read operation suceeds.

However, the non-error mode is more useful when checking to see if a packet/segment/whatever has arrived.

The thrown error object will have the constant buffer_error set to a non-false value.

Example
void read_callback(int i,string(8bit) new_data){
  inbuffer->add( new_data );while( Buffer packet = inbuffer->read_hbuffer(2)){
    packet->set_error_mode(Buffer.THROW_ERROR);if(mixed e =catch( handle_packet( packet )))if( e->buffer_error )
        protocol_error();// illegal data in packetelse
        throw(e);// the other code did something bad}}void handle_packet( Buffer pack ){switch( pack->read_int8()){
    ...
  case HEADER_FRAME:int num_headers = pack->read_int32();for(int i = 0; i<num_headers; i++ )
     headers[pack->read_hstring(2)]= pack->read_hstring(2);
    ...
  }}

Methodset_max_waste

voidset_max_waste(floatfactor)

Description

Configure how much free space should be allowed, at most, as a factor of the current buffer size.

The default is 0.5, leaving at most half the buffer as waste.


Methodsprintf

Buffersprintf(strict_sprintf_formatformat, sprintf_args ... args)

Description

Appends the output from sprintf at the end of the buffer.

This is somewhat faster than add(sprintf(...)) since no intermediate string is created.


Methodsscanf

arraysscanf(string(8bit)format)

Description

Reads data from the beginning of the buffer to match the specifed format, then return an array with the matches.

The non-matching data will be left in the buffer.

See array_sscanf for more information.

See also

match(), predef::sscanf(), array_sscanf()


Methodtrim

voidtrim()

Description

Frees unused memory.

Note that calling this function excessively will slow things down, since the data often has to be copied.

Note

This function could possibly throw an out-of-memory error if the realloc fails to find a new (smaller) memory area.


Methodtruncate

int(0..)|int(-1)truncate(int(0..)n)

Description

Truncates the buffer to a length of n bytes.

Returns -1 on error and the number of bytes removed otherwise.


Methodtry_read

string(8bit)try_read(int(0..)len)

Description

Attempt to read some data from the buffer.

Parameter len

Read at most len bytes from the buffer.

Returns

If the buffer contains less than len bytes of data, the entire buffer contents are returned. Otherwise the first len bytes are returned.

See also

read()


Methodunread

int(0..)|int(-1)unread(int(0..)n)

Description

Rewind the buffer n bytes.

Returns

This function returns how many more bytes of buffer is available to rewind, or -1 on error.

Note

Unless you add new data to the buffer using any of the add functions you can always rewind.

You can call unread(0) to see how much.

Class _Stdio.Buffer.RewindKey

Description

The return value of Buffer.rewind_on_error() and Buffer.rewind_key()

This object will cause the buffer to unwind to the position it was at when the object was created either when it is released (when it falls out of scope, explicit destruct does not count) or when rewind is called, depending on which function was used to create it.


Methodrelease

voidrelease()

Description

Do not rewind if the object is released.

Note

This is equivalent to calling destruct() on the object


Methodrewind

voidrewind()

Description

Rewinds the buffer explicitly.

Note

Destructs this RewindKey


Methodupdate

voidupdate()

Description

Update the location the buffer will be rewound to to the current position of the buffer.

Class _Stdio.Fd

Description

Low level I/O operations.

Note

This is not the class you want. Use Stdio.File and friends instead.

See also

Stdio.File, Stdio.FILE, _Stdio.Fd_ref


Variable_errno

protectedint(0..) _Stdio.Fd._errno

Description

Variable containing the internal value returned by errno().

See also

errno()


Variable_read_callback
Variable_write_callback
Variable_read_oob_callback
Variable_write_oob_callback
Variable_error_callback
Variable_fs_event_callback

mixed _Stdio.Fd._read_callback
mixed _Stdio.Fd._write_callback
mixed _Stdio.Fd._read_oob_callback
mixed _Stdio.Fd._write_oob_callback
mixed _Stdio.Fd._error_callback
mixed _Stdio.Fd._fs_event_callback

Description

Callback functions installed by Stdio.File()->set_callbacks() et al.


Variable_fd

Fd _Stdio.Fd._fd

Note

Read only


Methodcd

boolcd(string(8bit)|voidrelpath)

Description

Change current directory relative to this file.

Returns

Returns 1 on success and 0 (zero) on failure.

See also

predef::cd()


Methodclose

intclose()
intclose(stringdirection)

Description

Close a file or stream.

If direction is not specified, both the read and the write direction are closed. Otherwise only the directions specified is closed.

Returns

Returns 1 if the file or stream now is closed in all directions, and 0 otherwise.

Throws

An exception is thrown if an I/O error occurs.

The default behaviour for sockets is typically to flush buffered data in the background, but this can be changed with linger().

Note

close() has no effect if this file object has been associated with an already opened file, i.e. if open() was given an integer as the first argument.

See also

linger(), open(), open_socket()


Methodconnect

boolconnect(stringdest_addr, intdest_port)
boolconnect(stringdest_addr, intdest_port, stringsrc_addr, intsrc_port)
string(8bit)|int(0)connect(stringdest_addr, intdest_port, string|int(0)src_addr, int|int(0)src_port, string(8bit)data)

Description

Open a TCP/IP connection to the specified destination.

In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.

If the data argument is included the socket will use TCP_FAST_OPEN if available, if not the data will not be sent. In the data case the function either returns the data that has not been sent (only one packet can be sent with this option) or 0 if the connection failed immediately.

Returns

Returns 1 or the remaining data on success, and 0 on failure.

Note

In nonblocking mode 0 (zero) may be returned and errno() set to EWOULDBLOCK or WSAEWOULDBLOCK. This should not be regarded as a connection failure.

See also

open_socket()


Methodconnect_unix

boolconnect_unix(stringfilename)

Description

Open a UNIX domain socket connection to the specified destination.

Parameter filename

Filename to create.

In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.

Returns

Returns 1 on success, and 0 on failure.

Note

In nonblocking mode 0 (zero) may be returned and errno() set to EWOULDBLOCK or WSAEWOULDBLOCK. This should not be regarded as a connection failure.

Note

path had a quite restrictive length limit (~100 characters) prior to Pike 7.8.334.


Methodcreate

_Stdio.Fd_Stdio.Fd(stringfilename)
_Stdio.Fd_Stdio.Fd(stringfilename, stringmode)
_Stdio.Fd_Stdio.Fd(stringfilename, stringmode, intaccess)
_Stdio.Fd_Stdio.Fd(intfd)
_Stdio.Fd_Stdio.Fd(intfd, stringmode)

Description

See open().

See also

open()


Methoddup

Stdio.Fddup()

Description

Duplicate the file.

See also

dup2()


Methoddup2

intdup2(Stdio.Fileto)

Description

Duplicate a file over another.

This function works similarly to assign(), but instead of making the argument a reference to the same file, it creates a new file with the same properties and places it in the argument.

Returns

Returns 1 on success and 0 (zero) on failure.

Note

to need not be open, in which case a new fd is allocated.

Note

Note also that to is also assigned to the same backend (if any) as this object.

See also

assign(), dup()


Methoderrno

interrno()

Description

Return the errno for the latest failed file operation.


Methodfd_factory

Fdfd_factory()

Description

Factory creating Stdio.Fd objects.

This function is called by openat(), pipe(), dup() and other functions creating new file objects.

The default implementation calls object_program(this_object())() to create the new object, and returns the Fd inherit in it.

Note

Note that this function must return the Fd inherit in the object.

See also

Stdio.Port()->fd_factory(), openat(), pipe()


Methodget_dir

array(string) get_dir(string|voidpath)

Description

Get directory contents relative to an open directory.

Parameter path

Path relative to the open directory. Defaults to the directory itself.

Returns

Returns an array of filenames.

Note

Not available on all architectures.

See also

predef::get_dir(), statat(), openat(), unlinkat()


Methodgetxattr

stringgetxattr(stringattr)

Description

Return the value of a specified attribute, or 0 if it does not exist


Methodgrantpt

stringgrantpt()

Description

If this file has been created by calling openpt(), return the filename of the associated pts-file. This function should only be called once.

Returns

Returns the filename of the corresponding pts.

Note

This function is only available on some platforms.


Methodhardlinkat

voidhardlinkat(string(8bit)from, string(8bit)to, Stdio.File|voidtofd)

Description

Create a hardlink named to from the file from, where from is relative to this file, and to is relative to tofd unless it is not set in which case it is also relative to this file.

Note

This function is not available on all platforms.

See also

hardlink(), symlinkat(), unlinkat()


Methodis_open

intis_open()

Description

Returns true if the file is open.

Note

If the file is a socket that has been closed from the remote side, this function might still return true.

Note

Most methods can't be called for a file descriptor that isn't open. Notable exceptions errno, mode, and the set and query functions for callbacks and backend.


Methodisatty

boolisatty()

Description

Returns true if the file is a terminal.


Methodlinger

boollinger(int(-1..65535)|voidseconds)

Description

Set the socket linger behaviour on close().

Parameter seconds
-1

Reset to default behaviour. This typically means that close() will return immediately, but any buffered data will still be sent if possible.

0

Terminate the connection immediately on close(), and discard any buffered data.

(1..65535)

Have close() wait for at most seconds seconds for any buffered data to be sent after which the connection is terminated.

Returns

Returns 1 on success, and 0 (zero) on failure.

Note

This operation is only valid on sockets.

Note

This function was not available in Pike 7.8.775 and earlier.

See also

close()


Methodlistxattr

array(string) listxattr()

Description

Return an array of all extended attributes set on the file


Methodlock

Stdio.FileLockKeylock()
Stdio.FileLockKeylock(boolis_recursive)

Description

Makes an exclusive file lock on this file.

See also

trylock()


Methodmode

FileModeFlags|FilePropertyFlagsmode()

Description

Returns the open mode and capabilities for the file.

Returns

Returns an `|() of the following flags:

0x1000

FILE_READ

0x2000

FILE_WRITE

0x4000

FILE_APPEND

0x8000

FILE_CREATE

0x0100

FILE_TRUNC

0x0200

FILE_EXCLUSIVE

0x0400

FILE_NONBLOCKING

0x0080

PROP_TTY

0x0040

PROP_SEND_FD

0x0010

PROP_BIDIRECTIONAL

0x0008

PROP_BUFFERED

0x0004

PROP_SHUTDOWN

0x0002

PROP_NONBLOCK

0x0001

PROP_IPC

Note

In some versions of Pike 7.8 the PROP_ flags were filtered from the result.

See also

open()


Methodopen

intopen(stringfilename, stringmode)
intopen(stringfilename, stringmode, intaccess)
intopen(intfd, stringmode)

Description

Open a file, or use an existing fd.

If filename is given, attempt to open the named file. If fd is given instead, it should be the file descriptor for an already opened file, which will then be used by this object.

mode describes how the file is opened. It's a case-insensitive string consisting of one or more of the following letters:

"r"

Open for reading.

"w"

Open for writing.

"a"

Append new data to the end.

"c"

Create the file if it doesn't exist already.

"t"

Truncate the file to zero length if it already contains data. Use only together with "w".

"x"

Open exclusively - the open fails if the file already exists. Use only together with "c". Note that it's not safe to assume that this is atomic on some systems.

access specifies the permissions to use if a new file is created. It is a UNIX style permission bitfield:

0400

User has read permission.

0200

User has write permission.

0100

User has execute permission.

0040

Group has read permission.

0020

Group has write permission.

0010

Group has execute permission.

0004

Others have read permission.

0002

Others have write permission.

0001

Others have execute permission.

It's system dependent on which of these bits that are actually heeded. If access is not specified, it defaults to 00666, but note that on UNIX systems it's masked with the process umask before use.

Returns

Returns nonzero on success and 0 (zero) on failure. If there is a failure then errno returns the error code.

See also

close()


Methodopen_socket

boolopen_socket(int|voidport, string|voidaddr, int|string|voidfamily_hint)


Methodopenat

Stdio.Fileopenat(stringfilename)
Stdio.Fileopenat(stringfilename, stringmode)
Stdio.Fileopenat(stringfilename, stringmode, intaccess)

Description

Open a file relative to an opened directory.

Returns

Returns a new file object on success, and 0 (zero) on failure.

Note

Not available on all architectures.

See also

open(), statat(), unlinkat()


Methodopenpt

intopenpt(stringmode)

Description

Open the master end of a pseudo-terminal pair.

Returns

This function returns 1 for success, 0 otherwise.

See also

grantpt()


Methodpeek

int(-1..1)peek()
int(-1..1)peek(int|floattimeout)
int(-1..1)peek(int|floattimeout, intnot_eof)

Description

Check if there is data available to read, or wait some time for available data to read.

More specifically, a later call to read() will return immediately, either due to data being present, or due to some error (eg if a socket has been closed).

Parameter timeout

Timeout in seconds.

Parameter not_eof

Flag for specifying handling of end of file. The following values are currently defined:

0

Traditional (and default) behaviour. Return 1 at EOF.

1

Regard EOF as an error. Return -1 and set errno() to return EPIPE at EOF.

Returns
1

There is data available to read(), or not_eof is 0 (zero) and we're at EOF. A later call to read() will not block.

0

There is no data available (ie timeout).

-1

Error condition. The error code returned by errno() has been updated.

See also

errno(), read()

Note

The function may be interrupted prematurely of the timeout (due to signals); check the timing manually if this is imporant.


Methodpipe

Stdio.Filepipe()
Stdio.Filepipe(intflags)


Methodproxy

voidproxy(Stdio.Filefrom)

Description

Starts a thread that asynchronously copies data from from to this file.

See also

Stdio.sendfile()


Methodquery_address

stringquery_address()
stringquery_address(boollocal)

Description

Get address and port of a socket end-point.

Parameter local

If the argument local is not specified, or is 0 (zero), the remote end-point is returned. Otherwise, if local is 1, the local end-point is returned.

Returns

This function returns the address and port of a socket end-point on the form "x.x.x.x port" (IPv4) or "x:x:x:x:x:x:x:x port" (IPv6). IPv6 addresses may use the contracted syntax.

If this file is not a socket, is not connected, or some other error occurs, 0 (zero) is returned and errno() will return the error code.

Throws

An error is thrown if the socket (or file) isn't open.

See also

connect()


Methodquery_backend

Pike.Backendquery_backend()

Description

Return the backend used for the callbacks.

See also

set_backend


Methodquery_fd

intquery_fd()

Description

Returns the file descriptor number associated with this object.


Methodquery_mtu

intquery_mtu()

Description

Get the Max Transfer Unit for the object (if any).

Returns
-1

Returns -1 if the object is not a socket or if the mtu is unknown.

(1..)

Returns a positive value with the mtu on success.


Methodread

string(8bit)read()
string(8bit)read(intlen)
string(8bit)read(intlen, boolnot_all)

Description

Read data from a file or a stream.

Attempts to read len bytes from the file, and return it as a string. Less than len bytes can be returned if:

  • end-of-file is encountered for a normal file, or

  • it's a stream that has been closed from the other end, or

  • it's a stream in nonblocking mode, or

  • it's a stream and not_all is set, or

  • not_all isn't set and an error occurred (see below).

If not_all is nonzero, read() does not try its best to read as many bytes as you have asked for, but merely returns as much as the system read function returns. This is mainly useful with stream devices which can return exactly one row or packet at a time. If not_all is used in blocking mode, read() only blocks if there's no data at all available.

If something goes wrong and not_all is set, zero is returned. If something goes wrong and not_all is zero or left out, then either zero or a string shorter than len is returned. If the problem persists then a later call to read() fails and returns zero, however.

If everything went fine, a call to errno() directly afterwards returns zero. That includes an end due to end-of-file or remote close.

If no arguments are given, read() reads to the end of the file or stream.

If any file descriptors have been sent by the other side of the stream, receive_fd() will be called once for every sent file descriptor.

Note

It's not necessary to set not_all to avoid blocking reading when nonblocking mode is used.

Note

When at the end of a file or stream, repeated calls to read() will return the empty string since it's not considered an error. The empty string is never returned in other cases, unless nonblocking mode is used or len is zero.

See also

read_oob(), write(), receive_fd(), send_fd()


Methodread

intread(System.Memorydst, void|int(0..)offset)

Description

Reads data from a file or stream into the buffer dst at offset offset. Tries to read as many bytes as buffer space available.

Returns

The number of bytes read. Returns -1 on error and errno() will return the corresponding error code.


Methodread

intread(Stdio.Buffer|String.Bufferdst)

Description

Reads data from a file or stream into the buffer dst. Tries to read as many bytes as buffer space available. Will advance the write position in dst by the number of bytes read.

Returns

The number of bytes read. Returns -1 on error and errno() will return the corresponding error code.


Methodread_oob

stringread_oob()
stringread_oob(intlen)
stringread_oob(intlen, boolnot_all)

Description

Attempts to read len bytes of out-of-band data from the stream, and returns it as a string. Less than len bytes can be returned if:

  • the stream has been closed from the other end, or

  • nonblocking mode is used, or

  • not_all is set, or

  • not_all isn't set and an error occurred (see below).

If not_all is nonzero, read_oob() only returns as many bytes of out-of-band data as are currently available.

If something goes wrong and not_all is set, zero is returned. If something goes wrong and not_all is zero or left out, then either zero or a string shorter than len is returned. If the problem persists then a later call to read_oob() fails and returns zero, however.

If everything went fine, a call to errno() directly afterwards returns zero. That includes an end due to remote close.

If no arguments are given, read_oob() reads to the end of the stream.

Note

It is not guaranteed that all out-of-band data sent from the other end is received. Most streams only allow for a single byte of out-of-band data at a time.

Note

It's not necessary to set not_all to avoid blocking reading when nonblocking mode is used.

Note

When at the end of a file or stream, repeated calls to read() returns the empty string since it's not considered an error. The empty string is never returned in other cases, unless nonblocking mode is used or len is zero.

See also

read(), write_oob()


Methodreadlinkat

stringreadlinkat(string(8bit)path)

Description

Returns what the symbolic link path points to, where path is relative to the open file.

Note

This function is not available on all platforms.

See also

readlink(), symlink(), symlinkat()


Methodreceive_fd

voidreceive_fd(Stdio.Fdfd)

Description

Remote file descriptor reception handler.

Parameter fd

File descriptor received from the remote end of a pipe(). This object has been created by fd_factory().

This function is called from read() when a remote file descriptor has been received over a PROP_SEND_FD capable pipe().

The default implementation is just a prototype.

Overload this function to enable reception of remote file descriptors.

Note

The capability of sending and receiving remote file descriptors is only available on some operating systems. This capability is indicated by the precence of __HAVE_SEND_FD__.

See also

send_fd(), read(), fd_factory(), __HAVE_SEND_FD__


Methodrelease_fd

intrelease_fd()

Description

Returns the file descriptor number associated with this object, in addition to releasing it so that this object behaves as if closed. Other settings like callbacks and backend remain intact. take_fd can later be used to reinstate the file descriptor so that the state is restored.

See also

query_fd(), take_fd()


Methodremovexattr

voidremovexattr(stringattr)

Description

Remove the specified extended attribute.


Methodseek

intseek(intoffset)
intseek(intoffset, stringwhence)

Description

The seek() function repositions the offset of the open file associated with the file descriptor fd to the argument offset according to the directive whence as follows:

Stdio.SEEK_SET

The offset is set to offset bytes.

Stdio.SEEK_CUR

The offset is set to its current location plus offset bytes.

Stdio.SEEK_END

The offset is set to the size of the file plus offset bytes.

If whence is not specified it is SEEK_SET if offset is positive, and if offset is negative SEEK_END.

The seek() function on most operating systems allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.

Seeking file data and holes

Stdio.SEEK_DATA and Stdio.SEEK_HOLE are nonstandard extensions present in Linux, Solaris, FreeBSD, and DragonFly BSD; they are proposed for inclusion in the next POSIX revision.

Stdio.SEEK_DATA

Adjust the file offset to the next location in the file greater than or equal to offset containing data. If offset points to data, then the file offset is set to offset.

Stdio.SEEK_HOLE

Adjust the file offset to the next hole in the file greater than or equal to offset. If offset points into the middle of a hole, then the file offset is set to offset. If there is no hole past offset, then the file offset is adjusted to the end of the file (i.e., there is an implicit hole at the end of any file).

In both of the above cases, seek() fails if offset points past the end of the file.

These operations allow applications to map holes in a sparsely allocated file. This can be useful for applications such as file backup tools, which can save space when creating backups and preserve holes, if they have a mechanism for discovering holes.

For the purposes of these operations, a hole is a sequence of zeros that (normally) has not been allocated in the underlying file storage. However, a filesystem is not obliged to report holes, so these operations are not a guaranteed mechanism for mapping the storage space actually allocated to a file. (Furthermore, a sequence of zeros that actually has been written to the underlying storage may or may not be reported as a hole.)

In the simplest implementation, a filesystem can support the operations by making SEEK_HOLE always return the offset of the end of the file, and making SEEK_DATA always return offset (i.e., even if the location referred to by offset is a hole, it can be considered to consist of data that is a sequence of zeros).

Returns

Upon successful completion, seek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error.

See also

tell()


Methodseek

variant__deprecated__intseek(intunit, intmult)
variant__deprecated__intseek(intunit, intmult, intadd)

Description

Seek to a specified offset in a file.

If mult or add are specified, pos is calculated as pos = unit*mult + add.

If pos is negative then it is relative to the end of the file, otherwise it's an absolute offset from the start of the file.

Returns

Returns the new offset, or -1 on failure.

Note

The arguments mult and add are considered obsolete, and should not be used.

See also

tell()


Methodsend_fd

voidsend_fd(Stdio.Fdfd)

Description

Queues an open file descriptor for sending to the other end of a stream.

Note

The actual sending is performed at the next successful call to write(), this is due to limitations in the system calls. This means that it isn't possible to send a file descriptor without also sending some in-band data.

This operation is only supported on pipe()'s created with PROP_SEND_FD.

This function is not available on all operating systems, check for __HAVE_SEND_FD__.

The queue is emptied on successful write() and when the write direction is close()'d.

See also

receive_fd(), write(), pipe(), read(), __HAVE_SEND_FD__


Methodset_backend

voidset_backend(Pike.Backendbackend)

Description

Set the backend used for the callbacks.

Note

The backend keeps a reference to this object only when it is in callback mode. So if this object hasn't got any active callbacks and it runs out of other references, it will still be destructed quickly (after closing, if necessary).

Also, this object does not keep a reference to the backend.

See also

query_backend, set_nonblocking, set_read_callback, set_write_callback, set_fs_event_callback


Methodset_blocking

voidset_blocking()

Description

Sets this file to blocking operation.

This is the inverse operation of set_nonblocking().

See also

set_nonblocking()


Methodset_buffer

voidset_buffer(intbufsize, stringmode)
voidset_buffer(intbufsize)

Description

Set internal socket buffer.

This function sets the internal buffer size of a socket or stream.

The second argument allows you to set the read or write buffer by specifying "r" or "w".

Note

It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.

See also

open_socket(), accept()


Methodset_close_on_exec

voidset_close_on_exec(boolyes_no)

Description

Marks the file as to be closed in spawned processes.

This function determines whether this file will be closed when calling exec().

Default is that the file WILL be closed on exec except for stdin, stdout and stderr.

See also

Process.create_process(), exec()


Methodset_keepalive

boolset_keepalive(boolon_off)

Description

Equivalent to setsockopt(Stdio.SO_KEEPALIVE, on_off), but will set errno if SO_KEEPALIVE is not supported, rather than issuing a compilation error for the missing constant.


Methodset_nodelay

boolset_nodelay(bool|voidstate)

Description

Control Nagle's Algorithm (RFC 896)

Parameter state
0

Return to the normal state of using Nagle's Algorithm

1

(default) Disable Nagling - small writes will not be queued.

Returns

Returns 1 on success, and 0 (zero) on failure.

Note

This operation is only valid on sockets.

See also

setsockopt()


Methodset_nonblocking

voidset_nonblocking()

Description

Sets this file to nonblocking operation.

Note

Nonblocking operation is not supported on all Stdio.File objects. Notably it is not guaranteed to be supported on objects returned by pipe() unless PROP_NONBLOCK was specified in the call to pipe().

See also

set_blocking()


Methodsetsockopt

boolsetsockopt(intlevel, intopt, intstate)

Description

Set socket options like Stdio.SO_KEEPALIVE. This function is always available; the presence or absence of the option constants indicates availability of those features.

Returns

1 if successful, 0 if not (and sets errno())

See also

set_keepalive()


Methodsetxattr

voidsetxattr(stringattr, stringvalue, intflags)

Description

Set the attribute attr to the value value.

The flags parameter can be used to refine the semantics of the operation.

Stdio.XATTR_CREATE specifies a pure create, which fails if the named attribute exists already.

Stdio.XATTR_REPLACE specifies a pure replace operation, which fails if the named attribute does not already exist.

By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.

Returns

1 if successful, 0 otherwise, setting errno.


Methodstat

Statstat()

Description

Get status for an open file.

This function returns the same information as the function file_stat(), but for the file it is called in. If file is not an open file, 0 (zero) is returned. Zero is also returned if file is a pipe or socket.

Returns

See file_stat() for a description of the return value.

See also

file_stat(), statat()


Methodstatat

Statstatat(stringpath, void|boolsymlink)

Description

Get status for a file relative an open directory.

This function returns the same information as the function file_stat(), but relative to the file it is called in. If file is not an open file, 0 (zero) is returned. Zero is also returned if file is a pipe or socket.

Returns

See file_stat() for a description of the return value.

Note

Not available on all architectures.

See also

file_stat(), stat(), openat(), unlinkat()


Methodsymlinkat

voidsymlinkat(string(8bit)from, string(8bit)to)

Description

Create a symbolic link named to that points to from, where to is relative to this file..

Note

This function is not available on all platforms.

See also

hardlinkat(), symlink(), readlinkat(), unlinkat()


Methodsync

boolsync()

Description

Flush buffers to disk.

Returns

Returns 0 (zero) and sets errno on failure.

Returns 1 on success.


Methodtake_fd

voidtake_fd(intfd)

Description

Rehooks the given file descriptor number to be associated with this object. As opposed to using open with a file descriptor number, it will be closed by this object upon destruct or when close is called.

See also

release_fd()


Methodtcdrain

booltcdrain()

Description

Wait for transmission buffers to empty.

Returns

Returns 1 on success and 0 (zero) on failure.

See also

tcflush()


Methodtcflush

booltcflush(string(7bit)|voidflush_direction)

Description

Flush queued terminal control messages.

Parameter flush_direction
"TCIFLUSH"

Flush received but not read.

"TCOFLUSH"

Flush written but not transmitted.

"TCIOFLUSH"

Flush both of the above. Default.

Returns

Returns 1 on success and 0 (zero) on failure.

See also

tcdrain()


Methodtcgetattr
Methodtcsetattr

mapping(string(7bit):int) tcgetattr()
inttcsetattr(mapping(string(7bit):int) attr)
inttcsetattr(mapping(string(7bit):int) attr, string(7bit)when)

Description

Gets/sets term attributes. The returned value/the attr parameter is a mapping on the form

"ispeed" : int(-1..)

In baud rate.

"ospeed" : int(-1..)

Out baud rate.

"csize" : int(-1)|int(5..8)

Character size in bits.

"rows" : int

Terminal rows.

"columns" : int

Terminal columns.

flag_name : bool

The value of a named flag. The flag name is the string describing the termios flags (IGNBRK, BRKINT, IGNPAR, PARMRK, INPCK, ISTRIP, INLCR, IGNCR, ICRNL, IUCLC, IXON, IXANY, IXOFF, IMAXBEL, OPOST, OLCUC, ONLCR, OCRNL, ONOCR, ONLRET, OFILL, OFDEL, OXTABS, ONOEOT, CSTOPB, CREAD, PARENB, PARODD, HUPCL, CLOCAL, CRTSCTS, ISIG, ICANON, XCASE, ECHO, ECHOE, ECHOK, ECHONL, ECHOCTL, ECHOPRT, ECHOKE, FLUSHO, NOFLSH, TOSTOP, PENDIN). See the manpage for termios or other documentation for more information. All flags are not available on all platforms.

character_name : int(8bit)

Sets the value of a control character (VINTR, VQUIT, VERASE, VKILL, VEOF, VTIME, VMIN, VSWTC, VSTART, VSTOP, VSUSP, VEOL, VREPRINT, VDISCARD, VWERASE, VLNEXT, VEOL2). All control characters are not available on all platforms.

Negative values are not allowed as indata, but might appear in the result from tcgetattr when the actual value is unknown. tcsetattr returns 0 if failed.

The argument when to tcsetattr describes when the changes are to take effect:

"TCSANOW"

The change occurs immediately (default).

"TCSADRAIN"

The change occurs after all output has been written.

"TCSAFLUSH"

The change occurs after all output has been written, and empties input buffers.

Example

// setting the terminal in raw mode: Stdio.stdin->tcsetattr((["ECHO":0,"ICANON":0,"VMIN":0,"VTIME":0]));

Note

Unknown flags are ignored by tcsetattr(). tcsetattr always changes the attribute, so only include attributes that actually should be altered in the attribute mapping.

Bugs

Terminal rows and columns setting by tcsetattr() is not currently supported.

See also

tcsetsize()


Methodtcsendbreak

booltcsendbreak(int|voidduration)

Description

Send a break signal.

Parameter duration

Duration to send the signal for. 0 (zero) causes a break signal to be sent for between 0.25 and 0.5 seconds. Other values are operating system dependent:

SunOS

The number of joined break signals as above.

Linux, AIX, Digital Unix, Tru64

The time in milliseconds.

FreeBSD, NetBSD, HP-UX, MacOS

The value is ignored.

Solaris, Unixware

The behavior is changed to be similar to tcdrain().

Returns

Returns 1 on success and 0 (zero) on failure.


Methodtcsetsize

booltcsetsize(introws, intcols)

Description

Set the number of rows and columns for a terminal.

Returns

Returns 1 on success and 0 (zero) on failure.

See also

tcgetattr(), tcsetattr()


Methodtell

inttell()

Description

Returns the current offset in the file.

See also

seek()


Methodtruncate

booltruncate(intlength)

Description

Truncate a file.

Truncates the file to the specified length length.

Returns

Returns 1 on success, and 0 (zero) on failure.

See also

open()


Methodtrylock

Stdio.FileLockKeytrylock()
Stdio.FileLockKeytrylock(boolis_recursive)

Description

Attempts to place a file lock on this file.

See also

lock()


Methodunlinkat

intunlinkat(stringf)

Description

Remove a file or directory relative to an open file.

Returns

Returns 0 (zero) on failure, 1 otherwise.

See also

rm(), openat(), statat()


Methodwrite

intwrite(string(8bit)data)
intwrite(string(8bit)format, mixed ... extras)
intwrite(array(string(8bit)) data)
intwrite(array(string(8bit)) format, mixed ... extras)
intwrite(Stdio.Buffer|String.Buffer|System.Memorydata, void|int(0..)offset)

Description

Write data to a file or a stream.

If there are any file descriptors that have been queued for sending (with send_fd()), they will be sent.

Parameter data

Data to write.

If data is an array of strings, they are written in sequence.

Parameter format
Parameter extras

If more than one argument is given, sprintf() is used to format them using format. If format is an array, the strings in it are concatenated and the result is used as format string.

Parameter offset

The offset in data to start writing from.

Returns

Writes data and returns the number of bytes that were actually written.

(1..)

The number of bytes successfully written to the OS buffers.

This can be less than the size of the given data if eg:

  • Some data was written successfully and then something went wrong.

    If only some data was written due to an error and that error persists, then a later call to write() will fail and return -1.

  • Nonblocking mode is used and not all data could be written without blocking.

0

No bytes were written. This may be due to

  • data or the formatted data being the empty string.

  • Nonblocking mode is used and no data could be written without blocking.

-1

Something went wrong and no bytes were written.

If everything went fine, a call to errno() directly afterwards returns zero.

Note

Writing of wide strings is not supported. You have to encode the data somehow, e.g. with string_to_utf8 or with one of the charsets supported by Charset.encoder.

Note

The variant of this function using a buffer object does not release the interpreter lock.

See also

read(), write_oob(), send_fd()


Methodwrite_oob

intwrite_oob(stringdata)
intwrite_oob(stringformat, mixed ... extras)

Description

Write out-of-band data to a stream.

Writes out-of-band data to a stream and returns how many bytes that were actually written. It can be less than the size of the given data if some data was written successfully and then something went wrong.

-1 is returned if something went wrong and no bytes were written. If only some data was written due to an error and that error persists, then a later call to write_oob() fails and returns -1.

If everything went fine, a call to errno() directly afterwards returns zero.

If more than one argument is given, sprintf() is used to format them.

Note

It is not guaranteed that all out-of-band data sent from the other end is received. Most streams only allow for a single byte of out-of-band data at a time. Some streams sends the rest of the data as ordinary data.

See also

read_oob(), write()

Class _Stdio.Fd_ref

Description

Proxy class that contains stub functions that call the corresponding functions in Fd.

Used by Stdio.File.

Note

This is not the class you want. Use Stdio.File and friends instead.

See also

Stdio.File, Stdio.FILE, _Stdio.Fd


InheritFd

inherit Fd : Fd

Description

Fake inherit to propagate the documentation from _Stdio.Fd.


Variable_fd

Fd _Stdio.Fd_ref._fd

Description

Object to which called functions are relayed.

Class _Stdio.UDP


ConstantMSG_OOB

constant _Stdio.UDP.MSG_OOB

Description

Flag to specify to read() to read out of band packets.


ConstantMSG_PEEK

constant _Stdio.UDP.MSG_PEEK

Description

Flag to specify to read() to cause it to not remove the packet from the input buffer.


Variable_fd

UDP _Stdio.UDP._fd

Note

Read only


Methodadd_membership

intadd_membership(stringgroup, void|stringaddress)

Description

Join a multicast group.

Parameter group

group contains the address of the multicast group the application wants to join. It must be a valid multicast address.

Parameter address

address is the address of the local interface with which the system should join to the multicast group. If not provided the system will select an appropriate interface.

See also the Unix man page for setsocketopt IPPROTO_IP IP_ADD_MEMBERSHIP and IPPROTO_IPV6 IPV6_JOIN_GROUP.

Note

The address parameter is currently not supported for IPv6.

Note

This function did not support IPv6 in Pike 7.8 and earlier.

See also

drop_membership()


Methodbind

UDPbind(int|stringport, string|voidaddress, string|boolno_reuseaddr)

Description

Binds a port for receiving or transmitting UDP.

Parameter port

Either a port number or the name of a service as listed in /etc/services.

Parameter address

Local address to bind to.

Parameter no_reuseaddr

If set to 1, Pike will not set the SO_REUSEADDR option on the UDP port.

Note

SO_REUSEADDR is never applied when binding a random port (bind(0)).

In general, SO_REUSEADDR is not desirable on UDP ports. Unless used for receiving multicast, be sure to never bind a non-random port without setting no_reuseaddr to 1.

Throws

Throws error when unable to bind port.


Methodclose

boolclose()

Description

Closes an open UDP port.

Note

This method was introduced in Pike 7.5.


Methodconnect

boolconnect(stringaddress, int|stringport)

Description

Establish an UDP connection.

This function connects an UDP socket previously created with Stdio.UDP() to a remote socket. The address is the IP name or number for the remote machine.

Returns

Returns 1 on success, 0 (zero) otherwise.

Note

If the socket is in nonblocking mode, you have to wait for a write or close callback before you know if the connection failed or not.

See also

bind(), query_address()


Methoddrop_membership

intdrop_membership(stringgroup, void|stringaddress)

Description

Leave a multicast group.

Parameter group

group contains the address of the multicast group the application wants to join. It must be a valid multicast address.

Parameter address

address is the address of the local interface with which the system should join to the multicast group. If not provided the system will select an appropriate interface.

See also the Unix man page for setsocketopt IPPROTO_IP IP_DROP_MEMBERSHIP and IPPROTO_IPV6 IPV6_LEAVE_GROUP.

Note

The address parameter is currently not supported for IPv6.

Note

This function did not support IPv6 in Pike 7.8 and earlier.

See also

add_membership()


Methoddup

Stdio.UDPdup()

Description

Duplicate the udp socket.

See also

fd_factory()


Methodenable_broadcast

boolenable_broadcast()

Description

Set the broadcast flag. If enabled then sockets receive packets sent to a broadcast address and they are allowed to send packets to a broadcast address.

Returns

Returns 1 on success, 0 (zero) otherwise.

Note

This is normally only avalable to root users.


Methodenable_multicast

boolenable_multicast(stringreply_address)

Description

Set the local device for a multicast socket.

Parameter reply_address

Local address that should appear in the multicast packets.

See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_IF and IPPROTO_IPV6 IPV6_MULTICAST_IF.

Note

This function did not support IPv6 in Pike 7.8.


Methoderrno

interrno()

Description

Returns the error code for the last command on this object. Error code is normally cleared when a command is successful.


Methodfd_factory

UDPfd_factory()

Description

Factory creating Stdio.UDP objects.

This function is called by dup() and other functions creating new UDP objects.

The default implementation calls object_program(this_object())() to create the new object, and returns the UDP inherit in it.

Note

Note that this function must return the UDP inherit in the object.

See also

dup(), Stdio.File()->fd_factory()


Methodget_type

array(int) get_type()

Description

Returns socket type and protocol family.


Methodquery_address

stringquery_address()

Description

Returns the local address of a socket on the form "x.x.x.x port". If this file is not a socket, not connected or some other error occurs, zero is returned.


Methodquery_backend

Pike.Backendquery_backend()

Description

Return the backend used for the read callback.

See also

set_backend


Methodquery_fd

intquery_fd()

Description

Gets the file descriptor for this UDP port.


Methodquery_mtu

intquery_mtu()

Description

Get the Max Transfer Unit for the object (if any).

Returns
-1

Returns -1 if the object is not a socket or if the mtu is unknown.

(1..)

Returns a positive value with the mtu on success.

Note

The returned value is adjusted to take account for the IP and UDP headers, so that it should be usable without further adjustment unless further IP options are in use.


Methodread

mapping(string:int|string) read()
mapping(string:int|string) read(intflag)

Description

Read from the UDP socket.

Flag flag is a bitfield, 1 for out of band data and 2 for peek

Returns

mapping(string:int|string) in the form ([ "data" : string received data "ip" : string received from this ip "port" : int ...and this port ])

See also

set_read_callback(), MSG_OOB, MSG_PEEK


Methodsend

intsend(stringto, int|stringport, stringmessage)
intsend(stringto, int|stringport, stringmessage, intflags)

Description

Send data to a UDP socket.

Parameter to

The recipient address. For connect()ed objects specifying a recipient of either UNDEFINED or "" causes the default recipient to be used.

Parameter port

The recipient port number. For connect()ed objects specifying port number 0 casues the default recipient port to be used.

Parameter flag

A flag bitfield with 1 for out of band data and 2 for don't route flag.

Returns
(0..)

The number of bytes that were actually written.

(..-1)

Failed to send the message. Check errno() for the cause. Common causes are:

System.EMSGSIZE

The message is too large to send unfragmented.

System.EWOULDBLOCK

The send buffers are full.

Throws

Throws errors on invalid arguments and uninitialized object.

Note

Versions of Pike prior to 8.1.5 threw errors also on EMSGSIZE ("Too big message") and EWOULDBLOCK ("Message would block."). These versions of Pike also did not update the object errno on this function failing.

Note

Versions of Pike prior to 8.1.13 did not support the default recipient for connect()ed objects.

See also

connect(), errno(), query_mtu()


Methodset_backend

voidset_backend(Pike.Backendbackend)

Description

Set the backend used for the read callback.

Note

The backend keeps a reference to this object as long as there can be calls to the read callback, but this object does not keep a reference to the backend.

See also

query_backend


Methodset_blocking

objectset_blocking()

Description

Sets this object to be blocking.


Methodset_buffer

voidset_buffer(intbufsize, stringmode)
voidset_buffer(intbufsize)

Description

Set internal socket buffer.

This function sets the internal buffer size of a socket or stream.

The second argument allows you to set the read or write buffer by specifying "r" or "w".

Note

It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.

See also

open_socket(), accept()


Methodset_fd

UDPset_fd(intfd)

Description

Use the file descriptor fd for UDP.

See also

bind


Methodset_multicast_ttl

intset_multicast_ttl(intttl)

Description

Set the time-to-live value of outgoing multicast packets for this socket.

Parameter ttl

The number of router hops sent multicast packets should survive.

It is very important for multicast packets to set the smallest TTL possible. The default before calling this function is 1 which means that multicast packets don't leak from the local network unless the user program explicitly requests it.

See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_TTL and IPPROTO_IPV6 IPV6_MULTICAST_HOPS.

Note

This function did not support IPv6 in Pike 7.8 and earlier.

See also

add_membership()


Methodset_nonblocking

objectset_nonblocking(function(:void)|voidrcb, function(:void)|voidwcb)

Description

Sets this object to be nonblocking and the read and write callbacks.


Methodset_type

UDPset_type(intsock_type)
UDPset_type(intsock_type, intfamily)

Description

Sets socket type and protocol family.


Methodwait

boolwait(int|floattimeout)

Description

Check for data and wait max. timeout seconds.

Returns

Returns 1 if data are ready, 0 (zero) otherwise.

Class _Stdio._port


Methodaccept

Stdio.Fileaccept()

Description

Get the first connection request waiting for this port and return it as a connected socket.

If no connection request is waiting and the port is in nonblocking mode (i.e. an accept callback is installed) then zero is returned. Otherwise this function waits until a connection has arrived.

In Pike 7.8 and later the returned object is created via fd_factory().

Note

In Pike 7.7 and later the resulting file object will be assigned to the same backend as the port object.


Methodbind

intbind(int|stringport, void|function(:void) accept_callback, void|stringip, void|stringreuse_port)

Description

Opens a socket and binds it to port number on the local machine. If the second argument is present, the socket is set to nonblocking and the callback funcition is called whenever something connects to it. The callback will receive the id for this port as argument and should typically call accept to establish a connection.

If the optional argument ip is given, bind will try to bind to an interface with that host name or IP number. Omitting this will bind to all available IPv4 addresses; specifying "::" will bind to all IPv4 and IPv6 addresses.

If the OS supports TCP_FASTOPEN it is enabled automatically.

If the OS supports SO_REUSEPORT it is enabled if the fourth argument is true.

Returns

1 is returned on success, zero on failure. errno provides further details about the error in the latter case.

See also

accept, set_id


Methodbind_unix

intbind_unix(stringpath, void|function(:void) accept_callback)

Description

Opens a Unix domain socket at the given path in the file system. If the second argument is present, the socket is set to nonblocking and the callback funcition is called whenever something connects to it. The callback will receive the id for this port as argument and should typically call accept to establish a connection.

Returns

1 is returned on success, zero on failure. errno provides further details about the error in the latter case.

Note

This function is only available on systems that support Unix domain sockets.

Note

path had a quite restrictive length limit (~100 characters) prior to Pike 7.8.334.

See also

accept, set_id


Methodclose

voidclose()

Description

Closes the socket.


Methodcreate

_Stdio._port_Stdio._port(int|stringport, void|function(:void) accept_callback, void|stringip)
_Stdio._port_Stdio._port("stdin", void|function(:void) accept_callback)

Description

When called with an int or any string except "stdin" as first argument, this function does the same as bind() would do with the same arguments.

When called with "stdin" as argument, a socket is created out of the file descriptor 0. This is only useful if that actually IS a socket to begin with, and is equivalent to creating a port and initializing it with listen_fd(0).

See also

bind, listen_fd


Methoderrno

interrno()

Description

If the last call done on this port failed, this function will return an integer describing what went wrong. Refer to your unix manual for further information.


Methodfd_factory

protectedStdio.Fdfd_factory()

Description

Factory creating empty Stdio.Fd objects.

The default implementation creates an empty Stdio.Fd object.


Methodlisten_fd

intlisten_fd(intfd, void|function(:void) accept_callback)

Description

This function does the same as bind, except that instead of creating a new socket and bind it to a port, it expects the file descriptor fd to be an already open port.

Note

This function is only for the advanced user, and is generally used when sockets are passed to Pike at exec time.

See also

bind, accept


Methodquery_address

stringquery_address()

Description

Get the address and port of the local socket end-point.

Returns

This function returns the address and port of a socket end-point on the form "x.x.x.x port" (IPv4) or "x:x:x:x:x:x:x:x port" (IPv6).

If there is some error querying or formatting the address, 0 (zero) is returned and errno() will return the error code.

Throws

An error is thrown if the socket isn't bound.


Methodquery_backend

Pike.Backendquery_backend()

Description

Return the backend used for the accept callback.

See also

set_backend


Methodquery_fd

intquery_fd()

Description

Returns the file descriptor number associated with this object.


Methodquery_id

mixedquery_id()

Description

This function returns the id for this port. The id is normally the first argument to accept_callback.

See also

set_id


Methodset_accept_callback

voidset_accept_callback(function(:void)|voidaccept_callback)

Description

Change or remove the accept callback.

Parameter accept_callback

New accept callback.

See also

bind(), listen(), set_id()


Methodset_backend

voidset_backend(Pike.Backendbackend)

Description

Set the backend used for the accept callback.

Note

The backend keeps a reference to this object as long as the port is accepting connections, but this object does not keep a reference to the backend.

See also

query_backend


Methodset_id

mixedset_id(mixedid)

Description

This function sets the id used for accept_callback by this port. The default id is this_object().

Note

In Pike 8.0 and earlier the default value was 0 (zero) (even though it was documented as above).

See also

query_id, set_accept_callback()

Module _Stdio.IPPROTO

Description

Module containing various IP-protocol options.

Module _Stdio.SOCK

Description

Module containing constants for specifying socket options.


ConstantDGRAM

constant _Stdio.SOCK.DGRAM


ConstantPACKET

constant _Stdio.SOCK.PACKET


ConstantRAW

constant _Stdio.SOCK.RAW


ConstantRDM

constant _Stdio.SOCK.RDM


ConstantSEQPACKET

constant _Stdio.SOCK.SEQPACKET


ConstantSTREAM

constant _Stdio.SOCK.STREAM