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.
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.
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:
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.
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.
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.
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.
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:
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);
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.
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:
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.
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:
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.
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.
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.
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:
typeof
(mixed x)_typeof
(mixed x)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.
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.
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:
Pattern | Example | Description |
-?[1-9][0-9]* | 78 | Decimal number |
-?0[0-9]* | 0116 | Octal number |
-?0[xX][0-9a-fA-F]+ | 0x4e | Hexadecimal number |
-?0[bB][01]+ | 0b1001110 | Binary 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:
intp
(mixed x)random
(int x)reverse
(int x)sqrt
(int x)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:
Pattern | Example | Equals |
-?[0-9]*\.[0-9]+ | 3.1415926 | 3.1415926 |
-?[0-9]+e-?[0-9]+ | -5e3 | -5000.0 |
-?[0-9]*\.[0-9]+e-?[0-9]+ | .22e-2 | 0.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:
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.log
(float x)exp
(float x)pow
(float|int x, float|int y)sqrt
(float x)floor
(float x)ceil
(float x)round
(float x)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'
Pattern | Example |
. | 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 |
Sequence | ASCII code | Charcter |
\a | 7 | An acknowledge character |
\b | 8 | A backspace character |
\t | 9 | A tab character |
\n | 10 | A newline character |
\v | 11 | A vertical tab character |
\f | 12 | A form feed character |
\r | 13 | A carriage return character |
\" | 34 | A double quote character |
\\ | 92 | A 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:
Also, these functions operates on strings:
String.capitalize
(string s)String.count
(string haystack, string needle)sizeof
(haystack/needle)-1.String.width
(string s)lower_case
(string s)replace
(string s, string from, string to)reverse
(string s)search
(string haystack, string needle)sizeof
(string s)strlen
(s),
returns the length of the string.stringp
(mixed s)strlen
(string s)upper_case
(string s)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.
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:
aggregate
(mixed ... elems)allocate
(int size)arrayp
(mixed a)column
(array(mixed) a, mixed ind)equal
(mixed a, mixed b)filter
(array a, mixed func, mixed ... args)filter
for
details about that.)map
(array a, mixed func, mixed ... args)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
.)replace
(array a, mixed from, mixed to)reverse
(array a)rows
(array a, array indexes)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"}).search
(array haystack, mixed needle)sizeof
(mixed arr)sort
(array arr, array ... rest)Array.uniq
(array a)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:
indices
(mapping m)m_delete
(mapping m, mixed ind)mappingp
(mixed m)mkmapping
(array ind, array val)replace
(mapping m, mixed from, mixed to)search
(mapping m, mixed val)sizeof
(mapping m)values
(mapping m)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.zero_type
(mixed t)zero_type
will return
something else than 1.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.
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.
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.programp
(mixed p)The following operators and functions are important:
indices
(program p)values
(program p)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:
destruct
(object o)indices
(object o)object_program
(object o)objectp
(mixed o)this_object
()values
(object o)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.
function_name
(function f)function_object
(function f)functionp
(mixed f)this_function
()There are two types that are pure compile-time types:
The type void is used to indicate the absence or optionality of a value. There are two typical use cases:
UNDEFINED
.When creating functions with optional parameters the following functions may be of interest:
undefinedp
(mixed x)UNDEFINED
,
and 0 otherwise.query_num_arg
()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.
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).
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.
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:
Symbols implicitly inherited from the virtual base class.
These symbols exist mainly to simplify implementation of the corresponding lfuns.
lfun::
array
_annotations(object
|void
context
, int
|void
access
, bool
|void
recursive
)
Called by annotations()
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| See protected symbols as well. |
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.
annotations()
, lfun::_annotations()
array
(string
) _indices(object
|void
context
, int
|void
access
)
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| See protected symbols as well. |
Builtin function to list the identifiers of an object.
This is useful when lfun::_indices
has been overloaded.
::_values()
, ::_types()
, ::`->()
array
_types(object
|void
context
, int
|void
access
)
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| 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.
::_indices()
, ::_values()
, ::`->()
array
_values(object
|void
context
, int
|void
access
)
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| 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.
::_indices()
, ::_types()
, ::`->()
mixed
`->(string
index
, object
|void
context
, int
|void
access
)
Builtin arrow operator.
index
Symbol in context
to access.
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| 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.
::`->=()
mixed
`->=(string
index
, mixed
value
, object
|void
context
, int
|void
access
)
Builtin atomic arrow get and set operator.
index
Symbol in context
to change the value of.
value
The new value.
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| 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 the previous value at index index
of the current object.
::`->()
Pike 7.8 compatibility.
The symbols in this namespace will appear in programs that use #pike 7.8 or lower.
inherit 8.0:: :
The Digital Signature Algorithm (aka DSS, Digital Signature Standard).
this_program
generate_key()
Generates a public/private key pair. Needs the public parameters
p, q and g set, either through set_public_key
or
generate_parameters
.
this_program
generate_parameters(int
bits
)
Generate key parameters using nist_primes
.
Gmp.mpz
|zero
get_g()
Returns the generator.
Gmp.mpz
|zero
get_p()
Returns the modulo.
Gmp.mpz
|zero
get_q()
Returns the group order.
Gmp.mpz
|zero
get_x()
Returns the private key.
Gmp.mpz
|zero
get_y()
Returns the public key.
Gmp.mpz
hash(string
msg
)
Makes a DSA hash of the messge msg
.
string
name()
Returns the string "DSA"
.
array
(Gmp.mpz
) nist_primes(int
l
)
The (slow) NIST method of generating a DSA prime pair. Algorithm 4.56 of Handbook of Applied Cryptography.
bool
public_key_equal(.DSA
dsa
)
Compares the public key in this object with that in the provided
DSA
object.
array
(Gmp.mpz
) raw_sign(Gmp.mpz
h
, void
|Gmp.mpz
k
)
Sign the message h
. Returns the signature as two Gmp.mpz
objects.
bool
raw_verify(Gmp.mpz
h
, Gmp.mpz
r
, Gmp.mpz
s
)
Verify the signature r
,s
against the message h
.
this_program
set_private_key(Gmp.mpz
secret
)
Sets the private key in this DSA object.
this_program
set_public_key(Gmp.mpz
p_
, Gmp.mpz
q_
, Gmp.mpz
g_
, Gmp.mpz
y_
)
Sets the public key in this DSA object.
this_program
set_random(function
(int(0..)
:string
) r
)
Sets the random function, used to generate keys and parameters, to
the function r
. Default is Crypto.Random.random_string
.
string
sign_rsaref(string
msg
)
Make a RSA ref signature of message msg
.
string
sign_ssl(string
msg
)
Make an SSL signature of message msg
.
bool
verify_rsaref(string
msg
, string
s
)
Verify a RSA ref signature s
of message msg
.
bool
verify_ssl(string
msg
, string
s
)
Verify an SSL signature s
of message msg
.
string
cooked_get_d()
Returns the RSA private exponent (d) as a binary string, if known.
string
cooked_get_e()
Returns the RSA public exponent (e) as a binary string.
string
cooked_get_n()
Returns the RSA modulo (n) as a binary string.
string
cooked_get_p()
Returns the first RSA prime (p) as a binary string, if known.
string
cooked_get_q()
Returns the second RSA prime (q) as a binary string, if known.
string
cooked_sign(string
digest
)
Signs digest
as raw_sign
and returns the signature as a byte
string.
Crypto.RSA Crypto.RSA(
mapping
(string
:Gmp.mpz
|int
)|void
params
)
Can be initialized with a mapping with the elements n, e, d, p and q.
string
crypt(string
s
)
Encrypt or decrypt depending on set mode.
set_encrypt_key
, set_decrypt_key
string
decrypt(string
s
)
Decrypt a message encrypted with encrypt
.
string
encrypt(string
s
, function
(int
:string
)|void
r
)
Pads the message s
with rsa_pad
type 2, signs it and returns
the signature as a byte string.
r
Optional random function to be passed down to rsa_pad
.
this_program
generate_key(int(128..)
bits
, function
(int
:string
)|void
r
)
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.
Gmp.mpz
get_d()
Returns the RSA private exponent (d), if known.
Gmp.mpz
get_e()
Returns the RSA public exponent (e).
Gmp.mpz
get_n()
Returns the RSA modulo (n).
Gmp.mpz
get_p()
Returns the first RSA prime (p), if known.
Gmp.mpz
get_prime(int
bits
, function
(int
:string
) r
)
Generate a prime with bits
number of bits using random function
r
.
Gmp.mpz
get_q()
Returns the second RSA prime (q), if known.
string
name()
Returns the string "RSA"
.
bool
public_key_equal(this_program
rsa
)
Compares the public key of this RSA object with another RSA object.
int
query_blocksize()
Returns the crypto block size, or zero if not yet set.
Gmp.mpz
raw_sign(string
digest
)
Pads the digest
with rsa_pad
type 1 and signs it.
bool
raw_verify(string
digest
, Gmp.mpz
s
)
Verifies the digest
against the signature s
, assuming pad
type 1.
rsa_pad
, raw_sign
Gmp.mpz
rsa_pad(string
message
, int(1..2)
type
, function
(int
:string
)|void
random
)
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.
type
| The message is padded with |
| The message is padded with random data, using the |
int(0..)
rsa_size()
Returns the size of the key in terms of number of bits.
string
rsa_unpad(Gmp.mpz
block
, int
type
)
Reverse the effect of rsa_pad
.
this_program
set_decrypt_key(array
(Gmp.mpz
) key
)
Sets the public key to key
and the mod to decryption.
set_encrypt_key
, crypt
this_program
set_encrypt_key(array
(Gmp.mpz
) key
)
Sets the public key to key
and the mode to encryption.
set_decrypt_key
, crypt
this_program
set_private_key(Gmp.mpz
|int
priv
, array
(Gmp.mpz
|int
)|void
extra
)
Sets the private key.
priv
The private RSA exponent, often called d.
extra
Array | |
| The first prime, often called p. |
| The second prime, often called q. |
this_program
set_public_key(Gmp.mpz
|int
modulo
, Gmp.mpz
|int
pub
)
Sets the public key.
modulo
The RSA modulo, often called n. This value needs to be >=12.
pub
The public RSA exponent, often called e.
string
sha_sign(string
message
, mixed
|void
r
)
Document this function.
int
sha_verify(string
message
, string
signature
)
Document this function.
Gmp.mpz
sign(string
message
, Crypto.Hash
h
)
Signs the message
with a PKCS-1 signature using hash algorithm
h
.
bool
verify(string
msg
, Crypto.Hash
h
, Gmp.mpz
sign
)
Verify PKCS-1 signature sign
of message msg
using hash
algorithm h
.
function
(:void
) `()(void
|string
path
)
FIXME: Document this function
program
get_filesystem(string
what
)
FIXME: Document this function
int
parse_mode(int
old
, int
|string
mode
)
FIXME: Document this function
Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.
int
apply()
FIXME: Document this function
Base
cd(string
|void
directory
)
Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.
void
chmod(string
filename
, int
|string
mode
)
Change mode of a file or directory.
void
chown(string
filename
, int
|object
owner
, int
|object
group
)
Change ownership of the file or directory
Base
chroot(void
|string
directory
)
Change the root of the filesystem.
string
cwd()
Returns the current working directory within the filesystem.
array
find(void
|function
(Stat
:int
) mask
, mixed
... extra
)
FIXME: Document this function
array
(string
) get_dir(void
|string
directory
, void
|string
|array
glob
)
Returns an array of all files and directories within a given directory.
directory
Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.
glob
Return only files and dirs matching the glob (if given).
[get_stats]
array
(Stat
) get_stats(void
|string
directory
, void
|string
|array
glob
)
Returns stat-objects for the files and directories matching the given glob within the given directory.
[get_dir]
int
mkdir(string
directory
, void
|int
|string
mode
)
Create a new directory
Stdio.File
open(string
filename
, string
mode
)
Open a file within the filesystem
A Stdio.File object.
int
rm(string
filename
)
Remove a file from the filesystem.
Stat
stat(string
file
, int
|void
lstat
)
Return a stat-object for a file or a directory within the filesystem.
Describes the stat of a file
void
attach_statarray(array
(int
) a
)
Fills the stat-object with data from a Stdio.File.stat() call.
object
cd()
Change to the stated directory.
the directory if the stated object was a directory, 0 otherwise.
bool
isblk()
Is the file a block device?
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
ischr()
Is the file a character device?
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
isdir()
Is the file (?) a directory?
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
isdoor()
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
isfifo()
Is the file a FIFO?
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
islnk()
Is the file a link to some other file or directory?
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
isreg()
Is the file a regular file?
1 if the file is of a specific type 0 if the file is not.
[set_type]
bool
issock()
Is the file a socket?
1 if the file is of a specific type 0 if the file is not.
[set_type]
string
nice_date()
Returns the date of the stated object as cleartext.
Stdio.File
open(string
mode
)
Open the stated file within the filesystem
a [Stdio.File] object
[Stdio.File]
void
set_type(string
x
)
Set a type for the stat-object.
This call doesnot change the filetype in the underlaying filesystem.
x
Type to set. Type is one of the following:
[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]
Implements an abstraction of the normal filesystem.
Filesystem.System Filesystem.System(
void
|string
directory
, void
|string
root
, void
|int
fast
, void
|Filesystem.Base
parent
)
Instanciate a new object representing the filesystem.
directory
The directory (in the real filesystem) that should become the root of the filesystemobject.
root
Internal
fast
Internal
parent
Internal
inherit Filesystem.Base : Base
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:
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 }
Filesystem.Traversion Filesystem.Traversion(
string
path
, void
|bool
symlink
, void
|bool
ignore_errors
, void
|function
(array
:array
) sort_fun
)
path
The root path from which to traverse.
symlink
Don't traverse symlink directories.
ignore_errors
Ignore directories that can not be accessed.
sort_fun
Sort function to be applied to directory entries before traversing. Can also be a filter function.
float
progress(void
|float
share
)
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.
Stdio.Stat
stat()
Returns the stat for the current index-value-pair.
void
Filesystem.Tarcreate(string
filename
, void
|Filesystem.Base
parent
, void
|object
file
)
Filesystem which can be used to mount a Tar file.
filename
The tar file to mount.
parent
The parent filesystem. If non is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.
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.
Low-level Tar Filesystem.
void
extract(string
src_dir
, string
dest_dir
, void
|string
|function
(string
, Filesystem.Stat
:int
|string
) filter
, void
|int
flags
)
Extracts files from the tar file in sequential order.
src_dir
The root directory in the tar file system to extract.
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.
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.
flags
Bitfield of flags to control the extraction:
| Don't set any permission bits from the tar records. |
| Don't set set-user-ID, set-group-ID, or sticky bits from the tar records. |
| Don't set mtime from the tar records. |
| Set owning user and group from the tar records. |
| 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.
I/O errors are thrown.
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 Protocols.DNS : DNS
inherit predef::Protocols.DNS : DNS
Based on the current Protocols.DNS.
Pike 7.8 compatibility version of predef::Protocols.DNS.async_client
.
Protocols.DNS.async_client Protocols.DNS.async_client(
void
|string
|array
(string
) server
, void
|string
|array
(string
) domain
)
create() used to be visible.
::create()
inherit DNS::async_client : async_client
Based on the current Protocols.DNS.server.
Pike 7.8 compatibility version of predef::Protocols.DNS.client
.
Protocols.DNS.client Protocols.DNS.client(
void
|string
|array
(string
) server
, void
|int
|array
(string
) domain
)
create() used to be visible.
::create()
inherit DNS::client : client
Based on the current Protocols.DNS.client.
Pike 7.8 compatibility version of predef::Protocols.DNS.server
.
Protocols.DNS.server Protocols.DNS.server(
int
|string
|void
arg1
, string
|int
... args
)
create() used to be visible.
::create()
inherit DNS::server : server
Based on the current Protocols.DNS.server.
Alert packet.
SSL.alert SSL.alert(
int
level
, int
description
, int
version
, string
|void
message
, mixed
|void
trace
)
inherit .packet : packet
Based on the base packet
.
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.
string
|int
got_data(string
|int
s
)
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 ADT.Queue : alert
inherit ADT.Queue : application
inherit .handshake : handshake
inherit ADT.Queue : urgent
protected
object
recv_packet(string
data
)
Low-level receive handler. Returns a packet, an alert, or zero if more data is needed to get a complete packet.
void
send_close()
Initiate close.
void
send_packet(object
packet
, int
|void
priority
)
Queues a packet for write. Handshake and and change cipher must use the same priority, so must application data and close_notifies.
int
send_streaming_data(string
data
)
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.
void
set_alert_callback(function
(object
, int
|object
, string
:void
) callback
)
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.
string
|int
to_write()
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.
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.
void
advertise_protocols(string
... protos
)
Protocols to advertise during handshake using the next protocol negotiation extension. Currently only used together with spdy.
array
(string
) SSL.context.advertised_protocols
List of advertised protocols using using TLS next protocol negotiation.
int
SSL.context.auth_level
Policy for client authentication. One of SSL.Constants.AUTHLEVEL_none
,
SSL.Constants.AUTHLEVEL_ask
and SSL.Constants.AUTHLEVEL_require
.
array
(string
) SSL.context.certificates
The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.
function
(.context
, array
(int
), array
(string
):array
(string
)) SSL.context.client_certificate_selector
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.)
array
(array
(string
)) SSL.context.client_certificates
An array of certificate chains a client may present to a server when client certificate authentication is requested.
Crypto.RSA
SSL.context.client_rsa
The client's private key (used with client certificate authentication)
array
(string
) SSL.context.client_server_names
Host names to send to the server when using the Server Name extension.
int
SSL.context.client_use_sni
Should an SSL client include the Server Name extension?
If so, then client_server_names should specify the values to send.
.Cipher.DHParameters
SSL.context.dh_params
Parameters for dh keyexchange.
void
dhe_dss_mode(int
|void
min_keylength
)
Set preferred_suites
to DSS based methods.
min_keylength
Minimum acceptable key length in bits.
rsa_mode()
, filter_weak_suites()
Crypto.DSA
SSL.context.dsa
Servers default dsa key.
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
.
void
filter_weak_suites(int
min_keylength
)
Filter cipher suites from preferred_suites
that don't have
a key with an effective length of at least min_keylength
bits.
array
(string
) get_authorities()
Get the list of allowed authorities. See set_authorities
.
array
(array
(string
)) get_trusted_issuers()
Get the list of trusted issuers. See set_trusted_issuers
.
Crypto.RSA
SSL.context.long_rsa
Crypto.RSA
SSL.context.short_rsa
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.
.session
lookup_session(string
id
)
Lookup a session identifier in the cache. Returns the corresponding session, or zero if it is not found or caching is disabled.
int
SSL.context.max_sessions
Maximum number of sessions to keep in the cache.
.session
new_session()
Create a new session.
array
(int
) SSL.context.preferred_auth_methods
For client authentication. Used only if auth_level is AUTH_ask or AUTH_require.
array
(int
) SSL.context.preferred_compressors
Always ({ COMPRESSION_null })
array
(int
) SSL.context.preferred_suites
Cipher suites we want to support, in order of preference, best first.
void
purge_session(.session
s
)
Remove a session from the cache.
function
(int
:string
) SSL.context.random
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.
void
record_session(.session
s
)
Add a session to the cache (if caching is enabled).
int
SSL.context.require_trust
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.
Crypto.RSA
SSL.context.rsa
The server's default private key
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
.
void
rsa_mode(int
|void
min_keylength
)
Set preferred_suites
to RSA based methods.
min_keylength
Minimum acceptable key length in bits.
dhe_dss_mode()
, filter_weak_suites()
function
(.context
, array
(string
):array
(string
)) SSL.context.select_server_certificate_func
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
.
function
(.context
, array
(string
):object
) SSL.context.select_server_key_func
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
.
int
SSL.context.session_lifetime
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.
void
set_authorities(array
(string
) a
)
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.
void
set_trusted_issuers(array
(array
(string
)) i
)
Sets the list of trusted certificate issuers.
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.
mapping
(string
:array
(string
)) SSL.context.sni_certificates
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.
mapping
(string
:object
) SSL.context.sni_keys
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.
keys objects may be generated from a decoded key string using
Standards.PKCS.RSA.parse_private_key()
.
int
SSL.context.use_cache
Non-zero to enable cahing of sessions
int
SSL.context.verify_certificates
Determines whether certificates presented by the peer are verified, or just accepted as being valid.
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.
array
(int
) SSL.handshake.client_cert_types
array
(string
) SSL.handshake.client_cert_distinguished_names
A few storage variables for client certificate handling on the client side.
string
SSL.handshake.client_random
string
SSL.handshake.server_random
Random cookies, sent and received with the hello-messages.
SSL.handshake SSL.handshake(
int
is_server
, void
|SSL.context
ctx
, void
|ProtocolVersion
min_version
, void
|ProtocolVersion
max_version
)
is_server
Whether this is the server end of the connection or not.
ctx
The context for the connection.
min_version
Minimum version of SSL to support.
Defaults to Constants.PROTOCOL_SSL_3_0
.
max_version
Maximum version of SSL to support.
Defaults to Constants.PROTOCOL_minor
.
int(-1..1)
handle_handshake(int
type
, string
data
, string
raw
)
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.
SSL Record Layer. Handle formatting and parsing of packets.
object
|string
recv(string
data
, ProtocolVersion
version
)
Receive data read from the network.
data
Raw data from the network.
version
Minor version of the SSL 3 protocol suite to create a packet for.
Returns a string of leftover data if packet is complete,
otherwise 0
.
If there's an error, an alert object is returned.
string
send()
Serialize the packet for sending.
Returns the serialized packet.
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.
mapping
SSL.session.cert_data
information about the certificate in use by the peer, such as issuing authority, and verification status.
array
(string
) SSL.session.certificate_chain
our certificate chain
.Cipher.CipherSpec
SSL.session.cipher_spec
Information about the encryption method derived from the cipher_suite.
int
SSL.session.cipher_suite
Constant defining a choice of keyexchange, encryption and mac algorithm.
int
SSL.session.compression_algorithm
Always COMPRESSION_null.
Crypto.DSA
SSL.session.dsa
The server's dsa private key
array
(string
) generate_keys(string
client_random
, string
server_random
, array
(int
) version
)
Generates keys appropriate for the SSL version given in version
,
based on the client_random
and server_random
.
Array | |
| Client write MAC secret |
| Server write MAC secret |
| Client write key |
| Server write key |
| Client write IV |
| Server write IV |
string
SSL.session.identity
Identifies the session to the server
int
SSL.session.ke_method
Key exchange method, also derived from the cipher_suite.
string
SSL.session.master_secret
48 byte secret shared between the client and the server. Used for deriving the actual keys.
array
(.state
) new_client_states(string
client_random
, string
server_random
, array
(int
) version
)
Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.
Array | |
| Read state |
| Write state |
array
(.state
) new_server_states(string
client_random
, string
server_random
, array
(int
) version
)
Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.
Array | |
| Read state |
| Write state |
array
(string
) SSL.session.peer_certificate_chain
the peer certificate chain
Crypto.RSA
SSL.session.rsa
The server's private key
void
set_cipher_suite(int
suite
, ProtocolVersion
|int
version
)
Sets the proper authentication method and cipher specification
for the given cipher suite
and verison
.
void
set_compression_method(int
compr
)
Sets the compression method. Currently only COMPRESSION_null
is
supported.
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.
int
close(void
|string
how
, void
|int
clean_close
, void
|int
dont_throw
)
Close the connection. Both the read and write ends are always closed
how
This argument is only for Stdio.File
compatibility
and must be either "rw"
or 0
.
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.
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.
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.
I/O errors from both reading and writing might occur in blocking mode.
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.
shutdown
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
)
Create an SSL connection over an open stream
.
stream
Open socket or pipe to create the connection over.
ctx
The SSL context.
is_client
If is set then a client-side connection is started, server-side otherwise.
is_blocking
If is set then the stream is initially set in blocking mode, nonblocking mode otherwise.
min_version
The minimum minor version of SSL to support.
Defaults to PROTOCOL_SSL_3_0
.
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 errors on handshake failure in blocking client mode.
protected
void
destroy()
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.
close
int
errno()
Returns the current error number for the connection. Notable values are:
| No error |
| Connection closed by other end. |
mapping
get_peer_certificate_info()
Returns peer certificate information, if any.
array
get_peer_certificates()
Returns the peer certificate chain, if any.
int
is_open()
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.
In Pike 7.8 and earlier, this function returned zero in the case above where it now returns 2.
bool
linger(int(-1..65535)
|void
seconds
)
Set the linger time on close()
.
string
SSL.sslfile.next_protocol
The next protocol chosen by the client during next protocol negotiation.
Read only
function
(void
|object
, void
|mixed
:int
) query_accept_callback()
Returns the current accept callback.
set_accept_callback
string
query_address(int
|void
arg
)
Returns the address and port of the connection.
See Stdio.File.query_address
for details.
Stdio.File.query_address
function
(object
, int
|object
, string
:void
) query_alert_callback()
Returns the current alert callback.
set_alert_callback
Pike.Backend
query_backend()
Return the backend used for the file callbacks.
set_backend
array
(function
(mixed
, void
|string
:int
)) query_callbacks()
Returns the currently set callbacks in the same order
as the arguments to set_callbacks
.
set_callbacks
, set_nonblocking
function
(void
|mixed
:int
) query_close_callback()
Returns the current close callback.
set_close_callback
, set_nonblocking
, query_callbacks
SSL.connection
query_connection()
Return the SSL connection object.
This returns the low-level SSL.connection
object.
SSL.context
query_context()
Return the SSL context object.
mixed
query_id()
Returns the currently set id.
set_id
function
(void
|mixed
, void
|string
:int
) query_read_callback()
Returns the current read callback.
set_read_callback
, set_nonblocking
, query_callbacks
Stdio.File
query_stream()
Return the underlying stream.
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
.
shutdown
function
(void
|mixed
:int
) query_write_callback()
Returns the current write callback.
set_write_callback
, set_nonblocking
, query_callbacks
string
read(void
|int
length
, void
|bool
not_all
)
Read some (decrypted) data from the connection. Works like
Stdio.File.read
.
I/O errors from both reading and writing might occur in blocking mode.
write
int
renegotiate()
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.
The read buffer is not cleared - a read()
afterwards will
return data from both before and after the renegotiation.
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.
void
set_accept_callback(function
(void
|object
, void
|mixed
:int
) accept
)
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
).
Like the read, write and close callbacks, installing this callback implies callback mode, even after the handshake is done.
set_nonblocking
, set_callbacks
,
query_accept_callback
, query_callbacks
void
set_alert_callback(function
(object
, int
|object
, string
:void
) alert
)
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()
.
This object is part of a cyclic reference whenever this is set, just like setting any other callback.
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
.
query_alert_callback
void
set_backend(Pike.Backend
backend
)
Set the backend used for the file callbacks.
query_backend
void
set_blocking()
Set the stream in blocking mode. All but the alert callback are zapped.
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.
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.
Prior to version 7.5.12, this function didn't clear the accept callback.
set_nonblocking
, set_blocking_keep_callbacks
,
set_nonblocking_keep_callbacks
void
set_blocking_keep_callbacks()
Set blocking mode like set_blocking
, but don't alter any
callbacks.
set_blocking
, set_nonblocking
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
)
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.
read_oob
and write_oob
are currently ignored.
set_read_callback
, set_write_callback
,
set_close_callback
, set_accept_callback
, query_callbacks
void
set_close_callback(function
(void
|mixed
:int
) close
)
Install a function to be called when the connection is closed,
either normally or due to an error (use errno
to retrieve it).
query_close_callback
, set_nonblocking
, query_callbacks
void
set_id(mixed
id
)
Set the value to be sent as the first argument to the
callbacks installed by set_callbacks
.
query_id
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
)
Set the stream in nonblocking mode, installing the specified callbacks. The alert callback isn't touched.
Prior to version 7.5.12, this function didn't set the accept callback.
read_oob
and write_oob
are currently ignored.
set_callbacks
, query_callbacks
, set_nonblocking_keep_callbacks
,
set_blocking
void
set_nonblocking_keep_callbacks()
Set nonblocking mode like set_nonblocking
, but don't alter any
callbacks.
set_nonblocking
, set_blocking
, set_blocking_keep_callbacks
void
set_read_callback(function
(void
|mixed
, void
|string
:int
) read
)
Install a function to be called when data is available.
query_read_callback
, set_nonblocking
, query_callbacks
void
set_write_callback(function
(void
|mixed
:int
) write
)
Install a function to be called when data can be written.
query_write_callback
, set_nonblocking
, query_callbacks
Stdio.File
shutdown()
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
.
close
, set_alert_callback
int
write(string
|array
(string
) data
, mixed
... args
)
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.
This function returns zero if attempts are made to write data during the handshake phase and the mode is nonblocking.
I/O errors from both reading and writing might occur in blocking mode.
read
Interface similar to Stdio.Port
.
SSL.sslfile
accept()
Get the next pending SSL.sslfile
from the accept_queue
.
Returns the next pending SSL.sslfile
if any,
and 0
(zero) if there are none.
function
(object
, mixed
|void
:void
) SSL.sslport.accept_callback
int
bind(int
port
, function
(SSL.sslfile
|void
, mixed
|void
:int
) callback
, string
|void
ip
)
Bind an SSL port.
port
Port number to bind.
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.sslfile
s will be enqueued for later retrieval with
accept()
.
ip
Optional IP-number to bind.
Returns 1
if binding of the port succeeded,
and 0
(zero) on failure.
Stdio.Port()->bind()
, SSL.sslfile()->set_accept_callback()
,
listen_fd()
SSL.sslport SSL.sslport()
Create a new port for accepting SSL connections.
bind()
, listen_fd()
void
finished_callback(SSL.sslfile
f
, mixed
|void
id
)
SSL connection accept callback.
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.sslfile
s 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 ADT.Queue : accept_queue
inherit .context : context
inherit Stdio.Port : socket
int
listen_fd(int
fd
, function
(SSL.sslfile
|void
, mixed
|void
:int
) callback
)
Set up listening for SSL connections on an already opened fd.
fd
File descriptor to listen on.
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.sslfile
s will be enqueued for later retrieval with
accept()
.
Returns 1
if listening on the fd succeeded,
and 0
(zero) on failure.
Stdio.Port()->listen_fd()
, SSL.sslfile()->set_accept_callback()
,
bind()
Stdio.File
socket_accept()
Low-level accept.
Stdio.Port()->accept()
void
ssl_callback(mixed
id
)
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.
bind()
, finished_callback()
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
SSL.state.Alert
.Cipher.CipherAlgorithm
SSL.state.crypt
Encryption or decryption object.
Alert
|.packet
decrypt_packet(.packet
packet
, ProtocolVersion
version
)
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.
Alert
|.packet
encrypt_packet(.packet
packet
, ProtocolVersion
version
)
Encrypts a packet (including deflating and MAC-generation).
.Cipher.MACAlgorithm
SSL.state.mac
Message Authentication Code
Gmp.mpz
SSL.state.seq_num
64-bit sequence number.
object
SSL.state.session
Information about the used algorithms.
int
SSL.state.tls_iv
TLS IV prefix length.
Encryption and MAC algorithms used in SSL.
ADT.struct
anon_sign(object
context
, string
cookie
, ADT.struct
struct
)
The NULL signing method.
ADT.struct
dsa_sign(object
context
, string
cookie
, ADT.struct
struct
)
Signing using DSA.
array
lookup(int
suite
, ProtocolVersion
|int
version
)
Lookup the crypto parameters for a cipher suite.
suite
Cipher suite to lookup.
version
Minor version of the SSL protocol to support.
Returns 0
(zero) for unsupported combinations.
Otherwise returns an array with the following fields:
Array | |
| Key exchange method. |
| Initialized |
string
prf(string
secret
, string
label
, string
seed
, int
len
)
The Pseudo Random Function used to derive the secret keys.
ADT.struct
rsa_sign(object
context
, string
cookie
, ADT.struct
struct
)
Signing using RSA.
bool
rsa_verify(object
context
, string
cookie
, ADT.struct
struct
, Gmp.mpz
signature
)
Verify an RSA signature.
inherit Crypto.CBC : CBC
Cipher algorithm interface.
int(0..)
block_size()
Return the block size for this crypto.
this_program
set_encrypt_key(string
)
this_program
set_decrypt_key(string
)
Set the key used for encryption/decryption, and enter encryption mode.
Cipher specification.
program
SSL.Cipher.CipherSpec.bulk_cipher_algorithm
The algorithm to use for the bulk of the transfered data.
int
SSL.Cipher.CipherSpec.hash_size
The number of bytes in the MAC hashes.
int
SSL.Cipher.CipherSpec.iv_size
The number of bytes of random data needed for initialization vectors.
int
SSL.Cipher.CipherSpec.key_bits
The effective number of bits in key_material
.
This is typically key_material * 8
, but for eg DES
this is key_material * 7
.
int
SSL.Cipher.CipherSpec.key_material
The number of bytes of key material used on initialization.
program
SSL.Cipher.CipherSpec.mac_algorithm
The Message Authentication Code to use for the packets.
function
(object
, string
, ADT.struct
:ADT.struct
) SSL.Cipher.CipherSpec.sign
The function used to sign packets.
function
(object
, string
, ADT.struct
, Gmp.mpz
:bool
) SSL.Cipher.CipherSpec.verify
The function used to verify the signature for packets.
inherit Crypto.CBC : CBC
inherit Crypto.CBC : CBC
Implements Diffie-Hellman key-exchange.
The following key exchange methods are implemented here:
KE_dhe_dss
, KE_dhe_rsa
and KE_dh_anon
.
SSL.Cipher.DHKeyExchange SSL.Cipher.DHKeyExchange(
DHParameters
p
)
Diffie-Hellman parameters.
SSL.Cipher.DHParameters SSL.Cipher.DHParameters(
object
... args
)
Gmp.mpz
SSL.Cipher.DHParameters.p
Gmp.mpz
SSL.Cipher.DHParameters.g
Gmp.mpz
SSL.Cipher.DHParameters.order
inherit Crypto.CBC : CBC
Message Authentication Code interface.
string
hash(object
packet
, Gmp.mpz
seq_num
)
packet
Packet
to generate a MAC hash for.
seq_num
Sequence number for the packet in the stream.
Returns the MAC hash for the packet
.
constant
int
SSL.Cipher.MACAlgorithm.hash_header_size
The length of the header prefixed by hash()
.
string
hash_raw(string
data
)
Hashes the data with the hash algorithm and retuns it as a raw binary string.
HMAC using MD5.
This is the MAC algorithm used by TLS 1.0 and later.
SSL.Cipher.MAChmac_md5 SSL.Cipher.MAChmac_md5(
string
|void
s
)
inherit MAChmac_sha : MAChmac_sha
HMAC using SHA.
This is the MAC algorithm used by TLS 1.0 and later.
SSL.Cipher.MAChmac_sha SSL.Cipher.MAChmac_sha(
string
|void
s
)
string
hash(object
packet
, Gmp.mpz
seq_num
)
constant
int
SSL.Cipher.MAChmac_sha.hash_header_size
The length of the header prefixed by hash()
.
inherit MACAlgorithm : MACAlgorithm
MAC using MD5.
Note: This uses the algorithm from the SSL 3.0 draft.
inherit MACsha : MACsha
MAC using SHA.
Note: This uses the algorithm from the SSL 3.0 draft.
SSL.Cipher.MACsha SSL.Cipher.MACsha(
string
|void
s
)
string
hash(object
packet
, Gmp.mpz
seq_num
)
constant
int
SSL.Cipher.MACsha.hash_header_size
The length of the header prefixed by hash()
.
string
hash_master(string
data
, string
|void
s
)
inherit MACAlgorithm : MACAlgorithm
Protocol constants
constant
SSL.Constants.CIPHER_algorithms
Mapping from cipher algorithm to effective key length.
constant
int
SSL.Constants.PROTOCOL_major
constant
int
SSL.Constants.PROTOCOL_minor
Max supported SSL version.
Compression methods.
constant
SSL.Constants.COMPRESSION_deflate
Deflate compression.
constant
SSL.Constants.COMPRESSION_lzs
LZS compression.
constant
SSL.Constants.COMPRESSION_null
No compression.
Key exchange methods.
constant
SSL.Constants.KE_dh
Diffie-Hellman
constant
SSL.Constants.KE_dh_anon
Diffie-Hellman Anonymous
constant
SSL.Constants.KE_dhe_dss
Diffie-Hellman DSS
constant
SSL.Constants.KE_dhe_rsa
Diffie-Hellman RSA
constant
SSL.Constants.KE_dms
constant
SSL.Constants.KE_rsa
Rivest-Shamir-Adelman
Constants for specifying the versions of SSL to use.
SSL.sslfile()->create()
, SSL.handshake()->create()
constant
SSL.Constants.PROTOCOL_SSL_3_0
SSL 3.0 - The original SSL3 draft version.
constant
SSL.Constants.PROTOCOL_SSL_3_1
SSL 3.1 - The RFC 2246 version of SSL.
constant
SSL.Constants.PROTOCOL_SSL_3_2
SSL 3.2 - The RFC 4346 version of SSL.
constant
SSL.Constants.PROTOCOL_TLS_1_0
TLS 1.0 - The RFC 2246 version of TLS.
constant
SSL.Constants.PROTOCOL_TLS_1_1
TLS 1.1 - The RFC 4346 version of TLS.
Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)
MetaExplicit
Standards.ASN1.Types.TaggedType0
MetaExplicit
Standards.ASN1.Types.TaggedType1
MetaExplicit
Standards.ASN1.Types.TaggedType2
MetaExplicit
Standards.ASN1.Types.TaggedType3
Some common explicit tags for convenience.
These are typically used to indicate which of several optional fields are present.
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
andTaggedType1
respectively.
bool
asn1_IA5_valid(string
s
)
bool
asn1_bmp_valid(string
s
)
bool
asn1_broken_teletex_valid(string
s
)
bool
asn1_printable_valid(string
s
)
Checks if a Pike string can be encoded as a PrintableString
.
bool
asn1_teletex_valid(string
s
)
int(0)
asn1_universal_valid(string
s
)
int(1)
asn1_utf8_valid(string
s
)
Checks if a Pike string can be encoded with UTF8. That is always the case...
int(2bit)
extract_cls(int
i
)
Extract ASN1 type class from a combined tag.
make_combined_tag
int
extract_tag(int
i
)
Extract ASN1 type tag from a combined tag.
make_combined_tag
int
make_combined_tag(int
cls
, int
tag
)
Combines tag and class to a single integer, for internal uses.
cls
ASN1 type class (0..3).
tag
ASN1 type tag (1..).
The combined tag.
extract_tag
, extract_cls
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 : OctetString
Bit string object
inherit Object : Object
this_program
set_from_ascii(string(8bit)
s
)
Set the bitstring value as a string with "1"
and
"0"
.
this_program
set_length(int
len
)
Sets the length of the bit string to len
number of bits. Will
only work correctly on strings longer than len
bits.
string(8bit)
Standards.ASN1.Types.BitString.value
value of object
boolean object
inherit Object : Object
int
Standards.ASN1.Types.Boolean.value
value of object
(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 : String
Compound object primitive
array
(Object
) Standards.ASN1.Types.Compound.elements
Contents of compound object.
inherit Object : Object
Enumerated object
inherit Integer : Integer
IA5 String object
Character set: ASCII. Fixed width encoding with 1 octet per character.
inherit String : String
Object identifier object
this_program
append(int
... args
)
Returns a new Identifier
object with args
appended to the
ID path.
array
(int
) Standards.ASN1.Types.Identifier.id
value of object
inherit Object : Object
Integer object All integers are represented as bignums, for simplicity
inherit Object : Object
Gmp.mpz
Standards.ASN1.Types.Integer.value
value of object
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.
MetaExplicit m = MetaExplicit(1,2); Compound c = m(Integer(3));
Standards.ASN1.Types.MetaExplicit Standards.ASN1.Types.MetaExplicit(
int
cls
, int
tag
, mapping
(int
:program
)|void
types
)
Null object
inherit Object : Object
Generic, abstract base class for ASN1 data types.
int
get_cls()
Get the class of this object.
The class of this object.
int
get_combined_tag()
Get the combined tag (tag + class) for this object.
the combined tag header
string(8bit)
get_der()
Get the DER encoded version of this object.
DER encoded representation of this object.
string(8bit)
get_der_content()
Return the DER payload.
int
get_tag()
Get the tag for this object.
The tag for this object.
Octet string object
inherit String : String
PrintableString object
inherit String : String
Sequence object
inherit Compound : Compound
Set object
inherit Compound : Compound
string object primitive
inherit Object : Object
string
Standards.ASN1.Types.String.value
value of object
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.
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).
Charset
inherit String : String
UTCTime
int
get_posix()
inherit String : String
this_program
set_posix(int
t
)
UTF8 string object
Character set: ISO/IEC 10646-1 (compatible with Unicode).
Variable width encoding, see RFC 2279.
inherit String : String
Universal String object
Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.
The encoding is very likely UCS-4, but that's not yet verified.
inherit OctetString : OctetString
inherit String : String
string
build_digestinfo(string
msg
, Crypto.Hash
hash
)
Construct a PKCS-1 digestinfo.
msg
message to digest
hash
crypto hash object such as Crypto.SHA1
or Crypto.MD5
Crypto.RSA()->sign
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 7.9::Stdio : Stdio
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()
).
The output part of Stdio.FILE
is currently not buffered.
Stdio.FILE a;
foreach( a; index; value ) orprotected
object
_get_iterator()
Returns an iterator that will loop over the lines in this file.
line_iterator()
local
int
getchar()
This function returns one character from the input stream.
Returns the ISO-10646 (Unicode) value of the character.
Returns an int
and not a string
of length 1.
string
gets(bool
|void
not_all
)
Read one line of input with support for input conversion.
not_all
Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.
This function returns the line read if successful, and 0
if
no more lines are available.
ngets()
, read()
, line_iterator()
, set_charset()
inherit File : file
object
line_iterator(int
|void
trim
)
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.
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.
_get_iterator()
array
(string
) ngets(void
|int(1..)
n
, bool
|void
not_all
)
Get n
lines.
n
Number of lines to get, or all remaining if zero.
not_all
Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.
FILE
openat(string
filename
, string
mode
)
FILE
openat(string
filename
, string
mode
, int
mask
)
Same as Stdio.File()->openat()
, but returns a Stdio.FILE
object.
Stdio.File()->openat()
File
pipe(int
|void
flags
)
Same as Stdio.File()->pipe()
.
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.
int
printf(string
format
, mixed
... data
)
This function does approximately the same as:
.write
(sprintf
(format
,@data
))
write()
, sprintf()
string
read(int
|void
bytes
, void
|bool
now
)
Read bytes
(wide-) characters with buffering and support for
input conversion.
Stdio.File()->read()
, set_charset()
, unread()
void
set_charset(string
|void
charset
)
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".
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.
void
ungets(string
s
)
This function puts a line back in the input buffer. The line
can then be read with eg read()
, gets()
or getchar()
.
The string is autoterminated by an extra line-feed.
read()
, gets()
, getchar()
, unread()
void
unread(string
s
)
This function puts a string back in the input buffer. The string
can then be read with eg read()
, gets()
or getchar()
.
read()
, gets()
, getchar()
, ungets()
int
write(array
(string
)|string
what
, mixed
... fmt
)
Write what
with support for output_conversion.
Stdio.File()->write()
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.
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.
Stdio.FILE
int
assign(File
|Fd
o
)
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.
dup()
int
async_connect(string
host
, int
|string
port
, function
(int
, mixed
... :void
) callback
, mixed
... args
)
Open a TCP/IP connection asynchronously.
This function is similar to connect()
, but works asynchronously.
host
Hostname or IP to connect to.
port
Port number or service name to connect to.
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
.
args
Extra arguments to pass to callback
.
Returns 0
on failure, and 1
if callback
will be used.
The socket may be opened with open_socket()
ahead of
the call to this function, but it is not required.
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.
The socket will be in nonblocking state if the connection is successful, and any callbacks will be cleared.
connect()
, open_socket()
, set_nonblocking()
int
close()
int
close(string
direction
)
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.
Nonzero is returned if the file wasn't open in the specified direction, zero otherwise.
This function will not call the close_callback.
open
, open_socket
int
connect(string
host
, int
|string
port
, void
|string
client
, void
|int
|string
client_port
)
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
.
This function returns 1 for success, 0 otherwise.
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.
query_address()
, async_connect()
, connect_unix()
int
connect_unix(string
path
)
Open a UNIX domain socket connection to the specified destination.
Returns 1
on success, and 0
on failure.
Nonblocking mode is not supported while connecting
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
)
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"
.
Open mode will be filtered through the system UMASK. You
might need to use chmod()
later.
open()
, connect()
, Stdio.FILE
,
File
dup()
This function returns a clone of Stdio.File with all variables copied from this file.
All variables, even id, are copied.
assign()
int
errno()
Returns the error code for the last command on this file. Error code is normally cleared when a command is successful.
optional
inherit _Stdio.Fd_ref : Fd_ref
String.SplitIterator
|LineIterator
line_iterator(int
|void
trim
)
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.
int
open(string
filename
, string
mode
)
int
open(string
filename
, string
mode
, int
mask
)
Open a file for read, write or append. The parameter mode
should
contain one or more of the following letters:
| Open file for reading. |
| Open file for writing. |
| Open file for append (use with |
| Truncate file at open (use with |
| Create file if it doesn't exist (use with |
| Fail if file already exists (use with |
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).
This function returns 1
for success, 0
otherwise.
close()
, create()
int
open_socket(int
|string
|void
port
, string
|void
address
, int
|string
|void
family_hint
)
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()
.
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).
address
You may specify an address to bind to if your machine has many IP numbers.
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.
This function returns 1 for success, 0 otherwise.
connect()
, set_nonblocking()
, set_blocking()
File
openat(string
filename
, string
mode
)
File
openat(string
filename
, string
mode
, int
mask
)
Open a file relative to an open directory.
File.statat()
, File.unlinkat()
int
openpt(string
mode
)
Open the master end of a pseudo-terminal pair. The parameter
mode
should contain one or more of the following letters:
| Open terminal for reading. |
| Open terminal for writing. |
mode
should always contain at least one of the letters
"r"
or "w"
.
grantpt()
File
pipe(void
|int
required_properties
)
This function creates a pipe between the object it was called in and an object that is returned.
required_properties
Binary or (predef::`|()
) of required PROP_
properties.
| The resulting pipe may be used for inter process communication. |
| The resulting pipe supports nonblocking I/O. |
| The resulting pipe supports shutting down transmission in either
direction (see |
| The resulting pipe is buffered (usually 4KB). |
| The resulting pipe is bi-directional. |
| The resulting pipe might support sending of file descriptors
(see |
| The resulting pipe supports communication "backwards" (but
not necessarily "forwards", see |
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.
Calling this function with an argument of 0 is not the same as calling it with no arguments.
Process.create_process()
, send_fd()
, receive_fd()
,
PROP_IPC
, PROP_NONBLOCK
, PROP_SEND_FD
,
PROP_SHUTDOWN
, PROP_BUFFERED
, PROP_REVERSE
,
PROP_BIDIRECTIONAL
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()
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.
set_nonblocking()
, set_read_callback
,
set_write_callback
, set_read_oob_callback
,
set_write_oob_callback
, set_close_callback
,
set_callbacks
mixed
query_id()
This function returns the id that has been set with set_id()
.
set_id()
function
(:string
) read_function(int
nbytes
)
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
.
void
send_fd(File
|Fd
file
)
void
set_blocking()
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.
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.
set_nonblocking()
, set_nonblocking_keep_callbacks()
,
set_blocking_keep_callbacks()
void
set_nonblocking_keep_callbacks()
void
set_blocking_keep_callbacks()
Toggle between blocking and nonblocking, without changing the callbacks.
set_nonblocking()
, set_blocking()
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
)
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.
set_read_callback
, set_write_callback
,
set_read_oob_callback
, set_write_oob_callback
,
set_close_callback
, query_callbacks
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
)
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.
event_mask
An event mask specifing bitwise OR of one or more event types to
monitor, selected from Stdio.NOTE_WRITE
and friends.
These functions do not set the file nonblocking.
Callbacks are also set by set_callbacks
and
set_nonblocking()
.
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.
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.
Callback mode has nothing to do with nonblocking mode - although the two often are used together they don't have to be.
The file object will stay referenced from the backend object as long as there are callbacks that can receive events.
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.
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.
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
void
set_id(mixed
id
)
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.
query_id()
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()
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.
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.
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'.
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()
Handles listening to socket ports. Whenever you need a bound socket that is open and listens for connections you should use this program.
File
accept()
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.
Stdio.File
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
)
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.
bind
inherit _Stdio._port : _port
Pike 7.8 compatibility.
In 7.8 and earlier "_Stdio" was named "files".
inherit _Stdio : _Stdio
Pike 8.0 compatibility.
The symbols in this namespace will appear in programs that use #pike 8.0 or lower.
void
_assembler_debug()
Replaced by Debug.assembler_debug
.
int
_debug(int
d
)
Replaced by Debug.debug
.
void
_dump_program_tables(program
p
, int
|void
i
)
Replaced by Debug.dump_program_tables
.
int
_map_all_objects(function
(:void
) f
)
Replaced by Debug.map_all_objects
.
mixed
_next(mixed
x
)
Replaced by Debug.next
.
int
_optimizer_debug(int
d
)
Replaced by Debug.optimizer_debug
.
mixed
_prev(mixed
x
)
Replaced by Debug.prev
.
int
_refs(mixed
x
)
Replaced by Debug.refs
.
inherit predef:: :
object
next_object(object
o
)
Replaced by Debug.next_object
.
Wrapper for iterators that implements the 8.0 and earlier iterator API.
inherit ADT.Heap : Heap
int
size()
Returns the number of elements in the heap.
Replaced by lfun::_sizeof
.
mixed
top()
Removes and returns the item on top of the heap, which also is the smallest value in the heap.
Replaced by pop
.
Pike 8.0 compatibility array handling.
program
Crypto.Buffer
This class has moved to submodules of the respective ciphers.
This class has moved to submodules of the respective ciphers.
Replaced by BlockCipher.Buffer
.
Crypto.Buffer Crypto.Buffer(
Crypto.CipherState
|program
fun
, mixed
... args
)
This class has moved to submodules of the respective ciphers.
Replaced by BlockCipher.CBC
.
Crypto.CBC Crypto.CBC(
Crypto.CipherState
|program
fun
, mixed
... args
)
inherit Crypto.DH : pre
inherit pre::Parameters : Parameters
Gmp.mpz
Crypto.DH.Parameters.order
Alias for q
.
Replaced by q
.
inherit Crypto.DSA : pre
inherit pre::State : State
string(8bit)
sign_rsaref(string(8bit)
msg
)
Make a RSA ref signature of message msg
.
string(8bit)
sign_ssl(string(8bit)
msg
)
Make an SSL signature of message msg
.
bool
verify_rsaref(string(8bit)
msg
, string(8bit)
s
)
Verify a RSA ref signature s
of message msg
.
bool
verify_ssl(string(8bit)
msg
, string(8bit)
s
)
Verify an SSL signature s
of message msg
.
inherit Crypto.RSA : pre
string(8bit)
cooked_get_d()
Returns the RSA private exponent (d) as a binary string, if known.
string(8bit)
cooked_get_e()
Returns the RSA public exponent (e) as a binary string.
string(8bit)
cooked_get_n()
Returns the RSA modulo (n) as a binary string.
string(8bit)
cooked_get_p()
Returns the first RSA prime (p) as a binary string, if known.
string(8bit)
cooked_get_q()
Returns the second RSA prime (q) as a binary string, if known.
string(8bit)
cooked_sign(string(8bit)
digest
)
Signs digest
as raw_sign
and returns the signature as a byte
string.
this_program
generate_key(int(128..)
bits
, void
|int
|function
(int(0..)
:string(8bit)
) rnd
)
Compatibility with Pike 7.8.
inherit pre::State : State
Pike 8.0 compatibility mapping handling.
Pike 8.0 compatibility multiset handling.
string
http_encode_cookie(string
f
)
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.
string
http_encode_string(string
in
)
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
).
Replaced by uri_encode
.
inherit Protocols.HTTP.module : module
string
unentity(string
s
)
Helper function for replacing HTML entities with the corresponding unicode characters.
Replaced by Parser.parse_html_entities
.
inherit Protocols.HTTP.Server.SSLPort : SSLPort
void
set_certificate(string
|array
(string
) certificate
)
Replaced by add_cert
.
void
set_key(string
skey
)
Replaced by add_cert
.
array
(string(8bit)
) SSL.Context.certificates
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.
Replaced by find_cert
.
`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.
Replaced by find_cert
.
`rsa
, find_cert()
array
(array
(string(8bit)
)) SSL.Context.client_certificates
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.
Replaced by find_cert
.
`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.
Replaced by find_cert
.
`rsa
, find_cert()
Crypto.RSA.State
SSL.Context.client_rsa
Getting
The clients RSA private key.
Compatibility, don't use.
Replaced by find_cert
.
`certificates
, find_cert()
Setting
The clients RSA private key.
Compatibility, don't use.
Replaced by find_cert
.
`certificates
, find_cert()
void
dhe_dss_mode(int(0..)
|void
min_keylength
)
Set preferred_suites
to DSS based methods.
min_keylength
Minimum acceptable key length in bits.
rsa_mode()
, filter_weak_suites()
Replaced by get_suites
.
Crypto.DSA.State
SSL.Context.dsa
Getting
Compatibility.
Replaced by find_cert
.
Setting
Compatibility.
Replaced by find_cert
.
inherit SSL.Context : Context
Crypto.RSA.State
SSL.Context.rsa
Getting
The servers default private RSA key.
Compatibility, don't use.
Replaced by find_cert
.
`certificates
, find_cert()
Setting
The servers default private RSA key.
Compatibility, don't use.
Replaced by find_cert
.
`certificates
, find_cert()
void
rsa_mode(int(0..)
|void
min_keylength
)
Set preferred_suites
to RSA based methods.
min_keylength
Minimum acceptable key length in bits.
dhe_dss_mode()
, filter_weak_suites()
Replaced by get_suites
.
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.
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.
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.
Typed operation was not supported at all prior to Pike 7.8.363, and may not be supported for all databases.
int
|object
big_query(object
|string
q
, mixed
... extraargs
)
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).
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.
query
, streaming_query
int
|object
big_typed_query(object
|string
q
, mixed
... extraargs
)
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).
Typed mode is not supported by all sql databases. If not supported, an error is thrown.
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.
query
, typed_query
, big_query
, streaming_query
bool
Sql.Sql.case_convert
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).
| No (default) |
| Yes |
string
|object
compile_query(string
q
)
Compiles the query (if possible). Otherwise returns it as is. The resulting object can be used multiple times to the query functions.
q
SQL-query to compile.
query
, typed_query
, big_query
, big_typed_query
,
streaming_query
, streaming_typed_query
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
)
Create a new generic SQL object.
host
| Use this object to access the SQL-database. |
| 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 There is a special dbtype |
| Access through a UNIX-domain socket or similar. |
db
Select this database.
user
User name to access the database as.
password
Password to access the database.
options
Optional mapping of options.
See the SQL-database documentation for the supported options.
(eg Mysql.mysql()->create()
).
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.
Exactly which databases are supported by pike depends on the installed set of client libraries when pike was compiled.
The possible ones are
libmysql based mysql connection
libmysql based mysql connection, using SSL
ODBC
based connection
Msql
ODBC
based connection
Oracle
using oracle libraries
PostgreSQL direct network access. This module is independent of any external libraries.
PostgreSQL libray access. Uses the Postgres
module.
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.
In-process SQLite database, uses the SQLite
module
Uses the sybase
module to access sybase
Sybase and Microsoft SQL direct network access using the TDS protocol. This module is independent of any external libraries.
Support for options
was added in Pike 7.3.
void
create_db(string
db
)
Create a new database.
db
Name of database to create.
int
decode_date(string
d
)
Converts a database date-only spec to a system time value.
d
Date spec to decode.
int
decode_datetime(string
datetime
)
Converts a database date and time spec to a system time value.
datetime
Date and time spec to decode.
int
decode_time(string
t
, int
|void
want_utc
)
Converts a database time spec to a system time value.
t
Time spec to decode.
want_utc
Take the date part from this system time value. If zero, a seconds-since-midnight value is returned.
void
drop_db(string
db
)
Drop database
db
Name of database to drop.
string
encode_date(int
t
)
Converts a system time value to an appropriately formatted date-only spec for the database.
t
Time to encode.
string
encode_datetime(int
t
)
Converts a system time value to an appropriately formatted date and time spec for the database.
t
Time to encode.
string
encode_time(int
t
, int
|void
is_utc
)
Converts a system time value to an appropriately formatted time spec for the database.
t
Time to encode.
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.
int
|string
error()
Return last error message.
string
get_charset()
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).
set_charset
, Sql.mysql.get_charset
string
host_info()
Return info about the connection to the SQL-server.
int
is_open()
Returns true if the connection seems to be open.
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()
.
ping()
array
(string
) list_dbs(string
|void
wild
)
List available databases on this SQL-server.
wild
Optional wildcard to match against.
array
(mapping
(string
:mixed
)) list_fields(string
table
, string
|void
wild
)
List fields available in the specified table
table
Table to list the fields of.
wild
Optional wildcard to match against.
array
(string
) list_tables(string
|void
wild
)
List tables available in the current database.
wild
Optional wildcard to match against.
object
Sql.Sql.master_sql
Server specific connection object used for the actual SQL queries.
int
ping()
Check whether the connection is alive.
Returns one of the following:
| Everything ok. |
| The connection reconnected automatically. |
| The server has gone away, and the connection is dead. |
is_open()
array
(mapping
(string
:string
)) query(object
|string
q
, mixed
... extraargs
)
Sends an SQL query synchronously to the underlying SQL-server and returns the results in untyped mode.
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()
).
extraargs
This parameter, if specified, can be in two forms:
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.
Arguments as you would use in sprintf. They are automatically quoted.
res = query("select foo from bar where gazonk=%s","value");
Returns one of the following on success:
| 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. |
| The value |
Throws an exception if the query fails.
typed_query
, big_query
, streaming_query
string
quote(string
s
)
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);
void
reload()
Reload the tables.
void
select_db(string
db
)
Select database to access.
string
server_info()
Return info about the current SQL-server.
void
set_charset(string
charset
)
Changes the charset that the connection uses for queries and returned text strings.
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.
An error is thrown if the connection doesn't support the specified charset, or doesn't support charsets being set this way at all.
See the set_charset
functions for each database
connection type for further details about the effects on the
connection.
get_charset
, Sql.mysql.set_charset
void
shutdown()
Shutdown a database server.
string
sqlstate()
Return last SQLSTATE.
The SQLSTATE error codes are specified in ANSI SQL.
int
|object
streaming_query(object
|string
q
, mixed
... extraargs
)
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.
Streaming operation is not supported by all sql databases.
If not supported, this function will fall back to calling
big_query()
.
big_query
, streaming_typed_query
int
|object
streaming_typed_query(object
|string
q
, mixed
... extraargs
)
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).
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()
.
streaming_query
, big_typed_query
array
(mapping
(string
:mixed
)) typed_query(object
|string
q
, mixed
... extraargs
)
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 one of the following on success:
| 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. |
| The value |
Typed mode is not supported by all sql databases. If not supported, an error is thrown.
query
, big_typed_query
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
.
Sql.sql_result Sql.sql_result(
mixed
res
)
Create a new Sql.sql_result object
res
Result to use as base.
int
eof()
Returns non-zero if there are no more rows.
array
(mapping
(string
:mixed
)) fetch_fields()
Return information about the available fields.
string
fetch_json_result()
Fetch remaining result as JSON-encoded data.
int
|array
(string
|int
|float
) fetch_row()
Fetch the next row from the result.
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.
int
Sql.sql_result.index
This is the number of the current row. The actual semantics differs between different databases.
mixed
Sql.sql_result.master_res
The actual result.
this_program
next_result()
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 the sql_result
object if there were more results,
and 0
(zero) otherwise.
May throw the same errors as Sql.Sql()->big_query()
et al.
int
num_fields()
Returns the number of fields in the result.
int
num_rows()
Returns the number of rows in the result.
void
seek(int
skip
)
Skip past a number of rows.
skip
Number of rows to skip.
Some SQL utility functions
string
emulate_bindings(string
query
, mapping
(string
|int
:mixed
)|void
bindings
, void
|object
driver
)
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.
query
The query.
bindings
Optional mapping containing the variable bindings. Make sure that no confusion is possible in the query. If necessary, change the variables' names.
void
fallback()
Throw an error in case an unimplemented function is called.
array
(string
|mapping
(string
|int
:mixed
)) handle_extraargs(string
query
, array
(mixed
) extraargs
, void
|mapping
(string
|int
:mixed
) bindings
)
Handle sprintf
-based quoted arguments
query
The query as sent to one of the query functions.
extraargs
The arguments following the query.
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 an array with two elements:
Array | |
| The query altered to use bindings-syntax. |
| A bindings mapping. Zero if no bindings were added. |
string
quote(string
s
)
Quote a string so that it can safely be put in a query.
s
String to quote.
protected
ZeroWrapper
Sql.sql_util.zero
Instance of ZeroWrapper
used by handle_extraargs()
.
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 : UnicodeWrapper
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.
There's normally no need to use this class directly. It's used
automatically when mysql.set_unicode_decode_mode
is activated.
inherit UnicodeWrapper : UnicodeWrapper
Result object wrapper performing utf8 decoding of all fields.
Sql.sql_util.UnicodeWrapper Sql.sql_util.UnicodeWrapper(
object
master_result
)
bool
eof()
Returns 1
if there are no more rows in the result.
array
(int
|mapping
(string
:mixed
)) fetch_fields()
Returns Information about the fields in the result.
The following fields are converted from UTF8 if present:
| The name of the field. Always present. |
| The table the field is from. Not present from all databases. |
| The default value for the column. Not available from all databases. |
int
|string
fetch_json_result()
JSON is always utf8 default, do nothing.
int
|array
(string
) fetch_row()
Fetch the next row from the result.
All strings in the result are decoded from UTF8.
protected
array
(int
|mapping
(string
:mixed
)) Sql.sql_util.UnicodeWrapper.field_info
Cached fetch_fields()
result.
protected
object
Sql.sql_util.UnicodeWrapper.master_result
int
num_fields()
Returns the number of fields in the result.
int
num_rows()
Returns the number of rows in the result.
void
seek(int
rows
)
Skip ahead the specified number of rows.
Wrapper to handle zero.
zero
string sprintf(string format, ... Sql.sql_util.ZeroWrapper arg ... )
Returns the following:
| If |
| If |
Otherwise it formats a 0
(zero).
inherit Standards.ASN1.Types : pre
This used to be a string encoded with the T.61 character coding, and has been obsolete since the early 1990:s.
BrokenTeletexString
inherit BrokenTeletexString : BrokenTeletexString
Sequence
get_certificate_issuer(string
cert
)
Return the certificate issuer RDN from a certificate string.
cert
A string containing an X509 certificate.
Note that the certificate usually must be decoded using
Standards.PEM.simple_decode()
.
An Standards.ASN1.Sequence object containing the certificate issuer Distinguished Name (DN).
Replaced by Standards.X509.decode_certificate
.
Sequence
get_certificate_subject(string
cert
)
Return the certificate subject RDN from a certificate string.
cert
A string containing an X509 certificate.
Note that the certificate usually must be decoded using
PEM.simpe_decode()
.
An Standards.ASN1.Sequence object containing the certificate subject Distinguished Name (DN).
Replaced by Standards.X509.decode_certificate
.
inherit Standards.PKCS.Certificate : Certificate
RSA operations and types as described in PKCS-1.
Sequence
algorithm_identifier()
Returns the AlgorithmIdentifier as defined in RFC 5280 section 4.1.1.2.
Sequence
build_private_key(Crypto.RSA
rsa
)
Creates a PrivateKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5208 section 5.
Sequence
build_public_key(Crypto.RSA
rsa
)
Creates a SubjectPublicKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5280 section 4.1.2.7.
Crypto.RSA.State
parse_private_key(object
seq
)
Decode a RSAPrivateKey structure
key
RSAPrivateKey provided in ASN.1 format
Crypto.RSA
object
variant
Crypto.RSA.State
parse_private_key(string
key
)
Decode a DER-coded RSAPrivateKey structure
key
RSAPrivateKey provided in ASN.1 DER-encoded format
Crypto.RSA
object
Crypto.RSA.State
parse_public_key(string
key
)
Decode a DER-coded RSAPublicKey structure
key
RSAPublicKey provided in ASN.1 DER-encoded format
Crypto.RSA
object
string
private_key(Crypto.RSA
rsa
)
Create a DER-coded RSAPrivateKey structure
rsa
Crypto.RSA
object
ASN1 coded RSAPrivateKey structure
string
public_key(Crypto.RSA
rsa
)
Create a DER-coded RSAPublicKey structure
rsa
Crypto.RSA
object
ASN1 coded RSAPublicKey structure
Sequence
signature_algorithm_id(Crypto.Hash
hash
)
Returns the PKCS-1 algorithm identifier for RSA and the provided
hash algorithm. One of MD2
, MD5
, SHA1
, SHA256
,
SHA384
or SHA512
.
Pike 8.0 compatibility predef::Stdio
implementation.
inherit 8.1::Stdio : Stdio
Pike 8.0 compatibility String handling.
optional
Thread
`()(mixed
f
, mixed
... args
)
Create a new thread.
Replaced by predef::Thread.Thread
.
inherit Thread : pre
Support for parsing PEM-style messages.
Replaced by Standards.PEM
.
Represents an encapsulated message.
string
Tools.PEM.EncapsulatedMsg.body
Contains the raw message body. Access through decoded_body
to
get the decoded message.
string
Tools.PEM.EncapsulatedMsg.boundary
Contains the raw boundary string. Access through get_boundary
to get the decoded boundary string.
string
canonical_body()
Returns the raw body with all newlines as "\r\n"
.
string
decoded_body()
Returns decoded base64 encoded message body
string
get_boundary()
Returns decoded boundary string.
mapping
(string
:string
) Tools.PEM.EncapsulatedMsg.headers
Contains the message headers, or 0
.
string
to_string()
Returns the message body and headers in the standard message format.
Disassembles PGP and PEM style messages with parts separated by "-----BEGIN FOO-----" and "-----END FOO-----".
Tools.PEM.Msg Tools.PEM.Msg(
string
s
)
Creates a decoded PEM message
s
A string containing a PEM encoded message to be decoded.
string
Tools.PEM.Msg.final_text
Contains any text following the PEM message.
string
Tools.PEM.Msg.initial_text
Contains any text preceeding the PEM message.
mapping
(string
:EncapsulatedMsg
) Tools.PEM.Msg.parts
The decoded PEM message, as an array of EncapsulatedMsg
objects indexed by message name, such as "CERTIFICATE".
Represents an RFC 0934 text message.
Tools.PEM.RFC934 Tools.PEM.RFC934(
string
data
)
Decodes an RFC 0934 encoded message.
array
(EncapsulatedMsg
) Tools.PEM.RFC934.encapsulated
string
Tools.PEM.RFC934.final_boundary
string
Tools.PEM.RFC934.final_text
string
get_final_boundary()
string
Tools.PEM.RFC934.initial_text
string
to_string()
Functions to generate and validate RFC 2459 style X.509 v3 certificates.
Replaced by Standards.X509
.
constant
int
Tools.X509.CERT_BAD_SIGNATURE
constant
int
Tools.X509.CERT_CHAIN_BROKEN
constant
int
Tools.X509.CERT_INVALID
constant
int
Tools.X509.CERT_ROOT_UNTRUSTED
constant
int
Tools.X509.CERT_TOO_NEW
constant
int
Tools.X509.CERT_TOO_OLD
constant
int
Tools.X509.CERT_UNAUTHORIZED_CA
TBSCertificate
decode_certificate(string
|object
cert
)
string
dsa_sign_key(Sequence
issuer
, Crypto.DSA
dsa
, Sequence
subject
, string
public_key
, int
serial
, int
ttl
, array
|void
extensions
)
issuer
Distinguished name for the issuer.
rsa
RSA parameters for the issuer.
subject
Distinguished name for the subject.
public_key
DER-encoded integer.
See Standards.PKCS.DSA.public_key()
.
serial
Serial number for this key and issuer.
ttl
Validity time in seconds for this signature to be valid.
extensions
Set of extensions.
Returns a DER-encoded certificate.
string
make_selfsigned_dsa_certificate(Crypto.DSA
dsa
, int
ttl
, array
name
, array
|void
extensions
)
string
make_selfsigned_rsa_certificate(Crypto.RSA
rsa
, int
ttl
, array
name
, array
|void
extensions
)
Sequence
make_tbs(object
issuer
, object
algorithm
, object
subject
, object
keyinfo
, object
serial
, int
ttl
, array
extensions
)
UTC
make_time(int
t
)
Creates a Standards.ASN1.Types.UTC
object from the posix
time t
.
Verifier
make_verifier(Object
_keyinfo
)
mapping
(string
:int
) parse_time(UTC
asn1
)
Returns a mapping similar to that returned by gmtime
|
|
|
|
|
|
string
rsa_sign_digest(Crypto.RSA
rsa
, object
digest_id
, string
digest
)
string
rsa_sign_key(Sequence
issuer
, Crypto.RSA
rsa
, Sequence
subject
, string
public_key
, int
serial
, int
ttl
, array
|void
extensions
)
issuer
Distinguished name for the issuer.
rsa
RSA parameters for the issuer.
subject
Distinguished name for the issuer.
public_key
DER-encoded RSAPublicKey structure.
See Standards.PKCS.RSA.public_key()
.
serial
Serial number for this key and subject.
ttl
Validity time in seconds for this signature to be valid.
extensions
Set of extensions.
Returns a DER-encoded certificate.
bool
rsa_verify_digest(Crypto.RSA
rsa
, object
digest_id
, string
digest
, string
s
)
int(-1..1)
time_compare(mapping
(string
:int
) t1
, mapping
(string
:int
) t2
)
Comparision function between two "date" mappings of the
kind that parse_time
returns.
TBSCertificate
verify_certificate(string
s
, mapping
authorities
)
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.
This function allows self-signed certificates, and it doesn't check that names or extensions make sense.
mapping
verify_certificate_chain(array
(string
) cert_chain
, mapping
authorities
, int
|void
require_trust
)
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 describing type of verification failure, if verification failed.
May be one of the following: |
| Index number of the certificate that caused the verification failure. |
| Non-zero if the certificate is self-signed. |
| Non-zero if the certificate is verified. |
|
|
|
|
cert_chain
An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate.
authorities
A mapping from (DER-encoded) names to verifiers.
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.
Sequence
Tools.X509.TBSCertificate.algorithm
string
Tools.X509.TBSCertificate.der
object
Tools.X509.TBSCertificate.extensions
optional
this_program
init(Object
asn1
)
Sequence
Tools.X509.TBSCertificate.issuer
BitString
Tools.X509.TBSCertificate.issuer_id
optional
mapping
Tools.X509.TBSCertificate.not_after
mapping
Tools.X509.TBSCertificate.not_before
Verifier
Tools.X509.TBSCertificate.public_key
Gmp.mpz
Tools.X509.TBSCertificate.serial
Sequence
Tools.X509.TBSCertificate.subject
BitString
Tools.X509.TBSCertificate.subject_id
optional
int
Tools.X509.TBSCertificate.version
inherit Verifier : Verifier
this_program
init(string
key
)
bool
verify(Sequence
algorithm
, string
msg
, string
signature
)
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()
.
compile()
, cpp()
, CompilerEnvironment.CPP
#!
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.
#""
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.
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.
#string
#(#)
#[#]
#{#}
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 #}.
#["\n\'##]
is equivalent to"\"\\n\\'#"
.
#line
#<integer>
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.
#charset
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.
#define
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.
#elif
#elseif
These work as a combined #else
and #if
without
adding an extra level of nesting.
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
#if
, #ifdef
, #else
, defined()
, constant()
#elifdef
#elseifdef
These work as a combined #else
and #ifdef
without
adding an extra level of nesting.
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
#if
, #ifdef
, #else
, defined()
, constant()
#elifndef
#elseifndef
These work as a combined #else
and #ifndef
without
adding an extra level of nesting.
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
#if
, #ifdef
, #else
, defined()
, constant()
#else
This directive is used to divide the current code block into another code block with inverse activation.
#ifdef FAST_ALGORITHM do_fast_algorithm(); #elif defined(EXPERIMENTAL_ALGORITHM) do_experimental_algorithm(); #else do_default_algorithm(); #endif
#endif
End a block opened with #if
, #ifdef
, #ifndef
,
#else
, #elseif
or #elif
.
#ifdef DEBUG do_debug_stuff(); #endif // DEBUG
#error
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 that this directive will cause cpp()
to throw
an error at the end of preprocessing, which will cause
any compilation to fail.
#if !constant(Yp) #error Support for NIS not available. #endif
#warning
#if
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()
.
#ifdef
, #ifndef
, #elif
, #else
, #endif
,
defined()
, constant()
, efun()
#ifdef
Check whether an identifier is a macro.
The directive
#ifdef <identifier>
is equivalent to
#if defined
(<identifier>)
#if
, #ifndef
, defined
#ifndef
Check whether an identifier is not a macro.
This is the inverse of #ifdef
.
The directive
#ifndef <identifier>
is equivalent to
#if !defined
(<identifier>)
#if
, #ifdef
, defined
#include
#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.
#pike
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.
// 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.
// Pike modules that are bundled with Pike are // typically written for the same version of Pike. #pike __REAL_VERSION__
#pragma
This is a generic directive for flags to the compiler.
These are some of the flags that are available:
| This is the same as adding the modifier inline to all functions that follow. |
| Instructs the compiler to mark all symbols as final. |
| Enable warnings for use of deprecated symbols (default). |
| Disable warnings for use of deprecated symbols. This is typically used in code that implements the deprecated symbols. |
| Cause nested classes to save a reference to their surrounding class even if not strictly needed. |
| Inverse of "save_parent". This is needed to override
if the global symbol |
| Enable warnings for all cases where the compiler isn't certain that the types are correct. |
| 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 |
| Disable disassembly output (default). |
#require
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.
#if
#string
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.
do_something(#string "the_file.wks" );
#include
#undef
#undefine
This removes the effect of a #define
, all subsequent occurances of
the undefined identifier will not be replaced by anything.
Note that when undefining a macro, you just give the identifer, not the arguments.
// Strip debug #define werror(X ...) 0 #include "/home/someone/experimental/stuff.h" #undef werror
#define
, defined()
#warning
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.
#if !constant(Yp) #warning Support for NIS not available. Some features may not work. #endif
#error
void
_Pragma(string
directive
)
This macro inserts the corresponding #pragma
directive
in the source.
e.g. _Pragma("strict_types")
is the same
as #pragma strict_types
.
#pragma
constant
__AUTO_BIGNUM__
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__
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.
__REAL_MINOR__
int(1..)
__COUNTER__
This define contains a unique counter (unless it has been expanded Int.NATIVE_MAX times) represented as an integer.
constant
__DATE__
This define contains the current date at the time of compilation, e.g. "Jul 28 2001".
constant
__DIR__
This define contains the directory path of the source file.
constant
__FILE__
This define contains the file path and name of the source file.
constant
__LINE__
This define contains the current line number, represented as an integer, in the source file.
constant
__MAJOR__
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.
__REAL_MAJOR__
constant
__MINOR__
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.
__REAL_MINOR__
constant
__NT__
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__
This define is always true.
constant
__REAL_BUILD__
This define always contains the minor part of the version of the current Pike, represented as an integer.
__BUILD__
constant
__REAL_MAJOR__
This define always contains the major part of the version of the current Pike, represented as an integer.
__MAJOR__
constant
__REAL_MINOR__
This define always contains the minor part of the version of the current Pike, represented as an integer.
__MINOR__
constant
__REAL_VERSION__
This define always contains the version of the current Pike, represented as a float.
__VERSION__
constant
__TIME__
This define contains the current time at the time of compilation, e.g. "12:20:51".
constant
__VERSION__
This define contains the current Pike version as a float. If another Pike version is emulated, this define is updated accordingly.
__REAL_VERSION__
constant
__amigaos__
This define is defined when the Pike is running on Amiga OS.
bool
constant(mixed
identifier
)
__deprecated__
bool
efun(mixed
identifier
)
Check whether the argument resolves to a constant or not.
#if
, defined()
bool
defined(mixed
identifier
)
Check whether an identifier is a cpp macro or not.
defined
returns true if the symbol given as argument
is defined.
#if defined(MY_DEF) is equivalent to #ifdef MY_DEF.
#if
, #ifdef
, constant()
constant
static_assert
This define expands to the symbol _Static_assert
.
It is the preferred way to perform static (ie compile-time) assertions.
The macro can also be used to check for whether static assertions are supported.
predef::_Static_assert()
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()
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.
::
void
__INIT()
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.
This function can not be overloaded or blocked from executing.
lfun::create()
void
__create__(__unknown__
... args
)
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()
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 also that in case lfun::create()
does not exist,
it will be created as an alias for this function.
This function did not exist in Pike 8.0 and earlier (where it
was instead automatically inlined in lfun::create()
.
lfun::create()
, lfun::__INIT()
int
__hash()
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.
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.
The function predef::hash
does not return hash values that
are compatible with this one.
It's assumed that this function is side-effect free.
lfun::`==
, predef::hash_value()
array
_annotations(object
|void
context
, int
|void
access
, bool
|void
recursive
)
Called by annotations()
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| See protected symbols as well. |
recursive
Include nested annotations from the inherits.
annotations()
mixed
_atomic_get_set(mixed
index
, mixed
value
)
Get and set the value for an index atomically.
index
Index for which to get and set the value.
value
Value to set.
Returns the previous value at index index
.
lfun::`->=()
, lfun::`[]=()
, atomic_get_set()
,
lfun::_m_delete()
, lfun::`[]()
, lfun::`->()
void
_deserialize(object
o
, function
(function
(mixed
:void
), string
, type
:mixed
) deserializer
)
Dispatch function for Serialization.deserialize()
.
o
Object to serialize. Always a context of the current object.
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.
A default implementation of lfun::_serialize()
and
lfun::_deserialize()
is available in Serializer.Serializable
.
lfun::_serialize()
, Serializer.deserialize()
,
Serializer.Serializable()->_deserialize()
void
_destruct(void
|int
reason
)
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.
reason
A flag that tells why the object is destructed:
| Destructed explicitly by |
| Destructed due to running out of references. |
| Destructed by the garbage collector. |
| 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. |
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.
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
.
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.
lfun::create()
, predef::destruct()
int
_equal(mixed
arg
)
Recursive equality callback.
Is expected to return 1
if the current object is
equal to arg
, and 0
(zero) otherwise.
It's assumed that this function is side-effect free.
Note that this function may return different values at different times for the same argument due to the mutability of the object.
predef::equal()
, lfun::`==()
predef::Iterator
_get_iterator(mixed
... args
)
Iterator creation callback.
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.
It's assumed that this function is side-effect free.
predef::Iterator
, predef::get_iterator
, predef::foreach()
array
_indices(object
|void
context
, int
|void
access
)
List indices callback.
Expected to return an array with the valid indices in the object.
It's assumed that this function is side-effect free.
predef::indices()
, lfun::_values()
, lfun::_types()
,
::_indices()
bool
_is_type(string
basic_type
)
Type comparison callback.
Called by the cast operator to determine if an object simulates a basic type.
basic_type
One of:
|
|
|
|
|
|
|
|
|
|
|
|
The following five shouldn't occurr, but are here for completeness:
|
|
|
|
|
Expected to return 1
if the object is to be regarded as a
simulation of the type specified by basic_type
.
The argument is currently a string with the name of the type, but might in the future be a value of the type type.
It's assumed that this function is side-effect free.
mixed
_iterator_index()
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).
lfun::_iterator_next()
, lfun::_iterator_value()
mixed
_iterator_next()
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 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()
.
lfun::_iterator_index()
, lfun::_iterator_value()
mixed
_iterator_value()
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.
void
_m_add()
Called by m_add()
.
lfun::_m_delete()
, lfun::_m_clear()
void
_m_clear()
Called by m_clear()
.
lfun::_m_delete()
, lfun::_m_add()
mixed
_m_delete(mixed
arg
)
Delete index callback.
predef::m_delete()
mixed
_random(function
(int(0..)
:string(8bit)
) random_string
, function
(mixed
:mixed
) random
)
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.
random_string
A RandomInterface()->random_string
function that returns
a string(8bit) of the specified length.
random
A RandomInterface()->random
function.
predef::random()
, RandomInterface
mixed
_reverse(mixed
... options
)
Called by reverse()
.
mixed
_search(mixed
needle
, mixed
|void
start
, mixed
... extra_args
)
Search callback.
The arguments are sent straight from search()
, and are
as follows:
needle
Value to search for.
start
The first position to search.
extra_args
Optional extra arguments as passed to search()
.
predef::search()
void
_serialize(object
o
, function
(mixed
, string
, type
:void
) serializer
)
Dispatch function for Serializer.serialize()
.
o
Object to serialize. Always a context of the current object.
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.
A default implementation of lfun::_serialize()
and
lfun::_deserialize()
is available in Serializer.Serializable
.
lfun::_deserialize()
, Serializer.serialize()
,
Serializer.Serializable()->_serialize()
int
_size_object()
Debug.size_object()
callback.
Returns an approximation of the memory use in bytes for the object.
Debug.size_object()
, lfun::_sizeof()
int
_sizeof()
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.
Expected to return the number of valid indices in the object.
It's assumed that this function is side-effect free.
predef::sizeof()
string
_sprintf(int
conversion_type
, mapping
(string
:int
)|void
params
)
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"
.
conversion_type
One of:
| Signed binary integer. |
| Signed decimal integer. |
| Unsigned decimal integer. |
| Signed octal integer. |
| Lowercase signed hexadecimal integer. |
| Uppercase signed hexadecimal integer. |
| Character. If a fieldsize has been specified this will output the low-order bytes of the integer in network byte order. |
| Float. |
| Heuristically chosen representation of float. |
| Like %g, but uses uppercase E for exponent. |
| Exponential notation float. |
| Like %e, but uses uppercase E for exponent. |
| String. |
| Any value (debug style). |
| Type of the argument. |
params
Conversion parameters. The following parameters may be supplied:
| Precision. |
| Field width. |
| Indicates that the output should be left-aligned. |
| Indentation level in %O-mode. |
Is expected to return a string describing the object formatted
according to conversion_type
.
_sprintf()
is currently not called for the following
conversion-types:
| Binary IEEE representation of float (%4F gives single precision, %8F gives double precision.) |
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'
.
It's assumed that this function is side-effect free.
predef::sprintf()
mixed
_sqrt()
Called by sqrt()
.
sqrt()
mixed
_sqrt()
Called by sqrt when the square root of an object is requested.
_sqrt is not a real lfun, so it must not be defined as static.
predef::sqrt()
array
_types(object
|void
context
, int
|void
access
)
List types callback.
This callback is typically called via predef::types()
.
Expected to return an array with the types corresponding to
the indices returned by lfun::_indices()
.
It's assumed that this function is side-effect free.
predef::types()
was added in Pike 7.9.
predef::types()
, lfun::_indices()
, lfun::_values()
,
::_types()
array
_values(object
|void
context
, int
|void
access
)
List values callback.
Expected to return an array with the values corresponding to
the indices returned by lfun::_indices()
.
It's assumed that this function is side-effect free.
predef::values()
, lfun::_indices()
, lfun::_types()
,
::_values()
int
`!()
Logical not callback.
Returns non-zero if the object should be evaluated as false,
and 0
(zero) otherwise.
It's assumed that this function is side-effect free.
predef::`!()
mixed
`%(zero
... args
)
Left side modulo callback.
It's assumed that this function is side-effect free.
lfun::``%()
, predef::`%()
mixed
`&(zero
... args
)
Left side bitwise and/intersection callback.
It's assumed that this function is side-effect free.
lfun::``&()
, predef::`&()
mixed
`()(zero
... args
)
Apply callback.
predef::`()
mixed
`*(zero
... args
)
Left side multiplication/repetition/implosion callback.
It's assumed that this function is side-effect free.
lfun::``*()
, predef::`*()
object
|int
|float
`**(int
|float
|object
exp
)
Called by predef::`**()
.
predef::`**()
, lfun::``**()
mixed
`+(zero
arg
)
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.
It's assumed that this function is side-effect free.
In versions of Pike prior to 8.1.10 this function could get called with multiple arguments.
lfun::``+()
, lfun::`+=()
, predef::`+()
this_program
`+=(zero
arg
)
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.
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.
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.
In versions of Pike prior to 8.1.10 this function could get called with multiple arguments.
lfun::`+()
, predef::`+()
mixed
`-(void
|zero
arg
)
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
.
It's assumed that this function is side-effect free.
lfun::``-()
, predef::`-()
mixed
`->(string
index
, object
|void
context
, int
|void
access
)
Arrow index callback.
index
Symbol in context
to access.
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| See protected symbols as well. |
Returns the value at index
if it exists, and
UNDEFINED
otherwise.
It's assumed that this function is side-effect free.
predef::`->()
, ::`->()
mixed
`->=(string
index
, zero
value
, object
|void
context
, int
|void
access
)
Atomic get and set arrow index callback.
index
Symbol in context
to change the value of.
value
The new value.
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| See protected symbols as well. |
This function is to set the value at symbol index
of the current
object to value
.
Returns the previous value at symbol index
of the current object.
In Pike 8.0 and earlier the return value of this function was ignored.
predef::`->=()
, ::`->=()
, lfun::`[]=()
,
lfun::_atomic_get_set()
mixed
`/(zero
... args
)
Left side division/split callback.
It's assumed that this function is side-effect free.
lfun::``/()
, predef::`/()
bool
`<(mixed
arg
)
Less than test callback.
It's assumed that this function is side-effect free.
predef::`<()
mixed
`<<(zero
arg
)
Left side left shift callback.
It's assumed that this function is side-effect free.
lfun::``<<()
, predef::`<<()
bool
`==(mixed
arg
)
Equivalence test callback.
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.
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
.
It's assumed that this function is side-effect free.
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.
predef::`==()
, lfun::__hash
bool
`>(mixed
arg
)
Greater than test callback.
It's assumed that this function is side-effect free.
predef::`>()
mixed
`>>(zero
arg
)
Left side right shift callback.
It's assumed that this function is side-effect free.
lfun::``>>()
, predef::`>>()
mixed
`[..](zero
low
, int
low_bound_type
, zero
high
, int
high_bound_type
)
Subrange callback.
It's assumed that this function is side-effect free.
predef::`[..]
mixed
`[](zero
arg1
, zero
|void
arg2
)
Indexing callback.
For compatibility, this is also called to do subranges unless
there is a `[..]
in the class. See predef::`[..]
for
details.
It's assumed that this function is side-effect free.
predef::`[]()
, predef::`[..]
mixed
`[]=(zero
index
, zero
value
, object
|void
context
, int
|void
access
)
Atomic get and set index callback.
index
Index to change the value of.
value
The new value.
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).
access
Access permission override. One of the following:
| See only public symbols. |
| |
| See protected symbols as well. |
This function is to set the value at index index
of the current
object to value
.
Returns the previous value at index index
of the current object.
In Pike 8.0 and earlier the return value of this function was ignored.
predef::`[]=()
, lfun::`->=()
, lfun::_atomic_get_set()
mixed
`^(zero
... args
)
Left side exclusive or callback.
It's assumed that this function is side-effect free.
lfun::``^()
, predef::`^()
mixed
``%(zero
... args
)
Right side modulo callback.
It's assumed that this function is side-effect free.
lfun::`%()
, predef::`%()
mixed
``&(zero
... args
)
Right side bitwise and/intersection callback.
It's assumed that this function is side-effect free.
lfun::`&()
, predef::`&()
mixed
``*(zero
... args
)
Right side multiplication/repetition/implosion callback.
It's assumed that this function is side-effect free.
lfun::`*()
, predef::`*()
object
|int
|float
``**(int
|float
|object
base
)
Called by predef::`**()
.
predef::`**()
, lfun::`**()
mixed
``+(zero
arg
)
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.
It's assumed that this function is side-effect free.
In versions of Pike prior to 8.1.10 this function could get called with multiple arguments.
lfun::`+()
, predef::`+()
mixed
``-(zero
arg
)
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.
It's assumed that this function is side-effect free.
lfun::`-()
, predef::`-()
mixed
``/(zero
... args
)
Right side division/split callback.
It's assumed that this function is side-effect free.
lfun::`/()
, predef::`/()
mixed
``<<(zero
arg
)
Right side left shift callback.
It's assumed that this function is side-effect free.
lfun::`<<()
, predef::`<<()
mixed
``>>(zero
arg
)
Right side right shift callback.
It's assumed that this function is side-effect free.
lfun::`>>()
, predef::`>>()
mixed
``^(zero
... args
)
Right side exclusive or callback.
It's assumed that this function is side-effect free.
lfun::`^()
, predef::`^()
mixed
``|(zero
... args
)
Right side bitwise or/union callback.
It's assumed that this function is side-effect free.
lfun::`|()
, predef::`|()
mixed
`|(zero
... args
)
Left side bitwise or/union callback.
It's assumed that this function is side-effect free.
lfun::``|()
, predef::`|()
mixed
`~()
Complement/inversion callback.
It's assumed that this function is side-effect free.
predef::`~()
mixed
cast(string
requested_type
)
Value cast callback.
requested_type
Type to cast to.
Expected to return the object value-casted (converted) to
the type described by requested_type
.
The argument is currently a string with the name of the type, but might in the future be a value of the type type.
Currently casting between object types is a noop.
If the returned value is not deemed to be of the requested type a runtime error may be thrown.
It's assumed that this function is side-effect free.
void
lfun:create(__unknown__
... args
)
Object creation callback.
This function is called right after lfun::__INIT()
.
args
are the arguments passed when the program was called.
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()
.
In Pike 8.0 and earlier the code equivalent to
lfun::__create__()
was inlined at the beginning
of lfun::create()
.
If this function does not exist, but lfun::__create__()
does, it will instead be called directly.
lfun::__create__()
, lfun::__INIT()
, lfun::_destruct()
mixed
lfun::symbol
This is the default namespace and contains lots of global symbols.
constant
FUSE_MAJOR_VERSION
constant
FUSE_MINOR_VERSION
The version of FUSE
constant
int
HKEY_CLASSES_ROOT
constant
int
HKEY_LOCAL_MACHINE
constant
int
HKEY_CURRENT_USER
constant
int
HKEY_USERS
Root handles in the Windows registry.
These constants are only available on Win32 systems.
RegGetValue()
, RegGetValues()
, RegGetKeyNames()
program
ProxyFactory(program
p
)
Create a class that acts as a proxy for the specified program.
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.
The same proxy class will be returned if this function is called with the same program multiple times.
array
(string
) RegGetKeyNames(int
hkey
, string
key
)
Get a list of value key names from the register.
hkey
One of the following:
|
|
|
|
key
A registry key.
Returns an array of value keys stored at the specified location if any.
Returns UNDEFINED
on missing key
.
Throws errors on other failures.
> RegGetKeyNames(HKEY_CURRENT_USER, "Keyboard Layout"); (1) Result: ({ "IMEtoggle", "Preload", "Substitutes", "Toggle" })
This function is only available on Win32 systems.
RegGetValue()
, RegGetValues()
string
|int
|array
(string
) RegGetValue(int
hkey
, string
key
, string
index
)
Get a single value from the register.
hkey
One of the following:
|
|
|
|
key
Registry key.
index
Value name.
Returns the value stored at the specified location in the register
if any. Returns UNDEFINED
on missing keys, throws errors
on other failures.
This function is only available on Win32 systems.
RegGetValues()
, RegGetKeyNames()
mapping
(string
:string
|int
|array
(string
)) RegGetValues(int
hkey
, string
key
)
Get multiple values from the register.
hkey
One of the following:
|
|
|
|
key
Registry key.
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.
> RegGetValues(HKEY_CURRENT_USER, "Keyboard Layout\\Preload"); (5) Result: ([ "1":"0000041d" ])
This function is only available on Win32 systems.
RegGetValue()
, RegGetKeyNames()
constant
TOKENIZE_KEEP_ESCAPES
Don't unquote backslash-sequences in quoted strings during tokenizing. This is used for bug-compatibility with Microsoft...
tokenize()
, tokenize_labled()
constant
UNDEFINED
The undefined value; ie a zero for which zero_type()
returns 1.
void
_Static_assert(int
constant_expression
, string
constant_message
)
Perform a compile-time assertion check.
If constant_expression
is false, a compiler error message
containing constant_message
will be generated.
Note that the function call compiles to the null statement, and thus does not affect the run-time.
cpp::static_assert
array
__automap__(function
(:void
) fun
, mixed
... args
)
Automap execution function.
fun
Function to call for each of the mapped arguments.
args
Arguments for fun
. Either
| Wrapper for an array to loop over. All of the arrays will be looped over in parallel. |
| All other arguments will be held constant during
the automap, and sent as is to |
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.
It is an error not to have any Builtin.automap_marker
s
in args
.
Builtin.automap_marker
, map()
mixed
__cast(mixed
val
, string
|type
type_name
)
Cast val
to the type indicated by type_name
.
lfun::cast()
program
__empty_program(int
|void
line
, string
|void
file
)
type
__handle_sprintf_format(string
attr
, string
|zero
fmt
, type
arg_type
, type
|zero
cont_type
, mapping
state
)
Type attribute handler for "sprintf_format"
.
attr
Attribute to handle, either "sprintf_format"
or "strict_sprintf_format"
.
fmt
Sprintf-style formatting string to generate type information from.
arg_type
Declared type of the fmt
argument (typically string
).
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.
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
:
| The formatting string |
| The formatting string |
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.
PikeCompiler()->apply_attribute_constant()
, sprintf()
constant
__null_program
Program used internally by the compiler to create objects that are later modified into instances of the compiled program by the compiler.
__placeholder_object
string(8bit)
__parse_pike_type(string(8bit)
t
)
constant
__placeholder_object
Object used internally by the compiler.
__null_program
_disable_threads
_disable_threads()
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.
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.)
gethrdtime()
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()
These are aliases for the corresponding functions in
Pike.DefaultBackend
.
Pike.Backend()->call_out()
, Pike.Backend()->_do_call_outs()
,
Pike.Backend()->find_call_out()
, Pike.Backend()->remove_call_out()
,
Pike.Backend()->call_out_info()
bool
_equal(mixed
o
)
void
_exit(int
returncode
)
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.
exit()
void
_gdb_breakpoint()
This function only exists so that it is possible to set a gdb breakpoint on the function pike_gdb_breakpoint.
mixed
_m_delete(mixed
key
)
m_delete callback.
array
_random(function
(:void
) random_string
, function
(:void
) random
)
Get a random entry.
An array ({ key, value })
.
object
_static_modules
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.
type
_typeof(mixed
x
)
Return the runtime type of x
.
typeof()
bool
`!(object
|function
(:void
) arg
)
int(1)
`!(int(0)
arg
)
int(0)
`!(mixed
arg
)
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.
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.
No float is considered false, not even 0.0
.
`==()
, `!=()
, lfun::`!()
bool
`!=(mixed
arg1
, mixed
arg2
, mixed
... extras
)
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 1
if the test is successful, 0
otherwise.
`==()
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
)
Modulo.
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::`%()
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:
| If |
| The result will be
|
For numbers, this means that
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
).
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.
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.
/
and %
are compatible, so that
a == b*
for all floor
(a/b) + a%ba
and b
.
`/
, floor()
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
)
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)
.
If there's a single argument, that argument is returned.
If there are more than two arguments the result is:
`&(`&(
.arg1
, arg2
), @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:
| Bitwise and of |
| The result is a string where each character is the bitwise
and of the characters in the same position in |
| The result is like |
| Type intersection of |
The function is not destructive on the arguments - the result is always a new instance.
If this operator is used with arrays or multisets containing objects
which implement lfun::`==()
but not lfun::`>()
and
lfun::`<()
, the result will be undefined.
`|()
, lfun::`&()
, lfun::``&()
mixed
`()(function
(:void
) fun
, mixed
... args
)
mixed
call_function(function
(:void
) fun
, mixed
... args
)
Call a function.
Calls the function fun
with the arguments specified by args
.
lfun::`()()
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
)
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)
.
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
`*(`*(
.arg1
, arg2
), @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:
| arg2 can have any of the following types:
| ||||
| The result will be | ||||
| The result will be |
In Pike 7.0 and earlier the multiplication order was unspecified.
`+()
, `-()
, `/()
, lfun::`*()
, lfun::``*()
object
|int
|float
`**(object
|int
|float
arg1
, object
|int
|float
arg2
)
Exponentiation. Raise arg1 to the power of arg2.
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
)
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)
.
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:
| The result is the sum of all the arguments. It's a float if any argument is a float. |
| If any argument is a string, all will be converted to strings and concatenated in order to form the result. |
| The array arguments are concatened in order to form the result. |
| The result is like |
| The result is like |
The function is not destructive on the arguments - the result is always a new instance.
In Pike 7.0 and earlier the addition order was unspecified.
The treatment of UNDEFINED
was new
in Pike 7.0.
`-()
, lfun::`+()
, lfun::``+()
mixed
`+(mixed
o
)
Add callback. Returns the union of two trees.
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
)
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)
.
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:
`-(`-(
.arg1
, arg2
), @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:
| The result is |
| The result is |
| The result is like |
The function is not destructive on the arguments - the result is always a new instance.
In Pike 7.0 and earlier the subtraction order was unspecified.
If this operator is used with arrays or multisets containing objects
which implement lfun::`==()
but not lfun::`>()
and
lfun::`<()
, the result will be undefined.
`+()
mixed
`-(mixed
o
)
Sub[s]tract two trees from each other (key-wise).
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
)
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.
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:
| The non-protected (ie public) symbol named |
| The bignum function named |
| An array of all elements in |
| If |
| If |
| The non-protected (ie public) constant symbol |
In an expression a->b
, the symbol b
can be any
token that matches the identifier syntax - keywords are
disregarded in that context.
An arrow indexing expression in an lvalue context, i.e. where
the index is being assigned a new value, uses `->=
instead of
this function.
`[]()
, lfun::`->()
, ::`->()
, `->=
mixed
`->=(object
arg
, string
index
, mixed
val
)
mixed
`->=(mapping
arg
, string
index
, mixed
val
)
bool
`->=(multiset
arg
, string
index
, bool
val
)
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:
| The non-protected (ie public) variable named |
| Index |
| If |
val
will be returned.
In an expression a->b=c
, the symbol b
can be any
token that matches the identifier syntax - keywords are
disregarded in that context.
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.
`[]=()
, lfun::`->=()
, `->
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
)
Division/split.
Every expression with the /
operator becomes a call to
this function, i.e. a/b
is the same as
predef::`/(a,b)
.
If there are more than two arguments, the result will be
`/(`/(
.arg1
, arg2
), @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:
| arg2 can have any of the following types:
| ||||
| arg2 can have any of the following types:
| ||||
| The result will be |
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.
`%
bool
`<(mixed
arg1
, mixed
arg2
, mixed
... extras
)
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 1
if the test is successful, 0
otherwise.
`<=()
, `>()
, `>=()
int
`<<(int
arg1
, int(0..)
arg2
)
mixed
`<<(object
arg1
, int(0..)
|object
arg2
)
mixed
`<<(int
arg1
, object
arg2
)
mixed
`<<(float
arg1
, int(0..)
arg2
)
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.
`>>()
bool
`<=(mixed
arg1
, mixed
arg2
, mixed
... extras
)
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 1
if the test is successful, 0
otherwise.
For total orders, e.g. integers, this is the inverse of `>()
.
`<()
, `>()
, `>=()
bool
`==(mixed
arg1
, mixed
arg2
, mixed
... extras
)
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:
| Successful iff the two integers are numerically equal. |
| Successful iff the two floats are numerically equal and not NaN. |
| 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.) |
| Successful iff the two arguments point to the same instance. |
Returns 1
if the test is successful, 0
otherwise.
Floats and integers are not automatically converted to test
against each other, so e.g. 0==0.0
is false.
Programs are not automatically converted to types to be compared type-wise.
`!()
, `!=()
bool
`>(mixed
arg1
, mixed
arg2
, mixed
... extras
)
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 1
if the arguments are strictly decreasing, and
0
(zero) otherwise.
`<()
, `<=()
, `>=()
bool
`>=(mixed
arg1
, mixed
arg2
, mixed
... extras
)
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 1
if the test is successful, 0
otherwise.
For total orders, e.g. integers, this is the inverse of `<()
.
`<=()
, `>()
, `<()
int
`>>(int
arg1
, int(0..)
arg2
)
mixed
`>>(object
arg1
, int(0..)
|object
arg2
)
mixed
`>>(int
arg1
, object
arg2
)
float
`>>(float
arg1
, int(0..)
arg2
)
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.
`<<()
mixed
`[..](mixed
a
, int
atype
, mixed
b
, int
btype
)
predef::`[..]
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
)
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).
The returned value depends on the type of arg
:
arg
can have any of the following types:
| A string with the characters in the range is returned. |
| An array with the elements in the range is returned. |
| If the object implements As a compatibility measure, if the object does not implement
Note that |
lfun::`[..]
, `[]
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
)
Indexing.
This is the function form of expressions with the []
operator, i.e. a[i]
is the same as
predef::`[](a,i)
.
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:
| The non-protected (i.e. public) symbol named |
| The bignum function named |
| The character at index |
| If If |
| If |
| If |
| The non-protected (i.e. public) constant symbol |
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.
An indexing expression in an lvalue context, i.e. where the
index is being assigned a new value, uses `[]=
instead of
this function.
`->()
, lfun::`[]()
, `[]=
, `[..]
mixed
`[](mixed
key
)
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
)
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:
| The non-protected (ie public) variable named |
| Index |
| If |
val
will be returned.
An indexing expression in a non-lvalue context, i.e. where the
index is being queried instead of assigned, uses `[]
instead
of this function.
`->=()
, lfun::`[]=()
, `[]
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
)
Exclusive or.
Every expression with the ^
operator becomes a call to
this function, i.e. a^b
is the same as
predef::`^(a,b)
.
If there's a single argument, that argument is returned.
If there are more than two arguments, the result is:
`^(`^(
.arg1
, arg2
), @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:
| Bitwise exclusive or of |
| The result is a string where each character is the bitwise
exclusive or of the characters in the same position in
|
| The result is an array with the elements in 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. |
| The result is like |
| The result is like |
| The result is a type computed like this:
|
The function is not destructive on the arguments - the result is always a new instance.
If this operator is used with arrays or multisets containing objects
which implement lfun::`==()
but not lfun::`>()
and
lfun::`<()
, the result will be undefined.
`&()
, `|()
, lfun::`^()
, lfun::``^()
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
)
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)
.
If there's a single argument, that argument is returned.
If there are more than two arguments, the result is:
`|(`|(
.arg1
, arg2
), @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:
| Bitwise or of |
|
|
| The result is a string where each character is the bitwise
or of the characters in the same position in |
| The result is an array with the elements in Every element in |
| The result is like |
| The result is like |
| Type union of |
The function is not destructive on the arguments - the result is always a new instance.
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.
`&()
, lfun::`|()
, lfun::``|()
mixed
`~(object
arg
)
int
`~(int
arg
)
float
`~(float
arg
)
type
`~(type
|program
arg
)
string
`~(string
arg
)
Complement/inversion.
Every expression with the ~
operator becomes a call to
this function, i.e. ~a
is the same as
predef::`~(a)
.
The result will be as follows:
arg
can have any of the following types:
| If |
| The bitwise inverse of |
| The result will be |
| The type inverse of |
| If |
`!()
, lfun::`~()
float
abs(float
f
)
int
abs(int
f
)
object
abs(object
f
)
Return the absolute value for f
. If f
is
an object it must implement lfun::`<
and
unary lfun::`-
.
int
access(string
path
, string
|void
mode
)
access() checks if the calling process can access the file
path
. Symbolic links are dereferenced.
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.
| When the file is accessible using the given permissions. | ||||||||||||
| When the file is not accessible, in which case
Other errors can occur, but are not directly related to the
requested path, such as |
errno()
, Stdio.File
float
acos(int
|float
f
)
Return the arcus cosine value for f
.
The result will be in radians.
cos()
, asin()
float
acosh(int
|float
f
)
Return the hyperbolic arcus cosine value for f
.
cosh()
, asinh()
void
add_constant(string
name
, mixed
value
)
void
add_constant(string
name
)
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.
all_constants()
void
add_include_path(string
tmp
)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void
add_module_path(string
path
, string
|void
subpath
)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
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).
subpath
if path is a ZIP archive, this argument will determine the path within the archive to be searched.
void
add_program_path(string
tmp
)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
array
aggregate(mixed
... elements
)
Construct an array with the arguments as indices.
This function could be written in Pike as:
array aggregate(mixed ... elems) { return elems; }
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.
sizeof()
, arrayp()
, allocate()
mapping
aggregate_mapping(mixed
... elems
)
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, ... ])
sizeof()
, mappingp()
, mkmapping()
multiset
aggregate_multiset(mixed
... elems
)
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, ...>)
sizeof()
, multisetp()
, mkmultiset()
int
alarm(int
seconds
)
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 the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
ualarm()
, signal()
, call_out()
mapping
(string
:mixed
) all_constants()
Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.
add_constant()
array
allocate(int
size
)
array
allocate(int
size
, mixed
init
)
Allocate an array of size
elements. If init
is specified
then each element is initialized by copying that value
recursively.
sizeof()
, aggregate()
, arrayp()
array
(multiset
(Pike.Annotation
)) annotations(object
|program
|function
(:void
) x
, bool
|void
recurse
)
Return an array with the annotations for all symbols in x
.
x
| For objects which define For other objects an array with annotations for all non-protected symbols is returned. |
| Returns an array with annotations for all non-protected constant symbols. |
recurse
Include annotations recursively added via inherits.
The order of the resulting array is the same as that of indices()
for the same x
.
This function was added in Pike 8.1.
indices()
, values()
, types()
, lfun::_annotations()
,
::_annotations()
, Program.annotations
array
array_sscanf(string
data
, string
format
)
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.
sscanf()
, `/()
int
arrayp(mixed
arg
)
Returns 1
if arg
is an array, 0
(zero) otherwise.
intp()
, programp()
, mappingp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
float
asin(int
|float
f
)
Return the arcus sine value for f
.
The result will be in radians.
sin()
, acos()
float
asinh(int
|float
f
)
Return the hyperbolic arcus sine value for f
.
sinh()
, acosh()
float
atan(int
|float
f
)
Returns the arcus tangent value for f
.
The result will be in radians.
tan()
, asin()
, acos()
, atan2()
float
atan2(float
f1
, float
f2
)
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.
tan()
, asin()
, acos()
, atan()
float
atanh(int
|float
f
)
Returns the hyperbolic arcus tangent value for f
.
tanh()
, asinh()
, acosh()
void
atexit(function
(:void
) callback
)
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
.
Please note that atexit
callbacks are not called if Pike
exits abnormally.
exit()
, _exit()
mixed
atomic_get_set(mapping
|object
map
, mixed
key
, mixed
val
)
mixed
atomic_get_set(array
arr
, int
index
, mixed
val
)
Replace atomically the value for a key in a mapping or array.
map
arr
Mapping or array to alter.
key
index
Key or index to change the value for.
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 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.
m_delete()
array
(Pike.BacktraceFrame
) backtrace(int
|void
flags
)
Get a description of the current call stack.
flags
A bit mask of flags affecting generation of the backtrace.
Currently a single flag is defined:
| Return Note that since these values are "live", they may change or dissapear at any time unless the corresponding thread has been halted or similar. |
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.
Please note that the frame order may be reversed in a later version of Pike to accommodate for deferred backtraces.
Note that the arguments reported in the backtrace are the current values of the variables, and not the ones that were at call-time. This can be used to hide sensitive information from backtraces (eg passwords).
In old versions of Pike the entries used to be represented by arrays of the following format:
Array | |
| A string with the filename if known, else zero. |
| An integer containing the linenumber if known, else zero. |
| The function that was called at this level. |
| The arguments that the function was called with. |
The above format is still supported by eg describe_backtrace()
.
catch()
, throw()
string
basename(string
path
)
Returns the last segment of a path.
dirname()
, explode_path()
string
basetype(mixed
x
)
Same as sprintf("%t",x);
sprintf()
string
bkey(mixed
key
)
Render the internally used binary representation of the key into a string as a strings of '0's and '1's.
int
callablep(mixed
arg
)
Returns 1
if arg
is a callable, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, intp()
mapping
cast(string
type
)
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
int
cd(string
s
)
Change the current directory for the whole Pike process.
Returns 1
for success, 0
(zero) otherwise.
getcwd()
float
ceil(int
|float
f
)
Return the closest integer value greater or equal to f
.
ceil()
does not return an int
, merely an integer value
stored in a float
.
floor()
, round()
array
column(array
data
, mixed
index
)
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.
rows()
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
)
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.
getcwd()
, Stdio.append_path()
program
compile(string
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
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 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()
.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
, DefaultCompilerEnvironment
protected
program
compile(string
source
, object
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
program
compile_file(string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
)
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
)
compile()
, compile_string()
, cpp()
program
compile_string(string
source
, string
|void
filename
, object
|void
handler
, void
|program
p
, void
|object
o
, void
|int
_show_if_constant_errors
)
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
(source
, filename
))
compile()
, cpp()
, compile_file()
mixed
copy_value(mixed
value
)
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 `==()
).
equal()
float
cos(int
|float
f
)
Return the cosine value for f
.
f
should be specified in radians.
acos()
, sin()
, tan()
float
cosh(int
|float
f
)
Return the hyperbolic cosine value for f
.
acosh()
, sinh()
, tanh()
int
cp(string
from
, string
to
)
Copies the file from
to the new position to
. This is an
alias for Stdio.cp
.
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
)
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:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
| Mapping of predefined macros in addition to those
returned by |
compile()
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
)
string(46..122)
crypt(string(1..255)
password
)
bool
crypt(string(1..255)
input_password
, string(46..122)
crypted_password
)
string(46..122)
crypt()
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 that strings containing null characters will only be processed up until the null character.
string
ctime(int
timestamp
)
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
.
strftime()
, time()
, localtime()
, gmtime()
, mktime()
mixed
decode_value(string
coded_value
, void
|Codec
|int(-1)
codec
)
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.
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
.
encode_value()
, encode_value_canonic()
void
delay(int
|float
s
)
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.
signal()
, sleep()
bool
deprecated_typep(type
t
)
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__.
1
if the type has the "deprecated" attribute,
0
otherwise.
int(0..)
depth()
Calculate the depth of the tree.
string
describe_backtrace(mixed
trace
, void
|int
linewidth
)
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.
backtrace()
, describe_error()
, catch()
, throw()
string
describe_error(mixed
err
)
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.
describe_backtrace()
, get_backtrace
bool
destruct(void
|object
o
)
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 1
if o
has an lfun::_destruct()
that
returned 1
and inhibited destruction.
int
destructedp(mixed
arg
)
Returns 1
if arg
is a destructed object, 0
(zero) otherwise.
zero_type
, undefinedp
, intp
string
dirname(string
path
)
Returns all but the last segment of a path. Some example inputs and outputs:
Expression | Value |
dirname("/a/b") | "/a" |
dirname("/a/") | "/a" |
dirname("/a") | "/" |
dirname("/") | "/" |
dirname("") | "" |
basename()
, explode_path()
string
encode_value(mixed
value
, Codec
|void
codec
)
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
returns UNDEFINED for an
object, codec
->nameof(o)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.
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.
decode_value()
, sprintf()
, encode_value_canonic()
string
encode_value_canonic(mixed
value
, object
|void
codec
)
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 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.
encode_value()
, decode_value()
array
(int
) enumerate(int
n
)
array
enumerate(int
n
, void
|mixed
step
, void
|mixed
start
, void
|function
(:void
) operator
)
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
= `+
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;
}
map()
, foreach()
int
equal(mixed
a
, mixed
b
)
This function checks if the values a
and b
are equivalent.
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:
| Returns the same as |
| The contents of Note that for objects this case is only reached if neither
|
| Returns |
copy_value()
, `==()
int
errno()
This function returns the system error from the last file operation.
Note that you should normally use Stdio.File->errno()
instead.
Stdio.File->errno()
, strerror()
void
error(sprintf_format
f
, sprintf_args
... args
)
Throws an error. A more readable version of the code
throw( ({ sprintf(f, @args), backtrace() }) )
.
constant
int
is_gssapi_error
constant
string
error_type
Object recognition constants.
constant
int
is_gssapi_missing_services_error
constant
string
error_type
Object recognition constants.
int
exece(string
file
, array
(string
) args
)
int
exece(string
file
, array
(string
) args
, mapping
(string
:string
) env
)
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.
This function only returns if something went wrong during exece(2),
and in that case it returns 0
(zero).
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.
Process.create_process()
, fork()
, Stdio.File->pipe()
void
exit(int
returncode
, void
|string
fmt
, mixed
... extra
)
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.
_exit()
float
exp(float
|int
f
)
Return the natural exponential of f
.
log( exp( x ) ) == x
as long as exp(x) doesn't overflow an int.
pow()
, log()
array
(string
) explode_path(string
p
)
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()
.
Stdio.Stat
file_stat(string
path
, void
|bool
symlink
)
Stat a file.
If the argument symlink
is 1
symlinks will not be followed.
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.
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;
}
Stdio.Stat
, Stdio.File->stat()
int
file_truncate(string
file
, int
length
)
Truncates the file file
to the length specified in length
.
Returns 1 if ok, 0 if failed.
mapping
(string
:int
) filesystem_stat(string
path
)
Returns a mapping describing the properties of the filesystem
containing the path specified by path
.
If a filesystem cannot be determined 0
(zero) will be returned.
Otherwise a mapping(string:int) with the following fields will be returned:
| Size in bytes of the filesystem blocks. |
| Size of the entire filesystem in blocks. |
| Number of free blocks in the filesystem. |
| Number of available blocks in the filesystem.
This is usually somewhat less than the |
| Total number of files (aka inodes) allowed by this filesystem. |
| Number of free files in the filesystem. |
| Number of available files in the filesystem.
This is usually the same as the |
| Name assigned to the filesystem. This item is not available on all systems. |
| Type of filesystem (eg |
Please note that not all members are present on all OSs.
file_stat()
mixed
filter(mixed
arr
, void
|mixed
fun
, mixed
... extra
)
Filters the elements in arr
through fun
.
arr
is treated as a set of elements to be filtered, as
follows:
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.
The values are filtered with fun
, and the index/value
pairs it accepts are kept in the returned mapping.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
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:
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.
The object is used as a function like above, i.e. the
lfun::`()
method in it is called.
fun
is indexed with each element. The element is kept if
the result is nonzero, otherwise it's filtered 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.
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.
The function is never destructive on arr
.
map()
, foreach()
int
floatp(mixed
arg
)
Returns 1
if arg
is a float, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, multisetp()
, objectp()
,
mappingp()
, stringp()
, functionp()
float
floor(int
|float
f
)
Return the closest integer value less or equal to f
.
floor()
does not return an int
, merely an integer value
stored in a float
.
ceil()
, round()
object
fork()
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.
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()
.
Process.create_process()
string
function_name(function
(:void
)|program
f
)
Return the name of the function or program f
.
If f
is a global function defined in the runtime 0
(zero) will be returned.
function_object()
object
function_object(function
(:void
) f
)
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.
function_name()
, function_program()
program
function_program(function
(:void
)|program
f
)
Return the program the function f
is in.
If f
is a global function defined in the runtime 0
(zero) will be returned.
function_name()
, function_object()
int
functionp(mixed
arg
)
Returns 1
if arg
is a function, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, intp()
int
gc(mapping
|array
|void
quick
)
Force garbage collection.
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.)
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.
Pike.gc_parameters
, Debug.gc_status
CompilationHandler
get_active_compilation_handler()
Returns the currently active compilation compatibility handler, or 0 (zero) if none is active.
This function should only be used during a call of compile()
.
get_active_error_handler()
, compile()
,
master()->get_compilation_handler()
, CompilationHandler
CompilerEnvironment.PikeCompiler
|zero
get_active_compiler()
Returns the most recent of the currently active pike compilers,
or UNDEFINED
if none is active.
This function should only be used during a call of compile()
.
get_active_error_handler()
, compile()
,
master()->get_compilation_handler()
, CompilationHandler
CompilationHandler
get_active_error_handler()
Returns the currently active compilation error handler
(second argument to compile()
), or 0 (zero) if none
is active.
This function should only be used during a call of compile()
.
get_active_compilation_handler()
, compile()
, CompilationHandler
array
(array
(int
|string
|array
(string
))) get_all_groups()
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.
The groups source is system dependant. Refer to your system manuals for information about how to set the source.
Array | |
| Array with info about the group |
getgrent()
array
(array
(int
|string
)) get_all_users()
Returns an array with all users in the system.
An array with arrays of userinfo as in getpwent
.
getpwent()
getpwnam()
getpwuid()
array
get_backtrace(object
|array
err
)
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.
describe_backtrace()
, describe_error()
array
(string
) get_dir(void
|string
dirname
)
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.
mkdir()
, cd()
array
(int
) get_groups_for_user(int
|string
user
)
Gets all groups which a given user is a member of.
user
UID or loginname of the user
Array | |
| Information about all the users groups |
get_all_groups()
getgrgid()
getgrnam()
getpwuid()
getpwnam()
Iterator
get_iterator(object
|array
|mapping
|multiset
|string
data
, mixed
... args
)
Creates and returns a canonical iterator for data
.
data
can have any of the following types:
| If If |
| If |
| If |
| If |
| If |
This function is used by foreach
to get an iterator for an
object.
Iterator
, lfun::_get_iterator
array
(int
|mapping
(string
:array
(int
))) get_profiling_info(program
prog
)
Get profiling information.
Returns an array with two elements.
Array | |||||||||
| The first element is the number of times the program | ||||||||
| The second element is mapping from function name to an array with three elements.
|
This function is only available if the runtime was compiled with the option --with-profiling.
int
get_weak_flag(array
|mapping
|multiset
m
)
Returns the weak flag settings for m
. It's a combination of
Pike.WEAK_INDICES
and Pike.WEAK_VALUES
.
string
getcwd()
Returns the current working directory.
cd()
mapping
(string
:string
) getenv(void
|int
force_update
)
Queries the environment variables.
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 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.
On NT the environment variable name is case insensitive.
putenv()
string
getenv(string
varname
, void
|int
force_update
)
Query the value of a specific environment variable.
varname
Environment variable to query.
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 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.
On NT the environment variable name is case insensitive.
putenv()
array
(int
|string
|array
(string
)) getgrgid(int
gid
)
Get the group entry for the group with the id gid
using the systemfunction
getgrid(3).
gid
The id of the group
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrnam()
array
(int
|string
|array
(string
)) getgrnam(string
str
)
Get the group entry for the group with the name str
using the
systemfunction getgrnam(3).
str
The name of the group
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrgid()
int
gethrdtime(void
|int
nsec
)
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.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION
.
_disable_threads()
, gethrtime()
int
gethrtime(void
|int
nsec
)
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.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION
.
System.REAL_TIME_IS_MONOTONIC
, System.REAL_TIME_RESOLUTION
,
time()
, System.gettimeofday()
, gethrvtime()
,
Pike.implicit_gc_real_time
int
gethrvtime(void
|int
nsec
)
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.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.CPU_TIME_RESOLUTION
.
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.
The special function gauge
is implemented with this function.
System.CPU_TIME_IS_THREAD_LOCAL
, System.CPU_TIME_RESOLUTION
,
gauge()
, System.getrusage()
, gethrtime()
int
getpid()
Returns the process ID of this process.
System.getppid()
, System.getpgrp()
array
(int
|string
) getpwnam(string
str
)
Get the user entry for login str
using the systemfunction getpwnam(3).
str
The login name of the user whos userrecord is requested.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwuid()
getpwent()
array
(int
|string
) getpwuid(int
uid
)
Get the user entry for UID uid
using the systemfunction getpwuid(3).
uid
The uid of the user whos userrecord is requested.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwnam()
getpwent()
string
getxattr(string
file
, string
attr
, void
|bool
symlink
)
Return the value of a specified attribute, or 0 if it does not exist.
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
)
Match strings against a glob pattern.
glob
| The glob pattern. A question sign ('?') matches any character and an asterisk ('*') matches a string of arbitrary length. All other characters only match themselves. |
| 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) |
str
|
|
| All strings in the array |
sscanf()
, Regexp
mapping
(string
:int
) gmtime(int
timestamp
)
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.
localtime()
, time()
, ctime()
, mktime()
,
strptime()
int
has_index(string
haystack
, int
index
)
int
has_index(array
haystack
, int
index
)
int
has_index(mapping
|multiset
|object
|program
haystack
, mixed
index
)
Search for index
in haystack
.
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
A negative index in strings and arrays as recognized by the
index operators `[]()
and `[]=()
is not considered
a proper index by has_index()
has_value()
, has_prefix()
, has_suffix()
, indices()
,
search()
, values()
, zero_type()
int
has_prefix(string
|object
s
, string
prefix
)
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::`[]
.
has_suffix()
, has_value()
, search()
int
has_suffix(string
s
, string
suffix
)
Returns 1
if the string s
ends with suffix
,
returns 0
(zero) otherwise.
has_prefix()
, has_value()
, search()
int
has_value(string
haystack
, string
value
)
int
has_value(string
haystack
, int
value
)
int
has_value(array
|mapping
|object
|program
haystack
, mixed
value
)
Search for value
in haystack
.
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
has_index()
, indices()
, search()
, has_prefix()
,
has_suffix()
, values()
, zero_type()
int
hash(string
s
)
int
hash(string
s
, int
max
)
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.
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()
.
This hash function differs from the one provided by hash_value()
,
in that hash_value()
returns a process specific value.
hash_7_0()
, hash_7_4()
, hash_8_0()
, hash_value
int
hash_7_0(string
s
)
int
hash_7_0(string
s
, int
max
)
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.
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.
hash()
, hash_7_4
int
hash_7_4(string
s
)
int
hash_7_4(string
s
, int
max
)
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.
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.
hash_7_6()
, hash_7_0
int
hash_8_0(string
s
)
int
hash_8_0(string
s
, int
max
)
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.
Use hash_value()
for in-process hashing (eg, for implementing
lfun::_hash()
) or one of the cryptographic hash functions.
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.
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()
.
This hash function differs from the one provided by hash_value()
,
in that hash_value()
returns a process specific value.
hash()
, hash_7_0()
, hash_7_4()
, hash_value
int
hash_value(mixed
value
)
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.
This is the hashing method used by mappings.
lfun::__hash()
array
indices(string
|array
|mapping
|multiset
|object
x
)
Return an array of all valid indices for the value x
.
x
| For strings and arrays this is simply an array of ascending numbers. |
| For mappings and multisets, the array might contain any value. |
| For objects which define For other objects an array with the names of all non-protected symbols is returned. |
values()
, types()
, lfun::_indices()
int
intp(mixed
arg
)
Returns 1
if arg
is an int, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
int
is_absolute_path(string
p
)
Check if a path p
is fully qualified (ie not relative).
Returns 1 if the path is absolute, 0 otherwise.
constant
int
is_sql_null
SQL Null marker.
Replaced by is_val_null
.
constant
int
is_val_null
Nonzero recognition constant.
mixed
iterator_index(object
iter
)
Get the current index for iter
.
get_iterator()
bool
iterator_next(object
iter
)
Advance iter
one step.
get_iterator()
mixed
iterator_value(object
iter
)
Get the current value for iter
.
get_iterator()
bool
kill(int
pid
, int
signal
)
Send a signal to another process.
Some signals and their supposed purpose:
| Hang-up, sent to process when user logs out. |
| Interrupt, normally sent by ctrl-c. |
| Quit, sent by ctrl-\. |
| Illegal instruction. |
| Trap, mostly used by debuggers. |
| Aborts process, can be caught, used by Pike whenever something goes seriously wrong. |
| Emulation trap. |
| Floating point error (such as division by zero). |
| Really kill a process, cannot be caught. |
| Bus error. |
| Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike. |
| Bad system call. Should never happen to Pike. |
| Broken pipe. |
| Signal used for timer interrupts. |
| Termination signal. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Child process died. This signal is reserved for internal use by the Pike run-time. |
| Power failure or restart. |
| Window change signal. |
| Urgent socket data. |
| Pollable event. |
| Stop (suspend) process. |
| Stop (suspend) process. Sent by ctrl-z. |
| Continue suspended. |
| TTY input for background process. |
| TTY output for background process. |
| Virtual timer expired. |
| Profiling trap. |
| Out of CPU. |
| File size limit exceeded. |
| Stack fault |
| Success. |
| Failure. |
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.
signal()
, signum()
, signame()
, fork()
int
|float
|object
limit(int
|float
|object
minval
, int
|float
|object
x
, int
|float
|object
maxval
)
Limits the value x
so that it's between minval
and maxval
.
If x
is an object, it must implement the lfun::`<
method.
max()
and min()
array
(string
) listxattr(string
file
, void
|bool
symlink
)
Return an array of all extended attributes set on the file
program
load_module(string
module_name
)
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.
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.
mapping
(string
:int
) localtime(int
timestamp
)
Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.
This function returns a mapping with the following components:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Day of week (0 = Sunday). |
| Day of the year. |
| Is daylight-saving time active. |
| 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
.
Prior to Pike 7.5 the field "timezone"
was sometimes not
present, and was sometimes not adjusted for daylight-saving time.
Calendar
, gmtime()
, time()
, ctime()
, mktime()
,
strptime()
float
log(int
|float
f
)
Return the natural logarithm of f
.
exp( log(x) ) == x
for x > 0.
pow()
, exp()
string
lower_case(string
s
)
int
lower_case(int
c
)
Convert a string or character to lower case.
Returns a copy of the string s
with all upper case characters
converted to lower case, or the character c
converted to lower
case.
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.
Prior to Pike 7.5 this function only accepted strings.
upper_case()
, Charset.decoder
void
m_add(multiset
|object
l
, mixed
val
)
Add a member to a multiset.
m_delete()
void
m_clear(mapping
|multiset
|object
map
)
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.
m_delete()
mixed
m_delete(object
|mapping
|multiset
map
, mixed
index
)
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.
The value that was removed will be returned,
and UNDEFINED
otherwise.
Note that m_delete()
changes map
destructively.
mappingp()
mixed
map(mixed
arr
, void
|mixed
fun
, mixed
... extra
)
Applies fun
to the elements in arr
and collects the results.
arr
is treated as a set of elements, as follows:
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.
fun
is applied to the values, and each result is assigned
to the same index in a new mapping, which is returned.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
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:
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.
fun
is used as a function like above, i.e. the
lfun::`()
method in it is called.
Each element of the fun
array will be called for each
element of arr
.
fun
is indexed with each element. The result of that is
collected.
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.
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.
The function is never destructive on arr
.
filter()
, enumerate()
, foreach()
int
mappingp(mixed
arg
)
Returns 1
if arg
is a mapping, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
object
master()
Return the current master object.
May return UNDEFINED
if no master has been loaded yet.
replace_master()
int
|float
|object
max(int
|float
|object
, int
|float
|object
... args
)
string
max(string
, string
... args
)
int(0)
max()
Returns the largest value among args
. Compared objects
must implement the lfun::`<
method.
min()
and limit()
int
|float
|object
min(int
|float
|object
, int
|float
|object
... args
)
string
min(string
, string
... args
)
int(0)
min()
Returns the smallest value among args
. Compared objects
must implement the lfun::`<
method.
max()
and limit()
int
mkdir(string
dirname
, void
|int
mode
)
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 0
(zero) on failure, 1
otherwise.
rm()
, cd()
, Stdio.mkdirhier()
mapping
mkmapping(array
ind
, array
val
)
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()
.
indices()
, values()
multiset
mkmultiset(array
a
)
This function creates a multiset from an array.
aggregate_multiset()
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
)
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:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Is daylight-saving time active. If omitted or set to |
| 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.
For proper UTC calculations ensure that isdst = 0
and
timezone = 0
; omitting either one of these parameters
will mess up the UTC calculation.
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).
time()
, ctime()
, localtime()
, gmtime()
, strftime()
int
multisetp(mixed
arg
)
Returns 1
if arg
is a multiset, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, stringp()
, objectp()
,
mappingp()
, floatp()
, functionp()
int
mv(string
from
, string
to
)
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 0
(zero) on failure, 1
otherwise. Call
errno()
to get more error info on failure.
rm()
string
normalize_path(string
path
)
Replaces "\" with "/" if runing on MS Windows. It is
adviced to use System.normalize_path
instead.
mixed
nth(int(0..)
n
)
Get the n
th entry in order.
An array ({ key, value })
.
program
|function
(:void
) object_program(mixed
o
)
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.
bool
object_variablep(object
o
, string
var
)
Find out if an object identifier is a variable.
This function returns 1
if var
exists as a
non-protected variable in o
, and returns 0
(zero)
otherwise.
indices()
, values()
int
objectp(mixed
arg
)
Returns 1
if arg
is an object, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, functionp()
,
multisetp()
, floatp()
, intp()
int
|float
pow(float
|int
n
, float
|int
x
)
mixed
pow(object
n
, float
|int
|object
x
)
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.
exp()
, log()
int
programp(mixed
arg
)
Returns 1
if arg
is a program, 0
(zero) otherwise.
mappingp()
, intp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
void
putenv(string
varname
, void
|string
value
)
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.
On NT the environment variable name is case insensitive.
getenv()
int
query_num_arg()
Returns the number of arguments given when the previous function was called.
This is useful for functions that take a variable number of arguments.
call_function()
array
random(mapping
m
)
float
random(float
max
)
int
random(int
max
)
mixed
random(object
o
)
mixed
random(array
|multiset
x
)
Get a random value generated by the default RandomSystem
.
RandomSystem()->random()
, random_string()
void
random_seed(int
seed
)
This function sets the initial value for the random generator.
random()
Random.Deterministic
string
random_string(int
len
)
Get a string of random characters 0..255
with the length len
from the default RandomSystem
.
RandomSystem()->random_string()
, random()
void
remove_include_path(string
tmp
)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path()
.
add_include_path()
void
remove_module_path(string
tmp
)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path()
.
add_module_path()
void
remove_program_path(string
tmp
)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path()
.
add_program_path()
void
removexattr(string
file
, string
attr
, void
|bool
symlink
)
Remove the specified extended attribute.
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
)
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
can be
used.mkmapping
(from
, to
)
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 that replace()
on arrays and mappings is a destructive operation.
void
replace_master(object
o
)
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.
master()
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
)
Reverses a string, array or int.
s
String to reverse.
a
Array to reverse.
i
Integer to reverse.
o
Object to reverse.
start
Optional start index of the range to reverse.
Default: 0
(zero).
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
.
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.
sscanf()
int
rm(string
f
)
Remove a file or directory.
Returns 0
(zero) on failure, 1
otherwise.
May fail with errno()
set to EISDIR
or ENOTDIR
if the file has changed to a directory during the call
or the reverse.
Stdio.File()->unlinkat()
, mkdir()
, Stdio.recursive_rm()
float
round(int
|float
f
)
Return the closest integer value to f
.
round()
does not return an int
, merely an integer value
stored in a float
.
floor()
, ceil()
array
rows(mixed
data
, array
index
)
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.
column()
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
)
Search for needle
in haystack
.
haystack
Item to search in. This can be one of:
| When |
| When |
| When |
| When If |
start
If the optional argument start
is present search is started at
this position. This has no effect on mappings.
end
If the optional argument end
is present, the search will terminate
at this position (exclusive) if not found earlier.
Returns the position of needle
in haystack
if found.
If not found the returned value depends on the type of haystack
:
|
|
|
|
| The value returned by |
If start
is supplied to an iterator object without an
lfun::_search()
, haystack
will need to implement
Iterator()->set_index()
.
For mappings and object UNDEFINED
will be returned when not found.
In all other cases -1
will be returned when not found.
indices()
, values()
, zero_type()
, has_value()
,
has_prefix()
, has_suffix()
int
set_priority(string
level
, int(0..)
|void
pid
)
array
|mapping
|multiset
set_weak_flag(array
|mapping
|multiset
m
, int
state
)
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:
| Use weak references for indices. Only applicable for multisets and mappings. |
| Use weak references for values. Only applicable for arrays and mappings. |
| Shorthand for |
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
.
m
will be returned.
void
setxattr(string
file
, string
attr
, string
value
, int
flags
, void
|bool
symlink
)
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.
1 if successful, 0 otherwise, setting errno.
int
sgn(mixed
value
)
int
sgn(mixed
value
, mixed
zero
)
Check the sign of a value.
Returns -1
if value
is less than zero
,
1
if value
is greater than zero
and 0
(zero) otherwise.
abs()
function
(int
|void
:void
) signal(int
sig
, function
(int
|void
:void
) callback
)
function
(int
|void
:void
) signal(int
sig
)
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 the previous signal function, or 0 if none had been registered.
kill()
, signame()
, signum()
string
signame(int
sig
)
Returns a string describing the signal sig
.
kill()
, signum()
, signal()
int
signum(string
sig
)
Get a signal number given a descriptive string.
This function is the inverse of signame()
.
signame()
, kill()
, signal()
float
sin(int
|float
f
)
Returns the sine value for f
.
f
should be specified in radians.
asin()
, cos()
, tan()
float
sinh(int
|float
f
)
Returns the hyperbolic sine value for f
.
asinh()
, cosh()
, tanh()
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
)
Size query.
The result will be as follows:
arg
can have any of the following types:
| The number of characters in |
| The number of elements in |
| The number of key-value pairs in |
| If |
lfun::_sizeof()
void
sleep(int
|float
s
, void
|int
abort_on_signal
)
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.
signal()
, delay()
array
sort(array
(mixed
) index
, array
(mixed
) ... data
)
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.
The first argument is returned.
The sort is stable, i.e. elements that are compare-wise equal aren't reordered.
Array.sort_array
, reverse()
string
sprintf(strict_sprintf_format
format
, sprintf_args
... args
)
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:
| 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 | ||||||||
| Inverse table mode (left-to-right order). | ||||||||
| (Where n is a number or *) field width specifier. | ||||||||
| |||||||||
| Precision specifier. | ||||||||
| 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
| ||||||||
| 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. | ||||||||
| Select argument number n. Use * to use the next
argument as selector. The arguments are numbered starting from
|
The following operators are supported:
| Percent. |
| Signed binary integer. |
| Signed decimal integer. |
| Unsigned decimal integer. |
| Signed octal integer. |
| Lowercase signed hexadecimal integer. |
| Uppercase signed hexadecimal integer. |
| 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. |
| Float. (Locale dependent formatting.) |
| Heuristically chosen representation of float. (Locale dependent formatting.) |
| Like %g, but uses uppercase E for exponent. |
| Exponential notation float. (Locale dependent output.) |
| Like %e, but uses uppercase E for exponent. |
| 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. |
| String. |
| Quoted string. Escapes all control and non-8-bit characters, as well as the quote characters '\\' and '\"'. |
| 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 |
| Hexadecimal representation of the memory address of the object. Integers and floats have no address, and are printed as themselves. |
| Binary Hollerith string. Equivalent to |
| No argument. Same as |
| 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.
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
.
The 'q'
operator was added in Pike 7.7.
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__
.
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__
.
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
lfun::_sprintf()
, strict_sprintf_format
, sprintf_format
,
sprintf_args
, String.__HAVE_SPRINTF_STAR_MAPPING__
,
String.__HAVE_SPRINTF_NEGATIVE_F__
.
constant
sprintf_args
Type constant used for typing extra arguments that are
sent to sprintf()
.
strict_sprintf_format
, sprintf_format
, sprintf()
constant
sprintf_format
Type constant used for typing arguments that are optionally
sent to sprintf()
depending on the presence of extra arguments.
strict_sprintf_format
, sprintf_args
, sprintf()
constant
sprintf_result
Type constant used for typing the return value from sprintf()
.
strict_sprintf_format
, sprintf_format
, sprintf()
float
sqrt(float
f
)
int(0..)
sqrt(int(0..)
i
)
mixed
sqrt(object
o
)
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.
pow()
, log()
, exp()
, floor()
, lfun::_sqrt
int
sscanf(string
data
, string
format
, mixed
... lvalues
)
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:
| Reads a binary integer ( |
| Reads a decimal integer ( |
| Reads an octal integer ( |
| Reads a hexadecimal integer ( |
| Reads an integer that is either octal (leading zero),
hexadecimal (leading |
| Reads one character and returns it as an integer
( |
| Returns the current character offset in |
| Reads a float ("0101" makes 101.0). |
| Reads a float encoded according to the IEEE single precision
binary format ( |
| 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. |
| 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 |
| 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: |
| Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue. |
| 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. |
| 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 ( |
| 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,
|
| Ignore the matched characters with respect to any following
|
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.
// 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);
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).
sprintf
, array_sscanf
string
strerror(int
errno
)
This function returns a description of an error code. The error
code is usually obtained from eg Stdio.File->errno()
.
On some platforms the string returned can be somewhat nondescriptive.
string(1..255)
strftime(string(1..255)
format
, mapping
(string
:int
) tm
)
Convert the structure to a string.
The abbreviated weekday name according to the current locale
The full weekday name according to the current locale.
The abbreviated month name according to the current locale.
The full month name according to the current locale.
The preferred date and time representation for the current locale.
The century number (year/100) as a 2-digit integer.
The day of the month as a decimal number (range 01 to 31).
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.)
Like %d
, the day of the month as a decimal number,
but a leading zero is replaced by a space.
Modifier: use alternative format, see below.
Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
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.
Like %G
, but without century, that is,
with a 2-digit year (00-99). (TZ)
Equivalent to %b.
The hour as a decimal number using a 24-hour clock (range 00 to 23).
The hour as a decimal number using a 12-hour clock (range 01 to 12).
The day of the year as a decimal number (range 001 to 366).
The month as a decimal number (range 01 to 12).
The minute as a decimal number (range 00 to 59).
A newline character. (SU)
Modifier: use alternative format, see below. (SU)
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"
.
Like %p
but in lowercase: "am"
or "pm"
or a corresponding string for the current locale.
The time in a.m. or p.m. notation. In the POSIX locale this is
equivalent to %I:%M:%S %p
.
The time in 24-hour notation (%H:%M
). (SU)
For a version including the seconds, see %T
below.
The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)
The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)
A tab character. (SU)
The time in 24-hour notation (%H:%M:%S
). (SU)
The day of the week as a decimal, range 1 to 7, Monday being 1.
See also %w
. (SU)
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
.
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
.
The day of the week as a decimal, range 0 to 6, Sunday being 0.
See also %u
.
ctime()
, mktime()
, strptime()
, Gettext.setlocale
constant
strict_sprintf_format
Type constant used for typing arguments that are always
sent to sprintf()
regardless of the presence of extra arguments.
sprintf_format
, sprintf_args
, sprintf()
string(1..)
string_filter_non_unicode(string
s
)
Replace the most obviously non-unicode characters from s
with
the unicode replacement character.
This will replace characters outside the ranges
0x00000000-0x0000d7ff
and 0x0000e000-0x0010ffff
with 0xffea (the replacement character).
Charset.encoder()
, string_to_unicode()
,
unicode_to_string()
, utf8_to_string()
, string_to_utf8()
string(8bit)
string_to_unicode(string
s
, int(0..2)
|void
byteorder
)
Converts a string into an UTF16 compliant byte-stream.
s
String to convert to UTF16.
byteorder
Byte-order for the output. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
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.
Charset.decoder()
, string_to_utf8()
, unicode_to_string()
,
utf8_to_string()
utf8_string
string_to_utf8(string
s
)
utf8_string
string_to_utf8(string
s
, int
extended
)
Convert a string into a UTF-8 compliant byte-stream.
s
String to encode into UTF-8.
extended
Bitmask with extension options.
| Accept and encode the characters outside the valid ranges using the same algorithm. Such encoded characters are however not UTF-8 compliant. |
| Encode characters outside the BMP with UTF-8 encoded UTF-16 (ie split them into surrogate pairs and encode). |
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
.
Charset.encoder()
, string_to_unicode()
,
unicode_to_string()
, utf8_to_string()
int
stringp(mixed
arg
)
Returns 1
if arg
is a string, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, multisetp()
, objectp()
,
mappingp()
, floatp()
, functionp()
mapping
(string
:int
) strptime(string(1..255)
data
, string(1..255)
format
)
Parse the given data
using the format in format
as a date.
The % character.
The weekday name according to the C locale, in abbreviated form or the full name.
The month name according to the C locale, in abbreviated form or the full name.
The date and time representation for the C locale.
The century number (0-99).
The day of month (1-31).
Equivalent to %m/%d/%y.
The hour (0-23).
The hour on a 12-hour clock (1-12).
The day number in the year (1-366).
The month number (1-12).
The minute (0-59).
Arbitrary whitespace.
The C locale's equivalent of AM or PM.
Equivalent to %H:%M.
The second (0-60; 60 may occur for leap seconds; earlier also 61 was allowed).
Arbitrary whitespace.
Equivalent to %H:%M:%S.
The week number with Sunday the first day of the week (0-53).
The weekday number (0-6) with Sunday = 0.
The week number with Monday the first day of the week (0-53).
The date, using the C locale's date format.
The time, using the C locale's time format.
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).
The year, including century (for example, 1991).
localtime()
, gmtime()
, strftime()
float
tan(int
|float
f
)
Returns the tangent value for f
.
f
should be specified in radians.
atan()
, sin()
, cos()
float
tanh(int
|float
f
)
Returns the hyperbolic tangent value for f
.
atanh()
, sinh()
, cosh()
constant
this
Builtin read only variable that evaluates to the current object.
this_program
, this_object()
constant
this_function
Builtin constant that evaluates to the current function.
this
, this_object()
object
this_object(void
|int
level
)
Returns the object we are currently evaluating in.
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.
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
Builtin constant that evaluates to the current program.
this
, this_object()
mixed
|void
throw(mixed
value
)
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.
catch
int
time()
int
time(int(1)
one
)
float
time(int(2..)
t
)
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.
ctime()
, localtime()
, mktime()
, gmtime()
,
System.gettimeofday()
, gethrtime()
int
trace(int
level
, void
|string
facility
, void
|int
all_threads
)
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.
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:
| Trace calls to Pike functions and garbage collector runs. |
| Trace calls to builtin functions. |
| Trace every interpreted opcode. |
| Also trace the opcode arguments. |
facility
Valid facilities are:
| Trace the doings of the garbage collector. The setting is
never thread local.
|
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.
The old trace level in the current thread is returned.
type
|zero
typeof_identifier(program
p
, string
identifier
)
Allows access to the static type of an identifier ("member") in a program.
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.
array
(type
) types(string
|array
|mapping
|multiset
|object
|program
x
)
Return an array with the types of all valid indices for the value x
.
x
| For strings this is simply an array with int |
| For arrays, mappings and multisets this is simply an array with mixed. |
| For objects which define For other objects an array with type types for all non-protected symbols is returned. |
This function was added in Pike 7.9.
indices()
, values()
, lfun::_types()
int
ualarm(int
useconds
)
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 the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
alarm()
, signal()
, call_out()
int
undefinedp(mixed
arg
)
Returns 1
if arg
is undefined, 0
(zero) otherwise.
zero_type
, destructedp
, intp
string
unicode_to_string(string(8bit)
s
, int(0..2)
|void
byteorder
)
Converts an UTF16 byte-stream into a string.
s
String to convert to UTF16.
byteorder
Default input byte-order. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Note that this argument is disregarded if s
starts with a BOM.
Charset.decoder()
, string_to_unicode()
, string_to_utf8()
,
utf8_to_string()
string
upper_case(string
s
)
int
upper_case(int
c
)
Convert a string or character to upper case.
Returns a copy of the string s
with all lower case characters
converted to upper case, or the character c
converted to upper
case.
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.
Prior to Pike 7.5 this function only accepted strings.
lower_case()
, Charset.decoder
string
utf8_to_string(utf8_string
s
)
string
utf8_to_string(utf8_string
s
, int
extended
)
Converts an UTF-8 byte-stream into a string.
s
String of UTF-8 encoded data to decode.
extended
Bitmask with extension options.
| Accept and decode the extension used by |
| Accept and decode UTF-8 encoded UTF-16 (ie accept and decode valid surrogates). |
Throws an error if the stream is not a legal UTF-8 byte-stream.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are not decoded. An error is thrown instead.
Charset.encoder()
, string_to_unicode()
, string_to_utf8()
,
unicode_to_string()
, validate_utf8()
bool
validate_utf8(utf8_string
s
)
bool
validate_utf8(utf8_string
s
, int
extended
)
Checks whether a string is a valid UTF-8 byte-stream.
s
String of UTF-8 encoded data to validate.
extended
Bitmask with extension options.
| Accept the extension used by |
| Accept UTF-8 encoded UTF-16 (ie accept valid surrogate-pairs). |
Returns 0
(zero) if the stream is not a legal
UTF-8 byte-stream, and 1
if it is.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are considered invalid.
Charset.encoder()
, string_to_unicode()
, string_to_utf8()
,
unicode_to_string()
, utf8_to_string()
array
values(string
|array
|mapping
|multiset
|object
x
)
Return an array of all possible values from indexing the value
x
.
x
| For strings an array of int with the ISO10646 codes of the characters in the string is returned. |
| For a multiset an array filled with ones ( |
| For arrays a single-level copy of |
| For mappings the array may contain any value. |
| For objects which define For other objects an array with the values of all non-protected symbols is returned. |
indices()
, types()
, lfun::_values()
string
version()
Report the version of Pike. Does the same as
sprintf("Pike v%d.%d release %d", __REAL_VERSION__,
__REAL_MINOR__, __REAL_BUILD__);
__VERSION__
, __MINOR__
, __BUILD__
,
__REAL_VERSION__
, __REAL_MINOR__
, __REAL_BUILD__
,
int
werror(string
fmt
, mixed
... args
)
Writes a string on stderr. Works just like Stdio.File.write
on Stdio.stderr
.
int
write(string
fmt
, mixed
... args
)
Writes a string on stdout. Works just like Stdio.File.write
on Stdio.stdout
.
typedef
int(0)
zero
Zero datatype.
int
zero_type(mixed
a
)
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()
.