1. Control Structures

In this chapter all the control structures in Pike will be explained. Control structures are used to control the flow of the program execution. Note that functions that make the program pause and simple function calls are not qualified as control structures.

1.1. Conditions

Conditions are control structures that, given a test condition selects what code to be executed. These range from the binary "execute or not" to a large table of code where the selection of which code to run is based on an input parameter.

1.1.1. if

The simplest one is called the if statement. It can be written anywhere where a statement is expected and it looks like this:

if( expression )
  statement1;
else
  statement2;

Please note that there is no semicolon after the parenthesis or after the else. Step by step, if does the following:

  1. First it evaluates expression.
  2. If the result was false go to point 5.
  3. Execute statement1.
  4. Jump to point 6.
  5. Execute statement2.
  6. Done.

This is actually more or less how the interpreter executes the if statement. In short, statement1 is executed if expression is true otherwise statement2 is executed. If you are not interested in having something executed if the expression is false you can drop the whole else part like this:

if( expression )
  statement1;

If on the other hand you are not interested in evaluating something if the expression is false you should use the not operator to negate the true/false value of the expression. See FIXME: chapter for more information about the not operator. It would look like this:

if( ! expression )
  statement2;

Any of the statements here and in the rest of this chapter can also be a block of statements. A block is a list of statements, separated by semicolons and enclosed by brackets. Note that you should never put a semicolon after a block of statements. The example above would look like this;

if ( ! expression )
{
  statement;
  statement;
  statement;
}

It is also possible to place several if statements in sequence, so that if the first expression is false it continues with the next one and the next one until the first true expression is found.

if ( expression1 )
  statement1;
else if ( expression2 )
  statement2;
else if ( expression3 )
  statement3;
else
  statement4;

A special case of the above example is when in every expression you compare one variable with different values. For those applications the switch statement described below can be used instead to increas performance and simplify the code.

1.1.2. switch

A more sophisticated condition control structure is the switch statement. A switch lets you select one of many choices depending on the value of an expression and it can look something like this:

switch ( expression )
{
  case constant1:
    statement1;
    break;

  case constant2:
    statement2;
    break;

  case constant3 .. constant4:
    statement3;
    break;

  case constant5:
  case constant6:
    statement4;
    // Fallthrough

  default:
    statement5;
}

As you can see, a switch statement is a bit more complicated than an if statement. It is still fairly simple however. It starts by evaluating the expression it then searches all the case statements in the following block. If one is found to be equal to the value returned by the expression, Pike will continue executing the code directly following that case statement. When a break is encountered Pike will skip the rest of the code in the switch block and continue executing after the block. Note that it is not strictly necessary to have a break before the next case statement. If there is no break before the next case statement Pike will simply continue executing and execute the code after that case statement as well.

One of the case statements in the above example differs in that it is a range. In this case, any value between constant3 and constant4 will cause Pike to jump to statement3. Note that the ranges are inclusive, so the values constant3 and constant4 are also valid.

1.2. Loops

Loops are used to execute a piece of code more than once. Since this can be done in quite a few different ways there are four different loop control structures. They may all seem very similar, but using the right one at the right time makes the code a lot shorter and simpler.

1.2.1. while

While is the simplest of the loop control structures. It looks just like an if statement without the else part:

	while ( expression )
	  statement;

The difference in how it works isn't that big either, the statement is executed if the expression is true. Then the expression is evaluated again, and if it is true the statement is executed again. Then it evaluates the expression again and so forth... Here is an example of how it could be used:

int e=1;
while(e<5)
{
  show_record(e);
  e=e+1;
}

This would call show_record with the values 1, 2, 3 and 4.

1.2.2. for

For is simply an extension of while. It provides an even shorter and more compact way of writing loops. The syntax looks like this:

for ( initializer_statement ; expression ; incrementor_expression )
  statement ;

For does the following steps:

  1. Executes the the initializer_statement. The initializer statement is executed only once and is most commonly used to initialize the loop variable.
  2. Evaluates expression
  3. If the result was false it exits the loop and continues with the program after the loop.
  4. Executes statement.
  5. Executes the increment_expression.
  6. Starts over from 2.

This means that the example in the while section can be written like this:

for(int e=1; e<5; e=e+1)
  show_record(e);

1.2.3. do-while

Sometimes it is unpractical that the expression is always evaluated before the first time the loop is executed. Quite often you want to execute something, and then do it over and over until some condition is satisfied. This is exactly when you should use the do-while statement.

do
  statement;
while ( expression );

As usual, the statement can also be a block of statements, and then you do not need a semicolon after it. To clarify, this statement executes statement first, and then evaluates the expression. If the expression is true it executes the loop again. For instance, if you want to make a program that lets your modem dial your Internet provider, it could look something like this:

do {
  modem->write("ATDT441-9109\n"); // Dial 441-9109
} while(modem->gets()[..6]] != "CONNECT");

This example assumes you have written something that can communicate with the modem by using the functions write and gets.

1.2.4. foreach

Foreach is unique in that it does not have an explicit test expression evaluated for each iteration in the loop. Instead, foreach executes the statement once for each element in a set. Foreach has two syntaxes, the first of which look like this:

foreach ( array_expression, variable )
  statement;

We have already seen an example of foreach in the find_song function in chapter 2. What foreach does is:

  1. It evaluates the array_expression which must return an array.
  2. If the array is empty, exit the loop.
  3. It then assigns the first element from the array to the variable.
  4. Then it executes the statement.
  5. If there are more elements in the array, the next one is assigned to the variable, otherwise exit the loop.
  6. Go to point 4.

Foreach is not really necessary, but it is faster and clearer than doing the same thing with a for loop, as shown here:

array tmp1 = array_expression;
for ( tmp2 = 0; tmp2 < sizeof(tmp1); tmp2++ )
{
  variable = tmp1 [ tmp2 ];
  statement;
}

The second syntax for foreach is the more flexible iterator syntax, which can be used to iterate over arrays, mappings, multisets and strings as well as some objects. It also has the option of providing the index value:

foreach ( iterable_expression; optional_index_variable; optional_value_variable )
  statement;

This is approximately equivalent to:

for (Iterator iter = get_iterator(iterable_expression); iter; iter->next()) {
  optional_index_variable = iter->index();
  optional_value_variable = iter->value();
  statement;
}

See get_iterator() for further details.

1.3. Breaking out of loops

The loop control structures above are enough to solve any problem, but they are not enough to provide an easy solution to all problems. One thing that is still missing is the ability to exit a loop in the middle of it. There are three ways to do this:

1.3.1. break

break exits a loop, switch, or catch statement immediately and continues executing after the loop. Break can not be used outside of one of these. It is quite useful in conjunction with while(1) to construct command parsing loops for instance:

while(1)
{
  string command=Stdio.Readline()->read("> ");
  if(command=="quit") break;
  do_command(command);
}

When you want to break out of more than the innermost loop, you can tell break what loop to break free of using lables, as in:

array arr1, arr2;
while(1)
{
  // ...
a:if(sizeof(arr1) >= sizeof(arr2))
  {
    int i = sizeof(b), j = sizeof(yb);
    while(i)
      if(b[--i] != yb[--j])
        break a;
    // the code here is only run when arr1
    // and arr2 share some common suffix
  }
  // execution continues here
}

Inside a catch block, break will terminate the block with no exception being thrown; catch will return zero, as if execution had continued to the end of the block.

1.3.2. continue

Continue does almost the same thing as break, except instead of breaking out of the loop it only breaks out of the loop body. It then continues to execute the next iteration in the loop. For a while loop, this means it jumps up to the top again. For a for loop, it jumps to the incrementor expression. For a do-while loop it jumps down to the expression at the end. To continue our example above, continue can be used like this:

while(1)
{
  string command=Stdio.Readline()->read("> ");
  if(strlen(command) == 0) continue;
  if(command=="quit") break;
  do_command(command);
}

This way, do_command will never be called with an empty string as argument.

1.3.3. return

Return doesn't just exit the loop, it exits the whole function. We have seen several examples how to use it chapter 2. None of the functions in chapter two returned anything in particular however. To do that you just put the return value right after return. Of course the type of the return value must match the type in the function declaration. If your function declaration is int main() the value after return must be an int. For instance, if we wanted to make a program that always returns an error code to the system, just like the UNIX command false this is how it would be done:

#!/usr/local/bin/pike

int main()
{
  return 1;
}

This would return the error code 1 to the system when the program is run.

2. Data types

In this chapter we will discuss all the different ways to store data in Pike in detail. We have seen examples of many of these, but we haven't really gone into how they work. In this chapter we will also see which operators and functions work with the different types.

Types in Pike are used in two different contexts; during compile-time, and during run-time. Some types are only used during compile-time (void, mixed and all constructed types), all other types are also used during run-time. Also note the following functions and special forms:

type typeof(mixed x)
This special form returns the compile-time type for the expression x (which is not evaluated). Ie the type that the compiler believes that the expression will return if evaluated.
type _typeof(mixed x)
This function returns the run-type of the value x (which is evaluated).

There are two categories of run-time data types in Pike: basic types, and pointer types. The difference is that basic types are copied when assigned to a variable. With pointer types, merely the pointer is copied, that way you get two variables pointing to the same thing.

2.1. Basic types

The basic types are int, float and string. For you who are accustomed to C or C++, it may seem odd that a string is a basic type as opposed to an array of char, but it is surprisingly easy to get used to.

2.1.1. int

Int is short for integer, or integer number. They are normally 32 bit integers, which means that they are in the range -2147483648 to 2147483647. (Note that on some machines an int might be larger than 32 bits.) If Pike is compiled with bignum support the 32 bit limitation does not apply and thus the integers can be of arbitrary size. Since they are integers, no decimals are allowed. An integer constant can be written in several ways:

PatternExampleDescription
-?[1-9][0-9]*78Decimal number
-?0[0-9]*0116Octal number
-?0[xX][0-9a-fA-F]+0x4eHexadecimal number
-?0[bB][01]+0b1001110Binary number
-?'\\?.''N'ASCII character

All of the above represent the number 78. Octal notation means that each digit is worth 8 times as much as the one after. Hexadecimal notation means that each digit is worth 16 times as much as the one after. Hexadecimal notation uses the letters a, b, c, d, e and f to represent the numbers 10, 11, 12, 13, 14 and 15. In binary notation every digit is worth twice the value of the succeding digit, but only 1:s and 0:s are used. The ASCII notation gives the ASCII value of the character between the single quotes. In this case the character is N which just happens to be 78 in ASCII. Some characters, like special characters as newlines, can not be placed within single quotes. The special generation sequence for those characters, listed under strings, must be used instead. Specifically this applies to the single quote character itself, which has to be written as '\''.

When pike is compiled with bignum support integers in never overflow or underflow when they reach the system-defined maxint/minint. Instead they are silently converted into bignums. Integers are usually implemented as 2-complement 32-bits integers, and thus are limited within -2147483648 and 2147483647. This may however vary between platforms, especially 64-bit platforms. FIXME: Conversion back to normal integer?

All the arithmetic, bitwise and comparison operators can be used on integers. Also note these functions:

int intp(mixed x)
This function returns 1 if x is an int, 0 otherwise.
int random(int x)
This function returns a random number greater or equal to zero and smaller than x.
int reverse(int x)
This function reverses the order of the bits in x and returns the new number. It is not very useful.
int sqrt(int x)
This computes the square root of x. The value is always rounded down.

2.1.2. float

Although most programs only use integers, they are unpractical when doing trigonometric calculations, transformations or anything else where you need decimals. For this purpose you use float. Floats are normally 32 bit floating point numbers, which means that they can represent very large and very small numbers, but only with 9 accurate digits. To write a floating point constant, you just put in the decimals or write it in the exponential form:

PatternExampleEquals
-?[0-9]*\.[0-9]+3.14159263.1415926
-?[0-9]+e-?[0-9]+-5e3-5000.0
-?[0-9]*\.[0-9]+e-?[0-9]+.22e-20.0022

Of course you can have any number of decimals to increase the accuracy. Usually digits after the ninth digit are ignored, but on some architectures float might have higher accuracy than that. In the exponential form, e means "times 10 to the power of", so 1.0e9 is equal to "1.0 times 10 to the power of 9". FIXME: float and int is not compatible and no implicit cast like in C++

All the arithmetic and comparison operators can be used on floats. Also, these functions operates on floats:

trigonometric functions
The trigonometric functions are: sin, asin, cos, acos, tan and atan. If you do not know what these functions do you probably don't need them. Asin, acos and atan are of course short for arc sine, arc cosine and arc tangent. On a calculator they are often known as inverse sine, inverse cosine and inverse tangent.
float log(float x)
This function computes the natural logarithm of x,
float exp(float x)
This function computes e raised to the power of x.
float pow(float|int x, float|int y)
This function computes x raised to the power of y.
float sqrt(float x)
This computes the square root of x.
float floor(float x)
This function computes the largest integer value less than or equal to x. Note that the value is returned as a float, not an int.
float ceil(float x)
This function computes the smallest integer value greater than or equal to x and returns it as a float.
float round(float x)
This function computes the closest integer value to x and returns it as a float.

2.1.3. string

A string can be seen as an array of values from 0 to 2³²-1. Usually a string contains text such as a word, a sentence, a page or even a whole book. But it can also contain parts of a binary file, compressed data or other binary data. Strings in Pike are shared, which means that identical strings share the same memory space. This reduces memory usage very much for most applications and also speeds up string comparisons. We have already seen how to write a constant string:

"hello world" // hello world
"he" "llo"    // hello
"\116"        // N (116 is the octal ASCII value for N)
"\t"          // A tab character
"\n"          // A newline character
"\r"          // A carriage return character
"\b"          // A backspace character
"\0"          // A null character
"\""          // A double quote character
"\\"          // A singe backslash
"\x4e"        // N (4e is the hexadecimal ASCII value for N)
"\d78"        // N (78 is the decimal ACII value for N)
"hello world\116\t\n\r\b\0\"\\" // All of the above
"\xff"        // the character 255
"\xffff"      // the character 65536
"\xffffff"    // the character 16777215
"\116""3"     // 'N' followed by a '3'

PatternExample
.N
\\[0-7]+\116
\\x[0-9a-fA-F]+\x4e
\\d[0-9]+\d78
\\u[0-9a-fA-F]+ (4)\u004E
\\U[0-9a-fA-F]+ (8)\U0000004e
SequenceASCII codeCharcter
\a7An acknowledge character
\b8A backspace character
\t9A tab character
\n10A newline character
\v11A vertical tab character
\f12A form feed character
\r13A carriage return character
\"34A double quote character
\\92A backslash character

As you can see, any sequence of characters within double quotes is a string. The backslash character is used to escape characters that are not allowed or impossible to type. As you can see, \t is the sequence to produce a tab character, \\ is used when you want one backslash and \" is used when you want a double quote (") to be a part of the string instead of ending it. Also, \XXX where XXX is an octal number from 0 to 37777777777 or \xXX where XX is 0 to ffffffff lets you write any character you want in the string, even null characters. From version 0.6.105, you may also use \dXXX where XXX is 0 to 2³²-1. If you write two constant strings after each other, they will be concatenated into one string.

You might be surprised to see that individual characters can have values up to 2³²-1 and wonder how much memory that use. Do not worry, Pike automatically decides the proper amount of memory for a string, so all strings with character values in the range 0-255 will be stored with one byte per character. You should also beware that not all functions can handle strings which are not stored as one byte per character, so there are some limits to when this feature can be used.

Although strings are a form of arrays, they are immutable. This means that there is no way to change an individual character within a string without creating a new string. This may seem strange, but keep in mind that strings are shared, so if you would change a character in the string "foo", you would change *all* "foo" everywhere in the program.

However, the Pike compiler will allow you to to write code like you could change characters within strings, the following code is valid and works:

string s="hello torld";
s[6]='w';

However, you should be aware that this does in fact create a new string and it may need to copy the string s to do so. This means that the above operation can be quite slow for large strings. You have been warned. Most of the time, you can use replace, sscanf, `/ or some other high-level string operation to avoid having to use the above construction too much.

All the comparison operators plus the operators listed here can be used on strings:

Summation
Adding strings together will simply concatenate them. "foo"+"bar" becomes "foobar".
Subtraction
Subtracting one string from another will remove all occurrences of the second string from the first one. So "foobarfoogazonk" - "foo" results in "bargazonk".
Indexing
Indexing will let you get the ASCII value of any character in a string. The first index is zero.
Range
The range operator will let you copy any part of the string into a new string. Example: "foobar"[2..4] will return "oba".
Division
Division will let you divide a string at every occurrence of a word or character. For instance if you do "foobargazonk" / "o" the result would be ({"f","","bargaz","nk"}). It is also possible to divide the string into strings of length N by dividing the string by N. If N is converted to a float before dividing, the reminder of the division will be included in the result.
Multiplication
The inverse of the division operator can be accomplished by multiplying an array with a string. So if you evaluate ({"f","","bargaz","nk"}) * "o" the result would be "foobargazonk".
Modulo
To complement the division operator, you can do string % int. This operator will simply return the part of the string that was not included in the array returned by string / int

Also, these functions operates on strings:

string String.capitalize(string s)
Returns s with the first character converted to upper case.
int String.count(string haystack, string needle)
Returns the number of occurances of needle in haystack. Equivalent to sizeof(haystack/needle)-1.
int String.width(string s)
Returns the width s in bits (8, 16 or 32).
string lower_case(string s)
Returns s with all the upper case characters converted to lower case.
string replace(string s, string from, string to)
This function replaces all occurrences of the string from in s with to and returns the new string.
string reverse(string s)
This function returns a copy of s with the last byte from s first, the second last in second place and so on.
int search(string haystack, string needle)
This function finds the first occurrence of needle in haystack and returns where it found it.
string sizeof(string s)
Same as strlen(s), returns the length of the string.
int stringp(mixed s)
This function returns 1 if s is a string, 0 otherwise.
int strlen(string s)
Returns the length of the string s.
string upper_case(string s)
This function returns s with all lower case characters converted to upper case.

2.2. Pointer types

The basic types are, as the name implies, very basic. They are the foundation, most of the pointer types are merely interesting ways to store the basic types. The pointer types are array, mapping, multiset, program, object and function. They are all pointers which means that they point to something in memory. This "something" is freed when there are no more pointers to it. Assigning a variable with a value of a pointer type will not copy this "something" instead it will only generate a new reference to it. Special care sometimes has to be taken when giving one of these types as arguments to a function; the function can in fact modify the "something". If this effect is not wanted you have to explicitly copy the value. More about this will be explained later in this chapter.

2.2.1. array

Arrays are the simplest of the pointer types. An array is merely a block of memory with a fixed size containing a number of slots which can hold any type of value. These slots are called elements and are accessible through the index operator. To write a constant array you enclose the values you want in the array with ({ }) like this:

({ })      // Empty array
({ 1 })    // Array containing one element of type int
({ "" })   // Array containing a string
({ "", 1, 3.0 }) // Array of three elements, each of different type

As you can see, each element in the array can contain any type of value. Indexing and ranges on arrays works just like on strings, except with arrays you can change values inside the array with the index operator. However, there is no way to change the size of the array, so if you want to append values to the end you still have to add it to another array which creates a new array. Figure 4.1 shows how the schematics of an array. As you can see, it is a very simple memory structure.

Operators and functions usable with arrays:

indexing ( arr [ c ] )
Indexing an array retrieves or sets a given element in the array. The index c has to be an integer. To set an index, simply put the whole thing on the left side of an assignment, like this: arr [ c ] = new_value
range ( arr [ from .. to ] )
The range copies the elements from, from+1, , from+2 ... to into a new array. The new array will have the size to-from+1.
comparing (a == b and a != b)
The equal operator returns 1 if a and b are the same arrays. It is not enough that they have the same size and same data. They must be the same array. For example: ({1}) == ({1}) would return 0, while array(int) a=({1}); return a==a; would return 1. Note that you cannot use the operators >, >=, < or <= on arrays.
Summation (a + b)
As with strings, summation concatenates arrays. ({1})+({2}) returns ({1,2}).
Subtractions (a - b)
Subtracting one array from another returns a copy of a with all the elements that are also present in b removed. So ({1,3,8,3,2}) - ({3,1}) returns ({8,2}).
Intersection (a & b)
Intersection returns an array with all values that are present in both a and b. The order of the elements will be the same as the the order of the elements in a. Example: ({1,3,7,9,11,12}) & ({4,11,8,9,1}) will return: ({1,9,11}).
Union (a | b)
Union works almost as summation, but it only adds elements not already present in a. So, ({1,2,3}) | ({1,3,5}) will return ({1,2,3,5}). Note: the order of the elements in a can be changed!
Xor (a ^ b)
This is also called symmetric difference. It returns an array with all elements present in a or b but the element must NOT be present in both. Example: ({1,3,5,6}) ^ ({4,5,6,7}) will return ({1,3,4,7}).
Division (a / b)
This will split the array a into an array of arrays. If b is another array, a will be split at each occurance of that array. If b is an integer or float, a will be split between every bth element. Examples: ({1,2,3,4,5})/({2,3}) will return ({ ({1}), ({4,5}) }) and ({1,2,3,4})/2 will return ({ ({1,2}), ({3,4}) }).
Modulo (a % b)
This operation is valid only if b is an integer. It will return the part of the array that was not included by dividing a by b.
array aggregate(mixed ... elems)
This function does the same as the ({ }) operator; it creates an array from all arguments given to it. In fact, writing ({1,2,3}) is the same as writing aggregate(1,2,3).
array allocate(int size)
This function allocates a new array of size size. All the elements in the new array will be zeroes.
int arrayp(mixed a)
This function returns 1 if a is an array, 0 otherwise.
array column(array(mixed) a, mixed ind)
This function goes through the array a and indexes every element in it on ind and builds an array of the results. So if you have an array a in which each element is a also an array. This function will take a cross section, by picking out element ind from each of the arrays in a. Example: column( ({ ({1,2,3}), ({4,5,6}), ({7,8,9}) }), 2) will return ({3,6,9}).
int equal(mixed a, mixed b)
This function returns 1 if if a and b look the same. They do not have to be pointers to the same array, as long as they are the same size and contain equal data.
array filter(array a, mixed func, mixed ... args)
filter returns every element in a for which func returns true when called with that element as first argument, and args for the second, third, etc. arguments. (Both a and func can be other things; see the reference for filter for details about that.)
array map(array a, mixed func, mixed ... args)
This function works similar to filter but returns the results of the function func instead of returning the elements from a for which func returns true. (Like filter, this function accepts other things for a and func; see the reference for map.)
array replace(array a, mixed from, mixed to)
This function will create a copy of a with all elements equal to from replaced by to.
array reverse(array a)
Reverse will create a copy of a with the last element first, the last but one second, and so on.
array rows(array a, array indexes)
This function is similar to column. It indexes a with each element from indexes and returns the results in an array. For example: rows( ({"a","b","c"}), ({ 2,1,2,0}) ) will return ({"c","b","c","a"}).
int search(array haystack, mixed needle)
This function returns the index of the first occurrence of an element equal (tested with ==) to needle in the array haystack.
int sizeof(mixed arr)
This function returns the number of elements in the array arr.
array sort(array arr, array ... rest)
This function sorts arr in smaller-to-larger order. Numbers, floats and strings can be sorted. If there are any additional arguments, they will be permutated in the same manner as arr. See functions for more details.
array Array.uniq(array a)
This function returns a copy of the array a with all duplicate elements removed. Note that this function can return the elements in any order.

2.2.2. mapping

Mappings are are really just more generic arrays. However, they are slower and use more memory than arrays, so they cannot replace arrays completely. What makes mappings special is that they can be indexed on other things than integers. We can imagine that a mapping looks like this:

Each index-value pair is floating around freely inside the mapping. There is exactly one value for each index. We also have a (magical) lookup function. This lookup function can find any index in the mapping very quickly. Now, if the mapping is called m and we index it like this: m [ i ] the lookup function will quickly find the index i in the mapping and return the corresponding value. If the index is not found, zero is returned instead. If we on the other hand assign an index in the mapping the value will instead be overwritten with the new value. If the index is not found when assigning, a new index-value pair will be added to the mapping. Writing a constant mapping is easy:

([ ])       // Empty mapping
([ 1:2 ])   // Mapping with one index-value pair, the 1 is the index
([ "one":1, "two":2 ]) // Mapping which maps words to numbers
([ 1:({2.0}), "":([]), ]) // Mapping with lots of different types

As with arrays, mappings can contain any type. The main difference is that the index can be any type too. Also note that the index-value pairs in a mapping are not stored in a specific order. You can not refer to the fourteenth key-index pair, since there is no way of telling which one is the fourteenth. Because of this, you cannot use the range operator on mappings.

The following operators and functions are important:

indexing ( m [ ind ] )
As discussed above, indexing is used to retrieve, store and add values to the mapping.
addition, subtraction, union, intersection and xor
All these operators works exactly as on arrays, with the difference that they operate on the indices. In those cases when the value can come from either mapping, it will be taken from the right side of the operator. This makes it easier to add new values to a mapping with +=. Some examples:
([1:3, 3:1]) + ([2:5, 3:7]) returns ([1:3, 2:5, 3:7 ])
([1:3, 3:1]) - ([2:5, 3:7]) returns ([1:3])
([1:3, 3:1]) | ([2:5, 3:7]) returns ([1:3, 2:5, 3:7 ])
([1:3, 3:1]) & ([2:5, 3:7]) returns ([3:7])
([1:3, 3:1]) ^ ([2:5, 3:7]) returns ([1:3, 2:5])
same ( a == b )
Returns 1 if a is the same mapping as b, 0 otherwise.
not same ( a != b )
Returns 0 if a is the same mapping as b, 1 otherwise.
array indices(mapping m)
Indices returns an array containing all the indices in the mapping m.
mixed m_delete(mapping m, mixed ind)
This function removes the index-value pair with the index ind from the mapping m. It will return the value that was removed.
int mappingp(mixed m)
This function returns 1 if m is a mapping, 0 otherwise.
mapping mkmapping(array ind, array val)
This function constructs a mapping from the two arrays ind and val. Element 0 in ind and element 0 in val becomes one index-value pair. Element 1 in ind and element 1 in val becomes another index-value pair, and so on..
mapping replace(mapping m, mixed from, mixed to)
This function creates a copy of the mapping m with all values equal to from replaced by to.
mixed search(mapping m, mixed val)
This function returns the index of the 'first' index-value pair which has the value val.
int sizeof(mapping m)
Sizeof returns how many index-value pairs there are in the mapping.
array values(mapping m)
This function does the same as indices, but returns an array with all the values instead. If indices and values are called on the same mapping after each other, without any other mapping operations in between, the returned arrays will be in the same order. They can in turn be used as arguments to mkmapping to rebuild the mapping m again.
int zero_type(mixed t)
When indexing a mapping and the index is not found, zero is returned. However, problems can arise if you have also stored zeroes in the mapping. This function allows you to see the difference between the two cases. If zero_type(m [ ind ]) returns 1, it means that the value was not present in the mapping. If the value was present in the mapping, zero_type will return something else than 1.

2.2.3. multiset

A multiset is almost the same thing as a mapping. The difference is that there are no values:

Instead, the index operator will return 1 if the value was found in the multiset and 0 if it was not. When assigning an index to a multiset like this: mset[ ind ] = val the index ind will be added to the multiset mset if val is true. Otherwise ind will be removed from the multiset instead.

Writing a constant multiset is similar to writing an array:

(< >)      // Empty multiset
(< 17 >)  // Multiset with one index: 17
(< "", 1, 3.0, 1 >) // Multiset with four indices

Note that you can actually have more than one of the same index in a multiset. This is normally not used, but can be practical at times.

2.2.4. program

Normally, when we say program we mean something we can execute from a shell prompt. However, Pike has another meaning for the same word. In Pike a program is the same as a class in C++. A program holds a table of what functions and variables are defined in that program. It also holds the code itself, debug information and references to other programs in the form of inherits. A program does not hold space to store any data however. All the information in a program is gathered when a file or string is run through the Pike compiler. The variable space needed to execute the code in the program is stored in an object which is the next data type we will discuss.

Writing a program is easy, in fact, every example we have tried so far has been a program. To load such a program into memory, we can use compile_file which takes a file name, compiles the file and returns the compiled program. It could look something like this:

program p = compile_file("hello_world.pike");

You can also use the cast operator like this:

program p = (program) "hello_world";

This will also load the program hello_world.pike, the only difference is that it will cache the result so that next time you do (program)"hello_world" you will receive the _same_ program. If you call compile_file("hello_world.pike") repeatedly you will get a new program each time.

There is also a way to write programs inside programs with the help of the class keyword:

class class_name {
  inherits, variables and functions
}

The class keyword can be written as a separate entity outside of all functions, but it is also an expression which returns the program written between the brackets. The class_name is optional. If used you can later refer to that program by the name class_name. This is very similar to how classes are written in C++ and can be used in much the same way. It can also be used to create structs (or records if you program Pascal). Let's look at an example:

class record {
  string title;
  string artist;
  array(string) songs;
}

array(record) records = ({});

void add_empty_record()
{
  records+=({ record() });
}

void show_record(record rec)
{
  write("Record name: "+rec->title+"\n");
  write("Artist: "+rec->artist+"\n");
  write("Songs:\n");
  foreach(rec->songs, string song)
    write("   "+song+"\n");
}

This could be a small part of a better record register program. It is not a complete executable program in itself. In this example we create a program called record which has three identifiers. In add_empty_record a new object is created by calling record. This is called cloning and it allocates space to store the variables defined in the class record. Show_record takes one of the records created in add_empty_record and shows the contents of it. As you can see, the arrow operator is used to access the data allocated in add_empty_record. If you do not understand this section I suggest you go on and read the next section about objects and then come back and read this section again.

cloning
To create a data area for a program you need to instantiate or clone the program. This is accomplished by using a pointer to the program as if it was a function and call it. That creates a new object and calls the function create in the new object with the arguments.
compiling
All programs are generated by compiling a string. The string may of course be read from a file. For this purpose there are three functions: program compile(string p); program compile_file(string filename); program compile_string(string p, string filename); compile_file simply reads the file given as argument, compiles it and returns the resulting program. compile_string instead compiles whatever is in the string p. The second argument, filename, is only used in debug printouts when an error occurs in the newly made program. Both compile_file and compile_string call compile to actually compile the string after having called cpp on it.
casting
Another way of compiling files to program is to use the cast operator. Casting a string to the type program calls a function in the master object which will compile the program in question for you. The master also keeps the program in a cache, so if you later need the same program again it will not be re-compiled.
int programp(mixed p)
This function returns 1 if p is a program, 0 otherwise.
comparisons
As with all data types == and != can be used to see if two programs are the same or not.

The following operators and functions are important:

cloning ( p ( args ) )
Creates an object from a program. Discussed in the next section.
indexing ( p [ string ], or p -> identifier )
Retreives the value of the named constant from a program.
array(string) indices(program p)
Returns an array with the names of all non-protected constants in the program.
array(mixed) values(program p)
Returns an array with the values of all non-protected constants in the program.

2.2.5. object

Although programs are absolutely necessary for any application you might want to write, they are not enough. A program doesn't have anywhere to store data, it just merely outlines how to store data. To actually store the data you need an object. Objects are basically a chunk of memory with a reference to the program from which it was cloned. Many objects can be made from one program. The program outlines where in the object different variables are stored.

Each object has its own set of variables, and when calling a function in that object, that function will operate on those variables. If we take a look at the short example in the section about programs, we see that it would be better to write it like this:

class record {
  string title;
  string artist;
  array(string) songs;

  void show()
  {
    write("Record name: "+title+"\n");
    write("Artist: "+artist+"\n");
    write("Songs:\n");
    foreach(songs, string song)
      write("   "+song+"\n");
  }
}

array(record) records = ({});

void add_empty_record()
{
  records+=({ record() });
}

void show_record(object rec)
{
  rec->show();
}

Here we can clearly see how the function show prints the contents of the variables in that object. In essence, instead of accessing the data in the object with the -> operator, we call a function in the object and have it write the information itself. This type of programming is very flexible, since we can later change how record stores its data, but we do not have to change anything outside of the record program.

Functions and operators relevant to objects:

indexing
Objects can be indexed on strings to access identifiers. If the identifier is a variable, the value can also be set using indexing. If the identifier is a function, a pointer to that function will be returned. If the identifier is a constant, the value of that constant will be returned. Note that the -> operator is actually the same as indexing. This means that o->foo is the same as o["foo"]
cloning
As discussed in the section about programs, cloning a program is done by using a pointer to the program as a function and calling it. Whenever you clone an object, all the global variables will be initialized. After that the function create will be called with any arguments you call the program with.
void destruct(object o)
This function invalidates all references to the object o and frees all variables in that object. This function is also called when o runs out of references. If there is a function named destroy in the object, it will be called before the actual destruction of the object.
array(string) indices(object o)
This function returns a list of all identifiers in the object o.
program object_program(object o)
This function returns the program from which o was cloned.
int objectp(mixed o)
This function returns 1 if o is an object, 0 otherwise. Note that if o has been destructed, this function will return 0.
object this_object()
This function returns the object in which the interpreter is currently executing.
array values(object o)
This function returns the same as rows(o,indices(o)). That means it returns all the values of the identifiers in the object o.
comparing
As with all data types == and != can be used to check if two objects are the same or not.

2.2.6. function

When indexing an object on a string, and that string is the name of a function in the object a function is returned. Despite its name, a function is really a function pointer.

When the function pointer is called, the interpreter sets this_object() to the object in which the function is located and proceeds to execute the function it points to. Also note that function pointers can be passed around just like any other data type:

int foo() { return 1; }
function bar() { return foo; }
int gazonk() { return foo(); }
int teleledningsanka() { return bar()(); }

In this example, the function bar returns a pointer to the function foo. No indexing is necessary since the function foo is located in the same object. The function gazonk simply calls foo. However, note that the word foo in that function is an expression returning a function pointer that is then called. To further illustrate this, foo has been replaced by bar() in the function teleledningsanka.

For convenience, there is also a simple way to write a function inside another function. To do this you use the lambda keyword. The syntax is the same as for a normal function, except you write lambda instead of the function name:

lambda ( types ) { statements }

The major difference is that this is an expression that can be used inside an other function. Example:

function bar() { return lambda() { return 1; }; )

This is the same as the first two lines in the previous example, the keyword lambda allows you to write the function inside bar.

Note that unlike C++ and Java you can not use function overloading in Pike. This means that you cannot have one function called 'foo' which takes an integer argument and another function 'foo' which takes a float argument.

This is what you can do with a function pointer.

calling ( f ( mixed ... args ) )
As mentioned earlier, all function pointers can be called. In this example the function f is called with the arguments args.
string function_name(function f)
This function returns the name of the function f is pointing at.
object function_object(function f)
This function returns the object the function f is located in.
int functionp(mixed f)
This function returns 1 if f is a function, 0 otherwise. If f is located in a destructed object, 0 is returned.
function this_function()
This function returns a pointer to the function it is called from. This is normally only used with lambda functions because they do not have a name.

2.3. Compile-time types

There are two types that are pure compile-time types:

2.3.1. void

The type void is used to indicate the absence or optionality of a value. There are two typical use cases:

As the return type of a function (eg void foo();).
This indicates that the function does not return any value.
As one of the types in a type set for a function parameter (eg int foo(int|void param)).
This indicates that the caller of the function may omit that parameter when calling the function, in which case it will default to the special value UNDEFINED.

When creating functions with optional parameters the following functions may be of interest:

int undefinedp(mixed x)
This function returns 1 if x is UNDEFINED, and 0 otherwise.
int query_num_arg()
This function returns the number of arguments that the calling function got called with.

2.3.2. mixed

The type mixed is used to indicate that values of any type may be passed here, and that the actual type of the values that will be used at run-time is totally unknown.

This type is typically used when implementing container classes (where the actual values won't be manipulated by the code in the class), or as a convenience fall-back when the actual compile-time type is getting too complicated.

2.3.3. Constructed types

Futhermore more specific compile-time types may be constructed by either subtyping the basic types by specifying parameters (eg function(string(7bit), int(0..): string(7bit)) instead of just plain function), or by using the type union operator (`|) to specify several alternative types (eg int|float instead of mixed). Note that the run-time type may differ from the declared compile-time type (like eg function(string, int: string(7bit)) and int(17..17) respectively).

2.4. Sharing data

As mentioned in the beginning of this chapter, the assignment operator (=) does not copy anything when you use it on a pointer type. Instead it just creates another reference to the memory object. In most situations this does not present a problem, and it speeds up Pike's performance. However, you must be aware of this when programming. This can be illustrated with an example:

int main(int argc, array(string) argv)
{
  array(string) tmp;
  tmp=argv;
  argv[0]="Hello world.\n";
  write(tmp[0]);
}

This program will of course write Hello world.

Sometimes you want to create a copy of a mapping, array or object. To do so you simply call copy_value with whatever you want to copy as argument. Copy_value is recursive, which means that if you have an array containing arrays, copies will be made of all those arrays.

If you don't want to copy recursively, or you know you don't have to copy recursively, you can use the plus operator instead. For instance, to create a copy of an array you simply add an empty array to it, like this: copy_of_arr = arr + ({}); If you need to copy a mapping you use an empty mapping, and for a multiset you use an empty multiset.

2.5. Variables

When declaring a variable, you also have to specify what type of variable it is. For most types, such as int and string this is very easy. But there are much more interesting ways to declare variables than that, let's look at a few examples:

int x; // x is an integer
int|string x; // x is a string or an integer
array(string) x; // x is an array of strings
array x; // x is an array of mixed
mixed x; // x can be any type
string *x; // x is an array of strings

// x is a mapping from int to string
mapping(string:int) x;

// x implements Stdio.File
Stdio.File x;

// x implements Stdio.File
object(Stdio.File) x;

// x is a function that takes two integer
// arguments and returns a string
function(int,int:string) x;

// x is a function taking any amount of
// integer arguments and returns nothing.
function(int...:void) x;

// x is ... complicated
mapping(string:function(string|int...:mapping(string:array(string)))) x;

As you can see there are some interesting ways to specify types. Here is a list of what is possible:

mixed
This means that the variable can contain any type, or the function return any value.
array( type )
This means an array of elements with the type type.
mapping( key type : value type )
This is a mapping where the keys are of type key type and the values of value type.
multiset ( type )
This means a multiset containing values of the type type.
object ( program )
This means an object which 'implements' the specified program. The program can be a class, a constant, or a string. If the program is a string it will be casted to a program first. See the documentation for inherit for more information about this casting. The compiler will assume that any function or variable accessed in this object has the same type information as that function or variable has in program.
program
This too means 'an object which implements program'. program can be a class or a constant.
function( argument types : return type )
This is a function taking the specified arguments and returning return type. The argument types is a comma separated list of types that specify the arguments. The argument list can also end with ... to signify that there can be any amount of the last type.
type1 | type2
This means either type1 or type2
void
Void can only be used in certain places, if used as return type for a function it means that the function does not return a value. If used in the argument list for a function it means that that argument can be omitted. Example: function(int|void:void) this means a function that may or may not take an integer argument and does not return a value.

3. Language Reference

Namespace ::

Description

Symbols implicitly inherited from the virtual base class.

These symbols exist mainly to simplify implementation of the corresponding lfuns.

See also

lfun::


Method _annotations

array _annotations(object|void context, int|void access, bool|void recursive)

Description

Called by annotations()

Parameter context

Inherit in the current object to return the annotations for. If UNDEFINED or left out, this_program::this should be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

Parameter recursive

Include nested annotations from the inherits.

Builtin function to list the annotations (if any) of the identifiers of an object. This is useful when lfun::_annotations has been overloaded.

See also

annotations(), lfun::_annotations()


Method _indices

array(string) _indices(object|void context, int|void access)

Parameter context

Context in the current object to start the list from. If UNDEFINED or left out, this_program::this will be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

Builtin function to list the identifiers of an object. This is useful when lfun::_indices has been overloaded.

See also

::_values(), ::_types(), ::`->()


Method _types

array _types(object|void context, int|void access)

Parameter context

Context in the current object to start the list from. If UNDEFINED or left out, this_program::this will be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

Builtin function to list the types of the identifiers of an object. This is useful when lfun::_types has been overloaded.

See also

::_indices(), ::_values(), ::`->()


Method _values

array _values(object|void context, int|void access)

Parameter context

Context in the current object to start the list from. If UNDEFINED or left out, this_program::this will be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

Builtin function to list the values of the identifiers of an object. This is useful when lfun::_values has been overloaded.

See also

::_indices(), ::_types(), ::`->()


Method `->

mixed `->(string index, object|void context, int|void access)

Description

Builtin arrow operator.

Parameter index

Symbol in context to access.

Parameter context

Context in the current object to start the search from. If UNDEFINED or left out, this_program::this will be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

This function indexes the current object with the string index. This is useful when the arrow operator has been overloaded.

See also

::`->=()


Method `->=

mixed `->=(string index, mixed value, object|void context, int|void access)

Description

Builtin atomic arrow get and set operator.

Parameter index

Symbol in context to change the value of.

Parameter value

The new value.

Parameter context

Context in the current object to start the search from. If UNDEFINED or left out, this_program::this will be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

This function indexes the current object with the string index, and sets it to value. This is useful when the arrow set operator has been overloaded.

Returns

Returns the previous value at index index of the current object.

See also

::`->()

Namespace 7.8::

Description

Pike 7.8 compatibility.

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


Inherit

inherit 8.0:: :

Module Crypto

Class Crypto.DSA

Description

The Digital Signature Algorithm (aka DSS, Digital Signature Standard).


Method generate_key

this_program generate_key()

Description

Generates a public/private key pair. Needs the public parameters p, q and g set, either through set_public_key or generate_parameters.


Method generate_parameters

this_program generate_parameters(int bits)

Description

Generate key parameters using nist_primes.


Method get_g

Gmp.mpz|zero get_g()

Description

Returns the generator.


Method get_p

Gmp.mpz|zero get_p()

Description

Returns the modulo.


Method get_q

Gmp.mpz|zero get_q()

Description

Returns the group order.


Method get_x

Gmp.mpz|zero get_x()

Description

Returns the private key.


Method get_y

Gmp.mpz|zero get_y()

Description

Returns the public key.


Method hash

Gmp.mpz hash(string msg)

Description

Makes a DSA hash of the messge msg.


Method name

string name()

Description

Returns the string "DSA".


Method nist_primes

array(Gmp.mpz) nist_primes(int l)

Description

The (slow) NIST method of generating a DSA prime pair. Algorithm 4.56 of Handbook of Applied Cryptography.


Method public_key_equal

bool public_key_equal(.DSA dsa)

Description

Compares the public key in this object with that in the provided DSA object.


Method raw_sign

array(Gmp.mpz) raw_sign(Gmp.mpz h, void|Gmp.mpz k)

Description

Sign the message h. Returns the signature as two Gmp.mpz objects.


Method raw_verify

bool raw_verify(Gmp.mpz h, Gmp.mpz r, Gmp.mpz s)

Description

Verify the signature r,s against the message h.


Method set_private_key

this_program set_private_key(Gmp.mpz secret)

Description

Sets the private key in this DSA object.


Method set_public_key

this_program set_public_key(Gmp.mpz p_, Gmp.mpz q_, Gmp.mpz g_, Gmp.mpz y_)

Description

Sets the public key in this DSA object.


Method set_random

this_program set_random(function(int(0..):string) r)

Description

Sets the random function, used to generate keys and parameters, to the function r. Default is Crypto.Random.random_string.


Method sign_rsaref

string sign_rsaref(string msg)

Description

Make a RSA ref signature of message msg.


Method sign_ssl

string sign_ssl(string msg)

Description

Make an SSL signature of message msg.


Method verify_rsaref

bool verify_rsaref(string msg, string s)

Description

Verify a RSA ref signature s of message msg.


Method verify_ssl

bool verify_ssl(string msg, string s)

Description

Verify an SSL signature s of message msg.

Class Crypto.RSA


Method cooked_get_d

string cooked_get_d()

Description

Returns the RSA private exponent (d) as a binary string, if known.


Method cooked_get_e

string cooked_get_e()

Description

Returns the RSA public exponent (e) as a binary string.


Method cooked_get_n

string cooked_get_n()

Description

Returns the RSA modulo (n) as a binary string.


Method cooked_get_p

string cooked_get_p()

Description

Returns the first RSA prime (p) as a binary string, if known.


Method cooked_get_q

string cooked_get_q()

Description

Returns the second RSA prime (q) as a binary string, if known.


Method cooked_sign

string cooked_sign(string digest)

Description

Signs digest as raw_sign and returns the signature as a byte string.


Method create

Crypto.RSA Crypto.RSA(mapping(string:Gmp.mpz|int)|void params)

Description

Can be initialized with a mapping with the elements n, e, d, p and q.


Method crypt

string crypt(string s)

Description

Encrypt or decrypt depending on set mode.

See also

set_encrypt_key, set_decrypt_key


Method decrypt

string decrypt(string s)

Description

Decrypt a message encrypted with encrypt.


Method encrypt

string encrypt(string s, function(int:string)|void r)

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.


Method generate_key

this_program generate_key(int(128..) bits, function(int:string)|void r)

Description

Generate a valid RSA key pair with the size bits. A random function may be provided as arguemnt r, otherwise Crypto.Random.random_string will be used. Keys must be at least 128 bits.


Method get_d

Gmp.mpz get_d()

Description

Returns the RSA private exponent (d), if known.


Method get_e

Gmp.mpz get_e()

Description

Returns the RSA public exponent (e).


Method get_n

Gmp.mpz get_n()

Description

Returns the RSA modulo (n).


Method get_p

Gmp.mpz get_p()

Description

Returns the first RSA prime (p), if known.


Method get_prime

Gmp.mpz get_prime(int bits, function(int:string) r)

Description

Generate a prime with bits number of bits using random function r.


Method get_q

Gmp.mpz get_q()

Description

Returns the second RSA prime (q), if known.


Method name

string name()

Description

Returns the string "RSA".


Method public_key_equal

bool public_key_equal(this_program rsa)

Description

Compares the public key of this RSA object with another RSA object.


Method query_blocksize

int query_blocksize()

Description

Returns the crypto block size, or zero if not yet set.


Method raw_sign

Gmp.mpz raw_sign(string digest)

Description

Pads the digest with rsa_pad type 1 and signs it.


Method raw_verify

bool raw_verify(string digest, Gmp.mpz s)

Description

Verifies the digest against the signature s, assuming pad type 1.

See also

rsa_pad, raw_sign


Method rsa_pad

Gmp.mpz rsa_pad(string message, int(1..2) type, function(int:string)|void random)

Description

Pads the message to the current block size with method type and returns the result as an integer. This is equivalent to OS2IP(EME-PKCS1-V1_5-ENCODE(message)) in PKCS-1.

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 Crypto.Random.random_string will be used.


Method rsa_size

int(0..) rsa_size()

Description

Returns the size of the key in terms of number of bits.


Method rsa_unpad

string rsa_unpad(Gmp.mpz block, int type)

Description

Reverse the effect of rsa_pad.


Method set_decrypt_key

this_program set_decrypt_key(array(Gmp.mpz) key)

Description

Sets the public key to keyand the mod to decryption.

See also

set_encrypt_key, crypt


Method set_encrypt_key

this_program set_encrypt_key(array(Gmp.mpz) key)

Description

Sets the public key to key and the mode to encryption.

See also

set_decrypt_key, crypt


Method set_private_key

this_program set_private_key(Gmp.mpz|int priv, array(Gmp.mpz|int)|void extra)

Description

Sets the private key.

Parameter priv

The private RSA exponent, often called d.

Parameter extra
Array
Gmp.mpz|int 0

The first prime, often called p.

Gmp.mpz|int 1

The second prime, often called q.


Method set_public_key

this_program set_public_key(Gmp.mpz|int modulo, Gmp.mpz|int pub)

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.


Method sha_sign

string sha_sign(string message, mixed|void r)

FIXME

Document this function.


Method sha_verify

int sha_verify(string message, string signature)

FIXME

Document this function.


Method sign

Gmp.mpz sign(string message, Crypto.Hash h)

Description

Signs the message with a PKCS-1 signature using hash algorithm h.


Method verify

bool verify(string msg, Crypto.Hash h, Gmp.mpz sign)

Description

Verify PKCS-1 signature sign of message msg using hash algorithm h.

Module Filesystem


Method `()

function(:void) `()(void|string path)

Description

FIXME: Document this function


Method get_filesystem

program get_filesystem(string what)

Description

FIXME: Document this function


Method parse_mode

int parse_mode(int old, int|string mode)

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.


Method apply

int apply()

Description

FIXME: Document this function


Method cd

Base cd(string|void directory)

Description

Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.


Method chmod

void chmod(string filename, int|string mode)

Description

Change mode of a file or directory.


Method chown

void chown(string filename, int|object owner, int|object group)

Description

Change ownership of the file or directory


Method chroot

Base chroot(void|string directory)

Description

Change the root of the filesystem.


Method cwd

string cwd()

Description

Returns the current working directory within the filesystem.


Method find

array find(void|function(Stat:int) mask, mixed ... extra)

Description

FIXME: Document this function


Method get_dir

array(string) get_dir(void|string directory, void|string|array glob)

Description

Returns an array of all files and directories within a given directory.

Parameter directory

Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.

Parameter glob

Return only files and dirs matching the glob (if given).

See also

[get_stats]


Method get_stats

array(Stat) get_stats(void|string directory, void|string|array glob)

Description

Returns stat-objects for the files and directories matching the given glob within the given directory.

See also

[get_dir]


Method mkdir

int mkdir(string directory, void|int|string mode)

Description

Create a new directory


Method open

Stdio.File open(string filename, string mode)

Description

Open a file within the filesystem

Returns

A Stdio.File object.


Method rm

int rm(string filename)

Description

Remove a file from the filesystem.


Method stat

Stat stat(string file, int|void lstat)

Description

Return a stat-object for a file or a directory within the filesystem.

Class Filesystem.Stat

Description

Describes the stat of a file


Method attach_statarray

void attach_statarray(array(int) a)

Description

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


Method cd

object cd()

Description

Change to the stated directory.

Returns

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


Method isblk

bool isblk()

Description

Is the file a block device?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method ischr

bool ischr()

Description

Is the file a character device?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method isdir

bool isdir()

Description

Is the file (?) a directory?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method isdoor

bool isdoor()

Description

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method isfifo

bool isfifo()

Description

Is the file a FIFO?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method islnk

bool islnk()

Description

Is the file a link to some other file or directory?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method isreg

bool isreg()

Description

Is the file a regular file?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method issock

bool issock()

Description

Is the file a socket?

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method nice_date

string nice_date()

Description

Returns the date of the stated object as cleartext.


Method open

Stdio.File open(string mode)

Description

Open the stated file within the filesystem

Returns

a [Stdio.File] object

See also

[Stdio.File]


Method set_type

void set_type(string x)

Description

Set a type for the stat-object.

Note

This call doesnot change the filetype in the underlaying filesystem.

Parameter x

Type to set. Type is one of the following:

  • fifo
  • chr
  • dir
  • blk
  • reg
  • lnk
  • sock
  • door
See also

[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]

Class Filesystem.System

Description

Implements an abstraction of the normal filesystem.


Method create

Filesystem.System Filesystem.System(void|string directory, void|string root, void|int fast, void|Filesystem.Base parent)

Description

Instanciate a new object representing the filesystem.

Parameter directory

The directory (in the real filesystem) that should become the root of the filesystemobject.

Parameter root

Internal

Parameter fast

Internal

Parameter parent

Internal


Inherit Base

inherit Filesystem.Base : Base

Class Filesystem.Traversion

Description

Iterator object that traverses a directory tree and returns files as values and paths as indices. Example that uses the iterator to create a really simple sort of make:

Example

object i=Filesystem.Traversion("."); foreach(i; string dir; string file) { if(!has_suffix(file, ".c")) continue; file = dir+file; string ofile = file; ofile[-1]='o'; object s=file_stat(ofile); if(s && i->stat()->mtime<s->mtime) continue; // compile file }


Method create

Filesystem.Traversion Filesystem.Traversion(string path, void|bool symlink, void|bool ignore_errors, void|function(array:array) sort_fun)

Parameter path

The root path from which to traverse.

Parameter symlink

Don't traverse symlink directories.

Parameter ignore_errors

Ignore directories that can not be accessed.

Parameter sort_fun

Sort function to be applied to directory entries before traversing. Can also be a filter function.


Method progress

float progress(void|float share)

Description

Returns the current progress of the traversion as a value between 0.0 and 1.0. Note that this value isn't based on the number of files, but the directory structure.


Method stat

Stdio.Stat stat()

Description

Returns the stat for the current index-value-pair.

Module Filesystem.Tar


Method create

void Filesystem.Tarcreate(string filename, void|Filesystem.Base parent, void|object file)

Description

Filesystem which can be used to mount a Tar file.

Parameter filename

The tar file to mount.

Parameter parent

The parent filesystem. If non is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.

Parameter file

If specified, this should be an open file descriptor. This object could e.g. be a Stdio.File, Gz.File or Bz2.File object.

Class Filesystem.Tar._Tar

Description

Low-level Tar Filesystem.


Method extract

void extract(string src_dir, string dest_dir, void|string|function(string, Filesystem.Stat:int|string) filter, void|int flags)

Description

Extracts files from the tar file in sequential order.

Parameter src_dir

The root directory in the tar file system to extract.

Parameter dest_dir

The root directory in the real file system that will receive the contents of src_dir. It is assumed to exist and be writable.

Parameter filter

A filter for the entries under src_dir to extract. If it's a string then it's taken as a glob pattern which is matched against the path below src_dir. That path always begins with a /. For directory entries it ends with a / too, otherwise not.

If it's a function then it's called for every entry under src_dir, and those where it returns nonzero are extracted. The function receives the path part below src_dir as the first argument, which is the same as in the glob case above, and the stat struct as the second. If the function returns a string, it's taken as the path below dest_dir where this entry should be extracted (any missing directories are created automatically).

If filter is zero, then everything below src_dir is extracted.

Parameter flags

Bitfield of flags to control the extraction:

Filesystem.Tar.EXTRACT_SKIP_MODE

Don't set any permission bits from the tar records.

Filesystem.Tar.EXTRACT_SKIP_EXT_MODE

Don't set set-user-ID, set-group-ID, or sticky bits from the tar records.

Filesystem.Tar.EXTRACT_SKIP_MTIME

Don't set mtime from the tar records.

Filesystem.Tar.EXTRACT_CHOWN

Set owning user and group from the tar records.

Filesystem.Tar.EXTRACT_ERR_ON_UNKNOWN

Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise.

Files and directories are supported on all platforms, and symlinks are supported whereever symlink exists. Other record types are currently not supported.

Throws

I/O errors are thrown.

Module Protocols

Module Protocols.DNS

Description

Pike 7.8 compatibility.

Some symbols in predef::Protocols.DNS that are now protected used to be visible in Pike 7.8 and earlier.


Inherit DNS

inherit Protocols.DNS : DNS


Inherit DNS

inherit predef::Protocols.DNS : DNS

Description

Based on the current Protocols.DNS.

Class Protocols.DNS.async_client

Description

Pike 7.8 compatibility version of predef::Protocols.DNS.async_client.


Method create

Protocols.DNS.async_client Protocols.DNS.async_client(void|string|array(string) server, void|string|array(string) domain)

Description

create() used to be visible.

See also

::create()


Inherit async_client

inherit DNS::async_client : async_client

Description

Based on the current Protocols.DNS.server.

Class Protocols.DNS.client

Description

Pike 7.8 compatibility version of predef::Protocols.DNS.client.


Method create

Protocols.DNS.client Protocols.DNS.client(void|string|array(string) server, void|int|array(string) domain)

Description

create() used to be visible.

See also

::create()


Inherit client

inherit DNS::client : client

Description

Based on the current Protocols.DNS.client.

Class Protocols.DNS.server

Description

Pike 7.8 compatibility version of predef::Protocols.DNS.server.


Method create

Protocols.DNS.server Protocols.DNS.server(int|string|void arg1, string|int ... args)

Description

create() used to be visible.

See also

::create()


Inherit server

inherit DNS::server : server

Description

Based on the current Protocols.DNS.server.

Module SSL

Class SSL.alert

Description

Alert packet.


Method create

SSL.alert SSL.alert(int level, int description, int version, string|void message, mixed|void trace)


Inherit packet

inherit .packet : packet

Description

Based on the base packet.

Class SSL.connection

Description

SSL packet layer.

SSL.connection inherits SSL.handshake, and in addition to the state in the handshake super class, it contains the current read and write states, packet queues. This object is responsible for receiving and sending packets, processing handshake packets, and providing a clear text packages for some application.


Method got_data

string|int got_data(string|int s)

Description

Main receive handler. Returns a string of received application data, or 1 if a close was received, or -1 if an error occurred.

This function is intended to be called from an i/o read callback.


Inherit alert

inherit ADT.Queue : alert


Inherit application

inherit ADT.Queue : application


Inherit handshake

inherit .handshake : handshake


Inherit urgent

inherit ADT.Queue : urgent


Method recv_packet

protected object recv_packet(string data)

Description

Low-level receive handler. Returns a packet, an alert, or zero if more data is needed to get a complete packet.


Method send_close

void send_close()

Description

Initiate close.


Method send_packet

void send_packet(object packet, int|void priority)

Description

Queues a packet for write. Handshake and and change cipher must use the same priority, so must application data and close_notifies.


Method send_streaming_data

int send_streaming_data(string data)

Description

Send an application data packet. If the data block is too large then as much as possible of the beginning of it is sent. The size of the sent data is returned.


Method set_alert_callback

void set_alert_callback(function(object, int|object, string:void) callback)

Description

Called with alert object, sequence number of bad packet, and raw data as arguments, if a bad packet is received.

Can be used to support a fallback redirect https->http.


Method to_write

string|int to_write()

Description

Extracts data from the packet queues. Returns a string of data to be written, "" if there are no pending packets, 1 of the connection is being closed politely, and -1 if the connection died unexpectedly.

This function is intended to be called from an i/o write callback.

Class SSL.context

Description

Keeps the state that is shared by all SSL-connections for one server (or one port). It includes policy configuration, a server certificate, the server's private key(s), etc. It also includes the session cache.


Method advertise_protocols

void advertise_protocols(string ... protos)

Description

Protocols to advertise during handshake using the next protocol negotiation extension. Currently only used together with spdy.


Variable advertised_protocols

array(string) SSL.context.advertised_protocols

Description

List of advertised protocols using using TLS next protocol negotiation.


Variable auth_level

int SSL.context.auth_level

Description

Policy for client authentication. One of SSL.Constants.AUTHLEVEL_none, SSL.Constants.AUTHLEVEL_ask and SSL.Constants.AUTHLEVEL_require.


Variable certificates

array(string) SSL.context.certificates

Description

The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.


Variable client_certificate_selector

function(.context, array(int), array(string):array(string)) SSL.context.client_certificate_selector

Description

A function which will select an acceptable client certificate for presentation to a remote server. This function will receive the SSL context, an array of acceptable certificate types, and a list of DNs of acceptable certificate authorities. This function should return an array of strings containing a certificate chain, with the client certificate first, (and the root certificate last, if applicable.)


Variable client_certificates

array(array(string)) SSL.context.client_certificates

Description

An array of certificate chains a client may present to a server when client certificate authentication is requested.


Variable client_rsa

Crypto.RSA SSL.context.client_rsa

Description

The client's private key (used with client certificate authentication)


Variable client_server_names

array(string) SSL.context.client_server_names

Description

Host names to send to the server when using the Server Name extension.


Variable client_use_sni

int SSL.context.client_use_sni

Description

Should an SSL client include the Server Name extension?

If so, then client_server_names should specify the values to send.


Variable dh_params

.Cipher.DHParameters SSL.context.dh_params

Description

Parameters for dh keyexchange.


Method dhe_dss_mode

void dhe_dss_mode(int|void min_keylength)

Description

Set preferred_suites to DSS based methods.

Parameter min_keylength

Minimum acceptable key length in bits.

See also

rsa_mode(), filter_weak_suites()


Variable dsa

Crypto.DSA SSL.context.dsa

Description

Servers default dsa key.

Note

If SNI (Server Name Indication) is used and multiple keys are available, this key will not be used, instead the appropriate SNI key will be used (the default implementation stores these in sni_keys.


Method filter_weak_suites

void filter_weak_suites(int min_keylength)

Description

Filter cipher suites from preferred_suites that don't have a key with an effective length of at least min_keylength bits.


Method get_authorities

array(string) get_authorities()

Description

Get the list of allowed authorities. See set_authorities.


Method get_trusted_issuers

array(array(string)) get_trusted_issuers()

Description

Get the list of trusted issuers. See set_trusted_issuers.


Variable long_rsa
Variable short_rsa

Crypto.RSA SSL.context.long_rsa
Crypto.RSA SSL.context.short_rsa

Description

Temporary, non-certified, private keys, used with a server_key_exchange message. The rules are as follows:

If the long_rsa is not zero its public part will be sent. If it is zero and short_rsa is set, its public part will be sent instead. If they are both zero, no server_key_exchange message is sent.


Method lookup_session

.session lookup_session(string id)

Description

Lookup a session identifier in the cache. Returns the corresponding session, or zero if it is not found or caching is disabled.


Variable max_sessions

int SSL.context.max_sessions

Description

Maximum number of sessions to keep in the cache.


Method new_session

.session new_session()

Description

Create a new session.


Variable preferred_auth_methods

array(int) SSL.context.preferred_auth_methods

Description

For client authentication. Used only if auth_level is AUTH_ask or AUTH_require.


Variable preferred_compressors

array(int) SSL.context.preferred_compressors

Description

Always ({ COMPRESSION_null })


Variable preferred_suites

array(int) SSL.context.preferred_suites

Description

Cipher suites we want to support, in order of preference, best first.


Method purge_session

void purge_session(.session s)

Description

Remove a session from the cache.


Variable random

function(int:string) SSL.context.random

Description

Used to generate random cookies for the hello-message. If we use the RSA keyexchange method, and this is a server, this random number generator is not used for generating the master_secret.


Method record_session

void record_session(.session s)

Description

Add a session to the cache (if caching is enabled).


Variable require_trust

int SSL.context.require_trust

Description

When set, require the chain to be known, even if the root is self signed.

Note that if set, and certificates are set to be verified, trusted issuers must be provided, or no connections will be accepted.


Variable rsa

Crypto.RSA SSL.context.rsa

Description

The server's default private key

Note

If SNI (Server Name Indication) is used and multiple keys are available, this key will not be used, instead the appropriate SNI key will be used (the default implementation stores these in sni_keys.


Method rsa_mode

void rsa_mode(int|void min_keylength)

Description

Set preferred_suites to RSA based methods.

Parameter min_keylength

Minimum acceptable key length in bits.

See also

dhe_dss_mode(), filter_weak_suites()


Variable select_server_certificate_func

function(.context, array(string):array(string)) SSL.context.select_server_certificate_func

Description

A function which will select an acceptable server certificate for presentation to a client. This function will receive the SSL context, and an array of server names, if provided by the client. This function should return an array of strings containing a certificate chain, with the client certificate first, (and the root certificate last, if applicable.)

The default implementation will select a certificate chain for a given server based on values contained in sni_certificates.


Variable select_server_key_func

function(.context, array(string):object) SSL.context.select_server_key_func

Description

A function which will select an acceptable server key for presentation to a client. This function will receive the SSL context, and an array of server names, if provided by the client. This function should return an object matching the certificate for the server hostname.

The default implementation will select the key for a given server based on values contained in sni_keys.


Variable session_lifetime

int SSL.context.session_lifetime

Description

Sessions are removed from the cache when they are older than this limit (in seconds). Sessions are also removed from the cache if a connection using the session dies unexpectedly.


Method set_authorities

void set_authorities(array(string) a)

Description

Array of authorities that are accepted for client certificates. The server will only accept connections from clients whose certificate is signed by one of these authorities. The string is a DER-encoded certificate, which typically must be decoded using MIME.decode_base64 or Tools.PEM.Msg first.

Note that it is presumed that the issuer will also be trusted by the server. See trusted_issuers for details on specifying trusted issuers.

If empty, the server will accept any client certificate whose issuer is trusted by the server.


Method set_trusted_issuers

void set_trusted_issuers(array(array(string)) i)

Description

Sets the list of trusted certificate issuers.

Parameter a

An array of certificate chains whose root is self signed (ie a root issuer), and whose final certificate is an issuer that we trust. The root of the certificate should be first certificate in the chain. The string is a DER-encoded certificate, which typically must be decoded using MIME.decode_base64 or Tools.PEM.Msg first.

If this array is left empty, and the context is set to verify certificates, a certificate chain must have a root that is self signed.


Variable sni_certificates

mapping(string:array(string)) SSL.context.sni_certificates

Description

A mapping containing certificate chains for use by SNI (Server Name Indication). Each entry should consist of a key indicating the server hostname and the value containing the certificate chain for that hostname.


Variable sni_keys

mapping(string:object) SSL.context.sni_keys

Description

A mapping containing private keys for use by SNI (Server Name Indication). Each entry should consist of a key indicating the server hostname and the value containing the private key object for that hostname.

Note

keys objects may be generated from a decoded key string using Standards.PKCS.RSA.parse_private_key().


Variable use_cache

int SSL.context.use_cache

Description

Non-zero to enable cahing of sessions


Variable verify_certificates

int SSL.context.verify_certificates

Description

Determines whether certificates presented by the peer are verified, or just accepted as being valid.

Class SSL.handshake

Description

SSL.handshake keeps the state relevant for SSL handshaking. This includes a pointer to a context object (which doesn't change), various buffers, a pointer to a session object (reuse or created as appropriate), and pending read and write states being negotiated.

Each connection will have two sets or read and write state: The current read and write states used for encryption, and pending read and write states to be taken into use when the current keyexchange handshake is finished.


Variable client_cert_types
Variable client_cert_distinguished_names

array(int) SSL.handshake.client_cert_types
array(string) SSL.handshake.client_cert_distinguished_names

Description

A few storage variables for client certificate handling on the client side.


Variable client_random
Variable server_random

string SSL.handshake.client_random
string SSL.handshake.server_random

Description

Random cookies, sent and received with the hello-messages.


Method create

SSL.handshake SSL.handshake(int is_server, void|SSL.context ctx, void|ProtocolVersion min_version, void|ProtocolVersion max_version)

Parameter is_server

Whether this is the server end of the connection or not.

Parameter ctx

The context for the connection.

Parameter min_version

Minimum version of SSL to support. Defaults to Constants.PROTOCOL_SSL_3_0.

Parameter max_version

Maximum version of SSL to support. Defaults to Constants.PROTOCOL_minor.


Method handle_handshake

int(-1..1) handle_handshake(int type, string data, string raw)

Description

Do handshake processing. Type is one of HANDSHAKE_*, data is the contents of the packet, and raw is the raw packet received (needed for supporting SSLv2 hello messages).

This function returns 0 if hadshake is in progress, 1 if handshake is finished, and -1 if a fatal error occurred. It uses the send_packet() function to transmit packets.

Class SSL.packet

Description

SSL Record Layer. Handle formatting and parsing of packets.


Method recv

object|string recv(string data, ProtocolVersion version)

Description

Receive data read from the network.

Parameter data

Raw data from the network.

Parameter version

Minor version of the SSL 3 protocol suite to create a packet for.

Returns

Returns a string of leftover data if packet is complete, otherwise 0.

If there's an error, an alert object is returned.


Method send

string send()

Description

Serialize the packet for sending.

Returns

Returns the serialized packet.

Class SSL.session

Description

The most important information in a session object is a choice of encryption algorithms and a "master secret" created by keyexchange with a client. Each connection can either do a full key exchange to established a new session, or reuse a previously established session. That is why we have the session abstraction and the session cache. Each session is used by one or more connections, in sequence or simultaneously.

It is also possible to change to a new session in the middle of a connection.


Variable cert_data

mapping SSL.session.cert_data

Description

information about the certificate in use by the peer, such as issuing authority, and verification status.


Variable certificate_chain

array(string) SSL.session.certificate_chain

Description

our certificate chain


Variable cipher_spec

.Cipher.CipherSpec SSL.session.cipher_spec

Description

Information about the encryption method derived from the cipher_suite.


Variable cipher_suite

int SSL.session.cipher_suite

Description

Constant defining a choice of keyexchange, encryption and mac algorithm.


Variable compression_algorithm

int SSL.session.compression_algorithm

Description

Always COMPRESSION_null.


Variable dsa

Crypto.DSA SSL.session.dsa

Description

The server's dsa private key


Method generate_keys

array(string) generate_keys(string client_random, string server_random, array(int) version)

Description

Generates keys appropriate for the SSL version given in version, based on the client_random and server_random.

Returns
Array
string 0

Client write MAC secret

string 1

Server write MAC secret

string 2

Client write key

string 3

Server write key

string 4

Client write IV

string 5

Server write IV


Variable identity

string SSL.session.identity

Description

Identifies the session to the server


Variable ke_method

int SSL.session.ke_method

Description

Key exchange method, also derived from the cipher_suite.


Variable master_secret

string SSL.session.master_secret

Description

48 byte secret shared between the client and the server. Used for deriving the actual keys.


Method new_client_states

array(.state) new_client_states(string client_random, string server_random, array(int) version)

Description

Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.

Returns
Array
SSL.state read_state

Read state

SSL.state write_state

Write state


Method new_server_states

array(.state) new_server_states(string client_random, string server_random, array(int) version)

Description

Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.

Returns
Array
SSL.state read_state

Read state

SSL.state write_state

Write state


Variable peer_certificate_chain

array(string) SSL.session.peer_certificate_chain

Description

the peer certificate chain


Variable rsa

Crypto.RSA SSL.session.rsa

Description

The server's private key


Method set_cipher_suite

void set_cipher_suite(int suite, ProtocolVersion|int version)

Description

Sets the proper authentication method and cipher specification for the given cipher suite and verison.


Method set_compression_method

void set_compression_method(int compr)

Description

Sets the compression method. Currently only COMPRESSION_null is supported.

Class SSL.sslfile

Description

Interface similar to Stdio.File.

  • Handles blocking and nonblocking mode.

  • Handles callback mode in an arbitrary backend (also in blocking mode).

  • Read and write operations might each do both reading and writing. In callback mode that means that installing either a read or a write callback might install both internally. It also means that reading in one thread while writing in another doesn't work.

  • Callback changing operations like set_blocking and set_nonblocking aren't atomic.

  • Apart from the above, thread safety/atomicity characteristics are retained.

  • Blocking characterstics are retained for all functions.

  • is_open, connection init (create) and close (close) can do both reading and writing.

  • destroy attempts to close the stream properly by sending the close packet, but since it can't do blocking I/O it's not certain that it will succeed. The stream should therefore always be closed with an explicit close call.

  • Abrupt remote close without the proper handshake gets the errno System.EPIPE.

  • Objects do not contain cyclic references, so they are closed and destructed timely when dropped.


Method close

int close(void|string how, void|int clean_close, void|int dont_throw)

Description

Close the connection. Both the read and write ends are always closed

Parameter how

This argument is only for Stdio.File compatibility and must be either "rw" or 0.

Parameter clean_close

If set then close messages are exchanged to shut down the SSL connection but not the underlying stream. It may then continue to be used for other communication afterwards. The default is to send a close message and then close the stream without waiting for a response.

Parameter dont_throw

I/O errors are normally thrown, but that can be turned off with dont_throw. In that case errno is set instead and 0 is returned. 1 is always returned otherwise. It's not an error to close an already closed connection.

Note

If a clean close is requested in nonblocking mode then the stream is most likely not closed right away, and the backend is then still needed for a while afterwards to exchange the close packets. is_open returns 2 in that time window.

Note

I/O errors from both reading and writing might occur in blocking mode.

Note

If a clean close is requested and data following the close message is received at the same time, then this object will read it and has no way to undo that. That data can be retrieved with read afterwards.

See also

shutdown


Method create

SSL.sslfile SSL.sslfile(Stdio.File stream, SSL.context ctx, int|void is_client, int|void is_blocking, SSL.Constants.ProtocolVersion|void min_version, SSL.Constants.ProtocolVersion|void max_version)

Description

Create an SSL connection over an open stream.

Parameter stream

Open socket or pipe to create the connection over.

Parameter ctx

The SSL context.

Parameter is_client

If is set then a client-side connection is started, server-side otherwise.

Parameter is_blocking

If is set then the stream is initially set in blocking mode, nonblocking mode otherwise.

Parameter min_version

The minimum minor version of SSL to support. Defaults to PROTOCOL_SSL_3_0.

Parameter max_version

The maximum minor version of SSL to support. Defaults to PROTOCOL_minor.

The backend used by stream is taken over and restored after the connection is closed (see close and shutdown). The callbacks and id in stream are overwritten.

Throws

Throws errors on handshake failure in blocking client mode.


Method destroy

protected void destroy()

Description

Try to close down the connection properly since it's customary to close files just by dropping them. No guarantee can be made that the close packet gets sent successfully though, because we can't risk blocking I/O here. You should call close explicitly.

See also

close


Method errno

int errno()

Returns

Returns the current error number for the connection. Notable values are:

0

No error

System.EPIPE

Connection closed by other end.


Method get_peer_certificate_info

mapping get_peer_certificate_info()

Returns

Returns peer certificate information, if any.


Method get_peer_certificates

array get_peer_certificates()

Returns

Returns the peer certificate chain, if any.


Method is_open

int is_open()

Returns

Returns nonzero if the stream currently is open, zero otherwise.

This function does nonblocking I/O to check for a close packet in the input buffer.

If a clean close has been requested in nonblocking mode, then 2 is returned until the close packet exchanged has been completed.

Note

In Pike 7.8 and earlier, this function returned zero in the case above where it now returns 2.


Method linger

bool linger(int(-1..65535)|void seconds)

Description

Set the linger time on close().


Variable next_protocol

string SSL.sslfile.next_protocol

Description

The next protocol chosen by the client during next protocol negotiation.

Note

Read only


Method query_accept_callback

function(void|object, void|mixed:int) query_accept_callback()

Returns

Returns the current accept callback.

See also

set_accept_callback


Method query_address

string query_address(int|void arg)

Returns

Returns the address and port of the connection.

See Stdio.File.query_address for details.

See also

Stdio.File.query_address


Method query_alert_callback

function(object, int|object, string:void) query_alert_callback()

Returns

Returns the current alert callback.

See also

set_alert_callback


Method query_backend

Pike.Backend query_backend()

Description

Return the backend used for the file callbacks.

See also

set_backend


Method query_callbacks

array(function(mixed, void|string:int)) query_callbacks()

Returns

Returns the currently set callbacks in the same order as the arguments to set_callbacks.

See also

set_callbacks, set_nonblocking


Method query_close_callback

function(void|mixed:int) query_close_callback()

Returns

Returns the current close callback.

See also

set_close_callback, set_nonblocking, query_callbacks


Method query_connection

SSL.connection query_connection()

Description

Return the SSL connection object.

This returns the low-level SSL.connection object.


Method query_context

SSL.context query_context()

Description

Return the SSL context object.


Method query_id

mixed query_id()

Returns

Returns the currently set id.

See also

set_id


Method query_read_callback

function(void|mixed, void|string:int) query_read_callback()

Returns

Returns the current read callback.

See also

set_read_callback, set_nonblocking, query_callbacks


Method query_stream

Stdio.File query_stream()

Description

Return the underlying stream.

Note

Avoid any temptation to do destruct(sslfile_obj->query_stream()). That almost certainly creates more problems than it solves.

You probably want to use shutdown.

See also

shutdown


Method query_write_callback

function(void|mixed:int) query_write_callback()

Returns

Returns the current write callback.

See also

set_write_callback, set_nonblocking, query_callbacks


Method read

string read(void|int length, void|bool not_all)

Description

Read some (decrypted) data from the connection. Works like Stdio.File.read.

Note

I/O errors from both reading and writing might occur in blocking mode.

See also

write


Method renegotiate

int renegotiate()

Description

Renegotiate the connection by starting a new handshake. Note that the accept callback will be called again when the handshake is finished.

Returns zero if there are any I/O errors. errno() will give the details.

Note

The read buffer is not cleared - a read() afterwards will return data from both before and after the renegotiation.

Bugs

Data in the write queue in nonblocking mode is not properly written before resetting the connection. Do a blocking write("") first to avoid problems with that.


Method set_accept_callback

void set_accept_callback(function(void|object, void|mixed:int) accept)

Description

Install a function that will be called when the handshake is finished and the connection is ready for use.

The callback function will be called with the sslfile object and the additional id arguments (set with set_id).

Note

Like the read, write and close callbacks, installing this callback implies callback mode, even after the handshake is done.

See also

set_nonblocking, set_callbacks, query_accept_callback, query_callbacks


Method set_alert_callback

void set_alert_callback(function(object, int|object, string:void) alert)

Description

Install a function that will be called when an alert packet is about to be sent. It doesn't affect the callback mode - it's called both from backends and from within normal function calls like read and write.

This callback can be used to implement fallback to other protocols when used on the server side together with shutdown().

Note

This object is part of a cyclic reference whenever this is set, just like setting any other callback.

Note

This callback is not cleared by set_blocking, or settable by set_callbacks or set_nonblocking. It is also not part of the set returned by query_callbacks.

See also

query_alert_callback


Method set_backend

void set_backend(Pike.Backend backend)

Description

Set the backend used for the file callbacks.

See also

query_backend


Method set_blocking

void set_blocking()

Description

Set the stream in blocking mode. All but the alert callback are zapped.

Note

There might be some data still waiting to be written to the stream. That will be written in the next blocking call, regardless what it is.

Note

This function doesn't solve the case when the connection is used nonblocking in some backend thread and another thread switches it to blocking and starts using it. To solve that, put a call out in the backend from the other thread that switches it to blocking, and then wait until that call out has run.

Note

Prior to version 7.5.12, this function didn't clear the accept callback.

See also

set_nonblocking, set_blocking_keep_callbacks, set_nonblocking_keep_callbacks


Method set_blocking_keep_callbacks

void set_blocking_keep_callbacks()

Description

Set blocking mode like set_blocking, but don't alter any callbacks.

See also

set_blocking, set_nonblocking


Method set_callbacks

void set_callbacks(void|function(mixed, string:int) read, void|function(mixed:int) write, void|function(mixed:int) close, void|function(mixed, string:int) read_oob, void|function(mixed:int) write_oob, void|function(void|mixed:int) accept)

Description

Installs all the specified callbacks at once. Use UNDEFINED to keep the current setting for a callback.

Like set_nonblocking, the callbacks are installed atomically. As opposed to set_nonblocking, this function does not do anything with the stream, and it doesn't even have to be open.

Bugs

read_oob and write_oob are currently ignored.

See also

set_read_callback, set_write_callback, set_close_callback, set_accept_callback, query_callbacks


Method set_close_callback

void set_close_callback(function(void|mixed:int) close)

Description

Install a function to be called when the connection is closed, either normally or due to an error (use errno to retrieve it).

See also

query_close_callback, set_nonblocking, query_callbacks


Method set_id

void set_id(mixed id)

Description

Set the value to be sent as the first argument to the callbacks installed by set_callbacks.

See also

query_id


Method set_nonblocking

void set_nonblocking(void|function(void|mixed, void|string:int) read, void|function(void|mixed:int) write, void|function(void|mixed:int) close, void|function(void|mixed:int) read_oob, void|function(void|mixed:int) write_oob, void|function(void|mixed:int) accept)

Description

Set the stream in nonblocking mode, installing the specified callbacks. The alert callback isn't touched.

Note

Prior to version 7.5.12, this function didn't set the accept callback.

Bugs

read_oob and write_oob are currently ignored.

See also

set_callbacks, query_callbacks, set_nonblocking_keep_callbacks, set_blocking


Method set_nonblocking_keep_callbacks

void set_nonblocking_keep_callbacks()

Description

Set nonblocking mode like set_nonblocking, but don't alter any callbacks.

See also

set_nonblocking, set_blocking, set_blocking_keep_callbacks


Method set_read_callback

void set_read_callback(function(void|mixed, void|string:int) read)

Description

Install a function to be called when data is available.

See also

query_read_callback, set_nonblocking, query_callbacks


Method set_write_callback

void set_write_callback(function(void|mixed:int) write)

Description

Install a function to be called when data can be written.

See also

query_write_callback, set_nonblocking, query_callbacks


Method shutdown

Stdio.File shutdown()

Description

Shut down the SSL connection without sending any more packets.

If the connection is open then the underlying (still open) stream is returned.

If a nonclean (i.e. normal) close has been requested then the underlying stream is closed now if it wasn't closed already, and zero is returned.

If a clean close has been requested (see the second argument to close) then the behavior depends on the state of the close packet exchange: The first shutdown call after a successful exchange returns the (still open) underlying stream, and later calls return zero and clears errno. If the exchange hasn't finished then the stream is closed, zero is returned, and errno will return System.EPIPE.

See also

close, set_alert_callback


Method write

int write(string|array(string) data, mixed ... args)

Description

Write some (unencrypted) data to the connection. Works like Stdio.File.write except that this function often buffers some data internally, so there's no guarantee that all the consumed data has been successfully written to the stream in nonblocking mode. It keeps the internal buffering to a minimum, however.

Note

This function returns zero if attempts are made to write data during the handshake phase and the mode is nonblocking.

Note

I/O errors from both reading and writing might occur in blocking mode.

See also

read

Class SSL.sslport

Description

Interface similar to Stdio.Port.


Method accept

SSL.sslfile accept()

Description

Get the next pending SSL.sslfile from the accept_queue.

Returns

Returns the next pending SSL.sslfile if any, and 0 (zero) if there are none.


Variable accept_callback

function(object, mixed|void:void) SSL.sslport.accept_callback


Method bind

int bind(int port, function(SSL.sslfile|void, mixed|void:int) callback, string|void ip)

Description

Bind an SSL port.

Parameter port

Port number to bind.

Parameter callback

Callback to call when the SSL connection has been negotiated.

The callback is called with an SSL.sslfile as the first argument, and the id for the SSL.sslfile as the second.

If the callback is 0 (zero), then negotiated SSL.sslfiles will be enqueued for later retrieval with accept().

Parameter ip

Optional IP-number to bind.

Returns

Returns 1 if binding of the port succeeded, and 0 (zero) on failure.

See also

Stdio.Port()->bind(), SSL.sslfile()->set_accept_callback(), listen_fd()


Method create

SSL.sslport SSL.sslport()

Description

Create a new port for accepting SSL connections.

See also

bind(), listen_fd()


Method finished_callback

void finished_callback(SSL.sslfile f, mixed|void id)

Description

SSL connection accept callback.

Parameter f

The SSL.sslfile that just finished negotiation.

This function is installed as the SSL.sslfile accept callback by ssl_callback(), and enqueues the newly negotiated SSL.sslfile on the accept_queue.

If there has been an accept_callback installed by bind() or listen_fd(), it will be called with all pending SSL.sslfiles on the accept_queue.

If there's no accept_callback, then the SSL.sslfile will have to be retrieved from the queue by calling accept().


Inherit accept_queue

inherit ADT.Queue : accept_queue


Inherit context

inherit .context : context


Inherit socket

inherit Stdio.Port : socket


Method listen_fd

int listen_fd(int fd, function(SSL.sslfile|void, mixed|void:int) callback)

Description

Set up listening for SSL connections on an already opened fd.

Parameter fd

File descriptor to listen on.

Parameter callback

Callback to call when the SSL connection has been negotiated.

The callback is called with an SSL.sslfile as the first argument, and the id for the SSL.sslfile as the second.

If the callback is 0 (zero), then negotiated SSL.sslfiles will be enqueued for later retrieval with accept().

Returns

Returns 1 if listening on the fd succeeded, and 0 (zero) on failure.

See also

Stdio.Port()->listen_fd(), SSL.sslfile()->set_accept_callback(), bind()


Method socket_accept

Stdio.File socket_accept()

Description

Low-level accept.

See also

Stdio.Port()->accept()


Method ssl_callback

void ssl_callback(mixed id)

Description

Connection accept callback.

This function is installed as the Stdio.Port callback, and accepts the connection and creates a corresponding SSL.sslfile with finished_callback() as the accept callback.

See also

bind(), finished_callback()

Class SSL.state

Description

A connection switches from one set of state objects to another, one or more times during its lifetime. Each state object handles a one-way stream of packets, and operates in either decryption or encryption mode.


Constant Alert

constant SSL.state.Alert


Variable crypt

.Cipher.CipherAlgorithm SSL.state.crypt

Description

Encryption or decryption object.


Method decrypt_packet

Alert|.packet decrypt_packet(.packet packet, ProtocolVersion version)

Description

Destructively decrypts a packet (including inflating and MAC-verification, if needed). On success, returns the decrypted packet. On failure, returns an alert packet. These cases are distinguished by looking at the is_alert attribute of the returned packet.


Method encrypt_packet

Alert|.packet encrypt_packet(.packet packet, ProtocolVersion version)

Description

Encrypts a packet (including deflating and MAC-generation).


Variable mac

.Cipher.MACAlgorithm SSL.state.mac

Description

Message Authentication Code


Variable seq_num

Gmp.mpz SSL.state.seq_num

Description

64-bit sequence number.


Variable session

object SSL.state.session

Description

Information about the used algorithms.


Variable tls_iv

int SSL.state.tls_iv

Description

TLS IV prefix length.

Module SSL.Cipher

Description

Encryption and MAC algorithms used in SSL.


Method anon_sign

ADT.struct anon_sign(object context, string cookie, ADT.struct struct)

Description

The NULL signing method.


Method dsa_sign

ADT.struct dsa_sign(object context, string cookie, ADT.struct struct)

Description

Signing using DSA.


Method lookup

array lookup(int suite, ProtocolVersion|int version)

Description

Lookup the crypto parameters for a cipher suite.

Parameter suite

Cipher suite to lookup.

Parameter version

Minor version of the SSL protocol to support.

Returns

Returns 0 (zero) for unsupported combinations. Otherwise returns an array with the following fields:

Array
KeyExchangeType 0

Key exchange method.

CipherSpec 1

Initialized CipherSpec for the suite.


Method prf

string prf(string secret, string label, string seed, int len)

Description

The Pseudo Random Function used to derive the secret keys.


Method rsa_sign

ADT.struct rsa_sign(object context, string cookie, ADT.struct struct)

Description

Signing using RSA.


Method rsa_verify

bool rsa_verify(object context, string cookie, ADT.struct struct, Gmp.mpz signature)

Description

Verify an RSA signature.

Class SSL.Cipher.AES


Inherit CBC

inherit Crypto.CBC : CBC

Class SSL.Cipher.CipherAlgorithm

Description

Cipher algorithm interface.


Method block_size

int(0..) block_size()

Description

Return the block size for this crypto.


Method set_encrypt_key
Method set_decrypt_key

this_program set_encrypt_key(string)
this_program set_decrypt_key(string)

Description

Set the key used for encryption/decryption, and enter encryption mode.

Class SSL.Cipher.CipherSpec

Description

Cipher specification.


Variable bulk_cipher_algorithm

program SSL.Cipher.CipherSpec.bulk_cipher_algorithm

Description

The algorithm to use for the bulk of the transfered data.


Variable hash_size

int SSL.Cipher.CipherSpec.hash_size

Description

The number of bytes in the MAC hashes.


Variable iv_size

int SSL.Cipher.CipherSpec.iv_size

Description

The number of bytes of random data needed for initialization vectors.


Variable key_bits

int SSL.Cipher.CipherSpec.key_bits

Description

The effective number of bits in key_material.

This is typically key_material * 8, but for eg DES this is key_material * 7.


Variable key_material

int SSL.Cipher.CipherSpec.key_material

Description

The number of bytes of key material used on initialization.


Variable mac_algorithm

program SSL.Cipher.CipherSpec.mac_algorithm

Description

The Message Authentication Code to use for the packets.


Variable sign

function(object, string, ADT.struct:ADT.struct) SSL.Cipher.CipherSpec.sign

Description

The function used to sign packets.


Variable verify

function(object, string, ADT.struct, Gmp.mpz:bool) SSL.Cipher.CipherSpec.verify

Description

The function used to verify the signature for packets.

Class SSL.Cipher.DES


Inherit CBC

inherit Crypto.CBC : CBC

Class SSL.Cipher.DES3


Inherit CBC

inherit Crypto.CBC : CBC

Class SSL.Cipher.DHKeyExchange

Description

Implements Diffie-Hellman key-exchange.

The following key exchange methods are implemented here: KE_dhe_dss, KE_dhe_rsa and KE_dh_anon.


Method create

SSL.Cipher.DHKeyExchange SSL.Cipher.DHKeyExchange(DHParameters p)

Class SSL.Cipher.DHParameters

Description

Diffie-Hellman parameters.


Method create

SSL.Cipher.DHParameters SSL.Cipher.DHParameters(object ... args)


Variable p
Variable g
Variable order

Gmp.mpz SSL.Cipher.DHParameters.p
Gmp.mpz SSL.Cipher.DHParameters.g
Gmp.mpz SSL.Cipher.DHParameters.order

Class SSL.Cipher.IDEA


Inherit CBC

inherit Crypto.CBC : CBC

Class SSL.Cipher.MACAlgorithm

Description

Message Authentication Code interface.


Method hash

string hash(object packet, Gmp.mpz seq_num)

Parameter packet

Packet to generate a MAC hash for.

Parameter seq_num

Sequence number for the packet in the stream.

Returns

Returns the MAC hash for the packet.


Constant hash_header_size

constant int SSL.Cipher.MACAlgorithm.hash_header_size

Description

The length of the header prefixed by hash().


Method hash_raw

string hash_raw(string data)

Description

Hashes the data with the hash algorithm and retuns it as a raw binary string.

Class SSL.Cipher.MAChmac_md5

Description

HMAC using MD5.

This is the MAC algorithm used by TLS 1.0 and later.


Method create

SSL.Cipher.MAChmac_md5 SSL.Cipher.MAChmac_md5(string|void s)


Inherit MAChmac_sha

inherit MAChmac_sha : MAChmac_sha

Class SSL.Cipher.MAChmac_sha

Description

HMAC using SHA.

This is the MAC algorithm used by TLS 1.0 and later.


Method create

SSL.Cipher.MAChmac_sha SSL.Cipher.MAChmac_sha(string|void s)


Method hash

string hash(object packet, Gmp.mpz seq_num)


Constant hash_header_size

constant int SSL.Cipher.MAChmac_sha.hash_header_size

Description

The length of the header prefixed by hash().


Inherit MACAlgorithm

inherit MACAlgorithm : MACAlgorithm

Class SSL.Cipher.MACmd5

Description

MAC using MD5.

Note

Note: This uses the algorithm from the SSL 3.0 draft.


Inherit MACsha

inherit MACsha : MACsha

Class SSL.Cipher.MACsha

Description

MAC using SHA.

Note

Note: This uses the algorithm from the SSL 3.0 draft.


Method create

SSL.Cipher.MACsha SSL.Cipher.MACsha(string|void s)


Method hash

string hash(object packet, Gmp.mpz seq_num)


Constant hash_header_size

constant int SSL.Cipher.MACsha.hash_header_size

Description

The length of the header prefixed by hash().


Method hash_master

string hash_master(string data, string|void s)


Inherit MACAlgorithm

inherit MACAlgorithm : MACAlgorithm

Module SSL.Constants

Description

Protocol constants


Constant CIPHER_algorithms

constant SSL.Constants.CIPHER_algorithms

Description

Mapping from cipher algorithm to effective key length.


Constant PROTOCOL_major
Constant PROTOCOL_minor

constant int SSL.Constants.PROTOCOL_major
constant int SSL.Constants.PROTOCOL_minor

Description

Max supported SSL version.

Enum SSL.Constants.CompressionType

Description

Compression methods.


Constant COMPRESSION_deflate

constant SSL.Constants.COMPRESSION_deflate

Description

Deflate compression.


Constant COMPRESSION_lzs

constant SSL.Constants.COMPRESSION_lzs

Description

LZS compression.


Constant COMPRESSION_null

constant SSL.Constants.COMPRESSION_null

Description

No compression.

Enum SSL.Constants.KeyExchangeType

Description

Key exchange methods.


Constant KE_dh

constant SSL.Constants.KE_dh

Description

Diffie-Hellman


Constant KE_dh_anon

constant SSL.Constants.KE_dh_anon

Description

Diffie-Hellman Anonymous


Constant KE_dhe_dss

constant SSL.Constants.KE_dhe_dss

Description

Diffie-Hellman DSS


Constant KE_dhe_rsa

constant SSL.Constants.KE_dhe_rsa

Description

Diffie-Hellman RSA


Constant KE_dms

constant SSL.Constants.KE_dms


Constant KE_rsa

constant SSL.Constants.KE_rsa

Description

Rivest-Shamir-Adelman

Enum SSL.Constants.ProtocolVersion

Description

Constants for specifying the versions of SSL to use.

See also

SSL.sslfile()->create(), SSL.handshake()->create()


Constant PROTOCOL_SSL_3_0

constant SSL.Constants.PROTOCOL_SSL_3_0

Description

SSL 3.0 - The original SSL3 draft version.


Constant PROTOCOL_SSL_3_1

constant SSL.Constants.PROTOCOL_SSL_3_1

Description

SSL 3.1 - The RFC 2246 version of SSL.


Constant PROTOCOL_SSL_3_2

constant SSL.Constants.PROTOCOL_SSL_3_2

Description

SSL 3.2 - The RFC 4346 version of SSL.


Constant PROTOCOL_TLS_1_0

constant SSL.Constants.PROTOCOL_TLS_1_0

Description

TLS 1.0 - The RFC 2246 version of TLS.


Constant PROTOCOL_TLS_1_1

constant SSL.Constants.PROTOCOL_TLS_1_1

Description

TLS 1.1 - The RFC 4346 version of TLS.

Module Standards

Module Standards.ASN1

Module Standards.ASN1.Types

Description

Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)


Variable TaggedType0
Variable TaggedType1
Variable TaggedType2
Variable TaggedType3

MetaExplicit Standards.ASN1.Types.TaggedType0
MetaExplicit Standards.ASN1.Types.TaggedType1
MetaExplicit Standards.ASN1.Types.TaggedType2
MetaExplicit Standards.ASN1.Types.TaggedType3

Description

Some common explicit tags for convenience.

These are typically used to indicate which of several optional fields are present.

Example

Eg RFC 5915 section 3:

ECPrivateKey ::= SEQUENCE {
      version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
      privateKey     OCTET STRING,
      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
      publicKey  [1] BIT STRING OPTIONAL
    }

The presence of the fields parameters and publicKey above are indicated with TaggedType0 and TaggedType1 respectively.


Method asn1_IA5_valid

bool asn1_IA5_valid(string s)


Method asn1_bmp_valid

bool asn1_bmp_valid(string s)


Method asn1_broken_teletex_valid

bool asn1_broken_teletex_valid(string s)


Method asn1_printable_valid

bool asn1_printable_valid(string s)

Description

Checks if a Pike string can be encoded as a PrintableString.


Method asn1_teletex_valid

bool asn1_teletex_valid(string s)


Method asn1_universal_valid

int(0) asn1_universal_valid(string s)


Method asn1_utf8_valid

int(1) asn1_utf8_valid(string s)

Description

Checks if a Pike string can be encoded with UTF8. That is always the case...


Method extract_cls

int(2bit) extract_cls(int i)

Description

Extract ASN1 type class from a combined tag.

See also

make_combined_tag


Method extract_tag

int extract_tag(int i)

Description

Extract ASN1 type tag from a combined tag.

See also

make_combined_tag


Method make_combined_tag

int make_combined_tag(int cls, int tag)

Description

Combines tag and class to a single integer, for internal uses.

Parameter cls

ASN1 type class (0..3).

Parameter tag

ASN1 type tag (1..).

Returns

The combined tag.

See also

extract_tag, extract_cls

Class Standards.ASN1.Types.BMPString

Description

BMP String object

Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 2 octets per character.

FIXME: The encoding is very likely UCS-2, but that's not yet verified.


Inherit OctetString

inherit OctetString : OctetString

Class Standards.ASN1.Types.BitString

Description

Bit string object


Inherit Object

inherit Object : Object


Method set_from_ascii

this_program set_from_ascii(string(8bit) s)

Description

Set the bitstring value as a string with "1" and "0".


Method set_length

this_program set_length(int len)

Description

Sets the length of the bit string to len number of bits. Will only work correctly on strings longer than len bits.


Variable value

string(8bit) Standards.ASN1.Types.BitString.value

Description

value of object

Class Standards.ASN1.Types.Boolean

Description

boolean object


Inherit Object

inherit Object : Object


Variable value

int Standards.ASN1.Types.Boolean.value

Description

value of object

Class Standards.ASN1.Types.BrokenTeletexString

Description

(broken) TeletexString object

Encodes and decodes latin1, but labels it TeletexString, as is common in many broken programs (e.g. Netscape 4.0X).


Inherit String

inherit String : String

Class Standards.ASN1.Types.Compound

Description

Compound object primitive


Variable elements

array(Object) Standards.ASN1.Types.Compound.elements

Description

Contents of compound object.


Inherit Object

inherit Object : Object

Class Standards.ASN1.Types.Enumerated

Description

Enumerated object


Inherit Integer

inherit Integer : Integer

Class Standards.ASN1.Types.IA5String

Description

IA5 String object

Character set: ASCII. Fixed width encoding with 1 octet per character.


Inherit String

inherit String : String

Class Standards.ASN1.Types.Identifier

Description

Object identifier object


Method append

this_program append(int ... args)

Description

Returns a new Identifier object with args appended to the ID path.


Variable id

array(int) Standards.ASN1.Types.Identifier.id

Description

value of object


Inherit Object

inherit Object : Object

Class Standards.ASN1.Types.Integer

Description

Integer object All integers are represented as bignums, for simplicity


Inherit Object

inherit Object : Object


Variable value

Gmp.mpz Standards.ASN1.Types.Integer.value

Description

value of object

Class Standards.ASN1.Types.MetaExplicit

Description

Meta-instances handle a particular explicit tag and set of types. Once cloned this object works as a factory for Compound objects with the cls and tag that the meta object was initialized with.

Example

MetaExplicit m = MetaExplicit(1,2); Compound c = m(Integer(3));


Method create

Standards.ASN1.Types.MetaExplicit Standards.ASN1.Types.MetaExplicit(int cls, int tag, mapping(int:program)|void types)

Class Standards.ASN1.Types.Null

Description

Null object


Inherit Object

inherit Object : Object

Class Standards.ASN1.Types.Object

Description

Generic, abstract base class for ASN1 data types.


Method get_cls

int get_cls()

Description

Get the class of this object.

Returns

The class of this object.


Method get_combined_tag

int get_combined_tag()

Description

Get the combined tag (tag + class) for this object.

Returns

the combined tag header


Method get_der

string(8bit) get_der()

Description

Get the DER encoded version of this object.

Returns

DER encoded representation of this object.


Method get_der_content

string(8bit) get_der_content()

Description

Return the DER payload.


Method get_tag

int get_tag()

Description

Get the tag for this object.

Returns

The tag for this object.

Class Standards.ASN1.Types.OctetString

Description

Octet string object


Inherit String

inherit String : String

Class Standards.ASN1.Types.PrintableString

Description

PrintableString object


Inherit String

inherit String : String

Class Standards.ASN1.Types.Sequence

Description

Sequence object


Inherit Compound

inherit Compound : Compound

Class Standards.ASN1.Types.Set

Description

Set object


Inherit Compound

inherit Compound : Compound

Class Standards.ASN1.Types.String

Description

string object primitive


Inherit Object

inherit Object : Object


Variable value

string Standards.ASN1.Types.String.value

Description

value of object

Class Standards.ASN1.Types.TeletexString

Description

TeletexString object

Avoid this one; it seems to be common that this type is used to label strings encoded with the ISO 8859-1 character set (use asn1_broken_teletex_string for that). From http://www.mindspring.com/~asn1/nlsasn.htm:

/.../ Types GeneralString, VideotexString, TeletexString (T61String), and GraphicString exist in earlier versions [pre-1994] of ASN.1. They are considered difficult to use correctly by applications providing national language support. Varying degrees of application support for T61String values seems to be most common in older applications. Correct support is made more difficult, as character values available in type T61String have changed with the addition of new register entries from the 1984 through 1997 versions.

This implementation is based on the description of T.61 and T.51 in "Some functions for representing T.61 characters from the X.500 Directory Service in ISO 8859 terminals (Version 0.2. July 1994.)" by Enrique Silvestre Mora (mora@si.uji.es), Universitat Jaume I, Spain, found in the package ftp://pereiii.uji.es/pub/uji-ftp/unix/ldap/iso-t61.translation.tar.Z

The translation is only complete for 8-bit latin 1 strings. It encodes strictly to T.61, but decodes from the superset T.51.

Note

CCITT Recommendation T.61 is also known as ISO-IR 103:1985 (graphic characters) and ISO-IR 106:1985 and ISO-IR 107:1985 (control characters).

See also

Charset


Inherit String

inherit String : String

Class Standards.ASN1.Types.UTC

Description

UTCTime

RFC 2459 section 4.1.2.5.1.


Method get_posix

int get_posix()


Inherit String

inherit String : String


Method set_posix

this_program set_posix(int t)

Class Standards.ASN1.Types.UTF8String

Description

UTF8 string object

Character set: ISO/IEC 10646-1 (compatible with Unicode).

Variable width encoding, see RFC 2279.


Inherit String

inherit String : String

Class Standards.ASN1.Types.UniversalString

Description

Universal String object

Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.

FIXME

The encoding is very likely UCS-4, but that's not yet verified.


Inherit OctetString

inherit OctetString : OctetString

Class Standards.ASN1.Types.VisibleString


Inherit String

inherit String : String

Module Standards.PKCS

Module Standards.PKCS.Signature


Method build_digestinfo

string build_digestinfo(string msg, Crypto.Hash hash)

Description

Construct a PKCS-1 digestinfo.

Parameter msg

message to digest

Parameter hash

crypto hash object such as Crypto.SHA1 or Crypto.MD5

See also

Crypto.RSA()->sign

Module Stdio

Description

Pike 7.8 compatibility predef::Stdio implementation.

The main difference from later versions of Pike is that Stdio.File and Stdio.FILE use proxy functions defined in _Stdio.Fd_ref, instead of accessing the file descriptors directly.


Inherit Stdio

inherit 7.9::Stdio : Stdio

Class Stdio.FILE

Description

Stdio.FILE is a buffered version of Stdio.File, it inherits Stdio.File and has most of the functionality of Stdio.File. However, it has an input buffer that allows line-by-line input.

It also has support for automatic charset conversion for both input and output (see Stdio.FILE()->set_charset()).

Note

The output part of Stdio.FILE is currently not buffered.


Method _get_iterator

Stdio.FILE a;
foreach( a; index; value ) or
protected object _get_iterator()

Description

Returns an iterator that will loop over the lines in this file.

See also

line_iterator()


Method getchar

local int getchar()

Description

This function returns one character from the input stream.

Returns

Returns the ISO-10646 (Unicode) value of the character.

Note

Returns an int and not a string of length 1.


Method gets

string gets(bool|void not_all)

Description

Read one line of input with support for input conversion.

Parameter not_all

Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.

Returns

This function returns the line read if successful, and 0 if no more lines are available.

See also

ngets(), read(), line_iterator(), set_charset()


Inherit file

inherit File : file


Method line_iterator

object line_iterator(int|void trim)

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.

Note

It's not supported to call this method more than once unless a call to seek is done in advance. Also note that it's not possible to intermingle calls to read, gets or other functions that read data with the line iterator, it will produce unexpected results since the internal buffer in the iterator will not contain sequential file-data in those cases.

See also

_get_iterator()


Method ngets

array(string) ngets(void|int(1..) n, bool|void not_all)

Description

Get n lines.

Parameter n

Number of lines to get, or all remaining if zero.

Parameter not_all

Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.


Method openat

FILE openat(string filename, string mode)
FILE openat(string filename, string mode, int mask)

Description

Same as Stdio.File()->openat(), but returns a Stdio.FILE object.

See also

Stdio.File()->openat()


Method pipe

File pipe(int|void flags)

Description

Same as Stdio.File()->pipe().

Note

Returns an Stdio.File object, NOT an Stdio.FILE object.

In future releases of Pike this will most likely change to returning an Stdio.FILE object. This is already the case if STDIO_DIRECT_FD has been defined.


Method printf

int printf(string format, mixed ... data)

Description

This function does approximately the same as: write(sprintf(format,@data)).

See also

write(), sprintf()


Method read

string read(int|void bytes, void|bool now)

Description

Read bytes (wide-) characters with buffering and support for input conversion.

See also

Stdio.File()->read(), set_charset(), unread()


Method set_charset

void set_charset(string|void charset)

Description

Sets the input and output charset of this file to the specified charset. If charset is 0 or not specified the environment is used to try to detect a suitable charset.

The default charset if this function is not called is "ISO-8859-1".

FIXME

Consider using one of ISO-IR-196 ("\e%G" - switch to UTF-8 with return) or ISO-IR-190 ("\e%/G" - switch to UTF-8 level 1 no return) or ISO-IR-191 ("\e%/H" - switch to UTF-8 level 2 no return) or ISO-IR-192 ("\e%/I" - switch to UTF-8 level 3 no return) or ISO-IR-193 ("\e%/J" - switch to UTF-16 level 1 no return) or ISO-IR-194 ("\e%/K" - switch to UTF-16 level 2 no return) or ISO-IR-195 ("\e%/L" - switch to UTF-16 level 3 no return) or ISO-IR-162 ("\e%/@" - switch to UCS-2 level 1) or ISO-IR-163 ("\e%/A" - switch to UCS-4 level 1) or ISO-IR-174 ("\e%/C" - switch to UCS-2 level 2) or ISO-IR-175 ("\e%/D" - switch to UCS-4 level 2) or ISO-IR-176 ("\e%/E" - switch to UCS-2 level 3) or ISO-IR-177 ("\e%/F" - switch to UCS-4 level 3) or ISO-IR-178 ("\e%B" - switch to UTF-1) automatically to encode wide strings.


Method ungets

void ungets(string s)

Description

This function puts a line back in the input buffer. The line can then be read with eg read(), gets() or getchar().

Note

The string is autoterminated by an extra line-feed.

See also

read(), gets(), getchar(), unread()


Method unread

void unread(string s)

Description

This function puts a string back in the input buffer. The string can then be read with eg read(), gets() or getchar().

See also

read(), gets(), getchar(), ungets()


Method write

int write(array(string)|string what, mixed ... fmt)

Description

Write what with support for output_conversion.

See also

Stdio.File()->write()

Class Stdio.File

Description

This is the basic I/O object, it provides socket and pipe communication as well as file access. It does not buffer reads and writes or provide line-by-line reading, that is done with Stdio.FILE object.

Note

The file or stream will normally be closed when this object is destructed (unless there are more objects that refer to the same file through use of assign or dup). Objects do not contain cyclic references in themselves, so they will be destructed timely when they run out of references.

See also

Stdio.FILE


Method assign

int assign(File|Fd o)

Description

This function takes a clone of Stdio.File and assigns all variables of this file from it. It can be used together with dup() to move files around.

See also

dup()


Method async_connect

int async_connect(string host, int|string port, function(int, mixed ... :void) callback, mixed ... args)

Description

Open a TCP/IP connection asynchronously.

This function is similar to connect(), but works asynchronously.

Parameter host

Hostname or IP to connect to.

Parameter port

Port number or service name to connect to.

Parameter callback

Function to be called on completion. The first argument will be 1 if a connection was successfully established, and 0 (zero) on failure. The rest of the arguments to callback are passed verbatim from args.

Parameter args

Extra arguments to pass to callback.

Returns

Returns 0 on failure, and 1 if callback will be used.

Note

The socket may be opened with open_socket() ahead of the call to this function, but it is not required.

Note

This object is put in callback mode by this function. For callback to be called, the backend must be active. See e.g. set_read_callback for more details about backends and callback mode.

Note

The socket will be in nonblocking state if the connection is successful, and any callbacks will be cleared.

See also

connect(), open_socket(), set_nonblocking()


Method close

int close()
int close(string direction)

Description

Close the file. Optionally, specify "r", "w" or "rw" to close just the read, just the write or both read and write directions of the file respectively.

An exception is thrown if an I/O error occurs.

Returns

Nonzero is returned if the file wasn't open in the specified direction, zero otherwise.

Note

This function will not call the close_callback.

See also

open, open_socket


Method connect

int connect(string host, int|string port, void|string client, void|int|string client_port)

Description

This function connects a socket previously created with open_socket() to a remote socket through TCP/IP. The host argument is the hostname or IP number of the remote machine. A local IP and port can be explicitly bound by specifying client and client_port.

Returns

This function returns 1 for success, 0 otherwise.

Note

In nonblocking mode 0 (zero) may be returned and errno() set to EWOULDBLOCK or WSAEWOULDBLOCK. This should not be regarded as a connection failure. In nonblocking mode you need to wait for a write or close callback before you know if the connection failed or not.

See also

query_address(), async_connect(), connect_unix()


Method connect_unix

int connect_unix(string path)

Description

Open a UNIX domain socket connection to the specified destination.

Returns

Returns 1 on success, and 0 on failure.

Note

Nonblocking mode is not supported while connecting


Method create

Stdio.File Stdio.File()
Stdio.File Stdio.File(string filename)
Stdio.File Stdio.File(string filename, string mode)
Stdio.File Stdio.File(string filename, string mode, int mask)
Stdio.File Stdio.File(string descriptorname)
Stdio.File Stdio.File(int fd)
Stdio.File Stdio.File(int fd, string mode)

Description

There are four basic ways to create a Stdio.File object. The first is calling it without any arguments, in which case the you'd have to call open(), connect() or some other method which connects the File object with a stream.

The second way is calling it with a filename and open mode. This is the same thing as cloning and then calling open(), except shorter and faster.

The third way is to call it with descriptorname of "stdin", "stdout" or "stderr". This will open the specified standard stream.

For the advanced users, you can use the file descriptors of the systems (note: emulated by pike on some systems - like NT). This is only useful for streaming purposes on unix systems. This is not recommended at all if you don't know what you're into. Default mode for this is "rw".

Note

Open mode will be filtered through the system UMASK. You might need to use chmod() later.

See also

open(), connect(), Stdio.FILE,


Method dup

File dup()

Description

This function returns a clone of Stdio.File with all variables copied from this file.

Note

All variables, even id, are copied.

See also

assign()


Method errno

int errno()

Description

Returns the error code for the last command on this file. Error code is normally cleared when a command is successful.


Inherit Fd_ref

optional inherit _Stdio.Fd_ref : Fd_ref


Method line_iterator

String.SplitIterator|LineIterator line_iterator(int|void trim)

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.


Method open

int open(string filename, string mode)
int open(string filename, string mode, int mask)

Description

Open a file for read, write or append. The parameter mode should contain one or more of the following letters:

"r"

Open file for reading.

"w"

Open file for writing.

"a"

Open file for append (use with "w").

"t"

Truncate file at open (use with "w").

"c"

Create file if it doesn't exist (use with "w").

"x"

Fail if file already exists (use with "c").

mode should always contain at least one of the letters "r" or "w".

The parameter mask is protection bits to use if the file is created. Default is 0666 (read+write for all in octal notation).

Returns

This function returns 1 for success, 0 otherwise.

See also

close(), create()


Method open_socket

int open_socket(int|string|void port, string|void address, int|string|void family_hint)

Description

This makes this file into a socket ready for connections. The reason for this function is so that you can set the socket to nonblocking or blocking (default is blocking) before you call connect().

Parameter port

If you give a port number to this function, the socket will be bound to this port locally before connecting anywhere. This is only useful for some silly protocols like FTP. The port can also be specified as a string, giving the name of the service associated with the port. Pass -1 to not specify a port (eg to bind only to an address).

Parameter address

You may specify an address to bind to if your machine has many IP numbers.

Parameter family_hint

A protocol family for the socket can be specified. If no family is specified, one which is appropriate for the address is automatically selected. Thus, there is normally no need to specify it. If you do not want to specify a bind address, you can provide the address as a hint here instead, to allow the automatic selection to work anyway.

Returns

This function returns 1 for success, 0 otherwise.

See also

connect(), set_nonblocking(), set_blocking()


Method openat

File openat(string filename, string mode)
File openat(string filename, string mode, int mask)

Description

Open a file relative to an open directory.

See also

File.statat(), File.unlinkat()


Method openpt

int openpt(string mode)

Description

Open the master end of a pseudo-terminal pair. The parameter mode should contain one or more of the following letters:

"r"

Open terminal for reading.

"w"

Open terminal for writing.

mode should always contain at least one of the letters "r" or "w".

See also

grantpt()


Method pipe

File pipe(void|int required_properties)

Description

This function creates a pipe between the object it was called in and an object that is returned.

Parameter required_properties

Binary or (predef::`|()) of required PROP_ properties.

PROP_IPC

The resulting pipe may be used for inter process communication.

PROP_NONBLOCK

The resulting pipe supports nonblocking I/O.

PROP_SHUTDOWN

The resulting pipe supports shutting down transmission in either direction (see close()).

PROP_BUFFERED

The resulting pipe is buffered (usually 4KB).

PROP_BIDIRECTIONAL

The resulting pipe is bi-directional.

PROP_SEND_FD

The resulting pipe might support sending of file descriptors (see send_fd() and receive_fd() for details).

PROP_REVERSE

The resulting pipe supports communication "backwards" (but not necessarily "forwards", see PROP_BIDIRECTIONAL).

The default is PROP_NONBLOCK|PROP_BIDIRECTIONAL.

If PROP_BIDIRECTIONAL isn't specified, the read-end is this object, and the write-end is the returned object (unless PROP_REVERSE has been specified, in which case it is the other way around).

The two ends of a bi-directional pipe are indistinguishable.

If the File object this function is called in was open to begin with, it will be closed before the pipe is created.

Note

Calling this function with an argument of 0 is not the same as calling it with no arguments.

See also

Process.create_process(), send_fd(), receive_fd(), PROP_IPC, PROP_NONBLOCK, PROP_SEND_FD, PROP_SHUTDOWN, PROP_BUFFERED, PROP_REVERSE, PROP_BIDIRECTIONAL


Method query_read_callback
Method query_write_callback
Method query_read_oob_callback
Method query_write_oob_callback
Method query_close_callback
Method query_callbacks

function(mixed, string:int) query_read_callback()
function(mixed:int) query_write_callback()
function(mixed, string:int) query_read_oob_callback()
function(mixed:int) query_write_oob_callback()
function(mixed:int) query_close_callback()
array(function(mixed, void|string:int)) query_callbacks()

Description

These functions return the currently installed callbacks for the respective events.

query_callbacks returns the callbacks in the same order as set_callbacks and set_nonblocking expect them.

See also

set_nonblocking(), set_read_callback, set_write_callback, set_read_oob_callback, set_write_oob_callback, set_close_callback, set_callbacks


Method query_id

mixed query_id()

Description

This function returns the id that has been set with set_id().

See also

set_id()


Method read_function

function(:string) read_function(int nbytes)

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.


Method send_fd

void send_fd(File|Fd file)


Method set_blocking

void set_blocking()

Description

This function clears all callbacks and sets a stream to blocking mode. i.e. reading, writing and closing will wait until data has been transferred before returning.

Note

The callbacks are cleared and blocking mode is set in one atomic operation, so no callback gets called in between if the backend is running in another thread.

Even so, if the stream is in callback mode (i.e. if any callbacks are installed) then only the backend thread can use this function reliably; it might otherwise already be running in a callback which is about to call e.g. write when the stream becomes blocking.

See also

set_nonblocking(), set_nonblocking_keep_callbacks(), set_blocking_keep_callbacks()


Method set_nonblocking_keep_callbacks
Method set_blocking_keep_callbacks

void set_nonblocking_keep_callbacks()
void set_blocking_keep_callbacks()

Description

Toggle between blocking and nonblocking, without changing the callbacks.

See also

set_nonblocking(), set_blocking()


Method set_callbacks

void set_callbacks(void|function(mixed, string:int) read_cb, void|function(mixed:int) write_cb, void|function(mixed:int) close_cb, void|function(mixed, string:int) read_oob_cb, void|function(mixed:int) write_oob_cb)

Description

Installs all the specified callbacks at once. Use UNDEFINED to keep the current setting for a callback.

Like set_nonblocking, the callbacks are installed atomically. As opposed to set_nonblocking, this function does not do anything with the stream, and it doesn't even have to be open.

See also

set_read_callback, set_write_callback, set_read_oob_callback, set_write_oob_callback, set_close_callback, query_callbacks


Method set_read_callback
Method set_write_callback
Method set_read_oob_callback
Method set_write_oob_callback
Method set_close_callback
Method set_fs_event_callback

void set_read_callback(function(mixed, string:int) read_cb)
void set_write_callback(function(mixed:int) write_cb)
void set_read_oob_callback(function(mixed, string:int) read_oob_cb)
void set_write_oob_callback(function(mixed:int) write_oob_cb)
void set_close_callback(function(mixed:int) close_cb)
void set_fs_event_callback(function(mixed, int:int) fs_event_cb, int event_mask)

Description

These functions set the various callbacks, which will be called when various events occur on the stream. A zero as argument will remove the callback.

A Pike.Backend object is responsible for calling the callbacks. It requires a thread to be waiting in it to execute the calls. That means that only one of the callbacks will be running at a time, so you don't need mutexes between them.

Unless you've specified otherwise with the set_backend function, the default backend Pike.DefaultBackend will be used. It's normally activated by returning -1 from the main function and will then execute in the main thread.

  • When data arrives on the stream, read_cb will be called with some or all of that data as the second argument.

  • When the stream has buffer space over for writing, write_cb will be called so that you can write more data to it.

    This callback is also called after the remote end of a socket connection has closed the write direction. An attempt to write data to it in that case will generate a System.EPIPE errno. If the remote end has closed both directions simultaneously (the usual case), Pike will first attempt to call close_cb, then this callback (unless close_cb has closed the stream).

  • When out-of-band data arrives on the stream, read_oob_cb will be called with some or all of that data as the second argument.

  • When the stream allows out-of-band data to be sent, write_oob_cb will be called so that you can write more out-of-band data to it.

    If the OS doesn't separate the write events for normal and out-of-band data, Pike will try to call write_oob_cb first. If it doesn't write anything, then write_cb will be tried. This also means that write_oob_cb might get called when the remote end of a connection has closed the write direction.

  • When an error or an end-of-stream in the read direction occurs, close_cb will be called. errno will return the error, or zero in the case of an end-of-stream.

    The name of this callback is rather unfortunate since it really has nothing to do with a close: The stream is still open when close_cb is called (you might not be able to read and/or write to it, but you can still use things like query_address, and the underlying file descriptor is still allocated). Also, this callback will not be called for a local close, neither by a call to close or by destructing this object.

    Also, close_cb will not be called if a remote close only occurs in the write direction; that is handled by write_cb (or possibly write_oob_cb).

    Events to read_cb and close_cb will be automatically deregistered if an end-of-stream occurs, and all events in the case of an error. I.e. there won't be any more calls to the callbacks unless they are reinstalled. This doesn't affect the callback settings - query_read_callback et al will still return the installed callbacks.

If the stream is a socket performing a nonblocking connect (see open_socket and connect), a connection failure will call close_cb, and a successful connect will call either read_cb or write_cb as above.

All callbacks will receive the id set by set_id as first argument.

If a callback returns -1, no other callback or call out will be called by the backend in that round. I.e. the caller of the backend will get control back right away. For the default backend that means it will immediately start another round and check files and call outs anew.

Parameter event_mask

An event mask specifing bitwise OR of one or more event types to monitor, selected from Stdio.NOTE_WRITE and friends.

Note

These functions do not set the file nonblocking.

Note

Callbacks are also set by set_callbacks and set_nonblocking().

Note

After a callback has been called, it's disabled until it has accessed the stream accordingly, i.e. the write_cb callback is disabled after it's been called until something has been written with write, and the write_oob_cb callback is likewise disabled until something has been written with write_oob. Since the data already has been read when the read callbacks are called, this effect is not noticeable for them.

Note

Installing callbacks means that you will start doing I/O on the stream from the thread running the backend. If you are running these set functions from another thread you must be prepared that the callbacks can be called immediately by the backend thread, so it might not be safe to continue using the stream in this thread.

Because of that, it's useful to talk about "callback mode" when any callback is installed. In callback mode the stream should be seen as "bound" to the backend thread. For instance, it's only the backend thread that reliably can end callback mode before the stream is "handed over" to another thread.

Note

Callback mode has nothing to do with nonblocking mode - although the two often are used together they don't have to be.

Note

The file object will stay referenced from the backend object as long as there are callbacks that can receive events.

Bugs

Setting a close callback without a read callback currently only works when there's no risk of getting more data on the stream. Otherwise the close callback will be silently deregistered if data arrives.

Note

fs_event callbacks only trigger on systems that support these events. Currently, this includes systems that use kqueue, such as Mac OS X, and various flavours of BSD.

See also

set_callbacks, set_nonblocking(), set_id(), set_backend, query_read_callback, query_write_callback, query_read_oob_callback, query_write_oob_callback, query_close_callback


Method set_id

void set_id(mixed id)

Description

This function sets the id of this file. The id is mainly used as an identifier that is sent as the first argument to all callbacks. The default id is 0 (zero). Another possible use of the id is to hold all data related to this file in a mapping or array.

See also

query_id()


Method set_nonblocking

void set_nonblocking(function(mixed, string:int) read_callback, function(mixed:int) write_callback, function(mixed:int) close_callback)
void set_nonblocking(function(mixed, string:int) read_callback, function(mixed:int) write_callback, function(mixed:int) close_callback, function(mixed, string:int) read_oob_callback, function(mixed:int) write_oob_callback)
void set_nonblocking()

Description

This function sets a stream to nonblocking mode and installs the specified callbacks. See the set_*_callback functions for details about them. If no arguments are given, the callbacks will be cleared.

Note

As opposed to calling the set callback functions separately, this function will set all the callbacks and nonblocking mode atomically so that no callback gets called in between. That avoids races in case the backend is executed by another thread.

Note

Out-of-band data was not be supported on Pike 0.5 and earlier, and not on Pike 0.6 through 7.4 if they were compiled with the option '--without-oob'.

See also

set_blocking(), set_callbacks, set_read_callback(), set_write_callback(), set_read_oob_callback(), set_write_oob_callback(), set_close_callback() set_nonblocking_keep_callbacks(), set_blocking_keep_callbacks()

Class Stdio.Port

Description

Handles listening to socket ports. Whenever you need a bound socket that is open and listens for connections you should use this program.


Method accept

File accept()

Description

This function completes a connection made from a remote machine to this port. It returns a two-way stream in the form of a clone of Stdio.File. The new file is by initially set to blocking mode.

See also

Stdio.File


Method create

Stdio.Port Stdio.Port()
Stdio.Port Stdio.Port(int|string port)
Stdio.Port Stdio.Port(int|string port, function(:void) accept_callback)
Stdio.Port Stdio.Port(int|string port, function(:void) accept_callback, string ip)
Stdio.Port Stdio.Port("stdin")
Stdio.Port Stdio.Port("stdin", function(:void) accept_callback)

Description

If the first argument is other than "stdin" the arguments will be passed to bind().

When create is called with "stdin" as the first argument, a socket is created out of the file descriptor 0. This is only useful if it actually is a socket to begin with.

See also

bind


Inherit _port

inherit _Stdio._port : _port

Module files

Description

Pike 7.8 compatibility.

In 7.8 and earlier "_Stdio" was named "files".


Inherit _Stdio

inherit _Stdio : _Stdio

Namespace 8.0::

Description

Pike 8.0 compatibility.

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


Method _assembler_debug

void _assembler_debug()

Deprecated

Replaced by Debug.assembler_debug.


Method _debug

int _debug(int d)

Deprecated

Replaced by Debug.debug.


Method _dump_program_tables

void _dump_program_tables(program p, int|void i)

Deprecated

Replaced by Debug.dump_program_tables.


Method _map_all_objects

int _map_all_objects(function(:void) f)

Deprecated

Replaced by Debug.map_all_objects.


Method _next

mixed _next(mixed x)

Deprecated

Replaced by Debug.next.


Method _optimizer_debug

int _optimizer_debug(int d)

Deprecated

Replaced by Debug.optimizer_debug.


Method _prev

mixed _prev(mixed x)

Deprecated

Replaced by Debug.prev.


Method _refs

int _refs(mixed x)

Deprecated

Replaced by Debug.refs.


Inherit

inherit predef:: :


Method next_object

object next_object(object o)

Deprecated

Replaced by Debug.next_object.

Class Iterator

Description

Wrapper for iterators that implements the 8.0 and earlier iterator API.

Module ADT

Class ADT.Heap


Inherit Heap

inherit ADT.Heap : Heap


Method size

int size()

Description

Returns the number of elements in the heap.

Deprecated

Replaced by lfun::_sizeof.


Method top

mixed top()

Description

Removes and returns the item on top of the heap, which also is the smallest value in the heap.

Deprecated

Replaced by pop.

Module Array

Description

Pike 8.0 compatibility array handling.

Module Crypto


Variable Buffer

program Crypto.Buffer

Description

This class has moved to submodules of the respective ciphers.

Class Crypto.Buffer

Description

This class has moved to submodules of the respective ciphers.

Deprecated

Replaced by BlockCipher.Buffer.


Method create

Crypto.Buffer Crypto.Buffer(Crypto.CipherState|program fun, mixed ... args)

Class Crypto.CBC

Description

This class has moved to submodules of the respective ciphers.

Deprecated

Replaced by BlockCipher.CBC.


Method create

Crypto.CBC Crypto.CBC(Crypto.CipherState|program fun, mixed ... args)

Module Crypto.DH


Inherit pre

inherit Crypto.DH : pre

Class Crypto.DH.Parameters


Inherit Parameters

inherit pre::Parameters : Parameters


Variable order

Gmp.mpz Crypto.DH.Parameters.order

Description

Alias for q.

Deprecated

Replaced by q.

Module Crypto.DSA


Inherit pre

inherit Crypto.DSA : pre

Class Crypto.DSA.State


Inherit State

inherit pre::State : State


Method sign_rsaref

string(8bit) sign_rsaref(string(8bit) msg)

Description

Make a RSA ref signature of message msg.


Method sign_ssl

string(8bit) sign_ssl(string(8bit) msg)

Description

Make an SSL signature of message msg.


Method verify_rsaref

bool verify_rsaref(string(8bit) msg, string(8bit) s)

Description

Verify a RSA ref signature s of message msg.


Method verify_ssl

bool verify_ssl(string(8bit) msg, string(8bit) s)

Description

Verify an SSL signature s of message msg.

Module Crypto.RSA


Inherit pre

inherit Crypto.RSA : pre

Class Crypto.RSA.State


Method cooked_get_d

string(8bit) cooked_get_d()

Description

Returns the RSA private exponent (d) as a binary string, if known.


Method cooked_get_e

string(8bit) cooked_get_e()

Description

Returns the RSA public exponent (e) as a binary string.


Method cooked_get_n

string(8bit) cooked_get_n()

Description

Returns the RSA modulo (n) as a binary string.


Method cooked_get_p

string(8bit) cooked_get_p()

Description

Returns the first RSA prime (p) as a binary string, if known.


Method cooked_get_q

string(8bit) cooked_get_q()

Description

Returns the second RSA prime (q) as a binary string, if known.


Method cooked_sign

string(8bit) cooked_sign(string(8bit) digest)

Description

Signs digest as raw_sign and returns the signature as a byte string.


Method generate_key

this_program generate_key(int(128..) bits, void|int|function(int(0..):string(8bit)) rnd)

Description

Compatibility with Pike 7.8.


Inherit State

inherit pre::State : State

Module Mapping

Description

Pike 8.0 compatibility mapping handling.

Module Multiset

Description

Pike 8.0 compatibility multiset handling.

Module Protocols

Module Protocols.HTTP


Method http_encode_cookie

string http_encode_cookie(string f)

Description

This function used to claim that it encodes the specified string according to the HTTP cookie standard. If fact it does not - it applies URI-style (i.e. %XX) encoding on some of the characters that cannot occur literally in cookie values. There exist some web servers (read Roxen and forks) that usually perform a corresponding nonstandard decoding of %-style escapes in cookie values in received requests.

This function is deprecated. The function quoted_string_encode performs encoding according to the standard, but it is not safe to use with arbitrary chars. Thus URI-style encoding using uri_encode or percent_encode is normally a good choice, if you can use uri_decode/percent_decode at the decoding end.

Deprecated

Method http_encode_string

string http_encode_string(string in)

Description

This is a deprecated alias for uri_encode, for compatibility with Pike 7.6 and earlier.

In 7.6 this function didn't handle 8-bit and wider chars correctly. It encoded 8-bit chars directly to %XX escapes, and it used nonstandard %uXXXX escapes for 16-bit chars.

That is considered a bug, and hence the function is changed. If you need the old buggy encoding then use the 7.6 compatibility version (#pike 7.6).

Deprecated

Replaced by uri_encode.


Inherit module

inherit Protocols.HTTP.module : module


Method unentity

string unentity(string s)

Description

Helper function for replacing HTML entities with the corresponding unicode characters.

Deprecated

Replaced by Parser.parse_html_entities.

Module Protocols.HTTP.Server

Class Protocols.HTTP.Server.SSLPort


Inherit SSLPort

inherit Protocols.HTTP.Server.SSLPort : SSLPort


Method set_certificate

void set_certificate(string|array(string) certificate)

Deprecated

Replaced by add_cert.


Method set_key

void set_key(string skey)

Deprecated

Replaced by add_cert.

Module SSL

Class SSL.Context


Variable certificates

array(string(8bit)) SSL.Context.certificates

Description

Getting

The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`rsa, find_cert()

Setting

The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`rsa, find_cert()


Variable client_certificates

array(array(string(8bit))) SSL.Context.client_certificates

Description

Getting

The client's certificate, or a chain of X509.v3 certificates, with the client's certificate first and root certificate last.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`rsa, find_cert()

Setting

The client's certificate, or a chain of X509.v3 certificates, with the client's certificate first and root certificate last.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`rsa, find_cert()


Variable client_rsa

Crypto.RSA.State SSL.Context.client_rsa

Description

Getting

The clients RSA private key.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`certificates, find_cert()

Setting

The clients RSA private key.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`certificates, find_cert()


Method dhe_dss_mode

void dhe_dss_mode(int(0..)|void min_keylength)

Description

Set preferred_suites to DSS based methods.

Parameter min_keylength

Minimum acceptable key length in bits.

See also

rsa_mode(), filter_weak_suites()

Deprecated

Replaced by get_suites.


Variable dsa

Crypto.DSA.State SSL.Context.dsa

Description

Getting

Compatibility.

Deprecated

Replaced by find_cert.

Setting

Compatibility.

Deprecated

Replaced by find_cert.


Inherit Context

inherit SSL.Context : Context


Variable rsa

Crypto.RSA.State SSL.Context.rsa

Description

Getting

The servers default private RSA key.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`certificates, find_cert()

Setting

The servers default private RSA key.

Compatibility, don't use.

Deprecated

Replaced by find_cert.

See also

`certificates, find_cert()


Method rsa_mode

void rsa_mode(int(0..)|void min_keylength)

Description

Set preferred_suites to RSA based methods.

Parameter min_keylength

Minimum acceptable key length in bits.

See also

dhe_dss_mode(), filter_weak_suites()

Deprecated

Replaced by get_suites.

Module Sql

Class Sql.Sql

Description

This class encapsulates a connection to an SQL server. It is a generic interface on top of the DB server specific implementations. That doesn't mean that there aren't plenty of server specific characteristics that still shine through, though.

This class also serves as an interface guideline for the DB server specific connection classes.

Untyped and typed mode

The query results are returned in different ways depending on the query functions used: The ..typed_query functions select typed mode, while the other query functions uses the older untyped mode.

In untyped mode, all values except SQL NULL are returned as strings in their display representation, and SQL NULL is returned as zero.

In typed mode, values are returned in pike native form where it works well. That means at least that SQL integer fields are returned as pike integers, floats as floats, SQL NULL as Val.null, and of course strings still as strings. The representation of other SQL types depends on the capabilities of the server specific backends. It's also possible that floats in some cases are represented in other ways if too much precision is lost in the conversion to pike floats.

Note

For historical reasons, there may be server specific backends that operate differently from what is described here, e.g. some that return a bit of typed data in untyped mode.

Note

Typed operation was not supported at all prior to Pike 7.8.363, and may not be supported for all databases.


Method big_query

int|object big_query(object|string q, mixed ... extraargs)

Description

Sends an SQL query synchronously to the underlying SQL-server and returns the results in untyped mode.

For the arguments, please see the query() function.

The result is returned as an Sql.sql_result object in untyped mode. This allows for having some more info about the result as well as processing the result in a streaming fashion, although the result itself wasn't obtained streamingly from the server. Returns 0 if the query didn't return any result (e.g. INSERT or similar).

Note

Despite the name, this function is not only useful for "big" queries. It typically has less overhead than query also for ones that return only a few rows.

See also

query, streaming_query


Method big_typed_query

int|object big_typed_query(object|string q, mixed ... extraargs)

Description

Sends an SQL query synchronously to the underlying SQL-server and returns the results in typed mode.

For the arguments, please see the query() function.

The result is returned as an Sql.sql_result object in typed mode. This allows for having some more info about the result as well as processing the result in a streaming fashion, although the result itself wasn't obtained streamingly from the server. Returns 0 if the query didn't return any result (e.g. INSERT or similar).

Note

Typed mode is not supported by all sql databases. If not supported, an error is thrown.

Note

Despite the name, this function is not only useful for "big" queries. It typically has less overhead than typed_query also for ones that return only a few rows.

See also

query, typed_query, big_query, streaming_query


Variable case_convert

bool Sql.Sql.case_convert

Description

Convert all field names in mappings to lower_case. Only relevant to databases which only implement big_query(), and use upper/mixed-case fieldnames (eg Oracle).

0

No (default)

1

Yes


Method compile_query

string|object compile_query(string q)

Description

Compiles the query (if possible). Otherwise returns it as is. The resulting object can be used multiple times to the query functions.

Parameter q

SQL-query to compile.

See also

query, typed_query, big_query, big_typed_query, streaming_query, streaming_typed_query


Method create

Sql.Sql Sql.Sql(string host)
Sql.Sql Sql.Sql(string host, string db)
Sql.Sql Sql.Sql(string host, mapping(string:int|string) options)
Sql.Sql Sql.Sql(string host, string db, string user)
Sql.Sql Sql.Sql(string host, string db, string user, string password)
Sql.Sql Sql.Sql(string host, string db, string user, string password, mapping(string:int|string) options)
Sql.Sql Sql.Sql(object host)
Sql.Sql Sql.Sql(object host, string db)

Description

Create a new generic SQL object.

Parameter host
object

Use this object to access the SQL-database.

string

Connect to the server specified. The string should be on the format: dbtype://[user[:password]@]hostname[:port][/database] Use the dbtype protocol to connect to the database server on the specified host. If the hostname is "" then the port can be a file name to access through a UNIX-domain socket or similar, e g "mysql://root@:/tmp/mysql.sock/".

There is a special dbtype "mysqls" which works like "mysql" but sets the CLIENT_SSL option and loads the /etc/my.cnf config file to find the SSL parameters. The same function can be achieved using the "mysql" dbtype.

int(0)

Access through a UNIX-domain socket or similar.

Parameter db

Select this database.

Parameter user

User name to access the database as.

Parameter password

Password to access the database.

Parameter options

Optional mapping of options. See the SQL-database documentation for the supported options. (eg Mysql.mysql()->create()).

Note

In versions of Pike prior to 7.2 it was possible to leave out the dbtype, but that has been deprecated, since it never worked well.

Note

Exactly which databases are supported by pike depends on the installed set of client libraries when pike was compiled.

The possible ones are

mysql

libmysql based mysql connection

mysqls

libmysql based mysql connection, using SSL

dsn

ODBC based connection

msql

Msql

odbc

ODBC based connection

oracle

Oracle using oracle libraries

pgsql

PostgreSQL direct network access. This module is independent of any external libraries.

postgres

PostgreSQL libray access. Uses the Postgres module.

rsql

Remote SQL api, requires a rsql server running on another host. This is an API that uses sockets to communicate with a remote pike running pike -x rsqld on another host.

sqlite

In-process SQLite database, uses the SQLite module

sybase

Uses the sybase module to access sybase

tds

Sybase and Microsoft SQL direct network access using the TDS protocol. This module is independent of any external libraries.

Note

Support for options was added in Pike 7.3.


Method create_db

void create_db(string db)

Description

Create a new database.

Parameter db

Name of database to create.


Method decode_date

int decode_date(string d)

Description

Converts a database date-only spec to a system time value.

Parameter d

Date spec to decode.


Method decode_datetime

int decode_datetime(string datetime)

Description

Converts a database date and time spec to a system time value.

Parameter datetime

Date and time spec to decode.


Method decode_time

int decode_time(string t, int|void want_utc)

Description

Converts a database time spec to a system time value.

Parameter t

Time spec to decode.

Parameter want_utc

Take the date part from this system time value. If zero, a seconds-since-midnight value is returned.


Method drop_db

void drop_db(string db)

Description

Drop database

Parameter db

Name of database to drop.


Method encode_date

string encode_date(int t)

Description

Converts a system time value to an appropriately formatted date-only spec for the database.

Parameter t

Time to encode.


Method encode_datetime

string encode_datetime(int t)

Description

Converts a system time value to an appropriately formatted date and time spec for the database.

Parameter t

Time to encode.


Method encode_time

string encode_time(int t, int|void is_utc)

Description

Converts a system time value to an appropriately formatted time spec for the database.

Parameter t

Time to encode.

Parameter is_utc

If nonzero then time is taken as a "full" unix time spec (where the date part is ignored), otherwise it's converted as a seconds-since-midnight value.


Method error

int|string error()

Description

Return last error message.


Method get_charset

string get_charset()

Description

Returns the (database dependent) name of the charset used for (at least) query strings. Returns zero if the connection doesn't support charsets this way (typically means that a call to set_charset will throw an error).

See also

set_charset, Sql.mysql.get_charset


Method host_info

string host_info()

Description

Return info about the connection to the SQL-server.


Method is_open

int is_open()

Description

Returns true if the connection seems to be open.

Note

This function only checks that there's an open connection, and that the other end hasn't closed it yet. No data is sent over the connection.

For a more reliable check of whether the connection is alive, please use ping().

See also

ping()


Method list_dbs

array(string) list_dbs(string|void wild)

Description

List available databases on this SQL-server.

Parameter wild

Optional wildcard to match against.


Method list_fields

array(mapping(string:mixed)) list_fields(string table, string|void wild)

Description

List fields available in the specified table

Parameter table

Table to list the fields of.

Parameter wild

Optional wildcard to match against.


Method list_tables

array(string) list_tables(string|void wild)

Description

List tables available in the current database.

Parameter wild

Optional wildcard to match against.


Variable master_sql

object Sql.Sql.master_sql

Description

Server specific connection object used for the actual SQL queries.


Method ping

int ping()

Description

Check whether the connection is alive.

Returns

Returns one of the following:

0

Everything ok.

1

The connection reconnected automatically.

-1

The server has gone away, and the connection is dead.

See also

is_open()


Method query

array(mapping(string:string)) query(object|string q, mixed ... extraargs)

Description

Sends an SQL query synchronously to the underlying SQL-server and returns the results in untyped mode.

Parameter q

Query to send to the SQL-server. This can either be a string with the query, or a previously compiled query (see compile_query()).

Parameter extraargs

This parameter, if specified, can be in two forms:

  1. A mapping containing bindings of variables used in the query. A variable is identified by a colon (:) followed by a name or number. Each index in the mapping corresponds to one such variable, and the value for that index is substituted (quoted) into the query wherever the variable is used.

    res = query("SELECT foo FROM bar WHERE gazonk=:baz",
                ([":baz":"value"]));
    

    Binary values (BLOBs) may need to be placed in multisets.

  2. Arguments as you would use in sprintf. They are automatically quoted.

    res = query("select foo from bar where gazonk=%s","value");
    
Returns

Returns one of the following on success:

array(mapping(string:string))

The result as an array of mappings indexed on the name of the columns. The values are either strings with the display representations or zero for the SQL NULL value.

zero

The value 0 (zero) if the query didn't return any result (eg INSERT or similar).

Throws

Throws an exception if the query fails.

See also

typed_query, big_query, streaming_query


Method quote

string quote(string s)

Description

Quote a string s so that it can safely be put in a query.

All input that is used in SQL-querys should be quoted to prevent SQL injections.

Consider this harmfull code:

string my_input = "rob' OR name!='rob";
  string my_query = "DELETE FROM tblUsers WHERE name='"+my_input+"'";
  my_db->query(my_query);

This type of problems can be avoided by quoting my_input. my_input would then probably read something like rob\' OR name!=\'rob

Usually this is done - not by calling quote explicitly - but through using a sprintf like syntax

string my_input = "rob' OR name!='rob";
  my_db->query("DELETE FROM tblUsers WHERE name=%s",my_input);

Method reload

void reload()

Description

Reload the tables.


Method select_db

void select_db(string db)

Description

Select database to access.


Method server_info

string server_info()

Description

Return info about the current SQL-server.


Method set_charset

void set_charset(string charset)

Description

Changes the charset that the connection uses for queries and returned text strings.

Parameter charset

The charset to use. The valid values and their meanings depends on the database brand. However, the special value "unicode" (if supported) selects a mode where the query and result strings are unencoded (and possibly wide) unicode strings.

Throws

An error is thrown if the connection doesn't support the specified charset, or doesn't support charsets being set this way at all.

Note

See the set_charset functions for each database connection type for further details about the effects on the connection.

See also

get_charset, Sql.mysql.set_charset


Method shutdown

void shutdown()

Description

Shutdown a database server.


Method sqlstate

string sqlstate()

Description

Return last SQLSTATE.

The SQLSTATE error codes are specified in ANSI SQL.


Method streaming_query

int|object streaming_query(object|string q, mixed ... extraargs)

Description

Sends an SQL query synchronously to the underlying SQL-server and returns the results streaming in untyped mode.

For the arguments, please see the query() function.

The result is returned as a streaming Sql.sql_result object in untyped mode. This allows for having results larger than the available memory, and returning some more info about the result. Returns 0 if the query didn't return any result (e.g. INSERT or similar). For the other arguments, they are the same as for the query() function.

Note

Streaming operation is not supported by all sql databases. If not supported, this function will fall back to calling big_query().

See also

big_query, streaming_typed_query


Method streaming_typed_query

int|object streaming_typed_query(object|string q, mixed ... extraargs)

Description

Sends an SQL query synchronously to the underlying SQL-server and returns the results streaming in typed mode.

For the arguments, please see the query() function.

The result is returned as a streaming Sql.sql_result object in typed mode. This allows for having results larger than the available memory, and returning some more info about the result. Returns 0 if the query didn't return any result (e.g. INSERT or similar).

Note

Neither streaming operation nor typed results are supported by all sql databases. If not supported, this function will fall back to calling big_typed_query().

See also

streaming_query, big_typed_query


Method typed_query

array(mapping(string:mixed)) typed_query(object|string q, mixed ... extraargs)

Description

Sends an SQL query synchronously to the underlying SQL-server and returns the results in typed mode.

For the arguments, please see the query() function.

Returns

Returns one of the following on success:

array(mapping(string:mixed))

The result as an array of mappings indexed on the name of the columns. The values have the appropriate native pike types where they fit the SQL data types - see the class doc for details on typed mode.

zero

The value 0 (zero) if the query didn't return any result (eg INSERT or similar).

Note

Typed mode is not supported by all sql databases. If not supported, an error is thrown.

See also

query, big_typed_query

Class Sql.sql_result

Description

Implements the generic result base class of the SQL-interface. Used for return results from SQL.sql->big_query().

You typically don't get a direct clone of this class, but of a class that inherits it, like sql_array_result or sql_object_result.


Method create

Sql.sql_result Sql.sql_result(mixed res)

Description

Create a new Sql.sql_result object

Parameter res

Result to use as base.


Method eof

int eof()

Description

Returns non-zero if there are no more rows.


Method fetch_fields

array(mapping(string:mixed)) fetch_fields()

Description

Return information about the available fields.


Method fetch_json_result

string fetch_json_result()

Description

Fetch remaining result as JSON-encoded data.


Method fetch_row

int|array(string|int|float) fetch_row()

Description

Fetch the next row from the result.

Returns

Returns an array with one element per field in the same order as reported by fetch_fields(). See the Sql.Sql class documentation for more details on how different data types are represented.


Variable index

int Sql.sql_result.index

Description

This is the number of the current row. The actual semantics differs between different databases.


Variable master_res

mixed Sql.sql_result.master_res

Description

The actual result.


Method next_result

this_program next_result()

Description

Switch to the next set of results.

Some databases support returning more than one set of results. This function terminates the current result and switches to the next (if any).

Returns

Returns the sql_result object if there were more results, and 0 (zero) otherwise.

Throws

May throw the same errors as Sql.Sql()->big_query() et al.


Method num_fields

int num_fields()

Description

Returns the number of fields in the result.


Method num_rows

int num_rows()

Description

Returns the number of rows in the result.


Method seek

void seek(int skip)

Description

Skip past a number of rows.

Parameter skip

Number of rows to skip.

Module Sql.sql_util

Description

Some SQL utility functions


Method emulate_bindings

string emulate_bindings(string query, mapping(string|int:mixed)|void bindings, void|object driver)

Description

Build a raw SQL query, given the cooked query and the variable bindings It's meant to be used as an emulation engine for those drivers not providing such a behaviour directly (i.e. Oracle). The raw query can contain some variables (identified by prefixing a colon to a name or a number (i.e. ":var" or ":2"). They will be replaced by the corresponding value in the mapping.

Parameter query

The query.

Parameter bindings

Optional mapping containing the variable bindings. Make sure that no confusion is possible in the query. If necessary, change the variables' names.


Method fallback

void fallback()

Description

Throw an error in case an unimplemented function is called.


Method handle_extraargs

array(string|mapping(string|int:mixed)) handle_extraargs(string query, array(mixed) extraargs, void|mapping(string|int:mixed) bindings)

Description

Handle sprintf-based quoted arguments

Parameter query

The query as sent to one of the query functions.

Parameter extraargs

The arguments following the query.

Parameter bindings

Optional bindings mapping to which additional bindings will be added. It's returned as the second element in the return value. A new mapping is used if this isn't specified.

Returns

Returns an array with two elements:

Array
string 0

The query altered to use bindings-syntax.

mapping(string|int:mixed) 1

A bindings mapping. Zero if no bindings were added.


Method quote

string quote(string s)

Description

Quote a string so that it can safely be put in a query.

Parameter s

String to quote.


Variable zero

protected ZeroWrapper Sql.sql_util.zero

Description

Instance of ZeroWrapper used by handle_extraargs().

Class Sql.sql_util.MySQLBrokenUnicodeWrapper

Description

This one is used to get a buggy unicode support when compiled with an old MySQL client lib that doesn't have the charsetnr property in the field info. It looks at the binary flag instead, which is set for binary fields but might also be set for text fields (e.g. with a definition like "VARCHAR(255) BINARY").

I.e. the effect of using this one is that text fields with the binary flag won't be correctly decoded in unicode decode mode.

This has to be enabled either by passing "broken-unicode" as charset to Sql.mysql.create or Sql.mysql.set_charset, by calling Sql.mysql.set_unicode_decode_mode(-1), or by defining the environment variable PIKE_BROKEN_MYSQL_UNICODE_MODE. That will cause this buggy variant to be used if and only if the MySQL client lib doesn't support the charsetnr property.


Inherit UnicodeWrapper

inherit UnicodeWrapper : UnicodeWrapper

Class Sql.sql_util.MySQLUnicodeWrapper

Description

Result wrapper for MySQL that performs UTF-8 decoding of all nonbinary fields. Useful if the result charset of the connection has been set to UTF-8.

Note

There's normally no need to use this class directly. It's used automatically when mysql.set_unicode_decode_mode is activated.


Inherit UnicodeWrapper

inherit UnicodeWrapper : UnicodeWrapper

Class Sql.sql_util.UnicodeWrapper

Description

Result object wrapper performing utf8 decoding of all fields.


Method create

Sql.sql_util.UnicodeWrapper Sql.sql_util.UnicodeWrapper(object master_result)


Method eof

bool eof()

Description

Returns 1 if there are no more rows in the result.


Method fetch_fields

array(int|mapping(string:mixed)) fetch_fields()

Description

Returns Information about the fields in the result.

The following fields are converted from UTF8 if present:

"name" : string

The name of the field. Always present.

"table" : string

The table the field is from. Not present from all databases.

"default" : string

The default value for the column. Not available from all databases.


Method fetch_json_result

int|string fetch_json_result()

Description

JSON is always utf8 default, do nothing.


Method fetch_row

int|array(string) fetch_row()

Description

Fetch the next row from the result.

All strings in the result are decoded from UTF8.


Variable field_info

protected array(int|mapping(string:mixed)) Sql.sql_util.UnicodeWrapper.field_info

Description

Cached fetch_fields() result.


Variable master_result

protected object Sql.sql_util.UnicodeWrapper.master_result


Method num_fields

int num_fields()

Description

Returns the number of fields in the result.


Method num_rows

int num_rows()

Description

Returns the number of rows in the result.


Method seek

void seek(int rows)

Description

Skip ahead the specified number of rows.

Class Sql.sql_util.ZeroWrapper

Description

Wrapper to handle zero.

See also

zero


Method _sprintf

string sprintf(string format, ... Sql.sql_util.ZeroWrapper arg ... )

Returns

Returns the following:

"NULL"

If fmt is 's'.

"ZeroWrapper()"

If fmt is 'O'.

Otherwise it formats a 0 (zero).

Module Standards

Module Standards.ASN1

Module Standards.ASN1.Types


Inherit pre

inherit Standards.ASN1.Types : pre

Class Standards.ASN1.Types.TeletexString

Description

This used to be a string encoded with the T.61 character coding, and has been obsolete since the early 1990:s.

See also

BrokenTeletexString


Inherit BrokenTeletexString

inherit BrokenTeletexString : BrokenTeletexString

Module Standards.PKCS

Module Standards.PKCS.Certificate


Method get_certificate_issuer

Sequence get_certificate_issuer(string cert)

Description

Return the certificate issuer RDN from a certificate string.

Parameter cert

A string containing an X509 certificate.

Note that the certificate usually must be decoded using Standards.PEM.simple_decode().

Returns

An Standards.ASN1.Sequence object containing the certificate issuer Distinguished Name (DN).

Deprecated

Replaced by Standards.X509.decode_certificate.


Method get_certificate_subject

Sequence get_certificate_subject(string cert)

Description

Return the certificate subject RDN from a certificate string.

Parameter cert

A string containing an X509 certificate.

Note that the certificate usually must be decoded using PEM.simpe_decode().

Returns

An Standards.ASN1.Sequence object containing the certificate subject Distinguished Name (DN).

Deprecated

Replaced by Standards.X509.decode_certificate.


Inherit Certificate

inherit Standards.PKCS.Certificate : Certificate

Module Standards.PKCS.RSA

Description

RSA operations and types as described in PKCS-1.


Method algorithm_identifier

Sequence algorithm_identifier()

Description

Returns the AlgorithmIdentifier as defined in RFC 5280 section 4.1.1.2.


Method build_private_key

Sequence build_private_key(Crypto.RSA rsa)

Description

Creates a PrivateKeyInfo ASN.1 sequence for the given rsa object. See RFC 5208 section 5.


Method build_public_key

Sequence build_public_key(Crypto.RSA rsa)

Description

Creates a SubjectPublicKeyInfo ASN.1 sequence for the given rsa object. See RFC 5280 section 4.1.2.7.


Method parse_private_key

Crypto.RSA.State parse_private_key(object seq)

Description

Decode a RSAPrivateKey structure

Parameter key

RSAPrivateKey provided in ASN.1 format

Returns

Crypto.RSA object


Method parse_private_key

variant Crypto.RSA.State parse_private_key(string key)

Description

Decode a DER-coded RSAPrivateKey structure

Parameter key

RSAPrivateKey provided in ASN.1 DER-encoded format

Returns

Crypto.RSA object


Method parse_public_key

Crypto.RSA.State parse_public_key(string key)

Description

Decode a DER-coded RSAPublicKey structure

Parameter key

RSAPublicKey provided in ASN.1 DER-encoded format

Returns

Crypto.RSA object


Method private_key

string private_key(Crypto.RSA rsa)

Description

Create a DER-coded RSAPrivateKey structure

Parameter rsa

Crypto.RSA object

Returns

ASN1 coded RSAPrivateKey structure


Method public_key

string public_key(Crypto.RSA rsa)

Description

Create a DER-coded RSAPublicKey structure

Parameter rsa

Crypto.RSA object

Returns

ASN1 coded RSAPublicKey structure


Method signature_algorithm_id

Sequence signature_algorithm_id(Crypto.Hash hash)

Description

Returns the PKCS-1 algorithm identifier for RSA and the provided hash algorithm. One of MD2, MD5, SHA1, SHA256, SHA384 or SHA512.

Module Stdio

Description

Pike 8.0 compatibility predef::Stdio implementation.


Inherit Stdio

inherit 8.1::Stdio : Stdio

Module String

Description

Pike 8.0 compatibility String handling.

Module Thread


Method `()

optional Thread `()(mixed f, mixed ... args)

Description

Create a new thread.

Deprecated

Replaced by predef::Thread.Thread.


Inherit pre

inherit Thread : pre

Module Tools

Module Tools.PEM

Description

Support for parsing PEM-style messages.

Deprecated

Replaced by Standards.PEM.

Class Tools.PEM.EncapsulatedMsg

Description

Represents an encapsulated message.


Variable body

string Tools.PEM.EncapsulatedMsg.body

Description

Contains the raw message body. Access through decoded_body to get the decoded message.


Variable boundary

string Tools.PEM.EncapsulatedMsg.boundary

Description

Contains the raw boundary string. Access through get_boundary to get the decoded boundary string.


Method canonical_body

string canonical_body()

Description

Returns the raw body with all newlines as "\r\n".


Method decoded_body

string decoded_body()

Description

Returns decoded base64 encoded message body


Method get_boundary

string get_boundary()

Description

Returns decoded boundary string.


Variable headers

mapping(string:string) Tools.PEM.EncapsulatedMsg.headers

Description

Contains the message headers, or 0.


Method to_string

string to_string()

Description

Returns the message body and headers in the standard message format.

Class Tools.PEM.Msg

Description

Disassembles PGP and PEM style messages with parts separated by "-----BEGIN FOO-----" and "-----END FOO-----".


Method create

Tools.PEM.Msg Tools.PEM.Msg(string s)

Description

Creates a decoded PEM message

Parameter s

A string containing a PEM encoded message to be decoded.


Variable final_text

string Tools.PEM.Msg.final_text

Description

Contains any text following the PEM message.


Variable initial_text

string Tools.PEM.Msg.initial_text

Description

Contains any text preceeding the PEM message.


Variable parts

mapping(string:EncapsulatedMsg) Tools.PEM.Msg.parts

Description

The decoded PEM message, as an array of EncapsulatedMsg objects indexed by message name, such as "CERTIFICATE".

Class Tools.PEM.RFC934

Description

Represents an RFC 0934 text message.


Method create

Tools.PEM.RFC934 Tools.PEM.RFC934(string data)

Description

Decodes an RFC 0934 encoded message.


Variable encapsulated

array(EncapsulatedMsg) Tools.PEM.RFC934.encapsulated


Variable final_boundary

string Tools.PEM.RFC934.final_boundary


Variable final_text

string Tools.PEM.RFC934.final_text


Method get_final_boundary

string get_final_boundary()


Variable initial_text

string Tools.PEM.RFC934.initial_text


Method to_string

string to_string()

Module Tools.X509

Description

Functions to generate and validate RFC 2459 style X.509 v3 certificates.

Deprecated

Replaced by Standards.X509.


Constant CERT_BAD_SIGNATURE

constant int Tools.X509.CERT_BAD_SIGNATURE


Constant CERT_CHAIN_BROKEN

constant int Tools.X509.CERT_CHAIN_BROKEN


Constant CERT_INVALID

constant int Tools.X509.CERT_INVALID


Constant CERT_ROOT_UNTRUSTED

constant int Tools.X509.CERT_ROOT_UNTRUSTED


Constant CERT_TOO_NEW

constant int Tools.X509.CERT_TOO_NEW


Constant CERT_TOO_OLD

constant int Tools.X509.CERT_TOO_OLD


Constant CERT_UNAUTHORIZED_CA

constant int Tools.X509.CERT_UNAUTHORIZED_CA


Method decode_certificate

TBSCertificate decode_certificate(string|object cert)


Method dsa_sign_key

string dsa_sign_key(Sequence issuer, Crypto.DSA dsa, Sequence subject, string public_key, int serial, int ttl, array|void extensions)

Parameter issuer

Distinguished name for the issuer.

Parameter rsa

RSA parameters for the issuer.

Parameter subject

Distinguished name for the subject.

Parameter public_key

DER-encoded integer. See Standards.PKCS.DSA.public_key().

Parameter serial

Serial number for this key and issuer.

Parameter ttl

Validity time in seconds for this signature to be valid.

Parameter extensions

Set of extensions.

Returns

Returns a DER-encoded certificate.


Method make_selfsigned_dsa_certificate

string make_selfsigned_dsa_certificate(Crypto.DSA dsa, int ttl, array name, array|void extensions)


Method make_selfsigned_rsa_certificate

string make_selfsigned_rsa_certificate(Crypto.RSA rsa, int ttl, array name, array|void extensions)


Method make_tbs

Sequence make_tbs(object issuer, object algorithm, object subject, object keyinfo, object serial, int ttl, array extensions)


Method make_time

UTC make_time(int t)

Description

Creates a Standards.ASN1.Types.UTC object from the posix time t.


Method make_verifier

Verifier make_verifier(Object _keyinfo)


Method parse_time

mapping(string:int) parse_time(UTC asn1)

Description

Returns a mapping similar to that returned by gmtime

Returns
"year" : int
"mon" : int
"mday" : int
"hour" : int
"min" : int
"sec" : int

Method rsa_sign_digest

string rsa_sign_digest(Crypto.RSA rsa, object digest_id, string digest)


Method rsa_sign_key

string rsa_sign_key(Sequence issuer, Crypto.RSA rsa, Sequence subject, string public_key, int serial, int ttl, array|void extensions)

Parameter issuer

Distinguished name for the issuer.

Parameter rsa

RSA parameters for the issuer.

Parameter subject

Distinguished name for the issuer.

Parameter public_key

DER-encoded RSAPublicKey structure. See Standards.PKCS.RSA.public_key().

Parameter serial

Serial number for this key and subject.

Parameter ttl

Validity time in seconds for this signature to be valid.

Parameter extensions

Set of extensions.

Returns

Returns a DER-encoded certificate.


Method rsa_verify_digest

bool rsa_verify_digest(Crypto.RSA rsa, object digest_id, string digest, string s)


Method time_compare

int(-1..1) time_compare(mapping(string:int) t1, mapping(string:int) t2)

Description

Comparision function between two "date" mappings of the kind that parse_time returns.


Method verify_certificate

TBSCertificate verify_certificate(string s, mapping authorities)

Description

Decodes a certificate, checks the signature. Returns the TBSCertificate structure, or 0 if decoding or verification failes.

Authorities is a mapping from (DER-encoded) names to a verifiers.

Note

This function allows self-signed certificates, and it doesn't check that names or extensions make sense.


Method verify_certificate_chain

mapping verify_certificate_chain(array(string) cert_chain, mapping authorities, int|void require_trust)

Description

Decodes a certificate chain, checks the signatures. Verifies that the chain is unbroken, and that all certificates are in effect (time-wise.)

Returns a mapping with the following contents, depending on the verification of the certificate chain:

"error_code" : int

Error describing type of verification failure, if verification failed. May be one of the following: CERT_TOO_NEW, CERT_TOO_OLD, CERT_ROOT_UNTRUSTED, CERT_BAD_SIGNATURE, CERT_INVALID, CERT_UNAUTHORIZED_CA or CERT_CHAIN_BROKEN

"error_cert" : int

Index number of the certificate that caused the verification failure.

"self_signed" : bool

Non-zero if the certificate is self-signed.

"verified" : bool

Non-zero if the certificate is verified.

"authority" : string

Standards.ASN1.Sequence of the authority RDN that verified the chain.

"cn" : string

Standards.ASN1.Sequence of the common name RDN of the leaf certificate.

Parameter cert_chain

An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate.

Parameter authorities

A mapping from (DER-encoded) names to verifiers.

Parameter require_trust

Require that the certificate be traced to an authority, even if it is self signed.

See Standards.PKCS.Certificate.get_dn_string for converting the RDN to an X500 style string.

Class Tools.X509.TBSCertificate


Variable algorithm

Sequence Tools.X509.TBSCertificate.algorithm


Variable der

string Tools.X509.TBSCertificate.der


Variable extensions

object Tools.X509.TBSCertificate.extensions

Note

optional


Method init

this_program init(Object asn1)


Variable issuer

Sequence Tools.X509.TBSCertificate.issuer


Variable issuer_id

BitString Tools.X509.TBSCertificate.issuer_id

Note

optional


Variable not_after

mapping Tools.X509.TBSCertificate.not_after


Variable not_before

mapping Tools.X509.TBSCertificate.not_before


Variable public_key

Verifier Tools.X509.TBSCertificate.public_key


Variable serial

Gmp.mpz Tools.X509.TBSCertificate.serial


Variable subject

Sequence Tools.X509.TBSCertificate.subject


Variable subject_id

BitString Tools.X509.TBSCertificate.subject_id

Note

optional


Variable version

int Tools.X509.TBSCertificate.version

Class Tools.X509.rsa_verifier


Inherit Verifier

inherit Verifier : Verifier


Method init

this_program init(string key)


Method verify

bool verify(Sequence algorithm, string msg, string signature)

Namespace cpp::

Description

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

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

See also

compile(), cpp(), CompilerEnvironment.CPP


Directive #!

#!

Description

All lines beginning with #! will be regarded as comments, to enable shell integration. It is recommended that Pike applications begin with the line "#! /usr/bin/env pike" for maximum cross platform compatibility.


Directive #""

#""

Description

If a string literal is opened with #" newlines in the string will end up in the string literal, instead of triggering a "newline in string" error.

Note

Newlines will be converted to \n characters in the string even if the newlines in the file are something else.

This preprocessor directive may appear anywhere a string may appear.

See also

#string


Directive #(#)
Directive #[#]
Directive #{#}

#(#)
#[#]
#{#}

Description

If a string literal is opened with #( all subsequent characters until the closing #) will be treated as literals, including newlines, \, " and '.

There are three different pairs of start/end tokens for this type of literals, #( and #), #[ and #], and #{ and #}.

Example

#["\n\'##] is equivalent to "\"\\n\\'#".


Directive #line
Directive #<integer>

#line
#<integer>

Description

A hash character followed by a number or by the string "line" and a number will make the preprocessor line counter set this number as the line number for the next line and adjust the following lines accordingly.

All error messages from Pike will use these line numbers.

Optionally the number may be followed by a file name, e.g. #line 1 "/home/pike/program.pike.in". Then this filename will be used instead of the current file for error messages.


Directive #charset

#charset

Description

Inform the preprocessor about which charset the file is encoded with. The Charset module is called with this string to decode the remainder of the file.


Directive #define

#define

Description

This directive is used to define or redefine a cpp macro.

The simplest way to use define is to write

#define <identifier> <replacement string>

which will cause all subsequent occurances of <identifier to be replaced with the <replacement string>.

Define also has the capability to use arguments, thus a line like

#define <identifier>(arg1, arg2) <replacement string>

would cause <identifer> to be a macro. All occurances of '<identifier>(something1,something2d)' would be replaced with the <replacement string>. And in the <replacement string>, arg1 and arg2 will be replaced with something1 and something2.


Directive #elif
Directive #elseif

#elif
#elseif

Description

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

Example

The following two are equivalent:

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

And

#ifdef A
    // Code for A.
  #elif defined(B)
    // Code for B.
  #elseif defined(C)
    // Code for C.
  #else
    // Code for D.
  #endif
See also

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


Directive #elifdef
Directive #elseifdef

#elifdef
#elseifdef

Description

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

Example

The following two are equivalent:

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

And

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

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


Directive #elifndef
Directive #elseifndef

#elifndef
#elseifndef

Description

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

Example

The following two are equivalent:

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

And

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

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


Directive #else

#else

Description

This directive is used to divide the current code block into another code block with inverse activation.

Example
#ifdef FAST_ALGORITHM
    do_fast_algorithm();
  #elif defined(EXPERIMENTAL_ALGORITHM)
    do_experimental_algorithm();
  #else
    do_default_algorithm();
  #endif

Directive #endif

#endif

Description

End a block opened with #if, #ifdef, #ifndef, #else, #elseif or #elif.

Example
#ifdef DEBUG
    do_debug_stuff();
  #endif // DEBUG

Directive #error

#error

Description

Throw an error during preprocessing.

This directive causes a cpp error. It can be used to notify the user that certain functions are missing and similar things.

Note

Note that this directive will cause cpp() to throw an error at the end of preprocessing, which will cause any compilation to fail.

Example
#if !constant(Yp)
  #error Support for NIS not available.
  #endif
See also

#warning


Directive #if

#if

Description

The #if directive can evaluate simple expressions and, if the expression is evaluates to true, "activate" the code block that follows. The code block ends when an #endif, #else, #elseif or #elif block is encountered at the same nesting depth.

The #if expressions may include defines, integer, string and float constants, ?:, || and && operations, ~, ^, !, | and & operations, <, >, <=, >=, == and != operations, +, -, *, /, << and >> operations and paranthesis.

Strings may also be indexed with the [] index operator. Finally there are three special "functions" available in #if expressions; defined(), efun() and constant().

See also

#ifdef, #ifndef, #elif, #else, #endif, defined(), constant(), efun()


Directive #ifdef

#ifdef

Description

Check whether an identifier is a macro.

The directive

#ifdef <identifier>

is equivalent to

#if defined(<identifier>)

See also

#if, #ifndef, defined


Directive #ifndef

#ifndef

Description

Check whether an identifier is not a macro.

This is the inverse of #ifdef.

The directive

#ifndef <identifier>

is equivalent to

#if !defined(<identifier>)

See also

#if, #ifdef, defined


Directive #include

#include

Description

#include is used to insert the contents of another file into the processed file at the place of the include directive.

Files can be referenced either by absolute or relative path from the source file, or searched for in the include paths.

To include a file with absolute or relative path, use double quotes, e.g. #include "constants.pike" or #include "../debug.h".

To include from the include paths, use less than and greater than, e.g. #include <profiling.h>.

It is also possible to include a file whose path is defined in a preprocessor macro, e.g. #include USER_SETTINGS.


Directive #pike

#pike

Description

Set the Pike compiler backward compatibility level.

This tells the compiler which version of Pike it should attempt to emulate from this point on in the current compilation unit.

This is typically used to "quick-fix" old code to work with more recent versions of Pike.

Example
// This code was written for Pike 7.2, and depends on
  // the old behaviour for 7.2::dirname().
  #pike 7.2

  // ... Code that uses dirname() ...

This directive is also needed for Pike modules that have been installed globally, and might be used by a Pike that has been started with the -V flag.

Example
// Pike modules that are bundled with Pike are
  // typically written for the same version of Pike.
  #pike __REAL_VERSION__

Directive #pragma

#pragma

Description

This is a generic directive for flags to the compiler.

These are some of the flags that are available:

"all_inline"

This is the same as adding the modifier inline to all functions that follow.

"all_final"

Instructs the compiler to mark all symbols as final.

"deprecation_warnings"

Enable warnings for use of deprecated symbols (default).

"no_deprecation_warnings"

Disable warnings for use of deprecated symbols. This is typically used in code that implements the deprecated symbols.

"save_parent"

Cause nested classes to save a reference to their surrounding class even if not strictly needed.

"dont_save_parent"

Inverse of "save_parent". This is needed to override if the global symbol predef::__pragma_save_parent__ has been set.

"strict_types"

Enable warnings for all cases where the compiler isn't certain that the types are correct.

"disassemble"

Enable disassembly output for the code being compiled. Note that this option essentially has a function-level scope, so enabling it for just a few lines is usually a noop. This is similar to Debug.assembler_debug() level 3.

"no_disassemble"

Disable disassembly output (default).


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


Directive #string

#string

Description

The preprocessor directive #string will load the file in the string that follows and insert its contents as a string. This preprocessor directive may appear anywhere a string may appear.

Example
do_something(#string "the_file.wks"
);
See also

#include


Directive #undef
Directive #undefine

#undef
#undefine

Description

This removes the effect of a #define, all subsequent occurances of the undefined identifier will not be replaced by anything.

Note

Note that when undefining a macro, you just give the identifer, not the arguments.

Example

// Strip debug #define werror(X ...) 0 #include "/home/someone/experimental/stuff.h" #undef werror

See also

#define, defined()


Directive #warning

#warning

Description

Generate a warning during preprocessing.

This directive causes a cpp warning, it can be used to notify the user that certain functions are missing and similar things.

Example
#if !constant(Yp)
  #warning Support for NIS not available. Some features may not work.
  #endif
See also

#error


Method _Pragma

void _Pragma(string directive)

Description

This macro inserts the corresponding #pragma directive in the source.

e.g. _Pragma("strict_types") is the same as #pragma strict_types .

See also

#pragma


Constant __AUTO_BIGNUM__

constant __AUTO_BIGNUM__

Description

This define is defined when automatic bignum conversion is enabled. When enabled all integers will automatically be converted to bignums when they get bigger than what can be represented by an integer, hampering performance slightly instead of crashing the program. This define is always set since Pike 8.0.


Constant __BUILD__

constant __BUILD__

Description

This constant contains the build number of the current Pike version, represented as an integer. If another Pike version is emulated, this constant remains unaltered.

See also

__REAL_MINOR__


Variable __COUNTER__

int(1..) __COUNTER__

Description

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


Constant __DATE__

constant __DATE__

Description

This define contains the current date at the time of compilation, e.g. "Jul 28 2001".


Constant __DIR__

constant __DIR__

Description

This define contains the directory path of the source file.


Constant __FILE__

constant __FILE__

Description

This define contains the file path and name of the source file.


Constant __LINE__

constant __LINE__

Description

This define contains the current line number, represented as an integer, in the source file.


Constant __MAJOR__

constant __MAJOR__

Description

This define contains the major part of the current Pike version, represented as an integer. If another Pike version is emulated, this define is updated accordingly.

See also

__REAL_MAJOR__


Constant __MINOR__

constant __MINOR__

Description

This define contains the minor part of the current Pike version, represented as an integer. If another Pike version is emulated, this define is updated accordingly.

See also

__REAL_MINOR__


Constant __NT__

constant __NT__

Description

This define is defined when the Pike is running on a Microsoft Windows OS, not just Microsoft Windows NT, as the name implies.


Constant __PIKE__

constant __PIKE__

Description

This define is always true.


Constant __REAL_BUILD__

constant __REAL_BUILD__

Description

This define always contains the minor part of the version of the current Pike, represented as an integer.

See also

__BUILD__


Constant __REAL_MAJOR__

constant __REAL_MAJOR__

Description

This define always contains the major part of the version of the current Pike, represented as an integer.

See also

__MAJOR__


Constant __REAL_MINOR__

constant __REAL_MINOR__

Description

This define always contains the minor part of the version of the current Pike, represented as an integer.

See also

__MINOR__


Constant __REAL_VERSION__

constant __REAL_VERSION__

Description

This define always contains the version of the current Pike, represented as a float.

See also

__VERSION__


Constant __TIME__

constant __TIME__

Description

This define contains the current time at the time of compilation, e.g. "12:20:51".


Constant __VERSION__

constant __VERSION__

Description

This define contains the current Pike version as a float. If another Pike version is emulated, this define is updated accordingly.

See also

__REAL_VERSION__


Constant __amigaos__

constant __amigaos__

Description

This define is defined when the Pike is running on Amiga OS.


Method constant
Method efun

bool constant(mixed identifier)
__deprecated__ bool efun(mixed identifier)

Description

Check whether the argument resolves to a constant or not.

See also

#if, defined()


Method defined

bool defined(mixed identifier)

Description

Check whether an identifier is a cpp macro or not.

Returns

defined returns true if the symbol given as argument is defined.

Note

#if defined(MY_DEF) is equivalent to #ifdef MY_DEF.

See also

#if, #ifdef, constant()


Constant static_assert

constant static_assert

Description

This define expands to the symbol _Static_assert.

It is the preferred way to perform static (ie compile-time) assertions.

Note

The macro can also be used to check for whether static assertions are supported.

See also

predef::_Static_assert()

Namespace lfun::

Description

Callback functions used to overload various builtin functions.

The functions can be grouped into a few sets:

  • Object initialization and destruction.

    __INIT(), create(), _destruct()

  • Unary operator overloading.

    `~(), `!(), _values(), cast(), _sizeof(), _indices(), __hash()

  • Binary asymmetric operator overloading.

    `+(), ``+(), `-(), ``-(), `&(), ``&(), `|(), ``|(), `^(), ``^(), `<<(), ``<<(), `>>(), ``>>(), `*(), ``*(), `/(), ``/(), `%(), ``%()

  • Binary symmetric operator overloading.

    The optimizer will make assumptions about the relations between these functions.

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

  • Other binary operator overloading.

    `[](), `[]=(), `->(), `->=(), `+=(), `()()

  • Overloading of other builtin functions.

    _is_type(), _sprintf(), _m_delete(), _get_iterator(), _search()

Note

Although these functions are called from outside the object they exist in, they will still be used even if they are declared protected. It is in fact recommended to declare them protected, since that will hinder them being used for other purposes.

See also

::


Method __INIT

void __INIT()

Description

Inherit and variable initialization.

This function is generated automatically by the compiler. It's called just before lfun::create() when an object is instantiated.

It first calls any __INIT functions in inherited classes (regardless of modifiers on the inherits). It then executes all the variable initialization expressions in this class, in the order they occur.

Note

This function can not be overloaded or blocked from executing.

See also

lfun::create()


Method __create__

void __create__(__unknown__ ... args)

Description

Low-level object creation callback.

This function is generated automatically by the compiler for inline classes that declare parameters. A call to it and its arguments are automatically added to user-supplied lfun::create()

Note

This function is typically created implicitly by the compiler using the syntax:

class Foo(int foo) {
  int bar;
}

In the above case an implicit lfun::__create__() is created, and it's equivalent to:

class Foo {
  int foo;
  int bar;
  local protected void __create__(int foo)
  {
    this::foo = foo;
  }
}
Note

Note also that in case lfun::create() does not exist, it will be created as an alias for this function.

Note

This function did not exist in Pike 8.0 and earlier (where it was instead automatically inlined in lfun::create().

See also

lfun::create(), lfun::__INIT()


Method __hash

int __hash()

Description

Hashing callback.

The main caller of this function is predef::hash_value() or the low-level equivalent, which get called by various mapping operations when the object is used as index in a mapping.

Returns

It should return an integer that corresponds to the object in such a way that all values which lfun::`== considers equal to the object get the same hash value.

Note

The function predef::hash does not return hash values that are compatible with this one.

Note

It's assumed that this function is side-effect free.

See also

lfun::`==, predef::hash_value()


Method _annotations

array _annotations(object|void context, int|void access, bool|void recursive)

Description

Called by annotations()

Parameter context

Inherit in the current object to return the annotations for. If UNDEFINED or left out, this_program::this should be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

Parameter recursive

Include nested annotations from the inherits.

See also

annotations()


Method _atomic_get_set

mixed _atomic_get_set(mixed index, mixed value)

Description

Get and set the value for an index atomically.

Parameter index

Index for which to get and set the value.

Parameter value

Value to set.

Returns

Returns the previous value at index index.

See also

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


Method _deserialize

void _deserialize(object o, function(function(mixed:void), string, type:mixed) deserializer)

Description

Dispatch function for Serialization.deserialize().

Parameter o

Object to serialize. Always a context of the current object.

Parameter deserializer

Function to be called once for every variable to serialize.

The deserializer function expects to be called with three arguments:

setter - Function that sets the symbol value.

symbol - The symbol name.

symbol_type - The type of the symbol.

Note

A default implementation of lfun::_serialize() and lfun::_deserialize() is available in Serializer.Serializable.

See also

lfun::_serialize(), Serializer.deserialize(), Serializer.Serializable()->_deserialize()


Method _destruct

void _destruct(void|int reason)

Description

Object destruction callback.

This function is called right before the object is destructed. That can happen either through a call to predef::destruct(), when there are no more references to the object, or when the garbage collector discovers that it's part of a cyclic data structure that has become garbage.

Parameter reason

A flag that tells why the object is destructed:

Object.DESTRUCT_EXPLICIT

Destructed explicitly by predef::destruct.

Object.DESTRUCT_NO_REFS

Destructed due to running out of references.

Object.DESTRUCT_GC

Destructed by the garbage collector.

Object.DESTRUCT_CLEANUP

Destructed as part of the cleanup when the pike process exits. Occurs only if Pike has been compiled with the configure option --with-cleanup-on-exit. See note below.

Note

Objects are normally not destructed when a process exits, so _destruct functions aren't called then. Use atexit to get called when the process exits.

Note

Regarding destruction order during garbage collection:

If an object is destructed by the garbage collector, it's part of a reference cycle with other things but with no external references. If there are other objects with _destruct functions in the same cycle, it becomes a problem which to call first.

E.g. if this object has a variable with another object which (directly or indirectly) points back to this one, you might find that the other object already has been destructed and the variable thus contains zero.

The garbage collector tries to minimize such problems by defining an order as far as possible:

  • If an object A contains an lfun::_destruct and an object B does not, then A is destructed before B.

  • If A references B single way, then A is destructed before B.

  • If A and B are in a cycle, and there is a reference somewhere from B to A that is weaker than any reference from A to B, then A is destructed before B.

  • If a cycle is resolved according to the rule above by ignoring a weaker reference, and there is another ambiguous cycle that would get resolved by ignoring the same reference, then the latter cycle will be resolved by ignoring that reference.

  • Weak references (e.g. set with predef::set_weak_flag()) are considered weaker than normal references, and both are considered weaker than strong references.

  • Strong references are those from objects to the objects of their lexically surrounding classes. There can never be a cycle consisting only of strong references. (This means the gc never destructs a parent object before all children have been destructed.)

An example with well defined destruct order due to strong references:

class Super {
  class Sub {
    protected void _destruct() {
      if (!Super::this)
        error ("My parent has been destructed!\n");
    }
  }
  Sub sub = Sub();
  protected void _destruct() {
    if (!sub)
      werror ("sub already destructed.\n");
  }
}

The garbage collector ensures that these objects are destructed in an order so that werror in Super is called and not error in Sub.

Note

When the garbage collector calls lfun::_destruct, all accessible non-objects and objects without _destruct functions are still intact. They are not freed if the _destruct function adds external references to them. However, all objects with lfun::_destruct in the cycle are already scheduled for destruction and will therefore be destroyed even if external references are added to them.

See also

lfun::create(), predef::destruct()


Method _equal

int _equal(mixed arg)

Description

Recursive equality callback.

Returns

Is expected to return 1 if the current object is equal to arg, and 0 (zero) otherwise.

Note

It's assumed that this function is side-effect free.

Note

Note that this function may return different values at different times for the same argument due to the mutability of the object.

See also

predef::equal(), lfun::`==()


Method _get_iterator

predef::Iterator _get_iterator(mixed ... args)

Description

Iterator creation callback.

Parameter args

Optional extra arguments as passed to get_iterator(). The implicit call from foreach() does not provide any arguments.

The returned predef::Iterator instance works as a cursor that references a specific item contained (in some arbitrary sense) in this one.

Note

It's assumed that this function is side-effect free.

See also

predef::Iterator, predef::get_iterator, predef::foreach()


Method _indices

array _indices(object|void context, int|void access)

Description

List indices callback.

Returns

Expected to return an array with the valid indices in the object.

Note

It's assumed that this function is side-effect free.

See also

predef::indices(), lfun::_values(), lfun::_types(), ::_indices()


Method _is_type

bool _is_type(string basic_type)

Description

Type comparison callback.

Called by the cast operator to determine if an object simulates a basic type.

Parameter basic_type

One of:

"array"
"float"
"function"
"int"
"mapping"
"multiset"
"object"
"program"
"string"
"type"
"void"
"zero"

The following five shouldn't occurr, but are here for completeness:

"lvalue"
"mapping_data"
"object storage"
"pike_frame"
"unknown"
Returns

Expected to return 1 if the object is to be regarded as a simulation of the type specified by basic_type.

Note

The argument is currently a string with the name of the type, but might in the future be a value of the type type.

Note

It's assumed that this function is side-effect free.


Method _iterator_index

mixed _iterator_index()

Description

Called in Iterator objects by foreach (optional).

Returns the current index for an iterator, or UNDEFINED if the iterator doesn't point to any item. If this function is not present, the return value from lfun::_iterator_next() will be used.

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

See also

lfun::_iterator_next(), lfun::_iterator_value()


Method _iterator_next

mixed _iterator_next()

Description

Called in Iterator objects by foreach.

Advances the iterator one step.

Iterators start at the position before the first element, and foreach calls this function repeatedly until it returns UNDEFINED.

Calling it again after it has returned UNDEFINED will typically cause it to restart the iteration with the first element (ie the start and end sentinel values are the same).

Returns

Returns UNDEFINED if there are no more elements in the iterator. Otherwise it may return any other value, which for convenience will be used as index and/or value in case there is no lfun::_iterator_index() and/or no lfun::_iterator_value().

See also

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


Method _iterator_value

mixed _iterator_value()

Description

Called in Iterator objects by foreach (optional).

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


Method _m_add

void _m_add()

Description

Called by m_add().

See also

lfun::_m_delete(), lfun::_m_clear()


Method _m_clear

void _m_clear()

Description

Called by m_clear().

See also

lfun::_m_delete(), lfun::_m_add()


Method _m_delete

mixed _m_delete(mixed arg)

Description

Delete index callback.

See also

predef::m_delete()


Method _random

mixed _random(function(int(0..):string(8bit)) random_string, function(mixed:mixed) random)

Description

Called by random(). Typical use is when the object implements a ADT, when a call to this lfun should return a random member of the ADT or range implied by the ADT.

Parameter random_string

A RandomInterface()->random_string function that returns a string(8bit) of the specified length.

Parameter random

A RandomInterface()->random function.

See also

predef::random(), RandomInterface


Method _reverse

mixed _reverse(mixed ... options)

Description

Called by reverse().


Method _search

mixed _search(mixed needle, mixed|void start, mixed ... extra_args)

Description

Search callback.

The arguments are sent straight from search(), and are as follows:

Parameter needle

Value to search for.

Parameter start

The first position to search.

Parameter extra_args

Optional extra arguments as passed to search().

See also

predef::search()


Method _serialize

void _serialize(object o, function(mixed, string, type:void) serializer)

Description

Dispatch function for Serializer.serialize().

Parameter o

Object to serialize. Always a context of the current object.

Parameter serializer

Function to be called once for every variable to serialize.

The serializer function expects to be called with three arguments:

value - The value of the symbol.

symbol - The symbol name.

symbol_type - The type of the symbol.

Note

A default implementation of lfun::_serialize() and lfun::_deserialize() is available in Serializer.Serializable.

See also

lfun::_deserialize(), Serializer.serialize(), Serializer.Serializable()->_serialize()


Method _size_object

int _size_object()

Description

Debug.size_object() callback.

Returns

Returns an approximation of the memory use in bytes for the object.

See also

Debug.size_object(), lfun::_sizeof()


Method _sizeof

int _sizeof()

Description

Size query callback.

Called by predef::sizeof() to determine the number of elements in an object. If this function is not present, the number of public symbols in the object will be returned.

Returns

Expected to return the number of valid indices in the object.

Note

It's assumed that this function is side-effect free.

See also

predef::sizeof()


Method _sprintf

string _sprintf(int conversion_type, mapping(string:int)|void params)

Description

Sprintf callback.

This method is called by predef::sprintf() to print objects. If it is not present, printing of the object will not be supported for any conversion-type except for the %O-conversion-type, which will output "object".

Parameter conversion_type

One of:

'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 byte order.

'f'

Float.

'g'

Heuristically chosen representation of float.

'G'

Like %g, but uses uppercase E for exponent.

'e'

Exponential notation float.

'E'

Like %e, but uses uppercase E for exponent.

's'

String.

'O'

Any value (debug style).

't'

Type of the argument.

Parameter params

Conversion parameters. The following parameters may be supplied:

"precision" : int

Precision.

"width" : int

Field width.

"flag_left" : int(1)

Indicates that the output should be left-aligned.

"indent" : int

Indentation level in %O-mode.

Returns

Is expected to return a string describing the object formatted according to conversion_type.

Note

_sprintf() is currently not called for the following conversion-types:

'F'

Binary IEEE representation of float (%4F gives single precision, %8F gives double precision.)

Note

This function might be called at odd times, e.g. before lfun::create has been called or when an error has occurred. The reason is typically that it gets called when a backtrace is being formatted to report an error. It should therefore be very robust and not make any assumptions about its own internal state, at least not when conversion_type is 'O'.

Note

It's assumed that this function is side-effect free.

See also

predef::sprintf()


Method _sqrt

mixed _sqrt()

Description

Called by sqrt().

See also

sqrt()


Method _sqrt

mixed _sqrt()

Description

Called by sqrt when the square root of an object is requested.

Note

_sqrt is not a real lfun, so it must not be defined as static.

See also

predef::sqrt()


Method _types

array _types(object|void context, int|void access)

Description

List types callback.

This callback is typically called via predef::types().

Returns

Expected to return an array with the types corresponding to the indices returned by lfun::_indices().

Note

It's assumed that this function is side-effect free.

Note

predef::types() was added in Pike 7.9.

See also

predef::types(), lfun::_indices(), lfun::_values(), ::_types()


Method _values

array _values(object|void context, int|void access)

Description

List values callback.

Returns

Expected to return an array with the values corresponding to the indices returned by lfun::_indices().

Note

It's assumed that this function is side-effect free.

See also

predef::values(), lfun::_indices(), lfun::_types(), ::_values()


Method `!

int `!()

Description

Logical not callback.

Returns

Returns non-zero if the object should be evaluated as false, and 0 (zero) otherwise.

Note

It's assumed that this function is side-effect free.

See also

predef::`!()


Method `%

mixed `%(zero ... args)

Description

Left side modulo callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``%(), predef::`%()


Method `&

mixed `&(zero ... args)

Description

Left side bitwise and/intersection callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``&(), predef::`&()


Method `()

mixed `()(zero ... args)

Description

Apply callback.

See also

predef::`()


Method `*

mixed `*(zero ... args)

Description

Left side multiplication/repetition/implosion callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``*(), predef::`*()


Method `**

object|int|float `**(int|float|object exp)

Description

Called by predef::`**().

See also

predef::`**(), lfun::``**()


Method `+

mixed `+(zero arg)

Description

Left side addition/concatenation callback.

This is used by predef::`+. It's called with the argument that follow this object in the argument list of the call to predef::`+. The returned value should be a new instance that represents the addition/concatenation between this object and the argument.

Note

It's assumed that this function is side-effect free.

Note

In versions of Pike prior to 8.1.10 this function could get called with multiple arguments.

See also

lfun::``+(), lfun::`+=(), predef::`+()


Method `+=

this_program `+=(zero arg)

Description

Destructive addition/concatenation callback.

This is used by predef::`+. It's called with the argument that follow this object in the argument list of the call to predef::`+. It should update this object to represent the addition/concatenation between it and the argument. It should always return this object.

Note

This function should only be implemented if lfun::`+() also is. It should only work as a more optimized alternative to that one, for the case when it's safe to change the object destructively and use it directly as the result.

Note

This function is not an lfun for the += operator. It's only whether or not it's safe to do a destructive change that decides if this function or lfun::`+() is called; both the + operator and the += operator can call either one.

Note

In versions of Pike prior to 8.1.10 this function could get called with multiple arguments.

See also

lfun::`+(), predef::`+()


Method `-

mixed `-(void|zero arg)

Description

Negation and left side subtraction/set difference callback.

This is used by predef::`-. When called without an argument the result should be a new instance that represents the negation of this object, otherwise the result should be a new instance that represents the difference between this object and arg.

Note

It's assumed that this function is side-effect free.

See also

lfun::``-(), predef::`-()


Method `->

mixed `->(string index, object|void context, int|void access)

Description

Arrow index callback.

Parameter index

Symbol in context to access.

Parameter context

Context in the current object to start the search from. If UNDEFINED or left out, this_program::this is to be be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

Returns

Returns the value at index if it exists, and UNDEFINED otherwise.

Note

It's assumed that this function is side-effect free.

See also

predef::`->(), ::`->()


Method `->=

mixed `->=(string index, zero value, object|void context, int|void access)

Description

Atomic get and set arrow index callback.

Parameter index

Symbol in context to change the value of.

Parameter value

The new value.

Parameter context

Context in the current object to index.

If UNDEFINED or left out, this_program::this is to be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

This function is to set the value at symbol index of the current object to value.

Returns

Returns the previous value at symbol index of the current object.

Note

In Pike 8.0 and earlier the return value of this function was ignored.

See also

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


Method `/

mixed `/(zero ... args)

Description

Left side division/split callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``/(), predef::`/()


Method `<

bool `<(mixed arg)

Description

Less than test callback.

Note

It's assumed that this function is side-effect free.

See also

predef::`<()


Method `<<

mixed `<<(zero arg)

Description

Left side left shift callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``<<(), predef::`<<()


Method `==

bool `==(mixed arg)

Description

Equivalence test callback.

Returns

Is expected to return 1 if the current object is equivalent to arg (ie may be replaced with arg, with no semantic differences (disregarding the effects of destruct())), and 0 (zero) otherwise.

Note

If this is implemented it may be necessary to implement lfun::__hash too. Otherwise mappings may hold several objects as indices which are duplicates according to this function. This may also affect various other functions that use hashing internally, e.g. predef::Array.uniq.

Note

It's assumed that this function is side-effect free.

Note

It's recommended to only implement this function for immutable objects, as otherwise stuff may get confusing when things that once were equivalent no longer are so, or the reverse.

See also

predef::`==(), lfun::__hash


Method `>

bool `>(mixed arg)

Description

Greater than test callback.

Note

It's assumed that this function is side-effect free.

See also

predef::`>()


Method `>>

mixed `>>(zero arg)

Description

Left side right shift callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``>>(), predef::`>>()


Method `[..]

mixed `[..](zero low, int low_bound_type, zero high, int high_bound_type)

Description

Subrange callback.

Note

It's assumed that this function is side-effect free.

See also

predef::`[..]


Method `[]

mixed `[](zero arg1, zero|void arg2)

Description

Indexing callback.

For compatibility, this is also called to do subranges unless there is a `[..] in the class. See predef::`[..] for details.

Note

It's assumed that this function is side-effect free.

See also

predef::`[](), predef::`[..]


Method `[]=

mixed `[]=(zero index, zero value, object|void context, int|void access)

Description

Atomic get and set index callback.

Parameter index

Index to change the value of.

Parameter value

The new value.

Parameter context

Context in the current object to index.

If UNDEFINED or left out, this_program::this is to be used (ie start at the current context and ignore any overloaded symbols).

Parameter access

Access permission override. One of the following:

0

See only public symbols.

UNDEFINED
1

See protected symbols as well.

This function is to set the value at index index of the current object to value.

Returns

Returns the previous value at index index of the current object.

Note

In Pike 8.0 and earlier the return value of this function was ignored.

See also

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


Method `^

mixed `^(zero ... args)

Description

Left side exclusive or callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``^(), predef::`^()


Method ``%

mixed ``%(zero ... args)

Description

Right side modulo callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`%(), predef::`%()


Method ``&

mixed ``&(zero ... args)

Description

Right side bitwise and/intersection callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`&(), predef::`&()


Method ``*

mixed ``*(zero ... args)

Description

Right side multiplication/repetition/implosion callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`*(), predef::`*()


Method ``**

object|int|float ``**(int|float|object base)

Description

Called by predef::`**().

See also

predef::`**(), lfun::`**()


Method ``+

mixed ``+(zero arg)

Description

Right side addition/concatenation callback.

This is used by predef::`+. It's called with the sum of the arguments that precede this object in the argument list of the call to predef::`+. The returned value should be a new instance that represents the addition/concatenation between the argument and this object.

Note

It's assumed that this function is side-effect free.

Note

In versions of Pike prior to 8.1.10 this function could get called with multiple arguments.

See also

lfun::`+(), predef::`+()


Method ``-

mixed ``-(zero arg)

Description

Right side subtraction/set difference callback.

This is used by predef::`-. The result should be a new instance that represents the difference between arg and this object.

Note

It's assumed that this function is side-effect free.

See also

lfun::`-(), predef::`-()


Method ``/

mixed ``/(zero ... args)

Description

Right side division/split callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`/(), predef::`/()


Method ``<<

mixed ``<<(zero arg)

Description

Right side left shift callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`<<(), predef::`<<()


Method ``>>

mixed ``>>(zero arg)

Description

Right side right shift callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`>>(), predef::`>>()


Method ``^

mixed ``^(zero ... args)

Description

Right side exclusive or callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`^(), predef::`^()


Method ``|

mixed ``|(zero ... args)

Description

Right side bitwise or/union callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::`|(), predef::`|()


Method `|

mixed `|(zero ... args)

Description

Left side bitwise or/union callback.

Note

It's assumed that this function is side-effect free.

See also

lfun::``|(), predef::`|()


Method `~

mixed `~()

Description

Complement/inversion callback.

Note

It's assumed that this function is side-effect free.

See also

predef::`~()


Method cast

mixed cast(string requested_type)

Description

Value cast callback.

Parameter requested_type

Type to cast to.

Returns

Expected to return the object value-casted (converted) to the type described by requested_type.

Note

The argument is currently a string with the name of the type, but might in the future be a value of the type type.

Note

Currently casting between object types is a noop.

Note

If the returned value is not deemed to be of the requested type a runtime error may be thrown.

Note

It's assumed that this function is side-effect free.


Method create

void lfun:create(__unknown__ ... args)

Description

Object creation callback.

This function is called right after lfun::__INIT().

args are the arguments passed when the program was called.

Note

If there exists an implicitly created lfun::__create__() its arguments will be prepended to args (affecting the prototype for lfun::create()), and a call to it will be prepended to the code of lfun::create().

Note

In Pike 8.0 and earlier the code equivalent to lfun::__create__() was inlined at the beginning of lfun::create().

Note

If this function does not exist, but lfun::__create__() does, it will instead be called directly.

See also

lfun::__create__(), lfun::__INIT(), lfun::_destruct()


Variable symbol

mixed lfun::symbol

Namespace predef::

Description

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


Constant FUSE_MAJOR_VERSION
Constant FUSE_MINOR_VERSION

constant FUSE_MAJOR_VERSION
constant FUSE_MINOR_VERSION

Description

The version of FUSE


Constant HKEY_CLASSES_ROOT
Constant HKEY_LOCAL_MACHINE
Constant HKEY_CURRENT_USER
Constant HKEY_USERS

constant int HKEY_CLASSES_ROOT
constant int HKEY_LOCAL_MACHINE
constant int HKEY_CURRENT_USER
constant int HKEY_USERS

Description

Root handles in the Windows registry.

Note

These constants are only available on Win32 systems.

See also

RegGetValue(), RegGetValues(), RegGetKeyNames()


Method ProxyFactory

program ProxyFactory(program p)

Description

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

Parameter p

Program to generate a proxy for.

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

protected void create(object(p) obj)

Initialize the object to act as a proxy for obj.

_sprintf(int c, mapping|void params)

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

void _destruct()/void destroy()

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

Note

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


Method RegGetKeyNames

array(string) RegGetKeyNames(int hkey, string key)

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 is only available on Win32 systems.

See also

RegGetValue(), RegGetValues()


Method RegGetValue

string|int|array(string) RegGetValue(int hkey, string key, string index)

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 is only available on Win32 systems.

See also

RegGetValues(), RegGetKeyNames()


Method RegGetValues

mapping(string:string|int|array(string)) RegGetValues(int hkey, string key)

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 is only available on Win32 systems.

See also

RegGetValue(), RegGetKeyNames()


Constant TOKENIZE_KEEP_ESCAPES

constant TOKENIZE_KEEP_ESCAPES

Description

Don't unquote backslash-sequences in quoted strings during tokenizing. This is used for bug-compatibility with Microsoft...

See also

tokenize(), tokenize_labled()


Constant UNDEFINED

constant UNDEFINED

Description

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


Method _Static_assert

void _Static_assert(int constant_expression, string constant_message)

Description

Perform a compile-time assertion check.

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

Note

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

See also

cpp::static_assert


Method __automap__

array __automap__(function(:void) fun, mixed ... args)

Description

Automap execution function.

Parameter fun

Function to call for each of the mapped arguments.

Parameter args

Arguments for fun. Either

Builtin.automap_marker

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

mixed

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

Note

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

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

Note

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

See also

Builtin.automap_marker, map()


Method __cast

mixed __cast(mixed val, string|type type_name)

Description

Cast val to the type indicated by type_name.

See also

lfun::cast()


Method __empty_program

program __empty_program(int|void line, string|void file)


Method __handle_sprintf_format

type __handle_sprintf_format(string attr, string|zero fmt, type arg_type, type|zero cont_type, mapping state)

Description

Type attribute handler for "sprintf_format".

Parameter attr

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

Parameter fmt

Sprintf-style formatting string to generate type information from.

Parameter arg_type

Declared type of the fmt argument (typically string).

Parameter cont_type

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

Parameter state

State mapping.

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

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

"strict_sprintf_format"

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

"sprintf_format"

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

Returns

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

See also

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


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 halt. It then waits until all threads actually have halted, 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 OSes the effective user and group apply 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()


Method call_out
Method _do_call_outs
Method find_call_out
Method remove_call_out
Method call_out_info

mixed call_out(function(:void) f, float|int delay, mixed ... args)
void _do_call_outs()
int find_call_out(function(:void) f)
int find_call_out(mixed id)
int remove_call_out(function(:void) f)
int remove_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 _equal

bool _equal(mixed o)


Method _exit

void _exit(int returncode)

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 _gdb_breakpoint

void _gdb_breakpoint()

Description

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


Method _m_delete

mixed _m_delete(mixed key)

Description

m_delete callback.


Method _random

array _random(function(:void) random_string, function(:void) random)

Description

Get a random entry.

Returns

An array ({ key, value }).


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

Description

Return the runtime type of x.

See also

typeof()


Method `!

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

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 `!=(mixed arg1, mixed arg2, 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 `%(object arg1, mixed arg2)
mixed `%(mixed arg1, object arg2)
string `%(string arg1, int arg2)
array `%(array arg1, int arg2)
float `%(float arg1, float|int arg2)
float `%(int arg1, float arg2)
int `%(int arg1, int arg2)

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 `&(mixed arg1)
mixed `&(mixed arg1, mixed arg2, mixed ... extras)
mixed `&(object arg1, mixed arg2)
mixed `&(mixed arg1, object arg2)
int `&(int arg1, int arg2)
string `&(string arg1, string arg2)
array `&(array arg1, array arg2)
mapping `&(mapping arg1, mapping arg2)
mapping `&(mapping arg1, array arg2)
mapping `&(mapping arg1, multiset arg2)
multiset `&(multiset arg1, multiset arg2)
type `&(type|program arg1, type|program arg2)

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.

Note

If this operator is used with arrays or multisets containing objects which implement lfun::`==() but not lfun::`>() and lfun::`<(), the result will be undefined.

See also

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


Method `()
Method call_function

mixed `()(function(:void) fun, mixed ... args)
mixed call_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 `*(mixed arg1)
mixed `*(object arg1, mixed arg2, mixed ... extras)
mixed `*(mixed arg1, object arg2)
array `*(array arg1, int arg2)
array `*(array arg1, float arg2)
string `*(string arg1, int arg2)
string `*(string arg1, float arg2)
string `*(array(string) arg1, string arg2)
array `*(array(array) arg1, array arg2)
float `*(float arg1, int|float arg2)
float `*(int arg1, float arg2)
int `*(int arg1, int arg2)
mixed `*(mixed arg1, mixed arg2, 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 `**

object|int|float `**(object|int|float arg1, object|int|float arg2)

Description

Exponentiation. Raise arg1 to the power of arg2.


Method `+

mixed `+(mixed arg)
mixed `+(object arg, mixed ... more)
int `+(int arg, int ... more)
float `+(float|int arg, float|int ... more)
string `+(string|float|int arg, string|float|int ... more)
array `+(array arg, array ... more)
mapping `+(mapping arg, mapping ... more)
multiset `+(multiset arg, 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 `+(mixed o)

Description

Add callback. Returns the union of two trees.


Method `-

mixed `-(mixed arg1)
mixed `-(mixed arg1, mixed arg2, mixed ... extras)
mixed `-(object arg1, mixed arg2)
mixed `-(mixed arg1, object arg2)
int `-(int arg1, int arg2)
float `-(float arg1, int|float arg2)
float `-(int|float arg1, float arg2)
string `-(string arg1, string arg2)
array `-(array arg1, array arg2)
mapping `-(mapping arg1, array arg2)
mapping `-(mapping arg1, mapping arg2)
mapping `-(mapping arg1, multiset arg2)
multiset `-(multiset arg1, multiset arg2)

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.

Note

If this operator is used with arrays or multisets containing objects which implement lfun::`==() but not lfun::`>() and lfun::`<(), the result will be undefined.

See also

`+()


Method `-

mixed `-(mixed o)

Description

Sub[s]tract two trees from each other (key-wise).


Method `->

mixed `->(object arg, string index)
mixed `->(int arg, string index)
mixed `->(array arg, string index)
mixed `->(mapping arg, string index)
bool `->(multiset arg, string index)
mixed `->(program arg, string index)

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 `->=(object arg, string index, mixed val)
mixed `->=(mapping arg, string index, mixed val)
bool `->=(multiset arg, string index, bool val)

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 `/(object arg1, mixed arg2)
mixed `/(mixed arg1, object arg2)
array(string) `/(string arg1, int arg2)
array(string) `/(string arg1, float arg2)
array(array) `/(array arg1, int arg2)
array(array) `/(array arg1, float arg2)
array(string) `/(string arg1, string arg2)
array(array) `/(array arg1, array arg2)
float `/(float arg1, int|float arg2)
float `/(int arg1, float arg2)
int `/(int arg1, int arg2)
mixed `/(mixed arg1, mixed arg2, 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 `<(mixed arg1, mixed arg2, 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 `<<(int arg1, int(0..) arg2)
mixed `<<(object arg1, int(0..)|object arg2)
mixed `<<(int arg1, object arg2)
mixed `<<(float arg1, int(0..) arg2)

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.

If arg1 is a float and arg2 is a non-negative integer, arg1 will be multiplied by 1<<arg2.

Otherwise arg1 will be shifted arg2 bits left.

See also

`>>()


Method `<=

bool `<=(mixed arg1, mixed arg2, 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 `==(mixed arg1, mixed arg2, 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 `>(mixed arg1, mixed arg2, 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 `>=(mixed arg1, mixed arg2, 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 `>>(int arg1, int(0..) arg2)
mixed `>>(object arg1, int(0..)|object arg2)
mixed `>>(int arg1, object arg2)
float `>>(float arg1, int(0..) arg2)

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.

If arg1 is a float and arg2 is a non-negative integer, arg1 will be divided by 1<<arg2.

Otherwise arg1 will be shifted arg2 bits right.

See also

`<<()


Method `[..]

mixed `[..](mixed a, int atype, mixed b, int btype)

See also

predef::`[..]


Method `[..]

mixed `[..](object arg, mixed start, int start_type, mixed end, int end_type)
string `[..](string arg, int start, int start_type, int end, int end_type)
array `[..](array arg, int start, int start_type, int end, int end_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[i..j]    <=>	`[..] (a, i, Pike.INDEX_FROM_BEG, j, Pike.INDEX_FROM_BEG)
    a[i..<j]   <=>	`[..] (a, i, Pike.INDEX_FROM_BEG, j, Pike.INDEX_FROM_END)
    a[i..]     <=>	`[..] (a, i, Pike.INDEX_FROM_BEG, 0, Pike.OPEN_BOUND)
    a[<i..j]   <=>	`[..] (a, i, Pike.INDEX_FROM_END, j, Pike.INDEX_FROM_BEG)
    a[<i..<j]  <=>	`[..] (a, i, Pike.INDEX_FROM_END, j, Pike.INDEX_FROM_END)
    a[<i..]    <=>	`[..] (a, i, Pike.INDEX_FROM_END, 0, Pike.OPEN_BOUND)
    a[..j]     <=>	`[..] (a, 0, Pike.OPEN_BOUND, j, Pike.INDEX_FROM_BEG)
    a[..<j]    <=>	`[..] (a, 0, Pike.OPEN_BOUND, j, Pike.INDEX_FROM_END)
    a[..]      <=>	`[..] (a, 0, Pike.OPEN_BOUND, 0, Pike.OPEN_BOUND)

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 `[](object arg, mixed index)
mixed `[](object arg, string index)
function(:void) `[](int arg, string index)
int `[](string arg, int index)
mixed `[](array arg, int index)
mixed `[](array arg, mixed index)
mixed `[](mapping arg, mixed index)
bool `[](multiset arg, mixed index)
mixed `[](program arg, string index)
mixed `[](object arg, mixed start, mixed end)
string `[](string arg, int start, int end)
array `[](array arg, int start, int end)

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 `[](mixed key)


Method `[]=

mixed `[]=(object arg, mixed index, mixed val)
mixed `[]=(object arg, string index, mixed val)
mixed `[]=(array arg, int index, mixed val)
mixed `[]=(mapping arg, mixed index, mixed val)
bool `[]=(multiset arg, mixed index, bool val)

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 `^(mixed arg1)
mixed `^(mixed arg1, mixed arg2, mixed ... extras)
mixed `^(object arg1, mixed arg2)
mixed `^(mixed arg1, object arg2)
int `^(int arg1, int arg2)
string `^(string arg1, string arg2)
array `^(array arg1, array arg2)
mapping `^(mapping arg1, mapping arg2)
multiset `^(multiset arg1, multiset arg2)
type `^(program|type arg1, program|type arg2)

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 `>, `< and `==). 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 `>, `< 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.

Note

If this operator is used with arrays or multisets containing objects which implement lfun::`==() but not lfun::`>() and lfun::`<(), the result will be undefined.

See also

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


Method `|

mixed `|(mixed arg1)
mixed `|(mixed arg1, mixed arg2, mixed ... extras)
mixed `|(object arg1, mixed arg2)
mixed `|(mixed arg1, object arg2)
int `|(int arg1, int arg2)
string `|(string arg1, string arg2)
array `|(array arg1, array arg2)
mapping `|(mapping arg1, mapping arg2)
multiset `|(multiset arg1, multiset arg2)
type `|(program|type arg1, program|type arg2)

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.

zero

UNDEFINED may be or:ed with multisets, behaving as if it was an empty multiset.

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 don't already occur in arg1 (according to `>, `< and `==). 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.

Note

If this operator is used with arrays or multisets containing objects which implement lfun::`==() but not lfun::`>() and lfun::`<(), the result will be undefined.

The treatment of UNDEFINED with multisets was new in Pike 8.1.

See also

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


Method `~

mixed `~(object arg)
int `~(int arg)
float `~(float arg)
type `~(type|program arg)
string `~(string arg)

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::`~()


Method abs

float abs(float f)
int abs(int f)
object abs(object f)

Description

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


Method access

int access(string path, string|void mode)

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


Method acos

float acos(int|float f)

Description

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

See also

cos(), asin()


Method acosh

float acosh(int|float f)

Description

Return the hyperbolic arcus cosine value for f.

See also

cosh(), asinh()


Method add_constant

void add_constant(string name, mixed value)
void add_constant(string name)

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


Method add_include_path

void add_include_path(string tmp)

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


Method add_module_path

void add_module_path(string path, string|void subpath)

Description

Add a directory to search for modules.

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

See also

remove_module_path()

Parameter path

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

Parameter subpath

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


Method add_program_path

void add_program_path(string tmp)

Description

Add a directory to search for programs.

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

See also

remove_program_path()


Method aggregate

array aggregate(mixed ... elements)

Description

Construct an array with the arguments as indices.

This function could be written in Pike as:

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

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

See also

sizeof(), arrayp(), allocate()


Method aggregate_mapping

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


Method aggregate_multiset

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


Method alarm

int alarm(int seconds)

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


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


Method allocate

array allocate(int size)
array allocate(int size, mixed init)

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


Method annotations

array(multiset(Pike.Annotation)) annotations(object|program|function(:void) x, bool|void recurse)

Description

Return an array with the annotations for all symbols in x.

Parameter x
object

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

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

program

Returns an array with annotations for all non-protected constant symbols.

Parameter recurse

Include annotations recursively added via inherits.

Returns

The order of the resulting array is the same as that of indices() for the same x.

Note

This function was added in Pike 8.1.

See also

indices(), values(), types(), lfun::_annotations(), ::_annotations(), Program.annotations


Method array_sscanf

array array_sscanf(string data, string format)

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


Method arrayp

int arrayp(mixed arg)

Description

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

See also

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


Method asin

float asin(int|float f)

Description

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

See also

sin(), acos()


Method asinh

float asinh(int|float f)

Description

Return the hyperbolic arcus sine value for f.

See also

sinh(), acosh()


Method atan

float atan(int|float f)

Description

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

See also

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


Method atan2

float atan2(float f1, float f2)

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


Method atanh

float atanh(int|float f)

Description

Returns the hyperbolic arcus tangent value for f.

See also

tanh(), asinh(), acosh()


Method atexit

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


Method atomic_get_set

mixed atomic_get_set(mapping|object map, mixed key, mixed val)
mixed atomic_get_set(array arr, int index, mixed val)

Description

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

Parameter map
Parameter arr

Mapping or array to alter.

Parameter key
Parameter index

Key or index to change the value for.

Parameter val

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

Returns

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

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

See also

m_delete()


Method backtrace

array(Pike.BacktraceFrame) backtrace(int|void flags)

Description

Get a description of the current call stack.

Parameter flags

A bit mask of flags affecting generation of the backtrace.

Currently a single flag is defined:

1

Return LiveBacktraceFrames. This flag causes the frame objects to track changes (as long as they are in use), and makes eg local variables for functions available for inspection or change.

Note that since these values are "live", they may change or dissapear at any time unless the corresponding thread has been halted or similar.

Returns

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

The entries are represented by Pike.BacktraceFrame objects.

The current call frame will be last in the array.

Note

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

Note

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

Note

In old versions of Pike the entries used to be represented by arrays of the following format:

Array
string file

A string with the filename if known, else zero.

int line

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 above format is still supported by eg describe_backtrace().

See also

catch(), throw()


Method basename

string basename(string path)

Description

Returns the last segment of a path.

See also

dirname(), explode_path()


Method basetype

string basetype(mixed x)

Description

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

See also

sprintf()


Method bkey

string bkey(mixed key)

Description

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


Method callablep

int callablep(mixed arg)

Description

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

See also

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


Method cast

mapping cast(string type)

Description

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


Method cd

int cd(string s)

Description

Change the current directory for the whole Pike process.

Returns

Returns 1 for success, 0 (zero) otherwise.

See also

getcwd()


Method ceil

float ceil(int|float f)

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


Method column

array column(array data, mixed index)

Description

Extract a column from a two-dimensional array.

This function is exactly equivalent to:

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

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

See also

rows()


Method combine_path
Method combine_path_unix
Method combine_path_nt
Method combine_path_amigaos

string combine_path(string path, string ... paths)
string combine_path_unix(string path, string ... paths)
string combine_path_nt(string path, string ... paths)
string combine_path_amigaos(string path, 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()


Method compile

program compile(string source, CompilationHandler|void handler, int|void major, int|void minor, program|void target, object|void placeholder)

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


Method compile

protected program compile(string source, object|void handler, int|void major, int|void minor, program|void target, object|void placeholder)


Method compile_file

program compile_file(string filename, object|void handler, void|program p, void|object o)

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


Method compile_string

program compile_string(string source, string|void filename, object|void handler, void|program p, void|object o, 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()


Method copy_value

mixed copy_value(mixed value)

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


Method cos

float cos(int|float f)

Description

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

See also

acos(), sin(), tan()


Method cosh

float cosh(int|float f)

Description

Return the hyperbolic cosine value for f.

See also

acosh(), sinh(), tanh()


Method cp

int cp(string from, string to)

Description

Copies the file from to the new position to. This is an alias for Stdio.cp.


Method cpp

string cpp(string data, mapping|string|void current_file, int|string|void charset, object|void handler, void|int compat_major, void|int compat_minor, void|int picky_cpp)

Description

Run a string through the preprocessor.

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

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

"current_file" : string

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

"charset" : int|string

Charset to use when processing data.

"handler" : object

Compilation handler.

"compat_major" : int

Sets the major pike version used for compat handling.

"compat_minor" : int

Sets the minor pike version used for compat handling.

"picky_cpp" : int

Generate more warnings.

"keep_comments" : int

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

"prefix" : string

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

"predefines" : mapping(string:mixed)

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

See also

compile()


Method cpp

protected string cpp(string data, mapping|string|void current_file, int|string|void charset, object|void handler, void|int compat_major, void|int compat_minor, void|int picky_cpp)


Method crypt

string(46..122) crypt(string(1..255) password)
bool crypt(string(1..255) input_password, string(46..122) crypted_password)
string(46..122) crypt()

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.

The third syntax generates a random string and then crypts it, creating a string useful as a password.

Note

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


Method ctime

string ctime(int timestamp)

Description

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

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

See also

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


Method decode_value

mixed decode_value(string coded_value, void|Codec|int(-1) codec)

Description

Decode a value from the string coded_value.

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

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

Note

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

See also

encode_value(), encode_value_canonic()


Method delay

void delay(int|float s)

Description

This function makes the thread stop for s seconds.

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

See also

signal(), sleep()


Method deprecated_typep

bool deprecated_typep(type t)

Description

Checks if the supplied type has the "deprecated" attribute. This would generally only be true in static types of identifiers that have been marked as __deprecated__.

Returns

1 if the type has the "deprecated" attribute, 0 otherwise.


Method depth

int(0..) depth()

Description

Calculate the depth of the tree.


Method describe_backtrace

string describe_backtrace(mixed trace, void|int linewidth)

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


Method describe_error

string describe_error(mixed err)

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


Method destruct

bool destruct(void|object o)

Description

Mark an object as destructed.

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

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

Returns

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


Method destructedp

int destructedp(mixed arg)

Description

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

See also

zero_type, undefinedp, intp


Method dirname

string dirname(string path)

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


Method encode_value

string encode_value(mixed value, Codec|void codec)

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


Method encode_value_canonic

string encode_value_canonic(mixed value, object|void codec)

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


Method enumerate

array(int) enumerate(int n)
array enumerate(int n, void|mixed step, void|mixed start, void|function(:void) operator)

Description

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

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

Advanced use

The resulting array is calculated like this:

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

map(), foreach()


Method equal

int equal(mixed a, mixed b)

Description

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

Returns

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

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

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

Otherwise depending on the type of the values:

int

Returns the same as a == b.

array

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

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

type

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

See also

copy_value(), `==()


Method errno

int errno()

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


Method error

void error(sprintf_format f, sprintf_args ... args)

Description

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


Constant is_gssapi_error
Constant error_type

constant int is_gssapi_error
constant string error_type

Description

Object recognition constants.


Constant is_gssapi_missing_services_error
Constant error_type

constant int is_gssapi_missing_services_error
constant string error_type

Description

Object recognition constants.


Method exece

int exece(string file, array(string) args)
int exece(string file, 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()


Method exit

void exit(int returncode, void|string fmt, 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()


Method exp

float exp(float|int f)

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


Method explode_path

array(string) explode_path(string p)

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


Method file_stat

Stdio.Stat file_stat(string path, void|bool symlink)

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:

array(int) file_stat(string path, void|int(0..1) symlink)
{
  File.Stat st = predef::file_stat(path, symlink);
  if (!st) return 0;
  return (array(int))st;
}
See also

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


Method file_truncate

int file_truncate(string file, int length)

Description

Truncates the file file to the length specified in length.

Returns

Returns 1 if ok, 0 if failed.


Method filesystem_stat

mapping(string:int) filesystem_stat(string path)

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. For some more uncommon filesystems this may be an integer representing the magic number for the filesystem type (cf statfs(2) on eg Linux systems).

Note

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

See also

file_stat()


Method filter

mixed filter(mixed arr, void|mixed fun, 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()


Method floatp

int floatp(mixed arg)

Description

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

See also

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


Method floor

float floor(int|float f)

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


Method fork

object fork()

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


Method function_name

string function_name(function(:void)|program f)

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


Method function_object

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


Method function_program

program function_program(function(:void)|program f)

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


Method functionp

int functionp(mixed arg)

Description

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

See also

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


Method gc

int gc(mapping|array|void quick)

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 _destruct() functions are called during freeing, which can cause more things to be freed or allocated.

See also

Pike.gc_parameters, Debug.gc_status


Method get_active_compilation_handler

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


Method get_active_compiler

CompilerEnvironment.PikeCompiler|zero get_active_compiler()

Description

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

Note

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

See also

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


Method get_active_error_handler

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


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


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


Method get_backtrace

array get_backtrace(object|array err)

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


Method get_dir

array(string) get_dir(void|string dirname)

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


Method get_groups_for_user

array(int) get_groups_for_user(int|string user)

Description

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

Parameter user

UID or loginname of the user

Returns
Array
array 0..

Information about all the users groups

See also

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


Method get_iterator

Iterator get_iterator(object|array|mapping|multiset|string data, mixed ... args)

Description

Creates and returns a canonical iterator for data.

Returns
data can have any of the following types:
object

If data is an object with lfun::_get_iterator defined then it's called in it with the arguments args to create the iterator.

If data is an object that lacks lfun::_get_iterator then it's checked if it has lfun::_iterator_next() in which case it will simply be returned. Otherwise an attempt to wrap it in a CompatIterator will be performed.

array

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

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


Method get_profiling_info

array(int|mapping(string:array(int))) get_profiling_info(program prog)

Description

Get profiling information.

Returns

Returns an array with two elements.

Array
int num_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
int num_calls

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

int total_time

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

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


Method get_weak_flag

int get_weak_flag(array|mapping|multiset m)

Description

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


Method getcwd

string getcwd()

Description

Returns the current working directory.

See also

cd()


Method getenv

mapping(string:string) getenv(void|int force_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()


Method getenv

string getenv(string varname, void|int force_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()


Method getgrgid

array(int|string|array(string)) getgrgid(int gid)

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

Group name

string 1

Group password (encrypted)

int 2

ID of the group

array 3..

Array with UIDs of group members

See also

getgrent() getgrnam()


Method getgrnam

array(int|string|array(string)) getgrnam(string str)

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

Group name

string 1

Group password (encrypted)

int 2

ID of the group

array 3..

Array with UIDs of group members

See also

getgrent() getgrgid()


Method gethrdtime

int gethrdtime(void|int nsec)

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


Method gethrtime

int gethrtime(void|int nsec)

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


Method gethrvtime

int gethrvtime(void|int nsec)

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


Method getpid

int getpid()

Description

Returns the process ID of this process.

See also

System.getppid(), System.getpgrp()


Method getpwnam

array(int|string) getpwnam(string str)

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

Users username (loginname)

string 1

User password (encrypted)

int 2

Users ID

int 3

Users primary group ID

string 4

Users real name an possibly some other info

string 5

Users home directory

string 6

Users shell

See also

getpwuid() getpwent()


Method getpwuid

array(int|string) getpwuid(int uid)

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

Users username (loginname)

string 1

User password (encrypted)

int 2

Users ID

int 3

Users primary group ID

string 4

Users real name an possibly some other info

string 5

Users home directory

string 6

Users shell

See also

getpwnam() getpwent()


Method getxattr

string getxattr(string file, string attr, void|bool symlink)

Description

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


Method glob

bool glob(string glob, string str)
string glob(array(string) glob, string str)
array(string) glob(string glob, array(string) str)
array(string) glob(array(string) glob, array(string) str)

Description

Match strings against a glob pattern.

Parameter glob
string

The glob pattern. A question sign ('?') matches any character and an asterisk ('*') matches a string of arbitrary length. All other characters only match themselves.

array(string)

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

Parameter str
string

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

array(string)

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

See also

sscanf(), Regexp


Method gmtime

mapping(string:int) gmtime(int timestamp)

Description

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

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

See also

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


Method has_index

int has_index(string haystack, int index)
int has_index(array haystack, int index)
int has_index(mapping|multiset|object|program haystack, mixed index)

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


Method has_prefix

int has_prefix(string|object s, string prefix)

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


Method has_suffix

int has_suffix(string s, string suffix)

Description

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

See also

has_prefix(), has_value(), search()


Method has_value

int has_value(string haystack, string value)
int has_value(string haystack, int value)
int has_value(array|mapping|object|program haystack, mixed value)

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


Method hash

int hash(string s)
int hash(string s, int max)

Description

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

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

Note

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

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

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

Note

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

See also

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


Method hash_7_0

int hash_7_0(string s)
int hash_7_0(string s, int max)

Description

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

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

Note

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

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

See also

hash(), hash_7_4


Method hash_7_4

int hash_7_4(string s)
int hash_7_4(string s, int max)

Description

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

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

Note

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

This function is byte-order dependant for wide strings.

See also

hash_7_6(), hash_7_0


Method hash_8_0

int hash_8_0(string s)
int hash_8_0(string s, int max)

Description

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

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

Deprecated

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

Note

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

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

Note

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

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

Note

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

See also

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


Method hash_value

int hash_value(mixed value)

Description

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

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

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

Note

This is the hashing method used by mappings.

See also

lfun::__hash()


Method indices

array indices(string|array|mapping|multiset|object x)

Description

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

Parameter x
string

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

mapping

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

object

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

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

See also

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


Method intp

int intp(mixed arg)

Description

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

See also

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


Method is_absolute_path

int is_absolute_path(string p)

Description

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

Returns

Returns 1 if the path is absolute, 0 otherwise.


Constant is_sql_null

constant int is_sql_null

Description

SQL Null marker.

Deprecated

Replaced by is_val_null.


Constant is_val_null

constant int is_val_null

Description

Nonzero recognition constant.


Method iterator_index

mixed iterator_index(object iter)

Description

Get the current index for iter.

See also

get_iterator()


Method iterator_next

bool iterator_next(object iter)

Description

Advance iter one step.

See also

get_iterator()


Method iterator_value

mixed iterator_value(object iter)

Description

Get the current value for iter.

See also

get_iterator()


Method kill

bool kill(int pid, int signal)

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


Method limit

int|float|object limit(int|float|object minval, int|float|object x, int|float|object maxval)

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


Method listxattr

array(string) listxattr(string file, void|bool symlink)

Description

Return an array of all extended attributes set on the file


Method load_module

program load_module(string module_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.


Method localtime

mapping(string:int) localtime(int timestamp)

Description

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

Returns

This function returns a mapping with the following components:

"sec" : int(0..60)

Seconds over the minute.

"min" : int(0..59)

Minutes over the hour.

"hour" : int(0..23)

Hour of the day.

"mday" : int(1..31)

Day of the month.

"mon" : int(0..11)

Month of the year.

"year" : int(0..)

Year since 1900.

"wday" : int(0..6)

Day of week (0 = Sunday).

"yday" : int(0..365)

Day of the year.

"isdst" : bool

Is daylight-saving time active.

"timezone" : int

Offset from UTC, including daylight-saving time adjustment.

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

Note

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

See also

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


Method log

float log(int|float f)

Description

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

See also

pow(), exp()


Method lower_case

string lower_case(string s)
int lower_case(int c)

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


Method m_add

void m_add(multiset|object l, mixed val)

Description

Add a member to a multiset.

See also

m_delete()


Method m_clear

void m_clear(mapping|multiset|object map)

Description

Clear the contents of a mapping or multiset.

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

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

See also

m_delete()


Method m_delete

mixed m_delete(object|mapping|multiset map, mixed index)

Description

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

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

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

Returns

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

Note

Note that m_delete() changes map destructively.

See also

mappingp()


Method map

mixed map(mixed arr, void|mixed fun, mixed ... extra)

Description

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

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

array
multiset
string

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

mapping

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

program

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

object

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

fun is applied in different ways depending on its type:

function

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

object

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

array

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

multiset
mapping

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

"zero or left out"

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

string

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

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

Note

The function is never destructive on arr.

See also

filter(), enumerate(), foreach()


Method mappingp

int mappingp(mixed arg)

Description

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

See also

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


Method master

object master()

Description

Return the current master object.

Note

May return UNDEFINED if no master has been loaded yet.

See also

replace_master()


Method max

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

Description

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

See also

min() and limit()


Method min

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

Description

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

See also

max() and limit()


Method mkdir

int mkdir(string dirname, void|int mode)

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


Method mkmapping

mapping mkmapping(array ind, array val)

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


Method mkmultiset

multiset mkmultiset(array a)

Description

This function creates a multiset from an array.

See also

aggregate_multiset()


Method mktime

int mktime(mapping(string:int) tm)
int mktime(int sec, int min, int hour, int mday, int mon, int year, int|void isdst, int|void tz)

Description

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

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

"sec" : int(0..60)

Seconds over the minute.

"min" : int(0..59)

Minutes over the hour.

"hour" : int(0..23)

Hour of the day.

"mday" : int(1..31)

Day of the month.

"mon" : int(0..11)

Month of the year.

"year" : int(0..)

Year since 1900.

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

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

"timezone" : int

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

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

Note

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

Note

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

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

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

See also

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


Method multisetp

int multisetp(mixed arg)

Description

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

See also

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


Method mv

int mv(string from, string to)

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


Method normalize_path

string normalize_path(string path)

Description

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


Method nth

mixed nth(int(0..) n)

Description

Get the nth entry in order.

Returns

An array ({ key, value }).


Method object_program

program|function(:void) object_program(mixed o)

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.


Method object_variablep

bool object_variablep(object o, string var)

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


Method objectp

int objectp(mixed arg)

Description

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

See also

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


Method pow

int|float pow(float|int n, float|int x)
mixed pow(object n, float|int|object x)

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


Method programp

int programp(mixed arg)

Description

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

See also

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


Method putenv

void putenv(string varname, void|string value)

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


Method query_num_arg

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


Method random

array random(mapping m)
float random(float max)
int random(int max)
mixed random(object o)
mixed random(array|multiset x)

Description

Get a random value generated by the default RandomSystem.

See also

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


Method random_seed

void random_seed(int seed)

Description

This function sets the initial value for the random generator.

See also

random()

Deprecated

Random.Deterministic


Method random_string

string random_string(int len)

Description

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

See also

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


Method remove_include_path

void remove_include_path(string tmp)

Description

Remove a directory to search for include files.

This function performs the reverse operation of add_include_path().

See also

add_include_path()


Method remove_module_path

void remove_module_path(string tmp)

Description

Remove a directory to search for modules.

This function performs the reverse operation of add_module_path().

See also

add_module_path()


Method remove_program_path

void remove_program_path(string tmp)

Description

Remove a directory to search for programs.

This function performs the reverse operation of add_program_path().

See also

add_program_path()


Method removexattr

void removexattr(string file, string attr, void|bool symlink)

Description

Remove the specified extended attribute.


Method replace

string replace(string s, string from, string to)
string replace(string s, array(string) from, array(string) to)
string replace(string s, array(string) from, string to)
string replace(string s, mapping(string:string) replacements)
array replace(array a, mixed from, mixed to)
mapping replace(mapping a, mixed from, mixed to)

Description

Generic replace function.

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

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

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

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

Note

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


Method replace_master

void replace_master(object o)

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


Method reverse

string reverse(string s, int|void start, int|void end)
array reverse(array a, int|void start, int|void end)
int reverse(int i, int|void start, int|void end)
mixed reverse(object o, mixed ... options)

Description

Reverses a string, array or int.

Parameter s

String to reverse.

Parameter a

Array to reverse.

Parameter i

Integer to reverse.

Parameter o

Object to reverse.

Parameter start

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

Parameter end

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

Parameter options

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

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

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

See also

sscanf()


Method rm

int rm(string f)

Description

Remove a file or directory.

Returns

Returns 0 (zero) on failure, 1 otherwise.

Note

May fail with errno() set to EISDIR or ENOTDIR if the file has changed to a directory during the call or the reverse.

See also

Stdio.File()->unlinkat(), mkdir(), Stdio.recursive_rm()


Method round

float round(int|float f)

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


Method rows

array rows(mixed data, array index)

Description

Select a set of rows from an array.

This function is en optimized equivalent to:

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

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

See also

column()


Method search

int search(string haystack, string|int needle, int|void start, int|void end)
int search(array haystack, mixed needle, int|void start, int|void end)
mixed search(mapping haystack, mixed needle, mixed|void start)
mixed search(object haystack, mixed needle, mixed|void start, mixed ... extra_args)

Description

Search for needle in haystack.

Parameter haystack

Item to search in. This can be one of:

string

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

array

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

mapping

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

object

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

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

Parameter start

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

Parameter end

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

Returns

Returns the position of needle in haystack if found.

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

string|array

-1.

mapping|Iterator

UNDEFINED.

object

The value returned by lfun::_search().

Note

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

Note

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

See also

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


Method set_priority

int set_priority(string level, int(0..)|void pid)


Method set_weak_flag

array|mapping|multiset set_weak_flag(array|mapping|multiset m, int state)

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.


Method setxattr

void setxattr(string file, string attr, string value, int flags, void|bool symlink)

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.


Method sgn

int sgn(mixed value)
int sgn(mixed value, mixed zero)

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


Method signal

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

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


Method signame

string signame(int sig)

Description

Returns a string describing the signal sig.

See also

kill(), signum(), signal()


Method signum

int signum(string sig)

Description

Get a signal number given a descriptive string.

This function is the inverse of signame().

See also

signame(), kill(), signal()


Method sin

float sin(int|float f)

Description

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

See also

asin(), cos(), tan()


Method sinh

float sinh(int|float f)

Description

Returns the hyperbolic sine value for f.

See also

asinh(), cosh(), tanh()


Method sizeof

int(0..) sizeof(string arg)
int(0..) sizeof(array arg)
int(0..) sizeof(mapping arg)
int(0..) sizeof(multiset arg)
int(0..) sizeof(object arg)

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


Method sleep

void sleep(int|float s, void|int abort_on_signal)

Description

This function makes the thread stop for s seconds.

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

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

See also

signal(), delay()


Method sort

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


Method sprintf

string sprintf(strict_sprintf_format format, sprintf_args ... args)

Description

Print formated output to string.

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

The following modifiers are supported:

'0'

Zero pad numbers (implies right justification).

'!'

Toggle truncation.

' '

Pad positive integers with a space.

'+'

Pad positive integers with a plus sign.

'-'

Left adjust within field size (default is right).

'|'

Centered within field size.

'='

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

'/'

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

'#'

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

'$'

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

'n'

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

':n'
'.n'

Precision specifier.

';n'

Column width specifier.

'*'

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

"precision" : int|void

Precision.

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

Field width.

"flag_left" : bool|void

Indicates that the output should be left-aligned.

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

Indentation level in %O-mode.

"'"

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

'~'

Get pad string from argument list.

'<'

Use same argument again.

'^'

Repeat this on every line produced.

'@'

Repeat this format for each element in the argument array.

'>'

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

'_'

Set width to the length of data.

'[n]'

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

The following operators are supported:

'%'

Percent.

'b'

Signed binary integer.

'd'

Signed decimal integer.

'u'

Unsigned decimal integer.

'o'

Signed octal integer.

'x'

Lowercase signed hexadecimal integer.

'X'

Uppercase signed hexadecimal integer.

'c'

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

'f'

Float. (Locale dependent formatting.)

'g'

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

'G'

Like %g, but uses uppercase E for exponent.

'e'

Exponential notation float. (Locale dependent output.)

'E'

Like %e, but uses uppercase E for exponent.

'F'

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

's'

String.

'q'

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

'O'

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

'p'

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

'H'

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

'n'

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

't'

Type of the argument.

'{'

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

'}'

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

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

Note

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

Note

The 'q' operator was added in Pike 7.7.

Note

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

Note

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

Example
Pike v7.8 release 263 running Hilfe v3.5 (Incremental Pike Frontend)
> sprintf("The unicode character %c has character code %04X.", 'A', 'A');
(1) Result: "The unicode character A has character code 0041."
> sprintf("#%@02X is the HTML code for purple.", Image.Color.purple->rgb());
(2) Result: "#A020F0 is the HTML code for purple."
> int n=4711;
> sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n);
(3) Result: "4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary"
> write(#"Formatting examples:
Left adjusted  [%-10d]
Centered       [%|10d]
Right adjusted [%10d]
Zero padded    [%010d]
", n, n, n, n);
Formatting examples:
Left adjusted  [4711      ]
Centered       [   4711   ]
Right adjusted [      4711]
Zero padded    [0000004711]
(5) Result: 142
int screen_width=70;
> write("%-=*s\n", screen_width,
>> "This will wordwrap the specified string within the "+
>> "specified field size, this is useful say, if you let "+
>> "users specify their screen size, then the room "+
>> "descriptions will automagically word-wrap as appropriate.\n"+
>> "slosh-n's will of course force a new-line when needed.\n");
This will wordwrap the specified string within the specified field
size, this is useful say, if you let users specify their screen size,
then the room descriptions will automagically word-wrap as
appropriate.
slosh-n's will of course force a new-line when needed.
(6) Result: 355
> write("%-=*s %-=*s\n", screen_width/2,
>> "Two columns next to each other (any number of columns will "+
>> "of course work) independantly word-wrapped, can be useful.",
>> screen_width/2-1,
>> "The - is to specify justification, this is in addherence "+
>> "to std sprintf which defaults to right-justification, "+
>> "this version also supports centre and right justification.");
Two columns next to each other (any The - is to specify justification,
number of columns will of course    this is in addherence to std
work) independantly word-wrapped,   sprintf which defaults to
can be useful.                      right-justification, this version
                                    also supports centre and right
                                    justification.
(7) Result: 426
> write("%-$*s\n", screen_width,
>> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+
>> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+
>> "be forced\nby specifying a\npresision.\nThe most obvious\n"+
>> "use is for\nformatted\nls output.");
Given a          list of          slosh-n
separated        'words',         this option
creates a        table out        of them
the number of    columns          be forced
by specifying a  presision.       The most obvious
use is for       formatted        ls output.
(8) Result: 312
> write("%-#*s\n", screen_width,
>> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+
>> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+
>> "be forced\nby specifying a\npresision.\nThe most obvious\n"+
>> "use is for\nformatted\nls output.");
Given a          creates a        by specifying a
list of          table out        presision.
slosh-n          of them          The most obvious
separated        the number of    use is for
'words',         columns          formatted
this option      be forced        ls output.
(9) Result: 312
> sample = ([ "align":"left", "valign":"middle" ]);
(10) Result: ([ /* 2 elements */
         "align":"left",
         "valign":"middle"
       ])
> write("<td%{ %s='%s'%}>\n", (array)sample);
<td valign='middle' align='left
See also

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


Constant sprintf_args

constant sprintf_args

Description

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

See also

strict_sprintf_format, sprintf_format, sprintf()


Constant sprintf_format

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


Constant sprintf_result

constant sprintf_result

Description

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

See also

strict_sprintf_format, sprintf_format, sprintf()


Method sqrt

float sqrt(float f)
int(0..) sqrt(int(0..) i)
mixed sqrt(object o)

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


Method sscanf

int sscanf(string data, string format, mixed ... lvalues)

Description

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

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

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

"%b"

Reads a binary integer ("0101" makes 5)

"%d"

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

"%o"

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

"%x"

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

"%D"

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

"%c"

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

"%n"

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

"%f"

Reads a float ("0101" makes 101.0).

"%F"

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

"%s"

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

"%H"

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

"%[set]"

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

"%{format%}"

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

"%O"

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

"%%"

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

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

"*"

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

number

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

"-"

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

"+"

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

"!"

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

Note

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

Example
// a will be assigned "oo" and 1 will be returned
sscanf("foo", "f%s", a);

// a will be 4711 and b will be "bar", 2 will be returned
sscanf("4711bar", "%d%s", a, b);

// a will be 4711, 2 will be returned
sscanf("bar4711foo", "%*s%d", a);

// a will become "test", 2 will be returned
sscanf(" \t test", "%*[ \t]%s", a);

// Remove "the " from the beginning of a string
// If 'str' does not begin with "the " it will not be changed
sscanf(str, "the %s", str);

// It is also possible to declare a variable directly in the sscanf call;
// another reason for sscanf not to be an ordinary function:

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

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

See also

sprintf, array_sscanf


Method strerror

string strerror(int errno)

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.


Method strftime

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

Description

Convert the structure to a string.

%a

The abbreviated weekday name according to the current locale

%A

The full weekday name according to the current locale.

%b

The abbreviated month name according to the current locale.

%B

The full month name according to the current locale.

%c

The preferred date and time representation for the current locale.

%C

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

%d

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

%D

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

%e

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

%E

Modifier: use alternative format, see below.

%F

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

%G

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

%g

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

%h

Equivalent to %b.

%H

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

%I

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

%j

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

%m

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

%M

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

%n

A newline character. (SU)

%O

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

%p

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

%P

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

%r

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

%R

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

%s

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

%S

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

%t

A tab character. (SU)

%T

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

%u

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

%U

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

%V

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

%w

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

See also

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


Constant strict_sprintf_format

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


Method string_filter_non_unicode

string(1..) string_filter_non_unicode(string s)

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


Method string_to_unicode

string(8bit) string_to_unicode(string s, int(0..2)|void byteorder)

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


Method string_to_utf8

utf8_string string_to_utf8(string s)
utf8_string string_to_utf8(string s, int extended)

Description

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

Parameter s

String to encode into UTF-8.

Parameter extended

Bitmask with extension options.

1

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

2

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

Note

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

See also

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


Method stringp

int stringp(mixed arg)

Description

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

See also

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


Method strptime

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

Description

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

%%

The % character.

%a or %A

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

%b or %B or %h

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

%c

The date and time representation for the C locale.

%C

The century number (0-99).

%d or %e

The day of month (1-31).

%D

Equivalent to %m/%d/%y.

%H

The hour (0-23).

%I

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

%j

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

%m

The month number (1-12).

%M

The minute (0-59).

%n

Arbitrary whitespace.

%p

The C locale's equivalent of AM or PM.

%R

Equivalent to %H:%M.

%S

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

%t

Arbitrary whitespace.

%T

Equivalent to %H:%M:%S.

%U

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

%w

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

%W

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

%x

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

%X

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

%y

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

%Y

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

See also

localtime(), gmtime(), strftime()


Method tan

float tan(int|float f)

Description

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

See also

atan(), sin(), cos()


Method tanh

float tanh(int|float f)

Description

Returns the hyperbolic tangent value for f.

See also

atanh(), sinh(), cosh()


Constant this

constant this

Description

Builtin read only variable that evaluates to the current object.

See also

this_program, this_object()


Constant this_function

constant this_function

Description

Builtin constant that evaluates to the current function.

See also

this, this_object()


Method this_object

object this_object(void|int level)

Description

Returns the object we are currently evaluating in.

Parameter level

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

Note

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


Constant this_program

constant this_program

Description

Builtin constant that evaluates to the current program.

See also

this, this_object()


Method throw

mixed|void throw(mixed value)

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


Method time

int time()
int time(int(1) one)
float time(int(2..) t)

Description

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

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

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

See also

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


Method trace

int trace(int level, void|string facility, void|int all_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.


Method typeof_identifier

type|zero typeof_identifier(program p, string identifier)

Description

Allows access to the static type of an identifier ("member") in a program.

Returns

The static type of p->identifier, or UNDEFINED if it can not be determined, be it because identifier does not exist in p or for other reasons.


Method types

array(type) types(string|array|mapping|multiset|object|program x)

Description

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

Parameter x
string

For strings this is simply an array with int

array

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

object

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


Method ualarm

int ualarm(int useconds)

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


Method undefinedp

int undefinedp(mixed arg)

Description

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

See also

zero_type, destructedp, intp


Method unicode_to_string

string unicode_to_string(string(8bit) s, int(0..2)|void byteorder)

Description

Converts an UTF16 byte-stream into a string.

Parameter s

String to convert to UTF16.

Parameter byteorder

Default input byte-order. One of:

0

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

1

Little-endian byte-order.

2

Native byte-order.

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

See also

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


Method upper_case

string upper_case(string s)
int upper_case(int c)

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


Method utf8_to_string

string utf8_to_string(utf8_string s)
string utf8_to_string(utf8_string s, int extended)

Description

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

Parameter s

String of UTF-8 encoded data to decode.

Parameter extended

Bitmask with extension options.

1

Accept and decode the extension used by string_to_utf8().

2

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

Note

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

Note

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

See also

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


Method validate_utf8

bool validate_utf8(utf8_string s)
bool validate_utf8(utf8_string s, int extended)

Description

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

Parameter s

String of UTF-8 encoded data to validate.

Parameter extended

Bitmask with extension options.

1

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

2

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

Returns

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

Note

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

See also

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


Method values

array values(string|array|mapping|multiset|object x)

Description

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

Parameter x
string

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

multiset

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

array

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

mapping

For mappings the array may contain any value.

object

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


Method version

string version()

Description

Report the version of Pike. Does the same as

sprintf("Pike v%d.%d release %d", __REAL_VERSION__,
        __REAL_MINOR__, __REAL_BUILD__);
See also

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


Method werror

int werror(string fmt, mixed ... args)

Description

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


Method write

int write(string fmt, mixed ... args)

Description

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


Typedef zero

typedef int(0) zero

Description

Zero datatype.


Method zero_type

int zero_type(mixed a)

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