17. The rest

Namespace 7.4::


Methodhash

inthash(strings)
inthash(strings, intmax)

Description

Return an integer derived from the string s. The same string will always hash 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 reasons.

This function is byte-order dependant for wide strings.

See also

predef::hash(), 7.0::hash()

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.


Directive#require

#require

Description

If the directive evaluates to false, the source file will be considered to have failed dependencies, and will not be found by the resolver. In practical terms the cpp() call will return zero.

See also

#if


Variable__COUNTER__

int(1..)__COUNTER__

Description

This define contains a unique counter (unless it has been expanded Inte.NATIVE_MAX times) represented as an integer.


Constant__OS2__

constant__OS2__

Description

This define is defined when the Pike is running on IBM OS/2.

Namespace predef::


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


MethodRegGetKeyNames

array(string) RegGetKeyNames(inthkey, stringkey)

Description

Get a list of value key names from the register.

Parameter hkey

One of the following:

HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_USERS
Parameter key

A registry key.

Returns

Returns an array of value keys stored at the specified location if any. Returns UNDEFINED on missing key. Throws errors on other failures.

Example

> RegGetKeyNames(HKEY_CURRENT_USER, "Keyboard Layout"); (1) Result: ({ "IMEtoggle", "Preload", "Substitutes", "Toggle" })

Note

This function threw errors on missing key in Pike 7.6 and earlier (see System.RegGetKeyNames_76()).

Note

This function is only available on Win32 systems.

See also

RegGetValue(), RegGetValues(), System.RegGetKeyNames_76()


MethodRegGetValue

string|int|array(string) RegGetValue(inthkey, stringkey, stringindex)

Description

Get a single value from the register.

Parameter hkey

One of the following:

HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_USERS
Parameter key

Registry key.

Parameter index

Value name.

Returns

Returns the value stored at the specified location in the register if any. Returns UNDEFINED on missing keys, throws errors on other failures.

Note

This function threw errors on missing keys in Pike 7.6 and earlier (see System.RegGetValue_76()).

Note

This function is only available on Win32 systems.

See also

RegGetValues(), RegGetKeyNames(), System.RegGetValue_76()


MethodRegGetValues

mapping(string:string|int|array(string)) RegGetValues(inthkey, stringkey)

Description

Get multiple values from the register.

Parameter hkey

One of the following:

HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_USERS
Parameter key

Registry key.

Returns

Returns a mapping with all the values stored at the specified location in the register if any. Returns UNDEFINED on missing key. Throws errors on other failures.

Example

> RegGetValues(HKEY_CURRENT_USER, "Keyboard Layout\\Preload"); (5) Result: ([ "1":"0000041d" ])

Note

This function threw errors on missing key in Pike 7.6 and earlier (see System.RegGetValues_76()).

Note

This function is only available on Win32 systems.

See also

RegGetValue(), RegGetKeyNames(), System.RegGetValues_76()


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__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_disable_threads

_disable_threads_disable_threads()

Description

This function first posts a notice to all threads that it is time to stop. It then waits until all threads actually *have* stopped, and then then returns a lock object. All other threads will be blocked from running until that object has been freed/destroyed.

It's mainly useful to do things that require a temporary uid/gid change, since on many OS the effective user and group applies to all threads.

Note

You should make sure that the returned object is freed even if some kind of error is thrown. That means in practice that it should only have references (direct or indirect) from function local variables. Also, it shouldn't be referenced from cyclic memory structures, since those are only destructed by the periodic gc. (This advice applies to mutex locks in general, for that matter.)

See also

gethrdtime()


Methodcall_out
Method_do_call_outs
Methodfind_call_out
Methodremove_call_out
Methodcall_out_info

mixedcall_out(function(:void) f, float|intdelay, mixed ... args)
void_do_call_outs()
intfind_call_out(function(:void) f)
intfind_call_out(mixedid)
intremove_call_out(function(:void) f)
intremove_call_out(function(:void) id)
array(array) call_out_info()

Description

These are aliases for the corresponding functions in Pike.DefaultBackend.

See also

Pike.Backend()->call_out(), Pike.Backend()->_do_call_outs(), Pike.Backend()->find_call_out(), Pike.Backend()->remove_call_out(), Pike.Backend()->call_out_info()


Method_exit

void_exit(intreturncode)

Description

This function does the same as exit, but doesn't bother to clean up the Pike interpreter before exiting. This means that no destructors will be called, caches will not be flushed, file locks might not be released, and databases might not be closed properly.

Use with extreme caution.

See also

exit()


Method_next

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


Method_prev

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


Method_refs

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


Variable_static_modules

object_static_modules

Description

This is an object containing the classes for all static (ie non-dynamic) C-modules.

In a typic Pike with support for dynamic modules the contained module classes are:

Builtin

Gmp

_Stdio

_math

_system

If the Pike binary lacks support for dynamic modules, all C-modules will show up here.


Method_typeof

type_typeof(mixedx)

Description

Return the runtime type of x.

See also

typeof()


Method`!

bool`!(object|function(:void) arg)
int(1..1)`!(int(0..0)arg)
int(0..0)`!(mixedarg)

Description

Logical not.

Every expression with the ! operator becomes a call to this function, i.e. !a is the same as predef::`!(a).

It's also used when necessary to test truth on objects, i.e. in a statement if (o) ... where o is an object, the test becomes the equivalent of !!o so that any lfun::`!() the object might have gets called.

Returns

If arg is an object that implements lfun::`!(), that function will be called.

If arg is 0 (zero), a destructed object, or a function in a destructed object, 1 will be returned.

Otherwise 0 (zero) will be returned.

Note

No float is considered false, not even 0.0.

See also

`==(), `!=(), lfun::`!()


Method`!=

bool`!=(mixedarg1, mixedarg2, mixed ... extras)

Description

Inequality test.

Every expression with the != operator becomes a call to this function, i.e. a!=b is the same as predef::`!=(a,b).

This is the inverse of `==(); see that function for further details.

Returns

Returns 1 if the test is successful, 0 otherwise.

See also

`==()


Method`%

mixed`%(objectarg1, mixedarg2)
mixed`%(mixedarg1, objectarg2)
string`%(stringarg1, intarg2)
array`%(arrayarg1, intarg2)
float`%(floatarg1, float|intarg2)
float`%(intarg1, floatarg2)
int`%(intarg1, intarg2)

Description

Modulo.

Every expression with the % operator becomes a call to this function, i.e. a%b is the same as predef::`%(a,b).

Returns

If arg1 is an object that implements lfun::`%() then that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``%() then that function will be called with arg2 as the single argument.

Otherwise the result will be as follows:

arg1 can have any of the following types:
string|array

If arg2 is positive, the result will be the last `%(sizeof(arg1), arg2) elements of arg1. If arg2 is negative, the result will be the first `%(sizeof(arg1), -arg2) elements of arg1.

int|float

The result will be arg1 - arg2*floor(arg1/arg2). The result will be a float if either arg1 or arg2 is a float, and an int otherwise.

For numbers, this means that

  1. a % b always has the same sign as b (typically b is positive; array size, rsa modulo, etc, and a varies a lot more than b).

  2. The function f(x) = x % n behaves in a sane way; as x increases, f(x) cycles through the values 0,1, ..., n-1, 0, .... Nothing strange happens when you cross zero.

  3. The % operator implements the binary "mod" operation, as defined by Donald Knuth (see the Art of Computer Programming, 1.2.4). It should be noted that Pike treats %-by-0 as an error rather than returning 0, though.

  4. / and % are compatible, so that a == b*floor(a/b) + a%b for all a and b.

See also

`/, floor()


Method`&

mixed`&(mixedarg1)
mixed`&(mixedarg1, mixedarg2, mixed ... extras)
mixed`&(objectarg1, mixedarg2)
mixed`&(mixedarg1, objectarg2)
int`&(intarg1, intarg2)
string`&(stringarg1, stringarg2)
array`&(arrayarg1, arrayarg2)
mapping`&(mappingarg1, mappingarg2)
mapping`&(mappingarg1, arrayarg2)
mapping`&(mappingarg1, multisetarg2)
multiset`&(multisetarg1, multisetarg2)
type`&(type|programarg1, type|programarg2)

Description

Bitwise and/intersection.

Every expression with the & operator becomes a call to this function, i.e. a&b is the same as predef::`&(a,b).

Returns

If there's a single argument, that argument is returned.

If there are more than two arguments the result is: `&(`&(arg1arg2), @extras).

Otherwise, if arg1 is an object with an lfun::`&(), that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``&(), that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int

Bitwise and of arg1 and arg2.

string

The result is a string where each character is the bitwise and of the characters in the same position in arg1 and arg2. The arguments must be strings of the same length.

array|mapping|multiset

The result is like arg1 but only with the elements/indices that match any in arg2 (according to `== and, in the case of mappings, hash_value).

type|program

Type intersection of arg1 and arg2.

The function is not destructive on the arguments - the result is always a new instance.

See also

`|(), lfun::`&(), lfun::``&()


Method`()
Methodcall_function

mixed`()(function(:void) fun, mixed ... args)
mixedcall_function(function(:void) fun, mixed ... args)

Description

Call a function.

Calls the function fun with the arguments specified by args.

See also

lfun::`()()


Method`*

mixed`*(mixedarg1)
mixed`*(objectarg1, mixedarg2, mixed ... extras)
mixed`*(mixedarg1, objectarg2)
array`*(arrayarg1, intarg2)
array`*(arrayarg1, floatarg2)
string`*(stringarg1, intarg2)
string`*(stringarg1, floatarg2)
string`*(array(string) arg1, stringarg2)
array`*(array(array) arg1, arrayarg2)
float`*(floatarg1, int|floatarg2)
float`*(intarg1, floatarg2)
int`*(intarg1, intarg2)
mixed`*(mixedarg1, mixedarg2, mixed ... extras)

Description

Multiplication/repetition/implosion.

Every expression with the * operator becomes a call to this function, i.e. a*b is the same as predef::`*(a,b). Longer * expressions are normally optimized to one call, so e.g. a*b*c becomes predef::`*(a,b,c).

Returns

If there's a single argument, that argument will be returned.

If the first argument is an object that implements lfun::`*(), that function will be called with the rest of the arguments.

If there are more than two arguments, the result will be `*(`*(arg1arg2), @extras).

If arg2 is an object that implements lfun::``*(), that function will be called with arg1 as the single argument.

Otherwise the result will be as follows:

arg1 can have any of the following types:
arrayarg2 can have any of the following types:
int|float

The result will be arg1 concatenated arg2 times.

string|array

The result will be the elements of arg1 concatenated with arg2 interspersed.

string

The result will be arg1 concatenated arg2 times.

int|float

The result will be arg1 * arg2, and will be a float if either arg1 or arg2 is a float.

Note

In Pike 7.0 and earlier the multiplication order was unspecified.

See also

`+(), `-(), `/(), lfun::`*(), lfun::``*()


Method`+

mixed`+(mixedarg)
mixed`+(objectarg, mixed ... more)
int`+(intarg, int ... more)
float`+(float|intarg, float|int ... more)
string`+(string|float|intarg, string|float|int ... more)
array`+(arrayarg, array ... more)
mapping`+(mappingarg, mapping ... more)
multiset`+(multisetarg, multiset ... more)

Description

Addition/concatenation.

Every expression with the + operator becomes a call to this function, i.e. a+b is the same as predef::`+(a,b). Longer + expressions are normally optimized to one call, so e.g. a+b+c becomes predef::`+(a,b,c).

Returns

If there's a single argument, that argument is returned.

If arg is an object with only one reference and an lfun::`+=(), that function is called with the rest of the arguments, and its result is returned.

Otherwise, if arg is an object with an lfun::`+(), that function is called with the rest of the arguments, and its result is returned.

Otherwise, if any of the other arguments is an object that has an lfun::``+(), the first such function is called with the arguments leading up to it, and `+() is then called recursively with the result and the rest of the arguments.

Otherwise, if arg is UNDEFINED and the other arguments are either arrays, mappings or multisets, the first argument is ignored and the remaining are added together as described below. This is useful primarily when appending to mapping values since m[x] += ({foo}) will work even if m[x] doesn't exist yet.

Otherwise the result depends on the argument types:

int|float

The result is the sum of all the arguments. It's a float if any argument is a float.

string|int|float

If any argument is a string, all will be converted to strings and concatenated in order to form the result.

array

The array arguments are concatened in order to form the result.

mapping

The result is like arg but extended with the entries from the other arguments. If the same index (according to hash_value and `==) occur in several arguments, the value from the last one is used.

multiset

The result is like arg but extended with the entries from the other arguments. Subsequences with orderwise equal indices (i.e. where `< returns false) are concatenated into the result in argument order.

The function is not destructive on the arguments - the result is always a new instance.

Note

In Pike 7.0 and earlier the addition order was unspecified.

The treatment of UNDEFINED was new in Pike 7.0.

See also

`-(), lfun::`+(), lfun::``+()


Method`-

mixed`-(mixedarg1)
mixed`-(mixedarg1, mixedarg2, mixed ... extras)
mixed`-(objectarg1, mixedarg2)
mixed`-(mixedarg1, objectarg2)
int`-(intarg1, intarg2)
float`-(floatarg1, int|floatarg2)
float`-(int|floatarg1, floatarg2)
string`-(stringarg1, stringarg2)
array`-(arrayarg1, arrayarg2)
mapping`-(mappingarg1, arrayarg2)
mapping`-(mappingarg1, mappingarg2)
mapping`-(mappingarg1, multisetarg2)
multiset`-(multisetarg1, multisetarg2)

Description

Negation/subtraction/set difference.

Every expression with the - operator becomes a call to this function, i.e. -a is the same as predef::`-(a) and a-b is the same as predef::`-(a,b). Longer - expressions are normally optimized to one call, so e.g. a-b-c becomes predef::`-(a,b,c).

Returns

If there's a single argument, that argument is returned negated. If arg1 is an object with an lfun::`-(), that function is called without arguments, and its result is returned.

If there are more than two arguments the result is: `-(`-(arg1arg2), @extras).

Otherwise, if arg1 is an object with an lfun::`-(), that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``-(), that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int|float

The result is arg1 - arg2, and is a float if either arg1 or arg2 is a float.

string

The result is arg1 with all nonoverlapping occurrences of the substring arg2 removed. In cases with two overlapping occurrences, the leftmost is removed.

array|mapping|multiset

The result is like arg1 but without the elements/indices that match any in arg2 (according to `== and, in the case of mappings, hash_value).

The function is not destructive on the arguments - the result is always a new instance.

Note

In Pike 7.0 and earlier the subtraction order was unspecified.

See also

`+()


Method`->

mixed`->(objectarg, stringindex)
mixed`->(intarg, stringindex)
mixed`->(arrayarg, stringindex)
mixed`->(mappingarg, stringindex)
bool`->(multisetarg, stringindex)
mixed`->(programarg, stringindex)

Description

Arrow indexing.

Every non-lvalue expression with the -> operator becomes a call to this function. a->b is the same as predef::`^(a,"b") where "b" is the symbol b in string form.

This function behaves like `[], except that the index is passed literally as a string instead of being evaluated.

Returns

If arg is an object that implements lfun::`->(), that function will be called with index as the single argument.

Otherwise the result will be as follows:

arg can have any of the following types:
object

The non-protected (ie public) symbol named index will be looked up in arg.

int

The bignum function named index will be looked up in arg.

array

An array of all elements in arg arrow indexed with index will be returned.

mapping

If index exists in arg the corresponding value will be returned. Otherwise UNDEFINED will be returned.

multiset

If index exists in arg, 1 will be returned. Otherwise UNDEFINED will be returned.

program

The non-protected (ie public) constant symbol index will be looked up in arg.

Note

In an expression a->b, the symbol b can be any token that matches the identifier syntax - keywords are disregarded in that context.

Note

An arrow indexing expression in an lvalue context, i.e. where the index is being assigned a new value, uses `->= instead of this function.

See also

`[](), lfun::`->(), ::`->(), `->=


Method`->=

mixed`->=(objectarg, stringindex, mixedval)
mixed`->=(mappingarg, stringindex, mixedval)
bool`->=(multisetarg, stringindex, boolval)

Description

Arrow index assignment.

Every lvalue expression with the -> operator becomes a call to this function, i.e. a->b=c is the same as predef::`->=(a,"b",c) where "b" is the symbol b in string form.

This function behaves like `[]=, except that the index is passed literally as a string instead of being evaluated.

If arg is an object that implements lfun::`->=(), that function will be called with index and val as the arguments.

arg can have any of the following types:
object

The non-protected (ie public) variable named index will be looked up in arg, and assigned val.

array|mapping

Index index in arg will be assigned val.

multiset

If val is 0 (zero), one occurrance of index in arg will be removed. Otherwise index will be added to arg if it is not already there.

Returns

val will be returned.

Note

In an expression a->b=c, the symbol b can be any token that matches the identifier syntax - keywords are disregarded in that context.

Note

An arrow indexing expression in a non-lvalue context, i.e. where the index is being queried instead of assigned, uses `-> instead of this function.

See also

`[]=(), lfun::`->=(), `->


Method`/

mixed`/(objectarg1, mixedarg2)
mixed`/(mixedarg1, objectarg2)
array(string) `/(stringarg1, intarg2)
array(string) `/(stringarg1, floatarg2)
array(array) `/(arrayarg1, intarg2)
array(array) `/(arrayarg1, floatarg2)
array(string) `/(stringarg1, stringarg2)
array(array) `/(arrayarg1, arrayarg2)
float`/(floatarg1, int|floatarg2)
float`/(intarg1, floatarg2)
int`/(intarg1, intarg2)
mixed`/(mixedarg1, mixedarg2, mixed ... extras)

Description

Division/split.

Every expression with the / operator becomes a call to this function, i.e. a/b is the same as predef::`/(a,b).

Returns

If there are more than two arguments, the result will be `/(`/(arg1arg2), @extras).

If arg1 is an object that implements lfun::`/(), that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``/(), that function will be called with arg1 as the single argument.

Otherwise the result will be as follows:

arg1 can have any of the following types:
stringarg2 can have any of the following types:
int|float

The result will be and array of arg1 split in segments of length arg2. If arg2 is negative the splitting will start from the end of arg1.

string

The result will be an array of arg1 split at each occurrence of arg2. Note that the segments that matched against arg2 will not be in the result.

arrayarg2 can have any of the following types:
int|float

The result will be and array of arg1 split in segments of length arg2. If arg2 is negative the splitting will start from the end of arg1.

array

The result will be an array of arg1 split at each occurrence of arg2. Note that the elements that matched against arg2 will not be in the result.

float|int

The result will be arg1 / arg2. If both arguments are int, the result will be truncated to an int. Otherwise the result will be a float.

Note

Unlike in some languages, the function f(x) = x/n (x and n integers) behaves in a well-defined way and is always rounded down. When you increase x, f(x) will increase with one for each n:th increment. For all x, (x + n) / n = x/n + 1; crossing zero is not special. This also means that / and % are compatible, so that a = b*(a/b) + a%b for all a and b.

See also

`%


Method`<

bool`<(mixedarg1, mixedarg2, mixed ... extras)

Description

Less than test.

Every expression with the < operator becomes a call to this function, i.e. a<b is the same as predef::`<(a,b).

Returns

Returns 1 if the test is successful, 0 otherwise.

See also

`<=(), `>(), `>=()


Method`<<

int`<<(intarg1, intarg2)
mixed`<<(objectarg1, int|objectarg2)
mixed`<<(intarg1, objectarg2)

Description

Left shift.

Every expression with the << operator becomes a call to this function, i.e. a<<b is the same as predef::`<<(a,b).

If arg1 is an object that implements lfun::`<<(), that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``<<(), that function will be called with arg1 as the single argument.

Otherwise arg1 will be shifted arg2 bits left.

See also

`>>()


Method`<=

bool`<=(mixedarg1, mixedarg2, mixed ... extras)

Description

Less than or equal test.

Every expression with the <= operator becomes a call to this function, i.e. a<=b is the same as predef::`<=(a,b).

Returns

Returns 1 if the test is successful, 0 otherwise.

Note

For total orders, e.g. integers, this is the inverse of `>().

See also

`<(), `>(), `>=()


Method`==

bool`==(mixedarg1, mixedarg2, mixed ... extras)

Description

Equality test.

Every expression with the == operator becomes a call to this function, i.e. a==b is the same as predef::`==(a,b).

If more than two arguments are given, each argument is compared with the following one as described below, and the test is successful iff all comparisons are successful.

If the first argument is an object with an lfun::`==(), that function is called with the second as argument, unless the second argument is the same as the first argument. The test is successful iff its result is nonzero (according to `!).

Otherwise, if the second argument is an object with an lfun::`==(), that function is called with the first as argument, and the test is successful iff its result is nonzero (according to `!).

Otherwise, if the arguments are of different types, the test is unsuccessful. Function pointers to programs are automatically converted to program pointers if necessary, though.

Otherwise the test depends on the type of the arguments:

int

Successful iff the two integers are numerically equal.

float

Successful iff the two floats are numerically equal and not NaN.

string

Successful iff the two strings are identical, character for character. (Since all strings are kept unique, this is actually a test whether the arguments point to the same string, and it therefore run in constant time.)

array|mapping|multiset|object|function(:void)|program|type

Successful iff the two arguments point to the same instance.

Returns

Returns 1 if the test is successful, 0 otherwise.

Note

Floats and integers are not automatically converted to test against each other, so e.g. 0==0.0 is false.

Note

Programs are not automatically converted to types to be compared type-wise.

See also

`!(), `!=()


Method`>

bool`>(mixedarg1, mixedarg2, mixed ... extras)

Description

Greater than test.

Every expression with the > operator becomes a call to this function, i.e. a>b is the same as predef::`>(a,b).

Returns

Returns 1 if the arguments are strictly decreasing, and 0 (zero) otherwise.

See also

`<(), `<=(), `>=()


Method`>=

bool`>=(mixedarg1, mixedarg2, mixed ... extras)

Description

Greater than or equal test.

Every expression with the >= operator becomes a call to this function, i.e. a>=b is the same as predef::`>=(a,b).

Returns

Returns 1 if the test is successful, 0 otherwise.

Note

For total orders, e.g. integers, this is the inverse of `<().

See also

`<=(), `>(), `<()


Method`>>

int`>>(intarg1, intarg2)
mixed`>>(objectarg1, int|objectarg2)
mixed`>>(intarg1, objectarg2)

Description

Right shift.

Every expression with the >> operator becomes a call to this function, i.e. a>>b is the same as predef::`>>(a,b).

If arg1 is an object that implements lfun::`>>(), that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``>>(), that function will be called with arg1 as the single argument.

Otherwise arg1 will be shifted arg2 bits right.

See also

`<<()


Method`[..]

mixed`[..](objectarg, mixedstart, intstart_type, mixedend, intend_type)
string`[..](stringarg, intstart, intstart_type, intend, intend_type)
array`[..](arrayarg, intstart, intstart_type, intend, intend_type)

Description

Extracts a subrange.

This is the function form of expressions with the [..] operator. arg is the thing from which the subrange is to be extracted. start is the lower bound of the subrange and end the upper bound.

start_type and end_type specifies how the start and end indices, respectively, are to be interpreted. The types are either Pike.INDEX_FROM_BEG, Pike.INDEX_FROM_END or Pike.OPEN_BOUND. In the last case, the index value is insignificant.

The relation between [..] expressions and this function is therefore as follows:

a<span class='delim'>[</span>i..j<span class='delim'>]</span>    <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> i<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_BEG<span class='delim'>,</span> j<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_BEG<span class='delim'>)</span>
    a<span class='delim'>[</span>i..<span class='delim'><</span>j<span class='delim'>]</span>   <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> i<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_BEG<span class='delim'>,</span> j<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_END<span class='delim'>)</span>
    a<span class='delim'>[</span>i..<span class='delim'>]</span>     <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> i<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_BEG<span class='delim'>,</span> 0<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>OPEN_BOUND<span class='delim'>)</span>
    a<span class='delim'>[</span><span class='delim'><</span>i..j<span class='delim'>]</span>   <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> i<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_END<span class='delim'>,</span> j<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_BEG<span class='delim'>)</span>
    a<span class='delim'>[</span><span class='delim'><</span>i..<span class='delim'><</span>j<span class='delim'>]</span>  <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> i<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_END<span class='delim'>,</span> j<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_END<span class='delim'>)</span>
    a<span class='delim'>[</span><span class='delim'><</span>i..<span class='delim'>]</span>    <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> i<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_END<span class='delim'>,</span> 0<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>OPEN_BOUND<span class='delim'>)</span>
    a<span class='delim'>[</span>..j<span class='delim'>]</span>     <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> 0<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>OPEN_BOUND<span class='delim'>,</span> j<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_BEG<span class='delim'>)</span>
    a<span class='delim'>[</span>..<span class='delim'><</span>j<span class='delim'>]</span>    <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> 0<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>OPEN_BOUND<span class='delim'>,</span> j<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>INDEX_FROM_END<span class='delim'>)</span>
    a<span class='delim'>[</span>..<span class='delim'>]</span>      <=<span class='delim'>></span>	`[..] <span class='delim'>(</span>a<span class='delim'>,</span> 0<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>OPEN_BOUND<span class='delim'>,</span> 0<span class='delim'>,</span> <span class='ns'>Pike</span><span class='delim'>.</span>OPEN_BOUND<span class='delim'>)</span>

The subrange is specified as follows by the two bounds:

  • If the lower bound refers to an index before the lowest allowable (typically zero) then it's taken as an open bound which starts at the first index (without any error).

  • Correspondingly, if the upper bound refers to an index past the last allowable then it's taken as an open bound which ends at the last index (without any error).

  • If the lower bound is less than or equal to the upper bound, then the subrange is the inclusive range between them, i.e. from and including the element at the lower bound and up to and including the element at the upper bound.

  • If the lower bound is greater than the upper bound then the result is an empty subrange (without any error).

Returns

The returned value depends on the type of arg:

arg can have any of the following types:
string

A string with the characters in the range is returned.

array

An array with the elements in the range is returned.

object

If the object implements lfun::`[..], that function is called with the four remaining arguments.

As a compatibility measure, if the object does not implement lfun::`[..] but lfun::`[] then the latter is called with the bounds transformed to normal from-the-beginning indices in array-like fashion:

`[..] (a, i, Pike.INDEX_FROM_BEG, j, Pike.INDEX_FROM_BEG)

Calls a->`[] (i, j)

`[..] (a, i, Pike.INDEX_FROM_BEG, j, Pike.INDEX_FROM_END)

Calls a->`[] (i, a->_sizeof()-1-j)

`[..] (a, i, Pike.INDEX_FROM_BEG, 0, Pike.OPEN_BOUND)

Calls a->`[] (i, Int.NATIVE_MAX)

`[..] (a, i, Pike.INDEX_FROM_END, j, Pike.INDEX_FROM_BEG)

Calls a->`[] (a->_sizeof()-1-i, j)

`[..] (a, i, Pike.INDEX_FROM_END, j, Pike.INDEX_FROM_END)

Calls a->`[] (a->_sizeof()-1-i, a->_sizeof()-1-j), except that a->_sizeof() is called only once.

`[..] (a, i, Pike.INDEX_FROM_END, 0, Pike.OPEN_BOUND)

Calls a->`[] (a->_sizeof()-1-i, Int.NATIVE_MAX)

`[..] (a, 0, Pike.OPEN_BOUND, j, Pike.INDEX_FROM_BEG)

Calls a->`[] (0, j)

`[..] (a, 0, Pike.OPEN_BOUND, j, Pike.INDEX_FROM_END)

Calls a->`[] (0, a->_sizeof()-1-j)

`[..] (a, 0, Pike.OPEN_BOUND, 0, Pike.OPEN_BOUND)

Calls a->`[] (0, Int.NATIVE_MAX)

Note that Int.NATIVE_MAX might be replaced with an even larger integer in the future.

See also

lfun::`[..], `[]


Method`[]

mixed`[](objectarg, mixedindex)
mixed`[](objectarg, stringindex)
function(:void) `[](intarg, stringindex)
int`[](stringarg, intindex)
mixed`[](arrayarg, intindex)
mixed`[](arrayarg, mixedindex)
mixed`[](mappingarg, mixedindex)
bool`[](multisetarg, mixedindex)
mixed`[](programarg, stringindex)
mixed`[](objectarg, mixedstart, mixedend)
string`[](stringarg, intstart, intend)
array`[](arrayarg, intstart, intend)

Description

Indexing.

This is the function form of expressions with the [] operator, i.e. a[i] is the same as predef::`[](a,i).

Returns

If arg is an object that implements lfun::`[](), that function is called with the index argument.

Otherwise, the action depends on the type of arg:

arg can have any of the following types:
object

The non-protected (i.e. public) symbol named index is looked up in arg.

int

The bignum function named index is looked up in arg. The bignum functions are the same as those in the Gmp.mpz class.

string

The character at index index in arg is returned as an integer. The first character in the string is at index 0 and the highest allowed index is therefore sizeof(arg)-1. A negative index number accesses the string from the end instead, from -1 for the last char back to -sizeof(arg) for the first.

array

If index is an int, index number index of arg is returned. Allowed index number are in the range [-sizeof(arg)..sizeof(arg)-1]; see the string case above for details.

If index is not an int, an array of all elements in arg indexed with index are returned. I.e. it's the same as doing column(argindex).

mapping

If index exists in arg the corresponding value is returned. Otherwise UNDEFINED is returned.

multiset

If index exists in arg, 1 is returned. Otherwise UNDEFINED is returned.

program

The non-protected (i.e. public) constant symbol index is looked up in arg.

As a compatibility measure, this function also performs range operations if it's called with three arguments. In that case it becomes equivalent to:

`[..] (arg, start, Pike.INDEX_FROM_BEG, end, Pike.INDEX_FROM_BEG)

See `[..] for further details.

Note

An indexing expression in an lvalue context, i.e. where the index is being assigned a new value, uses `[]= instead of this function.

See also

`->(), lfun::`[](), `[]=, `[..]


Method`[]=

mixed`[]=(objectarg, mixedindex, mixedval)
mixed`[]=(objectarg, stringindex, mixedval)
mixed`[]=(arrayarg, intindex, mixedval)
mixed`[]=(mappingarg, mixedindex, mixedval)
bool`[]=(multisetarg, mixedindex, boolval)

Description

Index assignment.

Every lvalue expression with the [] operator becomes a call to this function, i.e. a[b]=c is the same as predef::`[]=(a,b,c).

If arg is an object that implements lfun::`[]=(), that function will be called with index and val as the arguments.

arg can have any of the following types:
object

The non-protected (ie public) variable named index will be looked up in arg, and assigned val.

array|mapping

Index index in arg will be assigned val.

multiset

If val is 0 (zero), one occurrance of index in arg will be removed. Otherwise index will be added to arg if it is not already there.

Returns

val will be returned.

Note

An indexing expression in a non-lvalue context, i.e. where the index is being queried instead of assigned, uses `[] instead of this function.

See also

`->=(), lfun::`[]=(), `[]


Method`^

mixed`^(mixedarg1)
mixed`^(mixedarg1, mixedarg2, mixed ... extras)
mixed`^(objectarg1, mixedarg2)
mixed`^(mixedarg1, objectarg2)
int`^(intarg1, intarg2)
string`^(stringarg1, stringarg2)
array`^(arrayarg1, arrayarg2)
mapping`^(mappingarg1, mappingarg2)
multiset`^(multisetarg1, multisetarg2)
type`^(program|typearg1, program|typearg2)

Description

Exclusive or.

Every expression with the ^ operator becomes a call to this function, i.e. a^b is the same as predef::`^(a,b).

Returns

If there's a single argument, that argument is returned.

If there are more than two arguments, the result is: `^(`^(arg1arg2), @extras).

Otherwise, if arg1 is an object with an lfun::`^(), that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``^(), that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int

Bitwise exclusive or of arg1 and arg2.

string

The result is a string where each character is the bitwise exclusive or of the characters in the same position in arg1 and arg2. The arguments must be strings of the same length.

array

The result is an array with the elements in arg1 that doesn't occur in arg2 concatenated with those in arg2 that doesn't occur in arg1 (according to `==). The order between the elements that come from the same argument is kept.

Every element is only matched once against an element in the other array, so if one contains several elements that are equal to each other and are more than their counterparts in the other array, the rightmost remaining elements are kept.

mapping

The result is like arg1 but with the entries from arg1 and arg2 whose indices are different between them (according to hash_value and `==).

multiset

The result is like arg1 but with the entries from arg1 and arg2 that are different between them (according to hash_value and `==). Subsequences with orderwise equal entries (i.e. where `< returns false) are handled just like the array case above.

type|program

The result is a type computed like this: (arg1&~arg2)|(~arg1&arg2).

The function is not destructive on the arguments - the result is always a new instance.

See also

`&(), `|(), lfun::`^(), lfun::``^()


Method`|

mixed`|(mixedarg1)
mixed`|(mixedarg1, mixedarg2, mixed ... extras)
mixed`|(objectarg1, mixedarg2)
mixed`|(mixedarg1, objectarg2)
int`|(intarg1, intarg2)
string`|(stringarg1, stringarg2)
array`|(arrayarg1, arrayarg2)
mapping`|(mappingarg1, mappingarg2)
multiset`|(multisetarg1, multisetarg2)
type`|(program|typearg1, program|typearg2)

Description

Bitwise or/union.

Every expression with the | operator becomes a call to this function, i.e. a|b is the same as predef::`|(a,b).

Returns

If there's a single argument, that argument is returned.

If there are more than two arguments, the result is: `|(`|(arg1arg2), @extras).

Otherwise, if arg1 is an object with an lfun::`|(), that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``|(), that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int

Bitwise or of arg1 and arg2.

string

The result is a string where each character is the bitwise or of the characters in the same position in arg1 and arg2. The arguments must be strings of the same length.

array

The result is an array with the elements in arg1 concatenated with those in arg2 that doesn't occur in arg1 (according to `==). The order between the elements that come from the same argument is kept.

Every element in arg1 is only matched once against an element in arg2, so if arg2 contains several elements that are equal to each other and are more than their counterparts in arg1, the rightmost remaining elements in arg2 are kept.

mapping

The result is like arg1 but extended with the entries from arg2. If the same index (according to hash_value and `==) occur in both, the value from arg2 is used.

multiset

The result is like arg1 but extended with the entries in arg2 that doesn't already occur in arg1 (according to `==). Subsequences with orderwise equal entries (i.e. where `< returns false) are handled just like the array case above.

type|program

Type union of arg1 and arg2.

The function is not destructive on the arguments - the result is always a new instance.

See also

`&(), lfun::`|(), lfun::``|()


Method`~

mixed`~(objectarg)
int`~(intarg)
float`~(floatarg)
type`~(type|programarg)
string`~(stringarg)

Description

Complement/inversion.

Every expression with the ~ operator becomes a call to this function, i.e. ~a is the same as predef::`~(a).

Returns

The result will be as follows:

arg can have any of the following types:
object

If arg implements lfun::`~(), that function will be called.

int

The bitwise inverse of arg will be returned.

float

The result will be -1.0 - arg.

type|program

The type inverse of arg will be returned.

string

If arg only contains characters in the range 0 - 255 (8-bit), a string containing the corresponding 8-bit inverses will be returned.

See also

`!(), lfun::`~()


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


Methodaccess

intaccess(stringpath, string|voidmode)

Description

access() checks if the calling process can access the file path. Symbolic links are dereferenced.

Parameter mode

The mode specifies the accessibility checks to be performed, and is either not specified or empty, in which case access() just tests if the file exists, or one or more of the characters "rwx".

r, w, and x test whether the file exists and grants read, write, and execute permissions, respectively.

The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file. This allows set-user-ID programs to easily determine the invoking user's authority.

If the calling process is privileged (i.e., its real UID is zero), then an X_OK check is successful for a regular file if execute permission is enabled for any of the file owner, group, or other.

Returns
1

When the file is accessible using the given permissions.

0

When the file is not accessible, in which case errno is set to one of the following values:

EACCESS

Access denied.

ELOOP

Too many symbolic links.

ENAMETOOLONG

The path is too long.

ENOENT

The file does not exist.

ENOTDIR

One of the directories used in path is not, in fact, a directory.

EROFS

The filesystem is read only and write access was requested.

Other errors can occur, but are not directly related to the requested path, such as ENOMEM, etc.

See also

errno(), Stdio.File


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


Methodaggregate

arrayaggregate(mixed ... elements)

Description

Construct an array with the arguments as indices.

This function could be written in Pike as:

<span class='type'>array</span> aggregate<span class='delim'>(</span><span class='type'>mixed</span> ... elems<span class='delim'>)</span> <span class='delim'>{</span> <span class='lang'>return</span> elems<span class='delim'>;</span> <span class='delim'>}</span>
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()


Methodalarm

intalarm(intseconds)

Description

Set an alarm clock for delivery of a signal.

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

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

Any previous alarms will in any case be canceled.

Returns

Returns the number of seconds 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

ualarm(), signal(), call_out()


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


Methodarrayp

intarrayp(mixedarg)

Description

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

See also

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


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


Methodatexit

voidatexit(function(:void) callback)

Description

This function puts the callback in a queue of callbacks to call when pike exits. The call order is reversed, i.e. callbacks that have been added earlier are called after callback.

Note

Please note that atexit callbacks are not called if Pike exits abnormally.

See also

exit(), _exit()


Methodbacktrace

array(Pike.BacktraceFrame) backtrace()

Description

FIXME: This documentation is not up to date!

Get a description of the current call stack.

The description is returned as an array with one entry for each call frame on the stack.

Each entry has this format:

Array
stringfile

A string with the filename if known, else zero.

intline

An integer containing the linenumber if known, else zero.

function(:void) fun

The function that was called at this level.

mixed|void ... args

The arguments that the function was called with.

The current call frame will be last in the array.

Note

Please note that the frame order may be reversed in a later version (than 7.1) of Pike to accommodate for deferred backtraces.

Note that the arguments reported in the backtrace are the current values of the variables, and not the ones that were at call-time. This can be used to hide sensitive information from backtraces (eg passwords).

See also

catch(), throw()


Methodbasename

stringbasename(stringx)

Description

Returns the last segment of a path.

See also

dirname(), explode_path()


Methodbasetype

stringbasetype(mixedx)

Description

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

See also

sprintf()


Methodcallablep

intcallablep(mixedarg)

Description

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

See also

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


Methodcd

intcd(strings)

Description

Change the current directory for the whole Pike process.

Returns

Returns 1 for success, 0 (zero) otherwise.

See also

getcwd()


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<span class='delim'>(</span>data<span class='delim'>,</span> <span class='lang'>lambda</span><span class='delim'>(</span><span class='type'>mixed</span> x<span class='delim'>,</span><span class='type'>mixed</span> y<span class='delim'>)</span> <span class='delim'>{</span> <span class='lang'>return</span> x<span class='delim'>[</span>y<span class='delim'>]</span><span class='delim'>;</span> <span class='delim'>}</span><span class='delim'>,</span> index<span class='delim'>)</span>

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


Methodcombine_path
Methodcombine_path_unix
Methodcombine_path_nt
Methodcombine_path_amigaos

stringcombine_path(stringpath, string ... paths)
stringcombine_path_unix(stringpath, string ... paths)
stringcombine_path_nt(stringpath, string ... paths)
stringcombine_path_amigaos(stringpath, string ... paths)

Description

Concatenate a number of paths to a straightforward path without any "//", "/.." or "/.". If any path argument is absolute then the result is absolute and the preceding arguments are ignored. If the result is relative then it might have leading ".." components. If the last nonempty argument ends with a directory separator then the result ends with that too. If all components in a relative path disappear due to subsequent ".." components then the result is ".".

combine_path_unix() concatenates in UNIX style, which also is appropriate for e.g. URL:s ("/" separates path components and absolute paths start with "/"). combine_path_nt() concatenates according to NT filesystem conventions ("/" and "\" separates path components and there might be a drive letter in front of absolute paths). combine_path_amigaos() concatenates according to AmigaOS filesystem conventions.

combine_path() is equivalent to combine_path_unix() on UNIX-like operating systems, and equivalent to combine_path_nt() on NT-like operating systems, and equivalent to combine_path_amigaos() on AmigaOS-like operating systems.

See also

getcwd(), Stdio.append_path()


Methodcompile

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

Description

Compile a string to a program.

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

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

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

Note

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

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

See also

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


Methodcompile_file

programcompile_file(stringfilename, 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.

See also

compile()


Methodcrypt

string(7bit)crypt(stringpassword)
boolcrypt(stringtyped_password, stringcrypted_password)

Description

This function crypts and verifies a short string (only the first 8 characters are significant).

The first syntax crypts the string password into something that is hopefully hard to decrypt.

The second syntax is used to verify typed_password against crypted_password, and returns 1 if they match, and 0 (zero) otherwise.

Note

Note that strings containing null characters will only be processed up until the null character.


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

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


Methoddecode_value

mixeddecode_value(stringcoded_value, void|Codeccodec)

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.

See also

encode_value(), encode_value_canonic()


Methoddelay

voiddelay(int|floats)

Description

This function makes the program stop for s seconds.

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

See also

signal(), sleep()


Methoddescribe_backtrace

stringdescribe_backtrace(mixedtrace, void|intlinewidth)

Description

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

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

Pass linewidth -1 to disable wrapping of the output.

See also

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


Methoddescribe_error

stringdescribe_error(mixederr)

Description

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

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

See also

describe_backtrace(), get_backtrace


Methoddestruct

voiddestruct(void|objecto)

Description

Mark an object as destructed.

Calls o->destroy(), 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.


Methoddestructedp

intdestructedp(mixedarg)

Description

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

See also

zero_type, undefinedp, intp


Methoddirname

stringdirname(stringx)

Description

Returns all but the last segment of a path. Some example inputs and outputs:

ExpressionValue
dirname("/a/b")"/a"
dirname("/a/")"/a"
dirname("/a")"/"
dirname("/")"/"
dirname("")""
See also

basename(), explode_path()


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:

<span class='type'>array</span> enumerate<span class='delim'>(</span><span class='type'>int</span> n<span class='delim'>,</span> <span class='type'>mixed</span> step<span class='delim'>,</span> <span class='type'>mixed</span> start<span class='delim'>,</span> <span class='type'>function</span> operator<span class='delim'>)</span>
<span class='delim'>{</span>
  <span class='type'>array</span> res <span class='delim'>=</span> allocate<span class='delim'>(</span>n<span class='delim'>)</span><span class='delim'>;</span>
  <span class='lang'>for</span> <span class='delim'>(</span><span class='type'>int</span> i<span class='delim'>=</span>0<span class='delim'>;</span> i <span class='delim'><</span> n<span class='delim'>;</span> i++<span class='delim'>)</span>
  <span class='delim'>{</span>
    res<span class='delim'>[</span>i<span class='delim'>]</span> <span class='delim'>=</span> start<span class='delim'>;</span>
    start <span class='delim'>=</span> operator<span class='delim'>(</span>start<span class='delim'>,</span> step<span class='delim'>)</span><span class='delim'>;</span>
  <span class='delim'>}</span>
  <span class='lang'>return</span> res<span class='delim'>;</span>
<span class='delim'>}</span>
See also

map(), foreach()


Methodequal

intequal(mixeda, mixedb)

Description

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

For all types but arrays, multisets and mappings, this operation is the same as doing a == b. For arrays, mappings and multisets however, their contents are checked recursively, and if all their contents are the same and in the same place, they are considered equal.

See also

copy_value()


Methoderrno

interrno()

Description

This function returns the system error from the last file operation.

Note

Note that you should normally use Stdio.File->errno() instead.

See also

Stdio.File->errno(), strerror()


Methoderror

voiderror(sprintf_formatf, sprintf_args ... args)

Description

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


Methodexece

intexece(stringfile, array(string) args)
intexece(stringfile, array(string) args, mapping(string:string) env)

Description

This function transforms the Pike process into a process running the program specified in the argument file with the arguments args.

If the mapping env is present, it will completely replace all environment variables before the new program is executed.

Returns

This function only returns if something went wrong during exece(2), and in that case it returns 0 (zero).

Note

The Pike driver _dies_ when this function is called. You must either use fork() or Process.create_process() if you wish to execute a program and still run the Pike runtime.

This function is not available on all platforms.

See also

Process.create_process(), fork(), Stdio.File->pipe()


Methodexit

voidexit(intreturncode, void|stringfmt, mixed ... extra)

Description

Exit the whole Pike program with the given returncode.

Using exit() with any other value than 0 (zero) indicates that something went wrong during execution. See your system manuals for more information about return codes.

The arguments after the returncode will be used for a call to werror to output a message on stderr.

See also

_exit()


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


Methodexplode_path

array(string) explode_path(stringp)

Description

Split a path p into its components.

This function divides a path into its components. This might seem like it could be done by dividing the string on <tt>"/"</tt>, but that will not work on some operating systems. To turn the components back into a path again, use combine_path().


Methodfile_stat

Stdio.Statfile_stat(stringpath, void|boolsymlink)

Description

Stat a file.

If the argument symlink is 1 symlinks will not be followed.

Returns

If the path specified by path doesn't exist 0 (zero) will be returned.

Otherwise an object describing the properties of path will be returned.

Note

In Pike 7.0 and earlier this function returned an array with 7 elements. The old behaviour can be simulated with the following function:

<span class='type'>array</span><span class='delim'>(</span><span class='type'>int</span><span class='delim'>)</span> file_stat<span class='delim'>(</span><span class='type'>string</span> path<span class='delim'>,</span> <span class='type'>void</span><span class='delim'>|</span><span class='type'>int</span><span class='delim'>(</span>0..1<span class='delim'>)</span> symlink<span class='delim'>)</span>
<span class='delim'>{</span>
  File<span class='delim'>.</span>Stat st <span class='delim'>=</span> predef::file_stat<span class='delim'>(</span>path<span class='delim'>,</span> symlink<span class='delim'>)</span><span class='delim'>;</span>
  <span class='lang'>if</span> <span class='delim'>(</span><span class='delim'>!</span>st<span class='delim'>)</span> <span class='lang'>return</span> 0<span class='delim'>;</span>
  <span class='lang'>return</span> <span class='delim'>(</span><span class='type'>array</span><span class='delim'>(</span><span class='type'>int</span><span class='delim'>)</span><span class='delim'>)</span>st<span class='delim'>;</span>
<span class='delim'>}</span>
See also

Stdio.Stat, Stdio.File->stat()


Methodfile_truncate

intfile_truncate(stringfile, intlength)

Description

Truncates the file file to the length specified in length.

Returns

Returns 1 if ok, 0 if failed.


Methodfilesystem_stat

mapping(string:int) filesystem_stat(stringpath)

Description

Returns a mapping describing the properties of the filesystem containing the path specified by path.

Returns

If a filesystem cannot be determined 0 (zero) will be returned.

Otherwise a mapping(string:int) with the following fields will be returned:

"blocksize" : int

Size in bytes of the filesystem blocks.

"blocks" : int

Size of the entire filesystem in blocks.

"bfree" : int

Number of free blocks in the filesystem.

"bavail" : int

Number of available blocks in the filesystem. This is usually somewhat less than the "bfree" value, and can usually be adjusted with eg tunefs(1M).

"files" : int

Total number of files (aka inodes) allowed by this filesystem.

"ffree" : int

Number of free files in the filesystem.

"favail" : int

Number of available files in the filesystem. This is usually the same as the "ffree" value, and can usually be adjusted with eg tunefs(1M).

"fsname" : string

Name assigned to the filesystem. This item is not available on all systems.

"fstype" : string

Type of filesystem (eg "nfs"). This item is not available on all systems.

Note

Please note that not all members are present on all OSs.

See also

file_stat()


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


Methodfloatp

intfloatp(mixedarg)

Description

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

See also

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


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


Methodfork

objectfork()

Description

Fork the process in two.

Fork splits the process in two, and for the parent it returns a pid object for the child. Refer to your Unix manual for further details.

Note

This function can cause endless bugs if used without proper care.

This function is disabled when using threads.

This function is not available on all platforms.

The most common use for fork is to start sub programs, which is better done with Process.create_process().

See also

Process.create_process()


Methodfunction_name

stringfunction_name(function(:void)|programf)

Description

Return the name of the function or program f.

If f is a global function defined in the runtime 0 (zero) will be returned.

See also

function_object()


Methodfunction_object

objectfunction_object(function(:void) f)

Description

Return the object the function f is in.

If f is a global function defined in the runtime 0 (zero) will be returned.

Zero will also be returned if f is a constant in the parent class. In that case function_program() can be used to get the parent program.

See also

function_name(), function_program()


Methodfunction_program

programfunction_program(function(:void)|programf)

Description

Return the program the function f is in.

If f is a global function defined in the runtime 0 (zero) will be returned.

See also

function_name(), function_object()


Methodfunctionp

intfunctionp(mixedarg)

Description

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

See also

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


Methodgc

intgc(mapping|voidquick)

Description

Force garbage collection.

Parameter quick

Perform a quick garbage collection on just this value, which must have been made weak by set_weak_flag(). All values that only have a single reference from quick will then be freed.

When quick hasn't been specified or is UNDEFINED, this function checks all the memory for cyclic structures such as arrays containing themselves and frees them if appropriate. It also frees up destructed objects and things with only weak references.

Normally there is no need to call this function since Pike will call it by itself every now and then. (Pike will try to predict when 20% of all arrays/object/programs in memory is 'garbage' and call this routine then.)

Returns

The amount of garbage is returned. This is the number of arrays, mappings, multisets, objects and programs that had no nonweak external references during the garbage collection. It's normally the same as the number of freed things, but there might be some difference since destroy() functions are called during freeing, which can cause more things to be freed or allocated.

See also

Pike.gc_parameters, Debug.gc_status


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_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_dir

array(string) get_dir(void|stringdirname)

Description

Returns an array of all filenames in the directory dirname, or 0 (zero) if the directory does not exist. When no dirname is given, current work directory is used.

See also

mkdir(), cd()


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)

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


Methodget_profiling_info

array(int|mapping(string:array(int))) get_profiling_info(programprog)

Description

Get profiling information.

Returns

Returns an array with two elements.

Array
intnum_clones

The first element is the number of times the program prog has been instantiated.

mapping(string:array(int)) fun_prof_info

The second element is mapping from function name to an array with three elements.

Array
intnum_calls

The first element is the number of times the function has been called.

inttotal_time

The second element is the total time (in milliseconds) spent executing this function, and any functions called from it.

intself_time

The third element is the time (in milliseconds) actually spent in this function so far.

Note

This function is only available if the runtime was compiled with the option --with-profiling.


Methodget_weak_flag

intget_weak_flag(array|mapping|multisetm)

Description

Returns the weak flag settings for m. It's a combination of Pike.WEAK_INDICES and Pike.WEAK_VALUES.


Methodgetcwd

stringgetcwd()

Description

Returns the current working directory.

See also

cd()


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)
boolglob(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 true, or keeps a string, if any of the given patterns match

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


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 7.5. If you want a hash that is compatible with Pike 7.4 and earlier, use 7.4::hash(). 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 7.0::hash().

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(), 7.4::hash(), 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(), 7.4::hash()


Methodhash_7_4

__deprecated__inthash_7_4(strings)
__deprecated__inthash_7_4(strings, intmax)

Deprecated

Replaced by 7.4::hash.

See also

7.4::hash(), hash()


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

hash(), lfun::__hash()


Methodindices

arrayindices(string|array|mapping|multiset|objectx)

Description

Return an array of all valid indices for the value x.

For strings and arrays this is simply an array of ascending numbers.

For mappings and multisets, the array might contain any value.

For objects which define lfun::_indices() that return value is used.

For other objects an array with all non-protected symbols is returned.

See also

values(), types(), lfun::_indices()


Methodintp

intintp(mixedarg)

Description

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

See also

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


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.


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

"timezone" : int

Offset from UTC, including daylight savings 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 savings time.

See also

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


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_delete

mixedm_delete(object|mappingmap, 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 the entry with index index will be removed from map destructively.

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

Returns

The value that was removed will be returned.

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.

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


Methodmappingp

intmappingp(mixedarg)

Description

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

See also

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


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


Methodmkdir

intmkdir(stringdirname, void|intmode)

Description

Create a directory.

If mode is specified, it's will be used for the new directory after being &'ed with the current umask (on OS'es that support this).

Returns

Returns 0 (zero) on failure, 1 otherwise.

See also

rm(), cd(), Stdio.mkdirhier()


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" : bool

Is daylight savings time.

"timezone" : int

The timezone offset from UTC in seconds. If left out, 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

On some operating systems (notably AIX and Win32), dates before 00:00:00 UTC, Jan 1, 1970 are not supported.

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

See also

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


Methodmultisetp

intmultisetp(mixedarg)

Description

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

See also

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


Methodmv

intmv(stringfrom, stringto)

Description

Rename or move a file or directory.

If the destination already exists, it will be replaced. Replacement often only works if to is of the same type as from, i.e. a file can only be replaced by another file and so on. Also, a directory will commonly be replaced only if it's empty.

On some OSs this function can't move directories, only rename them.

Returns

Returns 0 (zero) on failure, 1 otherwise. Call errno() to get more error info on failure.

See also

rm()


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


Methodnormalize_path

stringnormalize_path(stringpath)

Description

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


Methodobject_program

program|function(:void) object_program(mixedo)

Description

Return the program from which o was instantiated. If the object was instantiated from a class using parent references the generating function will be returned.

If o is not an object or has been destructed 0 (zero) will be returned.


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


Methodprogramp

intprogramp(mixedarg)

Description

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

See also

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


Methodquery_num_arg

intquery_num_arg()

Description

Returns the number of arguments given when the previous function was called.

This is useful for functions that take a variable number of arguments.

See also

call_function()


Methodrandom

arrayrandom(mappingm)

Description

Returns a random index-value pair from the mapping.


Methodrandom

floatrandom(floatmax)

Description

This function returns a random number in the range 0 .. max.

See also

random_seed()


Methodrandom

intrandom(intmax)

Description

This function returns a random number in the range 0 .. max-1.

See also

random_seed()


Methodrandom

mixedrandom(objecto)

Description

If random is called with an object, lfun::random will be called in the object.

See also

lfun::_random()


Methodrandom

mixedrandom(array|multisetx)

Description

Returns a random element from x.


Methodrandom_seed

voidrandom_seed(intseed)

Description

This function sets the initial value for the random generator.

See also

random()


Methodrandom_string

stringrandom_string(intlen)

Description

Returns a string of random characters 0-255 with the length len.


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

Description

Reverses a string, array or int.

Parameter s

String to reverse.

Parameter a

Array to reverse.

Parameter i

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

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.

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

See also

sscanf()


Methodrm

intrm(stringf)

Description

Remove a file or directory.

Returns

Returns 0 (zero) on failure, 1 otherwise.

See also

mkdir(), Stdio.recursive_rm()


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<span class='delim'>(</span>index<span class='delim'>,</span> <span class='lang'>lambda</span><span class='delim'>(</span><span class='type'>mixed</span> x<span class='delim'>)</span> <span class='delim'>{</span> <span class='lang'>return</span> data<span class='delim'>[</span>x<span class='delim'>]</span><span class='delim'>;</span> <span class='delim'>}</span><span class='delim'>)</span>

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)
intsearch(arrayhaystack, mixedneedle, int|voidstart)
mixedsearch(mappinghaystack, mixedneedle, mixed|voidstart)
mixedsearch(objecthaystack, mixedneedle, mixed|voidstart)

Description

Search for needle in haystack. Return the position of needle in haystack or -1 if not found.

If the optional argument start is present search is started at this position.

haystack can have any of the following types:
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. If needle isn't present in the mapping, zero is returned, and zero_type() will return 1 for this zero.

object

When haystack is an object implementing lfun::_search(), the result of calling lfun::_search() with needle 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 (and will thus evaluate to false), and a zero with zero_type 1 will be returned.

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

intsizeof(stringarg)
intsizeof(arrayarg)
intsizeof(mappingarg)
intsizeof(multisetarg)
intsizeof(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 program 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 size. Breaks between words (possibly skipping or adding spaces). Can not be used together with '/'.

'/'

Column mode with rough line break (break at exactly field size 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.

'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
<span class='ns'>Pike</span> v7<span class='delim'>.</span>8 release 263 running Hilfe v3<span class='delim'>.</span>5 <span class='delim'>(</span>Incremental <span class='ns'>Pike</span> Frontend<span class='delim'>)</span>
<span class='delim'>></span> sprintf<span class='delim'>(</span><span class='string'>"The unicode character %c has character code %04X."</span><span class='delim'>,</span> <span class='string'>'A'</span><span class='delim'>,</span> <span class='string'>'A'</span><span class='delim'>)</span><span class='delim'>;</span>
<span class='delim'>(</span>1<span class='delim'>)</span> Result<span class='delim'>:</span> <span class='string'>"The unicode character A has character code 0041."</span>
<span class='delim'>></span> sprintf<span class='delim'>(</span><span class='string'>"#%@02X is the HTML code for purple."</span><span class='delim'>,</span> <span class='ns'>Image</span><span class='delim'>.</span>Color<span class='delim'>.</span>purple->rgb<span class='delim'>(</span><span class='delim'>)</span><span class='delim'>)</span><span class='delim'>;</span>
<span class='delim'>(</span>2<span class='delim'>)</span> Result<span class='delim'>:</span> <span class='string'>"#A020F0 is the HTML code for purple."</span>
<span class='delim'>></span> <span class='type'>int</span> n<span class='delim'>=</span>4711<span class='delim'>;</span>
<span class='delim'>></span> sprintf<span class='delim'>(</span><span class='string'>"%d = hexadecimal %x = octal %o = %b binary"</span><span class='delim'>,</span> n<span class='delim'>,</span> n<span class='delim'>,</span> n<span class='delim'>,</span> n<span class='delim'>)</span><span class='delim'>;</span>
<span class='delim'>(</span>3<span class='delim'>)</span> Result<span class='delim'>:</span> <span class='string'>"4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary"</span>
<span class='delim'>></span> write<span class='delim'>(</span><span class='string'>#"Formatting examples:
Left adjusted  [%-10d]
Centered       [%|10d]
Right adjusted [%10d]
Zero padded    [%010d]
"</span><span class='delim'>,</span> n<span class='delim'>,</span> n<span class='delim'>,</span> n<span class='delim'>,</span> n<span class='delim'>)</span><span class='delim'>;</span>
Formatting examples<span class='delim'>:</span>
Left adjusted  <span class='delim'>[</span>4711      <span class='delim'>]</span>
Centered       <span class='delim'>[</span>   4711   <span class='delim'>]</span>
Right adjusted <span class='delim'>[</span>      4711<span class='delim'>]</span>
Zero padded    <span class='delim'>[</span>0000004711<span class='delim'>]</span>
<span class='delim'>(</span>5<span class='delim'>)</span> Result<span class='delim'>:</span> 142
<span class='type'>int</span> screen_width<span class='delim'>=</span>70<span class='delim'>;</span>
<span class='delim'>></span> write<span class='delim'>(</span><span class='string'>"%-=*s\n"</span><span class='delim'>,</span> screen_width<span class='delim'>,</span>
>> <span class='string'>"This will wordwrap the specified string within the "</span><span class='delim'>+</span>
>> <span class='string'>"specified field size, this is useful say, if you let "</span><span class='delim'>+</span>
>> <span class='string'>"users specify their screen size, then the room "</span><span class='delim'>+</span>
>> <span class='string'>"descriptions will automagically word-wrap as appropriate.\n"</span><span class='delim'>+</span>
>> <span class='string'>"slosh-n's will of course force a new-line when needed.\n"</span><span class='delim'>)</span><span class='delim'>;</span>
This will wordwrap the specified <span class='type'>string</span> within the specified field
size<span class='delim'>,</span> <span class='const'>this</span> is useful say<span class='delim'>,</span> <span class='lang'>if</span> you let users specify their screen size<span class='delim'>,</span>
then the room descriptions will automagically word<span class='delim'>-</span>wrap as
appropriate<span class='delim'>.</span>
slosh<span class='delim'>-</span>n<span class='string'>'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'</span>words<span class='string'>',\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        '</span>words<span class='string'>',         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'</span>words<span class='string'>',\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
'</span>words<span class='string'>',         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='</span><span class='delim'>%</span>s<span class='string'>'%}>\n", (array)sample);
<td valign='</span>middle<span class='string'>' align='</span>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 an opcode, 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 can contain strings separated by special matching directives like %d, %s%c and %f. Every such directive corresponds to one of the lvalues, in order they are listed. An lvalue is the name of a variable, a name of a local variable, an index in 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" fot 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


Methodstrerror

stringstrerror(interrno)

Description

This function returns a description of an error code. The error code is usually obtained from eg Stdio.File->errno().

Note

On some platforms the string returned can be somewhat nondescriptive.


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

string(8bit)string_to_utf8(strings)
string(8bit)string_to_utf8(strings, intextended)

Description

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

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.

If extended is 1 then characters outside the valid ranges are accepted too and encoded using the same algorithm. Such encoded characters are however not UTF-8 compliant.

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


Methodstrlen

intstrlen(string|multiset|array|mapping|objectthing)

Description

Alias for sizeof.

Deprecated

Replaced by sizeof.


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


Methodthis_object

objectthis_object(void|intlevel)

Description

Returns the object we are currently evaluating in.

level might 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 latest done by the pike process is returned again. That's 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 preciely than one second. It return how many seconds has passed since t. The precision of this function varies from system to system.

See also

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


Methodtrace

inttrace(intlevel, void|stringfacility, void|intall_threads)

Description

This function changes the trace level for the subsystem identified by facility to level. If facility is zero or left out, it changes the global trace level which affects all subsystems.

Enabling tracing causes messages to be printed to stderr. A higher trace level includes the output from all lower levels. The lowest level is zero which disables all trace messages.

See the -t command-line option for more information.

Parameter level

If facility is specified then there is typically only one trace level for it, i.e. it's an on-or-off toggle. The global trace levels, when facility isn't specified, are:

1

Trace calls to Pike functions and garbage collector runs.

2

Trace calls to builtin functions.

3

Trace every interpreted opcode.

4

Also trace the opcode arguments.

Parameter facility

Valid facilities are:

"gc"

Trace the doings of the garbage collector. The setting is never thread local. level has two different meanings:

1..2

Trace the start and end of each gc run.

3..

Additionally show info about the collected garbage, to aid hunting down garbage problems. This currently shows gc'd trampolines. Note that the output can be very bulky and is somewhat low-level technical. Also note that pike currently has to be configured with --with-rtldebug to enable this.

Parameter all_threads

Trace levels are normally thread local, so changes affect only the current thread. To change the level in all threads, pass a nonzero value in this argument.

Returns

The old trace level in the current thread is returned.


Methodtypes

array(type) types(string|array|mapping|multiset|objectx)

Description

Return an array of all valid indices for the value x.

For strings this is simply an array with int

For arrays, mappings and multisets this is simply an array with mixed.

For objects which define lfun::_types() that return value is used.

For other objects an array with type types for all non-protected symbols is returned.

Note

This function was added in Pike 7.9.

See also

indices(), values(), lfun::_types()


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


Methodundefinedp

intundefinedp(mixedarg)

Description

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

See also

zero_type, destructedp, intp


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.

Note

This function did not decode surrogates in Pike 7.2 and earlier.

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(string(8bit)s)
stringutf8_to_string(string(8bit)s, 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()


Methodvalues

arrayvalues(string|array|mapping|multiset|objectx)

Description

Return an array of all possible values from indexing the value x.

For strings an array of int with the ISO10646 codes of the characters in the string is returned.

For a multiset an array filled with ones (1) is returned.

For arrays a single-level copy of x is returned.

For mappings the array may contain any value.

For objects which define lfun::_values() that return value is used.

For other objects an array with the values of all non-protected symbols is returned.

See also

indices(), types(), lfun::_values()


Methodversion

stringversion()

Description

Report the version of Pike. Does the same as

sprintf<span class='delim'>(</span><span class='string'>"Pike v%d.%d release %d"</span><span class='delim'>,</span> <span class='const'>__REAL_VERSION__</span><span class='delim'>,</span>
        <span class='const'>__REAL_MINOR__</span><span class='delim'>,</span> <span class='const'>__REAL_BUILD__</span><span class='delim'>)</span><span class='delim'>;</span>
See also

__VERSION__, __MINOR__, __BUILD__, __REAL_VERSION__, __REAL_MINOR__, __REAL_BUILD__,


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.


Methodzero_type

intzero_type(mixeda)

Description

Return the type of zero.

There are many types of zeros out there, or at least there are two. One is returned by normal functions, and one returned by mapping lookups and find_call_out() when what you looked for wasn't there. The only way to separate these two kinds of zeros is zero_type().

Returns

When doing a find_call_out() or mapping lookup, zero_type() on this value will return 1 if there was no such thing present in the mapping, or if no such call_out could be found.

If the argument to zero_type() is a destructed object or a function in a destructed object, 2 will be returned.

In all other cases zero_type() will return 0 (zero).

See also

find_call_out()

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

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

<span class='type'>program</span> compile<span class='delim'>(</span><span class='type'>mixed</span> ... args<span class='delim'>)</span>
    <span class='delim'>{</span>
      <span class='lang'>return</span> PikeCompiler<span class='delim'>(</span>@args<span class='delim'>)</span>->compile<span class='delim'>(</span><span class='delim'>)</span><span class='delim'>;</span>
    <span class='delim'>}</span>
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


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


InheritReporter

inherit Reporter : Reporter

Description

Implements the Reporter API.

See also

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


Methodresolv

mixedresolv(stringidentifier, stringfilename, object|voidhandler)

Description

Look up identifier in the current context.

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

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

Description

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


Methodcompile

programcompile()

Description

Compile the current source into a program.

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

See also

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


Methodcreate

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

Description

Create a PikeCompiler object for a source string.

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

Parameter source

Source code to compile.

Parameter handler

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

Parameter major
Parameter minor

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

Parameter target

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

Parameter placeholder

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

Note

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

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

Note

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

See also

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


Methodget_compilation_handler

objectget_compilation_handler(intmajor, intminor)

Description

Get compatibility handler for Pike major.minor.

Note

This function is called by change_compiler_compatibility().


Methodget_default_module

mapping(string:mixed)|objectget_default_module()

Description

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

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

Returns
mapping(string:mixed)|object

Constant table to use.

int(0..0)

Use the builtin constant table.

Note

This function is called by change_compiler_compatibility().


Methodhandle_inherit

programhandle_inherit(stringinh)

Description

Look up an inherit inh in the current 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()


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


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, stringfilename, objecthandler)

Description

Resolve the symbol identifier.

The default implementation calls the corresponding function in any active handler, and otherwise falls back to CompilerEnvironment()->resolv() in the parent object.

Class CompilerEnvironment.PikeCompiler.CompilerState

Description

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

Note

Not in use yet!

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 index and 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_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

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 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<span class='delim'>;</span>
    ...
    <span class='lang'>foreach</span><span class='delim'>(</span>iterator<span class='delim'>+</span>0<span class='delim'>;</span> <span class='type'>mixed</span> index<span class='delim'>;</span> <span class='type'>mixed</span> value<span class='delim'>)</span> <span class='delim'>{</span>
      ...
    <span class='delim'>}</span>
Note

Even though this function is sufficient for foreach to advance the iterator, next() is the preferred API. next() has the additional advantage of not being an lfun, so it is possible to advance the iterator by hand.

See also

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

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.


Methodindex

mixedindex()

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


Methodnext

intnext()

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

`+, `+=, `-


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.


Methodvalue

mixedvalue()

Description

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

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.


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.


Methodbasename

stringbasename(stringx)

Description

Returns the last segment of a path.

See also

dirname(), explode_path()


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


Variablecompat_minor

int MasterObject.compat_minor


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


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


Methoddescribe_function

stringdescribe_function(function(:void) f)


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)


Methoddescribe_program

stringdescribe_program(program|function(:void) p)


Methoddirname

stringdirname(stringx)

Description

Returns all but the last segment of a path. Some example inputs and outputs:

ExpressionValue
dirname("/a/b")"/a"
dirname("/a/")"/a"
dirname("/a")"/"
dirname("/")"/"
dirname("")""
See also

basename(), explode_path()


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


Methoderror

voiderror(sprintf_formatf, sprintf_args ... args)

Description

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


Methodexplode_path

array(string) explode_path(stringp)

Description

Split a path p into its components.

This function divides a path into its components. This might seem like it could be done by dividing the string on <tt>"/"</tt>, but that will not work on some operating systems. To turn the components back into a path again, use combine_path().


Methodfc_reverse_lookup

stringfc_reverse_lookup(objectobj)

Description

Returns the path for obj in fc, if it got any.


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


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


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_7_8_master

protected inherit Pike_7_8_master : Pike_7_8_master

Description

Namespaces for compat masters.

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

See also

get_compat_master()


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.


Variableldflags

string MasterObject.ldflags

Description

Flags suitable for use when linking Pike C modules


Methodmaster_read_file

stringmaster_read_file(stringfile)


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)


Methodnormalize_path

stringnormalize_path(stringpath)

Description

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


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.


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


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


Methodstrlen

intstrlen(string|multiset|array|mapping|objectthing)

Description

Alias for sizeof.

Deprecated

Replaced by sizeof.


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.


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.

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

Description

Add a directory to search for modules.

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

See also

remove_module_path()


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


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


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)


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)


Methodresolv_base

mixedresolv_base(stringidentifier, string|voidcurrent_file, object|voidcurrent_handler)


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

Description

Pike 7.6 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.6.

Deprecated

Replaced by predef::MasterObject.

See also

get_compat_master(), master(), predef::MasterObject


Variableenvironment

mapping(string:array(string)) MasterObject.Pike_7_6_master.environment

Description

Mapping containing the environment variables.

The mapping currently has the following structure:

index : array(string)

Note that the index is lower_case()'d on NT.

Array
stringvarname

Variable name with case intact.

stringvalue

Variable value.

Note

This mapping should not be accessed directly; use getenv() and putenv() instead. This mapping is not publicly accessible in pikes newer than 7.6.

Note

This mapping is not compatible with Process.create_process(); use the mapping returned from calling getenv() without arguments instead.

Bugs

This mapping is not the real environment; it is just a copy of the environment made at startup. Pike does attempt to keep track of changes in the mapping and to reflect them in the real environment, but avoid accessing this mapping if at all possible.

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

Deprecated

Replaced by predef::MasterObject.

See also

get_compat_master(), master(), predef::MasterObject


InheritPike_7_6_master

inherit Pike_7_6_master : Pike_7_6_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 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 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 Apple

Class Apple.Keychain

Description

Support for the Apple Keychain format.

This is used for the files in eg /System/Library/Keychains.

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:

<span class='type'>int</span> main<span class='delim'>(</span> <span class='type'>int</span> c<span class='delim'>,</span> <span class='type'>array</span><span class='delim'>(</span><span class='type'>string</span><span class='delim'>)</span> argv <span class='delim'>)</span>
<span class='delim'>{</span>
  <span class='type'>mapping</span> arguments <span class='delim'>=</span> <span class='ns'>Arg</span><span class='delim'>.</span>parse<span class='delim'>(</span>argv<span class='delim'>)</span><span class='delim'>;</span>
  <span class='type'>array</span> files <span class='delim'>=</span> arguments<span class='delim'>[</span><span class='ns'>Arg</span><span class='delim'>.</span>REST<span class='delim'>]</span><span class='delim'>;</span>
  <span class='lang'>if</span><span class='delim'>(</span> arguments->help <span class='delim'>)</span> print_help<span class='delim'>(</span><span class='delim'>)</span><span class='delim'>;</span>
  ...
<span class='delim'>}</span>

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 LowOptions class and then start adding supported arguments:

<span class='type'>class</span> MyArguments <span class='delim'>{</span>
   <span class='lang'>inherit</span> <span class='ns'>Arg</span><span class='delim'>.</span>LowOptions<span class='delim'>;</span>
   Opt verbose <span class='delim'>=</span> NoOpt<span class='delim'>(</span><span class='string'>"-v"</span><span class='delim'>)</span><span class='delim'>|</span>NoOpt<span class='delim'>(</span><span class='string'>"--verbose"</span><span class='delim'>)</span><span class='delim'>;</span>
   Opt help <span class='delim'>=</span> MaybeOpt<span class='delim'>(</span><span class='string'>"--help"</span><span class='delim'>)</span><span class='delim'>;</span>
   Opt output <span class='delim'>=</span> HasOpt<span class='delim'>(</span><span class='string'>"--output"</span><span class='delim'>)</span><span class='delim'>|</span>HasOpt<span class='delim'>(</span><span class='string'>"-o"</span><span class='delim'>)</span><span class='delim'>;</span>
<span class='delim'>}</span><span class='delim'>;</span>

Then, in main:

MyArguments args = MyArguments(argv);

See the documentation for OptLibrary for details about the various Opt classes.


ConstantREST

constant Arg.REST

Description

Constant used by Arg.parse() to indicate the remaining objects.


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         ->  <span class='string'>"foo"</span><span class='delim'>:</span>1
--foo<span class='delim'>=</span>bar     ->  <span class='string'>"foo"</span><span class='delim'>:</span><span class='string'>"bar"</span>
<span class='delim'>-</span>bar          ->  <span class='string'>"b"</span><span class='delim'>:</span>1<span class='delim'>,</span><span class='string'>"a"</span><span class='delim'>:</span>1<span class='delim'>,</span><span class='string'>"r"</span><span class='delim'>:</span>1
<span class='delim'>-</span>bar<span class='delim'>=</span>foo      ->  <span class='string'>"b"</span><span class='delim'>:</span>1<span class='delim'>,</span><span class='string'>"a"</span><span class='delim'>:</span>1<span class='delim'>,</span><span class='string'>"r"</span><span class='delim'>:</span><span class='string'>"foo"</span> <span class='delim'>(</span>?<span class='delim'>)</span>
--foo --bar   ->  <span class='string'>"foo"</span><span class='delim'>:</span>1<span class='delim'>,</span><span class='string'>"bar"</span><span class='delim'>:</span>1
--foo <span class='delim'>-</span> --bar ->  <span class='string'>"foo"</span><span class='delim'>:</span>1
--foo x --bar ->  <span class='string'>"foo"</span><span class='delim'>:</span>1 <span class='delim'>(</span>?<span class='delim'>)</span>
<span class='delim'>-</span>foo          ->  <span class='string'>"f"</span><span class='delim'>:</span>1<span class='delim'>,</span><span class='string'>"o"</span><span class='delim'>:</span>2
<span class='delim'>-</span>x <span class='delim'>-</span>x <span class='delim'>-</span>x      ->  <span class='string'>"x"</span><span class='delim'>:</span>3
Example
<span class='type'>void</span> main<span class='delim'>(</span><span class='type'>int</span> n<span class='delim'>,</span> <span class='type'>array</span> argv<span class='delim'>)</span>
<span class='delim'>{</span>
  <span class='type'>mapping</span> opts <span class='delim'>=</span> <span class='ns'>Arg</span><span class='delim'>.</span>parse<span class='delim'>(</span>argv<span class='delim'>)</span><span class='delim'>;</span>
  argv <span class='delim'>=</span> opts<span class='delim'>[</span><span class='ns'>Arg</span><span class='delim'>.</span>REST<span class='delim'>]</span><span class='delim'>;</span>
  <span class='lang'>if</span><span class='delim'>(</span> opts->help <span class='delim'>)</span> <span class='comment'>/*... */</span>
<span class='delim'>}</span>

Class Arg.LowOptions


Variableapplication

protectedstring Arg.LowOptions.application


Variableargv

protectedarray(string) Arg.LowOptions.argv


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

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.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.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, int|stringprevious)

Description

Should return 1 for set options or a string containing the value of the option. Returning 0 means the option was not set (or matched). To properly chain arguments parsers, return ::get_value(argv, env, previous) instead of 0, unless you want to explicitly stop the chain and not set this option.

Class Arg.Options

Description

The option parser class that contains all the argument objects.


InheritLowOptions

inherit LowOptions : LowOptions


Methodunhandled_argument

protectedbool|stringunhandled_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 Builtin


Method_get_setter

function(mixed_void:void) _get_setter(objecto, stringvarname)

Description

Get a setter for the variable named varname in object o.

Returns

Returns a Setter()->`()() for the variable if it exists, and UNDEFINED otherwise.

See also

object_variablep()


Method_take_over_initial_predefines

mapping(string:mixed) _take_over_initial_predefines()

Class Builtin.Null

Description

This class is used to implement the low-level aspects of Val.Null.

Note

This class should typically not be used directly. Use Val.Null instead.

Note

This class was previously available as Sql.Null. Any such use should be replaced with Val.Null.

Deprecated

Replaced by Val.Null.

See also

Val.Null, Val.null


Methodencode_json

stringencode_json()

Description

Defined for use with Standards.JSON.encode, so that it formats NULL as null.

Class Builtin.Setter

Description

Internal class for implementing setters.

This class is used by _get_setter().

See also

_get_setter()


Method`()

void res = Builtin.Setter()()

Description

Set the variable for the setter to val.

This is the function returned by _get_setter().

Class Builtin.automap_marker

Description

This is an internal class used by __automap__().

It may show up during module dumping or in backtraces and the like.

It should in normal circumstances never be used directly.

See also

__automap__(), map()


Methodcreate

Builtin.automap_markerBuiltin.automap_marker(arrayarr, intdepth)

Parameter arr

Array that __automap__() is to loop over.

Parameter depth

Recursion depth of arr where the loop will be.

Module Bz2

Description

The Bz2 module contains functions to compress and uncompress strings using the same algorithm as the program bzip2. Compressing and decompressing can be done in streaming mode feeding the compress and decompress objects with arbitrarily large pieces of data.

The Bz2 module consists of three classes; Bz2.Deflate, Bz2.Inflate and Bz2.File. Bz2.Deflate is used to compress data and Bz2.Inflate is used to uncompress data. Bz2.File is used to handle Bzip2 files.

Note

Note that this module is only available if libbzip2 was available when Pike was compiled.

Note that although the functions in Inflate and Deflate use the same algorithm as bzip2, they do not use the exact same format, so you can not directly zip files or unzip zip-files using those functions. That is why there exists a third class for files.


InheritBz2

inherit "___Bz2" : Bz2

Class Bz2.Deflate

Description

Bz2.Deflate is a builtin program written in C. It interfaces the packing routines in the bzlib library.

Note

This program is only available if libz was available and found when Pike was compiled.

See also

Bz2.Inflate()


Methodcreate

Bz2.DeflateBz2.Deflate(int(1..9)|voidblock_size)

Description

If given, block_size should be a number from 1 to 9 indicating the block size used when doing compression. The actual block size will be a 100000 times this number. Low numbers are considered 'fast', higher numbers are considered 'slow' but give better packing. The parameter is set to 9 if it is omitted.

This function can also be used to re-initialize a Bz2.Deflate object so it can be re-used.


Methoddeflate

stringdeflate(stringdata, int(0..2)|voidflush_mode)

Description

This function performs bzip2 style compression on a string data and returns the packed data. Streaming can be done by calling this function several times and concatenating the returned data.

The optional argument flush_mode should be one of the following:

Bz2.BZ_RUN

Runs Bz2.Deflate->feed()

Bz2.BZ_FLUSH

Runs Bz2.Deflate->read()

Bz2.BZ_FINISH

Runs Bz2.Deflate->finish()

See also

Bz2.Inflate->inflate()


Methodfeed

voidfeed(stringdata)

Description

This function feeds the data to the internal buffers of the Deflate object. All data is buffered until a read or a finish is done.

See also

Bz2.Deflate->read()Bz2.Deflate->finish()


Methodfinish

stringfinish(stringdata)

Description

This method feeds the data to the internal buffers of the Deflate object. Then it compresses all buffered data adds a end of data marker ot it, returns the compressed data as a string, and reinitializes the deflate object.

See also

Bz2.Deflate->feed()Bz2.Deflate->read()


Methodread

stringread(stringdata)

Description

This function feeds the data to the internal buffers of the Deflate object. Then it compresses all buffered data and returns the compressed data as a string

See also

Bz2.Deflate->feed()Bz2.Deflate->finish()

Class Bz2.File

Description

Low-level implementation of read/write support for Bzip2 files

Note

This class is currently not available on Windows.


Methodclose

boolclose()

Description

closes the file


Methodcreate

Bz2.FileBz2.File()
Bz2.FileBz2.File(stringfilename, void|stringmode)

Description

Creates a Bz2.File object


Methodeof

booleof()

Returns

1 if EOF has been reached, 0 otherwise


InheritFile

inherit Bz2::File : File


Methodline_iterator

String.SplitIterator|Stdio.LineIteratorline_iterator(int|voidtrim)

Description

Returns an iterator that will loop over the lines in this file. If trim is true, all '\r' characters will be removed from the input.


Methodopen

boolopen(stringfile, void|stringmode)

Description

Opens a file for I/O.

Parameter file

The name of the file to be opened

Parameter mode

Mode for the file operations. Can be either "r" (read) or "w". Read is default.


Methodread

stringread(intlen)

Description

Reads len (uncompressed) bytes from the file. If len is omitted the whole file is read. If read is unsuccessful, 0 is returned.


Methodread_function

function(:string) read_function(intnbytes)

Description

Returns a function that when called will call read with nbytes as argument. Can be used to get various callback functions, eg for the fourth argument to String.SplitIterator.


Methodread_open

boolread_open(stringfile)

Description

Opens a file for reading.

Parameter file

The name of the file to be opened


Methodwrite

intwrite(stringdata)

Description

Writes the data to the file.

Returns

the number of bytes written to the file.


Methodwrite_open

boolwrite_open(stringfile)

Description

Opens a file for writing.

Parameter file

The name of the file to be opened

Class Bz2.Inflate

Description

Bz2.Inflate is a builtin program written in C. It interfaces the unpacking routines in the libz library.

Note

This program is only available if bzlib was available and found when Pike was compiled.

See also

Deflate


Methodcreate

Bz2.InflateBz2.Inflate()


Methodinflate

stringinflate(stringdata)

Description

This function performs bzip2 style decompression. It can do decompression with arbitrarily large pieces of data. When fed with data, it decompresses as much as it can and buffers the rest.

Example

while(..){ foo = compressed_data[i..i+9]; uncompressed_concatenated_data += inflate_object->inflate(foo); i = i+10; }

See also

Bz2.Deflate->deflate()

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::destroy 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 Calendar

Description

Time and day system

Q:  I need to parse some date in a non-strict format, like
   the one in the HTTP or mail protocol, or from a user web
   form.

A:  Calendar.dwim_day, or Calendar.dwim_time, should solve
   your problem. 

     > Calendar.dwim_day("1/2/3");
     Result: Day(Thu 2 Jan 2003)
     > Calendar.dwim_day("1 aug 2001");
     Result: Day(Wed 1 Aug 2001)

     > Calendar.dwim_time("1 aug 2001 23:14 EDT");
     Result: Minute(Wed 1 Aug 2001 23:14 EDT)
     > Calendar.dwim_time("2001 2 3 23:14:23 UTC+9");
     Result: Second(Sat 3 Feb 2001 23:14:23 UTC+9)

   If it doesn't, and it should, report the problem to me
   and I'll see what I can do. Note that the timezones
   are rather unpredictable - if it doesn't get it, you
   will get the default (local) timezone.

-------------------------------------------------------------------------  

Q:  The dwim_* functions are too slow. 

A:  They are not written to be fast, but to do good guessing.

   If you know the format, you should use the Calendar.parse
   function:

     > Calendar.parse("%Y-%M-%D %h:%m","2040-11-08 2:46");
     Result: Minute(Thu 8 Nov 2040 2:46 CET)
     > Calendar.parse("%Y w%W %e %h:%m %p %z","1913 w4 monday 2:14 pm CET");
     Result: Minute(Mon 20 Jan 1913 14:14 CET)

   These are the format characters:
    %Y absolute year 
    %y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069)
    %M month (number, name or short name) (needs %y)
    %W week (needs %y)
    %D date (needs %y, %m)
    %d short date (20000304, 000304)
    %a day (needs %y)
    %e weekday (needs %y, %w)
    %h hour (needs %d, %D or %W)
    %m minute (needs %h)
    %s second (needs %m)
    %f fraction of a second (needs %s)
    %t short time (205314, 2053)
    %z zone
    %p "am" or "pm"
    %n empty string (to be put at the end of formats)

   and you can also use "%*[....]" to skip some characters,
   as in sscanf().

   If this is too slow, there is currently no solution in Pike
   to do this faster, except possibly sscanf and manual calculations/
   time object creation.

-------------------------------------------------------------------------  

Q:  How do I get from unix time (time(2)) to a unit and back?

A:  Calendar.Unit("unix",time())
   unit->unix_time()

     > Calendar.Day("unix",987654321);
     Result: Day(Thu 19 Apr 2001)
     > Calendar.Second("unix",987654321);  
     Result: Second(Thu 19 Apr 2001 6:25:21 CEST)

     > Calendar.Day()->unix_time();   
     Result: 979081200

   Note that you will get the time for the start of the unit.
   Unix time is timezone independant.

   The day-of-time units (seconds, hours, etc) uses this
   as internal representation of time.

-------------------------------------------------------------------------  

Q:  I'm a mad astronomer, how do I do the same conversions with
   julian day numbers?

A:  Julian day numbers are used as the internal representation
   for the day, and for most other bigger-then-time-of-day calculations.

     > Calendar.Day("julian",2454545);  
     Result: Day(Wed 19 Mar 2008)
     > Calendar.Second("julian",2430122.0);
     Result: Second(Tue 6 May 1941 13:00:00 CET)

   Julian day numbers from day units and bigger are integers,
   representing the new julian number on that day. Julian day
   numbers from time of day units are represented in floats.

     > Calendar.Day()->julian_day();
     Result: 2451920
     > Calendar.Second()->julian_day();
     Result: 2451919.949595

   Watch out for the float precision, though. If you haven't
   compiled your Pike with --with-double-precision, this gives
   you awkwardly low precision - 6 hours.

-------------------------------------------------------------------------  

Q:  How do I convert a "Second(Sat 3 Feb 2001 23:14:23 UTC+9)" object
   to my timezone?

A:  ->set_timezone(your timezone)

     > Calendar.dwim_time("2001 2 3 23:14:23 PST")
     	  ->set_timezone("Europe/Stockholm");
     Result: Second(Sun 4 Feb 2001 8:14:23 CET)

     > Calendar.dwim_time("2001 2 3 23:14:23 PST")
     	  ->set_timezone("locale");
     Result: Second(Sun 4 Feb 2001 8:14:23 CET)

-------------------------------------------------------------------------  

Q:  How do I print my time object?

A:  ->format_xxx();

   You can either print it unit-sensitive,

     > Calendar.dwim_time("2001 2 3 23:14:23 PST")->format_nice();
     Result: "3 Feb 2001 23:14:23"
     > Calendar.Week()->format_nice();                            
     Result: "w2 2001"
     > Calendar.now()->format_nicez();
     Result: "10 Jan 10:51:15.489603 CET"

   or in a format not depending on the unit,

     > Calendar.Week()->format_ymd();            
     Result: "2001-01-08"
     > Calendar.Day()->format_time();
     Result: "2001-01-10 00:00:00"

   This is all the formats:

   format_ext_time       "Wednesday, 10 January 2001 10:49:57"
   format_ext_time_short "Wed, 10 Jan 2001 10:49:57 CET"
   format_ext_ymd        "Wednesday, 10 January 2001"
   format_iso_time       "2001-01-10 (Jan) -W02-3 (Wed) 10:49:57 UTC+1"
   format_iso_ymd        "2001-01-10 (Jan) -W02-3 (Wed)"
   format_mod            "10:49"
   format_month          "2001-01"
   format_month_short    "200101"
   format_mtime          "2001-01-10 10:49"
   format_time           "2001-01-10 10:49:57"
   format_time_short     "20010110 10:49:57"
   format_time_xshort    "010110 10:49:57"
   format_tod            "10:49:57"
   format_tod_short      "104957"
   format_todz           "10:49:57 CET"
   format_todz_iso       "10:49:57 UTC+1"
   format_week           "2001-w2"
   format_week_short     "2001w2"
   format_iso_week       "2001-W02"
   format_iso_week_short "200102"
   format_xtime          "2001-01-10 10:49:57.539198"
   format_xtod           "10:49:57.539658"
   format_ymd            "2001-01-10"
   format_ymd_short      "20010110"
   format_ymd_xshort     "010110"

   format_ctime          "Wed Jan 10 10:49:57 2001\n"
   format_smtp           "Wed, 10 Jan 2001 10:49:57 +0100"
   format_http           "Wed, 10 Jan 2001 09:49:57 GMT"

-------------------------------------------------------------------------  

Q:  How old am I?

A:  First, you need to create the time period representing your age.

     > object t=Calendar.dwim_time("1638 dec 23 7:02 pm")
     	  ->distance(Calendar.now());
     Result: Fraction(Thu 23 Dec 1638 19:02:00.000000 LMT - 
     		       Wed 10 Jan 2001 10:53:33.032856 CET)

  Now, you can ask for instance how many years this is:

     > t->how_many(Calendar.Year);
     Result: 362

  Or how many 17 seconds it is:

     > t->how_many(Calendar.Second()*17);
     Result: 672068344

  A note here is to use ->distance, and not ->range, since that
  will include the destination unit too:

    > Calendar.dwim_day("00-01-02")->range(Calendar.Week(2000,2))
       ->how_many(Calendar.Day());
    Result: 15
    > Calendar.dwim_day("00-01-02")->distance(Calendar.Week(2000,2))
       ->how_many(Calendar.Day());
    Result: 8

-------------------------------------------------------------------------  

Q:  In 983112378 days, what weekday will it be?

A:  (this weekday + 983112378) % 7   ;) 

   or take this day, add the number, and ask the object:

     > (Calendar.Day()+983112378)->week_day_name();
     Result: "Saturday"

   "+int" will add this number of the unit to the unit;
   this means that Calendar.Year()+2 will move two years
   forward, but Calendar.now()+2 will not move at all 
   - since now has zero size.

   To add a number of another time unit, simply do that:

     > Calendar.Day()+3*Calendar.Year();  
     Result: Day(Sat 10 Jan 2004)
     > Calendar.Day()+3*Calendar.Minute()*134;
     Result: Minute(Wed 10 Jan 2001 6:42 CET - Thu 11 Jan 2001 6:42 CET)

   The last result here is because the resulting time still will
   be as long as the first.

-------------------------------------------------------------------------  

Q:  Are there other calendars?

A:  Yes. 

   Calendar.Day is really a shortcut to Calendar.ISO.Day;
   this is tuned in the localization.h file.

   There is currently:

   Gregorian
	This is the base module for Julian style calendars;
	despite the name. Most calendars of today are in sync
	with the Gregorian calendar.
   ISO
	This inherits the Gregorian calendar to tweak it to
	conform to the ISO standards. Most affected are weeks, 
	which starts on Monday in the ISO calendar.
	This is also the default calendar.
   Discordian
	The Discordian calendar as described in Principia Discordia
	is in sync with the Gregorian calendar (although some claim
	that it should be the Julian - I go with what I can read 
	from my Principia Discordia). The module inherits and 
	tweaks the Gregorian module.
   Coptic
	The Coptic calendar is by some sources ("St. Marks'
	Coptic Orthodox Church" web pages) is for now on in sync with
	the Gregorian Calendar, so this module too inherits
	and tweaks the Gregorian module. It needs to be 
	adjusted for historical use.
   Julian
	This is the Julian calendar, with the small changes
	to the Gregorian calendar (leap years).
   Badi (Baha'i)
       The Badi calendar used by the Baha'i religion is based on the
       solar year. For the time being it is in sync with the Gregorian
       calendar.

   Islamic
	This is the Islamic calendar, using the 'Calendrical 
	Calculations' rules for new moon. It is based
	directly on the YMD module.
   Stardate
	This is the (TNG) Stardate calendar, which consists
	of one time unit only, the Tick (1000 Tick is one earth year). 
	It is based directly on TimeRanges.

-------------------------------------------------------------------------  

Q:  How do I convert between the calendars?

A:  You give the unit to be converted to the constructor of 
   the unit you want it to be.

   > Calendar.Coptic.Day(Calendar.dwim_day("14 feb 1983"));
   Result: Day(Mon 7 Ams 1699)
   > Calendar.Islamic.Minute(Calendar.dwim_day("14 feb 1983"));
   Result: Minute(aha 29 Rebîul-âchir 1403 AH 13:00 CET - 
   		   ith 1 Djumâda'l-ûla 1403 AH 13:00 CET)
   > Calendar.Day(Calendar.Stardate.Tick(4711));
   Result: Day(Sat 17 Sep 2327 0:00 sharp)

-------------------------------------------------------------------------  

Q:  Isn't there a <my country> calendar?

A:  <your country> uses the ISO calendar, with just different
   names for the months. Language is a parameter to the
   calendar units, as well as the timezone.

   You set the language by using ->set_language(yourlanguage).

     > t->set_language("pt")->format_ext_ymd();
     Result: "Quarta-feira, 10 Janeiro 2001"
     > t->set_language("roman")->format_ext_ymd();    
     Result: "Mercurii dies, X Ianuarius MMDCCLIII ab urbe condita"

   Note that all languages aren't supported. If you miss your
   favourite language or I got it all wrong (or have some time over
   to help me out), look in the Language.pmod file and send me an
   update.

   Or send me a list of the weekdays and month names
   (please start with Monday and January).

   Currently, these languages are supported:

     name        code    
     -------------------------------
     ISO                 (default, aka English)

     Afrikaans   af afr   (South Africa),
     Austrian    de_AT
     Basque      eu eus   (Spain)
     Catalan     ca cat   (Catalonia)
     Croatian    hr hrv
     Danish      da dan
     Dutch       nl nld
     English     en eng
     Estonian    et est
     Faroese     fo fao
     Finnish     fi fin
     French      fr fra
     Galician    gl glg   (Spain)
     German      de deu
     Greenlandic kl kal
     Hungarian   hu hun
     Icelandic   is isl
     Irish       ga gle   (Gaelic)
     Italian     it ita
     Latvian     lv lav
     Lithuanian  lt lit
     Norwegian   no nor
     Persian     fa fas   (Iran)
     Polish      pl pol
     Portugese   pt por
     Romanian    ro ron
     Serbian     sr srp   (Yugoslavia)
     Slovenian   sl slv
     Spanish     es spa
     Swedish     sv swe
     Turkish     tr 
     Welsh       cy cym

     Latin       la lat
     Roman              (Roman Latin)

-------------------------------------------------------------------------  

Q:  Isn't there a <whatever> calendar?

A:  Not if it isn't listed above. I'll appreciate any
   implementation help if you happen to have the time over
   to implement some calendar.

   I know I miss these:

     Chinese
     Jewish or Hebreic
     Maya      

   Of these, the two first are based on astronomical events,
   which I haven't had the time to look into yet, but the
   last - Maya - is totally numeric.

-------------------------------------------------------------------------  

Q:  I don't like that weeks starts on Mondays.
   Every school kids knows that weeks start on Sundays.

A:  According to the ISO 8601 standard, weeks start on mondays.

   If you don't like it, edit the Calendar.pmod/localization.h
   file to use the Gregorian calendar instead of the ISO.

   Or use Calendar.Gregorian.Day, etc.

-------------------------------------------------------------------------  

Q:  How do I find out which days are red in a specific region?

A:  Events.<region> 

   - contains the events for the region, as a SuperEvent. 
   You can ask this object to filter out the holidays,

      Events.se->holidays();

   which will be a superevent containing only holidays.

   To use this information, you can for instance use ->scan,
   here in an example to see what red days there are in Sweden
   the current month:

     > Calendar.Events.se->filter_flag("h")->scan(Calendar.Month());
     Result: ({ /* 6 elements */
    		   Day(Sun 7 Jan 2001),
    		   Day(Sun 14 Jan 2001),
    		   Day(Sun 21 Jan 2001),
    		   Day(Sun 28 Jan 2001),
    		   Day(Sat 6 Jan 2001),
    		   Day(Mon 1 Jan 2001)
    	       })

-------------------------------------------------------------------------  

Q:  How accurate are the events information?

A:  For some regions, very. For most region, not very.

   The first reason is lack of information of this kind on
   the web, especially sorted into useful rules (like "the
   third monday after 23 dec", not "8 jan").

   The second reason is lack of time and interest to do
   research, which is a rather tedious job.

   If you want to help, the check your region in the
   events/regions file and send us <pike@roxen.com> a patch.

   Don't send me "the x region is all wrong!" mails without
   telling me how it should look.

-------------------------------------------------------------------------  

Q:  My timezone says it's DST. It's wrong.

A:  No it isn't.  But:

   o The local timezone detector failed to find your timezone by
     itself, or found the wrong timezone.

   o or you use the wrong timezone.

   To make sure the right timezone is used, use the standard
   timezone names. Those aren't "CET" or "PST", but 
   "Europe/Amsterdam" or "America/Dawson".

   You can tune the default timezone by editing
   Calendar.pmod/localization.h.

   OR this may be in the future and you have a changed DST
   rule and uses an old Pike. Then you can either download
   a new version or download new timezone data files from 
   the ftp address below (if the internet still is there).
FIXME

This needs to be reformatted as documentation.


Constantnulltimerange

constant Calendar.nulltimerange = TimeRange

Description

This represents the null time range, which, to differ from the zero time range (the zero-length time range), isn't placed in time. This is the result of for instance `& between two strict non-overlapping timeranges - no time at all.

It has a constant, is_nulltimerange, which is non-zero. `! on this timerange is true.

Class Calendar.Calendar

Description

This is the base class of the calendars.


Methodnow

Calendar.TimeRanges.TimeRangenow()

Description

Give the zero-length time period of the current time.

Class Calendar.Ruleset

Description

This is the container class for rules.


Method`==

bool res = Calendar.Ruleset() == other


Methodclone

this_programclone()


Methodset_abbr2zone

this_programset_abbr2zone(mapping(string:string) abbr2zone)

Description

Sets the guess-mapping for timezones. Default is the mapping:

AbbreviationInterpretationUTC
AMTAmerica/ManausUTC-4
ASTAmerica/CuracaoUTC-4
CDTAmerica/Costa_RicaUTC-5
CSTAmerica/El SalvadorUTC-6
ESTAmerica/PanamaUTC-5
GSTAsia/DubaiUTC+4
ISTAsia/JerusalemUTC+2
WSTAustralia/PerthUTC+8
See also

YMD.parse


Methodset_language

this_programset_language(string|Calendar.Rule.Languagelang)


Methodset_rule

this_programset_rule(Calendar.Rule.Language|Calendar.Rule.Timezonerule)


Methodset_timezone

this_programset_timezone(string|Calendar.Rule.Timezonet)

Class Calendar.SuperTimeRange

Description

This class handles the cases where you have a time period with holes. These can be created by the ^ or | operators on time ranges.


Methodcreate

Calendar.SuperTimeRangeCalendar.SuperTimeRange(array(TimeRange) parts)

Description

A SuperTimeRange must have at least two parts, two time ranges. Otherwise, it's either not a time period at all or a normal time period.


InheritTimeRange

inherit TimeRange : TimeRange

Module Calendar.Austrian

Description

Same as the ISO calendar, but with austrian as the default language.

This calendar exist only for backwards compatible purposes.


InheritISO

inherit Calendar.ISO : ISO

Module Calendar.Badi

Description

This is the Badi calendar, used in the Baha'i religion.


Methoddaystart_offset

intdaystart_offset()

Description

Returns the offset to the start of the time range object


InheritYMD

inherit Calendar.YMD : YMD

Class Calendar.Badi.Vahid


InheritYMD

inherit YMD : YMD


Methodyear

Yearyear()
Yearyear(intn)
Yearyear(stringname)

Description

Return a year in the vahid by number or name:

vahid->year("Alif")

Module Calendar.Coptic

Description

This is the Coptic Orthodox Church calendar, that starts the 11th or 12th September and has 13 months.

Note

The (default) names of the months are different then other the emacs calendar; I do not know which ones are used - the difference seem to be only the transcription of the phonetic sounds (B <-> P, etc).

I do not know for how long back the calendar is valid, either. My sources claim that the calendar is synchronized with the Gregorian calendar, which is odd.


InheritGregorian

inherit Calendar.Gregorian : Gregorian

Module Calendar.Discordian

Description

The Discordian calendar, as described on page 34 in the fourth edition of Principia Discordia.

Chaotic enough, it's quite simpler then the Gregorian calendar; weeks are 5 days, and evens up on a year. Months are 73 days.

The leap day is inserted at the 60th day of the first month (Chaos), giving the first month 74 days. The description of the calendar is a "perpetual date converter from the gregorian to the POEE calendar", so the leap years are the same as the gregorians.

The Principia calls months "seasons", but for simplicity I call them months in this calendar.

If anyone know more about how to treat the leap day - now it is inserted in the month and week where it lands, rather then being separated from month and weeks, I'm interested to know.

- Mirar, Pope of POEE.


InheritGregorian

inherit Calendar.Gregorian : Gregorian

Module Calendar.Event

Class Calendar.Event.Date

Description

This class represents the event of a given gregorian date. For instance, Event.Date(12,10)->next(Day()) finds the next 12 of October.


Methodcreate

Calendar.Event.DateCalendar.Event.Date(int(1..31)month_day, int(1..12)month)

Description

The event is created by a given month day and a month number (1=January, 12=December).


InheritDay_Event

inherit Day_Event : Day_Event

Class Calendar.Event.Date_Weekday

Description

This class represents the event that a given gregorian date appears a given weekday. For instance, Event.Date_Weekday(12,10,5)->next(Day()) finds the next 12 of October that is a friday.


Methodcreate

Calendar.Event.Date_WeekdayCalendar.Event.Date_Weekday(intmonth_day, intmonth, intweekday)

Description

The event is created by a given month day, a month number (1=January, 12=December), and a weekday number (1=Monday, 7=Sunday).

Note

The week day numbers used are the same as the day of week in the ISO calendar - the Gregorian calendar has 1=Sunday, 7=Saturday.


InheritDay_Event

inherit Day_Event : Day_Event

Class Calendar.Event.Day_Event

Description

Day_Event is an abstract class, extending Event for events that are single days, using julian day numbers for the calculations.


ConstantNODAY

constantint Calendar.Event.Day_Event.NODAY

Description

Returned from scan_jd if the even searched for did not exist.


InheritEvent

inherit Event : Event


Constantis_day_event

constantint Calendar.Event.Day_Event.is_day_event

Description

This constant may be used to identify Day_Event objects.


Methodnext

Calendar.TimeRanges.TimeRangenext(void|Calendar.TimeRanges.TimeRangefrom, void|boolincluding)

Description

Uses the virtual method scan_jd.

See also

Event.next


Methodprevious

Calendar.TimeRanges.TimeRangeprevious(void|Calendar.TimeRanges.TimeRangefrom, void|boolincluding)

Description

Uses the virtual method scan_jd.

See also

Event.previous


Methodscan_jd

intscan_jd(Calendar.Calendarrealm, intjd, int(-1..-1)|int(1..1)direction)

Description

This method has to be defined, and is what really does some work.

Parameter direction
1

Forward (next),

-1

Backward (previous).

Returns

It should return the next or previous julian day (>jd) when the event occurs, or the constant NODAY if it doesn't.

Class Calendar.Event.Easter

Description

This class represents an easter.


Methodcreate

Calendar.Event.EasterCalendar.Event.Easter(void|intshift)

Description

shift is the year to shift from old to new style easter calculation. Default is 1582.


Methodeaster_yd

inteaster_yd(inty, intyjd, intleap)

Description

Calculates the year day for the easter.


InheritDay_Event

inherit Day_Event : Day_Event

Class Calendar.Event.Easter_Relative

Description

This class represents an easter relative event.


Methodcreate

Calendar.Event.Easter_RelativeCalendar.Event.Easter_Relative(stringid, stringname, intoffset)


InheritEaster

inherit Easter : Easter

Class Calendar.Event.Event

Description

Event is an abstract class, defining what methods an Event need to have.


Method`|
Method``|

SuperEvent res = Calendar.Event.Event() | with
SuperEvent res = with | Calendar.Event.Event()

Description

Joins several events into one SuperEvent.


Methoddescribe

stringdescribe()

Description

Returns a description of the event.


Constantis_event

constantint Calendar.Event.Event.is_event

Description

This constant may be used to identify an event object.


Methodnext
Methodprevious

Calendar.TimeRanges.TimeRangenext(void|Calendar.TimeRanges.TimeRangefrom, void|boolincluding)
Calendar.TimeRanges.TimeRangeprevious(void|Calendar.TimeRanges.TimeRangefrom, void|boolincluding)

Description

This calculates the next or previous occurance of the event, from the given timerange's start, including any event occuring at the start if that flag is set.

It returns zero if there is no next event.

These methods are virtual in the base class.


Methodscan

array(Calendar.TimeRanges.TimeRange) scan(Calendar.TimeRanges.TimeRangein)

Description

This calculates the eventual events that is contained or overlapped by the given timerange. scan uses next, if not overloaded.

Example

Calendar.Event.Easter()->scan(Calendar.Year(2000)) => ({ Day(Sun 23 Apr 2000) })

Note

scan can return an array of overlapping timeranges.

This method must use in->calendar_object->type to create the returned timeranges, and must keep the ruleset.


Methodscan_events

mapping(Calendar.TimeRanges.TimeRange:Event) scan_events(Calendar.TimeRanges.TimeRangein)

Description

Returns a mapping with time ranges mapped to events.

Class Calendar.Event.Gregorian_Fixed

Description

A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.

See also

Julian_Fixed


Methodcreate

Calendar.Event.Gregorian_FixedCalendar.Event.Gregorian_Fixed(stringid, stringname, int(1..31)month_day, int(1..12)month, intextra)


InheritDay_Event

inherit Day_Event : Day_Event


Constantis_fixed

constantint Calendar.Event.Gregorian_Fixed.is_fixed

Description

This constant may be used to identify Gregorian_Fixed objects.

Class Calendar.Event.Julian_Fixed

Description

A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.

See also

Gregorian_Fixed


InheritGregorian_Fixed

inherit Gregorian_Fixed : Gregorian_Fixed


Constantis_julian_fixed

constantint Calendar.Event.Julian_Fixed.is_julian_fixed

Description

This constant may be used to identify Julian_Fixed objects.

Class Calendar.Event.Monthday_Weekday

Description

This class represents the event that a given gregorian day of month appears a given weekday. For instance, Event.Monthday_Weekday(13,5)->next(Day()) finds the next friday the 13th.


Methodcreate

Calendar.Event.Monthday_WeekdayCalendar.Event.Monthday_Weekday(intmonth_day, intweekday)

Description

The event is created by a given month day, and a weekday number (1=Monday, 7=Sunday).

Note

The week day numbers used are the same as the day of week in the ISO calendar - the Gregorian calendar has 1=Sunday, 7=Saturday.


InheritDay_Event

inherit Day_Event : Day_Event

Class Calendar.Event.Monthday_Weekday_Relative

Description

This class represents a monthday weekday relative event or n:th special weekday event, e.g. "fourth sunday before 24 dec" => md=24,mn=12,wd=7,n=-4


Methodcreate

Calendar.Event.Monthday_Weekday_RelativeCalendar.Event.Monthday_Weekday_Relative(stringid, stringname, int(1..31)md, int(1..12)mn, int(1..7)_wd, int_n, void|bool_inclusive)


InheritGregorian_Fixed

inherit Gregorian_Fixed : Gregorian_Fixed

Class Calendar.Event.Nameday

Description

This is created by the Namedays classes to represent an event for a name.


InheritDay_Event

inherit Day_Event : Day_Event


Constantis_nameday

constantint Calendar.Event.Nameday.is_nameday

Description

This constant may be used to identify Nameday objects.

Class Calendar.Event.Namedays

Description

This contains a ruleset about namedays.


InheritEvent

inherit Event : Event


Constantis_namedays

constantint Calendar.Event.Namedays.is_namedays

Description

This constant may be used to identify Namedays.


Methodnamedays

mapping(Calendar.TimeRanges.TimeRange:array(string)) namedays(Calendar.TimeRanges.TimeRanget)

Description

Gives back an table of days with names that occur during the time period. Note that days without names will not appear in the returned mapping.


Methodnames

array(string) names(Calendar.TimeRanges.TimeRanget)

Description

Gives back an array of names that occur during the time period, in no particular order.

Class Calendar.Event.NullEvent

Description

A non-event.


InheritEvent

inherit Event : Event


Constantis_nullevent

constantint Calendar.Event.NullEvent.is_nullevent

Description

This constant may be used to identify a NullEvent.

Class Calendar.Event.Orthodox_Easter_Relative

Description

This class represents an orthodox easter relative event.


Methodcreate

Calendar.Event.Orthodox_Easter_RelativeCalendar.Event.Orthodox_Easter_Relative(stringid, stringname, intoffset)


InheritEaster_Relative

inherit Easter_Relative : Easter_Relative

Class Calendar.Event.Solar

Description

This class represents a solar event as observed from Earth.

The event_type is one of

0

Northern hemisphere spring equinox.

1

Northern hemisphere summer solstice.

2

Northern hemisphere autumn equinox.

3

Northern hemisphere winter solstice.


Methodcreate

Calendar.Event.SolarCalendar.Event.Solar(int|voidevent_type)


Variableevent_type

int|void Calendar.Event.Solar.event_type


InheritDay_Event

inherit Day_Event : Day_Event


Constantperiodic_table

protected constant Calendar.Event.Solar.periodic_table

Description
Array
array(float) 0..
Array
float0

Amplitude in days.

float1

Cosine phase in radians in year 2000.

float2

Period in radians/year.


Methodprevious

Calendar.TimeRanges.TimeRangeprevious(void|Calendar.TimeRanges.TimeRangefrom, void|boolincluding)

Description

Uses the virtual method scan_jd.

See also

Event.previous


Methodscan_jd

intscan_jd(Calendar.Calendarrealm, intjd, int(1..1)|int(-1..-1)direction)

Note

Returns unixtime in UTC to avoid losing the decimals!


Methodsolar_event

array(int|float) solar_event(inty)

Description

Calculate the next event.

Based on Meeus Astronomical Algorithms Chapter 27.

Class Calendar.Event.SuperEvent

Description

This class holds any number of events, and adds the functionality of event flags.

Note

Scanning (scan_events,next,etc) will drop flag information. Dig out what you need with holidays et al first.


Methodfilter_flag
Methodholidays
Methodflagdays

SuperEventfilter_flag(stringflag)
SuperEventholidays()
SuperEventflagdays()

Description

Filter out the events that has a certain flag set. Holidays (flag "h") are the days that are marked red in the calendar (non-working days), Flagdays (flag "f") are the days that the flag should be visible in (only some countries).


InheritEvent

inherit Event : Event

Class Calendar.Event.SuperNamedays

Description

Container for merged Namedays objects. Presumes non-overlapping namedays


Methodcreate

Calendar.Event.SuperNamedaysCalendar.Event.SuperNamedays(array(Nameday) namedayss, stringid)


Variablenamedayss
Variableid

array(Nameday) Calendar.Event.SuperNamedays.namedayss
string Calendar.Event.SuperNamedays.id


InheritEvent

inherit Event : Event

Class Calendar.Event.TZShift_Event

Description

Event containing information about when a timezone is changed.


InheritEvent

inherit Event : Event


Methodscan_history

protectedCalendar.TimeRanges.TimeRangescan_history(Calendar.Rule.Timezonetz, Calendar.TimeRanges.TimeRangefrom, intdirection, boolincluding)


Methodscan_rule

protectedCalendar.TimeRanges.TimeRangescan_rule(Calendar.Rule.Timezonetz, Calendar.TimeRanges.TimeRangefrom, intdirection, intincluding)


Methodscan_shift

protectedCalendar.TimeRanges.TimeRangescan_shift(Calendar.Rule.Timezonetz, Calendar.TimeRanges.TimeRangefrom, intdirection, intincluding)

Class Calendar.Event.Weekday

Description

This class represents any given weekday. For instance, Event.Weekday(5)->next(Day()) finds the next friday.

These are also available as the pre-defined events Events.monday, Events.tuesday, Events.wednesday, Events.thursday, Events.friday, Events.saturday and Events.sunday.


Methodcreate

Calendar.Event.WeekdayCalendar.Event.Weekday(intweekday, void|stringid)

Description

The event is created by a given weekday number (1=Monday, 7=Sunday).

Note

The week day numbers used are the same as the day of week in the ISO calendar - the Gregorian calendar has 1=Sunday, 7=Saturday.


InheritDay_Event

inherit Day_Event : Day_Event

Module Calendar.Events

Description

The Event system

Q: How do I find out which days are red in a specific region?

A: Events.<region>

- contains the events for the region, as a SuperEvent. You can ask this object to filter out the holidays,

Events.se.holidays();

Which will be a superevent containing only holidays.

To use this information, you can for instance use ->scan, here in an example to see what red days there were in Sweden in 2001

<span class='delim'>></span> <span class='ns'>Calendar</span><span class='delim'>.</span>Events<span class='delim'>.</span>se->filter_flag<span class='delim'>(</span><span class='string'>"h"</span><span class='delim'>)</span>->scan<span class='delim'>(</span><span class='ns'>Calendar</span><span class='delim'>.</span>Month<span class='delim'>(</span><span class='delim'>)</span><span class='delim'>)</span><span class='delim'>;</span>
      Result<span class='delim'>:</span> <span class='delim'>(</span><span class='delim'>{</span> <span class='comment'>/* 6 elements */</span>
     		   Day<span class='delim'>(</span>Sun 7 Jan 2001<span class='delim'>)</span><span class='delim'>,</span>
     		   Day<span class='delim'>(</span>Sun 14 Jan 2001<span class='delim'>)</span><span class='delim'>,</span>
     		   Day<span class='delim'>(</span>Sun 21 Jan 2001<span class='delim'>)</span><span class='delim'>,</span>
     		   Day<span class='delim'>(</span>Sun 28 Jan 2001<span class='delim'>)</span><span class='delim'>,</span>
     		   Day<span class='delim'>(</span>Sat 6 Jan 2001<span class='delim'>)</span><span class='delim'>,</span>
     		   Day<span class='delim'>(</span>Mon 1 Jan 2001<span class='delim'>)</span>

Method`[]
Method`->

Event.Event`[](stringregion)
Event.Event`->(stringregion)

Description

return the Event object for the specified region or the specified named event.

Module Calendar.Gregorian

Description

This is the standard conservative christian calendar, used regularly in some countries - USA, for instance - and which derivate - the ISO calendar - is used in most of Europe.


InheritYMD

inherit Calendar.YMD : YMD

Module Calendar.ISO

Description

This is the standard western calendar, which is a derivate of the Gregorian calendar, but with weeks that starts on Monday instead of Sunday.


InheritGregorian

inherit Calendar.Gregorian : Gregorian

Module Calendar.Islamic

Description

This is the islamic calendar. Due to some sources, they decide the first day of the new months on a month-to-month basis (sightings of the new moon), so it's probably not that accurate. If someone can confirm (or deny) accuracy better than that, please contact me so I can change this statement.

It's vaugely based on rules presented in algorithms by Dershowitz, Reingold and Clamen, 'Calendrical Calculations'. It is the same that's used in Emacs calendar mode.

Bugs

I have currently no idea how the arabic countries count the week. Follow the same rules as ISO for now... The time is also suspicious; the day really starts at sunset and not midnight, the hours of the day is not correct. Also don't know what to call years before 1 - go for "BH"; positive years are "AH", anno Hegirac.


InheritYMD

inherit Calendar.YMD : YMD

Module Calendar.Julian

Description

This is the Julian calendar, conjured up by the old Romans when their calendar were just too weird. It was used by the christians as so far as the 18th century in some parts of the world. (Especially the protestantic and orthodox parts.)

Note

Don't confuse the julian day with the Julian calendar. The former is just a linear numbering of days, used in the Calendar module as a common unit for absolute time.


InheritGregorian

inherit Calendar.Gregorian : Gregorian

Module Calendar.Rule

Class Calendar.Rule.Timezone

Description

Contains a time zone.


Methodcreate

Calendar.Rule.TimezoneCalendar.Rule.Timezone(intoffset, stringname)

Parameter offset

Offset to UTC, not counting DST.

Parameter name

The name of the time zone.


Methodraw_utc_offset

intraw_utc_offset()

Description

Returns the offset to UTC, not counting DST.


Methodtz_jd

arraytz_jd(intjulian_day)

FIXME

This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.


Methodtz_ux

arraytz_ux(intunixtime)

FIXME

This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.

Module Calendar.Stardate

Description

This implements TNG stardates.


Methodnow

cTicknow()

Description

Give the zero-length time period of the current time.

Class Calendar.Stardate.cTick


Methodcreate

Calendar.Stardate.cTickCalendar.Stardate.cTick(mixed ... args)
Calendar.Stardate.cTickCalendar.Stardate.cTick(int|floatdate)
Calendar.Stardate.cTickCalendar.Stardate.cTick()

Description

Apart from the standard creation methods (julian day, etc), you can create a stardate from the stardate number. The length of the period will then be zero.

You can also omit any arguments to create now.

Bugs

Since the precision is limited to the float type of Pike you can get non-precise results:

> Calendar.Second(Calendar.Stardate.Day(Calendar.Year()));
Result: Second(Fri 31 Dec 1999 23:59:18 CET - Sun 31 Dec 2000 23:59:18 CET)

Methodformat_long
Methodformat_short
Methodformat_vshort

stringformat_long(void|intprecision)
stringformat_short(void|intprecision)
stringformat_vshort(void|intprecision)

Description

Format the stardate tick nicely. Precision is the number of decimals. Defaults to 3.

long"-322537.312"
short"77463.312"(w/o >100000-component)
vshort"7463.312"(w/o >10000-component)

InheritTimeRange

inherit Calendar.TimeRange : TimeRange


Methodnumber_of_days

intnumber_of_days()

Description

This gives back the Gregorian/Earth/ISO number of days, for convinience and conversion to other calendars.


Methodnumber_of_seconds

intnumber_of_seconds()

Description

This gives back the Gregorian/Earth/ISO number of seconds, for convinience and conversion to other calendars.


Methodtic

floattic()

Description

This gives back the start of the stardate period, as a float.


Methodtics

floattics()

Description

This gives back the number of stardate tics in the period.

Module Calendar.Swedish

Description

Same as the ISO calendar, but with Swedish as the default language.

This calendar exist only for backwards compatible purposes.


InheritISO

inherit Calendar.ISO : ISO

Module Calendar.TZnames

Description

This module contains listnings of available timezones, in some different ways


Method_zone_tab
Methodzone_tab

string _zone_tab()
array(array) zone_tab()

Description

This returns the raw respectively parsed zone tab file from the timezone data files.

The parsed format is an array of zone tab line arrays,

({ string country_code,
   string position,
   string zone_name,
   string comment })

To convert the position to a Geography.Position, simply feed it to the constructor.


Constantabbr2zones

constant Calendar.TZnames.abbr2zones = mapping(string:array(string))

Description

This mapping is used to look up abbreviation to the possible regional zones.

It looks like this:

([ "CET": ({ "Europe/Stockholm", <i>[...]</i> }),
   "CST": ({ "America/Chicago", "Australia/Adelaide", <i>[...]</i> }),
   <i>[...]</i> }),

Note this: Just because it's noted "CST" doesn't mean it's a unique timezone. There is about 7 *different* timezones that uses "CST" as abbreviation; not at the same time, though, so the DWIM routines checks this before it's satisfied. Same with some other timezones.

For most timezones, there is a number of region timezones that for the given time are equal. This is because region timezones include rules about local summer time shifts and possible historic shifts.

The YMD.parse functions can handle timezone abbreviations by guessing.


Methodzonenames

array(string) zonenames()

Description

This reads the zone.tab file and returns name of all standard timezones, like "Europe/Belgrade".


Constantzones

constant Calendar.TZnames.zones = mapping(string:array(string))

Description

This constant is a mapping that can be used to loop over to get all the region-based timezones.

It looks like this:

([ "America": ({ "Los_Angeles", "Chicago", <i>[...]</i> }),
   "Europe":  ({ "Stockholm", <i>[...]</i> }),
   <i>[...]</i> }),

Please note that loading all the timezones can take some time, since they are generated and compiled on the fly.

Module Calendar.Time

Description

Base for time of day in calendars, ie calendars with hours, minutes, seconds

This module can't be used by itself, but is inherited by other modules (ISO by YMD, for instance).


InheritTimeRanges

inherit TimeRanges : TimeRanges

Class Calendar.Time.Fraction

Description

A Fraction is a part of a second, and/or a time period with higher resolution then a second.

It contains everything that is possible to do with a Second, and also some methods of grabbing the time period with higher resolution.

Note

Internally, the fraction time period is measured in nanoseconds. A shorter or more precise time period then in nanoseconds is not possible within the current Fraction class.


Methodcreate

Calendar.Time.FractionCalendar.Time.Fraction()
Calendar.Time.FractionCalendar.Time.Fraction("unix", int|floatunixtime)
Calendar.Time.FractionCalendar.Time.Fraction("unix", int|floatunixtime, int|floatlen)
Calendar.Time.FractionCalendar.Time.Fraction(inty, intm, intd, inth, intm, ints, intns)

Description

It is possible to create a Fraction in three ways, either "now" with no arguments or from a unix time (as from time(2)), or the convenience way from ymd-hms integers.

If created from unix time, both the start of the period and the size of the period can be given in floats, both representing seconds. Note that the default float precision in pike is rather low (same as 'float' in C, the 32 bit floating point precision, normally about 7 digits), so beware that the resolution might bite you. (Internally in a Fraction, the representation is an integer.)

If created without explicit length, the fraction will always be of zero length.


InheritSecond

inherit Second : Second


Methodnow

TimeofDay now()

Description

Give the zero-length time period of the current time.


Methodset_ruleset
Methodruleset

Calendar set_ruleset(Rulesetr)
Ruleset ruleset()

Description

Set or read the ruleset for the calendar. set_ruleset returns a new calendar object, but with the new ruleset.


Methodset_timezone
Methodtimezone

Calendar set_timezone(Timezonetz)
Calendar set_timezone(string|Timezonetz)
TimeZone timezone()

Description

Set or get the current timezone (including dst) rule. set_timezone returns a new calendar object, as the called calendar but with another set of rules.

Example:

> Calendar.now();
Result: Fraction(Fri 2 Jun 2000 18:03:22.010300 CET)
> Calendar.set_timezone(Calendar.Timezone.UTC)->now();
Result: Fraction(Fri 2 Jun 2000 16:03:02.323912 UTC)

Class Calendar.Time.Hour


InheritTimeofDay

inherit TimeofDay : TimeofDay

Class Calendar.Time.Minute


InheritTimeofDay

inherit TimeofDay : TimeofDay

Class Calendar.Time.Second


InheritTimeofDay

inherit TimeofDay : TimeofDay

Class Calendar.Time.SuperTimeRange


Methodsecond
Methodseconds
Methodnumber_of_seconds
Methodminute
Methodminutes
Methodnumber_of_minutes
Methodhour
Methodhours
Methodnumber_of_hours

Second second()
Second second(intn)
array(Second) seconds()
array(Second) seconds(intfirst, intlast)
int number_of_seconds()
Minute minute()
Minute minute(intn)
array(Minute) minutes()
array(Minute) minutes(intfirst, intlast)
int number_of_minutes()
Hour hour()
Hour hour(intn)
array(Hour) hours()
array(Hour) hours(intfirst, intlast)
int number_of_hours()

Description

Similar to TimeofDay, the Time::SuperTimeRange has a number of methods for digging out time parts of the range. Since a SuperTimeRange is a bit more complex - the major reason for its existance it that it contains holes, this calculation is a bit more advanced too.

If a range contains the seconds, say, 1..2 and 4..5, the third second (number 2, since we start from 0) in the range would be number 4, like this:

no   means this second
0    1
1    2
2    4      <- second three is missing,
3    5         as we don't have it in the example range

number_of_seconds() will in this example therefore also report 4, not 5, even if the time from start of the range to the end of the range is 5 seconds.


InheritSuperTimeRange

inherit TimeRanges.SuperTimeRange : SuperTimeRange

Class Calendar.Time.TimeofDay

Description

Virtual class used by e.g. Hour.


Methodcall_out

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

Description

Creates a call_out to this point in time.


Methodcreate

Calendar.Time.TimeofDayCalendar.Time.TimeofDay()
Calendar.Time.TimeofDayCalendar.Time.TimeofDay(intunixtime)

Description

In addition to the wide range of construction arguments for a normal TimeRange (see TimeRange.create), a time of day can also be constructed with unixtime as single argument consisting of the unix time - as returned from time(2) - of the time unit start.

It can also be constructed without argument, which then means "now", as in "this minute".


Methoddatetime

mapping datetime()

Description

This gives back a mapping with the relevant time information (representing the start of the period);

 ([ "year":     int        // year number (2000 AD=2000, 1 BC==0)
    "month":    int(1..)   // month of year
    "day":      int(1..)   // day of month
    "yearday":  int(1..)   // day of year
    "week":     int(1..)   // week of year
    "week_day": int(1..)   // day of week (depending on calendar)
 
    "hour":     int(0..)   // hour of day, including dst
    "minute":   int(0..59) // minute of hour
    "second":   int(0..59) // second of minute
    "fraction": float      // fraction of second
    "timezone": int        // offset to utc, including dst
 
    "unix":     int        // unix time
    "julian":   float      // julian day
 ]);

Methodformat_iso_ymd
Methodformat_ymd
Methodformat_ymd_short
Methodformat_ymd_xshort
Methodformat_iso_week
Methodformat_iso_week_short
Methodformat_week
Methodformat_week_short
Methodformat_month
Methodformat_month_short
Methodformat_iso_time
Methodformat_time
Methodformat_time_short
Methodformat_iso_short
Methodformat_time_xshort
Methodformat_mtime
Methodformat_xtime
Methodformat_tod
Methodformat_xtod
Methodformat_mod
Methodformat_nice
Methodformat_nicez

string format_iso_ymd()
string format_ymd()
string format_ymd_short()
string format_ymd_xshort()
string format_iso_week()
string format_iso_week_short()
string format_week()
string format_week_short()
string format_month()
string format_month_short()
string format_iso_time()
string format_time()
string format_time_short()
string format_iso_short()
string format_time_xshort()
string format_mtime()
string format_xtime()
string format_tod()
string format_xtod()
string format_mod()
string format_nice()
string format_nicez()

Description

Format the object into nice strings;

iso_ymd        "2000-06-02 (Jun) -W22-5 (Fri)" [2]
ext_ymd        "Friday, 2 June 2000" [2]
ymd            "2000-06-02"
ymd_short      "20000602"
ymd_xshort     "000602" [1]
iso_week       "2000-W22"
iso_week_short "2000W22"
week           "2000-w22" [2]
week_short     "2000w22" [2]
month          "2000-06"
month_short    "200006" [1]
iso_time       "2000-06-02 (Jun) -W22-5 (Fri) 20:53:14 UTC+1" [2]
ext_time       "Friday, 2 June 2000, 20:53:14" [2]
ctime          "Fri Jun  4 20:53:14 2000\n" [2] [3]
http           "Fri, 02 Jun 2000 19:53:14 GMT" [4]
time           "2000-06-02 20:53:14"
time_short     "20000602 20:53:14"
time_xshort    "000602 20:53:14"
iso_short      "20000602T20:53:14"
mtime          "2000-06-02 20:53"
xtime          "2000-06-02 20:53:14.000000"
todz           "20:53:14 CET"
todz_iso       "20:53:14 UTC+1"
tod            "20:53:14"
tod_short      "205314"
xtod           "20:53:14.000000"
mod            "20:53"
nice           "2 Jun 20:53", "2 Jun 2000 20:53:14" [2][5]
nicez          "2 Jun 20:53 CET" [2][5]
smtp           "Fri, 2 Jun 2000 20:53:14 +0100" [6]
commonlog      "02/Jun/2000:20:53:14 +0100" [2]
[1] note conflict (think 1 February 2003)
[2] language dependent
[3] as from the libc function ctime()
[4] as specified by the HTTP standard; this is always in GMT, ie, UTC. The timezone calculations needed will be executed implicitly. It is not language dependent.
[5] adaptive to type and with special cases for yesterday, tomorrow and other years
[6] as seen in Date: headers in mails

Methodhour_no
Methodminute_no
Methodsecond_no
Methodfraction_no

int hour_no()
int minute_no()
int second_no()
float fraction_no()

Description

This gives back the number of the time unit, on this day. Fraction is a float number, 0<=fraction<1.


Methodhour
Methodhours
Methodnumber_of_hours

Hour hour()
Hour hour(intn)
array(Hour) hours()
array(Hour) hours(intfirst, intlast)
int number_of_hours()

Description

hour() gives back the timerange representing the first or nth Hour of the called object. Note that hours normally starts to count at zero, so ->hour(2) gives the third hour within the range.

An Hour is in the Calendar perspective as any other time range not only 60 minutes, but also one of the (normally) 24 hours of the day, precisely.

hours() give back an array of all the hours containing the time periods called. With arguments, it will give back a range of those hours, in the same enumeration as the n to hour().

number_of_hours() simple counts the number of hours containing the called time period.

Note: The called object doesn't have to *fill* all the hours it will send back, it's enough if it exist in those hours:

    > object h=Calendar.Time.Hour();
    Result: Hour(265567)
    > h->hours();
    Result: ({ /* 1 element */
                Hour(265567)
            })
    > h+=Calendar.Time.Minute();
    Result: Minute(265567:01+60m)
    > h->hours();
    Result: ({ /* 2 elements */
                Hour(265567),
                Hour(265568)
            })
    

InheritTimeRange

inherit TimeRange : TimeRange


Methodjulian_day

float julian_day()

Description

This calculates the corresponding julian day, from the time range. Note that the calculated day is the beginning of the period, and is a float - julian day standard says .00 is midday, 12:00 pm.

Note

Normal pike (ie, 32 bit) floats (without --with-double-precision) has a limit of about 7 digits, and since we are about julian day 2500000, the precision on time of day is very limited.


Methodminute
Methodminutes
Methodnumber_of_minutes

Minute minute()
Minute minute(intn)
array(Minute) minutes()
array(Minute) minutes(intfirst, intlast)
int number_of_minutes()

Description

minute() gives back the timerange representing the first or nth Minute of the called object. Note that minutes normally starts to count at zero, so ->minute(2) gives the third minute within the range.

An Minute is in the Calendar perspective as any other time range not only 60 seconds, but also one of the (normally) 60 minutes of the Hour, precisely.

minutes() give back an array of all the minutes containing the time periods called. With arguments, it will give back a range of those minutes, in the same enumeration as the n to minute().

number_of_minutes() simple counts the number of minutes containing the called time period.


Methodmove_seconds
Methodmove_ns

TimeRange move_seconds(intseconds)
TimeRange move_ns(intnanoseconds)

Description

These two methods gives back the time range called moved the specified amount of time, with the length intact.

The motion is relative to the original position in time; 10 seconds ahead of 10:42:32 is 10:42:42, etc.


Methodsecond
Methodseconds
Methodnumber_of_seconds

Second second()
Second second(intn)
array(Second) seconds()
array(Second) seconds(intfirst, intlast)
int number_of_seconds()

Description

second() gives back the timerange representing the first or nth Second of the called object. Note that seconds normally starts to count at zero, so ->second(2) gives the third second within the range.

seconds() give back an array of all the seconds containing the time periods called. With arguments, it will give back a range of those seconds, in the same enumeration as the n to second().

number_of_seconds() simple counts the number of seconds containing the called time period.


Methodset_size_seconds
Methodset_size_ns

TimeRange set_size_seconds(intseconds)
TimeRange set_size_ns(intnanoseconds)

Description

These two methods allows the time range to be edited by size of specific units.


Methodunix_time

int unix_time()

Description

This calculates the corresponding unix time, - as returned from time(2) - from the time range. Note that the calculated unix time is the beginning of the period.

Module Calendar.TimeRanges

Class Calendar.TimeRanges.TimeRange

Description

This is the base class (usually implemented by e.g. Calendar subclasses like Calendar.Second) for any time measurement and calendrar information. It defines all the things you can do with a time range or any time period.

A TimeRange doubles as both a fixed period in time, and an amount of time. For instance, a week plus a day moves the week-period one day ahead (unaligning it with the week period, and thereby reducing it to just 7 days), no matter when in time the actual day were.


Method`==
Method_equal

bool res = Calendar.TimeRanges.TimeRange() == compared_to
boolequal(Calendar.TimeRanges.TimeRangefrom, TimeRangecompared_to)

Description

These two overloads the operator `== and the result of the equal function.

a==b is considered true if the two timeranges are of the same type, have the same rules (language, timezone, etc) and are the same timerange.

equal(a,b) are considered true if a and b are the same timerange, exactly the same as the equals method.

The __hash method is also present, to make timeranges possible to use as keys in mappings.

known bugs: _equal is not currently possible to overload, due to weird bugs, so equal uses `== for now.


Method`&

TimeRange res = Calendar.TimeRanges.TimeRange() & with

Description

Gives the cut on the called time period with another time period. The result is zero if the two periods doesn't overlap.

>- the past          the future -<
 |-------called-------|
      |-------other--------|
      >----- cut -----<
 

Method`*

TimeRange res = Calendar.TimeRanges.TimeRange() * n

Description

This changes the amount of time in the time period. t*17 is the same as doing t->set_size(t,17).


Method`+
Method`-

TimeRange res = Calendar.TimeRanges.TimeRange() + n
TimeRange res = Calendar.TimeRanges.TimeRange() + offset
TimeRange res = Calendar.TimeRanges.TimeRange() - m
TimeRange res = Calendar.TimeRanges.TimeRange() - x

Description

This calculates the (promoted) time period either n step away or with a given offset. These functions does use add to really do the job:

t+n         t->add(n)             t is a time period
t-n         t->add(-n)            offset is a time period
t+offset    t->add(1,offset)      n is an integer
t-offset    t->add(-1,offset)
n+t         t->add(n)
n-t         illegal
offset+t    offset->add(1,t)      | note this!
offset-t    offset->add(-1,t)     |

Mathematic rules:

x+(t-x) == t    x is an integer or a time period
(x+t)-x == t    t is a time period
(t+x)-x == t
o-(o-t) == t    o is a time period
t++ == t+1
t-- == t-1
Note

a-b does not give the distance between the start of a and b. Use the distance() function to calculate that.

The integer used to `+, `- and add are the number of steps the motion will be. It does never represent any fixed amount of time, like seconds or days.


Method`/
Methodsplit

array(TimeRange) res = Calendar.TimeRanges.TimeRange() / n
array(TimeRange) split(int|floatn, objectvoid|TimeRangewith)

Description

This divides the called timerange into n pieces. The returned timerange type is not neccesarily of the same type as the called one. If the optional timerange is specified then the resulting timeranges will be multiples of that range (except for the last one).

known bugs: These are currently not defined for supertimeranges.


Method`/
Methodhow_many

int res = Calendar.TimeRanges.TimeRange() / with
int how_many(TimeRangewith)

Description

This calculates how many instances of the given timerange has passed during the called timerange.

For instance, to figure out your age, create the timerange of your lifespan, and divide with the instance of a Year.


Method`<
Method`>

bool res = Calendar.TimeRanges.TimeRange() < compared_to
bool res = Calendar.TimeRanges.TimeRange() > compared_to

Description

These operators sorts roughty on the periods place in time. The major use might be to get multiset to work, besides sorting events clearly defined in time.


Method`^

TimeRange res = Calendar.TimeRanges.TimeRange() ^ with

Description

Gives the exclusive-or on the called time period and another time period, ie the union without the cut. The result is zero if the two periods were the same.

>- the past          the future -<
 |-------called-------|
      |-------other--------|
 <----|               |---->   - exclusive or
 

Method`|

TimeRange res = Calendar.TimeRanges.TimeRange() | with

Description

Gives the union on the called time period and another time period.

>- the past          the future -<
 |-------called-------|
      |-------other--------|
 <----------union---------->
 

Methodadd

TimeRange add(intn, void|TimeRangestep)

Description

calculates the (promoted) time period n steps away; if no step is given, the step's length is of the same length as the called time period.

It is not recommended to loop by adding the increment time period to a shorter period; this can cause faults, if the shorter time period doesn't exist in the incremented period. (Like week 53, day 31 of a month or the leap day of a year.)

Recommended use are like this:

   // loop over the 5th of the next 10 months
   TimeRange month=Month()+1;
   TimeRange orig_day=month()->day(5);
   for (int i=0; i<10; i++)
   {
      month++;
      TimeRange day=month->place(orig_day);
      <i>...use day...</i>
   }

Methodbeginning
Methodend

TimeRange beginning()
TimeRange end()

Description

This gives back the zero-sized beginning or end of the called time period.

rule: range(t->beginning(),t->end())==t


Methodcalendar

Calendar calendar()

Description

Simply gives back the calendar in use, for instance Calendar.ISO or Calendar.Discordian.


Methodstrictly_preceeds
Methodpreceeds
Methodis_previous_to
Methodoverlaps
Methodcontains
Methodequals
Methodis_next_to
Methodsucceeds
Methodstrictly_succeeds

boolstrictly_preceeds(TimeRangewhat)
boolpreceeds(TimeRangewhat)
boolis_previous_to(TimeRangewhat)
booloverlaps(TimeRangewhat)
boolcontains(TimeRangewhat)
boolequals(TimeRangewhat)
boolis_next_to(TimeRangewhat)
boolsucceeds(TimeRangewhat)
boolstrictly_succeeds(TimeRangewhat)

Description

These methods exists to compare two periods of time on the timeline.

          case            predicates
 
 <-- past       future ->
 
 |----A----|              A strictly preceeds B,
              |----B----| A preceeds B
 
 |----A----|              A strictly preceeds B, A preceeds B,
           |----B----|    A is previous to B, A touches B
 
     |----A----|          A preceeds B,
           |----B----|    A overlaps B, A touches B
 
     |-------A-------|    A preceeds B, A ends with B
           |----B----|    A overlaps B, A contains B, A touches B,
 
     |-------A-------|    A preceeds B,  A succeeds B,
         |---B---|        A overlaps B, A contains B, A touches B
 
        |----A----|       A overlaps B, A touches B, A contains B
        |----B----|       A equals B, A starts with B, A ends with B
 
     |-------A-------|    A succeeds B, A starts with B
     |----B----|          A overlaps B, A contains B, A touches B
 
           |----A----|    A succeeds B,
     |----B----|          A overlaps B, A touches B
 
           |----A----|    A strictly succeeds B, A succeeds B
 |----B----|              A is next to B, A touches B
 
             |----A----|  A strictly succeeds B,
 |----B----|              A succeeds B
 
 
Note

These methods only check the range of the first to the last time in the period; use of combined time periods (SuperTimeRanges) might not give you the result you want.

See also

`&amp;


Methodcreate

Calendar.TimeRanges.TimeRangeCalendar.TimeRanges.TimeRange(TimeRangefrom)

Description

Create the timerange from another timerange.

This is useful when converting objects from one calendar to another. Note that the ruleset will be transferred to the new object, so this method can't be used to convert between timezones or languges - use set_timezone, set_language or set_ruleset to achieve this.

Note

The size of the new object may be inexact; a Month object can't comprehend seconds, for instance.


Methodcreate

Calendar.TimeRanges.TimeRangeCalendar.TimeRanges.TimeRange("julian", int|floatjulian_day)

Description

Create the timerange from a julian day, the standardized method of counting days. If the timerange is more then a day, it will at least enclose the day.


Methodcreate

Calendar.TimeRanges.TimeRangeCalendar.TimeRanges.TimeRange("unix", intunixtime)
Calendar.TimeRanges.TimeRangeCalendar.TimeRanges.TimeRange("unix", intunixtime, intseconds_len)

Description

Create the timerange from unix time (as given by time(2)), with eventually the size of the time range in the same unit, seconds.


Methodrange
Methodspace
Methoddistance

TimeRange range(TimeRangeother)
TimeRange space(TimeRangeother)
TimeRange distance(TimeRangeother)

Description

Derives different time periods in between the called timerange and the parameter timerange.

>- the past          the future -<
 |--called--|         |--other--|
 >------------ range -----------<
            >--space--<
 >----- distance -----<
 

See also: add, TimeRanges.range, TimeRanges.space, TimeRanges.distance


Methodset_language
Methodlanguage

TimeRange set_language(Rule.Languagelang)
TimeRange set_language(stringlang)
Language language()

Description

Set or get the current language rule.


Methodnext
Methodprev

TimeRange next()
TimeRange prev()

Description

Next and prev are compatible and convinience functions; a->next() is exactly the same as a+1; a=a->next() is a++.


Methodoffset_to

int offset_to(TimeRangex)

Description

Calculates offset to x; this compares two timeranges and gives the integer offset between the two starting points.

This is true for suitable a and b: a+a->offset_to(b)==b

By suitable means that a and b are of the same type and size. This is obviously true only if a+n has b as a possible result for any n.


Methodplace

TimeRange place(TimeRangethis)
TimeRange place(TimeRangethis, boolforce)

Description

This will place the given timerange in this timerange, for instance, day 37 in the year - Year(1934)->place(Day(1948 d37)) => Day(1934 d37).

Note

The rules how to place things in different timeranges can be somewhat 'dwim'.


Methodset_ruleset
Methodruleset

TimeRange set_ruleset(Rulesetr)
TimeRange ruleset(Rulesetr)

Description

Set or get the current ruleset.

Note

this may include timezone shanges, and change the time of day.


Methodset_size

TimeRange set_size(TimeRangesize)
TimeRange set_size(intn, TimeRangesize)

Description

Gives back a new (or the same, if the size matches) timerange with the new size. If n are given, the resulting size will be n amounts of the given size.

Note

A negative size is not permitted; a zero one are.


Methodset_timezone
Methodtimezone

TimeRange set_timezone(Timezonetz)
TimeRange set_timezone(stringtz)
TimeZone timezone()

Description

Set or get the current timezone (including dst) rule.

Note

The time-of-day may very well change when you change timezone.

To get the time of day for a specified timezone, select the timezone before getting the time of day:

Year(2003)->...->set_timezone(TimeZone.CET)->...->hour(14)->...


Methodsubtract

TimeRange subtract(TimeRangewhat)

Description

This subtracts a period of time from another;

>- the past          the future -<
|-------called-------|
     |-------other--------|
<---->  <- called->subtract(other)
 
|-------called-------|
     |---third---|
<---->           <---> <- called->subtract(third)

Module Calendar.Timezone

Description

This module contains all the predefined timezones. Index it with whatever timezone you want to use.

Example: Calendar.Calendar my_cal= Calendar.ISO->set_timezone(Calendar.Timezone["Europe/Stockholm"]);

A simpler way of selecting timezones might be to just give the string to set_timezone; it indexes by itself:

Calendar.Calendar my_cal= Calendar.ISO->set_timezone("Europe/Stockholm");

Note

Do not confuse this module with Ruleset.Timezone, which is the base class of a timezone object.

"CET" and some other standard abbreviations work too, but not all of them (due to more then one country using them).

Do not call set_timezone too often, but remember the result if possible. It might take some time to initialize a timezone object.

There are about 504 timezones with 127 different daylight saving rules. Most of them historic.

The timezone information comes from ftp://elsie.nci.nih.gov/pub/ and are not made up from scratch. Timezone bugs may be reported to the timezone mailing list, tz@elsie.nci.nih.gov, preferable with a cc to mirar+pike@mirar.org. /Mirar

See also

TZnames


Constantlocale

constant Calendar.Timezone.locale = Rule.Timezone

Description

This contains the local timezone, found from various parts of the system, if possible.


Constantlocaltime

constant Calendar.Timezone.localtime = Rule.Timezone

Description

This is a special timezone, that uses localtime() and tzname to find out what current offset and timezone string to use.

locale uses this if there is no other way of finding a better timezone to use.

This timezone is limited by localtime and libc to the range of time_t, which is a MAXINT on most systems - 13 Dec 1901 20:45:52 to 19 Jan 2038 3:14:07, UTC.

Module Calendar.YMD

Description

base for all Roman-kind of Calendars, ie, one with years, months, weeks and days


Methoddatetime

mapping(string:int) datetime(int|voidunix_time)

Description

Replacement for localtime; gives back a mapping:

 ([ "year":     int        // year number (2000 AD=2000, 1 BC==0)
    "month":    int(1..)   // month of year
    "day":      int(1..)   // day of month
    "yearday":  int(1..)   // day of year
    "week":     int(1..)   // week of year
    "week_day": int(1..)   // day of week (depending on calendar)
    "unix":     int        // unix time
    "julian":   float      // julian day
    "hour":     int(0..)   // hour of day, including dst
    "minute":   int(0..59) // minute of hour
    "second":   int(0..59) // second of minute
    "fraction": float      // fraction of second
    "timezone": int        // offset to utc, including dst
 ]);
This is the same as calling Second()->datetime().

Methoddatetime_name
Methoddatetime_short_name

string datetime_name(int|voidunix_time)
string datetime_short_name(int|voidunix_time)

Description

Compat functions; same as format_iso and format_iso_short.


Methoddeltat

float deltat(intunadjusted_utc)

Description

Terrestrial Dynamical Time difference from standard time.

An approximation of the difference between TDT and UTC in fractional seconds at the specified time.

The zero point is 1901-06-25T14:23:01 UTC (unix time -2162281019), ie the accumulated number of leap seconds since then is returned.

Returns
Note

The function is based on polynomials provided by NASA, and the result may differ from actual for dates after 2004.


Methoddwim_day

Day dwim_day(stringdate)
Day dwim_day(stringdate, TimeRangecontext)

Description

Tries a number of different formats on the given date (in order):

<ref>parse</ref> format                  as in
"%y-%M-%D (%M) -W%W-%e (%e)"  "2000-03-20 (Mar) -W12-1 (Mon)"
"%y-%M-%D"                    "2000-03-20", "00-03-20"
"%M%/%D/%y"                   "3/20/2000"
"%D%*[ /]%M%*[ /-,]%y"        "20/3/2000" "20 mar 2000" "20/3 -00"
"%e%*[ ]%D%*[ /]%M%*[ /-,]%y" "Mon 20 Mar 2000" "Mon 20/3 2000"
"-%y%*[ /]%D%*[ /]%M"         "-00 20/3" "-00 20 mar"
"-%y%*[ /]%M%*[ /]%D"         "-00 3/20" "-00 march 20"
"%y%*[ /]%D%*[ /]%M"          "00 20 mar" "2000 20/3"
"%y%*[ /]%M%*[ /]%D"          "2000 march 20"
"%D%.%M.%y"                   "20.3.2000"
"%D%*[ -/]%M"                 "20/3" "20 mar" "20-03"
"%M%*[ -/]%D"                 "3/20" "march 20"
"%M-%D-%y"                    "03-20-2000"
"%D-%M-%y"                    "20-03-2000"
"%e%*[- /]%D%*[- /]%M"        "mon 20 march"
"%e%*[- /]%M%*[- /]%D"        "mon/march/20"
"%e%*[ -/wv]%W%*[ -/]%y"      "mon w12 -00" "1 w12 2000"
"%e%*[ -/wv]%W"               "mon w12"
"%d"                          "20000320", "000320"
"today"                       "today"
"last %e"                     "last monday"
"next %e"                     "next monday"
Note

Casts exception if it fails to dwim out a day. "dwim" means do-what-i-mean.


Methoddwim_time

Day dwim_time(stringdate_time)
Day dwim_time(stringdate_time, objectTimeRangecontext)

Description

Tries a number of different formats on the given date_time.

Note

Casts exception if it fails to dwim out a time. "dwim" means do-what-i-mean.


Methodformat_iso
Methodformat_iso_short
Methodformat_iso_tod
Methodformat_day_iso
Methodformat_day_iso_short

string format_iso(void|intunix_time)
string format_iso_short(void|intunix_time)
string format_iso_tod(void|intunix_time)
string format_day_iso(void|intunix_time)
string format_day_iso_short(void|intunix_time)

Description

Format the object into nice strings;

iso    "2000-06-02 (Jun) -W22-5 (Fri) 11:57:18 CEST"
iso_short   "2000-06-02 11:57:18"
iso_tod     "11:57:18"

InheritTime

inherit Time : Time


Methodparse

TimeRange parse(stringfmt, stringarg)

Description

parse a date, create relevant object fmt is in the format "abc%xdef..." where abc and def is matched, and %x is one of those time units:

%Y absolute year
%y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069)
%M month (number, name or short name) (needs %y)
%W week (needs %y)
%D date (needs %y, %m)
%d short date (20000304, 000304)
%a day (needs %y)
%e weekday (needs %y, %w)
%h hour (needs %d, %D or %W)
%m minute (needs %h)
%s second (needs %m)
%S seconds since the Epoch (only combines with %f)
%f fraction of a second (needs %s or %S)
%t short time (205314, 2053)
%z zone
%p "am" or "pm"
%n empty string (to be put at the end of formats)
Returns

0 if format doesn't match data, or the appropriate time object.

Note

The zone will be a guess if it doesn't state an exact regional timezone (like "Europe/Stockholm") - most zone abbriviations (like "CET") are used by more then one region with it's own daylight saving rules. Also beware that for instance CST can be up to four different zones, central Australia or America being the most common.

Abbreviation Interpretation
AMT          America/Manaus       [UTC-4]
AST          America/Curacao      [UTC-4]
CDT          America/Costa_Rica   [UTC-6]
CST          America/El Salvador  [UTC-6]
EST          America/Panama       [UTC-5]
GST          Asia/Dubai           [UTC+4]
IST          Asia/Jerusalem       [UTC+2]
WST          Australia/Perth      [UTC+8]

This mapping is modifiable in the ruleset, see Ruleset.set_abbr2zone.

Class Calendar.YMD.Day


Methodcreate

Calendar.YMD.DayCalendar.YMD.Day("unix", intunix_time)
Calendar.YMD.DayCalendar.YMD.Day("julian", int|floatjulian_day)
Calendar.YMD.DayCalendar.YMD.Day(intyear, intmonth, intday)
Calendar.YMD.DayCalendar.YMD.Day(intyear, intyear_day)
Calendar.YMD.DayCalendar.YMD.Day(intjulian_day)

Description

It's possible to create the day by using five different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year, month and day, from year and day of year, and from julian day without extra fuzz.


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.Fraction


InheritFraction

inherit Time.Fraction : Fraction


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.Hour


InheritHour

inherit Time.Hour : Hour


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.Minute


InheritMinute

inherit Time.Minute : Minute


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.Month


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.Second


InheritSecond

inherit Time.Second : Second


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.SuperTimeRange


InheritSuperTimeRange

inherit Time.SuperTimeRange : SuperTimeRange

Class Calendar.YMD.Week

Description

The Calendar week represents a standard time period of a week. In the Gregorian calendar, the standard week starts on a sunday and ends on a saturday; in the ISO calendar, it starts on a monday and ends on a sunday.

The week are might not be aligned to the year, and thus the week may cross year borders and the year of the week might not be the same as the year of all the days in the week. The basic rule is that the week year is the year that has the most days in the week, but since week number only is specified in the ISO calendar - and derivates - the week number of most calendars is the week number of most of the days in the ISO calendar, which modifies this rule for the Gregorian calendar; the week number and year is the same as for the ISO calendar, except for the sundays.

When adding, moving and subtracting months to a week, it falls back to using days.

When adding, moving or subtracting years, if tries to place the moved week in the resulting year.


Methodcreate

Calendar.YMD.WeekCalendar.YMD.Week("unix", intunix_time)
Calendar.YMD.WeekCalendar.YMD.Week("julian", int|floatjulian_day)
Calendar.YMD.WeekCalendar.YMD.Week(intyear, intweek)

Description

It's possible to create the standard week by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year and week number.

Can be less than 1 for the first week of the year if it begins in the previous year.


Methodday

Day day()
Day day(intn)
Day day(stringname)

Description

The Week type overloads the day() method, so it is possible to get a specified weekday by string:

week->day("sunday")

The integer and no argument behavior is inherited from YMD().

Note

the weekday-from-string routine is language dependent.


InheritYMD

inherit YMD : YMD

Class Calendar.YMD.YMD

Description

Base (virtual) time period of the Roman-kind of calendar.


Methoddatetime

mapping datetime()

Description

This gives back a mapping with the relevant time information (representing the start of the period);

 ([ "year":     int        // year number (2000 AD=2000, 1 BC==0)
    "month":    int(1..)   // month of year
    "day":      int(1..)   // day of month
    "yearday":  int(0..)   // day of year
    "week":     int(1..)   // week of year
    "week_day": int(0..)   // day of week
    "timezone": int        // offset to utc, including dst
 
    "unix":     int        // unix time
    "julian":   int        // julian day
 // for compatibility:
    "hour":     0          // hour of day, including dst
    "minute":   0          // minute of hour
    "second":   0          // second of minute
    "fraction": 0.0        // fraction of second
 ]);
Note

Day of week is compatible with old versions, ie, 0 is sunday, 6 is saturday, so it shouldn't be used to calculate the day of the week with the given week number. Year day is also backwards compatible, ie, one (1) less then from the year_day() function.

If this function is called in a Week object that begins with the first week of a year, it returns the previous year if that is where the week starts. To keep the representation unambiguous, the returned week number is then one more than the number of weeks in that year.

E.g. Week(2008,1)->datetime() will return year 2007 and week 53 since the first week of 2008 starts in 2007.


Methodday

Day day()
Day day(intn)

Description

Get day number n in the current range.

If n is negative, it is counted from the end of the range.


Methoddays

array(Day) days(int|voidfrom, objectint|voidto)

Description

Get the days in the current range.


Methodformat_iso_ymd
Methodformat_ymd
Methodformat_ymd_short
Methodformat_ymd_xshort
Methodformat_iso_week
Methodformat_iso_week_short
Methodformat_week
Methodformat_week_short
Methodformat_month
Methodformat_month_short
Methodformat_iso_time
Methodformat_time
Methodformat_time_short
Methodformat_time_xshort
Methodformat_mtime
Methodformat_xtime
Methodformat_tod
Methodformat_todz
Methodformat_xtod
Methodformat_mod

string format_iso_ymd()
string format_ymd()
string format_ymd_short()
string format_ymd_xshort()
string format_iso_week()
string format_iso_week_short()
string format_week()
string format_week_short()
string format_month()
string format_month_short()
string format_iso_time()
string format_time()
string format_time_short()
string format_time_xshort()
string format_mtime()
string format_xtime()
string format_tod()
string format_todz()
string format_xtod()
string format_mod()

Description

Format the object into nice strings;

iso_ymd        "2000-06-02 (Jun) -W22-5 (Fri)" [2]
ext_ymd        "Friday, 2 June 2000" [2]
ymd            "2000-06-02"
ymd_short      "20000602"
ymd_xshort     "000602" [1]
iso_week       "2000-W22"
iso_week_short "2000W22"
week           "2000-w22" [2]
week_short     "2000w22" [2]
month          "2000-06"
month_short    "200006" [1]
iso_time       "2000-06-02 (Jun) -W22-5 (Fri) 00:00:00 UTC+1" [2]
ext_time       "Friday, 2 June 2000, 00:00:00" [2]
ctime          "Fri Jun  2 00:00:00 2000\n" [2] [3]
http           "Fri, 02 Jun 2000 00:00:00 GMT" [4]
time           "2000-06-02 00:00:00"
time_short     "20000602 00:00:00"
time_xshort    "000602 00:00:00"
iso_short      "2000-06-02T00:00:00"
mtime          "2000-06-02 00:00"
xtime          "2000-06-02 00:00:00.000000"
tod            "00:00:00"
tod_short      "000000"
todz           "00:00:00 CET"
todz_iso       "00:00:00 UTC+1"
xtod           "00:00:00.000000"
mod            "00:00"
[1] note conflict (think 1 February 2003)
[2] language dependent
[3] as from the libc function ctime()
[4] as specified by the HTTP standard; not language dependent.

The iso variants aim to be compliant with ISO-8601.


Methodfraction_no
Methodhour_no
Methodjulian_day
Methodleap_year
Methodminute_no
Methodmonth_day
Methodmonth_no
Methodsecond_no
Methodutc_offset
Methodweek_day
Methodweek_no
Methodyear_day
Methodyear_no
Methodmonth_name
Methodmonth_shortname
Methodmonth_day_name
Methodweek_day_name
Methodweek_day_shortname
Methodweek_name
Methodyear_name
Methodtzname
Methodtzname_iso
Methodunix_time

float fraction_no()
int hour_no()
int julian_day()
int leap_year()
int minute_no()
int month_day()
int month_no()
int second_no()
int utc_offset()
int week_day()
int week_no()
int year_day()
int year_no()
string month_name()
string month_shortname()
string month_day_name()
string week_day_name()
string week_day_shortname()
string week_name()
string year_name()
string tzname()
string tzname_iso()
int unix_time()

Description

Returns the unix time integer corresponding to the start of the time range object. (An unix time integer is UTC.)


Methodsecond
Methodminute
Methodseconds
Methodnumber_of_seconds
Methodminutes
Methodnumber_of_minutes
Methodhour
Methodhours
Methodnumber_of_hours

Second second()
Second second(intn)
Minute minute(inthour, intminute, intsecond)
array(Second) seconds()
array(Second) seconds(intfirst, intlast)
int number_of_seconds()
Minute minute()
Minute minute(intn)
Minute minute(inthour, intminute)
array(Minute) minutes()
array(Minute) minutes(intfirst, intlast)
int number_of_minutes()
Hour hour()
Hour hour(intn)
array(Hour) hours()
array(Hour) hours(intfirst, intlast)
int number_of_hours()


InheritTimeRange

inherit TimeRange : TimeRange


Methodnumber_of_days

int number_of_days()

Description

Get the number of days in the current range.

Class Calendar.YMD.Year

Description

This is the time period of a year.


Methodcreate

Calendar.YMD.YearCalendar.YMD.Year("unix", intunix_time)
Calendar.YMD.YearCalendar.YMD.Year("julian", int|floatjulian_day)
Calendar.YMD.YearCalendar.YMD.Year(intyear)
Calendar.YMD.YearCalendar.YMD.Year(stringyear)
Calendar.YMD.YearCalendar.YMD.Year(TimeRangerange)

Description

It's possible to create the standard year by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from the year number.


InheritTimeRange

inherit TimeRange : TimeRange


InheritYMD

inherit YMD : YMD


Methodmonth

Month month()
Month month(intn)
Month month(stringname)

Description

The Year type overloads the month() method, so it is possible to get a specified month by string:

year->month("April")

The integer and no argument behavior is inherited from YMD().


Methodweek

Week week()
Week week(intn)
Week week(stringname)

Description

The Year type overloads the week() method, so it is possible to get a specified week by name:

year->week("17")year->week("w17")

The integer and no argument behavior is inherited from YMD().

This is useful, since the first week of a year not always (about half the years, in the ISO calendar) is numbered '1'.

Module Charset

Description

The Charset module supports a wide variety of different character sets, and it is flexible in regard of the names of character sets it accepts. The character case is ignored, as are the most common non-alaphanumeric characters appearing in character set names. E.g. "iso-8859-1" works just as well as "ISO_8859_1". All encodings specified in RFC 1345 are supported.

First of all the Charset module is capable of handling the following encodings of Unicode:

  • utf7, utf8, utf16, utf16be, utf16le, utf32, utf32be, utf32le, utf75 and utf7½

    UTF encodings

  • shiftjis, euc-kr, euc-cn and euc-jp

Most, if not all, of the relevant code pages are represented, as the following list shows. Prefix the numbers as noted in the list to get the wanted codec:

  • 037, 038, 273, 274, 275, 277, 278, 280, 281, 284, 285, 290, 297, 367, 420, 423, 424, 437, 500, 819, 850, 851, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 868, 869, 870, 871, 880, 891, 903, 904, 905, 918, 932, 936, 950 and 1026

    These may be prefixed with "cp", "ibm" or "ms".

  • 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257 and 1258

    These may be prefixed with "cp", "ibm", "ms" or "windows"

  • mysql-latin1

    The default charset in MySQL, similar to cp1252.

+359 more.

Note

In Pike 7.8 and earlier this module was named Locale.Charset.


Methoddecode_error

voiddecode_error(stringerr_str, interr_pos, stringcharset, void|stringreason, void|mixed ... args)

Description

Throws a DecodeError exception. See DecodeError.create for details about the arguments. If args is given then the error reason is formatted using sprintf(reason, @args).


Methoddecoder

Decoderdecoder(stringname)

Description

Returns a charset decoder object.

Parameter name

The name of the character set to decode from. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC1345.

Throws

If the asked-for name was not supported, an error is thrown.


Methoddecoder_from_mib

Decoderdecoder_from_mib(intmib)

Description

Returns a decoder for the encoding schema denoted by MIB mib.


Methodencode_error

voidencode_error(stringerr_str, interr_pos, stringcharset, void|stringreason, void|mixed ... args)

Description

Throws an EncodeError exception. See EncodeError.create for details about the arguments. If args is given then the error reason is formatted using sprintf(reason, @args).


Methodencoder

Encoderencoder(stringname, string|voidreplacement, function(string:string)|voidrepcb)

Description

Returns a charset encoder object.

Parameter name

The name of the character set to encode to. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC1345.

Parameter replacement

The string to use for characters that cannot be represented in the charset. It's used when repcb is not given or when it returns zero. If no replacement string is given then an error is thrown instead.

Parameter repcb

A function to call for every character that cannot be represented in the charset. If specified it's called with one argument - a string containing the character in question. If it returns a string then that one will replace the character in the output. If it returns something else then the replacement argument will be used to decide what to do.

Throws

If the asked-for name was not supported, an error is thrown.


Methodencoder_from_mib

Encoderencoder_from_mib(intmib, string|voidreplacement, function(string:string)|voidrepcb)

Description

Returns an encoder for the encoding schema denoted by MIB mib.


Methodnormalize

stringnormalize(stringin)

Description

All character set names are normalized through this function before compared.


Methodset_decoder

voidset_decoder(stringname, Decoderdecoder)

Description

Adds a custom defined character set decoder. The name is normalized through the use of normalize.


Methodset_encoder

voidset_encoder(stringname, Encoderencoder)

Description

Adds a custom defined character set encoder. The name is normalized through the use of normalize.

Class Charset.DecodeError

Description

Error thrown when decode fails (and no replacement char or replacement callback has been registered).

FIXME

This error class is not actually used by this module yet - decode errors are still thrown as untyped error arrays. At this point it exists only for use by other modules.


Variablecharset

string Charset.DecodeError.charset

Description

The decoding charset, typically as known to Charset.decoder.

Note

Other code may produce errors of this type. In that case this name is something that Charset.decoder does not accept (unless it implements exactly the same charset), and it should be reasonably certain that Charset.decoder never accepts that name in the future (unless it is extended to implement exactly the same charset).


Variableerr_pos

int Charset.DecodeError.err_pos

Description

The failing position in err_str.


Variableerr_str

string Charset.DecodeError.err_str

Description

The string that failed to be decoded.


InheritGeneric

inherit Error.Generic : Generic

Class Charset.Decoder

Description

Virtual base class for charset decoders.

Example

string win1252_to_string( string data ) { return Charset.decoder("windows-1252")->feed( data )->drain(); }


Variablecharset

string Charset.Decoder.charset

Description

Name of the charset - giving this name to decoder returns an instance of the same class as this object.

Note

This is not necessarily the same name that was actually given to decoder to produce this object.


Methodclear

this_programclear()

Description

Clear buffers, and reset all state.

Returns

Returns the current object to allow for chaining of calls.


Methoddrain

stringdrain()

Description

Get the decoded data, and reset buffers.

Returns

Returns the decoded string.


Methodfeed

this_programfeed(strings)

Description

Feeds a string to the decoder.

Parameter s

String to be decoded.

Returns

Returns the current object, to allow for chaining of calls.

Class Charset.EncodeError

Description

Error thrown when encode fails (and no replacement char or replacement callback has been registered).

FIXME

This error class is not actually used by this module yet - encode errors are still thrown as untyped error arrays. At this point it exists only for use by other modules.


Variablecharset

string Charset.EncodeError.charset

Description

The encoding charset, typically as known to Charset.encoder.

Note

Other code may produce errors of this type. In that case this name is something that Charset.encoder does not accept (unless it implements exactly the same charset), and it should be reasonably certain that Charset.encoder never accepts that name in the future (unless it is extended to implement exactly the same charset).


Variableerr_pos

int Charset.EncodeError.err_pos

Description

The failing position in err_str.


Variableerr_str

string Charset.EncodeError.err_str

Description

The string that failed to be encoded.


InheritGeneric

inherit Error.Generic : Generic

Class Charset.Encoder

Description

Virtual base class for charset encoders.


Variablecharset

string Charset.Encoder.charset

Description

Name of the charset - giving this name to encoder returns an instance of the same class as this one.

Note

This is not necessarily the same name that was actually given to encoder to produce this object.


InheritDecoder

inherit Decoder : Decoder

Description

An encoder only differs from a decoder in that it has an extra function.


Methodset_replacement_callback

voidset_replacement_callback(function(string:string) rc)

Description

Change the replacement callback function.

Parameter rc

Function that is called to encode characters outside the current character encoding.

Module Charset.Tables

Module Charset.Tables.iso88591

Description

Codec for the ISO-8859-1 character encoding.

Module Colors


Methodcmyk_to_rgb

array(int(8bit)) cmyk_to_rgb(array(int(0..100)) cmyk)
array(int(8bit)) cmyk_to_rgb(int(0..100)c, int(0..100)m, int(0..100)y, int(0..100)k)

Description

This function return the RGB value of the color describe by the provided CMYK value. It is essentially calling Image.Color.cmyk(c,m,y,k)->rgb()

See also

Colors.rgb_to_cmyk()Image.Color.cmyk()


Methodcolor_name

stringcolor_name(array(int(8bit)) rgb)

Description

Tries to find a name to color described by the provided RGB values. Partially an inverse function to Colors.parse_color(), although it can not find all the names that Colors.parse_color() can find RGB values for. Returns the colors rgb hex value prepended with "#" upon failure.


Methodhsv_to_rgb

array(int(8bit)) hsv_to_rgb(array(int(8bit)) hsv)
array(int(8bit)) hsv_to_rgb(int(8bit)h, int(8bit)s, int(8bit)v)

Description

This function returns the RGB value of the color described by the provided HSV value. It is essentially calling Image.Color.hsv(h,s,v)->rgb().

See also

Colors.rgb_to_hsv()Image.Color.hsv()


Methodparse_color

array(int(8bit)) parse_color(stringname, void|array(int) def)

Description

This function returns the RGB values that corresponds to the color that is provided by name to the function. It is essentially calling Image.Color.guess(), but returns the default value (or black if none is provided) if it failes.


Methodrgb_to_cmyk

array(int(0..100)) rgb_to_cmyk(array(int(8bit)) rgb)
array(int(0..100)) rgb_to_cmyk(int(8bit)r, int(8bit)g, int(8bit)b)

Description

This function returns the CMYK value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->cmyk().

See also

Colors.cmyk_to_rgb()Image.Color.Color.cmyk()


Methodrgb_to_hsv

array(int(8bit)) rgb_to_hsv(array(int(8bit)) rgb)
array(int(8bit)) rgb_to_hsv(int(8bit)r, int(8bit)g, int(8bit)b)

Description

This function returns the HSV value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->hsv().

See also

Colors.hsv_to_rgb()Image.Color.Color.hsv()

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 Crypto

Description

Various cryptographic classes and functions.

Hash functions These are based on the Hash API; MD2, MD4, MD5, SHA1, SHA256.

Stream cipher functions These are based on the Cipher API; AES, Arcfour, Blowfish, CAST, DES, DES3, IDEA, Serpent, Twofish. The Substitution program is compatible with the CipherState. Also conforming to the API are the helper modules Buffer, CBC, GCM and Pipe.

As the cryptographic services offered from this module isn't necessarily used for security applications, none of the strings inputted or outputted are marked as secure. This is up to the caller.

Note

This module is only available if Pike has been compiled with Nettle enabled (this is the default).


VariableBuffer

__deprecated__program Crypto.Buffer

Description

This class has moved to submodules of the respective ciphers.


Methodmake_crypt_md5

string(8bit)make_crypt_md5(string(8bit)password, void|string(8bit)salt)

Description

Hashes a password together with a salt with the crypt_md5 algorithm and returns the result.

See also

verify_crypt_md5


Methodrot13

string(8bit)rot13(string(8bit)data)

Description

Convenience function that accesses the crypt function of a substitution object keyed to perform standard ROT13 (de)ciphering.


Methodverify_crypt_md5

boolverify_crypt_md5(string(8bit)password, string(7bit)hash)

Description

Verifies the password against the crypt_md5 hash.

Throws

May throw an exception if the hash value is bad.

See also

make_crypt_md5

Class Crypto.AE

Description

Abstract class for AE algorithms.


InheritAE

inherit __builtin.Nettle.AE : AE

Class Crypto.AEAD

Description

Abstract class for AEAD algorithms.


InheritAEAD

inherit Nettle.AEAD : AEAD

Class Crypto.BlockCipher

Description

Abstract class for block cipher algorithms. Contains some tools useful for all block ciphers.

Contains the CBC submodule.


InheritBlockCipher

inherit Nettle.BlockCipher : BlockCipher

Class Crypto.BlockCipher16

Description

Abstract class for block cipher algorithms with a 16 byte block size. Contains some tools useful for all such block ciphers.

Contains the GCM submodule.


InheritBlockCipher16

inherit Nettle.BlockCipher16 : BlockCipher16

Class Crypto.Buffer

Description

This class has moved to submodules of the respective ciphers.

Deprecated

Replaced by BlockCipher.Buffer.


Methodcreate

Crypto.BufferCrypto.Buffer(CipherState|programfun, mixed ... args)

Class Crypto.BufferedCipher

Description

Abstract class for block cipher meta algorithms.

Contains the Buffer submodule.


InheritBufferedCipher

inherit Nettle.BufferedCipher : BufferedCipher

Class Crypto.CBC

Description

This class has moved to submodules of the respective ciphers.

Deprecated

Replaced by BlockCipher.CBC.


Methodcreate

Crypto.CBCCrypto.CBC(CipherState|programfun, mixed ... args)

Class Crypto.Cipher

Description

Abstract class for crypto algorithms. Contains some tools useful for all ciphers.

Note

Typically only inherited directly by stream ciphers.

Note

It is however convenient for typing as it contains the minimum base level API for a cipher.

See also

BufferedCipher, BlockCipher, BlockCipher16


InheritCipher

inherit Nettle.Cipher : Cipher

Class Crypto.HMAC

Description

HMAC, defined by RFC-2104


Method`()

Crypto.MAC.State res = Crypto.HMAC()()

Description

Calling the HMAC object with a password returns a new object that can perform the actual HMAC hashing. E.g. doing a HMAC hash with MD5 and the password "bar" of the string "foo" would require the code Crypto.HMAC(Crypto.MD5)("bar")("foo").


Methodcreate

Crypto.HMACCrypto.HMAC(.Hashh, int|voidb)

Parameter h

The hash object on which the HMAC object should base its operations. Typical input is Crypto.MD5.

Parameter b

The block size of one compression block, in octets. Defaults to block_size() of h.


Methodpkcs_digest

string(8bit)pkcs_digest(string(8bit)s)

Description

Makes a PKCS-1 digestinfo block with the message s.

See also

Standards.PKCS.Signature.build_digestinfo


Methodraw_hash

string(8bit)raw_hash(string(8bit)s)

Description

Calls the hash function given to create and returns the hash value of s.

Class Crypto.Hash

Description

Abstract class for hash algorithms. Contains some tools useful for all hashes.


InheritHash

inherit Nettle.Hash : Hash

Class Crypto.MAC

Description

Abstract class for Message Authentication Code (MAC) algorithms. Contains some tools useful for all MACs.


InheritMAC

inherit Nettle.MAC : MAC

Class Crypto.Pipe

Description

A wrapper class that connects several cipher algorithms into one algorithm. E.g. triple DES can be emulated with Crypto.Pipe(Crypto.DES, Crypto.DES, Crypto.DES).

Class Crypto.Sign

Description

Abstract class for signature algorithms. Contains some tools useful for all signatures.


Method`()

State res = Crypto.Sign()()

Description

Calling `() will return a State object.


Methodname

string(7bit)name()

Description

Returns the printable name of the signing algorithm.

Class Crypto.Substitution

Description

Implements a simple substitution crypto, ie. one of the first crypto systems ever invented and thus one of the least secure ones available.


Methoddecrypt

string(8bit)decrypt(string(8bit)c)

Description

Decrypts the cryptogram c.


Methodencrypt

string(8bit)encrypt(string(8bit)m)

Description

Encrypts the message m.


Methodfilter

stringfilter(stringm, void|multiset(int) save)

Description

Removes characters not in the encryption key or in the save multiset from the message m.


Methodset_ACA_K1_key

this_programset_ACA_K1_key(stringkey, void|intoffset, void|array(string) alphabet)

Description

Sets the key according to ACA K1 key generation. The plaintext alphabet is prepended with a keyword key that shifts the alphabet positions compared to the cryptogram alphabet. The plaintext alphabet is then reduced with the characters in the keyword. It is also optionally rotated offset number of steps.


Methodset_ACA_K2_key

this_programset_ACA_K2_key(stringkey, void|intoffset, void|array(string) alphabet)

Description

Sets the key according to ACA K2 key generation. The cryptogram alphabet is prepended with a keyword key that shifts the alphabet positions compared to the plaintext alphabet. The cryptogram alphabet is then reduced with the characters in the keyword. It is als optionally reotated offset number of steps.


Methodset_ACA_K3_key

this_programset_ACA_K3_key(stringkey, intoffset, void|array(string) alphabet)

Description

Sets the key according to ACA K3 key generation. Both the plaintext and the cryptogram alphabets are prepended with a keyword key, which characters are removed from the rest of the alphabet. The plaintext alphabet is then rotated offset number of steps.


Methodset_ACA_K4_key

this_programset_ACA_K4_key(stringkey1, stringkey2, void|intoffset, void|array(string) alphabet)

Description

Sets the key according to ACA K4 key generation. Both the plaintext and the cryptogram alphabets are prepended with the keywords key1 and key2. The plaintext alphabet is then rotated offset number of steps.


Methodset_key

this_programset_key(mapping(string:string|array(string)) key)

Description

Sets the encryption and decryption key. The decryption key is derived from the encryption key by reversing the mapping. If one index maps to an array of strings, one element from the array will be chosen at random in such substitution.

Throws

An error is thrown if the encryption key can not be made reversible.


Methodset_null_chars

this_programset_null_chars(int|floatp, array(string) chars)

Description

Set null characters (fillers). Characters from chars will be inserted into the output stream with a probability p.

Parameter p

A float between 0.0 and 1.0 or an integer between 0 and 100.

Parameter chars

An array of one character strings.


Methodset_rot_key

this_programset_rot_key(void|intsteps, void|array(string) alphabet)

Description

Sets the key to a ROT substitution system. steps defaults to 13 and alphabet defaults to A-Z, i.e. this function defaults to set the substitution crypto to be ROT13. If no alphabet is given the key will be case insensitive, e.g. the key will really be two ROT13 alphabets, one a-z and one A-Z, used simultaneously.

Module Crypto.AES

Description

AES (American Encryption Standard) is a quite new block cipher, specified by NIST as a replacement for the older DES standard. The standard is the result of a competition between cipher designers. The winning design, also known as RIJNDAEL, was constructed by Joan Daemen and Vincent Rijnmen.

Like all the AES candidates, the winning design uses a block size of 128 bits, or 16 octets, and variable key-size, 128, 192 and 256 bits (16, 24 and 32 octets) being the allowed key sizes. It does not have any weak keys.


InheritAES

inherit Nettle.AES : AES

Module Crypto.AES.POLY1305


Method`()

State`()(string(8bit)password)

Description

Get a POLY1305 State object initialized with a password.


InheritPOLY1305_AES

inherit Nettle.POLY1305_AES : POLY1305_AES

Module Crypto.AES.UMAC128

Description

UMAC is a familty of message digest functions based on universal hashing and AES that is specified in RFC 4418. They differ mainly in the size of the resulting digest.

UMAC128 outputs a digest of 128 bits or 16 octets.

See also

UMAC32, UMAC64, UMAC96


Method`()

State`()(string(8bit)password)

Description

Get a UMAC128 State object initialized with a password.


InheritUMAC128_AES

inherit Nettle.UMAC128_AES : UMAC128_AES

Module Crypto.AES.UMAC32

Description

UMAC is a familty of message digest functions based on universal hashing and AES that is specified in RFC 4418. They differ mainly in the size of the resulting digest.

UMAC32 outputs a digest of 32 bits or 4 octets.

See also

UMAC64, UMAC96, UMAC128


Method`()

State`()(string(8bit)password)

Description

Get a UMAC32 State object initialized with a password.


InheritUMAC32_AES

inherit Nettle.UMAC32_AES : UMAC32_AES

Module Crypto.AES.UMAC64

Description

UMAC is a familty of message digest functions based on universal hashing and AES that is specified in RFC 4418. They differ mainly in the size of the resulting digest.

UMAC64 outputs a digest of 64 bits or 8 octets.

See also

UMAC32, UMAC96, UMAC128


Method`()

State`()(string(8bit)password)

Description

Get a UMAC64 State object initialized with a password.


InheritUMAC64_AES

inherit Nettle.UMAC64_AES : UMAC64_AES

Module Crypto.AES.UMAC96

Description

UMAC is a familty of message digest functions based on universal hashing and AES that is specified in RFC 4418. They differ mainly in the size of the resulting digest.

UMAC96 outputs a digest of 96 bits or 12 octets.

See also

UMAC32, UMAC64, UMAC128


Method`()

State`()(string(8bit)password)

Description

Get a UMAC96 State object initialized with a password.


InheritUMAC96_AES

inherit Nettle.UMAC96_AES : UMAC96_AES

Module Crypto.Arcfour

Description

Arcfour is a stream cipher, also known under the trade marked name RC4, and it is one of the fastest ciphers around. A problem is that the key setup of Arcfour is quite weak, you should never use keys with structure, keys that are ordinary passwords, or sequences of keys like "secret:1", "secret:2", ..... If you have keys that don't look like random bit strings, and you want to use Arcfour, always hash the key before feeding it to Arcfour.


InheritARCFOUR

inherit Nettle.ARCFOUR : ARCFOUR

Module Crypto.Arctwo

Description

Arctwo is a block cipher, also known under the trade marked name RC2.

The cipher is quite weak, and should not be used for new software.


InheritARCTWO

inherit Nettle.ARCTWO : ARCTWO

Module Crypto.Blowfish

Description

BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block size of 64 bits (8 octets), and a variable key size, up to 448 bits. It has some weak keys.


InheritBLOWFISH

inherit Nettle.BLOWFISH : BLOWFISH

Module Crypto.CAST

Description

CAST-128 is a block cipher, specified in RFC 2144. It uses a 64 bit (8 octets) block size, and a variable key size of up to 128 bits.


InheritCAST128

inherit Nettle.CAST128 : CAST128

Module Crypto.Camellia

Description

The Camellia 128-bit block cipher.


InheritCAMELLIA

inherit Nettle.CAMELLIA : CAMELLIA

Module Crypto.ChaCha20

Description

ChaCha20 is a stream cipher by D. J. Bernstein.

Note

This module is not available in all versions of Nettle.


InheritCHACHA

inherit Nettle.CHACHA : CHACHA

Module Crypto.ChaCha20.POLY1305

Description

This is an AEAD cipher consisting of the CHACHA cipher and a MAC based on the POLY1305 algorithm.

Note

Note that this is an AEAD cipher, while AES.POLY1305 (aka POLY1305-AES) is a MAC.

Note

Note also that the POLY1305 algorithm used here is NOT identical to the one in the AES.POLY1305MAC. The iv/nonce handling differs.

Note

This module is not available in all versions of Nettle.


InheritCHACHA_POLY1305

inherit Nettle.CHACHA_POLY1305 : CHACHA_POLY1305

Module Crypto.DES

Description

DES is the old Data Encryption Standard, specified by NIST. It uses a block size of 64 bits (8 octets), and a key size of 56 bits. However, the key bits are distributed over 8 octets, where the least significant bit of each octet is used for parity. A common way to use DES is to generate 8 random octets in some way, then set the least significant bit of each octet to get odd parity, and initialize DES with the resulting key.

The key size of DES is so small that keys can be found by brute force, using specialized hardware or lots of ordinary work stations in parallel. One shouldn't be using plain DES at all today, if one uses DES at all one should be using DES3 or "triple DES".

DES also has some weak keys.


InheritDES

inherit Nettle.DES : DES

Module Crypto.DES3

Description

The inadequate key size of DES has already been mentioned. One way to increase the key size is to pipe together several DES boxes with independent keys. It turns out that using two DES ciphers is not as secure as one might think, even if the key size of the combination is a respectable 112 bits.

The standard way to increase DES's key size is to use three DES boxes. The mode of operation is a little peculiar: the middle DES box is wired in the reverse direction. To encrypt a block with DES3, you encrypt it using the first 56 bits of the key, then decrypt it using the middle 56 bits of the key, and finally encrypt it again using the last 56 bits of the key. This is known as "ede" triple-DES, for "encrypt-decrypt-encrypt".

The "ede" construction provides some backward compatibility, as you get plain single DES simply by feeding the same key to all three boxes. That should help keeping down the gate count, and the price, of hardware circuits implementing both plain DES and DES3.

DES3 has a key size of 168 bits, but just like plain DES, useless parity bits are inserted, so that keys are represented as 24 octets (192 bits). As a 112 bit key is large enough to make brute force attacks impractical, some applications uses a "two-key" variant of triple-DES. In this mode, the same key bits are used for the first and the last DES box in the pipe, while the middle box is keyed independently. The two-key variant is believed to be secure, i.e. there are no known attacks significantly better than brute force.


InheritDES3

inherit Nettle.DES3 : DES3

Module Crypto.DH

Description

Diffie-Hellman key-exchange related stuff.


VariableFFDHE2048

Parameters Crypto.DH.FFDHE2048

Description

Finite Field Diffie-Hellman 2048

From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.1.


VariableFFDHE2432

Parameters Crypto.DH.FFDHE2432

Description

Finite Field Diffie-Hellman 2432

From Negotiated FF-DHE for TLS draft 03, November 2014, Appendix A.1.


VariableFFDHE3072

Parameters Crypto.DH.FFDHE3072

Description

Finite Field Diffie-Hellman 3072

From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.2.


VariableFFDHE4096

Parameters Crypto.DH.FFDHE4096

Description

Finite Field Diffie-Hellman 4096

From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.3.


VariableFFDHE6144

Parameters Crypto.DH.FFDHE6144

Description

Finite Field Diffie-Hellman 6144

From Negotiated FF-DHE for TLS draft 02, October 2014, Appendix A.4.


VariableFFDHE8192

Parameters Crypto.DH.FFDHE8192

Description

Finite Field Diffie-Hellman 8192

From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.4.


VariableMODPGroup1

Parameters Crypto.DH.MODPGroup1

Description

MODP Group 1 (768 bit) (aka First Oakley Group (aka ORM96 group 1)).

RFC 2409 6.1

Note

Not allowed for use with FIPS 140.


VariableMODPGroup14

Parameters Crypto.DH.MODPGroup14

Description

MODP Group 14 (2048 bit).

RFC 3526 3


VariableMODPGroup15

Parameters Crypto.DH.MODPGroup15

Description

MODP Group 15 (3072 bit).

RFC 3526 3


VariableMODPGroup16

Parameters Crypto.DH.MODPGroup16

Description

MODP Group 16 (4096 bit).

RFC 3526 5


VariableMODPGroup17

Parameters Crypto.DH.MODPGroup17

Description

MODP Group 17 (6144 bit).

RFC 3526 6


VariableMODPGroup18

Parameters Crypto.DH.MODPGroup18

Description

MODP Group 18 (8192 bit).

RFC 3526 7


VariableMODPGroup2

Parameters Crypto.DH.MODPGroup2

Description

MODP Group 2 (1024 bit) (aka Second Oakley Group (aka ORM96 group 2)).

RFC 2409 6.2

Note

Not allowed for use with FIPS 140.


VariableMODPGroup22

Parameters Crypto.DH.MODPGroup22

Description

MODP Group 22 (1024-bit with 160-bit Subgroup).

RFC 5114 2.1


VariableMODPGroup23

Parameters Crypto.DH.MODPGroup23

Description

MODP Group 23 (2048-bit with 224-bit Subgroup).

RFC 5114 2.2


VariableMODPGroup24

Parameters Crypto.DH.MODPGroup24

Description

MODP Group 24 (2048-bit with 256-bit Subgroup).

RFC 5114 2.3


VariableMODPGroup5

Parameters Crypto.DH.MODPGroup5

Description

MODP Group 5 (1536 bit).

RFC 3526 2

Note

Not allowed for use with FIPS 140.

Class Crypto.DH.Parameters

Description

Diffie-Hellman parameters.


Methodcreate

Crypto.DH.ParametersCrypto.DH.Parameters(this_programother)

Description

Initialize the set of Diffie-Hellman parameters.

Parameter other

Copy the parameters from this object.


Methodcreate

Crypto.DH.ParametersCrypto.DH.Parameters(Crypto.DSA.Statedsa)

Description

Initialize the set of Diffie-Hellman parameters.

Parameter dsa

Copy the parameters from this object.


Methodcreate

Crypto.DH.ParametersCrypto.DH.Parameters(Gmp.mpz|intp, Gmp.mpz|int|voidg, Gmp.mpz|int|voidq)

Description

Initialize the set of Diffie-Hellman parameters.

Parameter p

The prime for the group.

Parameter g

The generator for the group. Defaults to 2.

Parameter q

The order of the group. Defaults to (p-1)/2.


Variableg

Gmp.mpz Crypto.DH.Parameters.g

Description

Generator.


Methodgenerate_keypair

array(Gmp.mpz) generate_keypair(function(int(0..):string(8bit)) rnd)

Description

Generate a Diffie-Hellman key pair.

Returns

Returns the following array:

Array
Gmp.mpz0

The generated public key.

Gmp.mpz1

The corresponding private key.


InheritDH_Params

inherit Nettle.DH_Params : DH_Params


Variableorder

__deprecated__Gmp.mpz Crypto.DH.Parameters.order

Description

Alias for q.

Deprecated

Replaced by q.


Variablep

Gmp.mpz Crypto.DH.Parameters.p

Description

Prime.


Variableq

Gmp.mpz Crypto.DH.Parameters.q

Description

Subgroup size.


Methodvalidate

boolvalidate(int(0..)effort)

Description

Validate that the DH Parameters doesn't have obvious security weaknesses. It will first attempt to verify the prime p using Donald Knuth's probabilistic primality test with provided effort. This has a chance of pow(0.25,effort) to produce a false positive. An effort of 0 skipps this step. The second test verifies that g is of high order.

Module Crypto.DSA

Description

The Digital Signature Algorithm DSA is part of the NIST Digital Signature Standard DSS, FIPS-186 (1993).


Method`()

protectedState`()()

Description

Calling `() will return a State object.


InheritSign

inherit Crypto.Sign : Sign


Methodname

string(8bit)name()

Description

Returns the string "DSA".

Class Crypto.DSA.State


Method_equal

boolequal(Crypto.DSA.Statefrom, mixedother)

Description

Compares the keys of this DSA object with something other.


Methodgenerate_key

variantthis_programgenerate_key()

Description

Generates a public/private key pair. Needs the public parameters p, q and g set, either through set_public_key or generate_key(int,int).


Methodgenerate_key

variantthis_programgenerate_key(intp_bits, intq_bits)

Description

Generates DSA parameters (p, q, g) and key (x, y). Depending on Nettle version q_bits can be 160, 224 and 256 bits. 160 works for all versions.


Methodget_g

Gmp.mpzget_g()

Description

Returns the DSA generator (g).


Methodget_p

Gmp.mpzget_p()

Description

Returns the DSA modulo (p).


Methodget_q

Gmp.mpzget_q()

Description

Returns the DSA group order (q).


Methodget_x

Gmp.mpzget_x()

Description

Returns the DSA private key (x).


Methodget_y

Gmp.mpzget_y()

Description

Returns the DSA public key (y).


Methodhash

Gmp.mpzhash(string(8bit)msg, .Hashh)

Description

Makes a DSA hash of the messge msg.


Inheritthis_program

inherit ::this_program : this_program


Methodname

string(8bit)name()

Description

Returns the string "DSA".


Methodpkcs_algorithm_identifier

Sequencepkcs_algorithm_identifier()

Description

Returns the AlgorithmIdentifier as defined in RFC5280 section 4.1.1.2 including the DSA parameters.


Methodpkcs_public_key

Sequencepkcs_public_key()

Description

Creates a SubjectPublicKeyInfo ASN.1 sequence for the object. See RFC 5280 section 4.1.2.7.


Methodpkcs_sign

string(8bit)pkcs_sign(string(8bit)message, .Hashh)

Description

Signs the message with a PKCS-1 signature using hash algorithm h.


Methodpkcs_signature_algorithm_id

Sequencepkcs_signature_algorithm_id(.Hashhash)

Description

Returns the PKCS-1 algorithm identifier for DSA and the provided hash algorithm. Only SHA1 supported.


Methodpkcs_verify

boolpkcs_verify(string(8bit)message, .Hashh, string(8bit)sign)

Description

Verify PKCS-1 signature sign of message message using hash algorithm h.


Methodpublic_key_equal

boolpublic_key_equal(this_programdsa)

Description

Compares the public key in this object with that in the provided DSA object.


Methodraw_sign

array(Gmp.mpz) raw_sign(Gmp.mpzh, void|Gmp.mpzk)

Description

Sign the message h. Returns the signature as two Gmp.mpz objects.


Methodraw_verify

boolraw_verify(Gmp.mpzh, Gmp.mpzr, Gmp.mpzs)

Description

Verify the signature r,s against the message h.


Methodset_private_key

this_programset_private_key(Gmp.mpzsecret)

Description

Sets the private key, the x parameter, in this DSA object.


Methodset_public_key

this_programset_public_key(Gmp.mpzmodulo, Gmp.mpzorder, Gmp.mpzgenerator, Gmp.mpzkey)

Description

Sets the public key in this DSA object.

Parameter modulo

This is the p parameter.

Parameter order

This is the group order q parameter.

Parameter generator

This is the g parameter.

Parameter kye

This is the public key y parameter.


Methodset_random

this_programset_random(function(int(0..):string(8bit)) r)

Description

Sets the random function, used to generate keys and parameters, to the function r. Default is Crypto.Random.random_string.


Methodsign_rsaref

__deprecated__string(8bit)sign_rsaref(string(8bit)msg)

Description

Make a RSA ref signature of message msg.


Methodsign_ssl

__deprecated__string(8bit)sign_ssl(string(8bit)msg)

Description

Make an SSL signature of message msg.


Methodverify_rsaref

__deprecated__boolverify_rsaref(string(8bit)msg, string(8bit)s)

Description

Verify a RSA ref signature s of message msg.


Methodverify_ssl

__deprecated__boolverify_ssl(string(8bit)msg, string(8bit)s)

Description

Verify an SSL signature s of message msg.

Module Crypto.ECC

Description

Elliptic Curve Cipher Constants.

This module contains constants used with elliptic curve algorithms.

Class Crypto.ECC.Curve

Description

The definition of an elliptic curve.

Objects of this class are typically not created by the user.

See also

SECP_192R1, SECP_224R1, SECP_256R1, SECP_384R1, SECP_521R1


InheritECC_Curve

inherit Nettle.ECC_Curve : ECC_Curve


Methodpkcs_algorithm_identifier

Sequencepkcs_algorithm_identifier()

Description

Returns the AlgorithmIdentifier as defined in RFC5480 section 2.


Methodpkcs_ec_parameters

Identifierpkcs_ec_parameters()

Description

Returns the PKCS-1 elliptic curve parameters for the curve. cf RFC 5480 2.1.1.


Methodpkcs_named_curve_id

Identifierpkcs_named_curve_id()

Description

Returns the PKCS-1 elliptic curve identifier for the curve. cf RFC 5480 2.1.1.

Class Crypto.ECC.Curve.ECDSA

Description

Elliptic Curve Digital Signing Algorithm


Method_equal

boolequal(Crypto.ECC.Curve.ECDSAfrom, mixedother)

Description

Compares the keys of this ECDSA object with something other.


Methodgenerate_key

this_programgenerate_key()

Description

Generate a new set of private and public keys on the current curve.


Methodget_curve

Curveget_curve()

Description

Return the curve.


Methodget_public_key

string(8bit)get_public_key()

Description

Get the ANSI x9.62 4.3.6 encoded uncompressed public key.


InheritECDSA

inherit ECC_Curve::ECDSA : ECDSA


Methodjose_decode

array(mapping(string(7bit):string(7bit)|int)|string(8bit)) jose_decode(string(7bit)jws)

Description

Verify and decode a JOSE JWS ECDSA signed value.

Parameter jws

A JSON Web Signature as returned by jose_sign().

Returns

Returns 0 (zero) on failure, and an array

Array
mapping(string(7bit):string(7bit)|int) 0

The JOSE header.

string(8bit)1

The signed message.

See also

pkcs_verify(), RFC 7515 section 3.5


Methodjose_sign

string(7bit)jose_sign(string(8bit)message, .Hash|voidh, mapping(string(7bit):string(7bit)|int)|voidheaders)

Description

Signs the message with a JOSE JWS ECDSA signature using hash algorithm h.

Parameter message

Message to sign.

Parameter h

Hash algorithm to use.

Returns

Returns the signature on success, and 0 (zero) on failure.

See also

pkcs_verify(), salt_size(), RFC 7515


Methodjwa

string(7bit)jwa(.Hashhash)

Description

Get the JWS algorithm identifier for a hash.

Returns

Returns 0 (zero) on failure.

See also

RFC 7518 section 3.1


Methodkey_size

int(0..)key_size()

Description

Return the size of the private key in bits.


Methodpkcs_algorithm_identifier

Sequencepkcs_algorithm_identifier()

Description

Returns the AlgorithmIdentifier as defined in RFC5480 section 2.1.1 including the ECDSA parameters.


Methodpkcs_public_key

Sequencepkcs_public_key()

Description

Creates a SubjectPublicKeyInfo ASN.1 sequence for the object. See RFC 5280 section 4.1.2.7.


Methodpkcs_sign

string(8bit)pkcs_sign(string(8bit)message, .Hashh)

Description

Signs the message with a PKCS-1 signature using hash algorithm h.


Methodpkcs_signature_algorithm_id

Sequencepkcs_signature_algorithm_id(.Hashhash)

Description

Returns the PKCS-1 algorithm identifier for ECDSA and the provided hash algorithm. Only SHA-1 and SHA-2 based hashes are supported currently.


Methodpkcs_verify

boolpkcs_verify(string(8bit)message, .Hashh, string(8bit)sign)

Description

Verify PKCS-1 signature sign of message message using hash algorithm h.


Methodpublic_key_equal

boolpublic_key_equal(this_programecdsa)

Description

Compares the public key in this object with that in the provided ECDSA object.


Methodset_private_key

this_programset_private_key(Gmp.mpz|intk)

Description

Set the private key.

Note

Throws errors if the key isn't valid for the curve.


Methodset_public_key

this_programset_public_key(Gmp.mpz|intx, Gmp.mpz|inty)

Description

Change to the selected point on the curve as public key.

Note

Throws errors if the point isn't on the curve.


Methodset_public_key

variantthis_programset_public_key(string(8bit)key)

Description

Change to the selected point on the curve as public key.

Parameter key

The public key encoded according to ANSI x9.62 4.3.6.

Note

Throws errors if the point isn't on the curve.


Methodset_random

this_programset_random(function(int:string(8bit)) r)

Description

Set the random function, used to generate keys and parameters, to the function r.


Methodsize

intsize()

Description

Return the curve size in bits.

Module Crypto.ECC.SECP_192R1


InheritCurve

inherit Curve : Curve

Module Crypto.ECC.SECP_224R1


InheritCurve

inherit Curve : Curve

Module Crypto.ECC.SECP_256R1


InheritCurve

inherit Curve : Curve

Module Crypto.ECC.SECP_384R1


InheritCurve

inherit Curve : Curve

Module Crypto.ECC.SECP_521R1


InheritCurve

inherit Curve : Curve

Module Crypto.GOST94

Description

The GOST94 or GOST R 34.11-94 hash algorithm is a Soviet-era algorithm used in Russian government standards, defined in RFC 4357.


InheritGOST94

inherit Nettle.GOST94 : GOST94

Module Crypto.IDEA

Description

The IDEA(tm) block cipher is covered by patents held by ETH and a Swiss company called Ascom-Tech AG. The Swiss patent number is PCT/CH91/00117, the European patent number is EP 0 482 154 B1, and the U.S. patent number is US005214703. IDEA(tm) is a trademark of Ascom-Tech AG. There is no license fee required for noncommercial use.


InheritIDEA

inherit Nettle.IDEA : IDEA

Module Crypto.Koremutake

Description

Quote from Koremutake home page http://shorl.com/koremutake:

In an attempt to temporarily solve the fact that human beings seem to be inable to remember important things (such as their names, car keys and seemingly random numbers with fourteen digits in 'em), we invented Koremutake.

It is, in plain language, a way to express any large number as a sequence of syllables. The general idea is that word-sounding pieces of information are a lot easier to remember than a sequence of digits.


Methoddecrypt

intdecrypt(stringc)

Description

Decode a koremutake string into an integer.


Methodencrypt

stringencrypt(intm)

Description

Encode an integer as a koremutake string.

Module Crypto.MD2

Description

MD2 is a message digest function constructed by Burton Kaliski, and is described in RFC 1319. It outputs message digests of 128 bits, or 16 octets.


InheritMD2

inherit Nettle.MD2 : MD2

Module Crypto.MD4

Description

MD4 is a message digest function constructed by Ronald Rivest, and is described in RFC 1320. It outputs message digests of 128 bits, or 16 octets.


InheritMD4

inherit Nettle.MD4 : MD4

Module Crypto.MD5

Description

MD5 is a message digest function constructed by Ronald Rivest, and is described in RFC 1321. It outputs message digests of 128 bits, or 16 octets.


Methodcrypt_hash

string(7bit)crypt_hash(string(8bit)password, string(7bit)salt, int|voidrounds)

Description

This is a convenience alias for Nettle.crypt_md5(), that uses the same API as the other hashes.

Note

The rounds parameter is currently ignored. For forward compatibility, either leave out, or specify as 1000.

See also

Nettle.Hash()->crypt_hash(), crypt_md5()


InheritMD5

inherit Nettle.MD5 : MD5

Module Crypto.NT

Class Crypto.NT.CryptContext

Description

Class representing an HCRYPTPROV handle.


Methodcreate

Crypto.NT.CryptContextCrypto.NT.CryptContext(string(8bit)name, string(8bit)csp, inttype, intflags)

Parameter name

Key container name. When flags is set to CRYPT_VERIFYCONTEXT the name must be 0.

Parameter csp

The name of the Crypto Service Provider to use. If set to 0 the user default CSP will be used.


Methodread

string(8bit)read(intsize, string(8bit)|voidinit)

Description

Retreive some random data. Calls CryptGenRandom in the NT API.

Module Crypto.None

Description

The plaintext algorithm.

This modules implements several of the crypto APIs, but without any crypto. It is intended to be used for testing of higher level algorithms.


InheritAE

inherit .AE : AE

Description

Implements the empty AE algorithm.


InheritMAC

inherit .MAC : MAC

Description

Implements the empty MAC algorithm.


Constantmac_jwa_id

protected constantstring Crypto.None.mac_jwa_id

Description

Implements the "none" JWS algorithm.

Module Crypto.PGP

Description

PGP stuff. See RFC 4880.


Methoddecode

mapping(string:string|mapping) decode(strings)

Description

Decodes PGP data.


Methoddecode_radix64

mapping(string:mixed) decode_radix64(stringdata)

Description

Decode ASCII armour.


Methodencode_radix64

stringencode_radix64(stringdata, stringtype, void|mapping(string:string) extra)

Description

Encode PGP data with ASCII armour.


Methodverify_signature

intverify_signature(stringtext, stringsig, stringpubkey)

Description

Verify text against signature sig with the public key pubkey.

Module Crypto.Password

Description

Password handling.

This module handles generation and verification of password hashes.

See also

verify(), hash(), crypt()


Methodhash

string(7bit)hash(string(8bit)password, string(7bit)|voidscheme, int|voidrounds)

Description

Generate a hash of password suitable for verify().

Parameter password

Password to hash.

Parameter scheme

Password hashing scheme. If not specified the strongest available will be used.

If an unsupported scheme is specified an error will be thrown.

Supported schemes are:

Crypt(3C)-style:

UNDEFINED

Use the strongest crypt(3C)-style hash that is supported.

"crypt"
"{crypt}"
"6"

SHA512.crypt_hash() with 96 bits of salt and a default of 5000 rounds.

"$6$"
"5"

SHA256.crypt_hash() with 96 bits of salt and a default of 5000 rounds.

"$5$"
"1"

MD5.crypt_hash() with 48 bits of salt and 1000 rounds.

"$1$"
""

predef::crypt() with 12 bits of salt.

LDAP (RFC2307)-style. Don't use these if you can avoid it, since they are suspectible to attacks. In particular avoid the unsalted variants at all costs:

"ssha"

SHA1.hash() with 96 bits of salt appended to the password.

"{ssha}"
"smd5"

MD5.hash() with 96 bits of salt appended to the password.

"{smd5}"
"sha"

SHA1.hash() without any salt.

"{sha}"
"md5"

MD5.hash() without any salt.

"{md5}"
Parameter rounds

The number of rounds to use in parameterized schemes. If not specified the scheme specific default will be used.

Returns

Returns a string suitable for verify(). This means that the hashes will be prepended with the suitable markers.

Note

Note that the availability of SHA512 depends on the version of Nettle that Pike has been compiled with.

Note

This function was added in Pike 7.8.755.

See also

verify(), predef::crypt(), Nettle.crypt_md5(), Nettle.Hash()->crypt_hash()


Methodverify

intverify(string(8bit)password, string(8bit)hash)

Description

Verify a password against a hash.

This function attempts to support most common password hashing schemes. The hash can be on any of the following formats.

LDAP-style (RFC2307) hashes:

"{SHA}XXXXXXXXXXXXXXXXXXXXXXXXXXXX"

The XXX string is taken to be a MIME.encode_base64SHA1 hash of the password. Source: OpenLDAP FAQ http://www.openldap.org/faq/data/cache/347.html.

"{SSHA}XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

The XXX string is taken to be a MIME.encode_base64 string in which the first 20 chars are an SHA1 hash and the remaining chars the salt. The input for the hash is the password concatenated with the salt. Source: OpenLDAP FAQ http://www.openldap.org/faq/data/cache/347.html.

"{MD5}XXXXXXXXXXXXXXXXXXXXXXXX"

The XXX string is taken to be a MIME.encode_base64MD5 hash of the password. Source: OpenLDAP FAQ http://www.openldap.org/faq/data/cache/418.html.

"{SMD5}XXXXXXXXXXXXXXXXXXXXXXXXXXXX"

The XXX string is taken to be a MIME.encode_base64 string in which the first 16 chars are an MD5 hash and the remaining chars the salt. The input for the hash is the password concatenated with the salt. Source: OpenLDAP FAQ http://www.openldap.org/faq/data/cache/418.html.

"{CRYPT}XXXXXXXXXXXXX"

The XX string is taken to be a crypt(3C)-style hash. This is the same thing as passing the XXX string without any preceding method name within {...}. I.e. it's interpreted according to the crypt-style hashes below.

Crypt-style hashes:

"$6$SSSSSSSSSSSSSSSS$XXXXXXXXXXXXXXXXXXXXXX"

The string is interpreted according to the "Unix crypt using SHA-256 and SHA-512" standard Version 0.4 2008-4-3, where SSSSSSSSSSSSSSSS is up to 16 characters of salt, and the string XXX the result of SHA512.crypt_hash() with 5000 rounds. Source: Unix crypt using SHA-256 and SHA-512 http://www.akkadia.org/drepper/SHA-crypt.txt

"$6$rounds=RR$SSSSSSSSSSSSSSSS$XXXXXXXXXXXXXXXXXXXXXX"

This is the same algorithm as the one above, but with the number of rounds specified by RR in decimal. Note that the number of rounds is clamped to be within 1000 and 999999999 (inclusive). Source: Unix crypt using SHA-256 and SHA-512 http://www.akkadia.org/drepper/SHA-crypt.txt

"$5$SSSSSSSSSSSSSSSS$XXXXXXXXXXXXXXXXXXXXXX"

The string is interpreted according to the "Unix crypt using SHA-256 and SHA-512" standard Version 0.4 2008-4-3, where SSSSSSSSSSSSSSSS is up to 16 characters of salt, and the string XXX the result of SHA256.crypt_hash() with 5000 rounds. Source: Unix crypt using SHA-256 and SHA-512 http://www.akkadia.org/drepper/SHA-crypt.txt

"$5$rounds=RR$SSSSSSSSSSSSSSSS$XXXXXXXXXXXXXXXXXXXXXX"

This is the same algorithm as the one above, but with the number of rounds specified by RR in decimal. Note that the number of rounds is clamped to be within 1000 and 999999999 (inclusive). Source: Unix crypt using SHA-256 and SHA-512 http://www.akkadia.org/drepper/SHA-crypt.txt

"$1$SSSSSSSS$XXXXXXXXXXXXXXXXXXXXXX"

The string is interpreted according to the GNU libc2 extension of crypt(3C) where SSSSSSSS is up to 8 chars of salt and the XXX string is an MD5-based hash created from the password and the salt. Source: GNU libc http://www.gnu.org/software/libtool/manual/libc/crypt.html.

"XXXXXXXXXXXXX"

The XXX string (which doesn't begin with "{") is taken to be a password hashed using the classic unix crypt(3C) function. If the string contains only chars from the set [a-zA-Z0-9./] it uses DES and the first two characters as salt, but other alternatives might be possible depending on the crypt(3C) implementation in the operating system.

""

The empty password hash matches all passwords.

Returns

Returns 1 on success, and 0 (zero) otherwise.

Note

This function was added in Pike 7.8.755.

See also

hash(), predef::crypt()

Module Crypto.RIPEMD160

Description

RIPEMD160 is a hash function designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel, as a strengthened version of RIPEMD (which, like MD4 and MD5, fails the collision-resistance requirement). It produces message digests of 160 bits, or 20 octets.


InheritRIPEMD160

inherit Nettle.RIPEMD160 : RIPEMD160

Module Crypto.RSA


Method`()

protectedState`()(mapping(string(8bit):Gmp.mpz|int)|voidparams)

Description

Calling `() will return a State object.


InheritSign

inherit Crypto.Sign : Sign


Methodname

string(8bit)name()

Description

Returns the string "RSA".

Class Crypto.RSA.State


Method_equal

boolequal(Crypto.RSA.Statefrom, mixedother)

Description

Compares the keys of this RSA object with something other.


Methodblock_size

intblock_size()

Description

Returns the crypto block size, or zero if not yet set.


Methodcooked_get_d

__deprecated__string(8bit)cooked_get_d()

Description

Returns the RSA private exponent (d) as a binary string, if known.


Methodcooked_get_e

__deprecated__string(8bit)cooked_get_e()

Description

Returns the RSA public exponent (e) as a binary string.


Methodcooked_get_n

__deprecated__string(8bit)cooked_get_n()

Description

Returns the RSA modulo (n) as a binary string.


Methodcooked_get_p

__deprecated__string(8bit)cooked_get_p()

Description

Returns the first RSA prime (p) as a binary string, if known.


Methodcooked_get_q

__deprecated__string(8bit)cooked_get_q()

Description

Returns the second RSA prime (q) as a binary string, if known.


Methodcooked_sign

__deprecated__string(8bit)cooked_sign(string(8bit)digest)

Description

Signs digest as raw_sign and returns the signature as a byte string.


Methodcreate

Crypto.RSA.StateCrypto.RSA.State(mapping(string(8bit):Gmp.mpz|int)|voidparams)

Description

Can be initialized with a mapping with the elements n, e, d, p and q.


Methodcrypt

string(8bit)crypt(string(8bit)s)

Description

Encrypt or decrypt depending on set mode.

See also

set_encrypt_key, set_decrypt_key


Methoddecrypt

string(8bit)decrypt(string(8bit)s)

Description

Decrypt a message encrypted with encrypt.


Methodencrypt

string(8bit)encrypt(string(8bit)s, function(int:string(8bit))|voidr)

Description

Pads the message s with rsa_pad type 2, signs it and returns the signature as a byte string.

Parameter r

Optional random function to be passed down to rsa_pad.


Methodgenerate_key

this_programgenerate_key(int(128..)bits, void|int|Gmp.mpze)

Description

Generate a valid RSA key pair with the size bits using the random function set with set_random(). The public exponent e will be used, which defaults to 65537. Keys must be at least 89 bits.


Methodgenerate_key

variant__deprecated__this_programgenerate_key(int(128..)bits, function(int(0..):string(8bit)) rnd)

Description

Compatibility with Pike 7.8.


Methodget_d

Gmp.mpzget_d()

Description

Returns the RSA private exponent (d), if known.


Methodget_e

Gmp.mpzget_e()

Description

Returns the RSA public exponent (e).


Methodget_n

Gmp.mpzget_n()

Description

Returns the RSA modulo (n).


Methodget_p

Gmp.mpzget_p()

Description

Returns the first RSA prime (p), if known.


Methodget_q

Gmp.mpzget_q()

Description

Returns the second RSA prime (q), if known.


Inheritthis_program

inherit ::this_program : this_program


Methodjose_decode

array(mapping(string(7bit):string(7bit)|int)|string(8bit)) jose_decode(string(7bit)jws)

Description

Verify and decode a JOSE JWS RSASSA-PKCS-v1.5 signed value.

Parameter jws

A JSON Web Signature as returned by jose_sign().

Returns

Returns 0 (zero) on failure, and an array

Array
mapping(string(7bit):string(7bit)|int) 0

The JOSE header.

string(8bit)1

The signed message.

See also

pkcs_verify(), RFC 7515 section 3.5


Methodjose_sign

string(7bit)jose_sign(string(8bit)message, mapping(string(7bit):string(7bit)|int)|voidheaders, .Hash|voidh)

Description

Signs the message with a JOSE JWS RSASSA-PKCS-v1.5 signature using hash algorithm h.

Parameter message

Message to sign.

Parameter headers

JOSE headers to use. Typically a mapping with a single element "typ".

Parameter h

Hash algorithm to use. Currently defaults to SHA256.

Returns

Returns the signature on success, and 0 (zero) on failure (typically that the hash + salt combo is too large for the RSA modulo).

See also

pkcs_verify(), salt_size(), RFC 7515


Methodkey_size

int(0..)key_size()

Description

Returns the size of the key in terms of number of bits.


Methodname

string(8bit)name()

Description

Returns the string "RSA".


Methodpkcs_public_key

Sequencepkcs_public_key()

Description

Calls Standards.PKCS.RSA.build_public_key with this object as argument.


Methodpkcs_sign

string(8bit)pkcs_sign(string(8bit)message, .Hashh)

Description

Signs the message with a PKCS-1 signature using hash algorithm h. This is equivalent to I2OSP(RSASP1(OS2IP(RSAES-PKCS1-V1_5-ENCODE(message)))) in PKCS#1 v2.2.


Methodpkcs_signature_algorithm_id

Sequencepkcs_signature_algorithm_id(.Hashhash)

Description

Calls Standards.PKCS.RSA.signatue_algorithm_id with the provided hash.


Methodpkcs_verify

boolpkcs_verify(string(8bit)message, .Hashh, string(8bit)sign)

Description

Verify PKCS-1 signature sign of message message using hash algorithm h.


Methodpublic_key_equal

boolpublic_key_equal(this_programrsa)

Description

Compares the public key of this RSA object with another RSA object.


Methodraw_sign

Gmp.mpzraw_sign(string(8bit)digest)

Description

Pads the digest with rsa_pad type 1 and signs it. This is equivalent to RSASP1(OS2IP(RSAES-PKCS1-V1_5-ENCODE(message))) in PKCS#1 v2.2.


Methodraw_verify

boolraw_verify(string(8bit)digest, Gmp.mpzs)

Description

Verifies the digest against the signature s, assuming pad type 1.

See also

rsa_pad, raw_sign


Methodrsa_pad

Gmp.mpzrsa_pad(string(8bit)message, int(1..2)type, function(int(0..):string(8bit))|voidrandom)

Description

Pads the message to the current block size with method type and returns the result as an integer. This is equivalent to OS2IP(RSAES-PKCS1-V1_5-ENCODE(message)) in PKCS#1 v2.2.

Parameter type
1

The message is padded with 0xff bytes.

2

The message is padded with random data, using the random function if provided. Otherwise the default random function set in the object will be used.


Methodrsa_unpad

string(8bit)rsa_unpad(Gmp.mpzblock, inttype)

Description

Reverse the effect of rsa_pad.


Methodset_decrypt_key

this_programset_decrypt_key(array(Gmp.mpz) key)

Description

Sets the public key to keyand the mod to decryption.

See also

set_encrypt_key, crypt


Methodset_encrypt_key

this_programset_encrypt_key(array(Gmp.mpz) key)

Description

Sets the public key to key and the mode to encryption.

See also

set_decrypt_key, crypt


Methodset_private_key

this_programset_private_key(Gmp.mpz|intpriv, array(Gmp.mpz|int)|voidextra)

Description

Sets the private key.

Parameter priv

The private RSA exponent, often called d.

Parameter extra
Array
Gmp.mpz|int0

The first prime, often called p.

Gmp.mpz|int1

The second prime, often called q.


Methodset_public_key

this_programset_public_key(Gmp.mpz|intmodulo, Gmp.mpz|intpub)

Description

Sets the public key.

Parameter modulo

The RSA modulo, often called n. This value needs to be >=12.

Parameter pub

The public RSA exponent, often called e.


Methodset_random

this_programset_random(function(int(0..):string(8bit)) r)

Description

Sets the random function, used to generate keys and parameters, to the function r. Default is Crypto.Random.random_string.

Module Crypto.Random

Description

This module contains a pseudo random number generator (PRNG) designed to give you the best possible random number generation. The current design is based on the Fortuna PRNG, but uses the system random source as input.


Methodadd_entropy

voidadd_entropy(string(8bit)data)

Description

Inject additional entropy into the random generator. One possible use is to persist random data between executions of an application. The internal state is approximately 256 bits, so storing 32 bytes from random_string() at shutdown and injecting them through add_entropy() agan at startup should carry over the entropy. Note that this doesn't affect the independent initialization that happens in the generator at startup, so the output sequence will be different than if the application had continued uninterrupted.

Parameter data

The random string.


Methodrandom

Gmp.mpzrandom(inttop)

Description

Returns a Gmp.mpz object with a random value between 0 and top. Uses random_string.


Methodrandom_string

string(8bit)random_string(intlen)

Description

Returns a string of length len with random content. The content is generated by a Fortuna random generator that is updated with output from /dev/urandom on UNIX and CryptGenRandom on NT.

Module Crypto.SALSA20

Description

The SALSA20 stream cipher.


InheritSALSA20

inherit Nettle.SALSA20 : SALSA20

Module Crypto.SALSA20R12

Description

The SALSA20 stream cipher reduced to just 12 rounds.


InheritSALSA20R12

inherit Nettle.SALSA20R12 : SALSA20R12

Module Crypto.SHA1

Description

SHA1 is a hash function specified by NIST (The U.S. National Institute for Standards and Technology). It outputs hash values of 160 bits, or 20 octets.


InheritSHA1

inherit Nettle.SHA1 : SHA1

Module Crypto.SHA224

Description

SHA224 is another hash function specified by NIST, intended as a replacement for SHA1, generating larger digests. It outputs hash values of 224 bits, or 28 octets.


InheritSHA224

inherit Nettle.SHA224 : SHA224

Module Crypto.SHA256

Description

SHA256 is another hash function specified by NIST, intended as a replacement for SHA1, generating larger digests. It outputs hash values of 256 bits, or 32 octets.


InheritSHA256

inherit Nettle.SHA256 : SHA256

Module Crypto.SHA384

Description

SHA384 is another hash function specified by NIST, intended as a replacement for SHA1, generating larger digests. It outputs hash values of 384 bits, or 48 octets.


InheritSHA384

inherit Nettle.SHA384 : SHA384

Module Crypto.SHA3_224

Description

SHA-3-224 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 224 bits, or 28 octets.


InheritSHA3_224

inherit Nettle.SHA3_224 : SHA3_224

Module Crypto.SHA3_256

Description

SHA-3-256 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 256 bits, or 32 octets.


InheritSHA3_256

inherit Nettle.SHA3_256 : SHA3_256

Module Crypto.SHA3_384

Description

SHA-3-386 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 256 bits, or 48 octets.


InheritSHA3_384

inherit Nettle.SHA3_384 : SHA3_384

Module Crypto.SHA3_512

Description

SHA-3-512 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 512 bits, or 64 octets.


InheritSHA3_512

inherit Nettle.SHA3_512 : SHA3_512

Module Crypto.SHA512

Description

SHA512 is another hash function specified by NIST, intended as a replacement for SHA1, generating larger digests. It outputs hash values of 512 bits, or 64 octets.


InheritSHA512

inherit Nettle.SHA512 : SHA512

Module Crypto.Serpent

Description

SERPENT is one of the AES finalists, designed by Ross Anderson, Eli Biham and Lars Knudsen. Thus, the interface and properties are similar to AES'. One peculiarity is that it is quite pointless to use it with anything but the maximum key size, smaller keys are just padded to larger ones.


InheritSERPENT

inherit Nettle.SERPENT : SERPENT

Module Crypto.Twofish

Description

Another AES finalist, this one designed by Bruce Schneier and others.


InheritTwofish

inherit Nettle.Twofish : Twofish

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.


Methodmute

intmute(intmute)
intmute()

Description

Mute or unmute audio device.


Methodstatus

mappingstatus()

Description

Returns mapping of current audio device status.

Class DVB.Stream

Description

Represents an elementary data stream (PES).


Methodclose

voidclose()

Description

Closes an open stream.

See also

read()


Methoddestroy

intdestroy()

Description

Purge a stream reader.

See also

DVB.dvb()->stream(), 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()

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


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

Note

In Pike 7.8.308 and earlier indent wasn't supported.


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


Methodlist_open_fds

voidlist_open_fds()

Note

Only available when compiled with dmalloc.


Methodlocate_references

voidlocate_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

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


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


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)


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.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, ([ "indent":2 ])) (2) Result: Debug.Subject > abs(class { inherit Debug.Subject; int `<(mixed ... args) { return 1; } }()); create() `-() destroy() (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

floatnumber_of_calls

The number of calls

floatself_time

The self CPU time

floatcpu_time

The self CPU time, 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

This is the location in the source of the start of the function

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

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

function(: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