27. The rest

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


Directive#elifdef
Directive#elseifdef

#elifdef
#elseifdef

Description

These work as a combined #else and #ifdef without adding an extra level of nesting.

Example

The following two are equivalent:

#ifdef A
    // Code for A.
  #else
  #ifdef B
    // Code for B.
  #else
  #ifdef C
    // Code for C.
  #else
    // Code for D.
  #endif
  #endif
  #endif

And

#ifdef A
    // Code for A.
  #elifdef B
    // Code for B.
  #elseifdef C
    // Code for C.
  #else
    // Code for D.
  #endif
See also

#if, #ifdef, #else, defined(), constant()


Directive#elifndef
Directive#elseifndef

#elifndef
#elseifndef

Description

These work as a combined #else and #ifndef without adding an extra level of nesting.

Example

The following two are equivalent:

#ifndef A
    // Code for not A.
  #else
  #ifndef B
    // Code for not B.
  #else
  #ifdef C
    // Code for not C.
  #else
    // Code for ABC.
  #endif
  #endif
  #endif

And

#ifndef A
    // Code for not A.
  #elifndef B
    // Code for not B.
  #elseifndef C
    // Code for not C.
  #else
    // Code for ABC.
  #endif
See also

#if, #ifdef, #else, defined(), constant()

Namespace predef::

Description

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


ConstantFUSE_MAJOR_VERSION
ConstantFUSE_MINOR_VERSION

constantFUSE_MAJOR_VERSION
constantFUSE_MINOR_VERSION

Description

The version of FUSE


ConstantHKEY_CLASSES_ROOT
ConstantHKEY_LOCAL_MACHINE
ConstantHKEY_CURRENT_USER
ConstantHKEY_USERS

constantintHKEY_CLASSES_ROOT
constantintHKEY_LOCAL_MACHINE
constantintHKEY_CURRENT_USER
constantintHKEY_USERS

Description

Root handles in the Windows registry.

Note

These constants are only available on Win32 systems.

See also

RegGetValue(), RegGetValues(), RegGetKeyNames()


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.


ConstantTOKENIZE_KEEP_ESCAPES

constantTOKENIZE_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()


ConstantUNDEFINED

constantUNDEFINED

Description

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


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)


Method__handle_sprintf_format

type__handle_sprintf_format(stringattr, stringfmt, typearg_type, typecont_type)

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.

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()


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


Method__parse_pike_type

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


Constant__placeholder_object

constant__placeholder_object

Description

Object used internally by the compiler.

See also

__null_program


Method_equal

bool_equal(mixedo)


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.


Method_m_delete

mixed_m_delete(mixedkey)

Description

m_delete callback.


Method_random

array_random(function(:void) random_string, function(:void) random)

Description

Get a random entry.

Returns

An array ({ key, value }).


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()


Methodbasetype

stringbasetype(mixedx)

Description

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

See also

sprintf()


Methodbkey

stringbkey(mixedkey)

Description

Render the internally used binary representation of the key into a string as a strings of '0's and '1's.


Methodcast

mappingcast(stringtype)

Description

Cast callback. Supports only cast to mapping and behaves as the inverse of create().


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()


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

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


Methodcompile_file

programcompile_file(stringfilename, object|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, void|stringfilename, object|voidhandler, void|programp, void|objecto, void|int_show_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()


Methodcpp

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


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(stringcoded_value, void|Codec|int(-1..-1)codec)

Description

Decode a value from the string coded_value.

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()


Methoddepth

int(0..)depth()

Description

Calculate the depth of the tree.


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

stringencode_value(mixedvalue, Codec|voidcodec)

Description

Code a value into a string.

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

stringencode_value_canonic(mixedvalue, object|voidcodec)

Description

Code a value into a string on canonical form.

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() }) ).


Constantis_gssapi_error
Constanterror_type

constantintis_gssapi_error
constantstringerror_type

Description

Object recognition constants.


Constantis_gssapi_missing_services_error
Constanterror_type

constantintis_gssapi_missing_services_error
constantstringerror_type

Description

Object recognition constants.


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.

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

array
multiset
string

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.

If fun is an array, it should have the same length as arr. In this case, the elements in arr are kept where the corresponding positions in fun are nonzero. Otherwise fun is used as described below.

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.

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

function

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 it 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
mapping

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

"zero or left out"

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(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 it's called in it with the arguments args to create the iterator.

If data is an object that lacks lfun::_get_iterator then it's assumed to already be an iterator object, and is simply returned.

array

If data is an array, an Array.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)
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. A question sign ('?') matches any character and an asterisk ('*') matches a string of arbitrary length. All other characters only match themselves.

array(string)

the function returns the matching glob if any of the given patterns match. Otherwise 0. If the second argument 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).

See also

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.

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.


Constantis_sql_null

constantintis_sql_null

Description

SQL Null marker.

Deprecated

Replaced by is_val_null.


Constantis_val_null

constantintis_val_null

Description

Nonzero recognition constant.


Methoditerator_index

mixediterator_index(objectiter)

Description

Get the current index for iter.

See also

get_iterator()


Methoditerator_next

booliterator_next(objectiter)

Description

Advance iter one step.

See also

get_iterator()


Methoditerator_value

mixediterator_value(objectiter)

Description

Get the current value for iter.

See also

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.

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.

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

array
multiset
string

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.

fun is applied in different ways depending on its type:

function

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
mapping

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

"zero or left out"

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..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..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 are not supported.

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.


Methodnth

mixednth(int(0..)n)

Description

Get the nth entry in order.

Returns

An array ({ key, value }).


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.

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

Field width.

"flag_left" : bool|void

Indicates that the output should be left-aligned.

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

Indentation level 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.

'X'

Uppercase signed hexadecimal integer.

'c'

Character. 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

The 'q' operator was added in Pike 7.7.

Note

Support for specifying modifiers via a mapping was added in Pike 7.8. This support can be tested for with the constant String.__HAVE_SPRINTF_STAR_MAPPING__.

Note

Support for specifying little endian byte order to 'F' was added in Pike 7.8. This support can be tested for with the constant String.__HAVE_SPRINTF_NEGATIVE_F__.

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
See also

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


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()


Methodsqrt

floatsqrt(floatf)
intsqrt(inti)
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


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()


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()


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

this, this_object()


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.


Constantthis_program

constantthis_program

Description

Builtin constant that evaluates to the current program.

See also

this, this_object()


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..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.


Typedefzero

typedefint(0..0)zero

Description

Zero datatype.

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

mixedhandle_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.


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()


Methodcompile

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


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

stringformat_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..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_import

programhandle_import(stringmodule, stringcurrent_file, object|voidhandler, object|voidcompat_handler)


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().


Methodhandle_inherit

programhandle_inherit(stringinh, stringcurrent_file, object|voidhandler, object|voidcompat_handler)


InheritOrigCompilerEnvironment

inherit predef::CompilerEnvironment : OrigCompilerEnvironment


InheritReporter

inherit Reporter : Reporter

Description

Implements the Reporter API.

See also

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


Methodresolv

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


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()


Methodapply_handler

protectedmixedapply_handler(stringfun, mixed ... args)


Methodchange_cpp_compatibility

voidchange_cpp_compatibility(intmajor, intminor)


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()


Variablehandler
Variablecompat_handler

object CompilerEnvironment.CPP.handler
object CompilerEnvironment.CPP.compat_handler


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.

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, 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()


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)|voidpredefs)

Description

Define multiple macros in one operation.

Parameter predefs

Macros to define.

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)


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) get_predefines()


Methodget_predefines

mapping(string:string|function(:void)|object) 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)


Inheritthis_program

inherit ::this_program : this_program


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)


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.


Methodapply_attribute_constant

typeapply_attribute_constant(stringattr, mixedvalue, typearg_type, voidcont_type)

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.

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 implements the "sprintf_format", "sscanf_format" and "sscanf_76_format" attributes.

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, type|voidb)

Description

Type attribute handler.

Parameter attribute

Attribute that a had.

Parameter a

Type of the value being called.

Parameter b

Type of the first argument in the call, or UNDEFINED if no more arguments.

Called during type checking when a has been successfully had a partial evaluation with the argument b and a had the type attribute attribute before the evaluation.

The default implementation implements the "deprecated" attribute.

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)


Methodchange_compiler_compatibility

voidchange_compiler_compatibility(intmajor, intminor)

Description

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


Variablehandler
Variablecompat_handler

object CompilerEnvironment.PikeCompiler.handler
object CompilerEnvironment.PikeCompiler.compat_handler


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


Methodcreate

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


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).


Methodget_compilation_handler

objectget_compilation_handler(intmajor, intminor)


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()


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..0)

Use the builtin constant table.

Note

This function is called by change_compiler_compatibility().


Methodhandle_import

programhandle_import(stringmodule)


Methodhandle_import

programhandle_import(stringmodule)

Description

Look up an import module.


Methodhandle_inherit

programhandle_inherit(stringinh)


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" attribute.

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()


Inheritthis_program

inherit ::this_program : this_program


Methodpop_type_attribute

boolpop_type_attribute(stringattribute, typea, typeb)

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" attribute.

Returns

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

See also

push_type_attribute(), index_type_attribute()


Methodpush_type_attribute

boolpush_type_attribute(stringattribute, typea, typeb)

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 "deprecated" attribute.

Returns

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

See also

pop_type_attribute(), index_type_attribute()


Methodreport

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


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)


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

boolsuppress_deprecation_warnings()

Description

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

Returns

1 if deprecation 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; `!() will only return true then, and _iterator_index and _iterator_value will return UNDEFINED. 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 optional. It's supported if and only if `-() is defined, but even then it's undefined how far back the iterator can move. Therefore iterators may support only a limited amount of backward movement, e.g. when they access a stream through a limited buffer. If such an iterator is moved back past the limit then it'll behave as if it's pointing entirely outside the data set (see above).

An iterator that doesn't support backward movement at all should throw an error if it's attempted.

See also

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


Method_iterator_index

mixed_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).


Method_iterator_next

int_iterator_next()

Description

If this function is defined it should advance the iterator one step, just like `+=(1) would do.

Note

This is the preferred way to advance the iterator, since it reduces the overhead.

Note

This function was optional in Pike 7.6 and earlier.

Returns

Returns 1 if it succeeded in advancing, and 0 (zero) if it has reached the end of the iterator.

See also

`+, `+=, `-


Method_iterator_value

mixed_iterator_value()

Description

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


Method_random

voidrandom(Iteratorarg)

Description

If this function is defined then it sets the iterator to point to 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.


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`!

bool res = !Iterator()

Description

Returns 0 (zero) when the iterator points to an item, 1 otherwise.


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() += steps

Description

Advance this iterator the specified number of steps and return it. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.

Note

foreach calls this function with a step value of 1 if _iterator_next() doesn't exist for compatibility with Pike 7.6 and earlier.

Note

foreach will call this function even when the the iterator has more than one reference. If you want to loop over a copy of the iterator, you can create a copy by adding 0 (zero) to it:

Iterator iterator;
    ...
    foreach(iterator+0;mixed index;mixed value){
      ...
    }
Note

Even though this function is sufficient for foreach to advance the iterator, _iterator_next() is the preferred API.

See also

_iterator_next, `+, `-


Method`-

Iterator res = Iterator() - steps

Description

This lfun should be defined if and only if the iterator supports backward movement to some degree. It should back 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 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.


Methodfirst

optionalboolfirst()

Description

If this function is defined then it resets the iterator to point to 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 MasterObject

Description

Master control program for Pike.

See also

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


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


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.


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.


Methodadd_filesystem_handler

mixedadd_filesystem_handler(stringmountpoint, objectfilesystem)

Description

mount a filesystem handler to be used by the resolver. on its own does noting, 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.


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.


Methodcast_to_object

objectcast_to_object(stringoname, stringcurrent_file, object|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, object|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()


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


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(),


Variablecurrentversion

Version MasterObject.currentversion

Description

Version information about the current Pike version.


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

stringdescribe_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

stringdescribe_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

stringdescribe_program(program|function(:void) p)

Description

Function called by sprintf("%O") for programs.


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".


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

stringfind_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

mixedget_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, object|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.


Variableinclude_prefix

string MasterObject.include_prefix

Description

Prefix for Pike-related C header files.


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_8_0_master

protected inherit Pike_8_0_master : Pike_8_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


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


Methodmaster_read_file

stringmaster_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)


Variableno_precompile

int MasterObject.no_precompile

Description

Turn off loading of precompiled modules.


Methodobjects_reverse_lookup

programobjects_reverse_lookup(objectobj)

Description

Returns the program for obj, if known to the master.


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.


Methodprogram_path_to_name

stringprogram_path_to_name(stringpath, void|stringmodule_prefix, void|stringmodule_suffix, void|stringobject_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.

Parameter msg

Warning message. Currently the following messages may be generated:

"bad_cycle"

A cycle where the destruction order isn't deterministic was detected by the garbage collector.

data will in this case contain an array of the elements in the cycle.

Parameter data

Optional data that further describes the warning specified by msg.


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(mixedbehaviour)

Description

Set the compile error, warning and exception behaviour.

Parameter behaviour

The desired behaviour. One of:

int(0..0)

Output compilation errors and warnings to stderr. This is the default behaviour.

int(1..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


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".


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?


Variablewant_warnings

int MasterObject.want_warnings

Description

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

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.


Methodcreate

MasterObject.CodecMasterObject.Codec(void|mixedencoded)

Description

The optional argument is the thing to encode; it's passed on to Encoder.


InheritDecoder

inherit Decoder : Decoder


InheritEncoder

inherit Encoder : Encoder

Class MasterObject.CompatResolver

Description

Resolver of symbols not located in the program being compiled.


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.


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

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

stringhandle_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()


Variablehandler_root_modules

mapping(object:joinnode) MasterObject.CompatResolver.handler_root_modules

Description

Lookup from handler module to corresponding root_module.


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.


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


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, object|voidcurrent_handler, object|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, object|voidcurrent_handler, object|voidcurrent_compat_handler)

Description

Look up identifier in the root module.


Methodresolv_or_error

mixedresolv_or_error(stringidentifier, string|voidcurrent_file, void|objectcurrent_handler)

Description

Same as resolv, but throws an error instead of returning UNDEFINED if the resolv failed.


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.

Class MasterObject.Decoder

Description

Codec for use with decode_value. This is the decoder corresponding to Encoder. See that one for more details.


Methodcreate

MasterObject.DecoderMasterObject.Decoder(void|stringfname, void|intmkobj, void|objecthandler)


Methoddecode_object

array(mixed) decode_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()


Variablefname
Variablemkobj
Variablehandler

void|string MasterObject.Decoder.fname
void|int MasterObject.Decoder.mkobj
void|object MasterObject.Decoder.handler

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.Version

Description

Contains version information about a Pike 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.


Variablemajor
Variableminor

int MasterObject.Version.major
int MasterObject.Version.minor

Description

The major and minor parts of the version.

Class MasterObject.dirnode

Description

Module node representing a single directory.

See also

joinnode


Variabledirname
Variablecompilation_handler
Variablename

string MasterObject.dirnode.dirname
object|void MasterObject.dirnode.compilation_handler
string|void MasterObject.dirnode.name


Methodcreate

MasterObject.dirnodeMasterObject.dirnode(stringdirname, object|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
object|void MasterObject.joinnode.compilation_handler
joinnode|mapping(mixed:int(0..0))|void MasterObject.joinnode.fallback_module
string|void MasterObject.joinnode.name


Methodcreate

MasterObject.joinnodeMasterObject.joinnode(array(object|mapping) joined_modules, object|voidcompilation_handler, joinnode|mapping(mixed:int(0..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 output to Stdio.stderr.

Note

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

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


Methodcreate

mklibpike.C_Include_Handlermklibpike.C_Include_Handler(array(string) search_path)


Variablesearch_path

array(string) mklibpike.C_Include_Handler.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


Variableapplication

protectedstring Arg.LowOptions.application


Variableargv

protectedarray(string) Arg.LowOptions.argv


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)


InheritOptLibrary

protected inherit OptLibrary : OptLibrary


Variableopts

protectedmapping(string:Opt) Arg.LowOptions.opts


Methodunhandled_argument

protectedboolunhandled_argument(array(string) argv, mapping(string:string) env)


Variablevalues

protectedmapping(string:int(1..1)|string) Arg.LowOptions.values

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));


Methodcreate

Arg.OptLibrary.IntArg.OptLibrary.Int(Optopt)


InheritOpt

inherit Opt : Opt


Variableopt

Opt Arg.OptLibrary.Int.opt

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"));


Methodcreate

Arg.OptLibrary.MultipleArg.OptLibrary.Multiple(Optopt)


InheritOpt

inherit Opt : Opt


Variableopt

Opt Arg.OptLibrary.Multiple.opt

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.


Variablehelp
Variablehelp_help

Opt Arg.Options.help
protectedstring Arg.Options.help_help

Description

Options that trigger help output.


InheritLowOptions

inherit LowOptions : LowOptions


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_programfrom_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.


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 ])


InheritANY

inherit .module.ANY : ANY

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


Methodcreate

Cache.DataCache.Data(void|mixedvalue, void|intexpire_time, void|floatpreciousness)

Description

expire_time is relative and in seconds.


Variablectime

int Cache.Data.ctime

Description

creation-time


Methoddata

mixeddata()

Description

A method in order to allow for lazy computation


Variableetime

int Cache.Data.etime

Description

expiry-time (if supplied). 0 otherwise


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.


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.


InheritBase

inherit Cache.Policy.Base : Base

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.


Methodexpire

voidexpire(Cache.Storage.Basestorage)

Description

This is an expire function that does nothing.


InheritBase

inherit Cache.Policy.Base : Base

Class Cache.Policy.Sized

Description

An LRU, size-constrained expiration policy manager.

Thanks

Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.


Methodcreate

Cache.Policy.SizedCache.Policy.Sized(intmax, void|intmin)


Methodexpire

voidexpire(Cache.Storage.Basestorage)


InheritBase

inherit Cache.Policy.Base : Base

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..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..0)|stringfirst()
int(0..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..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.


Methodcreate

Cache.Storage.GdbmCache.Storage.Gdbm(stringpath)

Description

A GDBM storage-manager must be hooked to a GDBM Database.


InheritBase

inherit Cache.Storage.Base : Base

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.


Methodget

int(0..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)


InheritBase

inherit Cache.Storage.Base : Base

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.


Methodcreate

Cache.Storage.MySQLCache.Storage.MySQL(stringsql_url)


InheritBase

inherit Cache.Storage.Base : Base

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.


Methodcreate

Cache.Storage.YabuCache.Storage.Yabu(stringpath)


InheritBase

inherit Cache.Storage.Base : Base

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..0)|stringident_user 
int(0..0)|stringauth_user 
intyear 
intmonth 
intday 
inthours 
intminutes 
intseconds 
inttimezone 
int(0..0)|stringmethod

One of "GET", "POST", "HEAD" etc.

int(0..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 offset

The position in the file where the parser should begin.

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


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.


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.


Methodhexdump

voidhexdump(string(8bit)raw)

Description

Write a hexadecimal dump of the contents of raw to Stdio.stderr.


Inherit_Debug

inherit _Debug : _Debug


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.

Class Debug.Decoder


Methodcreate

Debug.DecoderDebug.Decoder(Stdio.Bufferinput)


Variableinput

Stdio.Buffer Debug.Decoder.input

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.


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.


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.

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.


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.


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.


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


Methodattach_statarray

voidattach_statarray(array(int) a)

Description

Fills the stat-object with data from a Stdio.File.stat() call.


Methodcd

objectcd()

Description

Change to the stated directory.

Returns

the directory if the stated object was a directory, 0 otherwise.


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


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.


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


InheritBase

inherit Filesystem.Base : Base

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.Statstat()

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


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.


Variablebackend

protectedPike.Backend Filesystem.Monitor.basic.backend

Description

Backend to use.

If 0 (zero) - use the default backend.


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.


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()


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.


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().


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


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.


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()


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.


Methodcreate

Filesystem.Monitor.basic.MonitorFilesystem.Monitor.basic.Monitor(stringpath, MonitorFlagsflags, intmax_dir_check_interval, intfile_interval_factor, intstable_time)


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()


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


InheritElement

inherit ADT.Heap.Element : Element


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


Methodget_monitors

mapping(string:Monitor) get_monitors()

Description

Return the set of active monitors.


Inherit"symlinks.pike"

inherit "symlinks.pike" : "symlinks.pike"

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


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.


Variableavailable_ids

protectedint Filesystem.Monitor.symlinks.available_ids

Description

Bitmask of all unallocated symlink ids.


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.


Inheritbasic

inherit Filesystem.Monitor.basic : basic


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.


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.

Class Filesystem.Monitor.symlinks.DefaultMonitor

Description

Monitoring information for a single filesystem path.

With support for expansion of symbolic links.

See also

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, mixed ... :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.Statst, 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).


InheritDefaultMonitor

inherit basic::DefaultMonitor : DefaultMonitor

Description

Based on Filesystem.Monitor.basic.DefaultMonitor.


Methodlow_call_callback

voidlow_call_callback(function(string, mixed ... :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.


Variablesymlinks

int Filesystem.Monitor.symlinks.DefaultMonitor.symlinks

Description

Mask of symlink ids that can reach this monitor.


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


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)


InheritSystem

inherit Filesystem.System : System


Methodrm

intrm(stringfilename)

FIXME

Not implemented yet.

Class Filesystem.Tar.`()


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.


Inherit_TarFS

inherit _TarFS : _TarFS

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.Filedata, 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"


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.


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


Variablealt

float Geography.Position.alt

Description

Altitud of the position, in meters. Positive numbers is up. Zero is the shell of the current ellipsoid.


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.


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.


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).


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.


Variablelat

float Geography.Position.lat

Description

Latitude (N--S) of the position, in degrees. Positive number is north, negative number is south.


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"


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).


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


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.


Variablecountries

array(Country) Geography.Countries.countries

Description

All known countries.


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 as-known-as, if any


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.


Variablefips10

string Geography.Countries.Country.fips10

Description

FIPS 10-character code; "Federal Information Processing Standards 10-3" etc, used by some goverments in the US.


Variableformer

int Geography.Countries.Country.former

Description

Flag that is set if this country doesn't exist anymore. (eg USSR.)


Variableiso2

string Geography.Countries.Country.iso2

Description

ISO 2-character code aka domain name

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.


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.


InheritIP

inherit IP : IP

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..0)|zero

The option does not require a value.

int(1..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.


Methodgit

stringgit(stringgit_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()


Variablegit_binary

string Git.git_binary

Description

The git binary to use.

Defaults to "git", but may be overridden to select a different binary.


Methodhash_blob

stringhash_blob(stringdata)

Description

Hash algorithm for blobs that is compatible with git.


Methodlow_git

Process.Processlow_git(mapping(string:mixed) options, stringgit_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

stringtry_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/


Methodfac

Gmp.mpzfac(intx)

Description

Returns the factorial of x (x!).


Constantversion

constant Gmp.version

Description

The version of the current GMP library, e.g. "6.1.0".

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.


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()


Variablecatalan

mpf Gmp.mpf.catalan


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)


Variableeuler

mpf Gmp.mpf.euler


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()


Variableln2

mpf Gmp.mpf.ln2


Methodlog

mpflog()


Methodlog10

mpflog10()


Methodlog2

mpflog2()


Variablepi

mpf Gmp.mpf.pi


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..256)|int(-256..-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..256)|int(-256..-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


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.


Inheritcreate_pie

protected inherit .create_pie : create_pie

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 '?'.


Methodoutput

voidoutput(stringdata)

Description

Send data directly to the remote side.


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


Methodreply

voidreply(stringdata)
voidreply(stringheaders, Stdio.Filefd, intlen)
voidreply(int(0..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.


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

Module Java


MethodJArray

jobjectJArray(arraya)


MethodJBoolean

jobjectJBoolean(inti)


MethodJFloat

jobjectJFloat(floatf)


MethodJHashMap

jobjectJHashMap(mappingm)


MethodJInteger

jobjectJInteger(inti)


MethodJString

jobjectJString(strings)


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();

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


Methodcreate

Languages.PLIS.BindingLanguages.PLIS.Binding(objectvalue)


Variablevalue

object Languages.PLIS.Binding.value

Class Languages.PLIS.Builtin


Variableapply

function(:void) Languages.PLIS.Builtin.apply


Methodcreate

Languages.PLIS.BuiltinLanguages.PLIS.Builtin(function(:void) apply)


InheritLObject

inherit LObject : LObject

Class Languages.PLIS.Lambda


Methodcreate

Languages.PLIS.LambdaLanguages.PLIS.Lambda(objectformals, objectlist)


Variableformals
Variablelist

object Languages.PLIS.Lambda.formals
object Languages.PLIS.Lambda.list


InheritLObject

inherit LObject : LObject

Class Languages.PLIS.Number


Methodcreate

Languages.PLIS.NumberLanguages.PLIS.Number(int|float|objectvalue)


InheritSelfEvaluating

inherit SelfEvaluating : SelfEvaluating


Variablevalue

int|float|object Languages.PLIS.Number.value

Class Languages.PLIS.Parser


Variablebuffer

string Languages.PLIS.Parser.buffer


Methodcreate

Languages.PLIS.ParserLanguages.PLIS.Parser(stringbuffer)

Class Languages.PLIS.SelfEvaluating


Methodcreate

Languages.PLIS.SelfEvaluatingLanguages.PLIS.SelfEvaluating(stringname)


InheritLObject

inherit LObject : LObject


Variablename

string Languages.PLIS.SelfEvaluating.name

Class Languages.PLIS.String


Methodcreate

Languages.PLIS.StringLanguages.PLIS.String(stringvalue)


InheritSelfEvaluating

inherit SelfEvaluating : SelfEvaluating


Variablevalue

string Languages.PLIS.String.value

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()


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.


Inherit__joinnode

inherit __joinnode : __joinnode


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

Methodcall

function(:void) call(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) get_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.


Methodcreate

Locale.DeferredLocaleLocale.DeferredLocale(stringproject, function(:string) get_lang, string|intkey, stringfallback)


Variableproject
Variableget_lang
Variablekey
Variablefallback

protectedstring Locale.DeferredLocale.project
protectedfunction(:string) Locale.DeferredLocale.get_lang
protectedstring|int Locale.DeferredLocale.key
protectedstring Locale.DeferredLocale.fallback


Methodget_identifier

arrayget_identifier()

Description

Return the data nessesary to recreate this "string".

Class Locale.LanguageListObject


Methodcreate

Locale.LanguageListObjectLocale.LanguageListObject(array(string) languages)


Variablelanguages

array(string) Locale.LanguageListObject.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.


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.

Note

This category isn't available on all platforms.


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.

Note

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.

Note

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.


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.


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.


Methodmonth

stringmonth(int(1..12)num)

Description

Returns the name of month number num.


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.


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.


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

stringguess_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"


Inherit___MIME

inherit ___MIME : ___MIME


Methodparse_headers

array(mapping(string:string)|string) parse_headers(stringmessage)
array(mapping(string:array(string))|string) parse_headers(stringmessage, int(1..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 strin