constant
int
String.__HAVE_SPRINTF_NEGATIVE_F__
Presence of this symbol indicates that sprintf()
supports
little endian output for the 'F'-format specifier.
sprintf()
, lfun::_sprintf()
constant
int
String.__HAVE_SPRINTF_STAR_MAPPING__
Presence of this symbol indicates that sprintf()
supports
mappings for the '*'-modifier syntax.
sprintf()
, lfun::_sprintf()
int(0..)
bits(string
data
)
Gives the actual number of bits needed to represent every
character in the string. Unlike width
that only looks at the
allocated string width, bits
actually looks at the maximum used
character and delivers a more precise answer than just 8, 16, or
32 bits. The empty string results in 0.
string
capitalize(string
str
)
Convert the first character in str
to upper case, and return the
new string.
lower_case()
, upper_case()
string
common_prefix(array
(string
) strs
)
Find the longest common prefix from an array of strings.
int
count(string
haystack
, string
needle
)
Count the number of non-overlapping times the string needle
occurs in the string haystack
. The special cases for the needle
""
is that it occurs one time in the empty string, zero
times in a one character string and between every character
(length-1) in any other string.
search()
, `/()
string
expand_tabs(string
s
, int(1..)
|void
tab_width
, string
|void
tab
, string
|void
space
, string
|void
newline
)
Expands tabs in a string to ordinary spaces, according to common tabulation rules.
int(0..100)
fuzzymatch(string
a
, string
b
)
This function compares two strings using a fuzzy matching routine. The higher the resulting value, the better the strings match.
Array.diff()
, Array.diff_compare_table()
Array.diff_longest_sequence()
string(8bit)
hex2string(string(8bit)
hex
)
Convert a string of hexadecimal digits to binary data. Non-hexadecimal characters will be ignored when between tuples. Eg. "00 00" is ok, but "0 000" isn't.
string2hex()
string
implode_nicely(array
(string
|int
|float
) foo
, string
|void
separator
)
This function implodes a list of words to a readable string, e.g.
({"straw","berry","pie"})
becomes
"straw, berry and pie"
. If the separator is omitted, the
default is "and"
. If the words are numbers they are
converted to strings first.
`*()
string
int2char(int
x
)
Same as sprintf("%c",x);
sprintf()
string
int2hex(int
x
)
Same as sprintf("%x",x);
, i.e. returns the integer x
in
hexadecimal base using lower cased symbols.
sprintf()
string
int2roman(int
m
)
Converts the provided integer to a roman integer (i.e. a string).
Throws an error if m
is outside the range 0 to 10000.
string
int2size(int
size
)
Returns the size as a memory size string with suffix, e.g. 43210 is converted into "42.2 kB". To be correct to the latest standards it should really read "42.2 KiB", but we have chosen to keep the old notation for a while. The function knows about the quantifiers kilo, mega, giga, tera, peta, exa, zetta and yotta.
int
levenshtein_distance(string
a
, string
b
)
This function calculates the Levenshtein distance between two strings a and b. The Levenshtein distance describes the minimal number of character additions, removals or substitutions to apply to convert a to b.
Mathematically, the Levenshtein distance between two strings a, b is given by lev_a,b(|a|,|b|) where
lev_a,b(i, j) == max(i, j), if min(i, j) == 0 lev_a,b(i, j) == min( lev_a,b(i, j-1)+1, lev_a,b(i-1, j)+1, lev_a,b(i-1, j-1) + a_i!=b_j ), else
Note that the first element in the minimum corresponds to inserting a character to a (or deleting a character from b), the second to deleting a character from a and the third to match or mismatch, depending on whether the respective characters are equal.
Example: For example, the Levenshtein distance between "pike" and "bikes" is 2, since the following two edits change one into the other, and there is no way to do it with fewer than two edits: - "pike" -> "bike" (substitute "p" with "b") - "bike" -> "bikes" (add "s" at the end)
Note that the cost to compute the Levenshtein distance is roughly proportional to the product of the two string lengths. So this function is usually used to aid in fuzzy string matching, when at least one of the strings is short.
string
normalize_space(string
s
, string
|void
whitespace
)
s
Is returned after white space in it has been normalised. White space is normalised by stripping leading and trailing white space and replacing sequences of white space characters with a single space.
whitespace
Defines what is considered to be white space eligible for normalisation.
It has a default value that starts with " \t\r\n\v\f"
and in
addition to that contains all whitespace characters part of Unicode.
The first character denotes the character for replacing whitespace
sequences.
Trailing and leading whitespace around \r and \n characters
is stripped as well (only useful if they're not in the whitespace
set).
This function is a lot faster with just one argument (i.e. the builtin whitespace set has an optimised code path).
array
(int
) range(string
s
)
Returns the character range of a string in an array of two elements. The first element contains the lower bound and the second the upper. The precision is only 8 bits, so for wide strings only character blocks are known.
string
secure(string
str
)
Marks the string as secure, which will clear the memory area before freeing the string.
Object.secure()
string
sillycaps(string
str
)
Convert the first character in each word (separated by spaces) in
str
to upper case, and return the new string.
string
soundex(string
word
)
Returns the soundex value of word
according to
the original Soundex algorithm, patented by Margaret O´Dell
and Robert C. Russel in 1918. The method is based on the phonetic
classification of sounds by how they are made. It was only intended
for hashing of english surnames, and even at that it isn't that
much of a help.
string
status(int
verbose
)
Get string table statistics.
Returns a string with an ASCII table containing the current string table statistics.
Currently returns the empty string (""
)
if verbose
is zero.
The formatting and contents of the result may vary between different versions of Pike.
string
string2hex(string
data
, void
|int(0..)
flags
)
Convert a string of binary data to a hexadecimal string.
flags
The binary or of the following flags:
| Use upper case characters. |
| The input is in little-endian byte order. |
hex2string()
string
trim(string
s
)
Trim leading and trailing white spaces characters (space, tab,
newline, carriage return, form feed, vertical tab and all the
white spaces defined in Unicode) from the string s
.
string
trim_whites(string
s
)
Trim leading and trailing spaces and tabs from the string s
.
int(8)
|int(16)
|int(32)
width(string
s
)
Returns the width of a string.
Three return values are currently possible:
| The string |
| The string |
| The string |
It is possible that a future version of Pike may return
further values. In particular the width 7
seems
like it could be useful.
This class implements the "Bootstring" string transcoder described in ftp://ftp.rfc-editor.org/in-notes/rfc3492.txt.
String.Bootstring String.Bootstring(
int
base
, int
tmin
, int
tmax
, int
skew
, int
damp
, int
initial_bias
, int
initial_n
, int
delim
, string
digits
)
Creates a Bootstring transcoder instance using the specified parameters.
base
The base used by the variable-length integers.
tmin
The minimum threshold digit value for the variable-length integers. Must be >=0 and <= tmax.
tmax
The maximum threshold digit value for the variable-length integers. Must be <= base-1.
skew
The skew term for the bias adapation. Must be >= 1.
damp
The damping factor for the bias adaption. Must be >= 2.
initial_bias
The initial bias for the variable-length integer thresholding. initial_bias % base must be <= base - tmin.
initial_n
The first code point outside the "basic" set of code points.
delim
The "basic" code point used as the delimiter.
digits
The "basic" code points used as digits. The length of the string should be the same as the base parameter.
string
decode(string
s
)
Decodes a Bootstring encoded string of "basic" code points back to the original string space.
string
encode(string
s
)
Encodes a string using Bootstring encoding into a string constisting only of "basic" code points (< initial_n).
A buffer, used for building strings. It's
conceptually similar to a string, but you can only add
strings to it, and you can only get
the value from it once.
There is a reason for those seemingly rather odd limitations, it makes it possible to do some optimizations that really speed things up.
You do not need to use this class unless you add very many strings together, or very large strings.
For the fastest possible operation, write your code like this:
String.Buffer b = String.Buffer( ); function add = b->add; .. call add several times in code ... string result = b->get(); // also clears the buffer
int(0..)
search(String.Buffer from, int
character
, int
|void
start
, int
|void
end
)
Search for a character
in the buffer, starting the scan
from start
and ending at end
(inclusive).
Returns to position in the buffer where the character was found
on success, and UNDEFINED
on failure.
Stdio.Buffer()->_search()
, search()
, lfun::_search()
int(0..)
search(String.Buffer from, string
substring
, int
|void
start
, int
|void
end
)
Search for a substring
in the buffer, starting the scan
from start
and ending at end
(inclusive).
Returns to position in the buffer where the substring was found
on success, and UNDEFINED
on failure.
Stdio.Buffer()->_search()
, search()
, lfun::_search()
int
sizeof( String.Buffer arg )
Returns the size of the buffer.
string sprintf(string format, ... String.Buffer arg ... )
It is possible to sprintf
a String.Buffer object
as %s just as if it was a string.
String.Buffer
res = String.Buffer()
+ what
String.Buffer()
+= what
int
add(string
|String.Buffer
... data
)
Adds data
to the buffer.
Returns the size of the buffer.
Pike 7.8 and earlier did not support adding String.Buffer
s
directly.
(int)String.Buffer()
(float)String.Buffer()
(string)String.Buffer()
(array)String.Buffer()
(mapping)String.Buffer()
(multiset)String.Buffer()
It is possible to cast a String.Buffer object to
a string
and an int
.
void
clear()
Empty the buffer, and don't care about the old content.
This function was not available in Pike 7.8 and earlier.
get()
String.Buffer String.Buffer(
int
initial_size
)
Initializes a new buffer.
If no initial_size
is specified, 256 is used. If you
know approximately how big the buffer will be, you can optimize
the operation of add()
(slightly) by passing the size to this
function.
string
get()
Get the data from the buffer.
This will clear the data in the buffer
get_copy()
, clear()
string
get_copy()
Get the data from the buffer. Significantly slower than get
,
but does not clear the buffer.
get()
void
putchar(int
c
)
Appends the character c
at the end of the string.
int
sprintf(strict_sprintf_format
format
, sprintf_args
... args
)
Appends the output from sprintf
at the end of the string.
Returns the resulting size of the String.Buffer.
An object of this class is returned by get_iterator()
when
called with a string.
get_iterator
inherit predef::Iterator : predef::Iterator
This is a "compiled" version of the replace
function applied on
a string, with more than one replace string. The replace strings
are given to the create method as a from and to array
and are then analyzed. The `()
is then called with a
string and the replace rules in the Replace object will be
applied. The Replace object is used internally by the Pike
optimizer and need not be used manually.
String.Replace decode_value(string(8bit) data)
string(8bit) encode_value(String.Replace data)
string
res = String.Replace()
()
String.Replace String.Replace()
String.Replace String.Replace(
mapping
(string
:string
))
String.Replace String.Replace(
array
(string
) from
, array
(string
)|string
to
)
This is a "compiled" version of the replace
function applied on
a string, with just one replace string. The replace strings are
given to the create method as a from and tom string and
are then analyzed. The `()
is then called with a string
and the replace rule in the Replace object will be applied. The
Replace object is used internally by the Pike optimizer and need
not be used manually.
String.SingleReplace decode_value(string(8bit) data)
string(8bit) encode_value(String.SingleReplace data)
string
res = String.SingleReplace()
()
String.SingleReplace String.SingleReplace(
string
|void
from
, string
|void
to
)
May be called with either zero or two arguments.
An iterator that iterates over substrings of a string, separated by a character or several different characters.
Typically you don't need to explicitly use the SplitIterator. Expressions like the following are automatically optimized into using a SplitIterator.
foreach(str/"\n", string line)
write("%s\n", line);
inherit predef::Iterator : predef::Iterator
String.SplitIterator String.SplitIterator(
string
buffer
, int
|array
(int
)|multiset
(int
) split_set
, int
|void
flags
, function
(:string
|zero
)|void
feed
)
buffer
The string to split.
split_set
The character or characters to split on.
flags
Skip empty elements if set.
feed
Callback function that is called once the buffer
is used up
and the SplitIterator wants more data.
string
elite_string(string
in
, int(0..100)
|void
leetp
, bool
|void
eightbit
)
Translates a string to 1337. The optional argument leetp is the maximum percentage of leetness (100=max leet, 0=no leet).
The translation is performed in three steps, first the necessary elite translations (picture -> pic, cool->kewl etc), then optional translations (ok->k, dude->dood, -ers -> -orz), then calls elite_word on the resulting words.
string
elite_word(string
in
, int(0..100)
|void
leetp
, int(0..2)
|void
eightbit
)
Translates one word to 1337. The optional argument leetp is the maximum percentage of leetness (100=max leet, 0=no leet). elite_word only do character-based translation, for instance from "k" to "|<", but no language translation (no "cool" to "kewl").
Functions that helps generating HTML. All functions generates HTML that is XHTML compliant as well as backwards compatible with old HTML standards in what extent is possible.
array
(array
(string
)) pad_rows(array
(array
(string
)) rows
, string
|void
padding
)
Pads out the rows in a array of rows to equal length. The new elements in
the rows will have the value provided in padding
, or " ".
string
select(string
name
, array
(string
)|array
(array
(string
)) choices
, void
|string
selected
)
Creates an HTML select list.
name
The name of the select list. Will be used in the name attribute of the select element.
choices
May either be an array of strings, where each string is a choice, or an array of pairs. A pair is an array with two strings. The first string is the value of the choice while the second string is the presentation text associated with the value.
selected
The value that should be selected by default, if any.
select("language", ({ ({ "eng", "English" }), ({ "swe", "Swedish" }), ({ "nor", "Norwegian" }) }), "swe");
string
simple_obox(array
(array
(string
)) rows
, void
|string
frame_color
, string
|void
cell_color
, void
|string
width
, void
|string
padding
, void
|function
(int
, int
, string
, string
:string
) cell_callback
)
This function should solve most of the obox needs that arises. It creates a table out of the array of arrays of strings fed into it. The tables will (with default settings) have a thin black outline around the table and between its cells. Much effort has gone into finding a simple HTML reresentation of such obox that is rendered in a similar way in all popular browsers. The current implementation has been tested against IE, Netscape, Mozilla, Opera and Konquest.
rows
Simply an array of arrays with strings. The strings are the values that should appear in the table cells. All rows should have equal number of cells, otherwise the result will not be very eye pleasing.
frame_color
The color of the surrounding frame. Defaults to "#000000".
cell_color
The background color of the cells. Defaults to "#ffffff".
width
The border width. Defaults to "1".
padding
The amount of padding in each cell. Defaults to "3".
cell_callback
If provided, the cell callback will be called for each cell. As in parameters it will get the current x and y coordinates in the table. The upper left cell is 0,0. In addition to the coordinates it will also receive the background color and the contents of the current cell. It is expected to return a td-element.
function cb = lambda(int x, int y, string bgcolor, string contents) { if(y%2) return "<td bgcolor='#aaaaff'>"+contents+"</td>"; return "<td bgcolor='"+bgcolor+"'>"+contents+"</td>"; } simple_obox(my_rows, "#0000a0", 0, "1", "3", cb);
pad_rows
Provides the same functionality as the simple_obox
function,
in a "streaming" way. The real gain is different addtition methods
as well as the possibility to change the cell callback at any time.
simple_obox
void
add_cell(string
contents
)
Adds a cell with the provided content.
void
add_raw_cell(string
cell
)
Adds this cell to the table unmodified, e.g. it should have an enclosing td or th element.
void
add_row(array
(string
) cells
)
Adds a complete row. If the current row is nonempty a new row will be started.
void
add_tagdata_cell(string
tag
, mapping
(string
:string
) args
, string
contents
)
Creates a cell from the provided arguments and adds it to the table.
tag
The name of the element that should be produces. Typically "td" or "th".
args
A mapping with the elements attributes.
contents
The element contents.
(int)String.HTML.OBox()
(float)String.HTML.OBox()
(string)String.HTML.OBox()
(array)String.HTML.OBox()
(mapping)String.HTML.OBox()
(multiset)String.HTML.OBox()
It is possible to case this object to a string, which does the same
as calling render
, and to an array, which returns the cells in an
array of rows.
String.HTML.OBox String.HTML.OBox(
void
|string
frame_color
, void
|string
cell_color
, void
|string
width
, void
|string
padding
, void
|function
(int
, int
, string
, string
:string
) cell_callback
)
void
new_row()
Begin a new row. Succeeding cells will be added to this row instead of the current.
void
pad_rows()
Ensures that all rows have the same number of cells.
string
render()
Returns the result.
void
set_cell_callback(function
(int
, int
, string
, string
:string
) cell_callback
)
void
set_extra_args(array
(mapping
(string
:string
)) extra_args
)
The argument in the mappings will be added to the cell in the cooresponding column of the table.
void
set_extra_args(mapping
(string
:string
) extra_args
)
The argument in the mapping will be added to all created table cells.
General functions to operate on arrays.
bool
all(array
a
, function
(int(0)
, mixed
... :mixed
) predicate
, mixed
... extra_args
)
Returns 1 if all of the elements in a
fulfills the requirement
predicate
( a
[i], @extra_args
), otherwise 0. The
predicate should return non-zero for an element that meets the
requirements and zero for those that do not.
Array.all( ({ 2, 4, 6, 8 }), `<, 17 )
any
, has_value
bool
any(array
a
, function
(__unknown__
, __unknown__
... :mixed
) predicate
, mixed
... extra_args
)
Returns 1 if any of the elements in a
fulfills the requirement
predicate
( a
[i], @extra_args
), otherwise 0. The
predicate should return non-zero for an element that meets the
requirements and zero for those that do not.
Array.any( ({ 2, 4, 6, 8 }), `>, 5 )
all
, has_value
array
arrayify(void
|array
|mixed
x
)
Make an array of the argument, if it isn't already. An undefined argument gives the empty array. This is useful when something is either an array or a basic datatype, for instance in headers from the MIME module or Protocols.HTTP.Server.
x
Result depends of the argument type:
arrayify(x) => x
arrayify(x) => ({})
arrayify(x) => ({ x })
array
(array
) columns(array
x
, array
ind
)
Get multiple columns from an array.
This function is equivalent to
map(ind, lambda(mixed i) { return column(x, i); })
column()
array
(array
) combinations(array
arr
, int(0..)
len
)
Returns an array of all combinations of length len
of
elements from arr
.
permute()
array
common_prefix(array
(array
) arrs
)
Find the longest common prefix from an array of arrays.
String.common_prefix
array
(array
(array
)) compact_diff3(array
a
, array
b
, array
old
)
Given three arrays like those returned from diff3
, this
function "compacts" the diff3 result by removing all differences
where a and b agrees against old. The result is
on the same form as the result from diff
, and doesn't
include the sequence from old.
int
count(array
|mapping
|multiset
haystack
, mixed
needle
)
mapping
(mixed
:int
) count(array
|mapping
|multiset
haystack
)
Returns the number of occurrences of needle
in haystack
.
If the optional needle
argument is omitted, count
instead
works similar to the unix command sort|uniq -c, returning
a mapping with the number of occurrences of each element in
haystack
. For array or mapping haystack
s, it's the values
that are counted, for multisets the indices, as you'd expect.
String.count
, search
, has_value
array
(array
(array
)) diff(array
a
, array
b
)
Calculates which parts of the arrays that are common to both, and which parts that are not.
Returns an array with two elements, the first is an array of parts in
array a
, and the second is an array of parts in array b
.
diff_compare_table()
, diff_longest_sequence()
,
String.fuzzymatch()
array
(array
(array
)) diff3(array
a
, array
b
, array
c
)
Return the three-way difference between the arrays.
Array.diff()
, Array.diff_longest_sequence()
array
(array
(int
)) diff_compare_table(array
a
, array
b
)
Returns an array which maps from index in a
to corresponding
indices in b
.
> Array.diff_compare_table( ({ "a","b","c" }), ({ "b", "b", "c", "d", "b" })); Result: ({ ({ }), ({ 0, 1, 4 }), ({ 2 }) })
diff()
, diff_longest_sequence()
, String.fuzzymatch()
array
(int
) diff_dyn_longest_sequence(array
a
, array
b
)
Gives the longest sequence of indices in b
that have corresponding
values in the same order in a
.
This function performs the same operation as diff_longest_sequence()
,
but uses a different algorithm, which in some rare cases might be faster
(usually it's slower though).
diff_longest_sequence()
, diff()
, diff_compare_table()
,
String.fuzzymatch()
array
(int
) diff_longest_sequence(array
a
, array
b
)
Gives the longest sequence of indices in b
that have corresponding
values in the same order in a
.
diff()
, diff_compare_table()
, String.fuzzymatch()
int(-1..1)
dwim_sort_func(string
a
, string
b
)
Sort strings containing numbers with respect to their values rather than according to their formatting (this most notably causes leading zeroes to be ignored/unnecessary).
"foo7" will be sorted before "foo27", which will be before "foo100".
array
(mixed
) everynth(array
(mixed
) a
, void
|int(1..)
n
, void
|int(0..)
start
)
Return an array with every n
:th element of the array a
.
If n
is zero every other element will be returned.
splice()
, `/()
array
flatten(array
a
, mapping
(array
:array
)|void
state
)
Flatten a multi-dimensional array to a one-dimensional array.
Prior to Pike 7.5.7 it was not safe to call this function with cyclic data-structures.
array
(array
(array
)) greedy_diff(array
from
, array
to
)
Like Array.diff
, but tries to generate bigger continuous chunks of the
differences, instead of maximizing the number of difference chunks. More
specifically, greedy_diff
optimizes the cases where Array.diff
returns
({ ..., A, Z, B, ({}), C, ... })
({ ..., A, X, B, Y+B, C, ... })
into the somewhat shorter diff arrays
({ ..., A, Z, B+C, ... })
({ ..., A, X+B+Y, B+C, ... })
array
(int
) interleave_array(array
(mapping
(int
:mixed
)) tab
)
Interleave a sparse matrix.
Returns an array with offsets that describe how to shift the
rows of tab
so that only at most one non-zero value exists in
every column.
array
(int
) longest_ordered_sequence(array
a
)
Find the longest ordered sequence of elements.
This function returns an array of the indices in the longest ordered sequence of elements in the array.
diff()
int(-1..1)
lyskom_sort_func(string
a
, string
b
)
Sort comparison function that does not care about case, nor about the contents of any parts of the string enclosed with '()'
Example: "Foo (bar)" is given the same weight as "foo (really!)"
int(-1..1)
oid_sort_func(string
a
, string
b
)
Sort with care of numerical sort for OID values, e.g. "1.2.1" before "1.11.1".
|
|
|
|
|
|
In Pike 7.6 and older this function returned 0
both when
a<b
and a==b
.
sort_array
array
(array
) partition(array
a
, function
(int(0)
, mixed
... :mixed
) arbiter
, mixed
... extra_args
)
Splits an array in two, according to an arbitration function
arbiter
. The elements in a
who return non-zero for the
expression arbiter
( a
[i], @extra_args
) end up in
the first sub-array, the others in the second. The order is
preserved from the original array.
Array.partition( enumerate( 9 ), lambda(int n) { return n>3 && n<7; } ); > ({ ({ 4, 5, 6 }), ({ 0, 1, 2, 3, 7, 8 }) })
filter
, `/
, `%
array
permute(array
in
, int(0..)
number
)
Give a specified permutation of an array.
The number of permutations is equal to sizeof(
(the factorial of the size of the given array).in
)!
shuffle()
array
pop(array
list
)
Pops and returns the last value of the array, shortening the array by one element. If there are no elements in the array then 0 is returned otherwise an array is returned where the first returned element is the popped value, and the second element is the modified array.
Array.pop(({ "a", "b", "c", "d" })); > ({ "d", ({ "a", "b", "c" }) })
ADT.Stack
, ADT.Stack.pop
, ADT.Stack.quick_pop
array
push(array
list
, mixed
element
)
Threats an Array as a stack and pushes the element onto the end.
Array.push(({ "a", "b", "c", "d" }), "e"); > ({ "a", "b", "c", "d", "e" })
ADT.Stack
, ADT.Stack.push
mixed
reduce(function
(:void
) fun
, array
arr
, mixed
|void
zero
)
reduce()
sends the first two elements in arr
to fun
,
then the result and the next element in arr
to fun
and
so on. Then it returns the result. The function will return
zero
if arr
is the empty array. If arr
has
only one element, that element will be returned.
rreduce()
mixed
rreduce(function
(:void
) fun
, array
arr
, mixed
|void
zero
)
rreduce()
sends the last two elements in arr
to fun
,
then the third last element in arr
and the result to fun
and
so on. Then it returns the result. The function will return
zero
if arr
is the empty array. If arr
has
only one element, that element will be returned.
reduce()
int
search_array(array
arr
, string
|function
(:void
)|int
fun
, mixed
... args
)
search_array()
works like map()
, only it returns the index
of the first call that returnes true instead.
If no call returns true, -1 is returned.
sum()
, map()
array
|zero
shift(array
list
)
Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array it returns 0. Returns an array where the first element is the shifted value and the second element is the modified array.
Array.shift(({ "a", "b", "c", "d"})); > ({ "a", ({ "b", "c", "d" }) })
ADT.Stack
array
shuffle(array
arr
)
shuffle()
gives back the same elements, but in random order.
The array is modified destructively.
permute()
array
sort_array(array
arr
, function
(:void
)|void
cmp
, mixed
... args
)
This function sorts the array arr
after a compare-function
cmp
which takes two arguments and should return 1
if the
first argument is larger then the second. Returns the sorted array
- arr
is not sorted destructively.
The remaining arguments args
will be sent as 3rd, 4th etc. argument
to cmp
.
If cmp
is omitted, `>()
is used instead.
map()
, sort()
, `>()
, dwim_sort_func
, lyskom_sort_func
,
oid_sort_func
array
(mixed
) splice(array
(mixed
) arr1
, array
(mixed
) arr2
, array
(mixed
) ... more_arrays
)
Splice two or more arrays.
This means that the returned array has the first element in the first given array, then the first argument in next array and so on for all arrays. Then the second elements are added, etc.
`/()
, `*()
, `+()
, `-()
, everynth()
mixed
sum(array
a
)
Sum the elements of an array using `+. The empty array results in 0.
array
sum_arrays(function
(int(0)
... :mixed
) sum
, array
... args
)
Applies the function sum
columnwise on the elements in the
provided arrays. E.g. sum_arrays(`+,a,b,c)
does the same
as `+(a[*],b[*],c[*])
.
array
(array
) transpose(array
(array
) matrix
)
Takes an array of equally sized arrays (essentially a matrix of size M*N) and returns the transposed (N*M) version of it, where rows and columns are exchanged for one another.
array
uniq(array
a
, function
(mixed
, mixed
:bool
)|void
cmp
)
Remove elements that are duplicates.
a
Array that may contain duplicate elements.
cmp
Function to use for comparing elements. If not specified, the
elements will be compared with `==()
and hashed
(cf lfun::__hash()
).
This function returns an copy of the array a
with all
duplicate values removed. The order of the values is kept in the
result; it's always the first of several equal elements that is
kept.
The cmp
argument is only available in Pike 9.1 and later.
The cmp
function MUST return non-zero for all element pairs
that predef::`==()
considers equal.
array
uniq2(array
a
)
Perform the same action as the Unix uniq command on an array, that is, fold consecutive occurrences of the same element into a single element of the result array:
aabbbcaababb -> abcabab.
See also the uniq
function.
array
unshift(array
list
, mixed
element
)
Does the opposite of "shift". Or the opposite of a "push", depending on how you look at it. Prepends the element to the front of the array and returns the new array.
Array.unshift(({ "b", "c", "d" }), "a"); > ({ "a", "b", "c", "d" })
ADT.Stack
An object of this class is returned by get_iterator()
when
called with an array.
get_iterator
inherit predef::Iterator : predef::Iterator
constant
Mapping.delete
Alias for m_delete()
An object of this class is returned by get_iterator()
when
called with a mapping.
get_iterator
inherit predef::Iterator : predef::Iterator
A mapping look-alike that overrides (ie shadows) another parent
mapping.
The class implements most of the usual mapping operations.
protected
mapping
|ShadowedMapping
Mapping.ShadowedMapping.parent
protected
local
void
__create__(mapping
|ShadowedMapping
parent
)
Mapping.ShadowedMapping Mapping.ShadowedMapping(
mapping
|ShadowedMapping
parent
, mapping
|ShadowedMapping
parent
, mapping
|void
shadow
, bool
|void
modify_parent
)
parent
Mapping to be shadowed.
shadow
Initial shadow of parent
.
modify_parent
Modifications should be done to parent
rather than
to shadow
. If this is set, only entries that are
already present in shadow
can be modified by later
operations.
Multiset handling.
An object of this class is returned by get_iterator()
when
called with a multiset.
get_iterator
inherit predef::Iterator : predef::Iterator
constant
Int.NATIVE_MIN
constant
Int.NATIVE_MAX
The limits for using the native representation of integers on the current architecture. Any integer that is outside this range uses a more complex and slower representation. Also, some builtin functions that don't expect very large integers might start to complain about invalid argument type when given values outside this range (they typically say something like "Expected integer, got object").
NATIVE_MIN
is not greater than -2147483648
(-0x80000000
).
NATIVE_MAX
is not less than 2147483647
(0x7fffffff
).
The size of the native integers can be controlled when Pike is
compiled with the configure flags --with-int-int
,
--with-long-int
, and --with-long-long-int
. The
default is to use the longest available integer type that fits
inside a pointer, which typically means that it's 64 bit on "true"
64 bit architectures.
Inf
Int.inf
An object that behaves like positive infinity.
Inf
Int.ninf
An object that behaves like negative infinity.
bool
parity(int(0..)
value
)
Returns the parity of the integer value
. If the
parity is odd 1 is returned. If it is even 0 is
returned.
int(0..)
reflect(int
value
, int(0..)
bits
)
Reverses the order of the low order bits
number of bits
of the value value
.
Any higher order bits of the value will be cleared. The returned value will thus be unsigned.
reverse()
, swap_word()
, swap_long()
int(32bit)
swap_long(int(32bit)
i
)
Swaps the upper and lower word in a longword, and the upper and lower bytes in the words. Simply put, the bytes are reversed.
swap_word()
int(16bit)
swap_word(int(16bit)
i
)
Swaps the upper and lower byte in a word.
swap_long()
The type of Int.inf
. Do not create more instances of this.
constant
Float.DIGITS_10
constant
Float.MIN_10_EXP
constant
Float.MAX_10_EXP
constant
Float.MIN
constant
Float.MAX
constant
Float.EPSILON
These constants define the limits for floats on the current architecture:
The number of decimal digits that can be represented. Any number
with this many decimal digits can be stored in a float and
converted back to decimal form without change. DIGITS_10
is
not less than 6
.
Limits of the exponent in decimal base. 10 raised to any number
within this range can be represented in normalized form.
MIN_10_EXP
is not greater than -37
. MAX_10_EXP
is
not less than 37
.
The smallest normalized float greater than zero. It's not
greater than 1e-37
.
The largest finite float. It's not less than 1e37
.
The difference between 1 and the smallest value greater than 1
that can be represented. It's not greater than 1e-5
.
The size of the float type can be controlled when Pike is compiled
with the configure flags --with-double-precision
and
--with-long-double-precision
. The default is to use the
longest available float type that fits inside a pointer.
constant
Float.FLOAT_PRECISION
constant
Float.DOUBLE_PRECISION
constant
Float.LONG_DOUBLE_PRECISION
Tells which C compiler float type that is used for Pike floats.
Only one of these constants will exist (with the value 1
)
at runtime.
The float
type of the C compiler is used.
The double
type of the C compiler is used.
The long double
type of the C compiler is used.
The float type can be controlled when Pike is compiled with the
configure flags --with-double-precision
and
--with-long-double-precision
. The default is to use the
longest available float type that fits inside a pointer.
bool
isnan(float
x
)
Returns true if x
is nan.
function
(:void
) Y(function
(:void
) f
)
The dreaded fixpoint combinator "Y".
The Y combinator is useful when writing recursive lambdas. It converts a lambda that expects a self-reference as its first argument into one which can be called without this argument.
This example creates a lambda that computes the faculty function.
Function.Y(lambda(function f, int n) { return n>1? n*f(n-1) : 1; })
this_function
void
call_callback(function
(:void
) f
, mixed
... args
)
Call a callback function, but send throws from the callback function (ie, errors) to master()->handle_error. Also accepts if f is zero (0) without error.
Functions.call_callback(the_callback,some,arguments);
equals
{ mixed err=catch { if (the_callback) the_callback(some,arguments); }; if (err) master()->handle_error(err); }
(Approximately, since call_callback also calls handle_error if 0 were thrown.)
function
(:void
) composite(function
(:void
) ... f
)
Creates a composite function of the provided functions. The
composition function of f() and g(), q(x)=f(g(x)), is created by
function q = Function.composite(f, g);
.
map(input/",", Function.composite(String.trim, upper_case));
function
(mixed
... :function
(mixed
... :mixed
|void
)) curry(function
(:void
) f
)
Partially evaluate a function call.
This function allows N parameters to be given to a function taking M parameters (N<=M), yielding a new function taking M-N parameters.
What is actually returned from this function is a function taking N parameters, and returning a function taking M-N parameters.
This example creates a function adding 7 to its argument.
Function.curry(`+)(7)
string
defined(function
(:void
) fun
)
Returns a string with filename and linenumber where fun
was defined.
Returns 0
(zero) when no line can be found, e.g. for
builtin functions and functions in destructed objects.
mixed
splice_call(array
args
, function
(:void
) f
, mixed
|void
... extra
)
Calls the given function with the args
array plus the optional
extra arguments as its arguments and returns the result.
Most useful in conjunction with map
, and particularly in combination
with sscanf
with "...%{...%}..."
scan strings (which indeed
was what it was invented for in the first place).
args
The first arguments the function f
expects.
f
The function to apply the arguments on.
extra
Optional extra arguments to send to f
.
Whatever the supplied function f
returns.
class Product(string name, string version) { string _sprintf() { return sprintf("Product(%s/%s)", name, version); } } map(({ ({ "pike", "7.1.11" }), ({ "whitefish", "0.1" }) }), Function.splice_call, Product); ({ /* 2 elements */ Product(pike/7.1.11), Product(whitefish/0.1) })
function
(mixed
... :mixed
) uncurry(function
(:void
) f
)
This function, given a function taking N parameters, returns a new function taking N+1 parameters. The first argument will be ignored.
> Function.uncurry(`+)(7,2,3) Result: 5
Partially evaluate a function call.
This function returns a function that when called will do the
specified argument mapping. It is similar to curry
, but allows
more dynamic changes of the argument evaluation, you can leave the
first argument unspecified while setting others, or simply change
the argument order.
f
The first argument is the function to be called.
bind_args
All other arguments are either a generic value, which will be sent
as-is to the function or one of the placeholder values defined in
Function.Placeholder
, or one of your own implementation (inherit
Function.Placeholder.Base
and implement the value function.).
This example returns a function that limits the given argument to between 0 and 99.
import Function.Placeholder; function clip = Function.bind(limit, 0, arg0, 100);
function
(:void
) Function.bind.f
array
(mixed
) Function.bind.bind_args
protected
local
void
__create__(function
(:void
) f
, mixed
... bind_args
)
Function.bind Function.bind(
function
(:void
) f
, mixed
... bind_args
)
Placeholder arguments for Function.bind
constant
Function.Placeholder.arg0
constant
Function.Placeholder.arg1
constant
Function.Placeholder.arg2
constant
Function.Placeholder.arg3
constant
Function.Placeholder.arg4
constant
Function.Placeholder.arg5
constant
Function.Placeholder.arg6
constant
Function.Placeholder.arg7
constant
Function.Placeholder.arg8
constant
Function.Placeholder.arg9
arg<n> will return an instance of Arg
that returns the n:th arg.
For convenience for c++11 developers _0, _1 etc also works.
Note that arg0 is the first argument, not arg1
Arg
Function.Placeholder.rest
Return all arguments not used by any Arg
or Splice
.
Unlike Splice
this will return non-continous unused arguments.
This creates a version of call_out that has the function argument as the last argument
import Function.Placeholder; Function.bind( call_out, Arg(-1), rest)
Arg(x) returns the value of argument X
inherit Base : Base
int
Function.Placeholder.Arg.num
protected
local
void
__create__(int
num
)
Function.Placeholder.Arg Function.Placeholder.Arg(
int
num
)
mixed
value(bind
x
, array
args
)
The function that is called to return the argument value.
Expr(x) returns the result of calling x
.
The function will be passed the list of arguments.
If _splice is true, zero or more argument is returned in an array
Function.Placeholder.arg1 is thus more or less equivalent to
Expr(lambda(array args){return args[1];});
inherit Base : Base
function
(:void
) Function.Placeholder.Expr.func
void
|bool
Function.Placeholder.Expr._splice
protected
local
void
__create__(function
(:void
) func
, void
|bool
_splice
)
Function.Placeholder.Expr Function.Placeholder.Expr(
function
(:void
) func
, void
|bool
_splice
)
Splice(from) adds all arguments starting with argument number from
,
optionally ending with end.
Equivalent to args[from .. end]
inherit Base : Base
int
Function.Placeholder.Splice.from
void
|int
Function.Placeholder.Splice.end
protected
local
void
__create__(int
from
, void
|int
end
)
Function.Placeholder.Splice Function.Placeholder.Splice(
int
from
, void
|int
end
)
array
(program
) all_inherits(program
p
)
Enumerate all programs this program inherits, directly or indirectly. Similar to inherit_tree() but returns a flat array.
> class a{} > class b{} > class c{ inherit a; } > class d{ inherit b; inherit c; } > Program.inherit_tree(d); Result: ({ /* 3 elements */ b, c, a })
multiset
(Pike.Annotation
) annotations(program
x
, bool
|void
no_recurse
)
Return a multiset with the annotations for all symbols in x
attached
to this program.
x
Program whose identifiers should be returned.
no_recurse
Do not include annotations recursively added via inherits.
Returns an multiset with annotations added directly to this program.
This function was added in Pike 8.1.
indices()
, values()
, types()
, lfun::_annotations()
,
::_annotations()
string
defined(program
p
)
Returns a string with filename and linenumber describing where
the program p
was defined.
The returned string is of the format "filename:linenumber"
.
If it cannot be determined where the program was defined, 0
(zero) will be returned.
string
|zero
defined(program
x
, string
identifier
)
Returns a string with filename and linenumber where identifier
in x
was defined.
Returns 0
(zero) when no line can be found, e.g. for
builtin functions.
If identifier
can not be found in x
this function returns
where the program is defined.
int
implements(program
prog
, program
api
)
Returns 1 if prog
implements api
.
array
(program
) inherit_list(program
p
)
Returns an array with the programs that p
has inherited.
array
inherit_tree(program
p
)
Recursively builds a inheritance tree by fetching programs inheritance lists.
Returns an array with programs or arrays as elements.
> class a{} > class b{} > class c{ inherit a; } > class d{ inherit b; inherit c; } > Program.inherit_tree(d); Result: ({ /* 3 elements */ d, ({ /* 1 element */ program }), ({ /* 2 elements */ c, ({ /* 1 element */ program }) }) })
int
inherits(program
|object
child
, program
parent
)
Returns 1 if child
has inherited parent
.
Various Abstract Data Types.
inherit _ADT : _ADT
Implements a FIFO bit buffer, i.e. a buffer that operates on bits instead of bytes. It is not designed for performance, but as a way to handle complicated file formats and other standards where you may need to work on unaligned data units of sub byte size, without having to fry your brain while keeping track of all the bits yourself.
> ADT.BitBuffer b=ADT.BitBuffer(); > b->put1(2); (1) Result: ADT.BitBuffer(11) > b->put0(15); (2) Result: ADT.BitBuffer("\300\0"0) > b->drain(); (3) Result: "\300\0" > sizeof(b); (4) Result: 1
int
sizeof( ADT.BitBuffer arg )
sizeof()
will return the number of bits in the buffer.
ADT.BitBuffer ADT.BitBuffer(
void
|string
data
)
The buffer can be initialized with initial data during creation.
string
drain()
Drains the buffer of all full (8-bits wide) bytes.
this_program
feed(string
x
)
Adds full bytes to the buffer.
int
get(int
bits
)
Get bits
from the buffer.
Throws an error in case of data underflow.
The bits are extracted with the most significant bit first.
this_program
put(int
value
, int
bits
)
Put bits
number of bits with the value value
into the
buffer.
value
must not be larger than what can be stored with the
number of bits given in bits
.
The bits are added to the buffer with the most significant bit first.
this_program
put0(int
bits
)
Put bits
number of 0 bits into the buffer.
this_program
put1(int
bits
)
Put bits
number of 1 bits into the buffer.
string
read(void
|int
bytes
)
Reads bytes
(or less) bytes from the buffer and returns as
string.
This is an circular list implemented by an array. It has a constant time
complexity for pop and push. It has a limited max size but it can be
increased with the methods allocate()
or [set_max_size()].
bool
equal(ADT.CircularList from, mixed
coll
)
Returns true if the object coll
is a CircularList
and contains the same values in the same order.
ADT.CircularList a;
foreach( a; index; value ) orCircularListIterator
_get_iterator(void
|int
ind
)
Create and initiate a new CircularListIterator that could be used to iterate over this list.
ind
If an ind
value is supplied the iterator will be positioned at
that index.
An iterator.
array
indices( ADT.CircularList arg )
The indices in this list as an array.
void
_insert_element(int
index
, mixed
value
)
Insert an element in the list at the position index
, the value
at the position index
and all above will have their index increased
by one.
index
The index to insert the value at.
value
The new value.
An error if the index is out of range.
The max_size
is increased by one.
_remove_element()
void
_m_clear()
Clear the contents of the list.
clear()
mixed
_remove_element(int
index
)
Remove the values at index index
from the list.
index
The index to remove.
The removed value.
An error if the index is out of range.
The max_size
is decreased by one.
_insert_element()
int
search(ADT.CircularList from, mixed
value
, void
|int
start
)
Search the list for a specific value. Return the index of the first
value that is equal to value
. If no value was found UNDEFINED
is returned instead
value
The value to find
start
If a start value is supplied it will start searching at the index
start
.
Returns the index of the found value or -1
.
An error if the start is out of range.
int
sizeof( ADT.CircularList arg )
The number of elements in this list.
array
values( ADT.CircularList arg )
The values in this list as an array.
CircularList
res = ADT.CircularList()
+ coll
Addition operator
Append the content of this CircularList and @coll
and
return the results as a new CircularList
.
coll
The lists to append to this list
The result of the append as a new CircularList
.
mixed
res = ADT.CircularList()
[ index
]
Index operator
index
The index to get the value for, may be negative to index from the end.
The value at the index index
An error if the index is out of range.
ADT.CircularList()
[ index
] = value
Index assign operator.
Set the value at the index index
to be value
index
The index to set
value
The new value
The new value at the index index
An error if the index is out of range.
void
add(mixed
value
, bool
|void
force
)
Add a value at the front of the list
value
The value to add.
force
Add the value even if the list is full, in which case the element at the back of the list will be removed.
An error if the list is full and force
is false.
force
was not supported in Pike 8.0.1800 and earlier.
This is the same operation as push_front()
.
push_back()
, push_front()
void
allocate(int
elements
)
Increase the maxsize of the CircularlList.
elements
Add this number of new elements to the list.
set_max_size()
(
array
)ADT.CircularList()
Cast operator.
type
Casts to this type.
Casts to the following types are supported:
| Cast the content of this list to an array. |
An array with the contents of this list.
void
clear()
Clear the contents of the list.
Replaced by _m_clear
.
ADT.CircularList ADT.CircularList(
array
|int
arg
)
Creates a new CircularList
around the array arg or a new
CircularList
with the maximum size of arg.
int
delete_value(mixed
value
)
Remove the first occurrence of the value value
from the list.
value
The value to remove from the list.
The index of the removed element or -1 if there was no value to remove.
__deprecated__
CircularListIterator
first()
Create and initiate a new CircularListIterator that could be used to iterate over this list.
An iterator positioned before the first element of the list.
Replaced by _get_iterator
.
With the Pike 8.1 and later iterator API this is identical
to last()
and _get_iterator()
.
_get_iterator()
, last()
bool
is_empty()
Returns 1
if the list is empty otherwise 0
.
__deprecated__
CircularListIterator
last()
Create and initiate a new CircularListIterator that could be used to iterate over this list.
An iterator positioned after the last element of the list.
Replaced by _get_iterator
.
With the Pike 8.1 and later iterator API this is identical
to first()
and _get_iterator()
.
_get_iterator()
, first()
int
max_size()
Returns the maximal size of this list.
set_max_size()
mixed
peek_back()
The value at the back of the list but do not remove it from the list.
mixed
peek_front()
The value at the front of the list but do not remove it from the list.
mixed
pop_back()
Remove the value at the back of the list and return it.
The value at the back of the list.
mixed
pop_front()
Remove the value at the front of the list and return it.
The value at the front of the list.
void
push_back(mixed
value
, bool
|void
force
)
Add a new value at the end of the list.
value
The value to add.
force
Add the value even if the list is full, in which case the element at the front of the list will be removed.
An error if the list is full and force
is false.
force
was not supported in Pike 8.0.1800 and earlier.
add()
, push_front()
void
push_front(mixed
value
, bool
|void
force
)
Add a new value at the front of the list.
value
The value to add.
force
Add the value even if the list is full, in which case the element at the back of the list will be removed.
An error if the list is full and force
is false.
force
was not supported in Pike 8.0.1800 and earlier.
This is the same operation as add()
.
add()
, push_back()
int
set_max_size(int(0..)
new_size
)
new_size
The new size of the list.
Returns the old maximal size of the list.
When reducing in size, elements that no longer fit are dropped from the back.
allocate()
, max_size()
This is the iterator for the CircularList. It implements the IndexIterator and the OutputIterator.
bool
equal(ADT.CircularList.CircularListIterator from, mixed
iter
)
Compare this iterator with another iterator.
iter
The iterator to compare with
Returns true if both iterators iterates over the same objects and are positioned at the same spot.
int
_iterator_index()
The index at the current position.
mixed
_iterator_value()
The value at the current position.
CircularListIterator
res = ADT.CircularList.CircularListIterator()
+ steps
Move the iterator steps
steps forward (negative value on steps
will cause the iterator to move backwards) and return the result
as a new iterator.
A new iterator positioned steps
steps forward.
ADT.CircularList.CircularListIterator()
+= steps
Move this iterator steps
steps forward (negative value on steps
will cause the iterator to move backwards) and return the result.
This iterator positioned steps
steps forward.
CircularListIterator
res = ADT.CircularList.CircularListIterator()
- steps
Move the iterator steps
steps backwards (negative value on
steps
will cause the iterator to move forwards) and return
the result as a new iterator.
A new iterator positioned steps
steps backwards.
bool
res = ADT.CircularList.CircularListIterator()
< iter
Less then operator
Returns true if this iterator has a lower index
then iter
.
bool
res = ADT.CircularList.CircularListIterator()
> iter
Greater then operator
Returns true if this iterator has a higher index
then iter
.
ADT.CircularList.CircularListIterator ADT.CircularList.CircularListIterator(
object
list
, void
|int
start
)
Creates a new iterator for the CircularList list
. If start
is
supplied it will try to position the iterator at start
.
int
distance(object
iter
)
iter
The iterator to measure the distance to.
Returns distance between this iterator and iter
.
An error if the two iterator could not be compared.
This operation is only valid if both iterators are
for the same CircularList
object.
CircularList
get_collection()
Returns the CircularList this iterator currently iterates over.
bool
has_next(void
|int
steps
)
Returns true if it is possible to move steps
steps
forwards, if steps
weren't supplied it check if it is
possible to move one step forward.
bool
has_previous(void
|int
steps
)
Returns true if it is possible to move steps
steps
backwards, if steps
weren't supplied it check if it is
possible to move one step backward.
mixed
set_value(mixed
val
)
Set the value at the current position.
val
The new value
Returns the old value
This class implements a (min-)heap. The value of a child node will always be greater than or equal to the value of its parent node. Thus, the top node of the heap will always hold the smallest value.
__generic__
mixed
ValueType
= mixed
Type for the values on the heap.
int
sizeof( ADT.Heap arg )
Returns the number of elements in the heap.
Element
adjust(ValueType
|Element
value
)
Takes a value in the heap and sorts it through the heap to maintain its sort criteria (increasing order).
value
Either the element handle returned by push()
, or the pushed
value itself.
Returns the element handle for the value (if present in the heap),
and 0
(zero) otherwise.
Element
low_peek()
Returns the Element
on top of the heap (which is also the one with
the smallest value in the heap) without removing it.
Returns the smallest Element
on the heap if any, and
UNDEFINED
otherwise.
peek()
, low_pop()
, pop()
Element
low_pop()
Removes and returns the Element
on top of the heap,
which also is the smallest value in the heap.
Returns UNDEFINED
if the heap is empty.
pop()
, peek()
, push()
, remove()
ValueType
peek()
Returns the item on top of the heap (which is also the smallest value in the heap) without removing it.
Returns the smallest value on the heap if any, and
UNDEFINED
otherwise.
low_peek()
, pop()
ValueType
pop()
Removes and returns the item on top of the heap, which also is the smallest value in the heap.
Throws an error if the heap is empty.
low_pop()
, peek()
, push()
, remove()
Element
push(ValueType
|Element
value
)
Push an element onto the heap. The heap will automatically sort itself so that the smallest value will be at the top.
Returns an element handle, which can be used with
adjust()
and remove()
.
If value
is a Heap.Element
and already present on the heap
this is equivalent to calling adjust()
.
pop()
, remove()
void
remove(ValueType
|Element
value
)
Remove a value from the heap.
value
Value to remove.
push()
, pop()
Heap element.
__generic__
mixed
ValueType
= ValueType
ValueType
ADT.Heap.Element.value
protected
local
void
__create__(ValueType
value
)
ADT.Heap.Element ADT.Heap.Element(
ValueType
value
)
A history is a stack where you can only push entries. When the stack has reached a certain size the oldest entries are removed on every push. Other proposed names for this data type is leaking stack and table (where you push objects onto the table in one end and objects are falling off the table in the other.
__generic__
mixed
ValueType
= mixed
Type for the individual elements on the history stack.
array
(int
) indices( ADT.History arg )
Returns the index numbers of the history entries available.
int
sizeof( ADT.History arg )
A sizeof
operation on this object returns the number
of elements currently in the history, e.g. <= the current
max size.
array
(ValueType
) values( ADT.History arg )
Returns the values of the available history entries.
ValueType
res = ADT.History()
[ i
]
Get a value from the history as if it was an array, e.g. both positive and negative numbers may be used. The positive numbers are however offset with 1, so [1] is the first entry in the history and [-1] is the last.
ADT.History()
[ i
] = value
Overwrite one value in the history. The history position may be
identified either by positive or negative offset, like `[]
.
ADT.History ADT.History(
int(0..)
max_size
)
max_size
is the maximum number of entries that can reside in the
history at the same time.
void
flush()
Empties the history. All entries in the history are removed, to allow garbage collect to remove them. The entry sequence counter is not reset.
int
get_first_entry_num()
Returns the absolute sequence number of the oldest result still in the history. Returns 0 if there are no results in the history.
int
get_latest_entry_num()
Returns the absolute sequence number of the latest result inserted into the history.
int
get_maxsize()
Returns the maximum number of values in the history
set_maxsize
void
push(ValueType
value
)
Push a new value into the history.
bool
query_no_adjacent_duplicates()
Tells if the History object allows adjacent equal values. 1 means that only uniqe values are allowed adter each other.
set_no_adjacent_duplicates
void
set_maxsize(int
_maxsize
)
Set the maximume number of entries that can be stored in the history simultaneous.
get_maxsize
void
set_no_adjacent_duplicates(bool
i
)
Change how the History object should treat two identical values in a row. If 1 than only unique values are allowed after each other.
query_no_adjacent_duplicates
__generic__
mixed
RangeType
= mixed
Type for the limits of the interval.
Boundary
ADT.Interval.a
Boundary
ADT.Interval.b
RangeType
ADT.Interval.start
RangeType
ADT.Interval.stop
int
|float
sizeof( ADT.Interval arg )
string sprintf(string format, ... ADT.Interval arg ... )
this_program
|zero
res = ADT.Interval()
& i
this_program
res = ADT.Interval()
+ i
this_program
|zero
res = ADT.Interval()
- interval
bool
res = ADT.Interval()
== i
this_program
res = ADT.Interval()
| i
RangeType
beginning()
this_program
clone(mixed
... args
)
bool
contains(RangeType
|this_program
x
)
ADT.Interval ADT.Interval(
RangeType
|Boundary
a
, RangeType
|Boundary
b
)
RangeType
end()
Boundary
max(Boundary
a
, Boundary
b
)
Boundary
min(Boundary
a
, Boundary
b
)
bool
overlaps(this_program
i
)
bool
touches(this_program
i
)
__generic__
mixed
RangeType
= RangeType
int
ADT.Interval.Boundary.ux
Read only
RangeType
ADT.Interval.Boundary.x
protected
local
void
__create__(RangeType
x
)
string sprintf(string format, ... ADT.Interval.Boundary arg ... )
RangeType
res = ADT.Interval.Boundary()
- b
bool
res = ADT.Interval.Boundary()
< b
bool
res = ADT.Interval.Boundary()
> b
Boundary
res = ~ADT.Interval.Boundary()
ADT.Interval.Boundary ADT.Interval.Boundary(
RangeType
x
)
int
unix_time()
__generic__
mixed
RangeType
= RangeType
inherit Boundary(<
RangeType
>) : Boundary
string sprintf(string format, ... ADT.Interval.Closed arg ... )
bool
res = ADT.Interval.Closed()
== b
Boundary
res = ~ADT.Interval.Closed()
bool
overlaps(RangeType
|Boundary
b
)
bool
touches(RangeType
|Boundary
b
)
__generic__
mixed
RangeType
= RangeType
inherit Boundary(<
RangeType
>) : Boundary
string sprintf(string format, ... ADT.Interval.Open arg ... )
bool
res = ADT.Interval.Open()
< b
bool
res = ADT.Interval.Open()
== b
bool
res = ADT.Interval.Open()
> b
Boundary
res = ~ADT.Interval.Open()
bool
overlaps(RangeType
|Boundary
b
)
bool
touches(Boundary
b
)
Linked list of values.
protected
List
_reverse()
Reverse the list.
reverse()
int(0..)
sizeof( ADT.List arg )
Returns the number of elements in the list.
string sprintf(string format, ... ADT.List arg ... )
Describe the list.
sprintf()
, lfun::_sprintf()
array
values( ADT.List arg )
Returns an array of elements in the list.
mixed
res = ADT.List()
[ key
]
void
append(mixed
... values
)
Append values
to the end of the list.
insert()
(
array
)ADT.List()
Cast the lists. array
is the only
supported type.
ADT.List ADT.List(
mixed
... values
)
Create a new List
, and initialize it with values
.
void
flush()
Empties the List.
mixed
head()
Get the element at the head of the list.
Throws an error if the list is empty.
is_empty()
, tail()
, pop()
void
insert(mixed
... values
)
Insert values
at the front of the list.
append()
bool
is_empty()
Check if the list is empty.
Returns 1
if the list is empty,
and 0
(zero) if there are elements in the list.
mixed
pop()
Pop the element at the head of the list from the list.
Throws an error if the list is empty.
is_empty()
, head()
, tail()
, pop_back()
mixed
pop_back()
Pop the element at the tail of the list from the list.
Throws an error if the list is empty.
is_empty()
, head()
, tail()
, pop()
mixed
tail()
Get the element at the tail of the list.
Throws an error if the list is empty.
is_empty()
, head()
, pop_back()
Iterator
that loops over the List
.
protected
mixed
_iterator_next()
Advance to the next element in the list.
Returns the new element on success, and UNDEFINED
at the end of the list.
prev()
protected
mixed
_iterator_value()
Returns the value at the current position.
ADT.List._get_iterator()
+= steps
Advance or retrace the specified number of steps
.
next()
, prev
void
append(mixed
val
)
Append val
after the current position.
insert()
, delete()
, set()
_get_iterator
copy_iterator()
Returns a copy of the iterator at its current position.
void
delete()
Delete the current node.
The current position will advance to the next node.
This function thus performes the reverse operation
of insert()
.
insert()
, append()
, set()
bool
first()
Reset the iterator to point to the first element in the list.
Returns 1
if there are elements in the list,
and 0
(zero) if the list is empty.
void
insert(mixed
val
)
Insert val
at the current position.
append()
, delete()
, set()
bool
next()
Advance to the next element in the list.
Returns 1
on success, and 0
(zero)
at the end of the list.
prev()
bool
prev()
Retrace to the previous element in the list.
Returns 1
on success, and 0
(zero)
at the beginning of the list.
next()
void
set(mixed
val
)
Set the value of the current position to val
.
insert()
, append()
, delete()
mixed
value()
Returns the value at the current position.
This class works pretty much as a mapping except the order of the indices is kept in the order they are added. This class works equivalent to the Map() class in Javascript.
OrderedMapping m1 = OrderedMapping("foo", 1, "bar", 2); m1->gazonk = 3; foreach (m1; string key; int val) { write("# %s: %d\n", key, val); } /* output: # foo: 1 # bar: 2 # gazonk: 3 */ m_delete(m1, "gazonk"); m1 += OrderedMapping("afoo", 3); foreach (m1; string key; int val) { write("# %s: %d\n", key, val); } /* output: # foo: 1 # bar: 2 # afoo: 3 */
__generic__
mixed
IndexType
= mixed
Type for the indices of the mapping.
__generic__
mixed
ValueType
= mixed
Type for the values of the mapping.
(
mapping
)ADT.OrderedMapping()
(array
)ADT.OrderedMapping()
Cast the object into various other types.
This method can not be called on the object. A proper (cast)
has
to be done.
how
| Will return a |
| Will return an |
| Will return the indices as a |
| Will return the |
ADT.OrderedMapping ADT.OrderedMapping(
IndexType
|ValueType
... args
)
ADT.OrderedMapping m1 = ADT.OrderedMapping("key1", "val1", "key2", "val2");
An error is thrown if the number of arguments isn't even.
args
Odd arguments are the indices, even arguments the values.
"index", "value", "index", "value", ...
ADT.OrderedMapping ADT.OrderedMapping(
array
(IndexType
) keys
, array
(ValueType
) values
)
ADT.OrderedMapping m1 = ADT.OrderedMapping(({ "key1", "key2" }), ({ "val1", "val2" }));
And error is thrown if the size of the keys
and values
doens't match.
keys
values
This class implements a priority queue. Each element in the priority queue is assigned a priority value, and the priority queue always remains sorted in increasing order of the priority values. The top of the priority queue always holds the element with the smallest priority. The priority queue is realized as a (min-)heap.
__generic__
mixed
ValueType
= mixed
Type for the individual elements in the queue.
inherit .Heap(<
ValueType
>) : Heap
void
adjust_pri(elem
handle
, int
|float
new_pri
)
Adjust the priority value new_pri
of an element handle
in the
priority queue. The priority queue will automatically sort itself so
that the element with the smallest priority value will be at the top.
ValueType
peek()
Returns the item on top of the priority queue (which is also the element with the smallest priority value) without removing it.
ValueType
pop()
Removes and returns the item on top of the heap, which also is the smallest value in the heap.
elem
push(int
|float
pri
, ValueType
val
)
Push an element val
into the priority queue and assign a priority value
pri
to it. The priority queue will automatically sort itself so that
the element with the smallest priority will be at the top.
A simple FIFO queue.
__generic__
mixed
ValueType
= mixed
Type for the individual elements in the queue.
(
array
(ValueType
))ADT.Queue()
It is possible to cast ADT.Queue to an array.
ADT.Queue ADT.Queue(
ValueType
... args
)
Creates a queue with the initial items args
in it.
void
flush()
Empties the queue.
ValueType
get()
Returns the next element from the queue, or UNDEFINED
if
the queue is empty.
peek()
, put()
bool
is_empty()
Returns true if the queue is empty, otherwise zero.
ValueType
|zero
peek()
Returns the next element from the queue without removing it from
the queue. Returns UNDEFINED
if the queue is empty.
Prior to Pike 9.0 this function returned a plain 0
when the queue was empty.
get()
, put()
void
put(ValueType
... items
)
Adds items
to the queue.
get()
, peek()
__deprecated__
ValueType
read()
Replaced by get
.
__deprecated__
void
write(ValueType
... items
)
Replaced by put
.
This class implements a quantized resource scheduler.
Weighted consumers are added to the scheduler with add()
,
which returns a Consumer
object.
When there's some of the resource available to be consumed
the resource owner calls get()
, which returns the
Consumer
that is to use the resource. Consumer()->consume()
is then called with the fraction of the quanta that was consumed
(typically 1.0
). The amount of resources allocated to a
consumer is proportional to the weight of the consumer.
A consumer may be temporarily deactivated (in which case it won't
be returned by get()
, but still retain its share of the resource
which will be provided later by get()
when it has been reactivated.
protected
inherit .Heap : Heap
Consumer
add(Consumer
c
)
(Re-)activate a Consumer
.
variant
Consumer
add(int
|float
weight
, mixed
val
)
Create a Consumer
with the weight weight
for the value val
,
and add it to the Scheduler.
void
adjust_weight(Consumer
c
, int
new_weight
)
Adjust the weight value new_weight
of the Consumer
c
in the
scheduling table.
Consumer
get()
Returns the next Consumer
to consume some of the resource.
Returns a Consumer
if there are any active Consumers
and UNDEFINED
otherwise.
The same Consumer
will be returned until it has either
consumed some of the resource, been removed or another
Consumer
with lower priority has been added.
void
remove(Consumer
c
)
Remove the Consumer
c
from the set of active consumers.
The consumer may be reactivated by calling add()
.
constant
ADT.Scheduler.STATE_ACTIVE
A resource consumer.
Active consumers are kept in a (min-)Heap
.
inherit Element : Element
float
ADT.Scheduler.Consumer.pri
Accumulated deltas and initial priority.
Typically in the range 0.0 .. 2.0
, but may temporarily
be outside of the range.
void
ADT.Scheduler.Consumer.weight
Getting
Get the weight of the consumer.
Setting
Get the weight of the consumer.
void
consume(float
delta
)
Consume some of the resource.
delta
Share of the resource quanta that was actually consumed.
Typically 1.0
, but other values are supported.
This causes the consumer to be reprioritized.
ADT.Scheduler.Consumer ADT.Scheduler.Consumer(
int
|float
weight
, mixed
v
)
The sequence work similar to an array but has the possibility to insert and remove elements. It also has a more powerful iterator.
bool
equal(ADT.Sequence from, mixed
coll
)
Returns true if the object coll
is a Sequence
and contains the same values in the same order.
ADT.Sequence a;
foreach( a; index; value ) orSequenceIterator
_get_iterator(void
|int
ind
)
Create and initiate a new SequenceIterator that could be used to iterate over this sequence.
ind
If an ind
value is supplied the iterator will be positioned at
that index.
An iterator.
array
indices( ADT.Sequence arg )
The indices in this sequence as an array.
void
_insert_element(int
index
, mixed
value
)
Insert an element in the sequence at the position index
, the value
at the position index
and all above will have their index increased
by one.
index
The index to insert the value at.
value
The new value.
mixed
_remove_element(int
index
)
Remove the values at index index
from the sequence.
index
The index to remove.
The removed value.
int
search(ADT.Sequence from, mixed
value
, void
|int
start
)
Search the sequence for a specific value. Return the index of the first
value that is equal to value
. If no value was found UNDEFINED
is returned instead.
value
The value to find.
start
If a start value is supplied it will start searching at the index
start
.
Returns the index of the found value or UNDEFINED
.
int
sizeof( ADT.Sequence arg )
The number of elements in this sequence.
array
values( ADT.Sequence arg )
The values in this sequence as an array.
Sequence
res = ADT.Sequence()
& coll
And operator
Perform an and on this sequence and the coll
sequence by only returning
those values that is present in both sequences as a new Sequence
.
The remaining values is in the same order as they are in this sequence and
the values are compared using `==.
coll
The sequence to and to this sequence.
The result of the and as a new Sequence
.
Sequence
res = ADT.Sequence()
+ coll
Addition operator
Append the content of @coll
to this sequence and return the results
as a new Sequence
.
coll
The sequences to append to this sequence.
The result of the append as a new Sequence
.
Sequence
res = ADT.Sequence()
- coll
Subtraction operator
Removes those values in this sequence that also are present in @coll
and return the results as a new Sequence
.
coll
The sequence to subtract from this sequence.
The result of the subtraction as a new Sequence
.
mixed
res = ADT.Sequence()
[ index
]
Index operator.
index
The index to get the value for, could be negative to index from the end.
The value at the index index
.
An error if the index is out of range.
ADT.Sequence()
[ index
] = value
Index assign operator.
Set the value at the index index
to be value
.
index
The index to set.
value
The new value.
The new value at the index index
.
Sequence
res = ADT.Sequence()
^ coll
Xor operator
Perform a xor on this sequence and the coll
sequence by returning
those values that is present in one of the sequences but not in both
sequences as a new Sequence
.
The values are compared using `==.
coll
The sequence to xor with this sequence.
The result of the xor as a new Sequence
.
Sequence
res = ADT.Sequence()
| coll
Or operator
Perform an or on this sequence and the coll
sequence by returning
those values that is present in both sequences as a new Sequence
.
The values are compared using `==.
coll
The sequence to or with this sequence.
The result of the or as a new Sequence
.
void
add(mixed
value
)
Add a value at the end of the sequence.
value
The value to add.
(
array
)ADT.Sequence()
Cast operator.
type
Casts to this type.
Casts to the following types are supported:
| Cast the content of this sequence to an array. |
An array with the contents of this sequence.
void
clear()
Clear the contents of the sequence.
ADT.Sequence ADT.Sequence(
array
|int
arg
)
Creates a new Sequence
around the array arg or a new
Sequence
with the size of arg.
int
delete_value(mixed
value
)
Remove the first occurrence of the value value
from the sequence.
value
The value to remove from the sequence.
The index of the removed element or -1 if there was no value to remove.
SequenceIterator
first()
Create and initiate a new SequenceIterator that could be used to iterate over this sequence.
An iterator positioned at the first element in the sequence.
bool
is_empty()
Returns 1
if the sequence is empty otherwise 0
.
SequenceIterator
last()
Create and initiate a new SequenceIterator that could be used to iterate over this sequence.
An iterator positioned after the last element in the sequence.
int
max_size()
Returns -1.
This is the iterator for the Sequence. It implements the IndexIterator and the OutputIterator
bool
equal(ADT.Sequence.SequenceIterator from, mixed
iter
)
Compare this iterator with another iterator.
iter
The iterator to compare with.
Returns true if both iterators iterates over the same objects and are positioned at the same spot.
int
_iterator_index()
The index at the current position.
int
_iterator_next()
Advance to the next position in the sequence.
Returns the new position, or UNDEFINED
if
the end of the sequence is reached.
Calling this function when the end of the sequence has already been reached restarts the iterator at the first element of the sequence (if any).
mixed
_iterator_value()
The value at the current position.
SequenceIterator
res = ADT.Sequence.SequenceIterator()
+ steps
Move the iterator steps
steps forward (negative value on steps
will cause the iterator to move backwards) and return the result
as a new iterator.
A new iterator positioned steps
steps forward.
ADT.Sequence.SequenceIterator()
+= steps
Move this iterator steps
steps forward (negative value on steps
will cause the iterator to move backwards) and return the result.
This iterator positioned steps
steps forward.
SequenceIterator
res = ADT.Sequence.SequenceIterator()
- steps
Move the iterator steps
steps backwards (negative value on
steps
will cause the iterator to move forwards) and return
the result as a new iterator.
A new iterator positioned steps
steps backwards.
bool
res = ADT.Sequence.SequenceIterator()
< iter
Less then operator.
Returns true if this iterator has a lower index
then iter
.
bool
res = ADT.Sequence.SequenceIterator()
> iter
Greater then operator.
Returns true if this iterator is at a higher index
than iter
.
ADT.Sequence.SequenceIterator ADT.Sequence.SequenceIterator(
object
sequence
, void
|int
start
)
Creates a new iterator for the sequence sequence
. If start is
supplied it will try to position the iterator so that the next
iteration starts at start
.
int
distance(object
iter
)
iter
The iterator to measure the distance to.
Returns distance between this iterator and iter
.
An error if the two iterator could not be compared.
Sequence
get_collection()
Returns the Sequence this iterator currently iterates over.
bool
has_next(void
|int
steps
)
Returns true if it is possible to move steps
steps
forwards, if steps
is not supplied it checks if it is
possible to move one step forward.
bool
has_previous(void
|int
steps
)
Returns true if it is possible to move steps
steps
backwards, if steps
is not supplied it checks if it is
possible to move one step backward.
mixed
set_value(mixed
val
)
Set the value at the current position.
val
The new value.
Returns the old value.
ADT.Set implements a datatype for sets. These sets behave much like multisets, except that they are restricted to containing only one instance of each member value.
From a performance viewpoint, it is probably more efficient for a Pike program to use mappings to serve as sets, rather than using an ADT.Set,so ADT.Set is mainly provided for the sake of completeness and code readability.
__generic__
mixed
ValueType
= mixed
Type for the individual members of the set.
array
(ValueType
) indices( ADT.Set arg )
In analogy with multisets, indices() of an ADT.Set givess an array containing all members of the set.
int
sizeof( ADT.Set arg )
Number of items in the set.
string sprintf(string format, ... ADT.Set arg ... )
Printable representation of the set.
array
(int(1..)
) values( ADT.Set arg )
In analogy with multisets, values() of an ADT.Set givess an array indicating the number of occurrences in the set for each position in the member array returned by indices(). (Most of the time, this is probably rather useless for sets, since the result is an array which just contain 1's, one for each member of the set. Still, this function is provided for consistency.
this_program
res = ADT.Set()
& other
Intersection. Returns a set containing those values that were present in both the operand sets.
this_program
res = ADT.Set()
- other
Difference. The expression 'A - B', where A and B are sets, returns all elements in A that are not also present in B.
bool
res = ADT.Set()
< other
True subset. A < B returns true if each item in A is also present in B, and B contains at least one item not present in A.
bool
res = ADT.Set()
== other
Equality. A == B returns true if all items in A are present in B, and all items in B are present in A. Otherwise, it returns false.
bool
res = ADT.Set()
> other
True superset. A > B returns true if each item in B is also present in A, and A contains at least one item not present in B.i
bool
res = ADT.Set()
[ item
]
Indexing a set with a value V gives 1 if V is a member of the set, otherwise 0.
ADT.Set()
[ item
] = value
Setting an index V to 0 removes V from the set. Setting it to a non-0 value adds V as a member of the set.
this_program
res = ADT.Set()
| other
Union. Returns a set containing all elements present in either or both of the operand sets.
void
add(ValueType
... items
)
Add items
to the set.
(
array
(ValueType
))ADT.Set()
An ADT.Set can be cast to an array or a multiset.
bool
contains(ValueType
item
)
Check whether a value is a member of the set.
ADT.Set ADT.Set(
void
|ADT.Set
|array
(ValueType
)|multiset
(ValueType
)|mapping
(ValueType
:mixed
) initial_data
)
Create an ADT.Set, optionally initialized from another ADT.Set or a compatible type. If no initial data is given, the set will start out empty.
this_program
filter(function
(ValueType
:mixed
) f
)
Return a filtered version of the set, containing only those members
for which the filtering function f
returned true.
The filtering function is called with a single mixed-type argument which is the member value to be checked.
this_program
filter_destructively(function
(ValueType
:mixed
) f
)
Destructively filter the set, i.e. remove every element for which
the filtering function f
returns 0, and then return the set.
The filtering function is called with a single mixed-type argument which is the member value to be checked.
CAVEAT EMPTOR: This function was just a duplicate of filter()
in Pike 8.0 and earlier.
bool
is_empty()
Returns 1 if the set is empty, otherwise 0.
array
(mixed
) map(function
(ValueType
:mixed
) f
)
Map the values of a set: calls the map function f
once for each
member of the set, returning an array which contains the result of
each one of those function calls. Note that since a set isn't
ordered, the values in the returned array will be in more or less
random order. If you need to know which member value produced which
result, you have to make that a part of what the filtering function
returns.
The filtering function f
is called with a single, mixed-type
argument which is the member value to be mapped.
void
remove(ValueType
... items
)
Remove items
from the set.
void
reset()
Remove all items from the set.
bool
subset(ADT.Set
other
)
Subset. A <= B returns true if all items in A are also present in B.
bool
superset(ADT.Set
other
)
Superset. A >= B returns true if all items in B are also present in A.
This class implements a simple stack. Instead of adding and removing elements to an array, and thus making it vary in size for every push and pop operation, this stack tries to keep the stack size constant. If however the stack risks to overflow, it will allocate double its current size, i.e. pushing an element on an full 32 slot stack will result in a 64 slot stack with 33 elements.
__generic__
mixed
ElementType
= mixed
Type for the elements on the stack.
int
search(ADT.Stack from, mixed
item
)
Return the stack-depth to item
.
This function makes it possible to use
eg search()
and has_value()
on the stack.
int
sizeof( ADT.Stack arg )
sizeof
on a stack returns the number of entries
in the stack.
array
(ElementType
) values( ADT.Stack arg )
values
on a stack returns all the entries in
the stack, in order.
this_program
res = ADT.Stack()
+ s
A stack added with another stack yields a new stack with all the elements from both stacks, and the elements from the second stack at the top of the new stack.
ADT.Stack ADT.Stack(
int(1..)
|void
initial_size
)
An initial stack size can be given when a stack is cloned. The default value is 32.
ElementType
peek(int
|void
offset
)
Returns an element from the stack, without popping it.
offset
The number of elements from the top of the stack to skip.
Throws an error if called on an empty stack.
top()
ElementType
pop(void
|int
val
)
Pops and returns entry val
from the stack, counting
from the top. If no value is given the top element is
popped and returned. All popped entries are freed from
the stack.
void
pop_to(int
depth
)
Pops entries from the stack until the specified depth
is
reached. The popped entries are not actually freed, only the
stack pointer is moved.
void
push(ElementType
val
)
Push an element on the top of the stack.
void
quick_pop(void
|int
val
)
Pops val
entries from the stack, or one entry
if no value is given. The popped entries are not
actually freed, only the stack pointer is moved.
void
reset(int(1..)
|void
initial_size
)
Empties the stack, resets the stack pointer and shrinks the stack size to the given value or 32 if none is given.
create
void
set_stack(array
(ElementType
) stack
)
Sets the stacks content to the provided array.
ElementType
top()
Returns the top element from the stack, without popping it.
Throws an error if called on an empty stack.
peek()
Implements a struct which can be used for serialization and deserialization of data.
class ID3 { inherit ADT.Struct; Item head = Chars(3); Item title = Chars(30); Item artist = Chars(30); Item album = Chars(30); Item year = Chars(4); Item comment = Chars(30); Item genre = Byte(); }
Stdio.File f = Stdio.File("foo.mp3"); f->seek(-128); ADT.Struct tag = ID3(f); if(tag->head=="TAG") { write("Title: %s\n", tag->title); tag->title = "A new title" + "\0"*19; f->seek(-128); f->write( (string)tag ); }
class HollerithString { inherit ADT.Struct; Item strlen = Word(); Item str = Chars(strlen); }
array
(string
) indices( ADT.Struct arg )
The indices of a struct is the name of the struct items.
int
sizeof( ADT.Struct arg )
The size of the struct object is the number of bytes allocated for the struct.
array
values( ADT.Struct arg )
The values of a struct is the values of the struct items.
mixed
res = ADT.Struct()
[ item
]
mixed
res = ADT.Struct()
->X
The struct can be indexed by item name to get the associated value.
ADT.Struct()
[ item
] = y
ADT.Struct()
->X = y
It is possible to assign a new value to a struct item by indexing it by name and assign a value.
(int)ADT.Struct()
(float)ADT.Struct()
(string)ADT.Struct()
(array)ADT.Struct()
(mapping)ADT.Struct()
(multiset)ADT.Struct()
The struct can be casted into a string, which is eqivivalent
to running encode
, or into an array. When casted into an
array each array element is the encoded value of that struct
item.
ADT.Struct ADT.Struct(
void
|string
|Stdio.File
data
)
data
Data to be decoded and populate the struct. Can either be a file object or a string.
void
decode(string
|Stdio.File
data
)
Decodes data
according to the struct and populates
the struct variables. The data
can either be a file
object or a string.
string
encode()
Serializes the struct into a string. This string is equal
to the string fed to decode
if nothing in the struct
has been altered.
One byte, integer value between 0 and 255.
inherit Item : Item
ADT.Struct.Byte ADT.Struct.Byte(
int(8bit)
|void
initial_value
)
The byte can be initialized with an optional value.
A string of bytes.
inherit Item : Item
ADT.Struct.Chars ADT.Struct.Chars(
int
|Item
size
, void
|string
value
)
size
is the number of bytes that are part of this struct
item, or optionally an earlier Item that will be looked up in
runtime.
The initial value of the char string is value
or,
if not provided, a string of zero bytes.
One word (2 bytes) in intel order, integer value between 0 and 65535.
Word
inherit Word : Word
One longword (4 bytes) in intel order, integer value between 0 and 2^32.
Long
inherit Drow : Drow
ADT.Struct.Gnol ADT.Struct.Gnol(
int(0..)
|void
initial_value
)
The longword can be initialized with an optional value.
Interface class for struct items.
One longword (4 bytes) in network order, integer value between 0 and 2^32.
Gnol
inherit Word : Word
ADT.Struct.Long ADT.Struct.Long(
int(0..)
|void
initial_value
)
The longword can be initialized with an optional value.
One byte, signed integer value between -128 and 127.
inherit Item : Item
ADT.Struct.SByte ADT.Struct.SByte(
int(-128..127)
|void
initial_value
)
The byte can be initialized with an optional value.
One longword (4 bytes) in network order, signed integer value -(2^31) <= x < 2^31-1.
inherit SWord : SWord
ADT.Struct.SLong ADT.Struct.SLong(
int
|void
initial_value
)
The longword can be initialized with an optional value.
One word (2 bytes) in network order, signed integer value between 0 and 65535.
inherit Item : Item
ADT.Struct.SWord ADT.Struct.SWord(
int(-32768..32767)
|void
initial_value
)
The word can be initialized with an optional value.
One word (2 bytes) in network order, integer value between 0 and 65535.
Drow
inherit Item : Item
ADT.Struct.Word ADT.Struct.Word(
int(16bit)
|void
initial_value
)
The word can be initialized with an optional value.
Alias for SWord
inherit SWord : SWord
Alias for SLong
inherit SLong : SLong
64 bit signed integer.
inherit SLong : SLong
Alias for SByte
inherit SByte : SByte
Alias for Word
inherit Word : Word
Alias for Long
inherit Long : Long
64 bit unsigned integer.
inherit Long : Long
Alias for Byte
inherit Byte : Byte
This class implements an hierarchial quantized resource scheduler.
It differs from Scheduler
by the [Consumer]s making
up a dependency tree.
Active consumers closer to the root will receive the resource before their children.
Implements most of RFC 7540 section 5.3.
Scheduler
inherit .Scheduler : Scheduler
Consumer
|zero
ADT.TreeScheduler.root
The root of the Customer
dependency tree.
Note that the root is never active (ie added to the Scheduler).
Customer
s that don't have an explicit dependency depend on root
.
variant
Consumer
add(int
|float
weight
, mixed
val
, Consumer
parent
)
Create a Consumer
depending on parent
with the weight weight
for the value val
, and add it to the Scheduler.
A resource consumer.
All consumers (both active and inactive) are nodes in
a dependency tree. This means that to avoid excessive
garbage detach()
must be called in consumers that
are no longer to be used.
Active consumers are kept in a (min-)Heap
.
inherit ::this_program : this_program
array
(Consumer
) ADT.TreeScheduler.Consumer.children
Consumer
s that depend on us.
Consumer
|zero
ADT.TreeScheduler.Consumer.parent
Consumer
that we depend on.
ADT.TreeScheduler.Consumer ADT.TreeScheduler.Consumer(
int
|float
weight
, mixed
v
, Consumer
|void
parent
)
void
detach()
Detach from the tree.
Any children are moved to our parent and their weights adjusted to keep their priorities.
If the consumer was active it will be deactivated.
void
reparent_siblings()
Reparent all sibling Consumer
s, so that we become
the only child of our parent.
set_parent()
void
set_parent(Consumer
new_parent
, int
|float
weight
)
Change to a new parent.
new_parent
Consumer
this object depends on. We will only
get returned by get()
when new_parent
is
inactive (ie remove
d).
weight
New weight.
If new_parent
depends on us, it will be moved
to take our place in depending on our old parent.
To perform the exclusive mode reparent from RFC 7540
figure 5, call reparent_siblings()
after this function.
detach()
, remove()
, create()
, reparent_siblings()
void
update_quanta()
Update the cached quanta value.
This function should be called whenever our weight
or that of our siblings has changed.
String buffer with the possibility to read and write data as they would be formatted in structs.
Replaced by Stdio.Buffer
.
inherit Stdio.Buffer : Buffer
this_program
add_data(string(8bit)
s
)
Adds the data s
verbatim to the end of the buffer.
string(8bit)
contents()
Trims the buffer to only contain the data after the read pointer and returns the contents of the buffer.
ADT.struct ADT.struct(
void
|string(8bit)
s
)
Create a new buffer, optionally initialized with the
value s
.
Gmp.mpz
get_bignum(int(1..)
|void
len
)
Reads a bignum written by put_bignum
from the buffer.
string(8bit)
get_fix_string(int
len
)
Reads a fixed sized string of length len
from the buffer.
array
(int
) get_fix_uint_array(int(8bit)
item_size
, int
size
)
Reads an array of integers as written by put_fix_uint_array
from the buffer.
string(8bit)
get_rest()
Get the remaining data from the buffer and clears the buffer.
int(0..)
get_uint(int(0..)
len
)
Reads an unsigned integer from the buffer.
string(8bit)
get_var_string(int(0..)
len
)
Reads a string written by put_var_string
from the buffer.
array
(int
) get_var_uint_array(int(8bit)
item_size
, int(0..)
len
)
Reads an array of integers as written by put_var_uint_array
from the buffer.
bool
is_empty()
Returns one if there is any more data to read.
string(8bit)
pop_data()
Return all the data in the buffer and empties it.
this_program
put_bignum(Gmp.mpz
i
, int(1..)
|void
len_width
)
Appends a bignum i
as a variable string preceded with an
unsigned integer of the size len_width
declaring the length
of the string. len_width
defaults to 2.
this_program
put_fix_string(string(8bit)
s
)
Appends the fix sized string s
to the buffer.
this_program
put_fix_uint_array(array
(int
) data
, int(8bit)
item_size
)
Appends an array of unsigned integers of width item_size
to the buffer.
this_program
put_uint(int
i
, int(0..)
len
)
Appends an unsigned integer in network order to the buffer.
i
Unsigned integer to append.
len
Length of integer in bytes.
this_program
put_var_string(string(8bit)
s
, int(0..)
len_width
)
Appends a variable string s
preceded with an unsigned integer
of the size len_width
declaring the length of the string. The
string s
should be 8 bits wide.
this_program
put_var_string_array(array
(string(8bit)
) data
, int(0..)
item_size
, int(0..)
len
)
Appends an array of variable length strings with item_size
bytes hollerith coding, prefixed by a len
bytes large integer
declaring the total size of the array in bytes.
this_program
put_var_uint_array(array
(int
) data
, int(8bit)
item_size
, int(0..)
len
)
Appends an array of unsigned integers of width item_size
to the buffer, preceded with an unsigned integer len
declaring
the size of the array in bytes.
This module offers CritBit tree implementations for different key types.
These CritBit trees support prefixes as proper keys. Hence they should really be called Tries.
object
Tree(void
|string
|program
|mapping
type
)
Creates a CritBit tree for keys of type type
. If no argument is given,
an instance of ADT.CritBit.StringTree
is returned. Supported types are "string"
,
"int"
, "float"
, "ipv4"
and Calendar.TimeRange
.
array
(string
) sort_ipv4(array
(string
) a
, array
... data
)
Sorts an ARRAY OF IPv4-Adresses (and optional netmasks) given in dotted decimal representation with the /23 netmask notation.
> array(string) a = ({ "127.0.0.121", > "127.0.0.0/16", > "127.0.0.1/8", > "127.0.0.0/8", > "128.0.0.0/1", > "192.168.21.3", > "8.8.8.8" }); > write("%O\n", CritBit.sort_ipv4(a)); ({ /* 7 elements */ "8.8.8.8", "127.0.0.0/8", "127.0.0.0/16", "127.0.0.1/8", "127.0.0.121", "128.0.0.0/1", "192.168.21.3" })
inherit IntTree : IntTree
this_program
copy()
Copy callback to also clone backwards
int
|object
decode_key(int
i
)
Decodes an integer back to a Calendar.TimeRange
object. Keeps
a mapping of all keys stored in the tree to transform back.
int
encode_key(object
|int
o
)
Encodes a Calendar.TimeRange object into unix timestanp.
This class implements a CritBit-tree/trie that can be used as a
mapping-like data structure. Values of float|int
can be
used as indices, while any possible type (also mixed
) can
be stored.
CritBit trees are prefixed based search trees that allow for fast random
access as well as prefix and range based lookups. Keys are stored in
alphabetical order and can be iterated over using foreach
.
Other than that, it can be used like mapping(float|int:mixed)
.
ADT.CritBit.FloatTree tree = ADT.CritBit.FloatTree(); float|int key1 = 12.0; tree[key1] = ({ 4, 5, 6 }); tree[key1]; // now is ({ 4, 5, 6 }) m_delete(tree, key1); // tree is empty again
ADT.CritBit.FloatTree tree = ADT.CritBit.FloatTree(); array(float|int) a = ({ 80.4, 99.9, 14.2 }); foreach(a; int idx; float|int val) { tree[val] = idx; } foreach(tree; float|int key; mixed val) { // in here the keys will be reached in order 14.2, 80.4 and 99.9. }
ADT.CritBit.FloatTree tree = ADT.CritBit.FloatTree(); array(float|int) a = ({ 80.4, 99.9, 14.2 }); foreach (a; int idx; float|int val) { tree[val] = idx; } foreach(ADT.CritBit.FloatTree.Iterator (tree, -1); float|int key; mixed val) { // in here the keys will be reached in order 99.9, 80.4 and 14.2. }
ADT.CritBit.FloatTree.Iterator
bool
equal(ADT.CritBit.FloatTree from, mixed
o
)
array
indices( ADT.CritBit.FloatTree arg )
Returns a sorted array of indices of the FloatTree
.
mixed
m_delete(ADT.CritBit.FloatTree from, mixed
key
)
m_delete callback.
array
random( ADT.CritBit.FloatTree arg )
Get a random entry.
An array ({ key, value })
.
int
sizeof( ADT.CritBit.FloatTree arg )
Gives the number of entries in the FloatTree
.
array
values( ADT.CritBit.FloatTree arg )
Returns an array of values of the FloatTree
object. The returned
array matches
_indices
so that mkmapping(indices(tree), values(tree))
would
create a mapping with the same contents as this FloatTree
.
mixed
res = ADT.CritBit.FloatTree()
+ o
Add callback. Returns the union of two trees.
mixed
res = ADT.CritBit.FloatTree()
- o
Sub[s]tract two trees from each other (key-wise).
mixed
res = ADT.CritBit.FloatTree()
[start..end]
predef::`[..]
mixed
res = ADT.CritBit.FloatTree()
[ key
]
ADT.CritBit.FloatTree()
[ key
] = val
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.
(
mapping
)ADT.CritBit.FloatTree()
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
FloatTree
copy()
Create a copy of the tree.
ADT.CritBit.FloatTree ADT.CritBit.FloatTree(
array
|mapping
|void
o
)
Create a FloatTree from o.
float
|int
encode_key(mixed
o
)
mixed
decode_key(float
|int
o
)
These callbacks can be implemented when inheriting FloatTree in order
to allow for arbitrary key types. encode_key
is similar to the
lfun::_hash()
callback. This only works as expected when it is possible
to implement a unique representation for keys. These callbacks are called
everytime a key is stored or indexed in the tree.
int(0..)
depth()
Calculate the depth of the tree.
float
|int
first()
Get the lexicographically first index in the tree.
FloatTree
get_subtree(void
|mixed
key
)
Get a copy of the subtree starting at prefix
key
.
float
|int
last()
Get the lexicographically last index in the tree.
float
|int
next(mixed
current
)
Get the key after current
in lexicographical order.
mixed
nth(int(0..)
n
)
Get the n
th entry in order.
An array ({ key, value })
.
float
|int
previous(mixed
current
)
Get the key before current
in lexicographical order.
Iterator class for FloatTree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling foreach
on an object of
FloatTree. In foreach
the iterator runs over all elements
from the first to the last.
predef::Iterator
for a description of the interface.
ADT.CritBit.FloatTree._get_iterator ADT.CritBit.FloatTree._get_iterator(
void
|int
step
, void
|mixed
start
, void
|mixed
stop
)
Returns an iterator object that runs from start
to
stop
using a stepsize of step
. The arguments
default to 1
, tree->first()
and
tree->last()
, respectively.
This class implements a CritBit-tree/trie that can be used as a
mapping-like data structure. Values of string
can be
used as indices, while any possible type (also mixed
) can
be stored.
CritBit trees are prefixed based search trees that allow for fast random
access as well as prefix and range based lookups. Keys are stored in
alphabetical order and can be iterated over using foreach
.
Other than that, it can be used like mapping(string:mixed)
.
ADT.CritBit.IPv4Tree tree = ADT.CritBit.IPv4Tree(); string key1 = "127.0.0.0/8"; tree[key1] = "reject"; tree[key1]; // now is "reject" m_delete(tree, key1); // tree is empty again
ADT.CritBit.IPv4Tree tree = ADT.CritBit.IPv4Tree(); array(string) a = ({ "10.243.7.1", "127.0.0.1/8", "172.16.5.2" }); foreach(a; int idx; string val) { tree[val] = idx; } foreach(tree; string key; mixed val) { // in here the keys will be reached in order "10.243.7.1", "127.0.0.1/8" and "172.16.5.2". }
ADT.CritBit.IPv4Tree tree = ADT.CritBit.IPv4Tree(); array(string) a = ({ "10.243.7.1", "127.0.0.1/8", "172.16.5.2" }); foreach (a; int idx; string val) { tree[val] = idx; } foreach(ADT.CritBit.IPv4Tree.Iterator (tree, -1); string key; mixed val) { // in here the keys will be reached in order "172.16.5.2", "127.0.0.1/8" and "10.243.7.1". }
ADT.CritBit.IPv4Tree.Iterator
bool
equal(ADT.CritBit.IPv4Tree from, mixed
o
)
array
indices( ADT.CritBit.IPv4Tree arg )
Returns a sorted array of indices of the IPv4Tree
.
mixed
m_delete(ADT.CritBit.IPv4Tree from, mixed
key
)
m_delete callback.
array
random( ADT.CritBit.IPv4Tree arg )
Get a random entry.
An array ({ key, value })
.
int
sizeof( ADT.CritBit.IPv4Tree arg )
Gives the number of entries in the IPv4Tree
.
array
values( ADT.CritBit.IPv4Tree arg )
Returns an array of values of the IPv4Tree
object. The returned
array matches
_indices
so that mkmapping(indices(tree), values(tree))
would
create a mapping with the same contents as this IPv4Tree
.
mixed
res = ADT.CritBit.IPv4Tree()
+ o
Add callback. Returns the union of two trees.
mixed
res = ADT.CritBit.IPv4Tree()
- o
Sub[s]tract two trees from each other (key-wise).
mixed
res = ADT.CritBit.IPv4Tree()
[start..end]
predef::`[..]
mixed
res = ADT.CritBit.IPv4Tree()
[ key
]
ADT.CritBit.IPv4Tree()
[ key
] = val
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.
(
mapping
)ADT.CritBit.IPv4Tree()
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
string
|int
common_prefix()
Returns the common prefix of all keys.
If the tree has no elements, UNDEFINED
is returned.
IPv4Tree
copy()
Create a copy of the tree.
ADT.CritBit.IPv4Tree ADT.CritBit.IPv4Tree(
array
|mapping
|void
o
)
Create a IPv4Tree from o.
string
encode_key(mixed
o
)
mixed
decode_key(string
o
)
These callbacks can be implemented when inheriting IPv4Tree in order
to allow for arbitrary key types. encode_key
is similar to the
lfun::_hash()
callback. This only works as expected when it is possible
to implement a unique representation for keys. These callbacks are called
everytime a key is stored or indexed in the tree.
int(0..)
depth()
Calculate the depth of the tree.
string
first()
Get the lexicographically first index in the tree.
IPv4Tree
get_subtree(void
|mixed
key
)
Get a copy of the subtree starting at prefix
key
.
string
last()
Get the lexicographically last index in the tree.
string
next(mixed
current
)
Get the key after current
in lexicographical order.
mixed
nth(int(0..)
n
)
Get the n
th entry in order.
An array ({ key, value })
.
string
previous(mixed
current
)
Get the key before current
in lexicographical order.
Iterator class for IPv4Tree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling foreach
on an object of
IPv4Tree. In foreach
the iterator runs over all elements
from the first to the last.
predef::Iterator
for a description of the interface.
ADT.CritBit.IPv4Tree._get_iterator ADT.CritBit.IPv4Tree._get_iterator(
void
|int
step
, void
|mixed
start
, void
|mixed
stop
)
Returns an iterator object that runs from start
to
stop
using a stepsize of step
. The arguments
default to 1
, tree->first()
and
tree->last()
, respectively.
This class implements a CritBit-tree/trie that can be used as a
mapping-like data structure. Values of int
can be
used as indices, while any possible type (also mixed
) can
be stored.
CritBit trees are prefixed based search trees that allow for fast random
access as well as prefix and range based lookups. Keys are stored in
alphabetical order and can be iterated over using foreach
.
Other than that, it can be used like mapping(int:mixed)
.
ADT.CritBit.IntTree tree = ADT.CritBit.IntTree(); int key1 = 12; tree[key1] = ({ 1, 2 ,3 }); tree[key1]; // now is ({ 1, 2 ,3 }) m_delete(tree, key1); // tree is empty again
ADT.CritBit.IntTree tree = ADT.CritBit.IntTree(); array(int) a = ({ 1025, 15000, 3 }); foreach(a; int idx; int val) { tree[val] = idx; } foreach(tree; int key; mixed val) { // in here the keys will be reached in order 3, 1025 and 15000. }
ADT.CritBit.IntTree tree = ADT.CritBit.IntTree(); array(int) a = ({ 1025, 15000, 3 }); foreach (a; int idx; int val) { tree[val] = idx; } foreach(ADT.CritBit.IntTree.Iterator (tree, -1); int key; mixed val) { // in here the keys will be reached in order 15000, 1025 and 3. }
ADT.CritBit.IntTree.Iterator
bool
equal(ADT.CritBit.IntTree from, mixed
o
)
array
indices( ADT.CritBit.IntTree arg )
Returns a sorted array of indices of the IntTree
.
mixed
m_delete(ADT.CritBit.IntTree from, mixed
key
)
m_delete callback.
array
random( ADT.CritBit.IntTree arg )
Get a random entry.
An array ({ key, value })
.
int
sizeof( ADT.CritBit.IntTree arg )
Gives the number of entries in the IntTree
.
array
values( ADT.CritBit.IntTree arg )
Returns an array of values of the IntTree
object. The returned
array matches
_indices
so that mkmapping(indices(tree), values(tree))
would
create a mapping with the same contents as this IntTree
.
mixed
res = ADT.CritBit.IntTree()
+ o
Add callback. Returns the union of two trees.
mixed
res = ADT.CritBit.IntTree()
- o
Sub[s]tract two trees from each other (key-wise).
mixed
res = ADT.CritBit.IntTree()
[start..end]
predef::`[..]
mixed
res = ADT.CritBit.IntTree()
[ key
]
ADT.CritBit.IntTree()
[ key
] = val
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.
(
mapping
)ADT.CritBit.IntTree()
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
IntTree
copy()
Create a copy of the tree.
ADT.CritBit.IntTree ADT.CritBit.IntTree(
array
|mapping
|void
o
)
Create a IntTree from o.
int
encode_key(mixed
o
)
mixed
decode_key(int
o
)
These callbacks can be implemented when inheriting IntTree in order
to allow for arbitrary key types. encode_key
is similar to the
lfun::_hash()
callback. This only works as expected when it is possible
to implement a unique representation for keys. These callbacks are called
everytime a key is stored or indexed in the tree.
int(0..)
depth()
Calculate the depth of the tree.
int
first()
Get the lexicographically first index in the tree.
IntTree
get_subtree(void
|mixed
key
)
Get a copy of the subtree starting at prefix
key
.
int
last()
Get the lexicographically last index in the tree.
int
next(mixed
current
)
Get the key after current
in lexicographical order.
mixed
nth(int(0..)
n
)
Get the n
th entry in order.
An array ({ key, value })
.
int
previous(mixed
current
)
Get the key before current
in lexicographical order.
Iterator class for IntTree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling foreach
on an object of
IntTree. In foreach
the iterator runs over all elements
from the first to the last.
predef::Iterator
for a description of the interface.
ADT.CritBit.IntTree._get_iterator ADT.CritBit.IntTree._get_iterator(
void
|int
step
, void
|mixed
start
, void
|mixed
stop
)
Returns an iterator object that runs from start
to
stop
using a stepsize of step
. The arguments
default to 1
, tree->first()
and
tree->last()
, respectively.
Data structure representing a set of disjunct ADT.Interval
objects. Can be thought
of as an interval with gaps.
ADT.CritBit.RangeSet ADT.CritBit.RangeSet(
function
(:void
)|object
|program
tree
)
Create a RangeSet from a given tree program.
object
ADT.CritBit.Reverse.tree
protected
local
void
__create__(object
tree
)
ADT.CritBit.Reverse ADT.CritBit.Reverse(
object
tree
)
This class implements a CritBit-tree/trie that can be used as a
mapping-like data structure. Values of string
can be
used as indices, while any possible type (also mixed
) can
be stored.
CritBit trees are prefixed based search trees that allow for fast random
access as well as prefix and range based lookups. Keys are stored in
alphabetical order and can be iterated over using foreach
.
Other than that, it can be used like mapping(string:mixed)
.
ADT.CritBit.StringTree tree = ADT.CritBit.StringTree(); string key1 = "foo"; tree[key1] = ({ 7, 8, 9 }); tree[key1]; // now is ({ 7, 8, 9 }) m_delete(tree, key1); // tree is empty again
ADT.CritBit.StringTree tree = ADT.CritBit.StringTree(); array(string) a = ({ "fooo", "bar", "ahead" }); foreach(a; int idx; string val) { tree[val] = idx; } foreach(tree; string key; mixed val) { // in here the keys will be reached in order "ahead", "bar" and "foo". }
ADT.CritBit.StringTree tree = ADT.CritBit.StringTree(); array(string) a = ({ "fooo", "bar", "ahead" }); foreach (a; int idx; string val) { tree[val] = idx; } foreach(ADT.CritBit.StringTree.Iterator (tree, -1); string key; mixed val) { // in here the keys will be reached in order "foo", "bar" and "ahead". }
ADT.CritBit.StringTree.Iterator
bool
equal(ADT.CritBit.StringTree from, mixed
o
)
array
indices( ADT.CritBit.StringTree arg )
Returns a sorted array of indices of the StringTree
.
mixed
m_delete(ADT.CritBit.StringTree from, mixed
key
)
m_delete callback.
array
random( ADT.CritBit.StringTree arg )
Get a random entry.
An array ({ key, value })
.
int
sizeof( ADT.CritBit.StringTree arg )
Gives the number of entries in the StringTree
.
array
values( ADT.CritBit.StringTree arg )
Returns an array of values of the StringTree
object. The returned
array matches
_indices
so that mkmapping(indices(tree), values(tree))
would
create a mapping with the same contents as this StringTree
.
mixed
res = ADT.CritBit.StringTree()
+ o
Add callback. Returns the union of two trees.
mixed
res = ADT.CritBit.StringTree()
- o
Sub[s]tract two trees from each other (key-wise).
mixed
res = ADT.CritBit.StringTree()
[start..end]
predef::`[..]
mixed
res = ADT.CritBit.StringTree()
[ key
]
ADT.CritBit.StringTree()
[ key
] = val
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.
(
mapping
)ADT.CritBit.StringTree()
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
string
|int
common_prefix()
Returns the common prefix of all keys.
If the tree has no elements, UNDEFINED
is returned.
StringTree
copy()
Create a copy of the tree.
ADT.CritBit.StringTree ADT.CritBit.StringTree(
array
|mapping
|void
o
)
Create a StringTree from o.
string
encode_key(mixed
o
)
mixed
decode_key(string
o
)
These callbacks can be implemented when inheriting StringTree in order
to allow for arbitrary key types. encode_key
is similar to the
lfun::_hash()
callback. This only works as expected when it is possible
to implement a unique representation for keys. These callbacks are called
everytime a key is stored or indexed in the tree.
int(0..)
depth()
Calculate the depth of the tree.
string
first()
Get the lexicographically first index in the tree.
StringTree
get_subtree(void
|mixed
key
)
Get a copy of the subtree starting at prefix
key
.
string
last()
Get the lexicographically last index in the tree.
string
next(mixed
current
)
Get the key after current
in lexicographical order.
mixed
nth(int(0..)
n
)
Get the n
th entry in order.
An array ({ key, value })
.
string
previous(mixed
current
)
Get the key before current
in lexicographical order.
Iterator class for StringTree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling foreach
on an object of
StringTree. In foreach
the iterator runs over all elements
from the first to the last.
predef::Iterator
for a description of the interface.
ADT.CritBit.StringTree._get_iterator ADT.CritBit.StringTree._get_iterator(
void
|int
step
, void
|mixed
start
, void
|mixed
stop
)
Returns an iterator object that runs from start
to
stop
using a stepsize of step
. The arguments
default to 1
, tree->first()
and
tree->last()
, respectively.
An abstract data type for binary relations.
This datatype implements something similar to a set of tuples <left, right>, or a multi-valued mapping.
mixed
sizeof( ADT.Relation.Binary arg )
Returns the number of relation entries in the relation. (Or with other words: the number of relations in the relation set.)
mixed
res = ADT.Relation.Binary()
& rel
The expression `rel1 & rel2' returns a new relation which has those and only those relation entries that are present in both rel1 and rel2.
mixed
res = ADT.Relation.Binary()
()
Does the same as the contains
function: returns true if the
relation "left
R right
" exists, and otherwise false.
mixed
res = ADT.Relation.Binary()
+ rel
mixed
res = ADT.Relation.Binary()
| rel
The expression `rel1 | rel2' and `rel1 + rel2' returns a new relation which has all the relation entries present in rel1, or rel2, or both.
mixed
res = ADT.Relation.Binary()
- rel
The expression `rel1 - rel2' returns a new relation which has those and only those relation entries that are present in rel1 and not present in rel2.
this_program
add(mixed
left
, mixed
right
)
Adds "left
R right
" as a member of the relation. Returns
the same relation.
mixed
contains(mixed
left
, mixed
right
)
Return true/false: does the relation "left
R right
" exist?
object
filter(function
(:void
) f
)
Filters the entries in the relation, and returns a relation with
all those entries for which the filtering function f
returned
true. The function f
gets two arguments: the left and the right
value for every entry in the relation.
this_program
filter_destructively(function
(:void
) f
)
Filters the entries in the relation destructively, removing all
entries for which the filtering function f
returns false.
The function f
gets two arguments: the left and the right value
for each entry in the relation.
array
|zero
find_shortest_path(mixed
from
, mixed
to
, void
|multiset
avoiding
)
Assuming the relation's domain and range sets are equal, and that
the relation xRy means "there is a path from node x to node y",
find_shortest_path
attempts to find a path with a minimum number
of steps from one given node to another. The path is returned as an
array of nodes (including the starting and ending node), or 0 if no
path was found. If several equally short paths exist, one of them
will be chosen pseudorandomly.
Trying to find a path from a node to itself will always succeed, returning an array of one element: the node itself. (Or in other words, a path with no steps, only a starting/ending point).
The argument avoiding
is either 0 (or omitted), or a multiset of
nodes that must not be part of the path.
mixed
get_id()
Return the ID value which was given as first argument to create().
this_program
make_symmetric()
Makes the relation symmetric, i.e. makes sure that if xRy is part of the relation set, then yRx should also be a part of the relation set.
array
map(function
(:void
) f
)
Maps every entry in the relation. The function f gets two arguments: the left and the right relation value. Returns an array with the return values of f for each and every mapped entry.
Note: since the entries in the relation are not ordered,
the returned array will have its elements in no particular
order. If you need to know which relation entry produced which
result in the array, you have to make that information part
of the value that f
returns.
this_program
remove(mixed
left
, mixed
right
)
Removes "left
R right
" as a member of the relation. Returns
the same relation.
An iterator which makes all the left/right entities in the relation available as index/value pairs.
ADT.Table is a generic module for manipulating tables.
Each table contains one or several columns. Each column is associated with a name, the column name. Optionally, one can provide a column type. The Table module can do a number of operations on a given table, like computing the sum of a column, grouping, sorting etc.
All column references are case insensitive. A column can be referred to by its position (starting from zero). All operations are non-destructive. That means that a new table object will be returned after, for example, a sort.
The table base-class.
array
(string
) indices( ADT.Table.table arg )
This method returns the column names for the table. The case used when the table was created will be returned.
int
sizeof( ADT.Table.table arg )
This method returns the number of rows in the table.
array
(array
) values( ADT.Table.table arg )
This method returns the contents of a table as a two dimensional array. The format is an array of rows. Each row is an array of columns.
bool
res = ADT.Table.table()
== table
This method compares two tables. They are equal if the contents of the tables and the column names are equal. The column name comparison is case insensitive.
array
res = ADT.Table.table()
[ column
]
Same as col()
.
this_program
append_bottom(object
table
)
This method appends two tables. The table given as an argument will be added at the bottom of the current table. Note, the column names must be equal. The column name comparison is case insensitive.
this_program
append_right(object
table
)
This method appends two tables. The table given as an argument will be added on the right side of the current table. Note that the number of rows in both tables must be equal.
array
col(int
|string
column
)
This method returns the contents of a given column as an array.
ADT.Table.table ADT.Table.table(
array
(array
) table
, array
(string
) column_names
, array
(mapping
(string
:string
))|void
column_types
)
The ADT.Table.table
class takes two or three arguments:
table
The first argument is a two-dimensional array consisting of
one array of columns per row. All rows must have the same
number of columns as specified in column_names
.
column_names
This argument is an array of column names associated with each
column in the table. References by column name are case insensitive.
The case used in column_names
will be used when the table is
displayed. A column can also be referred to by its position,
starting from zero.
column_types
This is an optional array of mappings. The column type
information is only used when displaying the table. Currently, only the
keyword "type"
is recognized. The type can be specified as
"text"
or "num"
(numerical). Text columns are left
adjusted, whereas numerical columns are right adjusted. If a mapping
in the array is 0 (zero), it will be assumed to be a text column.
If column_types
is omitted, all columns will displayed as text.
See ADT.Table.ASCII.encode()
on how to display a table.
ADT.Table.ASCII.encode()
object
decode(string
s
)
This method returns a table object from a binary string
representation of a table, as returned by encode()
.
this_program
distinct(int
|string
... columns
)
This method groups by the given columns and returns a table with only unique rows. When no columns are given, all rows will be unique. A new table object will be returned.
string
encode()
This method returns a binary string representation of the table. It is useful when one wants to store a the table, for example in a file.
this_program
group(mapping
(int
|string
:function
(:void
))|function
(:void
) f
, mixed
... args
)
This method calls the function f
for each column each time a
non uniqe row will be joined. The table will be grouped by the
columns not listed. The result will be returned as a new table object.
this_program
limit(int
n
)
This method truncates the table to the first n
rows and returns
a new object.
object
map(function
(:void
) f
, array
(int
|string
)|int
|string
columns
, mixed
... args
)
This method calls the function f
for all rows in the table.
The value returned will replace the values in the columns given
as argument to map. If the function returns an array, several
columns will be replaced. Otherwise the first column will be
replaced. The result will be returned as a new table object.
this_program
remove(int
|string
... columns
)
Like select()
, but the given columns
will not be in the
resulting table.
this_program
rename(string
|int
from
, string
to
)
This method renames the column named from
to to
and
returns a new table object. Note that from
can be the column
position.
protected
this_program
reverse()
This method reverses the rows of the table and returns a new table object.
array
row(int
row_number
)
This method returns the contents of a given row as an array.
object
rsort(int
|string
... columns
)
Like sort()
, but in descending order.
this_program
select(int
|string
... columns
)
This method returns a new table object with the selected columns only.
this_program
sort(int
|string
... columns
)
This method sorts the table in ascendent order on one or several columns and returns a new table object. The left most column is sorted last. Note that the sort is stable.
rsort()
this_program
sum(int
|string
... columns
)
This method sums all equal rows. The table will be grouped by the columns not listed. The result will be returned as a new table object.
mapping
type(int
|string
column
, void
|mapping
type
)
This method gives the type for the given column
.
If a second argument is given, the old type will be replaced
with type
. The column type is only used when the table is displayed.
The format is as specified in create()
.
this_program
where(array
(int
|string
)|int
|string
columns
, function
(:void
) f
, mixed
... args
)
This method calls the function for each row. If the function returns zero, the row will be thrown away. If the function returns something non-zero, the row will be kept. The result will be returned as a new table object.
string
encode(object
table
, void
|mapping
options
)
This method returns a table represented in ASCII suitable for
human eyes. options
is an optional mapping. If the keyword
"indent"
is used with a number, the table will be
indented with that number of space characters.