int
hash(string
s
)
int
hash(string
s
, int
max
)
Return an integer derived from the string s
. The same string
will always hash to the same value, also between processes.
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
This function is provided for backward compatibility reasons.
This function is byte-order dependant for wide strings.
predef::hash()
, 7.0::hash()
Pike has a builtin C-style preprocessor. It works similar to the ANSI-C preprocessor but has a few extra features. These and the default set of preprocessor macros are described here.
#require
If the directive evaluates to false, the source file will be
considered to have failed dependencies, and will not be found by
the resolver. In practical terms the cpp()
call will return
zero.
#if
int(1..)
__COUNTER__
This define contains a unique counter (unless it has been expanded Inte.NATIVE_MAX times) represented as an integer.
constant
__OS2__
This define is defined when the Pike is running on IBM OS/2.
constant
FUSE_MAJOR_VERSION
constant
FUSE_MINOR_VERSION
The version of FUSE
constant
int
HKEY_CLASSES_ROOT
constant
int
HKEY_LOCAL_MACHINE
constant
int
HKEY_CURRENT_USER
constant
int
HKEY_USERS
Root handles in the Windows registry.
These constants are only available on Win32 systems.
RegGetValue()
, RegGetValues()
, RegGetKeyNames()
array
(string
) RegGetKeyNames(int
hkey
, string
key
)
Get a list of value key names from the register.
hkey
One of the following:
|
|
|
|
key
A registry key.
Returns an array of value keys stored at the specified location if any.
Returns UNDEFINED
on missing key
.
Throws errors on other failures.
> RegGetKeyNames(HKEY_CURRENT_USER, "Keyboard Layout"); (1) Result: ({ "IMEtoggle", "Preload", "Substitutes", "Toggle" })
This function threw errors on missing key
in Pike 7.6 and earlier
(see System.RegGetKeyNames_76()
).
This function is only available on Win32 systems.
RegGetValue()
, RegGetValues()
, System.RegGetKeyNames_76()
string
|int
|array
(string
) RegGetValue(int
hkey
, string
key
, string
index
)
Get a single value from the register.
hkey
One of the following:
|
|
|
|
key
Registry key.
index
Value name.
Returns the value stored at the specified location in the register
if any. Returns UNDEFINED
on missing keys, throws errors
on other failures.
This function threw errors on missing keys in Pike 7.6 and earlier
(see System.RegGetValue_76()
).
This function is only available on Win32 systems.
RegGetValues()
, RegGetKeyNames()
, System.RegGetValue_76()
mapping
(string
:string
|int
|array
(string
)) RegGetValues(int
hkey
, string
key
)
Get multiple values from the register.
hkey
One of the following:
|
|
|
|
key
Registry key.
Returns a mapping with all the values stored at the specified location
in the register if any.
Returns UNDEFINED
on missing key
.
Throws errors on other failures.
> RegGetValues(HKEY_CURRENT_USER, "Keyboard Layout\\Preload"); (5) Result: ([ "1":"0000041d" ])
This function threw errors on missing key
in Pike 7.6 and earlier
(see System.RegGetValues_76()
).
This function is only available on Win32 systems.
RegGetValue()
, RegGetKeyNames()
, System.RegGetValues_76()
constant
TOKENIZE_KEEP_ESCAPES
Don't unquote backslash-sequences in quoted strings during tokenizing. This is used for bug-compatibility with Microsoft...
tokenize()
, tokenize_labled()
constant
UNDEFINED
The undefined value; ie a zero for which zero_type()
returns 1.
void
_Static_assert(int
constant_expression
, string
constant_message
)
Perform a compile-time assertion check.
If constant_expression
is false, a compiler error message
containing constant_message
will be generated.
Note that the function call compiles to the null statement, and thus does not affect the run-time.
cpp::static_assert
array
__automap__(function
(:void
) fun
, mixed
... args
)
Automap execution function.
fun
Function to call for each of the mapped arguments.
args
Arguments for fun
. Either
| Wrapper for an array to loop over. All of the arrays will be looped over in parallel. |
| All other arguments will be held constant during
the automap, and sent as is to |
This function is used by the compiler to implement the automap syntax, and should in normal circumstances never be used directly.
It may however show up during module dumping and in backtraces.
It is an error not to have any Builtin.automap_marker
s
in args
.
Builtin.automap_marker
, map()
program
__empty_program(int
|void
line
, string
|void
file
)
type
__handle_sprintf_format(string
attr
, string
fmt
, type
arg_type
, type
cont_type
)
Type attribute handler for "sprintf_format"
.
attr
Attribute to handle, either "sprintf_format"
or "strict_sprintf_format"
.
fmt
Sprintf-style formatting string to generate type information from.
arg_type
Declared type of the fmt
argument (typically string
).
cont_type
Continuation function type after the fmt
argument. This is
scanned for the type attribute "sprintf_args"
to
determine where the remaining arguments to sprintf()
will
come from.
This function is typically called from
PikeCompiler()->apply_attribute_constant()
and is used to perform
stricter compile-time argument checking of sprintf()
-style functions.
It currently implements two operating modes depending on the value of
attr
:
| The formatting string |
| The formatting string |
Returns cont_type
with "sprintf_args"
replaced by the
arguments required by the fmt
formatting string, and
"sprintf_result"
replaced by the resulting string type.
PikeCompiler()->apply_attribute_constant()
, sprintf()
constant
__null_program
Program used internally by the compiler to create objects that are later modified into instances of the compiled program by the compiler.
__placeholder_object
string(8bit)
__parse_pike_type(string(8bit)
t
)
constant
__placeholder_object
Object used internally by the compiler.
__null_program
_disable_threads
_disable_threads()
This function first posts a notice to all threads that it is time to stop. It then waits until all threads actually *have* stopped, and then then returns a lock object. All other threads will be blocked from running until that object has been freed/destroyed.
It's mainly useful to do things that require a temporary uid/gid change, since on many OS the effective user and group applies to all threads.
You should make sure that the returned object is freed even if some kind of error is thrown. That means in practice that it should only have references (direct or indirect) from function local variables. Also, it shouldn't be referenced from cyclic memory structures, since those are only destructed by the periodic gc. (This advice applies to mutex locks in general, for that matter.)
gethrdtime()
mixed
call_out(function
(:void
) f
, float
|int
delay
, mixed
... args
)
void
_do_call_outs()
int
find_call_out(function
(:void
) f
)
int
find_call_out(mixed
id
)
int
remove_call_out(function
(:void
) f
)
int
remove_call_out(function
(:void
) id
)
array
(array
) call_out_info()
These are aliases for the corresponding functions in
Pike.DefaultBackend
.
Pike.Backend()->call_out()
, Pike.Backend()->_do_call_outs()
,
Pike.Backend()->find_call_out()
, Pike.Backend()->remove_call_out()
,
Pike.Backend()->call_out_info()
void
_exit(int
returncode
)
This function does the same as exit
, but doesn't bother to clean
up the Pike interpreter before exiting. This means that no destructors
will be called, caches will not be flushed, file locks might not be
released, and databases might not be closed properly.
Use with extreme caution.
exit()
mixed
_next(mixed
x
)
Find the next object/array/mapping/multiset/program or string.
All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
next_object()
, _prev()
mixed
_prev(mixed
x
)
Find the previous object/array/mapping/multiset or program.
All objects, arrays, mappings, multisets and programs are stored in linked lists inside Pike. This function returns the previous item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
Unlike _next()
this function does not work on strings.
next_object()
, _next()
int
_refs(string
|array
|mapping
|multiset
|function
(:void
)|object
|program
o
)
Return the number of references o
has.
It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
Note that the number of references will always be at least one since the value is located on the stack when this function is executed.
_next()
, _prev()
object
_static_modules
This is an object containing the classes for all static (ie non-dynamic) C-modules.
In a typic Pike with support for dynamic modules the contained module classes are:
Builtin
Gmp
_Stdio
_math
_system
If the Pike binary lacks support for dynamic modules, all C-modules will show up here.
type
_typeof(mixed
x
)
Return the runtime type of x
.
typeof()
bool
`!(object
|function
(:void
) arg
)
int(1..1)
`!(int(0..0)
arg
)
int(0..0)
`!(mixed
arg
)
Logical not.
Every expression with the !
operator becomes a call to
this function, i.e. !a
is the same as
predef::`!(a)
.
It's also used when necessary to test truth on objects, i.e. in
a statement if (o) ...
where o
is an object, the
test becomes the equivalent of !!o
so that any
lfun::`!()
the object might have gets called.
If arg
is an object that implements lfun::`!()
, that function
will be called.
If arg
is 0
(zero), a destructed object, or a function in a
destructed object, 1
will be returned.
Otherwise 0
(zero) will be returned.
No float is considered false, not even 0.0
.
`==()
, `!=()
, lfun::`!()
bool
`!=(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Inequality test.
Every expression with the !=
operator becomes a call to
this function, i.e. a!=b
is the same as
predef::`!=(a,b)
.
This is the inverse of `==()
; see that function for further
details.
Returns 1
if the test is successful, 0
otherwise.
`==()
mixed
`%(object
arg1
, mixed
arg2
)
mixed
`%(mixed
arg1
, object
arg2
)
string
`%(string
arg1
, int
arg2
)
array
`%(array
arg1
, int
arg2
)
float
`%(float
arg1
, float
|int
arg2
)
float
`%(int
arg1
, float
arg2
)
int
`%(int
arg1
, int
arg2
)
Modulo.
Every expression with the %
operator becomes a call to
this function, i.e. a%b
is the same as
predef::`%(a,b)
.
If arg1
is an object that implements lfun::`%()
then
that function will be called with arg2
as the single argument.
If arg2
is an object that implements lfun::``%()
then
that function will be called with arg2
as the single argument.
Otherwise the result will be as follows:
arg1
can have any of the following types:
| If |
| The result will be
|
For numbers, this means that
a % b
always has the same sign as b
(typically b
is positive;
array size, rsa modulo, etc, and a
varies a
lot more than b
).
The function f(x) = x % n
behaves in a sane way;
as x
increases, f(x)
cycles through the
values 0,1, ..., n-1, 0, ...
. Nothing
strange happens when you cross zero.
The %
operator implements the binary "mod" operation,
as defined by Donald Knuth (see the Art of Computer Programming,
1.2.4). It should be noted that Pike treats %-by-0 as an error
rather than returning 0, though.
/
and %
are compatible, so that
a == b*
for all floor
(a/b) + a%ba
and b
.
`/
, floor()
mixed
`&(mixed
arg1
)
mixed
`&(mixed
arg1
, mixed
arg2
, mixed
... extras
)
mixed
`&(object
arg1
, mixed
arg2
)
mixed
`&(mixed
arg1
, object
arg2
)
int
`&(int
arg1
, int
arg2
)
string
`&(string
arg1
, string
arg2
)
array
`&(array
arg1
, array
arg2
)
mapping
`&(mapping
arg1
, mapping
arg2
)
mapping
`&(mapping
arg1
, array
arg2
)
mapping
`&(mapping
arg1
, multiset
arg2
)
multiset
`&(multiset
arg1
, multiset
arg2
)
type
`&(type
|program
arg1
, type
|program
arg2
)
Bitwise and/intersection.
Every expression with the &
operator becomes a call to
this function, i.e. a&b
is the same as
predef::`&(a,b)
.
If there's a single argument, that argument is returned.
If there are more than two arguments the result is:
`&(`&(
.arg1
, arg2
), @extras
)
Otherwise, if arg1
is an object with an lfun::`&()
, that
function is called with arg2
as argument, and its result is
returned.
Otherwise, if arg2
is an object with an lfun::``&()
, that
function is called with arg1
as argument, and its result is
returned.
Otherwise the result depends on the argument types:
arg1
can have any of the following types:
| Bitwise and of |
| The result is a string where each character is the bitwise
and of the characters in the same position in |
| The result is like |
| Type intersection of |
The function is not destructive on the arguments - the result is always a new instance.
`|()
, lfun::`&()
, lfun::``&()
mixed
`()(function
(:void
) fun
, mixed
... args
)
mixed
call_function(function
(:void
) fun
, mixed
... args
)
Call a function.
Calls the function fun
with the arguments specified by args
.
lfun::`()()
mixed
`*(mixed
arg1
)
mixed
`*(object
arg1
, mixed
arg2
, mixed
... extras
)
mixed
`*(mixed
arg1
, object
arg2
)
array
`*(array
arg1
, int
arg2
)
array
`*(array
arg1
, float
arg2
)
string
`*(string
arg1
, int
arg2
)
string
`*(string
arg1
, float
arg2
)
string
`*(array
(string
) arg1
, string
arg2
)
array
`*(array
(array
) arg1
, array
arg2
)
float
`*(float
arg1
, int
|float
arg2
)
float
`*(int
arg1
, float
arg2
)
int
`*(int
arg1
, int
arg2
)
mixed
`*(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Multiplication/repetition/implosion.
Every expression with the *
operator becomes a call to
this function, i.e. a*b
is the same as
predef::`*(a,b)
. Longer *
expressions are
normally optimized to one call, so e.g. a*b*c
becomes
predef::`*(a,b,c)
.
If there's a single argument, that argument will be returned.
If the first argument is an object that implements lfun::`*()
,
that function will be called with the rest of the arguments.
If there are more than two arguments, the result will be
`*(`*(
.arg1
, arg2
), @extras
)
If arg2
is an object that implements lfun::``*()
, that
function will be called with arg1
as the single argument.
Otherwise the result will be as follows:
arg1
can have any of the following types:
| arg2 can have any of the following types:
| ||||
| The result will be | ||||
| The result will be |
In Pike 7.0 and earlier the multiplication order was unspecified.
`+()
, `-()
, `/()
, lfun::`*()
, lfun::``*()
mixed
`+(mixed
arg
)
mixed
`+(object
arg
, mixed
... more
)
int
`+(int
arg
, int
... more
)
float
`+(float
|int
arg
, float
|int
... more
)
string
`+(string
|float
|int
arg
, string
|float
|int
... more
)
array
`+(array
arg
, array
... more
)
mapping
`+(mapping
arg
, mapping
... more
)
multiset
`+(multiset
arg
, multiset
... more
)
Addition/concatenation.
Every expression with the +
operator becomes a call to
this function, i.e. a+b
is the same as
predef::`+(a,b)
. Longer +
expressions are
normally optimized to one call, so e.g. a+b+c
becomes
predef::`+(a,b,c)
.
If there's a single argument, that argument is returned.
If arg
is an object with only one reference and an
lfun::`+=()
, that function is called with the rest of the
arguments, and its result is returned.
Otherwise, if arg
is an object with an lfun::`+()
, that
function is called with the rest of the arguments, and its
result is returned.
Otherwise, if any of the other arguments is an object that has
an lfun::``+()
, the first such function is called with the
arguments leading up to it, and `+()
is then called
recursively with the result and the rest of the arguments.
Otherwise, if arg
is UNDEFINED
and the other arguments are
either arrays, mappings or multisets, the first argument is
ignored and the remaining are added together as described below.
This is useful primarily when appending to mapping values since
m[x] += ({foo})
will work even if m[x]
doesn't
exist yet.
Otherwise the result depends on the argument types:
| The result is the sum of all the arguments. It's a float if any argument is a float. |
| If any argument is a string, all will be converted to strings and concatenated in order to form the result. |
| The array arguments are concatened in order to form the result. |
| The result is like |
| The result is like |
The function is not destructive on the arguments - the result is always a new instance.
In Pike 7.0 and earlier the addition order was unspecified.
The treatment of UNDEFINED
was new
in Pike 7.0.
`-()
, lfun::`+()
, lfun::``+()
mixed
`-(mixed
arg1
)
mixed
`-(mixed
arg1
, mixed
arg2
, mixed
... extras
)
mixed
`-(object
arg1
, mixed
arg2
)
mixed
`-(mixed
arg1
, object
arg2
)
int
`-(int
arg1
, int
arg2
)
float
`-(float
arg1
, int
|float
arg2
)
float
`-(int
|float
arg1
, float
arg2
)
string
`-(string
arg1
, string
arg2
)
array
`-(array
arg1
, array
arg2
)
mapping
`-(mapping
arg1
, array
arg2
)
mapping
`-(mapping
arg1
, mapping
arg2
)
mapping
`-(mapping
arg1
, multiset
arg2
)
multiset
`-(multiset
arg1
, multiset
arg2
)
Negation/subtraction/set difference.
Every expression with the -
operator becomes a call to
this function, i.e. -a
is the same as
predef::`-(a)
and a-b
is the same as
predef::`-(a,b)
. Longer -
expressions are
normally optimized to one call, so e.g. a-b-c
becomes
predef::`-(a,b,c)
.
If there's a single argument, that argument is returned negated.
If arg1
is an object with an lfun::`-()
, that function is
called without arguments, and its result is returned.
If there are more than two arguments the result is:
`-(`-(
.arg1
, arg2
), @extras
)
Otherwise, if arg1
is an object with an lfun::`-()
, that
function is called with arg2
as argument, and its result is
returned.
Otherwise, if arg2
is an object with an lfun::``-()
, that
function is called with arg1
as argument, and its result is
returned.
Otherwise the result depends on the argument types:
arg1
can have any of the following types:
| The result is |
| The result is |
| The result is like |
The function is not destructive on the arguments - the result is always a new instance.
In Pike 7.0 and earlier the subtraction order was unspecified.
`+()
mixed
`->(object
arg
, string
index
)
mixed
`->(int
arg
, string
index
)
mixed
`->(array
arg
, string
index
)
mixed
`->(mapping
arg
, string
index
)
bool
`->(multiset
arg
, string
index
)
mixed
`->(program
arg
, string
index
)
Arrow indexing.
Every non-lvalue expression with the ->
operator becomes
a call to this function. a->b
is the same as
predef::`^(a,"b")
where "b"
is the symbol
b
in string form.
This function behaves like `[]
, except that the index is
passed literally as a string instead of being evaluated.
If arg
is an object that implements lfun::`->()
, that function
will be called with index
as the single argument.
Otherwise the result will be as follows:
arg
can have any of the following types:
| The non-protected (ie public) symbol named |
| The bignum function named |
| An array of all elements in |
| If |
| If |
| The non-protected (ie public) constant symbol |
In an expression a->b
, the symbol b
can be any
token that matches the identifier syntax - keywords are
disregarded in that context.
An arrow indexing expression in an lvalue context, i.e. where
the index is being assigned a new value, uses `->=
instead of
this function.
`[]()
, lfun::`->()
, ::`->()
, `->=
mixed
`->=(object
arg
, string
index
, mixed
val
)
mixed
`->=(mapping
arg
, string
index
, mixed
val
)
bool
`->=(multiset
arg
, string
index
, bool
val
)
Arrow index assignment.
Every lvalue expression with the ->
operator becomes a
call to this function, i.e. a->b=c
is the same as
predef::`->=(a,"b",c)
where "b"
is the symbol
b
in string form.
This function behaves like `[]=
, except that the index is
passed literally as a string instead of being evaluated.
If arg
is an object that implements lfun::`->=()
, that function
will be called with index
and val
as the arguments.
arg
can have any of the following types:
| The non-protected (ie public) variable named |
| Index |
| If |
val
will be returned.
In an expression a->b=c
, the symbol b
can be any
token that matches the identifier syntax - keywords are
disregarded in that context.
An arrow indexing expression in a non-lvalue context, i.e. where
the index is being queried instead of assigned, uses `->
instead of this function.
`[]=()
, lfun::`->=()
, `->
mixed
`/(object
arg1
, mixed
arg2
)
mixed
`/(mixed
arg1
, object
arg2
)
array
(string
) `/(string
arg1
, int
arg2
)
array
(string
) `/(string
arg1
, float
arg2
)
array
(array
) `/(array
arg1
, int
arg2
)
array
(array
) `/(array
arg1
, float
arg2
)
array
(string
) `/(string
arg1
, string
arg2
)
array
(array
) `/(array
arg1
, array
arg2
)
float
`/(float
arg1
, int
|float
arg2
)
float
`/(int
arg1
, float
arg2
)
int
`/(int
arg1
, int
arg2
)
mixed
`/(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Division/split.
Every expression with the /
operator becomes a call to
this function, i.e. a/b
is the same as
predef::`/(a,b)
.
If there are more than two arguments, the result will be
`/(`/(
.arg1
, arg2
), @extras
)
If arg1
is an object that implements lfun::`/()
, that
function will be called with arg2
as the single argument.
If arg2
is an object that implements lfun::``/()
, that
function will be called with arg1
as the single argument.
Otherwise the result will be as follows:
arg1
can have any of the following types:
| arg2 can have any of the following types:
| ||||
| arg2 can have any of the following types:
| ||||
| The result will be |
Unlike in some languages, the function f(x) = x/n (x and n integers) behaves in a well-defined way and is always rounded down. When you increase x, f(x) will increase with one for each n:th increment. For all x, (x + n) / n = x/n + 1; crossing zero is not special. This also means that / and % are compatible, so that a = b*(a/b) + a%b for all a and b.
`%
bool
`<(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Less than test.
Every expression with the <
operator becomes a call to
this function, i.e. a<b
is the same as
predef::`<(a,b)
.
Returns 1
if the test is successful, 0
otherwise.
`<=()
, `>()
, `>=()
int
`<<(int
arg1
, int
arg2
)
mixed
`<<(object
arg1
, int
|object
arg2
)
mixed
`<<(int
arg1
, object
arg2
)
Left shift.
Every expression with the <<
operator becomes a call to
this function, i.e. a<<b
is the same as
predef::`<<(a,b)
.
If arg1
is an object that implements lfun::`<<()
, that
function will be called with arg2
as the single argument.
If arg2
is an object that implements lfun::``<<()
, that
function will be called with arg1
as the single argument.
Otherwise arg1
will be shifted arg2
bits left.
`>>()
bool
`<=(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Less than or equal test.
Every expression with the <=
operator becomes a call to
this function, i.e. a<=b
is the same as
predef::`<=(a,b)
.
Returns 1
if the test is successful, 0
otherwise.
For total orders, e.g. integers, this is the inverse of `>()
.
`<()
, `>()
, `>=()
bool
`==(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Equality test.
Every expression with the ==
operator becomes a call to
this function, i.e. a==b
is the same as
predef::`==(a,b)
.
If more than two arguments are given, each argument is compared with the following one as described below, and the test is successful iff all comparisons are successful.
If the first argument is an object with an lfun::`==()
, that
function is called with the second as argument, unless the
second argument is the same as the first argument. The test is
successful iff its result is nonzero (according to `!
).
Otherwise, if the second argument is an object with an
lfun::`==()
, that function is called with the first as
argument, and the test is successful iff its result is nonzero
(according to `!
).
Otherwise, if the arguments are of different types, the test is unsuccessful. Function pointers to programs are automatically converted to program pointers if necessary, though.
Otherwise the test depends on the type of the arguments:
| Successful iff the two integers are numerically equal. |
| Successful iff the two floats are numerically equal and not NaN. |
| Successful iff the two strings are identical, character for character. (Since all strings are kept unique, this is actually a test whether the arguments point to the same string, and it therefore run in constant time.) |
| Successful iff the two arguments point to the same instance. |
Returns 1
if the test is successful, 0
otherwise.
Floats and integers are not automatically converted to test
against each other, so e.g. 0==0.0
is false.
Programs are not automatically converted to types to be compared type-wise.
`!()
, `!=()
bool
`>(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Greater than test.
Every expression with the >
operator becomes a call to
this function, i.e. a>b
is the same as
predef::`>(a,b)
.
Returns 1
if the arguments are strictly decreasing, and
0
(zero) otherwise.
`<()
, `<=()
, `>=()
bool
`>=(mixed
arg1
, mixed
arg2
, mixed
... extras
)
Greater than or equal test.
Every expression with the >=
operator becomes a call to
this function, i.e. a>=b
is the same as
predef::`>=(a,b)
.
Returns 1
if the test is successful, 0
otherwise.
For total orders, e.g. integers, this is the inverse of `<()
.
`<=()
, `>()
, `<()
int
`>>(int
arg1
, int
arg2
)
mixed
`>>(object
arg1
, int
|object
arg2
)
mixed
`>>(int
arg1
, object
arg2
)
Right shift.
Every expression with the >>
operator becomes a call to
this function, i.e. a>>b
is the same as
predef::`>>(a,b)
.
If arg1
is an object that implements lfun::`>>()
, that
function will be called with arg2
as the single argument.
If arg2
is an object that implements lfun::``>>()
, that
function will be called with arg1
as the single argument.
Otherwise arg1
will be shifted arg2
bits right.
`<<()
mixed
`[..](object
arg
, mixed
start
, int
start_type
, mixed
end
, int
end_type
)
string
`[..](string
arg
, int
start
, int
start_type
, int
end
, int
end_type
)
array
`[..](array
arg
, int
start
, int
start_type
, int
end
, int
end_type
)
Extracts a subrange.
This is the function form of expressions with the [..]
operator. arg
is the thing from which the subrange is to be
extracted. start
is the lower bound of the subrange and
end
the upper bound.
start_type
and end_type
specifies how the start
and
end
indices, respectively, are to be interpreted. The types
are either Pike.INDEX_FROM_BEG
, Pike.INDEX_FROM_END
or
Pike.OPEN_BOUND
. In the last case, the index value is
insignificant.
The relation between [..]
expressions and this function
is therefore as follows:
a[i..j] <=> `[..] (a, i, Pike.INDEX_FROM_BEG, j, Pike.INDEX_FROM_BEG)
a[i..<j] <=> `[..] (a, i, Pike.INDEX_FROM_BEG, j, Pike.INDEX_FROM_END)
a[i..] <=> `[..] (a, i, Pike.INDEX_FROM_BEG, 0, Pike.OPEN_BOUND)
a[<i..j] <=> `[..] (a, i, Pike.INDEX_FROM_END, j, Pike.INDEX_FROM_BEG)
a[<i..<j] <=> `[..] (a, i, Pike.INDEX_FROM_END, j, Pike.INDEX_FROM_END)
a[<i..] <=> `[..] (a, i, Pike.INDEX_FROM_END, 0, Pike.OPEN_BOUND)
a[..j] <=> `[..] (a, 0, Pike.OPEN_BOUND, j, Pike.INDEX_FROM_BEG)
a[..<j] <=> `[..] (a, 0, Pike.OPEN_BOUND, j, Pike.INDEX_FROM_END)
a[..] <=> `[..] (a, 0, Pike.OPEN_BOUND, 0, Pike.OPEN_BOUND)
The subrange is specified as follows by the two bounds:
If the lower bound refers to an index before the lowest allowable (typically zero) then it's taken as an open bound which starts at the first index (without any error).
Correspondingly, if the upper bound refers to an index past the last allowable then it's taken as an open bound which ends at the last index (without any error).
If the lower bound is less than or equal to the upper bound, then the subrange is the inclusive range between them, i.e. from and including the element at the lower bound and up to and including the element at the upper bound.
If the lower bound is greater than the upper bound then the result is an empty subrange (without any error).
The returned value depends on the type of arg
:
arg
can have any of the following types:
| A string with the characters in the range is returned. |
| An array with the elements in the range is returned. |
| If the object implements As a compatibility measure, if the object does not implement
Note that |
lfun::`[..]
, `[]
mixed
`[](object
arg
, mixed
index
)
mixed
`[](object
arg
, string
index
)
function
(:void
) `[](int
arg
, string
index
)
int
`[](string
arg
, int
index
)
mixed
`[](array
arg
, int
index
)
mixed
`[](array
arg
, mixed
index
)
mixed
`[](mapping
arg
, mixed
index
)
bool
`[](multiset
arg
, mixed
index
)
mixed
`[](program
arg
, string
index
)
mixed
`[](object
arg
, mixed
start
, mixed
end
)
string
`[](string
arg
, int
start
, int
end
)
array
`[](array
arg
, int
start
, int
end
)
Indexing.
This is the function form of expressions with the []
operator, i.e. a[i]
is the same as
predef::`[](a,i)
.
If arg
is an object that implements lfun::`[]()
, that
function is called with the index
argument.
Otherwise, the action depends on the type of arg
:
arg
can have any of the following types:
| The non-protected (i.e. public) symbol named |
| The bignum function named |
| The character at index |
| If If |
| If |
| If |
| The non-protected (i.e. public) constant symbol |
As a compatibility measure, this function also performs range operations if it's called with three arguments. In that case it becomes equivalent to:
`[..] (arg, start, Pike.INDEX_FROM_BEG, end, Pike.INDEX_FROM_BEG)
See `[..]
for further details.
An indexing expression in an lvalue context, i.e. where the
index is being assigned a new value, uses `[]=
instead of
this function.
`->()
, lfun::`[]()
, `[]=
, `[..]
mixed
`[]=(object
arg
, mixed
index
, mixed
val
)
mixed
`[]=(object
arg
, string
index
, mixed
val
)
mixed
`[]=(array
arg
, int
index
, mixed
val
)
mixed
`[]=(mapping
arg
, mixed
index
, mixed
val
)
bool
`[]=(multiset
arg
, mixed
index
, bool
val
)
Index assignment.
Every lvalue expression with the []
operator becomes a
call to this function, i.e. a[b]=c
is the same as
predef::`[]=(a,b,c)
.
If arg
is an object that implements lfun::`[]=()
, that function
will be called with index
and val
as the arguments.
arg
can have any of the following types:
| The non-protected (ie public) variable named |
| Index |
| If |
val
will be returned.
An indexing expression in a non-lvalue context, i.e. where the
index is being queried instead of assigned, uses `[]
instead
of this function.
`->=()
, lfun::`[]=()
, `[]
mixed
`^(mixed
arg1
)
mixed
`^(mixed
arg1
, mixed
arg2
, mixed
... extras
)
mixed
`^(object
arg1
, mixed
arg2
)
mixed
`^(mixed
arg1
, object
arg2
)
int
`^(int
arg1
, int
arg2
)
string
`^(string
arg1
, string
arg2
)
array
`^(array
arg1
, array
arg2
)
mapping
`^(mapping
arg1
, mapping
arg2
)
multiset
`^(multiset
arg1
, multiset
arg2
)
type
`^(program
|type
arg1
, program
|type
arg2
)
Exclusive or.
Every expression with the ^
operator becomes a call to
this function, i.e. a^b
is the same as
predef::`^(a,b)
.
If there's a single argument, that argument is returned.
If there are more than two arguments, the result is:
`^(`^(
.arg1
, arg2
), @extras
)
Otherwise, if arg1
is an object with an lfun::`^()
, that
function is called with arg2
as argument, and its result is
returned.
Otherwise, if arg2
is an object with an lfun::``^()
, that
function is called with arg1
as argument, and its result is
returned.
Otherwise the result depends on the argument types:
arg1
can have any of the following types:
| Bitwise exclusive or of |
| The result is a string where each character is the bitwise
exclusive or of the characters in the same position in
|
| The result is an array with the elements in Every element is only matched once against an element in the other array, so if one contains several elements that are equal to each other and are more than their counterparts in the other array, the rightmost remaining elements are kept. |
| The result is like |
| The result is like |
| The result is a type computed like this:
|
The function is not destructive on the arguments - the result is always a new instance.
`&()
, `|()
, lfun::`^()
, lfun::``^()
mixed
`|(mixed
arg1
)
mixed
`|(mixed
arg1
, mixed
arg2
, mixed
... extras
)
mixed
`|(object
arg1
, mixed
arg2
)
mixed
`|(mixed
arg1
, object
arg2
)
int
`|(int
arg1
, int
arg2
)
string
`|(string
arg1
, string
arg2
)
array
`|(array
arg1
, array
arg2
)
mapping
`|(mapping
arg1
, mapping
arg2
)
multiset
`|(multiset
arg1
, multiset
arg2
)
type
`|(program
|type
arg1
, program
|type
arg2
)
Bitwise or/union.
Every expression with the |
operator becomes a call to
this function, i.e. a|b
is the same as
predef::`|(a,b)
.
If there's a single argument, that argument is returned.
If there are more than two arguments, the result is:
`|(`|(
.arg1
, arg2
), @extras
)
Otherwise, if arg1
is an object with an lfun::`|()
, that
function is called with arg2
as argument, and its result is
returned.
Otherwise, if arg2
is an object with an lfun::``|()
, that
function is called with arg1
as argument, and its result is
returned.
Otherwise the result depends on the argument types:
arg1
can have any of the following types:
| Bitwise or of |
| The result is a string where each character is the bitwise
or of the characters in the same position in |
| The result is an array with the elements in Every element in |
| The result is like |
| The result is like |
| Type union of |
The function is not destructive on the arguments - the result is always a new instance.
`&()
, lfun::`|()
, lfun::``|()
mixed
`~(object
arg
)
int
`~(int
arg
)
float
`~(float
arg
)
type
`~(type
|program
arg
)
string
`~(string
arg
)
Complement/inversion.
Every expression with the ~
operator becomes a call to
this function, i.e. ~a
is the same as
predef::`~(a)
.
The result will be as follows:
arg
can have any of the following types:
| If |
| The bitwise inverse of |
| The result will be |
| The type inverse of |
| If |
`!()
, lfun::`~()
float
abs(float
f
)
int
abs(int
f
)
object
abs(object
f
)
Return the absolute value for f
. If f
is
an object it must implement lfun::`<
and
unary lfun::`-
.
int
access(string
path
, string
|void
mode
)
access() checks if the calling process can access the file
path
. Symbolic links are dereferenced.
mode
The mode
specifies the accessibility checks to be performed, and
is either not specified or empty, in which case access() just tests
if the file exists, or one or more of the characters "rwx"
.
r, w, and x test whether the file exists and grants read, write, and execute permissions, respectively.
The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file. This allows set-user-ID programs to easily determine the invoking user's authority.
If the calling process is privileged (i.e., its real UID is zero), then an X_OK check is successful for a regular file if execute permission is enabled for any of the file owner, group, or other.
| When the file is accessible using the given permissions. | ||||||||||||
| When the file is not accessible, in which case
Other errors can occur, but are not directly related to the
requested path, such as |
errno()
, Stdio.File
float
acos(int
|float
f
)
Return the arcus cosine value for f
.
The result will be in radians.
cos()
, asin()
float
acosh(int
|float
f
)
Return the hyperbolic arcus cosine value for f
.
cosh()
, asinh()
void
add_constant(string
name
, mixed
value
)
void
add_constant(string
name
)
Add a new predefined constant.
This function is often used to add builtin functions.
All programs compiled after the add_constant()
function has been
called can access value
by the name name
.
If there is a constant called name
already, it will be replaced by
by the new definition. This will not affect already compiled programs.
Calling add_constant()
without a value will remove that name from
the list of constants. As with replacing, this will not affect already
compiled programs.
all_constants()
array
aggregate(mixed
... elements
)
Construct an array with the arguments as indices.
This function could be written in Pike as:
array aggregate(mixed ... elems) { return elems; }
Arrays are dynamically allocated there is no need to declare them
like int a[10]=allocate(10);
(and it isn't possible either) like
in C, just array(int) a=allocate(10);
will do.
sizeof()
, arrayp()
, allocate()
mapping
aggregate_mapping(mixed
... elems
)
Construct a mapping.
Groups the arguments together two and two in key-index pairs and
creates a mapping of those pairs. Generally, the mapping literal
syntax is handier: ([ key1:val1, key2:val2, ... ])
sizeof()
, mappingp()
, mkmapping()
multiset
aggregate_multiset(mixed
... elems
)
Construct a multiset with the arguments as indices. The multiset
will not contain any values. This method is most useful when
constructing multisets with map
or similar; generally, the
multiset literal syntax is handier: (<elem1, elem2, ...>)
With it, it's also possible to construct a multiset with values:
(<index1: value1, index2: value2, ...>)
sizeof()
, multisetp()
, mkmultiset()
int
alarm(int
seconds
)
Set an alarm clock for delivery of a signal.
alarm()
arranges for a SIGALRM signal to be delivered to the
process in seconds
seconds.
If seconds
is 0
(zero), no new alarm will be scheduled.
Any previous alarms will in any case be canceled.
Returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
ualarm()
, signal()
, call_out()
mapping
(string
:mixed
) all_constants()
Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.
add_constant()
array
allocate(int
size
)
array
allocate(int
size
, mixed
init
)
Allocate an array of size
elements. If init
is specified
then each element is initialized by copying that value
recursively.
sizeof()
, aggregate()
, arrayp()
array
array_sscanf(string
data
, string
format
)
This function works just like sscanf()
, but returns the matched
results in an array instead of assigning them to lvalues. This is often
useful for user-defined sscanf strings.
sscanf()
, `/()
int
arrayp(mixed
arg
)
Returns 1
if arg
is an array, 0
(zero) otherwise.
intp()
, programp()
, mappingp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
float
asin(int
|float
f
)
Return the arcus sine value for f
.
The result will be in radians.
sin()
, acos()
float
asinh(int
|float
f
)
Return the hyperbolic arcus sine value for f
.
sinh()
, acosh()
float
atan(int
|float
f
)
Returns the arcus tangent value for f
.
The result will be in radians.
tan()
, asin()
, acos()
, atan2()
float
atan2(float
f1
, float
f2
)
Returns the arcus tangent value for f1
/f2
, and uses
the signs of f1
and f2
to determine the quadrant.
The result will be in radians.
tan()
, asin()
, acos()
, atan()
float
atanh(int
|float
f
)
Returns the hyperbolic arcus tangent value for f
.
tanh()
, asinh()
, acosh()
void
atexit(function
(:void
) callback
)
This function puts the callback
in a queue of callbacks to
call when pike exits. The call order is reversed, i.e. callbacks
that have been added earlier are called after callback
.
Please note that atexit
callbacks are not called if Pike
exits abnormally.
exit()
, _exit()
array
(Pike.BacktraceFrame
) backtrace()
FIXME: This documentation is not up to date!
Get a description of the current call stack.
The description is returned as an array with one entry for each call frame on the stack.
Each entry has this format:
Array | |
| A string with the filename if known, else zero. |
| An integer containing the linenumber if known, else zero. |
| The function that was called at this level. |
| The arguments that the function was called with. |
The current call frame will be last in the array.
Please note that the frame order may be reversed in a later version (than 7.1) of Pike to accommodate for deferred backtraces.
Note that the arguments reported in the backtrace are the current values of the variables, and not the ones that were at call-time. This can be used to hide sensitive information from backtraces (eg passwords).
catch()
, throw()
string
basename(string
x
)
Returns the last segment of a path.
dirname()
, explode_path()
string
basetype(mixed
x
)
Same as sprintf("%t",x);
sprintf()
int
callablep(mixed
arg
)
Returns 1
if arg
is a callable, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, intp()
int
cd(string
s
)
Change the current directory for the whole Pike process.
Returns 1
for success, 0
(zero) otherwise.
getcwd()
float
ceil(int
|float
f
)
Return the closest integer value greater or equal to f
.
ceil()
does not return an int
, merely an integer value
stored in a float
.
floor()
, round()
array
column(array
data
, mixed
index
)
Extract a column from a two-dimensional array.
This function is exactly equivalent to:
map(data, lambda(mixed x,mixed y) { return x[y]; }, index)
Except of course it is a lot shorter and faster. That is, it indices every index in the array data on the value of the argument index and returns an array with the results.
rows()
string
combine_path(string
path
, string
... paths
)
string
combine_path_unix(string
path
, string
... paths
)
string
combine_path_nt(string
path
, string
... paths
)
string
combine_path_amigaos(string
path
, string
... paths
)
Concatenate a number of paths to a straightforward path without
any "//"
, "/.."
or "/."
. If any path
argument is absolute then the result is absolute and the
preceding arguments are ignored. If the result is relative then
it might have leading ".."
components. If the last
nonempty argument ends with a directory separator then the
result ends with that too. If all components in a relative path
disappear due to subsequent ".."
components then the
result is "."
.
combine_path_unix()
concatenates in UNIX style, which also is
appropriate for e.g. URL:s ("/" separates path components and
absolute paths start with "/"). combine_path_nt()
concatenates according to NT filesystem conventions ("/" and "\"
separates path components and there might be a drive letter in
front of absolute paths). combine_path_amigaos()
concatenates
according to AmigaOS filesystem conventions.
combine_path()
is equivalent to combine_path_unix()
on UNIX-like
operating systems, and equivalent to combine_path_nt()
on NT-like
operating systems, and equivalent to combine_path_amigaos()
on
AmigaOS-like operating systems.
getcwd()
, Stdio.append_path()
program
compile(string
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
Compile a string to a program.
This function takes a piece of Pike code as a string and compiles it into a clonable program.
The optional argument handler
is used to specify an alternative
error handler. If it is not specified the current master object will
be used.
The optional arguments major
and minor
are used to tell the
compiler to attempt to be compatible with Pike major
.minor
.
Note that source
must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that compile()
does not preprocess the program.
To preprocess the program you can use compile_string()
or
call the preprocessor manually by calling cpp()
.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
, DefaultCompilerEnvironment
program
compile_file(string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
)
Compile the Pike code contained in the file filename
into a program.
This function will compile the file filename
to a Pike program that can
later be instantiated. It is the same as doing
.compile_string
(Stdio.read_file
(filename
), filename
)
compile()
, compile_string()
, cpp()
program
compile_string(string
source
, void
|string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
, void
|int
_show_if_constant_errors
)
Compile the Pike code in the string source
into a program.
If filename
is not specified, it will default to "-"
.
Functionally equal to
.compile
(cpp
(source
, filename
))
compile()
, cpp()
, compile_file()
mixed
copy_value(mixed
value
)
Copy a value recursively.
If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed.
The resulting value will always be equal to the copied (as tested with
the function equal()
), but they may not the the same value (as tested
with `==()
).
equal()
float
cos(int
|float
f
)
Return the cosine value for f
.
f
should be specified in radians.
acos()
, sin()
, tan()
float
cosh(int
|float
f
)
Return the hyperbolic cosine value for f
.
acosh()
, sinh()
, tanh()
string
cpp(string
data
, mapping
|string
|void
current_file
, int
|string
|void
charset
, object
|void
handler
, void
|int
compat_major
, void
|int
compat_minor
, void
|int
picky_cpp
)
Run a string through the preprocessor.
Preprocesses the string data
with Pike's builtin ANSI-C look-alike
preprocessor. If the current_file
argument has not been specified,
it will default to "-"
. charset
defaults to "ISO-10646"
.
If the second argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
compile()
string(7bit)
crypt(string
password
)
bool
crypt(string
typed_password
, string
crypted_password
)
This function crypts and verifies a short string (only the first 8 characters are significant).
The first syntax crypts the string password
into something that
is hopefully hard to decrypt.
The second syntax is used to verify typed_password
against
crypted_password
, and returns 1
if they match, and
0
(zero) otherwise.
Note that strings containing null characters will only be processed up until the null character.
string
ctime(int
timestamp
)
Convert the output from a previous call to time()
into a readable
string containing the current year, month, day and time.
Like localtime
, this function might throw an error if the
ctime(2) call failed on the system. It's platform dependent what
time ranges that function can handle, e.g. Windows doesn't handle
a negative timestamp
.
time()
, localtime()
, mktime()
, gmtime()
mixed
decode_value(string
coded_value
, void
|Codec
|int(-1..-1)
codec
)
Decode a value from the string coded_value
.
This function takes a string created with encode_value()
or
encode_value_canonic()
and converts it back to the value that was
coded.
If codec
is specified, it's used as the codec for the decode.
If none is specified, then one is instantiated through
master()->Decoder()
. As a compatibility fallback, the
master itself is used if it has no Decoder
class.
If codec
is the special value -1
, then decoding of
types, functions, programs and objects is disabled.
Decoding a coded_value
that you have not generated yourself
is a security risk that can lead to execution of arbitrary
code, unless codec
is specified as -1
.
encode_value()
, encode_value_canonic()
void
delay(int
|float
s
)
This function makes the program stop for s
seconds.
Only signal handlers can interrupt the sleep. Other callbacks are not called during delay. Beware that this function uses busy-waiting to achieve the highest possible accuracy.
signal()
, sleep()
string
describe_backtrace(mixed
trace
, void
|int
linewidth
)
Return a readable message that describes where the backtrace
trace
was made (by backtrace
).
It may also be an error object or array (typically caught by a
catch
), in which case the error message also is included in the
description.
Pass linewidth
-1 to disable wrapping of the output.
backtrace()
, describe_error()
, catch()
, throw()
string
describe_error(mixed
err
)
Return the error message from an error object or array (typically
caught by a catch
). The type of the error is checked, hence
err
is declared as mixed
and not object|array
.
If an error message couldn't be obtained, a fallback message
describing the failure is returned. No errors due to incorrectness
in err
are thrown.
describe_backtrace()
, get_backtrace
void
destruct(void
|object
o
)
Mark an object as destructed.
Calls o->destroy()
, and then clears all variables in the
object. If no argument is given, the current object is destructed.
All pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible.
int
destructedp(mixed
arg
)
Returns 1
if arg
is a destructed object, 0
(zero) otherwise.
zero_type
, undefinedp
, intp
string
dirname(string
x
)
Returns all but the last segment of a path. Some example inputs and outputs:
Expression | Value |
dirname("/a/b") | "/a" |
dirname("/a/") | "/a" |
dirname("/a") | "/" |
dirname("/") | "/" |
dirname("") | "" |
basename()
, explode_path()
string
encode_value(mixed
value
, Codec
|void
codec
)
Code a value into a string.
This function takes a value, and converts it to a string. This string
can then be saved, sent to another Pike process, packed or used in
any way you like. When you want your value back you simply send this
string to decode_value()
and it will return the value you encoded.
Almost any value can be coded, mappings, floats, arrays, circular structures etc.
If codec
is specified, it's used as the codec for the encode.
If none is specified, then one is instantiated through
master()->Encoder()
. As a compatibility fallback, the
master itself is used if it has no Encoder
class.
If
returns UNDEFINED for an
object, codec
->nameof(o)val = o->encode_object(o)
will be called. The
returned value will be passed to o->decode_object(o, val)
when the object is decoded.
When only simple types like int, floats, strings, mappings, multisets and arrays are encoded, the produced string is very portable between pike versions. It can at least be read by any later version.
The portability when objects, programs and functions are involved depends mostly on the codec. If the byte code is encoded, i.e. when Pike programs are actually dumped in full, then the string can probably only be read by the same pike version.
decode_value()
, sprintf()
, encode_value_canonic()
string
encode_value_canonic(mixed
value
, object
|void
codec
)
Code a value into a string on canonical form.
Takes a value and converts it to a string on canonical form, much like
encode_value()
. The canonical form means that if an identical value is
encoded, it will produce exactly the same string again, even if it's
done at a later time and/or in another Pike process. The produced
string is compatible with decode_value()
.
Note that this function is more restrictive than encode_value()
with
respect to the types of values it can encode. It will throw an error
if it can't encode to a canonical form.
encode_value()
, decode_value()
array
(int
) enumerate(int
n
)
array
enumerate(int
n
, void
|mixed
step
, void
|mixed
start
, void
|function
(:void
) operator
)
Create an array with an enumeration, useful for initializing arrays
or as first argument to map()
or foreach()
.
The defaults are: step
= 1, start
= 0, operator
= `+
The resulting array is calculated like this:
array enumerate(int n, mixed step, mixed start, function operator)
{
array res = allocate(n);
for (int i=0; i < n; i++)
{
res[i] = start;
start = operator(start, step);
}
return res;
}
map()
, foreach()
int
equal(mixed
a
, mixed
b
)
This function checks if the values a
and b
are equal.
For all types but arrays, multisets and mappings, this operation is
the same as doing
.
For arrays, mappings and multisets however, their contents are checked
recursively, and if all their contents are the same and in the same
place, they are considered equal.a
== b
copy_value()
int
errno()
This function returns the system error from the last file operation.
Note that you should normally use Stdio.File->errno()
instead.
Stdio.File->errno()
, strerror()
void
error(sprintf_format
f
, sprintf_args
... args
)
Throws an error. A more readable version of the code
throw( ({ sprintf(f, @args), backtrace() }) )
.
int
exece(string
file
, array
(string
) args
)
int
exece(string
file
, array
(string
) args
, mapping
(string
:string
) env
)
This function transforms the Pike process into a process running
the program specified in the argument file
with the arguments args
.
If the mapping env
is present, it will completely replace all
environment variables before the new program is executed.
This function only returns if something went wrong during exece(2),
and in that case it returns 0
(zero).
The Pike driver _dies_ when this function is called. You must either
use fork()
or Process.create_process()
if you wish to execute a
program and still run the Pike runtime.
This function is not available on all platforms.
Process.create_process()
, fork()
, Stdio.File->pipe()
void
exit(int
returncode
, void
|string
fmt
, mixed
... extra
)
Exit the whole Pike program with the given returncode
.
Using exit()
with any other value than 0
(zero) indicates
that something went wrong during execution. See your system manuals
for more information about return codes.
The arguments after the returncode
will be used for a call to
werror
to output a message on stderr.
_exit()
float
exp(float
|int
f
)
Return the natural exponential of f
.
log( exp( x ) ) == x
as long as exp(x) doesn't overflow an int.
pow()
, log()
array
(string
) explode_path(string
p
)
Split a path p
into its components.
This function divides a path into its components. This might seem like
it could be done by dividing the string on <tt>"/"</tt>, but that will
not work on some operating systems. To turn the components back into
a path again, use combine_path()
.
Stdio.Stat
file_stat(string
path
, void
|bool
symlink
)
Stat a file.
If the argument symlink
is 1
symlinks will not be followed.
If the path specified by path
doesn't exist 0
(zero) will
be returned.
Otherwise an object describing the properties of path
will be
returned.
In Pike 7.0 and earlier this function returned an array with 7 elements. The old behaviour can be simulated with the following function:
array(int) file_stat(string path, void|int(0..1) symlink)
{
File.Stat st = predef::file_stat(path, symlink);
if (!st) return 0;
return (array(int))st;
}
Stdio.Stat
, Stdio.File->stat()
int
file_truncate(string
file
, int
length
)
Truncates the file file
to the length specified in length
.
Returns 1 if ok, 0 if failed.
mapping
(string
:int
) filesystem_stat(string
path
)
Returns a mapping describing the properties of the filesystem
containing the path specified by path
.
If a filesystem cannot be determined 0
(zero) will be returned.
Otherwise a mapping(string:int) with the following fields will be returned:
| Size in bytes of the filesystem blocks. |
| Size of the entire filesystem in blocks. |
| Number of free blocks in the filesystem. |
| Number of available blocks in the filesystem.
This is usually somewhat less than the |
| Total number of files (aka inodes) allowed by this filesystem. |
| Number of free files in the filesystem. |
| Number of available files in the filesystem.
This is usually the same as the |
| Name assigned to the filesystem. This item is not available on all systems. |
| Type of filesystem (eg |
Please note that not all members are present on all OSs.
file_stat()
mixed
filter(mixed
arr
, void
|mixed
fun
, mixed
... extra
)
Filters the elements in arr
through fun
.
arr
is treated as a set of elements to be filtered, as
follows:
Each element is filtered with fun
. The return value is of
the same type as arr
and it contains the elements that
fun
accepted. fun
is applied in order to each element,
and that order is retained between the kept elements.
If fun
is an array, it should have the same length as
arr
. In this case, the elements in arr
are kept where
the corresponding positions in fun
are nonzero. Otherwise
fun
is used as described below.
The values are filtered with fun
, and the index/value
pairs it accepts are kept in the returned mapping.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
If there is a lfun::cast
method in the object, it's called
to try to cast the object to an array, a mapping, or a
multiset, in that order, which is then filtered as described
above.
Unless something else is mentioned above, fun
is used as
filter like this:
fun
is called for each element. It gets the current
element as the first argument and extra
as the rest. The
element is kept if it returns true, otherwise it's filtered
out.
The object is used as a function like above, i.e. the
lfun::`()
method in it is called.
fun
is indexed with each element. The element is kept if
the result is nonzero, otherwise it's filtered out.
Each element that is callable is called with extra
as
arguments. The element is kept if the result of the call is
nonzero, otherwise it's filtered out. Elements that aren't
callable are also filtered out.
Each element is indexed with the given string. If the result
of that is zero then the element is filtered out, otherwise
the result is called with extra
as arguments. The element
is kept if the return value is nonzero, otherwise it's
filtered out.
This is typically used when arr
is a collection of
objects, and fun
is the name of some predicate function
in them.
The function is never destructive on arr
.
map()
, foreach()
array
(object
) find_all_clones(program
p
, bool
|void
include_subclasses
)
Return an array with all objects that are clones of p
.
p
Program that the objects should be a clone of.
include_subclasses
If true, include also objects that are clones of programs
that have inherited p
. Note that this adds significant
overhead.
This function is only intended to be used for debug purposes.
map_all_objects()
int
floatp(mixed
arg
)
Returns 1
if arg
is a float, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, multisetp()
, objectp()
,
mappingp()
, stringp()
, functionp()
float
floor(int
|float
f
)
Return the closest integer value less or equal to f
.
floor()
does not return an int
, merely an integer value
stored in a float
.
ceil()
, round()
object
fork()
Fork the process in two.
Fork splits the process in two, and for the parent it returns a pid object for the child. Refer to your Unix manual for further details.
This function can cause endless bugs if used without proper care.
This function is disabled when using threads.
This function is not available on all platforms.
The most common use for fork is to start sub programs, which is
better done with Process.create_process()
.
Process.create_process()
string
function_name(function
(:void
)|program
f
)
Return the name of the function or program f
.
If f
is a global function defined in the runtime 0
(zero) will be returned.
function_object()
object
function_object(function
(:void
) f
)
Return the object the function f
is in.
If f
is a global function defined in the runtime 0
(zero) will be returned.
Zero will also be returned if f
is a constant in the
parent class. In that case function_program()
can be
used to get the parent program.
function_name()
, function_program()
program
function_program(function
(:void
)|program
f
)
Return the program the function f
is in.
If f
is a global function defined in the runtime 0
(zero) will be returned.
function_name()
, function_object()
int
functionp(mixed
arg
)
Returns 1
if arg
is a function, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, intp()
int
gc(mapping
|void
quick
)
Force garbage collection.
quick
Perform a quick garbage collection on just this value,
which must have been made weak by set_weak_flag()
.
All values that only have a single reference from
quick
will then be freed.
When quick
hasn't been specified or is UNDEFINED
,
this function checks all the memory for cyclic structures such
as arrays containing themselves and frees them if appropriate.
It also frees up destructed objects and things with only weak
references.
Normally there is no need to call this function since Pike will call it by itself every now and then. (Pike will try to predict when 20% of all arrays/object/programs in memory is 'garbage' and call this routine then.)
The amount of garbage is returned. This is the number of arrays, mappings, multisets, objects and programs that had no nonweak external references during the garbage collection. It's normally the same as the number of freed things, but there might be some difference since destroy() functions are called during freeing, which can cause more things to be freed or allocated.
Pike.gc_parameters
, Debug.gc_status
CompilationHandler
get_active_compilation_handler()
Returns the currently active compilation compatibility handler, or 0 (zero) if none is active.
This function should only be used during a call of compile()
.
get_active_error_handler()
, compile()
,
master()->get_compilation_handler()
, CompilationHandler
CompilationHandler
get_active_error_handler()
Returns the currently active compilation error handler
(second argument to compile()
), or 0 (zero) if none
is active.
This function should only be used during a call of compile()
.
get_active_compilation_handler()
, compile()
, CompilationHandler
array
(array
(int
|string
|array
(string
))) get_all_groups()
Returns an array of arrays with all groups in the system groups source.
Each element in the returned array has the same structure as in
getgrent
function.
The groups source is system dependant. Refer to your system manuals for information about how to set the source.
Array | |
| Array with info about the group |
getgrent()
array
(array
(int
|string
)) get_all_users()
Returns an array with all users in the system.
An array with arrays of userinfo as in getpwent
.
getpwent()
getpwnam()
getpwuid()
array
get_backtrace(object
|array
err
)
Return the backtrace array from an error object or array
(typically caught by a catch
), or zero if there is none. Errors
are thrown on if there are problems retrieving the backtrace.
describe_backtrace()
, describe_error()
array
(string
) get_dir(void
|string
dirname
)
Returns an array of all filenames in the directory dirname
, or
0
(zero) if the directory does not exist. When no
dirname
is given, current work directory is used.
mkdir()
, cd()
array
(int
) get_groups_for_user(int
|string
user
)
Gets all groups which a given user is a member of.
user
UID or loginname of the user
Array | |
| Information about all the users groups |
get_all_groups()
getgrgid()
getgrnam()
getpwuid()
getpwnam()
Iterator
get_iterator(object
|array
|mapping
|multiset
|string
data
)
Creates and returns a canonical iterator for data
.
data
can have any of the following types:
| If If |
| If |
| If |
| If |
| If |
This function is used by foreach
to get an iterator for an
object.
Iterator
, lfun::_get_iterator
array
(int
|mapping
(string
:array
(int
))) get_profiling_info(program
prog
)
Get profiling information.
Returns an array with two elements.
Array | |||||||||
| The first element is the number of times the program | ||||||||
| The second element is mapping from function name to an array with three elements.
|
This function is only available if the runtime was compiled with the option --with-profiling.
int
get_weak_flag(array
|mapping
|multiset
m
)
Returns the weak flag settings for m
. It's a combination of
Pike.WEAK_INDICES
and Pike.WEAK_VALUES
.
string
getcwd()
Returns the current working directory.
cd()
array
(int
|string
|array
(string
)) getgrgid(int
gid
)
Get the group entry for the group with the id gid
using the systemfunction
getgrid(3).
gid
The id of the group
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrnam()
array
(int
|string
|array
(string
)) getgrnam(string
str
)
Get the group entry for the group with the name str
using the
systemfunction getgrnam(3).
str
The name of the group
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrgid()
int
gethrdtime(void
|int
nsec
)
Return the high resolution real time spent with threads disabled
since the Pike interpreter was started. The time is normally
returned in microseconds, but if the optional argument nsec
is nonzero it's returned in nanoseconds.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION
.
_disable_threads()
, gethrtime()
int
gethrtime(void
|int
nsec
)
Return the high resolution real time since some arbitrary event in
the past. The time is normally returned in microseconds, but if
the optional argument nsec
is nonzero it's returned in
nanoseconds.
It's system dependent whether or not this time is monotonic, i.e.
if it's unaffected by adjustments of the calendaric clock in the
system. System.REAL_TIME_IS_MONOTONIC
tells what it is. Pike
tries to use monotonic time for this function if it's available.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION
.
System.REAL_TIME_IS_MONOTONIC
, System.REAL_TIME_RESOLUTION
,
time()
, System.gettimeofday()
, gethrvtime()
,
Pike.implicit_gc_real_time
int
gethrvtime(void
|int
nsec
)
Return the CPU time that has been consumed by this process or
thread. -1 is returned if the system couldn't determine it. The
time is normally returned in microseconds, but if the optional
argument nsec
is nonzero it's returned in nanoseconds.
The CPU time includes both user and system time, i.e. it's
approximately the same thing you would get by adding together the
"utime" and "stime" fields returned by System.getrusage
(but
perhaps with better accuracy).
It's however system dependent whether or not it's the time
consumed in all threads or in the current one only;
System.CPU_TIME_IS_THREAD_LOCAL
tells which. If both types are
available then thread local time is preferred.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.CPU_TIME_RESOLUTION
.
The garbage collector might run automatically at any time. The
time it takes is not included in the figure returned by this
function, so that normal measurements aren't randomly clobbered
by it. Explicit calls to gc
are still included, though.
The special function gauge
is implemented with this function.
System.CPU_TIME_IS_THREAD_LOCAL
, System.CPU_TIME_RESOLUTION
,
gauge()
, System.getrusage()
, gethrtime()
int
getpid()
Returns the process ID of this process.
System.getppid()
, System.getpgrp()
array
(int
|string
) getpwnam(string
str
)
Get the user entry for login str
using the systemfunction getpwnam(3).
str
The login name of the user whos userrecord is requested.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwuid()
getpwent()
array
(int
|string
) getpwuid(int
uid
)
Get the user entry for UID uid
using the systemfunction getpwuid(3).
uid
The uid of the user whos userrecord is requested.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwnam()
getpwent()
string
getxattr(string
file
, string
attr
, void
|bool
symlink
)
Return the value of a specified attribute, or 0 if it does not exist.
bool
glob(string
glob
, string
str
)
bool
glob(array
(string
) glob
, string
str
)
array
(string
) glob(string
glob
, array
(string
) str
)
array
(string
) glob(array
(string
) glob
, array
(string
) str
)
Match strings against a glob pattern.
glob
| The glob pattern. A question sign ('?') matches any character and an asterisk ('*') matches a string of arbitrary length. All other characters only match themselves. |
| the function returns true, or keeps a string, if any of the given patterns match |
str
|
|
| All strings in the array |
sscanf()
, Regexp
mapping
(string
:int
) gmtime(int
timestamp
)
Convert seconds since 00:00:00 UTC, Jan 1, 1970 into components.
This function works like localtime()
but the result is
not adjusted for the local time zone.
localtime()
, time()
, ctime()
, mktime()
int
has_index(string
haystack
, int
index
)
int
has_index(array
haystack
, int
index
)
int
has_index(mapping
|multiset
|object
|program
haystack
, mixed
index
)
Search for index
in haystack
.
Returns 1
if index
is in the index domain of haystack
,
or 0
(zero) if not found.
This function is equivalent to (but sometimes faster than):
search(indices(haystack), index) != -1
A negative index in strings and arrays as recognized by the
index operators `[]()
and `[]=()
is not considered
a proper index by has_index()
has_value()
, has_prefix()
, has_suffix()
, indices()
,
search()
, values()
, zero_type()
int
has_prefix(string
|object
s
, string
prefix
)
Returns 1
if the string s
starts with prefix
,
returns 0
(zero) otherwise.
When s
is an object, it needs to implement
lfun::_sizeof()
and lfun::`[]
.
has_suffix()
, has_value()
, search()
int
has_suffix(string
s
, string
suffix
)
Returns 1
if the string s
ends with suffix
,
returns 0
(zero) otherwise.
has_prefix()
, has_value()
, search()
int
has_value(string
haystack
, string
value
)
int
has_value(string
haystack
, int
value
)
int
has_value(array
|mapping
|object
|program
haystack
, mixed
value
)
Search for value
in haystack
.
Returns 1
if value
is in the value domain of haystack
,
or 0
(zero) if not found.
This function is in all cases except when both arguments are strings equivalent to (but sometimes faster than):
search(values(haystack), value) != -1
If both arguments are strings, has_value()
is equivalent to:
search(haystack, value) != -1
has_index()
, indices()
, search()
, has_prefix()
,
has_suffix()
, values()
, zero_type()
int
hash(string
s
)
int
hash(string
s
, int
max
)
Return an integer derived from the string s
. The same string
always hashes to the same value, also between processes,
architectures, and Pike versions (see compatibility notes below,
though).
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
The hash algorithm was changed in Pike 7.5. If you want a hash
that is compatible with Pike 7.4 and earlier, use 7.4::hash()
.
The difference only affects wide strings.
The hash algorithm was also changed in Pike 7.1. If you want a hash
that is compatible with Pike 7.0 and earlier, use 7.0::hash()
.
This hash function differs from the one provided by hash_value()
,
in that hash_value()
returns a process specific value.
hash_7_0()
, 7.4::hash()
, hash_value
int
hash_7_0(string
s
)
int
hash_7_0(string
s
, int
max
)
Return an integer derived from the string s
. The same string
always hashes to the same value, also between processes.
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
This function is provided for backward compatibility with code written for Pike up and including version 7.0.
This function is not NUL-safe, and is byte-order dependant.
hash()
, 7.4::hash()
__deprecated__
int
hash_7_4(string
s
)
__deprecated__
int
hash_7_4(string
s
, int
max
)
Replaced by 7.4::hash
.
7.4::hash()
, hash()
int
hash_value(mixed
value
)
Return a hash value for the argument. It's an integer in the native integer range.
The hash will be the same for the same value in the running process only (the memory address is typically used as the basis for the hash value).
If the value is an object with an lfun::__hash
, that function
is called and its result returned.
This is the hashing method used by mappings.
hash()
, lfun::__hash()
array
indices(string
|array
|mapping
|multiset
|object
x
)
Return an array of all valid indices for the value x
.
For strings and arrays this is simply an array of ascending numbers.
For mappings and multisets, the array might contain any value.
For objects which define lfun::_indices()
that return value
is used.
For other objects an array with all non-protected symbols is returned.
values()
, types()
, lfun::_indices()
int
intp(mixed
arg
)
Returns 1
if arg
is an int, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
int
is_absolute_path(string
p
)
Check if a path p
is fully qualified (ie not relative).
Returns 1 if the path is absolute, 0 otherwise.
constant
int
is_sql_null
SQL Null marker.
Replaced by is_val_null
.
constant
int
is_val_null
Nonzero recognition constant.
bool
kill(int
pid
, int
signal
)
Send a signal to another process.
Some signals and their supposed purpose:
| Hang-up, sent to process when user logs out. |
| Interrupt, normally sent by ctrl-c. |
| Quit, sent by ctrl-\. |
| Illegal instruction. |
| Trap, mostly used by debuggers. |
| Aborts process, can be caught, used by Pike whenever something goes seriously wrong. |
| Emulation trap. |
| Floating point error (such as division by zero). |
| Really kill a process, cannot be caught. |
| Bus error. |
| Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike. |
| Bad system call. Should never happen to Pike. |
| Broken pipe. |
| Signal used for timer interrupts. |
| Termination signal. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Child process died. This signal is reserved for internal use by the Pike run-time. |
| Power failure or restart. |
| Window change signal. |
| Urgent socket data. |
| Pollable event. |
| Stop (suspend) process. |
| Stop (suspend) process. Sent by ctrl-z. |
| Continue suspended. |
| TTY input for background process. |
| TTY output for background process. |
| Virtual timer expired. |
| Profiling trap. |
| Out of CPU. |
| File size limit exceeded. |
| Stack fault |
| Success. |
| Failure. |
Note that you have to use signame to translate the name of a signal to its number.
Note that the kill function is not available on platforms that do not support signals. Some platforms may also have signals not listed here.
signal()
, signum()
, signame()
, fork()
int
|float
|object
limit(int
|float
|object
minval
, int
|float
|object
x
, int
|float
|object
maxval
)
Limits the value x
so that it's between minval
and maxval
.
If x
is an object, it must implement the lfun::`<
method.
max()
and min()
array
(string
) listxattr(string
file
, void
|bool
symlink
)
Return an array of all extended attributes set on the file
program
load_module(string
module_name
)
Load a binary module.
This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.
When a module is loaded the C function pike_module_init() will be called to initialize it. When Pike exits pike_module_exit() will be called. These two functions must be available in the module.
The current working directory is normally not searched for
dynamic modules. Please use "./name.so"
instead of just
"name.so"
to load modules from the current directory.
mapping
(string
:int
) localtime(int
timestamp
)
Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.
This function returns a mapping with the following components:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Day of week (0 = Sunday). |
| Day of the year. |
| Is daylight-saving time active. |
| Offset from UTC, including daylight-saving time adjustment. |
An error is thrown if the localtime(2) call failed on the system.
It's platform dependent what time ranges that function can handle,
e.g. Windows doesn't handle a negative timestamp
.
Prior to Pike 7.5 the field "timezone"
was sometimes not
present, and was sometimes not adjusted for daylight-saving time.
Calendar
, gmtime()
, time()
, ctime()
, mktime()
float
log(int
|float
f
)
Return the natural logarithm of f
.
exp( log(x) ) == x
for x > 0.
pow()
, exp()
string
lower_case(string
s
)
int
lower_case(int
c
)
Convert a string or character to lower case.
Returns a copy of the string s
with all upper case characters
converted to lower case, or the character c
converted to lower
case.
Assumes the string or character to be coded according to
ISO-10646 (aka Unicode). If they are not, Charset.decoder
can
do the initial conversion for you.
Prior to Pike 7.5 this function only accepted strings.
upper_case()
, Charset.decoder
mixed
m_delete(object
|mapping
map
, mixed
index
)
If map
is an object that implements lfun::_m_delete()
,
that function will be called with index
as its single argument.
Otherwise if map
is a mapping the entry with index index
will be removed from map
destructively.
If the mapping does not have an entry with index index
, nothing is done.
The value that was removed will be returned.
Note that m_delete()
changes map
destructively.
mappingp()
mixed
map(mixed
arr
, void
|mixed
fun
, mixed
... extra
)
Applies fun
to the elements in arr
and collects the results.
arr
is treated as a set of elements, as follows:
fun
is applied in order to each element. The results are
collected, also in order, to a value of the same type as
arr
, which is returned.
fun
is applied to the values, and each result is assigned
to the same index in a new mapping, which is returned.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
If there is a lfun::cast
method in the object, it's
called to try to cast the object to an array, a mapping, or
a multiset, in that order, which is then handled as
described above.
fun
is applied in different ways depending on its type:
fun
is called for each element. It gets the current
element as the first argument and extra
as the rest. The
result of the call is collected.
fun
is used as a function like above, i.e. the
lfun::`()
method in it is called.
fun
is indexed with each element. The result of that is
collected.
Each element that is callable is called with extra
as
arguments. The result of the calls are collected. Elements
that aren't callable gets zero as result.
Each element is indexed with the given string. If the result
of that is zero then a zero is collected, otherwise it's
called with extra
as arguments and the result of that
call is collected.
This is typically used when arr
is a collection of
objects, and fun
is the name of some function in them.
The function is never destructive on arr
.
filter()
, enumerate()
, foreach()
int
mappingp(mixed
arg
)
Returns 1
if arg
is a mapping, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
object
master()
Return the current master object.
May return UNDEFINED
if no master has been loaded yet.
replace_master()
int
|float
|object
max(int
|float
|object
, int
|float
|object
... args
)
string
max(string
, string
... args
)
int(0..0)
max()
Returns the largest value among args
. Compared objects
must implement the lfun::`<
method.
min()
and limit()
int
|float
|object
min(int
|float
|object
, int
|float
|object
... args
)
string
min(string
, string
... args
)
int(0..0)
min()
Returns the smallest value among args
. Compared objects
must implement the lfun::`<
method.
max()
and limit()
int
mkdir(string
dirname
, void
|int
mode
)
Create a directory.
If mode
is specified, it's will be used for the new directory after
being &
'ed with the current umask (on OS'es that support this).
Returns 0
(zero) on failure, 1
otherwise.
rm()
, cd()
, Stdio.mkdirhier()
mapping
mkmapping(array
ind
, array
val
)
Make a mapping from two arrays.
Makes a mapping ind[x]
:val[x]
, 0 <= x < sizeof(ind).
ind
and val
must have the same size.
This is the inverse operation of indices()
and values()
.
indices()
, values()
multiset
mkmultiset(array
a
)
This function creates a multiset from an array.
aggregate_multiset()
int
mktime(mapping
(string
:int
) tm
)
int
mktime(int
sec
, int
min
, int
hour
, int
mday
, int
mon
, int
year
, int
|void
isdst
, int
|void
tz
)
This function converts information about date and time into an integer which contains the number of seconds since 00:00:00 UTC, Jan 1, 1970.
You can either call this function with a mapping containing the following elements:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Is daylight-saving time active. If omitted or set to |
| The timezone offset from UTC in seconds. If omitted, the time will be calculated in the local timezone. |
Or you can just send them all on one line as the second syntax suggests.
For proper UTC calculations ensure that isdst = 0
and
timezone = 0
; omitting either one of these parameters
will mess up the UTC calculation.
On some operating systems (notably AIX and Win32), dates before 00:00:00 UTC, Jan 1, 1970 are not supported.
On most 32-bit systems, the supported range of dates is from Dec 13, 1901 20:45:52 UTC through to Jan 19, 2038 03:14:07 UTC (inclusive).
On most 64-bit systems, the supported range of dates is expressed in 56 bits and is thus practically unlimited (at least up to 1141 milion years in the past and into the future).
time()
, ctime()
, localtime()
, gmtime()
int
multisetp(mixed
arg
)
Returns 1
if arg
is a multiset, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, stringp()
, objectp()
,
mappingp()
, floatp()
, functionp()
int
mv(string
from
, string
to
)
Rename or move a file or directory.
If the destination already exists, it will be replaced.
Replacement often only works if to
is of the same type as
from
, i.e. a file can only be replaced by another file and so
on. Also, a directory will commonly be replaced only if it's
empty.
On some OSs this function can't move directories, only rename them.
Returns 0
(zero) on failure, 1
otherwise. Call
errno()
to get more error info on failure.
rm()
object
next_object(object
o
)
object
next_object()
Returns the next object from the list of all objects.
All objects are stored in a linked list.
If no arguments have been given next_object()
will return the first
object from the list.
If o
has been specified the object after o
on the list will be
returned.
This function is not recomended to use.
destruct()
string
normalize_path(string
path
)
Replaces "\" with "/" if runing on MS Windows. It is
adviced to use System.normalize_path
instead.
program
|function
(:void
) object_program(mixed
o
)
Return the program from which o
was instantiated. If the
object was instantiated from a class using parent references
the generating function will be returned.
If o
is not an object or has been destructed 0
(zero)
will be returned.
bool
object_variablep(object
o
, string
var
)
Find out if an object identifier is a variable.
This function returns 1
if var
exists as a
non-protected variable in o
, and returns 0
(zero)
otherwise.
indices()
, values()
int
objectp(mixed
arg
)
Returns 1
if arg
is an object, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, functionp()
,
multisetp()
, floatp()
, intp()
int
|float
pow(float
|int
n
, float
|int
x
)
mixed
pow(object
n
, float
|int
|object
x
)
Return n
raised to the power of x
. If both n
and x
are integers the result will be an integer.
If n
is an object its pow method will be called with
x
as argument.
exp()
, log()
int
programp(mixed
arg
)
Returns 1
if arg
is a program, 0
(zero) otherwise.
mappingp()
, intp()
, arrayp()
, stringp()
, objectp()
,
multisetp()
, floatp()
, functionp()
int
query_num_arg()
Returns the number of arguments given when the previous function was called.
This is useful for functions that take a variable number of arguments.
call_function()
mixed
random(object
o
)
If random is called with an object, lfun::random
will be
called in the object.
lfun::_random()
int
random(int
max
)
This function returns a random number in the range 0 ..
.max
-1
random_seed()
float
random(float
max
)
This function returns a random number in the range 0 ..
.max
-ɛ
random_seed()
mixed
random(array
|multiset
x
)
Returns a random element from x
.
array
random(mapping
m
)
Returns a random index-value pair from the mapping.
void
random_seed(int
seed
)
This function sets the initial value for the random generator.
random()
string
random_string(int
len
)
Returns a string of random characters 0-255 with the length len
.
void
removexattr(string
file
, string
attr
, void
|bool
symlink
)
Remove the specified extended attribute.
string
replace(string
s
, string
from
, string
to
)
string
replace(string
s
, array
(string
) from
, array
(string
) to
)
string
replace(string
s
, array
(string
) from
, string
to
)
string
replace(string
s
, mapping
(string
:string
) replacements
)
array
replace(array
a
, mixed
from
, mixed
to
)
mapping
replace(mapping
a
, mixed
from
, mixed
to
)
Generic replace function.
This function can do several kinds replacement operations, the different syntaxes do different things as follows:
If all the arguments are strings, a copy of s
with every
occurrence of from
replaced with to
will be returned.
Special case: to
will be inserted between every character in
s
if from
is the empty string.
If the first argument is a string, and the others array(string), a string
with every occurrance of from
[i] in s
replaced with
to
[i] will be returned. Instead of the arrays from
and to
a mapping equivalent to
can be
used.mkmapping
(from
, to
)
If the first argument is an array or mapping, the values of a
which
are `==()
with from
will be replaced with to
destructively.
a
will then be returned.
Note that replace()
on arrays and mappings is a destructive operation.
void
replace_master(object
o
)
Replace the master object with o
.
This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is usually a good idea to have your master inherit the original master and only re-define certain functions.
FIXME: Tell how to inherit the master.
master()
string
reverse(string
s
, int
|void
start
, int
|void
end
)
array
reverse(array
a
, int
|void
start
, int
|void
end
)
int
reverse(int
i
, int
|void
start
, int
|void
end
)
Reverses a string, array or int.
s
String to reverse.
a
Array to reverse.
i
Integer to reverse.
start
Optional start index of the range to reverse.
Default: 0
(zero).
end
Optional end index of the range to reverse.
Default for strings: sizeof(s)-1
.
Default for arrays: sizeof(a)-1
.
Default for integers: Pike.get_runtime_info()->int_size - 1
.
This function reverses a string, char by char, an array, value by value or an int, bit by bit and returns the result. It's not destructive on the input value.
Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.
sscanf()
int
rm(string
f
)
Remove a file or directory.
Returns 0
(zero) on failure, 1
otherwise.
mkdir()
, Stdio.recursive_rm()
float
round(int
|float
f
)
Return the closest integer value to f
.
round()
does not return an int
, merely an integer value
stored in a float
.
floor()
, ceil()
array
rows(mixed
data
, array
index
)
Select a set of rows from an array.
This function is en optimized equivalent to:
map(index, lambda(mixed x) { return data[x]; })
That is, it indices data on every index in the array index and returns an array with the results.
column()
int
search(string
haystack
, string
|int
needle
, int
|void
start
)
int
search(array
haystack
, mixed
needle
, int
|void
start
)
mixed
search(mapping
haystack
, mixed
needle
, mixed
|void
start
)
mixed
search(object
haystack
, mixed
needle
, mixed
|void
start
)
Search for needle
in haystack
.
haystack
Item to search in. This can be one of:
| When |
| When |
| When |
| When If |
start
If the optional argument start
is present search is started at
this position.
Returns the position of needle
in haystack
if found.
If not found the returned value depends on the type of haystack
:
|
|
|
|
| The value returned by |
If start
is supplied to an iterator object without an
lfun::_search()
, haystack
will need to implement
Iterator()->set_index()
.
For mappings and object UNDEFINED
will be returned when not found.
In all other cases -1
will be returned when not found.
indices()
, values()
, zero_type()
, has_value()
,
has_prefix()
, has_suffix()
int
set_priority(string
level
, int(0..)
|void
pid
)
array
|mapping
|multiset
set_weak_flag(array
|mapping
|multiset
m
, int
state
)
Set the value m
to use weak or normal references in its
indices and/or values (whatever is applicable). state
is a
bitfield built by using |
between the following flags:
| Use weak references for indices. Only applicable for multisets and mappings. |
| Use weak references for values. Only applicable for arrays and mappings. |
| Shorthand for |
If a flag is absent, the corresponding field will use normal
references. state
can also be 1
as a compatibility
measure; it's treated like Pike.WEAK
.
m
will be returned.
void
setxattr(string
file
, string
attr
, string
value
, int
flags
, void
|bool
symlink
)
Set the attribute attr
to the value value
.
The flags parameter can be used to refine the semantics of the operation.
Stdio.XATTR_CREATE
specifies a pure create, which
fails if the named attribute exists already.
Stdio.XATTR_REPLACE
specifies a pure replace operation, which
fails if the named attribute does not already exist.
By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.
1 if successful, 0 otherwise, setting errno.
int
sgn(mixed
value
)
int
sgn(mixed
value
, mixed
zero
)
Check the sign of a value.
Returns -1
if value
is less than zero
,
1
if value
is greater than zero
and 0
(zero) otherwise.
abs()
function
(int
|void
:void
) signal(int
sig
, function
(int
|void
:void
) callback
)
function
(int
|void
:void
) signal(int
sig
)
Trap signals.
This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc, I advise you not to; Pike should not receive any such signals, and if it does, it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.
The callback will receive the signal number as its only argument.
See the documentation for kill()
for a list of signals.
If no second argument is given, the signal handler for that signal is restored to the default handler.
If the second argument is zero, the signal will be completely ignored.
Returns the previous signal function, or 0 if none had been registered.
kill()
, signame()
, signum()
string
signame(int
sig
)
Returns a string describing the signal sig
.
kill()
, signum()
, signal()
int
signum(string
sig
)
Get a signal number given a descriptive string.
This function is the inverse of signame()
.
signame()
, kill()
, signal()
float
sin(int
|float
f
)
Returns the sine value for f
.
f
should be specified in radians.
asin()
, cos()
, tan()
float
sinh(int
|float
f
)
Returns the hyperbolic sine value for f
.
asinh()
, cosh()
, tanh()
int
sizeof(string
arg
)
int
sizeof(array
arg
)
int
sizeof(mapping
arg
)
int
sizeof(multiset
arg
)
int
sizeof(object
arg
)
Size query.
The result will be as follows:
arg
can have any of the following types:
| The number of characters in |
| The number of elements in |
| The number of key-value pairs in |
| If |
lfun::_sizeof()
void
sleep(int
|float
s
, void
|int
abort_on_signal
)
This function makes the program stop for s
seconds.
Only signal handlers can interrupt the sleep, and only when
abort_on_signal
is set. If more than one thread is running
the signal must be sent to the sleeping thread. Other callbacks
are not called during sleep.
If s
is zero then this thread will yield to other threads but
not sleep otherwise. Note that Pike yields internally at regular
intervals so it's normally not necessary to do this.
signal()
, delay()
array
sort(array
(mixed
) index
, array
(mixed
) ... data
)
Sort arrays destructively.
This function sorts the array index
destructively. That means
that the array itself is changed and returned, no copy is created.
If extra arguments are given, they are supposed to be arrays of the
same size as index
. Each of these arrays will be modified in the
same way as index
. I.e. if index 3 is moved to position 0 in index
index 3 will be moved to position 0 in all the other arrays as well.
The sort order is as follows:
Integers and floats are sorted in ascending order.
Strings are sorted primarily on the first characters that are different, and secondarily with shorter strings before longer. Different characters are sorted in ascending order on the character value. Thus the sort order is not locale dependent.
Arrays are sorted recursively on the first element. Empty arrays are sorted before nonempty ones.
Multisets are sorted recursively on the first index. Empty multisets are sorted before nonempty ones.
Objects are sorted in ascending order according to `<()
,
`>()
and `==()
.
Other types aren't reordered.
Different types are sorted in this order: Arrays, mappings,
multisets, objects, functions, programs, strings, types,
integers and floats. Note however that objects can control
their ordering wrt other types with `<
, `>
and `==
,
so this ordering of types only applies to objects without
those functions.
The first argument is returned.
The sort is stable, i.e. elements that are compare-wise equal aren't reordered.
Array.sort_array
, reverse()
string
sprintf(strict_sprintf_format
format
, sprintf_args
... args
)
Print formated output to string.
The format
string is a string containing a description of how to
output the data in args
. This string should generally speaking
have one %<modifiers><operator> format specifier
(examples: %s, %0d, %-=20s) for each of the arguments.
The following modifiers are supported:
| Zero pad numbers (implies right justification). | ||||||||
| Toggle truncation. | ||||||||
| Pad positive integers with a space. | ||||||||
| Pad positive integers with a plus sign. | ||||||||
| Left adjust within field size (default is right). | ||||||||
| Centered within field size. | ||||||||
| Column mode if strings are greater than field size. Breaks
between words (possibly skipping or adding spaces). Can not be
used together with | ||||||||
| Column mode with rough line break (break at exactly field size
instead of between words). Can not be used together with | ||||||||
| Table mode, print a list of | ||||||||
| Inverse table mode (left-to-right order). | ||||||||
| (Where n is a number or *) field width specifier. | ||||||||
| |||||||||
| Precision specifier. | ||||||||
| Column width specifier. | ||||||||
| If n is a * then next argument is used for precision/field
size. The argument may either be an integer, or a modifier mapping
as received by
| ||||||||
| Set a pad string. ' cannot be a part of the pad string (yet). | ||||||||
| Get pad string from argument list. | ||||||||
| Use same argument again. | ||||||||
| Repeat this on every line produced. | ||||||||
| Repeat this format for each element in the argument array. | ||||||||
| Put the string at the bottom end of column instead of top. | ||||||||
| Set width to the length of data. | ||||||||
| Select argument number n. Use * to use the next
argument as selector. The arguments are numbered starting from
|
The following operators are supported:
| Percent. |
| Signed binary integer. |
| Signed decimal integer. |
| Unsigned decimal integer. |
| Signed octal integer. |
| Lowercase signed hexadecimal integer. |
| Uppercase signed hexadecimal integer. |
| Character. If a fieldsize has been specified this will output the low-order bytes of the integer in network (big endian) byte order. To get little endian byte order, negate the field size. |
| Float. (Locale dependent formatting.) |
| Heuristically chosen representation of float. (Locale dependent formatting.) |
| Like %g, but uses uppercase E for exponent. |
| Exponential notation float. (Locale dependent output.) |
| Like %e, but uses uppercase E for exponent. |
| Binary IEEE representation of float (%4F gives single precision, %8F gives double precision) in network (big endian) byte order. To get little endian byte order, negate the field size. |
| String. |
| Quoted string. Escapes all control and non-8-bit characters, as well as the quote characters '\\' and '\"'. |
| Any value, debug style. Do not rely on the exact formatting;
how the result looks can vary depending on locale, phase of
the moon or anything else the |
| Binary Hollerith string. Equivalent to |
| No argument. Same as |
| Type of the argument. |
| Perform the enclosed format for every element of the argument array. |
|
Most modifiers and operators are combinable in any fashion, but some combinations may render strange results.
If an argument is an object that implements lfun::_sprintf()
, that
callback will be called with the operator as the first argument, and
the current modifiers as the second. The callback is expected to return
a string.
sprintf-style formatting is applied by many formatting functions, such
write()
and werror()
. It is also possible to get sprintf-style
compile-time argument checking by using the type-attributes
sprintf_format
or strict_sprintf_format
in combination
with sprintf_args
.
The 'q'
operator was added in Pike 7.7.
Support for specifying modifiers via a mapping was added in Pike 7.8.
This support can be tested for with the constant
String.__HAVE_SPRINTF_STAR_MAPPING__
.
Support for specifying little endian byte order to 'F'
was added in Pike 7.8. This support can be tested for with the
constant String.__HAVE_SPRINTF_NEGATIVE_F__
.
Pike v7.8 release 263 running Hilfe v3.5 (Incremental Pike Frontend) > sprintf("The unicode character %c has character code %04X.", 'A', 'A'); (1) Result: "The unicode character A has character code 0041." > sprintf("#%@02X is the HTML code for purple.", Image.Color.purple->rgb()); (2) Result: "#A020F0 is the HTML code for purple." > int n=4711; > sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n); (3) Result: "4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary" > write(#"Formatting examples: Left adjusted [%-10d] Centered [%|10d] Right adjusted [%10d] Zero padded [%010d] ", n, n, n, n); Formatting examples: Left adjusted [4711 ] Centered [ 4711 ] Right adjusted [ 4711] Zero padded [0000004711] (5) Result: 142 int screen_width=70; > write("%-=*s\n", screen_width, >> "This will wordwrap the specified string within the "+ >> "specified field size, this is useful say, if you let "+ >> "users specify their screen size, then the room "+ >> "descriptions will automagically word-wrap as appropriate.\n"+ >> "slosh-n's will of course force a new-line when needed.\n"); This will wordwrap the specified string within the specified field size, this is useful say, if you let users specify their screen size, then the room descriptions will automagically word-wrap as appropriate. slosh-n's will of course force a new-line when needed. (6) Result: 355 > write("%-=*s %-=*s\n", screen_width/2, >> "Two columns next to each other (any number of columns will "+ >> "of course work) independantly word-wrapped, can be useful.", >> screen_width/2-1, >> "The - is to specify justification, this is in addherence "+ >> "to std sprintf which defaults to right-justification, "+ >> "this version also supports centre and right justification."); Two columns next to each other (any The - is to specify justification, number of columns will of course this is in addherence to std work) independantly word-wrapped, sprintf which defaults to can be useful. right-justification, this version also supports centre and right justification. (7) Result: 426 > write("%-$*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output."); Given a list of slosh-n separated 'words', this option creates a table out of them the number of columns be forced by specifying a presision. The most obvious use is for formatted ls output. (8) Result: 312 > write("%-#*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output."); Given a creates a by specifying a list of table out presision. slosh-n of them The most obvious separated the number of use is for 'words', columns formatted this option be forced ls output. (9) Result: 312 > sample = ([ "align":"left", "valign":"middle" ]); (10) Result: ([ /* 2 elements */ "align":"left", "valign":"middle" ]) > write("<td%{ %s='%s'%}>\n", (array)sample); <td valign='middle' align='left
lfun::_sprintf()
, strict_sprintf_format
, sprintf_format
,
sprintf_args
, String.__HAVE_SPRINTF_STAR_MAPPING__
,
String.__HAVE_SPRINTF_NEGATIVE_F__
.
constant
sprintf_args
Type constant used for typing extra arguments that are
sent to sprintf()
.
strict_sprintf_format
, sprintf_format
, sprintf()
constant
sprintf_format
Type constant used for typing arguments that are optionally
sent to sprintf()
depending on the presence of extra arguments.
strict_sprintf_format
, sprintf_args
, sprintf()
constant
sprintf_result
Type constant used for typing the return value from sprintf()
.
strict_sprintf_format
, sprintf_format
, sprintf()
float
sqrt(float
f
)
int
sqrt(int
i
)
mixed
sqrt(object
o
)
Returns the square root of f
, or in the integer case, the square root
truncated to the closest lower integer. If the argument is an object,
the lfun _sqrt in the object will be called.
pow()
, log()
, exp()
, floor()
, lfun::_sqrt
int
sscanf(string
data
, string
format
, mixed
... lvalues
)
The purpose of sscanf is to match a string data
against a format
string and place the matching results into a list of variables. The list
of lvalues
are destructively modified (which is only possible because
sscanf really is an opcode, rather than a pike function) with the values
extracted from the data
according to the format
specification. Only
the variables up to the last matching directive of the format string are
touched.
The format
string can contain strings separated by special matching
directives like %d, %s %c and %f. Every such
directive corresponds to one of the lvalues
, in order they are listed.
An lvalue is the name of a variable, a name of a local variable, an index
in an array, mapping or object. It is because of these lvalues that sscanf
can not be implemented as a normal function.
Whenever a percent character is found in the format string, a match is performed, according to which operator and modifiers follow it:
| Reads a binary integer ( |
| Reads a decimal integer ( |
| Reads an octal integer ( |
| Reads a hexadecimal integer ( |
| Reads an integer that is either octal (leading zero),
hexadecimal (leading 0x) or decimal. ( |
| Reads one character and returns it as an integer
( |
| Returns the current character offset in |
| Reads a float ("0101" makes 101.0). |
| Reads a float encoded according to the IEEE single precision
binary format ( |
| Reads a string. If followed by %d, %s will only read non-numerical characters. If followed by a %[], %s will only read characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text. |
| Reads a Hollerith-encoded string, i.e. first reads the length
of the string and then that number of characters. The size and
byte order of the length descriptor can be modified in the
same way as %c. As an example |
| Matches a string containing a given set of characters (those given inside the brackets). Ranges of characters can be defined by using a minus character between the first and the last character to be included in the range. Example: %[0-9H] means any number or 'H'. Note that sets that includes the character '-' must have it first (not possible in complemented sets, see below) or last in the brackets to avoid having a range defined. Sets including the character ']' must list this first too. If both '-' and ']' should be included then put ']' first and '-' last. It is not possible to make a range that ends with ']'; make the range end with '\' instead and put ']' at the beginning of the set. Likewise it is generally not possible to have a range start with '-'; make the range start with '.' instead and put '-' at the end of the set. If the first character after the [ bracket is '^' (%[^set]), and this character does not begin a range, it means that the set is complemented, which is to say that any character except those inside brackets is matched. To include '-' in a complemented set, it must be put last, not first. To include '^' in a non-complemented set, it can be put anywhere but first, or be specified as a range ("^-^"). |
| Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue. |
| Match a Pike constant, such as string or integer (currently only integer, string and character constants are functional). |
| Match a single percent character (hence this is how you quote the % character to just match, and not start an lvalue matcher directive). |
Similar to sprintf
, you may supply modifiers between the % character
and the operator, to slightly change its behaviour from the default:
| The operator will only match its argument, without assigning any variable. |
| You may define a field width by supplying a numeric modifier.
This means that the format should match that number of
characters in the input data; be it a number characters
long string, integer or otherwise ( |
| Supplying a minus sign toggles the decoding to read the data encoded in little-endian byte order, rather than the default network (big-endian) byte order. |
| Interpret the data as a signed entity. In other words,
|
| Ignore the matched characters with respect to any following
|
Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.
// a will be assigned "oo" and 1 will be returned sscanf("foo", "f%s", a);
// a will be 4711 and b will be "bar", 2 will be returned sscanf("4711bar", "%d%s", a, b);
// a will be 4711, 2 will be returned sscanf("bar4711foo", "%*s%d", a);
// a will become "test", 2 will be returned sscanf(" \t test", "%*[ \t]%s", a);
// Remove "the " from the beginning of a string // If 'str' does not begin with "the " it will not be changed sscanf(str, "the %s", str);
// It is also possible to declare a variable directly in the sscanf call; // another reason for sscanf not to be an ordinary function:
sscanf("abc def", "%s %s", string a, string b);
The number of directives matched in the format string. Note that a string directive (%s or %[]) counts as a match even when matching just the empty string (which either may do).
sprintf
, array_sscanf
string
strerror(int
errno
)
This function returns a description of an error code. The error
code is usually obtained from eg Stdio.File->errno()
.
On some platforms the string returned can be somewhat nondescriptive.
constant
strict_sprintf_format
Type constant used for typing arguments that are always
sent to sprintf()
regardless of the presence of extra arguments.
sprintf_format
, sprintf_args
, sprintf()
string(1..)
string_filter_non_unicode(string
s
)
Replace the most obviously non-unicode characters from s
with
the unicode replacement character.
This will replace characters outside the ranges
0x00000000-0x0000d7ff
and 0x0000e000-0x0010ffff
with 0xffea (the replacement character).
Charset.encoder()
, string_to_unicode()
,
unicode_to_string()
, utf8_to_string()
, string_to_utf8()
string(8bit)
string_to_unicode(string
s
, int(0..2)
|void
byteorder
)
Converts a string into an UTF16 compliant byte-stream.
s
String to convert to UTF16.
byteorder
Byte-order for the output. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Throws an error if characters not legal in an UTF16 stream are encountered. Valid characters are in the range 0x00000 - 0x10ffff, except for characters 0xfffe and 0xffff.
Characters in range 0x010000 - 0x10ffff are encoded using surrogates.
Charset.decoder()
, string_to_utf8()
, unicode_to_string()
,
utf8_to_string()
string(8bit)
string_to_utf8(string
s
)
string(8bit)
string_to_utf8(string
s
, int
extended
)
Convert a string into a UTF-8 compliant byte-stream.
s
String to encode into UTF-8.
extended
Bitmask with extension options.
| Accept and encode the characters outside the valid ranges using the same algorithm. Such encoded characters are however not UTF-8 compliant. |
| Encode characters outside the BMP with UTF-8 encoded UTF-16 (ie split them into surrogate pairs and encode). |
Throws an error if characters not valid in an UTF-8 stream are
encountered. Valid characters are in the ranges
0x00000000-0x0000d7ff
and 0x0000e000-0x0010ffff
.
Charset.encoder()
, string_to_unicode()
,
unicode_to_string()
, utf8_to_string()
int
stringp(mixed
arg
)
Returns 1
if arg
is a string, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, multisetp()
, objectp()
,
mappingp()
, floatp()
, functionp()
int
strlen(string
|multiset
|array
|mapping
|object
thing
)
Alias for sizeof
.
Replaced by sizeof
.
float
tan(int
|float
f
)
Returns the tangent value for f
.
f
should be specified in radians.
atan()
, sin()
, cos()
float
tanh(int
|float
f
)
Returns the hyperbolic tangent value for f
.
atanh()
, sinh()
, cosh()
constant
this
Builtin read only variable that evaluates to the current object.
this_program
, this_object()
object
this_object(void
|int
level
)
Returns the object we are currently evaluating in.
level
might be used to access the object of a surrounding
class: The object at level 0 is the current object, the object
at level 1 is the one belonging to the class that surrounds
the class that the object comes from, and so on.
As opposed to a qualified this
reference such as
global::this
, this function doesn't always access the
objects belonging to the lexically surrounding classes. If the
class containing the call has been inherited then the objects
surrounding the inheriting class are accessed.
constant
this_program
Builtin constant that evaluates to the current program.
this
, this_object()
mixed
|void
throw(mixed
value
)
Throw value
to a waiting catch
.
If no catch
is waiting the global error handling will send the
value to master()->handle_error()
.
If you throw an array with where the first index contains an error
message and the second index is a backtrace, (the output from
backtrace()
) then it will be treated exactly like a real error
by overlying functions.
catch
int
time()
int
time(int(1..1)
one
)
float
time(int(2..)
t
)
This function returns the number of seconds since 00:00:00 UTC, 1 Jan 1970.
The second syntax does not query the system for the current
time, instead the last time value used by the pike process is returned
again. It avoids a system call, and thus is slightly faster,
but can be wildly inaccurate. Pike
queries the time internally when a thread has waited for
something, typically in sleep
or in a backend (see
Pike.Backend
).
The third syntax can be used to measure time more precisely than one
second. It returns how many seconds have passed since t
. The precision
of this function varies from system to system.
ctime()
, localtime()
, mktime()
, gmtime()
,
System.gettimeofday
, gethrtime
int
trace(int
level
, void
|string
facility
, void
|int
all_threads
)
This function changes the trace level for the subsystem identified
by facility
to level
. If facility
is zero or left out, it
changes the global trace level which affects all subsystems.
Enabling tracing causes messages to be printed to stderr. A higher trace level includes the output from all lower levels. The lowest level is zero which disables all trace messages.
See the -t command-line option for more information.
level
If facility
is specified then there is typically only one
trace level for it, i.e. it's an on-or-off toggle. The global
trace levels, when facility
isn't specified, are:
| Trace calls to Pike functions and garbage collector runs. |
| Trace calls to builtin functions. |
| Trace every interpreted opcode. |
| Also trace the opcode arguments. |
facility
Valid facilities are:
| Trace the doings of the garbage collector. The setting is
never thread local.
|
all_threads
Trace levels are normally thread local, so changes affect only the current thread. To change the level in all threads, pass a nonzero value in this argument.
The old trace level in the current thread is returned.
array
(type
) types(string
|array
|mapping
|multiset
|object
x
)
Return an array of all valid indices for the value x
.
For strings this is simply an array with int
For arrays, mappings and multisets this is simply an array with mixed.
For objects which define lfun::_types()
that return value
is used.
For other objects an array with type types for all non-protected symbols is returned.
This function was added in Pike 7.9.
indices()
, values()
, lfun::_types()
int
ualarm(int
useconds
)
Set an alarm clock for delivery of a signal.
alarm()
arranges for a SIGALRM signal to be delivered to the
process in useconds
microseconds.
If useconds
is 0
(zero), no new alarm will be scheduled.
Any previous alarms will in any case be canceled.
Returns the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
alarm()
, signal()
, call_out()
int
undefinedp(mixed
arg
)
Returns 1
if arg
is undefined, 0
(zero) otherwise.
zero_type
, destructedp
, intp
string
unicode_to_string(string(8bit)
s
, int(0..2)
|void
byteorder
)
Converts an UTF16 byte-stream into a string.
s
String to convert to UTF16.
byteorder
Default input byte-order. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Note that this argument is disregarded if s
starts with a BOM.
This function did not decode surrogates in Pike 7.2 and earlier.
Charset.decoder()
, string_to_unicode()
, string_to_utf8()
,
utf8_to_string()
string
upper_case(string
s
)
int
upper_case(int
c
)
Convert a string or character to upper case.
Returns a copy of the string s
with all lower case characters
converted to upper case, or the character c
converted to upper
case.
Assumes the string or character to be coded according to
ISO-10646 (aka Unicode). If they are not, Charset.decoder
can
do the initial conversion for you.
Prior to Pike 7.5 this function only accepted strings.
lower_case()
, Charset.decoder
string
utf8_to_string(string(8bit)
s
)
string
utf8_to_string(string(8bit)
s
, int
extended
)
Converts an UTF-8 byte-stream into a string.
s
String of UTF-8 encoded data to decode.
extended
Bitmask with extension options.
| Accept and decode the extension used by |
| Accept and decode UTF-8 encoded UTF-16 (ie accept and decode valid surrogates). |
Throws an error if the stream is not a legal UTF-8 byte-stream.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are not decoded. An error is thrown instead.
Charset.encoder()
, string_to_unicode()
, string_to_utf8()
,
unicode_to_string()
array
values(string
|array
|mapping
|multiset
|object
x
)
Return an array of all possible values from indexing the value
x
.
For strings an array of int with the ISO10646 codes of the characters in the string is returned.
For a multiset an array filled with ones (1
) is
returned.
For arrays a single-level copy of x
is returned.
For mappings the array may contain any value.
For objects which define lfun::_values()
that return value
is used.
For other objects an array with the values of all non-protected symbols is returned.
indices()
, types()
, lfun::_values()
string
version()
Report the version of Pike. Does the same as
sprintf("Pike v%d.%d release %d", __REAL_VERSION__,
__REAL_MINOR__, __REAL_BUILD__);
__VERSION__
, __MINOR__
, __BUILD__
,
__REAL_VERSION__
, __REAL_MINOR__
, __REAL_BUILD__
,
int
werror(string
fmt
, mixed
... args
)
Writes a string on stderr. Works just like Stdio.File.write
on Stdio.stderr
.
int
write(string
fmt
, mixed
... args
)
Writes a string on stdout. Works just like Stdio.File.write
on Stdio.stdout
.
int
zero_type(mixed
a
)
Return the type of zero.
There are many types of zeros out there, or at least there are two.
One is returned by normal functions, and one returned by mapping
lookups and find_call_out()
when what you looked for wasn't there.
The only way to separate these two kinds of zeros is zero_type()
.
When doing a find_call_out()
or mapping lookup, zero_type()
on
this value will return 1
if there was no such thing present in
the mapping, or if no such call_out could be found.
If the argument to zero_type()
is a destructed object or a function
in a destructed object, 2
will be returned.
In all other cases zero_type()
will return 0
(zero).
find_call_out()
An Encoder
and a Decoder
lumped into a single instance which
can be used for both encoding and decoding.
inherit Decoder : Decoder
inherit Encoder : Encoder
Objects used by the compiler to handle references to global symbols, modules, external files, etc.
There can be up to three compilation handlers active at the same time during a compilation. They are in order of precedence:
The error handler
This is the object passed to compile()
as
the second argument (if any). This object is returned by
get_active_error_handler()
during a compilation.
The compatibility handler
This is the object returned by
master()->get_compilation_handler()
(if any), which
the compiler calls when it sees #pike-directives,
or expressions using the version scope
(eg 7.4::rusage
). This object is returned by
get_active_compilation_handler()
during a compilation.
The master object.
This is returned by master()
at any time.
Any of the objects may implement a subset of the CompilationHandler
functions, and the first object that implements a function will be
used. The error handler object can thus be used to block certain
functionality (eg to restrict the number of available functions).
master()->get_compilation_handler()
, get_active_error_handler()
,
get_active_compilation_handler()
, compile()
void
compile_error(string
filename
, int
line
, string
msg
)
Called by compile()
and cpp()
when they encounter
errors in the code they compile.
filename
File where the error was detected.
line
Line where the error was detected.
msg
Description of error.
compile_warning()
.
void
compile_exception(mixed
exception
)
Called by compile()
and cpp()
if they trigger
exceptions.
void
compile_warning(string
filename
, int
line
, string
msg
)
Called by compile()
to report warnings.
filename
File which triggered the warning.
line
Line which triggered the warning.
msg
Warning message.
compile_error()
mapping
(string
:mixed
)|object
get_default_module()
Returns the default module from which global symbols will be fetched.
Returns the default module, or 0
(zero).
If 0
(zero) is returned the compiler use the mapping
returned by all_constants()
as fallback.
get_predefines()
mapping
(string
:mixed
) get_predefines()
Called by cpp()
to get the set of global symbols.
Returns a mapping from symbol name to symbol value. Returns zero on failure.
resolv()
, get_default_module()
mixed
handle_import(string
path
, string
filename
, CompilationHandler
handler
)
Called by compile()
and cpp()
to handle import
directives specifying specific paths.
Returns the resolved value, or UNDEFINED
on failure.
string
handle_include(string
header_file
, string
current_file
, bool
is_local_ref
)
Called by cpp()
to resolv #include
and #string
directives.
header_file
File that was requested for inclusion.
current_file
File where the directive was found.
is_local_ref
Specifies reference method.
| Directive was |
| Directive was |
Returns the filename to pass to read_include()
if found,
and 0
(zero) on failure.
read_include()
string
read_include(string
filename
)
Called by cpp()
to read included files.
filename
Filename as returned by handle_include()
.
Returns a string with the content of the header file on success,
and 0
(zero) on failure.
handle_include()
mixed
resolv(string
symbol
, string
filename
, CompilationHandler
handler
)
Called by compile()
and cpp()
to resolv
module references.
Returns the resolved value, or UNDEFINED
on failure.
get_predefines()
The compiler environment.
By inheriting this class and overloading the functions, it is possible to make a custom Pike compiler.
Prior to Pike 7.8 this sort of customization has to be done
either via custom master objects, or via CompilationHandler
s.
CompilationHandler
, MasterObject
, master()
, replace_master()
program
compile(string
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
Compile a string to a program.
This function takes a piece of Pike code as a string and compiles it into a clonable program.
The optional argument handler
is used to specify an alternative
error handler. If it is not specified the current master object will
be used.
The optional arguments major
and minor
are used to tell the
compiler to attempt to be compatible with Pike major
.minor
.
This function essentially performs
program compile(mixed ... args)
{
return PikeCompiler(@args)->compile();
}
Note that source
must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that compile()
does not preprocess the program.
To preprocess the program you can use compile_string()
or
call the preprocessor manually by calling cpp()
.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
object
get_compilation_handler(int
major
, int
minor
)
Get compatibility handler for Pike major
.minor
.
The default implementation calls the corresponding function in the master object.
This function is typically called by
PikeCompiler()->get_compilation_handler()
.
MasterObject()->get_compilation_handler()
.
mapping
(string
:mixed
)|object
get_default_module()
Get the default module for the current compatibility level
(ie typically the value returned by predef::all_constants()
).
The default implementation calls the corresponding function in the master object.
| Constant table to use. |
| Use the builtin constant table. |
This function is typically called by
Pike_compiler()->get_default_module()
.
MasterObject()->get_default_module()
.
program
handle_inherit(string
inh
, string
current_file
, object
|void
handler
)
Look up an inherit inh
.
The default implementation calls the corresponding function in the master object.
MasterObject()->handle_inherit()
.
inherit Reporter : Reporter
Implements the Reporter
API.
Reporter()->report()
, Reporter()->SeverityLevel
mixed
resolv(string
identifier
, string
filename
, object
|void
handler
)
Look up identifier
in the current context.
The default implementation calls the corresponding function in the master object.
The Pike compiler.
An object of this class compiles a single string of Pike code.
type
apply_attribute_constant(string
attr
, mixed
value
, type
arg_type
, void
cont_type
)
Handle constant arguments to attributed function argument types.
attr
Attribute that arg_type
had.
value
Constant value sent as parameter.
arg_type
Declared type of the function argument.
cont_type
Continuation function type after the current argument.
This function is called when a function is called
with the constant value value
and it has been
successfully matched against arg_type
,
and arg_type
had the type attribute attr
.
This function is typically used to perform specialized
argument checking and to allow for a strengthening
of the function type based on value
.
The default implementation implements the "sprintf_format"
,
"sscanf_format"
and "sscanf_76_format"
attributes.
Returns a continuation type if it succeeded in strengthening the type.
Returns UNDEFINED otherwise (this is not an error indication).
pop_type_attribute()
, push_type_attribute()
bool
apply_type_attribute(string
attribute
, type
a
, type
|void
b
)
Type attribute handler.
attribute
Attribute that a
had.
a
Type of the value being called.
b
Type of the first argument in the call, or
UNDEFINED
if no more arguments.
Called during type checking when a
has been successfully
had a partial evaluation with the argument b
and
a
had the type attribute attribute
before the
evaluation.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie __attribute__(attribute, a)(b)
) is valid,
and 0
(zero) otherwise.
pop_type_attribute()
, push_type_attribute()
void
change_compiler_compatibility(int
major
, int
minor
)
Change compiler to attempt to be compatible with Pike major
.minor
.
program
compile()
Compile the current source into a program.
This function compiles the current Pike source code into a clonable program.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
, create()
CompilerEnvironment.PikeCompiler CompilerEnvironment.PikeCompiler(
string
|void
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
Create a PikeCompiler object for a source string.
This function takes a piece of Pike code as a string and initializes a compiler object accordingly.
source
Source code to compile.
handler
The optional argument handler
is used to specify an alternative
error handler. If it is not specified the current master object
at compile time will be used.
major
minor
The optional arguments major
and minor
are used to tell the
compiler to attempt to be compatible with Pike major
.minor
.
target
__empty_program()
program to fill in. The virgin program
returned by __empty_program()
will be modified and returned
by compile()
on success.
placeholder
__null_program()
placeholder object to fill in. The object
will be modified into an instance of the resulting program
on successfull compile. Note that lfun::create()
in the
program will be called without any arguments.
Note that source
must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that no preprocessing is performed.
To preprocess the program you can use compile_string()
or
call the preprocessor manually by calling cpp()
.
Note that all references to target
and placeholder
should
removed if compile()
failes. On failure the placeholder
object will be destructed.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
object
get_compilation_handler(int
major
, int
minor
)
Get compatibility handler for Pike major
.minor
.
This function is called by change_compiler_compatibility()
.
mapping
(string
:mixed
)|object
get_default_module()
Get the default module for the current compatibility level
(ie typically the value returned by predef::all_constants()
).
The default implementation calls the corresponding function
in the current handler, the current compatibility handler
or in the parent CompilerEnvironment
in that order.
| Constant table to use. |
| Use the builtin constant table. |
This function is called by change_compiler_compatibility()
.
program
handle_inherit(string
inh
)
Look up an inherit inh
in the current program.
bool
pop_type_attribute(string
attribute
, type
a
, type
b
)
Type attribute handler.
Called during type checking when a <= b
and
a
had the type attribute attribute
before the
comparison.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie __attribute__(attribute, a) <= b
), and
0
(zero) otherwise.
push_type_attribute()
bool
push_type_attribute(string
attribute
, type
a
, type
b
)
Type attribute handler.
Called during type checking when a <= b
and
b
had the type attribute attribute
before the
comparison.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie a <= __attribute__(attribute, b)
), and
0
(zero) otherwise.
pop_type_attribute()
void
report(SeverityLevel
severity
, string
filename
, int
linenumber
, string
subsystem
, string
message
, mixed
... extra_args
)
Report a diagnostic from the compiler.
The default implementation attempts to call the first corresponding function in the active handlers in priority order:
Call handler->report().
Call handler->compile_warning() or handler->compile_error()
depending on severity
.
Call compat->report().
Call compat->compile_warning() or compat->compile_error()
depending on severity
.
Fallback: Call CompilerEnvironment()->report()
in the parent object.
The arguments will be as follows:
The report() function will be called with the same arguments as this function.
Depending on the severity
either compile_warning()
or compile_error() will be called.
They will be called with the filename
, linenumber
and formatted message
as arguments.
Note that these will not be called for the NOTICE
severity,
and that compile_error() will be used for both ERROR
and
FATAL
.
In Pike 7.8 and earlier the report() function was not called in the handlers.
CompilerEnvironment()->report()
mixed
resolv(string
identifier
, string
filename
, object
handler
)
Resolve the symbol identifier
.
The default implementation calls the corresponding function
in any active handler, and otherwise falls back to
CompilerEnvironment()->resolv()
in the parent object.
Keeps the state of a single program/class during compilation.
Not in use yet!
This class acts as a lock against other threads accessing the compiler.
The lock is released when the object is destructed.
Codec used by decode_value()
to decode objects, functions and
programs which have been encoded by Encoder.nameof
in the
corresponding Encoder
object.
object
__register_new_program(program
p
)
Called to register the program that is being decoded. Might get called repeatedly with several other programs that are being decoded recursively. The only safe assumption is that when the top level thing being decoded is a program, then the first call will be with the unfinished embryo that will later become that program.
Returns either zero or a placeholder object. A placeholder
object must be a clone of __null_program
. When the program is
finished, the placeholder object will be converted to a clone of
it. This is used for pike module objects.
function
(:void
) functionof(string
data
)
Decode function encoded in data
.
This function is called by decode_value()
when it encounters
encoded functions.
data
Encoding of some function as returned by Encoder.nameof()
.
Returns the decoded function.
objectof()
, programof()
object
objectof(string
data
)
Decode object encoded in data
.
This function is called by decode_value()
when it encounters
encoded objects.
data
Encoding of some object as returned by Encoder.nameof()
.
Returns the decoded object.
functionof()
, programof()
program
programof(string
data
)
Decode program encoded in data
.
This function is called by decode_value()
when it encounters
encoded programs.
data
Encoding of some program as returned by Encoder.nameof()
.
Returns the decoded program.
functionof()
, objectof()
Codec used by encode_value()
to encode objects, functions and
programs. Its purpose is to look up some kind of identifier for
them, so they can be mapped back to the corresponding instance
by decode_value()
, rather than creating a new copy.
mixed
nameof(object
|function
(:void
)|program
x
)
Called by encode_value()
to encode objects, functions and programs.
Returns something encodable on success, typically a string.
The returned value will be passed to the corresponding
objectof()
, functionof()
or programof()
by
decode_value()
.
If it returns UNDEFINED
then encode_value
starts to encode
the thing recursively, so that decode_value
later will
rebuild a copy.
encode_value()
has fallbacks for some classes of objects,
functions and programs.
Decoder.objectof()
, Decoder.functionof()
,
Decoder.objectof()
This is the interface for iterator objects. They implement an interface to a collection or stream of data items and a cursor that can be used to iterate over and examine individual items in the data set.
Iterators are typically created to access a data set in some
specific object, array, mapping, multiset or string. An object can
have several iterators that access different data sets in it, or
the same in different ways. E.g. strings have both an iterator for
access char-by-char (String.Iterator
), and another for access
over splitted substrings (String.SplitIterator
).
lfun::_get_iterator
may be defined in an object to get an
instance of the canonical iterator type for it. It's used by e.g.
foreach
to iterate over objects conveniently.
It's not an error to advance an iterator past the beginning or end
of the data set; `!()
will only return true then, and index
and value
will return UNDEFINED
. An iterator in that state
need not keep track of positions, so it's undefined what happens
if it's "moved back" into the set of items.
Backward movement for iterators is optional. It's supported if and
only if `-()
is defined, but even then it's undefined how far
back the iterator can move. Therefore iterators may support only a
limited amount of backward movement, e.g. when they access a
stream through a limited buffer. If such an iterator is moved back
past the limit then it'll behave as if it's pointing entirely
outside the data set (see above).
An iterator that doesn't support backward movement at all should throw an error if it's attempted.
predef::get_iterator
, lfun::_get_iterator
,
Array.Iterator
, Mapping.Iterator
, Multiset.Iterator
,
String.Iterator
, String.SplitIterator
.
void
random( Iterator arg )
If this function is defined then it sets the iterator to point
to a random item in the accessible set. The random distribution
should be rectangular within that set, and the pseudorandom
sequence provided by random
should be used.
int
sizeof( Iterator arg )
Returns the total number of items in the data set according to this iterator. If the size of the data set is unlimited or unknown then this function shouldn't be defined.
bool
res = !Iterator()
Returns 0
(zero) when the iterator points to an item,
1
otherwise.
Iterator
res = Iterator()
+ steps
Returns a clone of this iterator which is advanced the specified number of steps. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.
next
, `+=
, `-
Iterator()
+= steps
Advance this iterator the specified number of steps and return it. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.
foreach
calls this function with a step value of 1
if next()
doesn't exist for compatibility with Pike 7.6
and earlier.
foreach
will call this function even when the the
iterator has more than one reference. If you want to
loop over a copy of the iterator, you can create a
copy by adding 0
(zero) to it:
Iterator iterator;
...
foreach(iterator+0; mixed index; mixed value) {
...
}
Even though this function is sufficient for foreach
to
advance the iterator, next()
is the preferred API.
next()
has the additional advantage of not being an
lfun, so it is possible to advance the iterator by hand.
next
, `+
, `-
Iterator
res = Iterator()
- steps
This lfun should be defined if and only if the iterator supports backward movement to some degree. It should back up the specified number of steps. The amount may be negative to move forward.
next
, `+
, `+=
Iterator Iterator(
void
|mixed
data
)
Initialize this iterator to access a data set in data
. The
type of data
is specific to the iterator implementation. An
iterator may also access some implicit data set, in which case
data
isn't specified at all.
The iterator initially points to the first item in the data set, if there is any.
The iterator does not need to support being reused, so this
function is typically declared protected
.
optional
bool
first()
If this function is defined then it resets the iterator to point to the first item.
Returns zero if there are no items at all in the data set, one otherwise.
It's not enough to set the iterator to the earliest accessible item. If the iterator doesn't support backing up to the original start position then this function should not be implemented.
mixed
index()
Returns the current index, or UNDEFINED
if the iterator
doesn't point to any item.
If there's no obvious index set then the index is the current
position in the data set, counting from 0
(zero).
int
next()
If this function is defined it should advance the iterator one
step, just like
would do.`+=
(1)
This is the preferred way to advance the iterator, since it reduces the overhead.
This function was optional in Pike 7.6 and earlier.
Returns 1 if it succeeded in advancing, and 0 (zero) if it has reached the end of the iterator.
`+
, `+=
, `-
optional
void
set_index(zero
index
)
If this function is defined it should set the iterator at the specified index.
It should be possible to set the index at the end of the iterator.
mixed
value()
Returns the current value, or UNDEFINED
if the iterator
doesn't point to any item.
Master control program for Pike.
predef::master()
, predef::replace_master()
program
MasterObject.Decoder
This program in the master is cloned and used as codec by
decode_value
if it wasn't given any codec. An instance is only
created on-demand the first time decode_value
encounters
something for which it needs a codec, i.e. the result of a call to
Pike.Encoder.nameof
.
Decoder
, Pike.Decoder
program
MasterObject.Encoder
This program in the master is cloned and used as codec by
encode_value
if it wasn't given any codec. An instance is only
created on-demand the first time encode_value
encounters
something for which it needs a codec, i.e. an object, program, or
function.
Encoder
, Pike.Encoder
void
_main(array
(string(8bit)
) orig_argv
)
This function is called when all the driver is done with all setup of modules, efuns, tables etc. etc. and is ready to start executing _real_ programs. It receives the arguments not meant for the driver.
string
MasterObject._pike_file_name
string
MasterObject._master_file_name
These are useful if you want to start other Pike processes with the same options as this one was started with.
bool
asyncp()
Returns 1 if we´re in async-mode, e.g. if the main method has returned a negative number.
object
backend_thread()
The backend_thread() function is useful to determine if you are the backend thread - important when doing async/sync protocols. This method is only available if thread_create is present.
string
basename(string
x
)
Returns the last segment of a path.
dirname()
, explode_path()
constant
int
MasterObject.bt_max_string_len
This constant contains the maximum length of a function entry in a backtrace. Defaults to 200 if no BT_MAX_STRING_LEN define has been given.
object
cast_to_object(string
oname
, string
current_file
, object
|void
current_handler
)
This function is called when the drivers wants to cast a string to an object because of an implict or explicit cast. This function may also receive more arguments in the future.
object
cast_to_object(string
str
, string
|void
current_file
)
Called by the Pike runtime to cast strings to objects.
str
String to cast to object.
current_file
Filename of the file that attempts to perform the cast.
Returns the resulting object.
cast_to_program()
program
cast_to_program(string
pname
, string
current_file
, object
|void
handler
)
This function is called when the driver wants to cast a string to a program, this might be because of an explicit cast, an inherit or a implict cast. In the future it might receive more arguments, to aid the master finding the right program.
program
cast_to_program(string
str
, string
|void
current_file
)
Called by the Pike runtime to cast strings to programs.
str
String to cast to object.
current_file
Filename of the file that attempts to perform the cast.
Returns the resulting program.
cast_to_object()
string
MasterObject.cflags
Flags suitable for use when compiling Pike C modules
int
MasterObject.compat_major
int
MasterObject.compat_minor
void
compile_error(string
file
, int
line
, string
err
)
This function is called whenever a compile error occurs. line
is zero for errors that aren't associated with any specific line.
err
is not newline terminated.
compile_warning()
, compile_exception()
,
get_inhibit_compile_errors()
, set_inhibit_compile_errors()
,
int
compile_exception(array
|object
trace
)
This function is called when an exception is caught during
compilation. Its message is also reported to compile_error
if
this function returns zero.
compile_error()
, compile_warning()
,
get_inhibit_compile_errors()
, set_inhibit_compile_errors()
,
program
compile_file(string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
)
Compile the Pike code contained in the file filename
into a program.
This function will compile the file filename
to a Pike program that can
later be instantiated. It is the same as doing
.compile_string
(Stdio.read_file
(filename
), filename
)
compile()
, compile_string()
, cpp()
program
compile_string(string
source
, void
|string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
, void
|int
_show_if_constant_errors
)
Compile the Pike code in the string source
into a program.
If filename
is not specified, it will default to "-"
.
Functionally equal to
.compile
(cpp
(source
, filename
))
compile()
, cpp()
, compile_file()
void
compile_warning(string
file
, int
line
, string
err
)
This function is called whenever a compile warning occurs. line
is zero for warnings that aren't associated with any specific
line. err
is not newline terminated.
compile_error()
, compile_exception()
,
get_inhibit_compile_errors()
, set_inhibit_compile_errors()
,
Version
MasterObject.currentversion
Version information about the current Pike version.
string
decode_charset(string
data
, string
charset
)
This function is called by cpp() when it wants to do character code conversion.
string
decode_charset(string
raw
, string
charset
)
Convert raw
from encoding charset
to UNICODE.
This function is called by cpp()
when it encounters
#charset
directives.
raw
String to convert.
charset
Name of encoding that raw
uses.
raw
decoded to UNICODE, or 0
(zero) if the decoding failed.
Charset
string
describe_backtrace(mixed
trace
, void
|int
linewidth
)
Return a readable message that describes where the backtrace
trace
was made (by backtrace
).
It may also be an error object or array (typically caught by a
catch
), in which case the error message also is included in the
description.
Pass linewidth
-1 to disable wrapping of the output.
backtrace()
, describe_error()
, catch()
, throw()
string
describe_backtrace(mixed
exception
)
Called by various routines to format a readable description of an exception.
exception
Something that was thrown. Usually an Error.Generic
object, or
an array with the following content:
Array | |
| Error message. |
| Backtrace to the point where the exception occurred. |
Returns a string describing the exeception.
Usually added by the initialization code the global name space
with add_constant()
.
predef::describe_backtrace()
string
describe_error(mixed
err
)
Return the error message from an error object or array (typically
caught by a catch
). The type of the error is checked, hence
err
is declared as mixed
and not object|array
.
If an error message couldn't be obtained, a fallback message
describing the failure is returned. No errors due to incorrectness
in err
are thrown.
describe_backtrace()
, get_backtrace
string
describe_function(function
(:void
) f
)
string
describe_module(object
|program
mod
, array
(object
)|void
ret_obj
)
Describe the path to the module mod
.
mod
If mod
is a program, attempt to describe the path
to a clone of mod
.
ret_obj
If an instance of mod
is found, it will be returned
by changing element 0
of ret_obj
.
The a description of the path.
The returned description will end with a proper indexing method
currently either "."
or "->"
.
string
describe_object(object
o
)
string
describe_program(program
|function
(:void
) p
)
string
dirname(string
x
)
Returns all but the last segment of a path. Some example inputs and outputs:
Expression | Value |
dirname("/a/b") | "/a" |
dirname("/a/") | "/a" |
dirname("/a") | "/" |
dirname("/") | "/" |
dirname("") | "" |
basename()
, explode_path()
string
MasterObject.doc_prefix
Prefix for autodoc files.
mapping
(string
:program
|NoValue
) MasterObject.programs
mapping
(program
:object
) MasterObject.documentation
mapping
(program
:string
) MasterObject.source_cache
Mapping containing the cache of currently compiled files.
This mapping currently has the following structure:
|
The filename path separator is / on both NT and UNIX.
Special cases: The current master program is available under the
name "/master"
, and the program containing the main
function under "/main"
.
void
enable_source_cache()
Enable caching of sources from compile_string()
void
error(sprintf_format
f
, sprintf_args
... args
)
Throws an error. A more readable version of the code
throw( ({ sprintf(f, @args), backtrace() }) )
.
array
(string
) explode_path(string
p
)
Split a path p
into its components.
This function divides a path into its components. This might seem like
it could be done by dividing the string on <tt>"/"</tt>, but that will
not work on some operating systems. To turn the components back into
a path again, use combine_path()
.
string
fc_reverse_lookup(object
obj
)
Returns the path for obj
in fc
, if it got any.
array
get_backtrace(object
|array
err
)
Return the backtrace array from an error object or array
(typically caught by a catch
), or zero if there is none. Errors
are thrown on if there are problems retrieving the backtrace.
describe_backtrace()
, describe_error()
object
get_compat_master(int
major
, int
minor
)
Return a master object compatible with the specified version of Pike.
This function is used to implement the various compatibility versions
of master()
.
get_compilation_handler()
, master()
CompilationHandler
get_compilation_handler(int
major
, int
minor
)
Get compilation handler for simulation of Pike vmajor
.minor
.
This function is called by cpp()
when it encounters
#pike
directives.
major
Major version.
minor
Minor version.
Returns a compilation handler for Pike >= major
.minor
.
mixed
get_inhibit_compile_errors()
Get the current compile error, warning and exception behaviour.
See set_inhibit_compile_errors()
for details.
set_inhibit_compile_errors()
int
get_precompiled_mtime(string
id
)
Given an identifier returned by query_precompiled_names, returns the mtime of the precompiled entry. Returns -1 if there is no entry.
mapping
(string
:string
) getenv(void
|int
force_update
)
Queries the environment variables.
force_update
A cached copy of the real environment is kept to make this
function quicker. If the optional flag force_update
is nonzero
then the real environment is queried and the cache is updated from
it. That can be necessary if the environment changes through other
means than putenv
, typically from a C-level library.
Returns the whole environment as a mapping. Destructive operations on the mapping will not affect the internal environment representation.
Variable names and values cannot be wide strings nor contain
'\0'
characters. Variable names also cannot contain
'='
characters.
On NT the environment variable name is case insensitive.
putenv()
string
getenv(string
varname
, void
|int
force_update
)
Query the value of a specific environment variable.
varname
Environment variable to query.
force_update
A cached copy of the real environment is kept to make this
function quicker. If the optional flag force_update
is nonzero
then the real environment is queried and the cache is updated from
it. That can be necessary if the environment changes through other
means than putenv
, typically from a C-level library.
Returns the value of the environment variable varname
if it exists, and 0
(zero) otherwise.
Variable names and values cannot be wide strings nor contain
'\0'
characters. Variable names also cannot contain
'='
characters.
On NT the environment variable name is case insensitive.
putenv()
void
handle_error(array
|object
trace
)
This function is called when an error occurs that is not caught with catch().
void
handle_error(mixed
exception
)
Called by the Pike runtime if an exception isn't caught.
exception
Value that was throw()
'n.
describe_backtrace()
program
handle_inherit(string
pname
, string
current_file
, object
|void
handler
)
This function is called whenever a inherit is called for. It is supposed to return the program to inherit. The first argument is the argument given to inherit, and the second is the file name of the program currently compiling. Note that the file name can be changed with #line, or set by compile_string, so it can not be 100% trusted to be a filename. previous_object(), can be virtually anything in this function, as it is called from the compiler.
string
MasterObject.include_prefix
Prefix for Pike-related C header files.
inherit Codec : Codec
inherit CompatResolver : CompatResolver
inherit CompilationHandler : CompilationHandler
The master object acts as fallback compilation handler for
compile()
and cpp()
.
protected
inherit Pike_7_8_master : Pike_7_8_master
Namespaces for compat masters.
This inherit is used to provide compatibility namespaces
for get_compat_master()
.
get_compat_master()
int
is_absolute_path(string
p
)
Check if a path p
is fully qualified (ie not relative).
Returns 1 if the path is absolute, 0 otherwise.
string
MasterObject.ldflags
Flags suitable for use when linking Pike C modules
string
master_read_file(string
file
)
array
(string
) module_defined(object
|program
mod
)
Find the files in which mod
is defined, as they may be hidden away in
joinnodes and dirnodes
mod
The module we are looking for.
An array of strings with filenames. (one for each file in a joinnode, or just one otherwise)
string
normalize_path(string
path
)
Replaces "\" with "/" if runing on MS Windows. It is
adviced to use System.normalize_path
instead.
program
objects_reverse_lookup(object
obj
)
Returns the program for obj
, if known to the master.
constant
int
MasterObject.out_of_date_warning
Should Pike complain about out of date compiled files. 1 means yes and 0 means no. Controlled by the OUT_OF_DATE_WARNING define.
string
program_path_to_name(string
path
, void
|string
module_prefix
, void
|string
module_suffix
, void
|string
object_suffix
)
Converts a module path on the form "Foo.pmod/Bar.pmod"
or
"/path/to/pike/lib/modules/Foo.pmod/Bar.pmod"
to a module
identifier on the form "Foo.Bar"
.
If module_prefix
or module_suffix
are given, they are
prepended and appended, respectively, to the returned string if
it's a module file (i.e. ends with ".pmod"
or
".so"
). If object_suffix
is given, it's appended to the
returned string if it's an object file (i.e. ends with
".pike"
).
string
programs_reverse_lookup(program
prog
)
Returns the path for prog
in programs
, if it got any.
void
putenv(string
varname
, void
|string
value
)
Sets the environment variable varname
to value
.
If value
is omitted or zero, the environment variable
varname
is removed.
varname
and value
cannot be wide strings nor contain
'\0'
characters. varname
also cannot contain
'='
characters.
On NT the environment variable name is case insensitive.
getenv()
array
(string
) query_precompiled_names(string
fname
)
Returns identifiers (e.g. file names) of potentially precompiled files in priority order.
string
read_precompiled(string
id
)
Given an identifier returned by query_precompiled_names, returns the precompiled entry. Can assume the entry exists.
void
runtime_warning(string
where
, string
what
, mixed
... args
)
Called for every runtime warning. The first argument identifies where the warning comes from, the second identifies the specific message, and the rest depends on that. See code below for currently implemented warnings.
void
runtime_warning(string
subsystem
, string
msg
, mixed
|void
data
)
Called by the Pike runtime to warn about data inconsistencies.
subsystem
Runtime subsystem where the warning was generated. Currently the following subsystems may call this function:
| The garbage collector. |
msg
Warning message. Currently the following messages may be generated:
| A cycle where the destruction order isn't deterministic was detected by the garbage collector. |
data
Optional data that further describes the warning specified by msg
.
void
set_inhibit_compile_errors(mixed
behaviour
)
Set the compile error, warning and exception behaviour.
behaviour
The desired behaviour. One of:
| Output compilation errors and warnings to stderr. This is the default behaviour. |
| Inhibit output of compilator diagnostics. |
| Function to call for compilation errors. Compilation warnings and exceptions are inhibited. The function will be called with the same arguments
as those passed to |
| Compilation handler to use for diagnostics. |
Note that the behaviour is thread local, and is not copied to new threads when they are created.
get_inhibit_compile_errors()
object
show_doc(program
|object
|function
(:void
) obj
)
Show documentation for the item obj
obj
The object for which the documentation should be shown
an AutoDoc object
int
MasterObject.show_if_constant_errors
int
strlen(string
|multiset
|array
|mapping
|object
thing
)
Alias for sizeof
.
Replaced by sizeof
.
void
thread_quanta_exceeded(Thread.Thread
thread
, int
ns
)
Function called when a thread has exceeded the thread quanta.
thread
Thread that exceeded the thread quanta.
ns
Number of nanoseconds that the thread executed before allowing other threads to run.
The default master prints a diagnostic and the thread backtrace
to Stdio.stderr
.
This function runs in a signal handler context, and should thus avoid handling of mutexes, etc.
get_thread_quanta()
, set_thread_quanta()
void
unregister(program
p
)
Unregister a program that was only partially compiled.
Called by compile()
to clean up references to partially compiled
programs.
p
Partially compiled program that should no longer be referenced.
Shouldn't this function be in the compilation handler?
int
MasterObject.want_warnings
If not zero compilation warnings will be written out on stderr.
int
werror(string
fmt
, mixed
... args
)
Writes a string on stderr. Works just like Stdio.File.write
on Stdio.stderr
.
int
write(string
fmt
, mixed
... args
)
Writes a string on stdout. Works just like Stdio.File.write
on Stdio.stdout
.
Encoder
and Decoder
rolled into one. This is for mainly
compatibility; there's typically no use combining encoding and
decoding into the same object.
MasterObject.Codec MasterObject.Codec(
void
|mixed
encoded
)
The optional argument is the thing to encode; it's passed on to
Encoder
.
inherit Decoder : Decoder
inherit Encoder : Encoder
Resolver of symbols not located in the program being compiled.
void
add_include_path(string
tmp
)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void
add_module_path(string
tmp
)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
void
add_predefine(string
name
, mixed
value
)
Add a define (without arguments) which will be implicitly
defined in cpp
calls.
void
add_program_path(string
tmp
)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
MasterObject.CompatResolver MasterObject.CompatResolver(
mixed
version
, CompatResolver
|void
fallback_resolver
)
The CompatResolver is initialized with a value that can be casted into a "%d.%d" string, e.g. a version object.
It can also optionally be initialized with a fallback resolver.
CompatResolver
MasterObject.CompatResolver.fallback_resolver
If we fail to resolv, try the fallback.
Typical configuration:
0.6->7.0->7.2-> ... ->master
mapping
get_default_module()
mapping
get_predefines()
Returns a mapping with the current predefines.
string
handle_include(string
f
, string
current_file
, int
local_include
)
This function is called whenever an #include directive is encountered. It receives the argument for #include and should return the file name of the file to include
mapping
(object
:joinnode
) MasterObject.CompatResolver.handler_root_modules
Lookup from handler module to corresponding root_module.
protected
mapping
(string
:mixed
) instantiate_static_modules(object
|mapping
static_modules
)
Instantiate static modules in the same way that dynamic modules are instantiated.
array
(string
) MasterObject.CompatResolver.pike_include_path
The complete include search path
array
(string
) MasterObject.CompatResolver.pike_module_path
The complete module search path
array
(string
) MasterObject.CompatResolver.pike_program_path
The complete program search path
string
read_include(string
f
)
void
remove_include_path(string
tmp
)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path()
.
add_include_path()
void
remove_module_path(string
tmp
)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path()
.
add_module_path()
void
remove_predefine(string
name
)
Remove a define from the set that are implicitly defined in
cpp
calls.
void
remove_program_path(string
tmp
)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path()
.
add_program_path()
mixed
resolv(string
identifier
, string
|void
current_file
, object
|void
current_handler
)
mixed
resolv_base(string
identifier
, string
|void
current_file
, object
|void
current_handler
)
mixed
resolv_or_error(string
identifier
, string
|void
current_file
, void
|object
current_handler
)
Same as resolv
, but throws an error instead of returning
UNDEFINED
if the resolv failed.
joinnode
MasterObject.CompatResolver.root_module
Join node of the root modules for this resolver.
array
(string
) MasterObject.CompatResolver.system_module_path
The pike system module path, not including any set by the user.
Codec for use with decode_value
. This is the decoder
corresponding to Encoder
. See that one for more details.
MasterObject.Decoder MasterObject.Decoder(
void
|string
fname
, void
|int
mkobj
, void
|object
handler
)
array
(mixed
) decode_object(object
o
, mixed
data
)
Restore the state of an encoded object.
o
Object to modify.
data
State information from Encoder()->encode_object()
.
The default implementation calls o->_decode(data)
if the object has an _decode()
, otherwise if
data
is an array, returns it to indicate that lfun::create()
should be called.
This function is called before lfun::create()
in the object has been called, but after lfun::__INIT()
has been called.
Returns an array to indicate to the caller that
lfun::create()
should be called with the elements
of the array as arguments.
Returns 0
(zero) to inhibit calling of lfun::create()
.
Encoder()->encode_object()
void
|string
MasterObject.Decoder.fname
void
|int
MasterObject.Decoder.mkobj
void
|object
MasterObject.Decoder.handler
Codec for use with encode_value
. It understands all the
standard references to builtin functions, pike modules, and the
main program script.
The format of the produced identifiers are documented here to allow extension of this class:
The produced names are either strings or arrays. The string variant specifies the thing to look up according to the first character:
'c' Look up in all_constants(). 's' Look up in _static_modules. 'r' Look up with resolv(). 'p' Look up in programs. 'o' Look up in programs, then look up the result in objects. 'f' Look up in fc.
In the array format, the first element is a string as above and the rest specify a series of things to do with the result:
A string Look up this string in the result. 'm' Get module object in dirnode. 'p' Do object_program(result).
All lowercase letters and the symbols ':', '/' and '.' are reserved for internal use in both cases where characters are used above.
MasterObject.Encoder MasterObject.Encoder(
void
|mixed
encoded
)
Creates an encoder instance. If encoded
is specified, it's
encoded instead of being reverse resolved to a name. That's
necessary to encode programs.
string
|array
nameof(mixed
what
, void
|array
(object
) module_object
)
When module_object
is set and the name would end with an
object_program
step (i.e. 'p'
), then drop that
step so that the name corresponds to the object instead.
will receive the found object.module_object
[0]
Pike 7.6 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 7.6.
Replaced by predef::MasterObject
.
get_compat_master()
, master()
, predef::MasterObject
mapping
(string
:array
(string
)) MasterObject.Pike_7_6_master.environment
Mapping containing the environment variables.
The mapping currently has the following structure:
| Note that the index is
|
This mapping should not be accessed directly; use getenv()
and putenv()
instead. This mapping is not publicly
accessible in pikes newer than 7.6.
This mapping is not compatible with Process.create_process()
;
use the mapping returned from calling getenv()
without arguments
instead.
This mapping is not the real environment; it is just a copy of the environment made at startup. Pike does attempt to keep track of changes in the mapping and to reflect them in the real environment, but avoid accessing this mapping if at all possible.
Pike 7.8 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 7.7 and 7.8.
Replaced by predef::MasterObject
.
get_compat_master()
, master()
, predef::MasterObject
inherit Pike_7_6_master : Pike_7_6_master
Contains version information about a Pike version.
int
res = MasterObject.Version()
< v
int
res = MasterObject.Version()
> v
int
res = MasterObject.Version()
== v
int
hash_value( MasterObject.Version arg )
Methods define so that version objects can be compared and ordered.
(int)MasterObject.Version()
(float)MasterObject.Version()
(string)MasterObject.Version()
(array)MasterObject.Version()
(mapping)MasterObject.Version()
(multiset)MasterObject.Version()
The version object can be casted into a string.
MasterObject.Version MasterObject.Version(
int
major
, int
minor
)
Set the version in the object.
int
MasterObject.Version.major
int
MasterObject.Version.minor
The major and minor parts of the version.
Module node representing a single directory.
joinnode
string
MasterObject.dirnode.dirname
object
|void
MasterObject.dirnode.compilation_handler
string
|void
MasterObject.dirnode.name
MasterObject.dirnode MasterObject.dirnode(
string
dirname
, object
|void
compilation_handler
, string
|void
name
)
Module node holding possibly multiple directories, and optionally falling back to another level.
dirnode
array
(object
|mapping
) MasterObject.joinnode.joined_modules
object
|void
MasterObject.joinnode.compilation_handler
joinnode
|mapping
(mixed
:int(0..0)
)|void
MasterObject.joinnode.fallback_module
string
|void
MasterObject.joinnode.name
MasterObject.joinnode MasterObject.joinnode(
array
(object
|mapping
) joined_modules
, object
|void
compilation_handler
, joinnode
|mapping
(mixed
:int(0..0)
)|void
fallback_module
, string
|void
name
)
API for reporting parse errors and similar.
void
report(SeverityLevel
severity
, string
filename
, int(1..)
linenumber
, string
subsystem
, string
message
, mixed
... extra_args
)
Report a diagnostic from the compiler.
severity
The severity of the diagnostic.
filename
linenumber
Location which triggered the diagnostic.
subsystem
Compiler subsystem that generated the diagnostic.
message
sprintf()
-style formatting string with the diagnostic message.
extra_args
Extra arguments to sprintf()
.
The default implementation does the following:
If there's a MasterObject()->report()
, call it
with the same arguments as ourselves.
Otherwise depending on severity
:
| Ignored. |
| Calls |
| Calls |
|
If there's no master object yet, the diagnostic is output to
Stdio.stderr
.
In Pike 7.8 and earlier MasterObject()->report()
was not called.
PikeCompiler()->report()
Message severity level. { NOTICE, WARNING, ERROR, FATAL }
report()
constant
Reporter.NOTICE
constant
Reporter.WARNING
constant
Reporter.ERROR
constant
Reporter.FATAL
mapping
(string
:array
(array
(Parser.C.Token
))) parse(array
(Parser.C.Token
) tokens
)
Returns a mapping from symbol to a tuple of return type and parameters.
int
res = string_assignment()
[ i
]
String index operator.
string_assignment()
[ i
] = j
String assign index operator.
Support for the Apple Keychain format.
This is used for the files in eg /System/Library/Keychains.
Argument parsing module This module supports two rather different methods of argument parsing. The first is suitable quick argument parsing without much in the way of checking:
int main( int c, array(string) argv )
{
mapping arguments = Arg.parse(argv);
array files = arguments[Arg.REST];
if( arguments->help ) print_help();
...
}
The Arg.parse
method will return a mapping from argument name
to the argument value, if any.
Non-option arguments will be placed in the index Arg.REST
The second way to use this module is to inherit the LowOptions class and then start adding supported arguments:
class MyArguments {
inherit Arg.LowOptions;
Opt verbose = NoOpt("-v")|NoOpt("--verbose");
Opt help = MaybeOpt("--help");
Opt output = HasOpt("--output")|HasOpt("-o");
};
Then, in main:
MyArguments args = MyArguments(argv);
See the documentation for OptLibrary
for details about the various
Opt classes.
constant
Arg.REST
Constant used by Arg.parse() to indicate the remaining objects.
mapping
(string
:string
|int(1..)
) parse(array
(string
) argv
)
Convenience function for simple argument parsing.
Handles the most common cases.
The return value is a mapping from option name to the option value.
The special index Arg.REST will be set to the remaining arguments after all options have been parsed.
The following argument syntaxes are supported:
--foo -> "foo":1
--foo=bar -> "foo":"bar"
-bar -> "b":1,"a":1,"r":1
-bar=foo -> "b":1,"a":1,"r":"foo" (?)
--foo --bar -> "foo":1,"bar":1
--foo - --bar -> "foo":1
--foo x --bar -> "foo":1 (?)
-foo -> "f":1,"o":2
-x -x -x -> "x":3
void main(int n, array argv) { mapping opts = Arg.parse(argv); argv = opts[Arg.REST]; if( opts->help ) /*... */ }
protected
string
Arg.LowOptions.application
protected
array
(string
) Arg.LowOptions.argv
Arg.LowOptions Arg.LowOptions(
array
(string
) _argv
, void
|mapping
(string
:string
) env
)
protected
inherit OptLibrary : OptLibrary
protected
mapping
(string
:Opt
) Arg.LowOptions.opts
protected
bool
unhandled_argument(array
(string
) argv
, mapping
(string
:string
) env
)
protected
mapping
(string
:int(1..1)
|string
) Arg.LowOptions.values
Default value for a setting.
Opt output = HasOpt("-o")|Default("a.out");
inherit Opt : Opt
Environment fallback for an option. Can of course be used as only Opt source.
Opt debug = NoOpt("--debug")|Env("MY_DEBUG");
inherit Opt : Opt
Parses an option that has a parameter. --foo=bar, -x
bar and -x=bar will set the variable to bar
.
Opt user = HasOpt("--user")|HasOpt("-u");
inherit NoOpt : NoOpt
Parses an option that may have a parameter. --foo,
-x and x in a sequence like -axb will set the
variable to 1
. --foo=bar, -x bar and
-x=bar will set the variable to bar
.
Opt debug = MaybeOpt("--debug");
inherit NoOpt : NoOpt
Parses an option without parameter, such as --help, -x or "x" from -axb.
Opt verbose = NoOpt("-v")|NoOpt("--verbose");
inherit Opt : Opt
Base class for parsing an argument. Inherit this class to create custom made option types.
protected
string
__sprintf()
This function will be called by _sprintf
, which
handles formatting of chaining between objects.
array
(string
) get_opts()
Should return a list of options that are parsed. To properly
chain argument parsers, return your_opts +
::get_opts()
.
mixed
get_value(array
(string
) argv
, mapping
(string
:string
) env
, int
|string
previous
)
Should return 1 for set options or a string containing the
value of the option. Returning 0 means the option was not set
(or matched). To properly chain arguments parsers, return
::get_value(argv, env, previous)
instead of 0
,
unless you want to explicitly stop the chain and not set this
option.
The option parser class that contains all the argument objects.
inherit LowOptions : LowOptions
protected
bool
|string
unhandled_argument(array
(string
) argv
, mapping
(string
:string
) env
)
Options parser with a unhandled_argument implementation that parses most common argument formats.
inherit LowOptions : LowOptions
bool
unhandled_argument(array
(string
) argv
, mapping
(string
:string
) env
)
Handles arguments as described in Arg.parse
Decoder object.
It needs _Ffmpeg.ffmpeg
module for real work.
Audio.Codec.decoder Audio.Codec.decoder(
string
|void
codecname
, object
|void
_codec
)
Creates decoder object
codecnum
Some of supported codec, like _Ffmpeg.CODEC_ID_*
_codec
The low level object will be used for decoder.
By default _Ffmpeg.ffmpeg
object will be used.
Until additional library is implemented the second
parameter _codec
hasn't effect.
_Ffmpeg.ffmpeg
, _Ffmpeg.CODEC_ID_MP2
mapping
|int
decode(int
|void
partial
)
Decodes audio data
partial
Only one frame will be decoded per call.
If successfull a mapping with decoded data and byte number of used input data is returned, 0 otherwise.
this_program
from_file(Audio.Format.ANY
file
)
Set codec type from file
It uses Audio.Format.ANY
's method get_map()
to determine which codec should be used.
file
The object Audio.Format.ANY
.
mapping
get_status()
Returns decoder status
Audio data format handling
API remains marked "unstable".
int
check_format()
Check if data are correctly formated.
string
get_data()
Returns data only.
The operation is destructive. Ie. current data cursor is moved over.
get_frame
, get_sample
string
get_frame()
Returns frame for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_data
, get_sample
mapping
get_map()
mapping
get_sample()
Returns sample for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_frame
, get_data
this_program
read_file(string
filename
, int
|void
nocheck
)
Reads data from file
read_streamed
this_program
read_streamed(string
filename
, int
|void
nocheck
)
Reads data from stream
Ie. for packetized data source the beggining of data is searched.
read_file
this_program
read_string(string
data
, int
|void
nocheck
)
Reads data from string
A MP3 file parser with ID3 tag support.
mapping
|int
get_frame()
Gets next frame from file
Frame is represented by the following mapping. It contains from parsed frame headers and frame data itself.
([ "bitrate": int "copyright": int(0..1), "data": frame_data, "emphasis": emphasis, "extension": "channels":0, "id":1, "layer":3, "original": int(0..1), "padding": int(0..1), "private": int(0..1), "sampling": int ])
inherit .module.ANY : ANY
function
(mixed_void
:void
) _get_setter(object
o
, string
varname
)
Get a setter for the variable named varname
in object o
.
Returns a Setter()->`()()
for the variable if it exists,
and UNDEFINED
otherwise.
object_variablep()
mapping
(string
:mixed
) _take_over_initial_predefines()
This class is used to implement the low-level aspects of Val.Null
.
This class should typically not be used directly. Use
Val.Null
instead.
This class was previously available as Sql.Null
. Any such use
should be replaced with Val.Null
.
Replaced by Val.Null
.
Val.Null
, Val.null
string
encode_json()
Defined for use with Standards.JSON.encode
, so that it
formats NULL as null
.
Internal class for implementing setters.
This class is used by _get_setter()
.
_get_setter()
void
res = Builtin.Setter()
()
Set the variable for the setter to val
.
This is the function returned by _get_setter()
.
This is an internal class used by __automap__()
.
It may show up during module dumping or in backtraces and the like.
It should in normal circumstances never be used directly.
__automap__()
, map()
Builtin.automap_marker Builtin.automap_marker(
array
arr
, int
depth
)
arr
Array that __automap__()
is to loop over.
depth
Recursion depth of arr
where the loop will be.
The Bz2 module contains functions to compress and uncompress strings using the same algorithm as the program bzip2. Compressing and decompressing can be done in streaming mode feeding the compress and decompress objects with arbitrarily large pieces of data.
The Bz2 module consists of three classes; Bz2.Deflate
,
Bz2.Inflate
and Bz2.File
. Bz2.Deflate
is used to compress
data and Bz2.Inflate
is used to uncompress data. Bz2.File
is
used to handle Bzip2 files.
Note that this module is only available if libbzip2 was available when Pike was compiled.
Note that although the functions in Inflate
and Deflate
use the same algorithm as bzip2, they do not use the
exact same format, so you can not directly zip files or unzip
zip-files using those functions. That is why there exists a
third class for files.
inherit "___Bz2" : Bz2
Bz2.Deflate is a builtin program written in C. It interfaces the packing routines in the bzlib library.
This program is only available if libz was available and found when Pike was compiled.
Bz2.Inflate()
Bz2.Deflate Bz2.Deflate(
int(1..9)
|void
block_size
)
If given, block_size
should be a number from 1 to 9 indicating
the block size used when doing compression. The actual block size
will be a 100000 times this number. Low numbers are considered
'fast', higher numbers are considered 'slow' but give better
packing. The parameter is set to 9 if it is omitted.
This function can also be used to re-initialize a Bz2.Deflate object so it can be re-used.
string
deflate(string
data
, int(0..2)
|void
flush_mode
)
This function performs bzip2 style compression on a string
data
and returns the packed data. Streaming can be done by
calling this function several times and concatenating the
returned data.
The optional argument flush_mode
should be one of the
following:
| Runs Bz2.Deflate->feed() |
| Runs Bz2.Deflate->read() |
| Runs Bz2.Deflate->finish() |
Bz2.Inflate->inflate()
void
feed(string
data
)
This function feeds the data to the internal buffers of the Deflate object. All data is buffered until a read or a finish is done.
Bz2.Deflate->read()
Bz2.Deflate->finish()
string
finish(string
data
)
This method feeds the data to the internal buffers of the Deflate object. Then it compresses all buffered data adds a end of data marker ot it, returns the compressed data as a string, and reinitializes the deflate object.
Bz2.Deflate->feed()
Bz2.Deflate->read()
string
read(string
data
)
This function feeds the data to the internal buffers of the Deflate object. Then it compresses all buffered data and returns the compressed data as a string
Bz2.Deflate->feed()
Bz2.Deflate->finish()
Low-level implementation of read/write support for Bzip2 files
This class is currently not available on Windows.
bool
close()
closes the file
Bz2.File Bz2.File()
Bz2.File Bz2.File(
string
filename
, void
|string
mode
)
Creates a Bz2.File object
bool
eof()
1 if EOF has been reached, 0 otherwise
inherit Bz2::File : File
String.SplitIterator
|Stdio.LineIterator
line_iterator(int
|void
trim
)
Returns an iterator that will loop over the lines in this file. If trim is true, all '\r' characters will be removed from the input.
bool
open(string
file
, void
|string
mode
)
Opens a file for I/O.
file
The name of the file to be opened
mode
Mode for the file operations. Can be either "r" (read) or "w". Read is default.
string
read(int
len
)
Reads len (uncompressed) bytes from the file. If len is omitted the whole file is read. If read is unsuccessful, 0 is returned.
function
(:string
) read_function(int
nbytes
)
Returns a function that when called will call read
with
nbytes as argument. Can be used to get various callback
functions, eg for the fourth argument to
String.SplitIterator
.
bool
read_open(string
file
)
Opens a file for reading.
file
The name of the file to be opened
int
write(string
data
)
Writes the data to the file.
the number of bytes written to the file.
bool
write_open(string
file
)
Opens a file for writing.
file
The name of the file to be opened
Bz2.Inflate is a builtin program written in C. It interfaces the unpacking routines in the libz library.
This program is only available if bzlib was available and found when Pike was compiled.
Deflate
Bz2.Inflate Bz2.Inflate()
string
inflate(string
data
)
This function performs bzip2 style decompression. It can do decompression with arbitrarily large pieces of data. When fed with data, it decompresses as much as it can and buffers the rest.
while(..){ foo = compressed_data[i..i+9]; uncompressed_concatenated_data += inflate_object->inflate(foo); i = i+10; }
Bz2.Deflate->deflate()
Common Caching implementation
This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies.
To create a new cache, do Cache.cache
( Cache.Storage.Base
storage_type, Cache.Policy.Base
expiration_policy )
The cache store instances of Cache.Data
.
Base stored object for the cache system.
int
Cache.Data.atime
last-access time.
float
Cache.Data.cost
relative preciousness scale
Cache.Data Cache.Data(
void
|mixed
value
, void
|int
expire_time
, void
|float
preciousness
)
expire_time is relative and in seconds.
int
Cache.Data.ctime
creation-time
mixed
data()
A method in order to allow for lazy computation
int
Cache.Data.etime
expiry-time (if supplied). 0 otherwise
int
recursive_low_size(mixed
whatfor
)
Attempts a wild guess of an object's size. It's left here as a common utility. Some classes won't even need it.
int
size()
A method in order to allow for lazy computation. Used by some Policy Managers
This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies. Mechanisms to allow for distributed caching systems will be added in time, or at least that is the plan.
void
alookup(string
key
, function
(string
, mixed
, mixed
... :void
) callback
, int
|float
timeout
, mixed
... args
)
Asynchronously look the cache up. The callback will be given as arguments the key, the value, and then any user-supplied arguments. If the timeout (in seconds) expires before any data could be retrieved, the callback is called anyways, with 0 as value.
void
async_cleanup_cache()
Cache.cache Cache.cache(
Cache.Storage.Base
storage_mgr
, Cache.Policy.Base
policy_mgr
, void
|int
cleanup_cycle_delay
)
Creates a new cache object. Required are a storage manager, and an expiration policy object.
void
delete(string
key
, void
|bool
hard
)
Forcibly removes some key.
If the 'hard' parameter is supplied and true, deleted objects will also
have their lfun::destroy
method called upon removal by some
backends (i.e. memory)
mixed
lookup(string
key
)
Looks in the cache for an element with the given key and, if available, returns it. Returns 0 if the element is not available
void
start_cleanup_cycle()
void
store(string
key
, mixed
value
, void
|int
max_life
, void
|float
preciousness
, void
|multiset
(string
) dependants
)
Sets some value in the cache. Notice that the actual set operation might even not happen at all if the set data doesn't make sense. For instance, storing an object or a program in an SQL-based backend will not be done, and no error will be given about the operation not being performed.
Notice that while max_life will most likely be respected (objects will be garbage-collected at pre-determined intervals anyways), the preciousness . is to be seen as advisory only for the garbage collector If some data was stored with the same key, it gets returned. Also notice that max_life is relative and in seconds. dependants are not fully implemented yet. They are implemented after a request by Martin Stjerrholm, and their purpose is to have some weak form of referential integrity. Simply speaking, they are a list of keys which (if present) will be deleted when the stored entry is deleted (either forcibly or not). They must be handled by the storage manager.
void
threaded_cleanup_cycle()
Base class for cache expiration policies.
void
expire(Cache.Storage.Base
storage
)
Expire callback.
This function is called to expire parts
of storage
.
All Storage.Policy classes must MUST implement this method.
A multiple-policies expiration policy manager.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Policy.Multiple Cache.Policy.Multiple(
Cache.Policy.Base
... policies
)
void
expire(Cache.Storage.Base
storage
)
This expire function calls the expire functions in all of the sub-policies in turn.
inherit Cache.Policy.Base : Base
Null policy-manager for the generic Caching system
This is a policy manager that doesn't actually expire anything. It is useful in multilevel and/or network-based caches.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
void
expire(Cache.Storage.Base
storage
)
This is an expire function that does nothing.
inherit Cache.Policy.Base : Base
An LRU, size-constrained expiration policy manager.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Policy.Sized Cache.Policy.Sized(
int
max
, void
|int
min
)
void
expire(Cache.Storage.Base
storage
)
inherit Cache.Policy.Base : Base
An access-time-based expiration policy manager.
inherit Cache.Policy.Base : Base
Base class for cache storage managers.
All Cache.Storage
managers must provide these methods.
void
aget(string
key
, function
(string
, int(0..0)
|Cache.Data
, mixed
... :void
) callback
, mixed
... extra_callback_args
)
Fetch some data from the cache asynchronously.
callback()
will get as first argument key
, and as second
argument 0 (cache miss) or an Cache.Data
object, plus any
additional argument that the user may have supplied.
mixed
delete(string
key
, void
|bool
hard
)
Delete the entry specified by key
from the cache (if present).
If hard
is 1, some backends may force a destruct()
on the deleted value.
Dependants (if present) are automatically deleted.
Returns the deleted entry.
int(0..0)
|string
first()
int(0..0)
|string
next()
These two functions are an iterator over the cache. There is an
internal cursor, which is reset by each call to first()
. Subsequent
calls to next()
will iterate over all the contents of the cache.
These functions are not meant to be exported to the user, but are solely for the policy managers' benefit.
int(0..0)
|Cache.Data
get(string
key
, void
|bool
notouch
)
Fetch some data from the cache synchronously.
Be careful, as with some storage managers it might block the calling thread for some time.
void
set(string
key
, mixed
value
, void
|int
max_life
, void
|float
preciousness
, void
|multiset
(string
) dependants
)
Data-object creation is performed here if necessary, or in get()
depending on the backend.
This allows the storage managers to have their own data class implementation.
A GBM-based storage manager.
This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Storage.Gdbm Cache.Storage.Gdbm(
string
path
)
A GDBM storage-manager must be hooked to a GDBM Database.
inherit Cache.Storage.Base : Base
inherit Cache.Data : Data
A RAM-based storage manager.
This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
int(0..0)
|Cache.Data
get(string
key
, void
|int
notouch
)
Fetches some data from the cache. If notouch is set, don't touch the data from the cache (meant to be used by the storage manager only)
inherit Cache.Storage.Base : Base
inherit Cache.Data : Data
An SQL-based storage manager
This storage manager provides the means to save data to an SQL-based backend.
For now it's mysql only, dialectization will be added at a later time. Serialization should be taken care of by the low-level SQL drivers.
An administrator is supposed to create the database and give the user enough privileges to write to it. It will be care of this driver to create the database tables itself.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Storage.MySQL Cache.Storage.MySQL(
string
sql_url
)
inherit Cache.Storage.Base : Base
Database manipulation is done externally. This class only returns values, with some lazy decoding.
inherit Cache.Data : Data
A Yabu-based storage manager.
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Storage.Yabu Cache.Storage.Yabu(
string
path
)
inherit Cache.Storage.Base : Base
inherit Cache.Data : Data
Time and day system
Q: I need to parse some date in a non-strict format, like
the one in the HTTP or mail protocol, or from a user web
form.
A: Calendar.dwim_day, or Calendar.dwim_time, should solve
your problem.
> Calendar.dwim_day("1/2/3");
Result: Day(Thu 2 Jan 2003)
> Calendar.dwim_day("1 aug 2001");
Result: Day(Wed 1 Aug 2001)
> Calendar.dwim_time("1 aug 2001 23:14 EDT");
Result: Minute(Wed 1 Aug 2001 23:14 EDT)
> Calendar.dwim_time("2001 2 3 23:14:23 UTC+9");
Result: Second(Sat 3 Feb 2001 23:14:23 UTC+9)
If it doesn't, and it should, report the problem to me
and I'll see what I can do. Note that the timezones
are rather unpredictable - if it doesn't get it, you
will get the default (local) timezone.
-------------------------------------------------------------------------
Q: The dwim_* functions are too slow.
A: They are not written to be fast, but to do good guessing.
If you know the format, you should use the Calendar.parse
function:
> Calendar.parse("%Y-%M-%D %h:%m","2040-11-08 2:46");
Result: Minute(Thu 8 Nov 2040 2:46 CET)
> Calendar.parse("%Y w%W %e %h:%m %p %z","1913 w4 monday 2:14 pm CET");
Result: Minute(Mon 20 Jan 1913 14:14 CET)
These are the format characters:
%Y absolute year
%y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069)
%M month (number, name or short name) (needs %y)
%W week (needs %y)
%D date (needs %y, %m)
%d short date (20000304, 000304)
%a day (needs %y)
%e weekday (needs %y, %w)
%h hour (needs %d, %D or %W)
%m minute (needs %h)
%s second (needs %m)
%f fraction of a second (needs %s)
%t short time (205314, 2053)
%z zone
%p "am" or "pm"
%n empty string (to be put at the end of formats)
and you can also use "%*[....]" to skip some characters,
as in sscanf().
If this is too slow, there is currently no solution in Pike
to do this faster, except possibly sscanf and manual calculations/
time object creation.
-------------------------------------------------------------------------
Q: How do I get from unix time (time(2)) to a unit and back?
A: Calendar.Unit("unix",time())
unit->unix_time()
> Calendar.Day("unix",987654321);
Result: Day(Thu 19 Apr 2001)
> Calendar.Second("unix",987654321);
Result: Second(Thu 19 Apr 2001 6:25:21 CEST)
> Calendar.Day()->unix_time();
Result: 979081200
Note that you will get the time for the start of the unit.
Unix time is timezone independant.
The day-of-time units (seconds, hours, etc) uses this
as internal representation of time.
-------------------------------------------------------------------------
Q: I'm a mad astronomer, how do I do the same conversions with
julian day numbers?
A: Julian day numbers are used as the internal representation
for the day, and for most other bigger-then-time-of-day calculations.
> Calendar.Day("julian",2454545);
Result: Day(Wed 19 Mar 2008)
> Calendar.Second("julian",2430122.0);
Result: Second(Tue 6 May 1941 13:00:00 CET)
Julian day numbers from day units and bigger are integers,
representing the new julian number on that day. Julian day
numbers from time of day units are represented in floats.
> Calendar.Day()->julian_day();
Result: 2451920
> Calendar.Second()->julian_day();
Result: 2451919.949595
Watch out for the float precision, though. If you haven't
compiled your Pike with --with-double-precision, this gives
you awkwardly low precision - 6 hours.
-------------------------------------------------------------------------
Q: How do I convert a "Second(Sat 3 Feb 2001 23:14:23 UTC+9)" object
to my timezone?
A: ->set_timezone(your timezone)
> Calendar.dwim_time("2001 2 3 23:14:23 PST")
->set_timezone("Europe/Stockholm");
Result: Second(Sun 4 Feb 2001 8:14:23 CET)
> Calendar.dwim_time("2001 2 3 23:14:23 PST")
->set_timezone("locale");
Result: Second(Sun 4 Feb 2001 8:14:23 CET)
-------------------------------------------------------------------------
Q: How do I print my time object?
A: ->format_xxx();
You can either print it unit-sensitive,
> Calendar.dwim_time("2001 2 3 23:14:23 PST")->format_nice();
Result: "3 Feb 2001 23:14:23"
> Calendar.Week()->format_nice();
Result: "w2 2001"
> Calendar.now()->format_nicez();
Result: "10 Jan 10:51:15.489603 CET"
or in a format not depending on the unit,
> Calendar.Week()->format_ymd();
Result: "2001-01-08"
> Calendar.Day()->format_time();
Result: "2001-01-10 00:00:00"
This is all the formats:
format_ext_time "Wednesday, 10 January 2001 10:49:57"
format_ext_time_short "Wed, 10 Jan 2001 10:49:57 CET"
format_ext_ymd "Wednesday, 10 January 2001"
format_iso_time "2001-01-10 (Jan) -W02-3 (Wed) 10:49:57 UTC+1"
format_iso_ymd "2001-01-10 (Jan) -W02-3 (Wed)"
format_mod "10:49"
format_month "2001-01"
format_month_short "200101"
format_mtime "2001-01-10 10:49"
format_time "2001-01-10 10:49:57"
format_time_short "20010110 10:49:57"
format_time_xshort "010110 10:49:57"
format_tod "10:49:57"
format_tod_short "104957"
format_todz "10:49:57 CET"
format_todz_iso "10:49:57 UTC+1"
format_week "2001-w2"
format_week_short "2001w2"
format_iso_week "2001-W02"
format_iso_week_short "200102"
format_xtime "2001-01-10 10:49:57.539198"
format_xtod "10:49:57.539658"
format_ymd "2001-01-10"
format_ymd_short "20010110"
format_ymd_xshort "010110"
format_ctime "Wed Jan 10 10:49:57 2001\n"
format_smtp "Wed, 10 Jan 2001 10:49:57 +0100"
format_http "Wed, 10 Jan 2001 09:49:57 GMT"
-------------------------------------------------------------------------
Q: How old am I?
A: First, you need to create the time period representing your age.
> object t=Calendar.dwim_time("1638 dec 23 7:02 pm")
->distance(Calendar.now());
Result: Fraction(Thu 23 Dec 1638 19:02:00.000000 LMT -
Wed 10 Jan 2001 10:53:33.032856 CET)
Now, you can ask for instance how many years this is:
> t->how_many(Calendar.Year);
Result: 362
Or how many 17 seconds it is:
> t->how_many(Calendar.Second()*17);
Result: 672068344
A note here is to use ->distance, and not ->range, since that
will include the destination unit too:
> Calendar.dwim_day("00-01-02")->range(Calendar.Week(2000,2))
->how_many(Calendar.Day());
Result: 15
> Calendar.dwim_day("00-01-02")->distance(Calendar.Week(2000,2))
->how_many(Calendar.Day());
Result: 8
-------------------------------------------------------------------------
Q: In 983112378 days, what weekday will it be?
A: (this weekday + 983112378) % 7 ;)
or take this day, add the number, and ask the object:
> (Calendar.Day()+983112378)->week_day_name();
Result: "Saturday"
"+int" will add this number of the unit to the unit;
this means that Calendar.Year()+2 will move two years
forward, but Calendar.now()+2 will not move at all
- since now has zero size.
To add a number of another time unit, simply do that:
> Calendar.Day()+3*Calendar.Year();
Result: Day(Sat 10 Jan 2004)
> Calendar.Day()+3*Calendar.Minute()*134;
Result: Minute(Wed 10 Jan 2001 6:42 CET - Thu 11 Jan 2001 6:42 CET)
The last result here is because the resulting time still will
be as long as the first.
-------------------------------------------------------------------------
Q: Are there other calendars?
A: Yes.
Calendar.Day is really a shortcut to Calendar.ISO.Day;
this is tuned in the localization.h file.
There is currently:
Gregorian
This is the base module for Julian style calendars;
despite the name. Most calendars of today are in sync
with the Gregorian calendar.
ISO
This inherits the Gregorian calendar to tweak it to
conform to the ISO standards. Most affected are weeks,
which starts on Monday in the ISO calendar.
This is also the default calendar.
Discordian
The Discordian calendar as described in Principia Discordia
is in sync with the Gregorian calendar (although some claim
that it should be the Julian - I go with what I can read
from my Principia Discordia). The module inherits and
tweaks the Gregorian module.
Coptic
The Coptic calendar is by some sources ("St. Marks'
Coptic Orthodox Church" web pages) is for now on in sync with
the Gregorian Calendar, so this module too inherits
and tweaks the Gregorian module. It needs to be
adjusted for historical use.
Julian
This is the Julian calendar, with the small changes
to the Gregorian calendar (leap years).
Badi (Baha'i)
The Badi calendar used by the Baha'i religion is based on the
solar year. For the time being it is in sync with the Gregorian
calendar.
Islamic
This is the Islamic calendar, using the 'Calendrical
Calculations' rules for new moon. It is based
directly on the YMD module.
Stardate
This is the (TNG) Stardate calendar, which consists
of one time unit only, the Tick (1000 Tick is one earth year).
It is based directly on TimeRanges.
-------------------------------------------------------------------------
Q: How do I convert between the calendars?
A: You give the unit to be converted to the constructor of
the unit you want it to be.
> Calendar.Coptic.Day(Calendar.dwim_day("14 feb 1983"));
Result: Day(Mon 7 Ams 1699)
> Calendar.Islamic.Minute(Calendar.dwim_day("14 feb 1983"));
Result: Minute(aha 29 Rebîul-âchir 1403 AH 13:00 CET -
ith 1 Djumâda'l-ûla 1403 AH 13:00 CET)
> Calendar.Day(Calendar.Stardate.Tick(4711));
Result: Day(Sat 17 Sep 2327 0:00 sharp)
-------------------------------------------------------------------------
Q: Isn't there a <my country> calendar?
A: <your country> uses the ISO calendar, with just different
names for the months. Language is a parameter to the
calendar units, as well as the timezone.
You set the language by using ->set_language(yourlanguage).
> t->set_language("pt")->format_ext_ymd();
Result: "Quarta-feira, 10 Janeiro 2001"
> t->set_language("roman")->format_ext_ymd();
Result: "Mercurii dies, X Ianuarius MMDCCLIII ab urbe condita"
Note that all languages aren't supported. If you miss your
favourite language or I got it all wrong (or have some time over
to help me out), look in the Language.pmod file and send me an
update.
Or send me a list of the weekdays and month names
(please start with Monday and January).
Currently, these languages are supported:
name code
-------------------------------
ISO (default, aka English)
Afrikaans af afr (South Africa),
Austrian de_AT
Basque eu eus (Spain)
Catalan ca cat (Catalonia)
Croatian hr hrv
Danish da dan
Dutch nl nld
English en eng
Estonian et est
Faroese fo fao
Finnish fi fin
French fr fra
Galician gl glg (Spain)
German de deu
Greenlandic kl kal
Hungarian hu hun
Icelandic is isl
Irish ga gle (Gaelic)
Italian it ita
Latvian lv lav
Lithuanian lt lit
Norwegian no nor
Persian fa fas (Iran)
Polish pl pol
Portugese pt por
Romanian ro ron
Serbian sr srp (Yugoslavia)
Slovenian sl slv
Spanish es spa
Swedish sv swe
Turkish tr
Welsh cy cym
Latin la lat
Roman (Roman Latin)
-------------------------------------------------------------------------
Q: Isn't there a <whatever> calendar?
A: Not if it isn't listed above. I'll appreciate any
implementation help if you happen to have the time over
to implement some calendar.
I know I miss these:
Chinese
Jewish or Hebreic
Maya
Of these, the two first are based on astronomical events,
which I haven't had the time to look into yet, but the
last - Maya - is totally numeric.
-------------------------------------------------------------------------
Q: I don't like that weeks starts on Mondays.
Every school kids knows that weeks start on Sundays.
A: According to the ISO 8601 standard, weeks start on mondays.
If you don't like it, edit the Calendar.pmod/localization.h
file to use the Gregorian calendar instead of the ISO.
Or use Calendar.Gregorian.Day, etc.
-------------------------------------------------------------------------
Q: How do I find out which days are red in a specific region?
A: Events.<region>
- contains the events for the region, as a SuperEvent.
You can ask this object to filter out the holidays,
Events.se->holidays();
which will be a superevent containing only holidays.
To use this information, you can for instance use ->scan,
here in an example to see what red days there are in Sweden
the current month:
> Calendar.Events.se->filter_flag("h")->scan(Calendar.Month());
Result: ({ /* 6 elements */
Day(Sun 7 Jan 2001),
Day(Sun 14 Jan 2001),
Day(Sun 21 Jan 2001),
Day(Sun 28 Jan 2001),
Day(Sat 6 Jan 2001),
Day(Mon 1 Jan 2001)
})
-------------------------------------------------------------------------
Q: How accurate are the events information?
A: For some regions, very. For most region, not very.
The first reason is lack of information of this kind on
the web, especially sorted into useful rules (like "the
third monday after 23 dec", not "8 jan").
The second reason is lack of time and interest to do
research, which is a rather tedious job.
If you want to help, the check your region in the
events/regions file and send us <pike@roxen.com> a patch.
Don't send me "the x region is all wrong!" mails without
telling me how it should look.
-------------------------------------------------------------------------
Q: My timezone says it's DST. It's wrong.
A: No it isn't. But:
o The local timezone detector failed to find your timezone by
itself, or found the wrong timezone.
o or you use the wrong timezone.
To make sure the right timezone is used, use the standard
timezone names. Those aren't "CET" or "PST", but
"Europe/Amsterdam" or "America/Dawson".
You can tune the default timezone by editing
Calendar.pmod/localization.h.
OR this may be in the future and you have a changed DST
rule and uses an old Pike. Then you can either download
a new version or download new timezone data files from
the ftp address below (if the internet still is there).
This needs to be reformatted as documentation.
constant
Calendar.nulltimerange
= TimeRange
This represents the null time range,
which, to differ from the zero time range
(the zero-length time range), isn't placed
in time. This is the result of for instance
`&
between two strict non-overlapping
timeranges - no time at all.
It has a constant, is_nulltimerange, which is non-zero. `! on this timerange is true.
This is the base class of the calendars.
Calendar.TimeRanges.TimeRange
now()
Give the zero-length time period of the current time.
This is the container class for rules.
bool
res = Calendar.Ruleset()
== other
this_program
clone()
this_program
set_abbr2zone(mapping
(string
:string
) abbr2zone
)
Sets the guess-mapping for timezones. Default is the mapping:
Abbreviation | Interpretation | UTC |
AMT | America/Manaus | UTC-4 |
AST | America/Curacao | UTC-4 |
CDT | America/Costa_Rica | UTC-5 |
CST | America/El Salvador | UTC-6 |
EST | America/Panama | UTC-5 |
GST | Asia/Dubai | UTC+4 |
IST | Asia/Jerusalem | UTC+2 |
WST | Australia/Perth | UTC+8 |
YMD.parse
this_program
set_language(string
|Calendar.Rule.Language
lang
)
this_program
set_rule(Calendar.Rule.Language
|Calendar.Rule.Timezone
rule
)
this_program
set_timezone(string
|Calendar.Rule.Timezone
t
)
This class handles the cases where you have a time period with holes. These can be created by the ^ or | operators on time ranges.
Calendar.SuperTimeRange Calendar.SuperTimeRange(
array
(TimeRange
) parts
)
A SuperTimeRange must have at least two parts, two time ranges. Otherwise, it's either not a time period at all or a normal time period.
inherit TimeRange : TimeRange
Same as the ISO
calendar,
but with austrian as the default language.
This calendar exist only for backwards compatible purposes.
inherit Calendar.ISO : ISO
This is the Badi calendar, used in the Baha'i religion.
int
daystart_offset()
Returns the offset to the start of the time range object
inherit Calendar.YMD : YMD
inherit YMD : YMD
Year
year()
Year
year(int
n
)
Year
year(string
name
)
Return a year in the vahid by number or name:
vahid->year("Alif")
This is the Coptic Orthodox Church calendar, that starts the 11th or 12th September and has 13 months.
The (default) names of the months are different then other the emacs calendar; I do not know which ones are used - the difference seem to be only the transcription of the phonetic sounds (B <-> P, etc).
I do not know for how long back the calendar is valid,
either. My sources claim that the calendar is synchronized
with the Gregorian
calendar, which is odd.
inherit Calendar.Gregorian : Gregorian
The Discordian calendar, as described on page 34 in the fourth edition of Principia Discordia.
Chaotic enough, it's quite simpler then the Gregorian
calendar;
weeks are 5 days, and evens up on a year. Months are 73 days.
The leap day is inserted at the 60th day of the first month (Chaos), giving the first month 74 days. The description of the calendar is a "perpetual date converter from the gregorian to the POEE calendar", so the leap years are the same as the gregorians.
The Principia calls months "seasons", but for simplicity I call them months in this calendar.
If anyone know more about how to treat the leap day - now it is inserted in the month and week where it lands, rather then being separated from month and weeks, I'm interested to know.
- Mirar, Pope of POEE.
inherit Calendar.Gregorian : Gregorian
This class represents the event of a given gregorian date. For instance, Event.Date(12,10)->next(Day()) finds the next 12 of October.
Calendar.Event.Date Calendar.Event.Date(
int(1..31)
month_day
, int(1..12)
month
)
The event is created by a given month day and a month number (1=January, 12=December).
inherit Day_Event : Day_Event
This class represents the event that a given gregorian date appears a given weekday. For instance, Event.Date_Weekday(12,10,5)->next(Day()) finds the next 12 of October that is a friday.
Calendar.Event.Date_Weekday Calendar.Event.Date_Weekday(
int
month_day
, int
month
, int
weekday
)
The event is created by a given month day, a month number (1=January, 12=December), and a weekday number (1=Monday, 7=Sunday).
The week day numbers used are the same as the day of week in
the ISO
calendar - the Gregorian
calendar has 1=Sunday,
7=Saturday.
inherit Day_Event : Day_Event
Day_Event
is an abstract class, extending Event
for events
that are single days, using julian day numbers for the calculations.
constant
int
Calendar.Event.Day_Event.NODAY
Returned from scan_jd
if the even searched for did not
exist.
inherit Event : Event
constant
int
Calendar.Event.Day_Event.is_day_event
This constant may be used to identify Day_Event
objects.
Calendar.TimeRanges.TimeRange
next(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Uses the virtual method scan_jd
.
Event.next
Calendar.TimeRanges.TimeRange
previous(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Uses the virtual method scan_jd
.
Event.previous
int
scan_jd(Calendar.Calendar
realm
, int
jd
, int(-1..-1)
|int(1..1)
direction
)
This method has to be defined, and is what really does some work.
direction
| Forward (next), |
| Backward (previous). |
It should return the next or previous
julian day (>jd) when the event occurs,
or the constant NODAY
if it doesn't.
This class represents an easter.
Calendar.Event.Easter Calendar.Event.Easter(
void
|int
shift
)
shift
is the year to shift from old to new style easter
calculation. Default is 1582.
int
easter_yd(int
y
, int
yjd
, int
leap
)
Calculates the year day for the easter.
inherit Day_Event : Day_Event
This class represents an easter relative event.
Calendar.Event.Easter_Relative Calendar.Event.Easter_Relative(
string
id
, string
name
, int
offset
)
inherit Easter : Easter
Event is an abstract class, defining what methods an Event need to have.
SuperEvent
res = Calendar.Event.Event()
| with
SuperEvent
res = with
| Calendar.Event.Event()
Joins several events into one SuperEvent
.
string
describe()
Returns a description of the event.
constant
int
Calendar.Event.Event.is_event
This constant may be used to identify an event object.
Calendar.TimeRanges.TimeRange
next(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Calendar.TimeRanges.TimeRange
previous(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
This calculates the next or previous occurance of the event, from the given timerange's start, including any event occuring at the start if that flag is set.
It returns zero if there is no next event.
These methods are virtual in the base class.
array
(Calendar.TimeRanges.TimeRange
) scan(Calendar.TimeRanges.TimeRange
in
)
This calculates the eventual events that is contained or
overlapped by the given timerange. scan
uses next
, if not
overloaded.
Calendar.Event.Easter()->scan(Calendar.Year(2000)) => ({ Day(Sun 23 Apr 2000) })
scan
can return an array of overlapping timeranges.
This method must use in->calendar_object->type to create the returned timeranges, and must keep the ruleset.
mapping
(Calendar.TimeRanges.TimeRange
:Event
) scan_events(Calendar.TimeRanges.TimeRange
in
)
Returns a mapping with time ranges mapped to events.
A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.
Julian_Fixed
Calendar.Event.Gregorian_Fixed Calendar.Event.Gregorian_Fixed(
string
id
, string
name
, int(1..31)
month_day
, int(1..12)
month
, int
extra
)
inherit Day_Event : Day_Event
constant
int
Calendar.Event.Gregorian_Fixed.is_fixed
This constant may be used to identify Gregorian_Fixed
objects.
A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.
Gregorian_Fixed
inherit Gregorian_Fixed : Gregorian_Fixed
constant
int
Calendar.Event.Julian_Fixed.is_julian_fixed
This constant may be used to identify Julian_Fixed
objects.
This class represents the event that a given gregorian day of month appears a given weekday. For instance, Event.Monthday_Weekday(13,5)->next(Day()) finds the next friday the 13th.
Calendar.Event.Monthday_Weekday Calendar.Event.Monthday_Weekday(
int
month_day
, int
weekday
)
The event is created by a given month day, and a weekday number (1=Monday, 7=Sunday).
The week day numbers used are the same as the day of week in
the ISO
calendar - the Gregorian
calendar has 1=Sunday,
7=Saturday.
inherit Day_Event : Day_Event
This class represents a monthday weekday relative event or n:th special weekday event, e.g. "fourth sunday before 24 dec" => md=24,mn=12,wd=7,n=-4
Calendar.Event.Monthday_Weekday_Relative Calendar.Event.Monthday_Weekday_Relative(
string
id
, string
name
, int(1..31)
md
, int(1..12)
mn
, int(1..7)
_wd
, int
_n
, void
|bool
_inclusive
)
inherit Gregorian_Fixed : Gregorian_Fixed
This is created by the Namedays
classes
to represent an event for a name.
inherit Day_Event : Day_Event
constant
int
Calendar.Event.Nameday.is_nameday
This constant may be used to identify Nameday
objects.
This contains a ruleset about namedays.
inherit Event : Event
constant
int
Calendar.Event.Namedays.is_namedays
This constant may be used to identify Namedays
.
mapping
(Calendar.TimeRanges.TimeRange
:array
(string
)) namedays(Calendar.TimeRanges.TimeRange
t
)
Gives back an table of days with names that occur during the time period. Note that days without names will not appear in the returned mapping.
array
(string
) names(Calendar.TimeRanges.TimeRange
t
)
Gives back an array of names that occur during the time period, in no particular order.
A non-event.
inherit Event : Event
constant
int
Calendar.Event.NullEvent.is_nullevent
This constant may be used to identify a NullEvent.
This class represents an orthodox easter relative event.
Calendar.Event.Orthodox_Easter_Relative Calendar.Event.Orthodox_Easter_Relative(
string
id
, string
name
, int
offset
)
inherit Easter_Relative : Easter_Relative
This class represents a solar event as observed from Earth.
The event_type
is one of
| Northern hemisphere spring equinox. |
| Northern hemisphere summer solstice. |
| Northern hemisphere autumn equinox. |
| Northern hemisphere winter solstice. |
Calendar.Event.Solar Calendar.Event.Solar(
int
|void
event_type
)
int
|void
Calendar.Event.Solar.event_type
inherit Day_Event : Day_Event
Calendar.Event.Solar.protected
constantperiodic_table
Array | |||||||||
|
|
Calendar.TimeRanges.TimeRange
previous(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Uses the virtual method scan_jd
.
Event.previous
int
scan_jd(Calendar.Calendar
realm
, int
jd
, int(1..1)
|int(-1..-1)
direction
)
Returns unixtime in UTC to avoid losing the decimals!
array
(int
|float
) solar_event(int
y
)
Calculate the next event.
Based on Meeus Astronomical Algorithms Chapter 27.
This class holds any number of events, and adds the functionality of event flags.
Scanning (scan_events,next,etc) will drop flag information.
Dig out what you need with holidays
et al first.
SuperEvent
filter_flag(string
flag
)
SuperEvent
holidays()
SuperEvent
flagdays()
Filter out the events that has a certain flag set. Holidays (flag "h") are the days that are marked red in the calendar (non-working days), Flagdays (flag "f") are the days that the flag should be visible in (only some countries).
inherit Event : Event
Container for merged Namedays
objects. Presumes non-overlapping
namedays
Calendar.Event.SuperNamedays Calendar.Event.SuperNamedays(
array
(Nameday
) namedayss
, string
id
)
array
(Nameday
) Calendar.Event.SuperNamedays.namedayss
string
Calendar.Event.SuperNamedays.id
inherit Event : Event
Event containing information about when a timezone is changed.
inherit Event : Event
protected
Calendar.TimeRanges.TimeRange
scan_history(Calendar.Rule.Timezone
tz
, Calendar.TimeRanges.TimeRange
from
, int
direction
, bool
including
)
protected
Calendar.TimeRanges.TimeRange
scan_rule(Calendar.Rule.Timezone
tz
, Calendar.TimeRanges.TimeRange
from
, int
direction
, int
including
)
protected
Calendar.TimeRanges.TimeRange
scan_shift(Calendar.Rule.Timezone
tz
, Calendar.TimeRanges.TimeRange
from
, int
direction
, int
including
)
This class represents any given weekday. For instance, Event.Weekday(5)->next(Day()) finds the next friday.
These are also available as the pre-defined events Events.monday
,
Events.tuesday
, Events.wednesday
, Events.thursday
,
Events.friday
, Events.saturday
and Events.sunday
.
Calendar.Event.Weekday Calendar.Event.Weekday(
int
weekday
, void
|string
id
)
The event is created by a given weekday number (1=Monday, 7=Sunday).
The week day numbers used are the same as the day of week in
the ISO
calendar - the Gregorian
calendar has 1=Sunday,
7=Saturday.
inherit Day_Event : Day_Event
The Event system
Q: How do I find out which days are red in a specific region?
A: Events.<region>
- contains the events for the region, as a SuperEvent. You can ask this object to filter out the holidays,
Events.se.holidays();
Which will be a superevent containing only holidays.
To use this information, you can for instance use ->scan, here in an example to see what red days there were in Sweden in 2001
> Calendar.Events.se->filter_flag("h")->scan(Calendar.Month());
Result: ({ /* 6 elements */
Day(Sun 7 Jan 2001),
Day(Sun 14 Jan 2001),
Day(Sun 21 Jan 2001),
Day(Sun 28 Jan 2001),
Day(Sat 6 Jan 2001),
Day(Mon 1 Jan 2001)
Event.Event
`[](string
region
)
Event.Event
`->(string
region
)
return the Event object for the specified region or the specified named event.
This is the standard conservative christian calendar,
used regularly in some countries - USA, for instance - and
which derivate - the ISO
calendar - is used in most of
Europe.
inherit Calendar.YMD : YMD
This is the standard western calendar, which is a derivate of the Gregorian calendar, but with weeks that starts on Monday instead of Sunday.
inherit Calendar.Gregorian : Gregorian
This is the islamic calendar. Due to some sources, they decide the first day of the new months on a month-to-month basis (sightings of the new moon), so it's probably not that accurate. If someone can confirm (or deny) accuracy better than that, please contact me so I can change this statement.
It's vaugely based on rules presented in algorithms by Dershowitz, Reingold and Clamen, 'Calendrical Calculations'. It is the same that's used in Emacs calendar mode.
I have currently no idea how the arabic countries
count the week. Follow the same rules as ISO
for now... The time is also suspicious; the day
really starts at sunset and not midnight,
the hours of the day is not correct. Also don't know
what to call years before 1 - go for "BH"; positive
years are "AH", anno Hegirac.
inherit Calendar.YMD : YMD
This is the Julian calendar, conjured up by the old Romans when their calendar were just too weird. It was used by the christians as so far as the 18th century in some parts of the world. (Especially the protestantic and orthodox parts.)
Don't confuse the julian day with the Julian calendar. The former is just a linear numbering of days, used in the Calendar module as a common unit for absolute time.
inherit Calendar.Gregorian : Gregorian
Contains a time zone.
Calendar.Rule.Timezone Calendar.Rule.Timezone(
int
offset
, string
name
)
offset
Offset to UTC, not counting DST.
name
The name of the time zone.
int
raw_utc_offset()
Returns the offset to UTC, not counting DST.
array
tz_jd(int
julian_day
)
This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.
array
tz_ux(int
unixtime
)
This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.
This implements TNG stardates.
cTick
now()
Give the zero-length time period of the current time.
Calendar.Stardate.cTick Calendar.Stardate.cTick(
mixed
... args
)
Calendar.Stardate.cTick Calendar.Stardate.cTick(
int
|float
date
)
Calendar.Stardate.cTick Calendar.Stardate.cTick()
Apart from the standard creation methods (julian day, etc), you can create a stardate from the stardate number. The length of the period will then be zero.
You can also omit any arguments to create now.
Since the precision is limited to the float type of Pike you can get non-precise results:
> Calendar.Second(Calendar.Stardate.Day(Calendar.Year()));
Result: Second(Fri 31 Dec 1999 23:59:18 CET - Sun 31 Dec 2000 23:59:18 CET)
string
format_long(void
|int
precision
)
string
format_short(void
|int
precision
)
string
format_vshort(void
|int
precision
)
Format the stardate tick nicely. Precision is the number of decimals. Defaults to 3.
long | "-322537.312" | |
short | "77463.312" | (w/o >100000-component) |
vshort | "7463.312" | (w/o >10000-component) |
inherit Calendar.TimeRange : TimeRange
int
number_of_days()
This gives back the Gregorian/Earth/ISO number of days, for convinience and conversion to other calendars.
int
number_of_seconds()
This gives back the Gregorian/Earth/ISO number of seconds, for convinience and conversion to other calendars.
float
tic()
This gives back the start of the stardate period, as a float.
float
tics()
This gives back the number of stardate tics in the period.
Same as the ISO
calendar, but with Swedish as the default language.
This calendar exist only for backwards compatible purposes.
inherit Calendar.ISO : ISO
This module contains listnings of available timezones, in some different ways
string
_zone_tab()
array
(array
) zone_tab()
This returns the raw respectively parsed zone tab file from the timezone data files.
The parsed format is an array of zone tab line arrays,
({ string country_code, string position, string zone_name, string comment })
To convert the position to a Geography.Position, simply feed it to the constructor.
constant
Calendar.TZnames.abbr2zones
= mapping
(string
:array
(string
))
This mapping is used to look up abbreviation to the possible regional zones.
It looks like this:
([ "CET": ({ "Europe/Stockholm", <i>[...]</i> }), "CST": ({ "America/Chicago", "Australia/Adelaide", <i>[...]</i> }), <i>[...]</i> }),
Note this: Just because it's noted "CST" doesn't mean it's a unique timezone. There is about 7 *different* timezones that uses "CST" as abbreviation; not at the same time, though, so the DWIM routines checks this before it's satisfied. Same with some other timezones.
For most timezones, there is a number of region timezones that for the given time are equal. This is because region timezones include rules about local summer time shifts and possible historic shifts.
The YMD.parse
functions can handle timezone abbreviations
by guessing.
array
(string
) zonenames()
This reads the zone.tab file and returns name of all standard timezones, like "Europe/Belgrade".
constant
Calendar.TZnames.zones
= mapping
(string
:array
(string
))
This constant is a mapping that can be used to loop over to get all the region-based timezones.
It looks like this:
([ "America": ({ "Los_Angeles", "Chicago", <i>[...]</i> }), "Europe": ({ "Stockholm", <i>[...]</i> }), <i>[...]</i> }),
Please note that loading all the timezones can take some time, since they are generated and compiled on the fly.
Base for time of day in calendars, ie calendars with hours, minutes, seconds
This module can't be used by itself, but
is inherited by other modules (ISO
by YMD
,
for instance).
inherit TimeRanges : TimeRanges
A Fraction is a part of a second, and/or a time period with higher resolution then a second.
It contains everything that is possible to do with a
Second
, and also some methods of grabbing
the time period with higher resolution.
Internally, the fraction time period is measured in nanoseconds. A shorter or more precise time period then in nanoseconds is not possible within the current Fraction class.
Calendar.Time.Fraction Calendar.Time.Fraction()
Calendar.Time.Fraction Calendar.Time.Fraction(
"unix"
, int
|float
unixtime
)
Calendar.Time.Fraction Calendar.Time.Fraction(
"unix"
, int
|float
unixtime
, int
|float
len
)
Calendar.Time.Fraction Calendar.Time.Fraction(
int
y
, int
m
, int
d
, int
h
, int
m
, int
s
, int
ns
)
It is possible to create a Fraction in three ways, either "now" with no arguments or from a unix time (as from time(2)), or the convenience way from ymd-hms integers.
If created from unix time, both the start of the period and the size of the period can be given in floats, both representing seconds. Note that the default float precision in pike is rather low (same as 'float' in C, the 32 bit floating point precision, normally about 7 digits), so beware that the resolution might bite you. (Internally in a Fraction, the representation is an integer.)
If created without explicit length, the fraction will always be of zero length.
inherit Second : Second
TimeofDay
now()
Give the zero-length time period of the current time.
Calendar
set_ruleset(Ruleset
r
)
Ruleset
ruleset()
Set or read the ruleset for the calendar.
set_ruleset
returns a new calendar object,
but with the new ruleset.
Calendar
set_timezone(Timezone
tz
)
Calendar
set_timezone(string
|Timezone
tz
)
TimeZone
timezone()
Set or get the current timezone (including dst) rule.
set_timezone
returns a new calendar object,
as the called calendar but with another set of rules.
Example:
> Calendar.now(); Result: Fraction(Fri 2 Jun 2000 18:03:22.010300 CET) > Calendar.set_timezone(Calendar.Timezone.UTC)->now(); Result: Fraction(Fri 2 Jun 2000 16:03:02.323912 UTC)
inherit TimeofDay : TimeofDay
inherit TimeofDay : TimeofDay
inherit TimeofDay : TimeofDay
Second
second()
Second
second(int
n
)
array
(Second
) seconds()
array
(Second
) seconds(int
first
, int
last
)
int
number_of_seconds()
Minute
minute()
Minute
minute(int
n
)
array
(Minute
) minutes()
array
(Minute
) minutes(int
first
, int
last
)
int
number_of_minutes()
Hour
hour()
Hour
hour(int
n
)
array
(Hour
) hours()
array
(Hour
) hours(int
first
, int
last
)
int
number_of_hours()
Similar to TimeofDay
, the Time::SuperTimeRange
has a number of methods for digging out time parts of the
range. Since a SuperTimeRange
is a bit more
complex - the major reason for its existance it that it
contains holes, this calculation is a bit more advanced too.
If a range contains the seconds, say, 1..2 and 4..5, the third second (number 2, since we start from 0) in the range would be number 4, like this:
no means this second 0 1 1 2 2 4 <- second three is missing, 3 5 as we don't have it in the example range
number_of_seconds
() will in this example
therefore also report 4, not 5, even if the time from
start of the range to the end of the range is 5 seconds.
inherit TimeRanges.SuperTimeRange : SuperTimeRange
Virtual class used by e.g. Hour.
void
call_out(function
(:void
) fun
, mixed
...args
)
Creates a call_out to this point in time.
Calendar.Time.TimeofDay Calendar.Time.TimeofDay()
Calendar.Time.TimeofDay Calendar.Time.TimeofDay(
int
unixtime
)
In addition to the wide range of construction arguments
for a normal TimeRange (see TimeRange.create
),
a time of day can also be constructed with unixtime
as single argument consisting of the unix time
- as returned from time(2) - of the time unit start.
It can also be constructed without argument, which then means "now", as in "this minute".
mapping
datetime()
This gives back a mapping with the relevant time information (representing the start of the period);
([ "year": int // year number (2000 AD=2000, 1 BC==0) "month": int(1..) // month of year "day": int(1..) // day of month "yearday": int(1..) // day of year "week": int(1..) // week of year "week_day": int(1..) // day of week (depending on calendar) "hour": int(0..) // hour of day, including dst "minute": int(0..59) // minute of hour "second": int(0..59) // second of minute "fraction": float // fraction of second "timezone": int // offset to utc, including dst "unix": int // unix time "julian": float // julian day ]);
string
format_iso_ymd()
string
format_ymd()
string
format_ymd_short()
string
format_ymd_xshort()
string
format_iso_week()
string
format_iso_week_short()
string
format_week()
string
format_week_short()
string
format_month()
string
format_month_short()
string
format_iso_time()
string
format_time()
string
format_time_short()
string
format_iso_short()
string
format_time_xshort()
string
format_mtime()
string
format_xtime()
string
format_tod()
string
format_xtod()
string
format_mod()
string
format_nice()
string
format_nicez()
Format the object into nice strings;
iso_ymd "2000-06-02 (Jun) -W22-5 (Fri)" [2] ext_ymd "Friday, 2 June 2000" [2] ymd "2000-06-02" ymd_short "20000602" ymd_xshort "000602" [1] iso_week "2000-W22" iso_week_short "2000W22" week "2000-w22" [2] week_short "2000w22" [2] month "2000-06" month_short "200006" [1] iso_time "2000-06-02 (Jun) -W22-5 (Fri) 20:53:14 UTC+1" [2] ext_time "Friday, 2 June 2000, 20:53:14" [2] ctime "Fri Jun 4 20:53:14 2000\n" [2] [3] http "Fri, 02 Jun 2000 19:53:14 GMT" [4] time "2000-06-02 20:53:14" time_short "20000602 20:53:14" time_xshort "000602 20:53:14" iso_short "20000602T20:53:14" mtime "2000-06-02 20:53" xtime "2000-06-02 20:53:14.000000" todz "20:53:14 CET" todz_iso "20:53:14 UTC+1" tod "20:53:14" tod_short "205314" xtod "20:53:14.000000" mod "20:53" nice "2 Jun 20:53", "2 Jun 2000 20:53:14" [2][5] nicez "2 Jun 20:53 CET" [2][5] smtp "Fri, 2 Jun 2000 20:53:14 +0100" [6] commonlog "02/Jun/2000:20:53:14 +0100" [2][1] note conflict (think 1 February 2003)
int
hour_no()
int
minute_no()
int
second_no()
float
fraction_no()
This gives back the number of the time unit, on this day. Fraction is a float number, 0<=fraction<1.
Hour
hour()
Hour
hour(int
n
)
array
(Hour
) hours()
array
(Hour
) hours(int
first
, int
last
)
int
number_of_hours()
hour
() gives back the timerange representing the
first or nth Hour of the called object.
Note that hours normally starts to count at zero,
so ->hour(2) gives the third hour within
the range.
An Hour is in the Calendar perspective as any other time range not only 60 minutes, but also one of the (normally) 24 hours of the day, precisely.
hours
() give back an array of all the hours
containing the time periods called. With arguments,
it will give back a range of those hours, in the
same enumeration as the n to hour
().
number_of_hours
() simple counts the
number of hours containing the called time period.
Note: The called object doesn't have to *fill* all the hours it will send back, it's enough if it exist in those hours:
> object h=Calendar.Time.Hour(); Result: Hour(265567) > h->hours(); Result: ({ /* 1 element */ Hour(265567) }) > h+=Calendar.Time.Minute(); Result: Minute(265567:01+60m) > h->hours(); Result: ({ /* 2 elements */ Hour(265567), Hour(265568) })
inherit TimeRange : TimeRange
float
julian_day()
This calculates the corresponding julian day, from the time range. Note that the calculated day is the beginning of the period, and is a float - julian day standard says .00 is midday, 12:00 pm.
Normal pike (ie, 32 bit) floats (without --with-double-precision) has a limit of about 7 digits, and since we are about julian day 2500000, the precision on time of day is very limited.
Minute
minute()
Minute
minute(int
n
)
array
(Minute
) minutes()
array
(Minute
) minutes(int
first
, int
last
)
int
number_of_minutes()
minute
() gives back the timerange representing the
first or nth Minute of the called object.
Note that minutes normally starts to count at zero,
so ->minute(2) gives the third minute within
the range.
An Minute is in the Calendar perspective as any other
time range not only 60 seconds, but also one
of the (normally) 60 minutes of the Hour
, precisely.
minutes
() give back an array of all the minutes
containing the time periods called. With arguments,
it will give back a range of those minutes, in the
same enumeration as the n to minute
().
number_of_minutes
() simple counts the
number of minutes containing the called time period.
TimeRange
move_seconds(int
seconds
)
TimeRange
move_ns(int
nanoseconds
)
These two methods gives back the time range called moved the specified amount of time, with the length intact.
The motion is relative to the original position in time; 10 seconds ahead of 10:42:32 is 10:42:42, etc.
Second
second()
Second
second(int
n
)
array
(Second
) seconds()
array
(Second
) seconds(int
first
, int
last
)
int
number_of_seconds()
second
() gives back the timerange representing the
first or nth Second of the called object.
Note that seconds normally starts to count at zero,
so ->second(2) gives the third second within
the range.
seconds
() give back an array of all the seconds
containing the time periods called. With arguments,
it will give back a range of those seconds, in the
same enumeration as the n to second
().
number_of_seconds
() simple counts the
number of seconds containing the called time period.
TimeRange
set_size_seconds(int
seconds
)
TimeRange
set_size_ns(int
nanoseconds
)
These two methods allows the time range to be edited by size of specific units.
int
unix_time()
This calculates the corresponding unix time, - as returned from time(2) - from the time range. Note that the calculated unix time is the beginning of the period.
This is the base class (usually implemented by e.g. Calendar subclasses like Calendar.Second) for any time measurement and calendrar information. It defines all the things you can do with a time range or any time period.
A TimeRange doubles as both a fixed period in time, and an amount of time. For instance, a week plus a day moves the week-period one day ahead (unaligning it with the week period, and thereby reducing it to just 7 days), no matter when in time the actual day were.
bool
res = Calendar.TimeRanges.TimeRange()
== compared_to
bool
equal(Calendar.TimeRanges.TimeRange from, TimeRange
compared_to
)
These two overloads the operator `== and the result of the equal function.
a==b is considered true if the two timeranges are of the same type, have the same rules (language, timezone, etc) and are the same timerange.
equal(a,b) are considered
true if a and b are the same timerange, exactly the same
as the equals
method.
The __hash method is also present, to make timeranges possible to use as keys in mappings.
known bugs: _equal is not currently possible to overload, due to weird bugs, so equal uses `== for now.
TimeRange
res = Calendar.TimeRanges.TimeRange()
& with
Gives the cut on the called time period with another time period. The result is zero if the two periods doesn't overlap.
>- the past the future -< |-------called-------| |-------other--------| >----- cut -----<
TimeRange
res = Calendar.TimeRanges.TimeRange()
* n
This changes the amount of time in
the time period. t*17 is
the same as doing t->set_size
(t,17).
TimeRange
res = Calendar.TimeRanges.TimeRange()
+ n
TimeRange
res = Calendar.TimeRanges.TimeRange()
+ offset
TimeRange
res = Calendar.TimeRanges.TimeRange()
- m
TimeRange
res = Calendar.TimeRanges.TimeRange()
- x
This calculates the (promoted) time period
either n step away or with a given offset.
These functions does use add
to really
do the job:
t+n t->add(n) t is a time period t-n t->add(-n) offset is a time period t+offset t->add(1,offset) n is an integer t-offset t->add(-1,offset) n+t t->add(n) n-t illegal offset+t offset->add(1,t) | note this! offset-t offset->add(-1,t) |
Mathematic rules:
x+(t-x) == t x is an integer or a time period (x+t)-x == t t is a time period (t+x)-x == t o-(o-t) == t o is a time period t++ == t+1 t-- == t-1
a-b does not give the distance between the start of a and b.
Use the distance
() function to calculate that.
The integer used to `+, `- and add are the number of steps the motion will be. It does never represent any fixed amount of time, like seconds or days.
array
(TimeRange
) res = Calendar.TimeRanges.TimeRange()
/ n
array
(TimeRange
) split(int
|float
n
, object
void|TimeRangewith
)
This divides the called timerange into n pieces. The returned timerange type is not necessarily of the same type as the called one. If the optional timerange is specified then the resulting timeranges will be multiples of that range (except for the last one).
known bugs:
These are currently not defined for
supertimeranges
.
int
res = Calendar.TimeRanges.TimeRange()
/ with
int
how_many(TimeRange
with
)
This calculates how many instances of the given timerange has passed during the called timerange.
For instance, to figure out your age,
create the timerange of your lifespan, and divide
with the instance of a Year
.
bool
res = Calendar.TimeRanges.TimeRange()
< compared_to
bool
res = Calendar.TimeRanges.TimeRange()
> compared_to
These operators sorts roughty on the periods place in time. The major use might be to get multiset to work, besides sorting events clearly defined in time.
TimeRange
res = Calendar.TimeRanges.TimeRange()
^ with
Gives the exclusive-or on the called time period and another time period, ie the union without the cut. The result is zero if the two periods were the same.
>- the past the future -< |-------called-------| |-------other--------| <----| |----> - exclusive or
TimeRange
res = Calendar.TimeRanges.TimeRange()
| with
Gives the union on the called time period and another time period.
>- the past the future -< |-------called-------| |-------other--------| <----------union---------->
TimeRange
add(int
n
, void
|TimeRange
step
)
calculates the (promoted) time period n steps away; if no step is given, the step's length is of the same length as the called time period.
It is not recommended to loop by adding the increment time period to a shorter period; this can cause faults, if the shorter time period doesn't exist in the incremented period. (Like week 53, day 31 of a month or the leap day of a year.)
Recommended use are like this:
// loop over the 5th of the next 10 months TimeRange month=Month()+1; TimeRange orig_day=month()->day(5); for (int i=0; i<10; i++) { month++; TimeRange day=month->place(orig_day); <i>...use day...</i> }
TimeRange
beginning()
TimeRange
end()
This gives back the zero-sized beginning or end of the called time period.
rule: range(t->beginning(),t->end())==t
Calendar
calendar()
Simply gives back the calendar in use, for instance Calendar.ISO or Calendar.Discordian.
bool
strictly_preceeds(TimeRange
what
)
bool
preceeds(TimeRange
what
)
bool
is_previous_to(TimeRange
what
)
bool
overlaps(TimeRange
what
)
bool
contains(TimeRange
what
)
bool
equals(TimeRange
what
)
bool
is_next_to(TimeRange
what
)
bool
succeeds(TimeRange
what
)
bool
strictly_succeeds(TimeRange
what
)
These methods exists to compare two periods of time on the timeline.
case predicates <-- past future -> |----A----| A strictly preceeds B, |----B----| A preceeds B |----A----| A strictly preceeds B, A preceeds B, |----B----| A is previous to B, A touches B |----A----| A preceeds B, |----B----| A overlaps B, A touches B |-------A-------| A preceeds B, A ends with B |----B----| A overlaps B, A contains B, A touches B, |-------A-------| A preceeds B, A succeeds B, |---B---| A overlaps B, A contains B, A touches B |----A----| A overlaps B, A touches B, A contains B |----B----| A equals B, A starts with B, A ends with B |-------A-------| A succeeds B, A starts with B |----B----| A overlaps B, A contains B, A touches B |----A----| A succeeds B, |----B----| A overlaps B, A touches B |----A----| A strictly succeeds B, A succeeds B |----B----| A is next to B, A touches B |----A----| A strictly succeeds B, |----B----| A succeeds B
These methods only check the range of the first to the
last time in the period;
use of combined time periods (SuperTimeRange
s)
might not give you the result you want.
`&
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
TimeRange
from
)
Create the timerange from another timerange.
This is useful when converting objects from
one calendar to another. Note that the ruleset will be
transferred to the new object, so this method
can't be used to convert between timezones
or languges - use set_timezone
,
set_language
or set_ruleset
to achieve this.
The size of the new object may be inexact; a Month object can't comprehend seconds, for instance.
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
"julian"
, int
|float
julian_day
)
Create the timerange from a julian day, the standardized method of counting days. If the timerange is more then a day, it will at least enclose the day.
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
"unix"
, int
unixtime
)
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
"unix"
, int
unixtime
, int
seconds_len
)
Create the timerange from unix time (as given by time(2)), with eventually the size of the time range in the same unit, seconds.
TimeRange
range(TimeRange
other
)
TimeRange
space(TimeRange
other
)
TimeRange
distance(TimeRange
other
)
Derives different time periods in between the called timerange and the parameter timerange.
>- the past the future -< |--called--| |--other--| >------------ range -----------< >--space--< >----- distance -----<
See also: add, TimeRanges.range, TimeRanges.space, TimeRanges.distance
TimeRange
set_language(Rule.Language
lang
)
TimeRange
set_language(string
lang
)
Language
language()
Set or get the current language rule.
TimeRange
next()
TimeRange
prev()
Next and prev are compatible and convinience functions; a->next() is exactly the same as a+1; a=a->next() is a++.
int
offset_to(TimeRange
x
)
Calculates offset to x; this compares two timeranges and gives the integer offset between the two starting points.
This is true for suitable a and b: a+a->offset_to(b)==b
By suitable means that a and b are of the same type and size. This is obviously true only if a+n has b as a possible result for any n.
TimeRange
place(TimeRange
this
)
TimeRange
place(TimeRange
this
, bool
force
)
This will place the given timerange in this timerange, for instance, day 37 in the year - Year(1934)->place(Day(1948 d37)) => Day(1934 d37).
The rules how to place things in different timeranges can be somewhat 'dwim'.
TimeRange
set_ruleset(Ruleset
r
)
TimeRange
ruleset(Ruleset
r
)
Set or get the current ruleset.
this may include timezone shanges, and change the time of day.
TimeRange
set_size(TimeRange
size
)
TimeRange
set_size(int
n
, TimeRange
size
)
Gives back a new (or the same, if the size matches) timerange with the new size. If n are given, the resulting size will be n amounts of the given size.
A negative size is not permitted; a zero one are.
TimeRange
set_timezone(Timezone
tz
)
TimeRange
set_timezone(string
tz
)
TimeZone
timezone()
Set or get the current timezone (including dst) rule.
The time-of-day may very well change when you change timezone.
To get the time of day for a specified timezone, select the timezone before getting the time of day:
Year(2003)->...->set_timezone(TimeZone.CET)->...->hour(14)->...
TimeRange
subtract(TimeRange
what
)
This subtracts a period of time from another;
>- the past the future -< |-------called-------| |-------other--------| <----> <- called->subtract(other) |-------called-------| |---third---| <----> <---> <- called->subtract(third)
This module contains all the predefined timezones. Index it with whatever timezone you want to use.
Example: Calendar.Calendar my_cal= Calendar.ISO->set_timezone(Calendar.Timezone["Europe/Stockholm"]);
A simpler way of selecting timezones might be
to just give the string to
set_timezone
;
it
indexes by itself:
Calendar.Calendar my_cal= Calendar.ISO->set_timezone("Europe/Stockholm");
Do not confuse this module with Ruleset.Timezone
,
which is the base class of a timezone object.
"CET" and some other standard abbreviations work too, but not all of them (due to more then one country using them).
Do not call set_timezone
too often, but remember the result if possible. It might take
some time to initialize a timezone object.
There are about 504 timezones with 127 different daylight saving rules. Most of them historic.
The timezone information comes from ftp://elsie.nci.nih.gov/pub/ and are not made up from scratch. Timezone bugs may be reported to the timezone mailing list, tz@elsie.nci.nih.gov, preferable with a cc to mirar+pike@mirar.org. /Mirar
TZnames
constant
Calendar.Timezone.locale
= Rule.Timezone
This contains the local timezone, found from various parts of the system, if possible.
constant
Calendar.Timezone.localtime
= Rule.Timezone
This is a special timezone, that uses localtime
()
and tzname
to find out what current offset and timezone string to use.
locale
uses this if there is no other
way of finding a better timezone to use.
This timezone is limited by localtime
and
libc to the range of time_t,
which is a MAXINT on most systems - 13 Dec 1901 20:45:52
to 19 Jan 2038 3:14:07, UTC.
base for all Roman-kind of Calendars, ie, one with years, months, weeks and days
mapping
(string
:int
) datetime(int
|void
unix_time
)
Replacement for localtime; gives back a mapping:
([ "year": int // year number (2000 AD=2000, 1 BC==0) "month": int(1..) // month of year "day": int(1..) // day of month "yearday": int(1..) // day of year "week": int(1..) // week of year "week_day": int(1..) // day of week (depending on calendar) "unix": int // unix time "julian": float // julian day "hour": int(0..) // hour of day, including dst "minute": int(0..59) // minute of hour "second": int(0..59) // second of minute "fraction": float // fraction of second "timezone": int // offset to utc, including dst ]);This is the same as calling
Second
()->datetime
().
string
datetime_name(int
|void
unix_time
)
string
datetime_short_name(int
|void
unix_time
)
Compat functions; same as format_iso
and format_iso_short
.
float
deltat(int
unadjusted_utc
)
Terrestrial Dynamical Time difference from standard time.
An approximation of the difference between TDT and UTC in fractional seconds at the specified time.
The zero point is 1901-06-25T14:23:01 UTC (unix time -2162281019), ie the accumulated number of leap seconds since then is returned.
The function is based on polynomials provided by NASA, and the result may differ from actual for dates after 2004.
Day
dwim_day(string
date
)
Day
dwim_day(string
date
, TimeRange
context
)
Tries a number of different formats on the given date (in order):
<ref>parse</ref> format as in "%y-%M-%D (%M) -W%W-%e (%e)" "2000-03-20 (Mar) -W12-1 (Mon)" "%y-%M-%D" "2000-03-20", "00-03-20" "%M%/%D/%y" "3/20/2000" "%D%*[ /]%M%*[ /-,]%y" "20/3/2000" "20 mar 2000" "20/3 -00" "%e%*[ ]%D%*[ /]%M%*[ /-,]%y" "Mon 20 Mar 2000" "Mon 20/3 2000" "-%y%*[ /]%D%*[ /]%M" "-00 20/3" "-00 20 mar" "-%y%*[ /]%M%*[ /]%D" "-00 3/20" "-00 march 20" "%y%*[ /]%D%*[ /]%M" "00 20 mar" "2000 20/3" "%y%*[ /]%M%*[ /]%D" "2000 march 20" "%D%.%M.%y" "20.3.2000" "%D%*[ -/]%M" "20/3" "20 mar" "20-03" "%M%*[ -/]%D" "3/20" "march 20" "%M-%D-%y" "03-20-2000" "%D-%M-%y" "20-03-2000" "%e%*[- /]%D%*[- /]%M" "mon 20 march" "%e%*[- /]%M%*[- /]%D" "mon/march/20" "%e%*[ -/wv]%W%*[ -/]%y" "mon w12 -00" "1 w12 2000" "%e%*[ -/wv]%W" "mon w12" "%d" "20000320", "000320" "today" "today" "last %e" "last monday" "next %e" "next monday"
Casts exception if it fails to dwim out a day. "dwim" means do-what-i-mean.
Day
dwim_time(string
date_time
)
Day
dwim_time(string
date_time
, object
TimeRangecontext
)
Tries a number of different formats on the given date_time.
Casts exception if it fails to dwim out a time. "dwim" means do-what-i-mean.
string
format_iso(void
|int
unix_time
)
string
format_iso_short(void
|int
unix_time
)
string
format_iso_tod(void
|int
unix_time
)
string
format_day_iso(void
|int
unix_time
)
string
format_day_iso_short(void
|int
unix_time
)
Format the object into nice strings;
iso "2000-06-02 (Jun) -W22-5 (Fri) 11:57:18 CEST" iso_short "2000-06-02 11:57:18" iso_tod "11:57:18"
inherit Time : Time
TimeRange
parse(string
fmt
, string
arg
)
parse a date, create relevant object fmt is in the format "abc%xdef..." where abc and def is matched, and %x is one of those time units:
%Y absolute year %y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069) %M month (number, name or short name) (needs %y) %W week (needs %y) %D date (needs %y, %m) %d short date (20000304, 000304) %a day (needs %y) %e weekday (needs %y, %w) %h hour (needs %d, %D or %W) %m minute (needs %h) %s second (needs %m) %S seconds since the Epoch (only combines with %f) %f fraction of a second (needs %s or %S) %t short time (205314, 2053) %z zone %p "am" or "pm" %n empty string (to be put at the end of formats)
0 if format doesn't match data, or the appropriate time object.
The zone will be a guess if it doesn't state an exact regional timezone (like "Europe/Stockholm") - most zone abbriviations (like "CET") are used by more then one region with it's own daylight saving rules. Also beware that for instance CST can be up to four different zones, central Australia or America being the most common.
Abbreviation Interpretation AMT America/Manaus [UTC-4] AST America/Curacao [UTC-4] CDT America/Costa_Rica [UTC-6] CST America/El Salvador [UTC-6] EST America/Panama [UTC-5] GST Asia/Dubai [UTC+4] IST Asia/Jerusalem [UTC+2] WST Australia/Perth [UTC+8]
This mapping is modifiable in the ruleset, see
Ruleset.set_abbr2zone
.
Calendar.YMD.Day Calendar.YMD.Day(
"unix"
, int
unix_time
)
Calendar.YMD.Day Calendar.YMD.Day(
"julian"
, int
|float
julian_day
)
Calendar.YMD.Day Calendar.YMD.Day(
int
year
, int
month
, int
day
)
Calendar.YMD.Day Calendar.YMD.Day(
int
year
, int
year_day
)
Calendar.YMD.Day Calendar.YMD.Day(
int
julian_day
)
It's possible to create the day by using five different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year, month and day, from year and day of year, and from julian day without extra fuzz.
inherit YMD : YMD
inherit Time.Fraction : Fraction
inherit YMD : YMD
inherit Time.Hour : Hour
inherit YMD : YMD
inherit Time.Minute : Minute
inherit YMD : YMD
inherit YMD : YMD
inherit Time.Second : Second
inherit YMD : YMD
inherit Time.SuperTimeRange : SuperTimeRange
The Calendar week represents a standard time period of a week. In the Gregorian calendar, the standard week starts on a sunday and ends on a saturday; in the ISO calendar, it starts on a monday and ends on a sunday.
The week are might not be aligned to the year, and thus the week may cross year borders and the year of the week might not be the same as the year of all the days in the week. The basic rule is that the week year is the year that has the most days in the week, but since week number only is specified in the ISO calendar - and derivates - the week number of most calendars is the week number of most of the days in the ISO calendar, which modifies this rule for the Gregorian calendar; the week number and year is the same as for the ISO calendar, except for the sundays.
When adding, moving and subtracting months to a week, it falls back to using days.
When adding, moving or subtracting years, if tries to place the moved week in the resulting year.
Calendar.YMD.Week Calendar.YMD.Week(
"unix"
, int
unix_time
)
Calendar.YMD.Week Calendar.YMD.Week(
"julian"
, int
|float
julian_day
)
Calendar.YMD.Week Calendar.YMD.Week(
int
year
, int
week
)
It's possible to create the standard week by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year and week number.
Can be less than 1 for the first week of the year if it begins in the previous year.
Day
day()
Day
day(int
n
)
Day
day(string
name
)
The Week type overloads the day() method, so it is possible to get a specified weekday by string:
week->day("sunday")
The integer and no argument behavior is inherited
from YMD
().
the weekday-from-string routine is language dependent.
inherit YMD : YMD
Base (virtual) time period of the Roman-kind of calendar.
mapping
datetime()
This gives back a mapping with the relevant time information (representing the start of the period);
([ "year": int // year number (2000 AD=2000, 1 BC==0) "month": int(1..) // month of year "day": int(1..) // day of month "yearday": int(0..) // day of year "week": int(1..) // week of year "week_day": int(0..) // day of week "timezone": int // offset to utc, including dst "unix": int // unix time "julian": int // julian day // for compatibility: "hour": 0 // hour of day, including dst "minute": 0 // minute of hour "second": 0 // second of minute "fraction": 0.0 // fraction of second ]);
Day of week is compatible with old versions, ie, 0 is sunday, 6 is saturday, so it shouldn't be used to calculate the day of the week with the given week number. Year day is also backwards compatible, ie, one (1) less then from the year_day() function.
If this function is called in a Week object that begins with the first week of a year, it returns the previous year if that is where the week starts. To keep the representation unambiguous, the returned week number is then one more than the number of weeks in that year.
E.g. Week(2008,1)->datetime() will return year 2007 and week 53 since the first week of 2008 starts in 2007.
Day
day()
Day
day(int
n
)
Get day number n in the current range.
If n is negative, it is counted from the end of the range.
array
(Day
) days(int
|void
from
, object
int|voidto
)
Get the days in the current range.
string
format_iso_ymd()
string
format_ymd()
string
format_ymd_short()
string
format_ymd_xshort()
string
format_iso_week()
string
format_iso_week_short()
string
format_week()
string
format_week_short()
string
format_month()
string
format_month_short()
string
format_iso_time()
string
format_time()
string
format_time_short()
string
format_time_xshort()
string
format_mtime()
string
format_xtime()
string
format_tod()
string
format_todz()
string
format_xtod()
string
format_mod()
Format the object into nice strings;
iso_ymd "2000-06-02 (Jun) -W22-5 (Fri)" [2] ext_ymd "Friday, 2 June 2000" [2] ymd "2000-06-02" ymd_short "20000602" ymd_xshort "000602" [1] iso_week "2000-W22" iso_week_short "2000W22" week "2000-w22" [2] week_short "2000w22" [2] month "2000-06" month_short "200006" [1] iso_time "2000-06-02 (Jun) -W22-5 (Fri) 00:00:00 UTC+1" [2] ext_time "Friday, 2 June 2000, 00:00:00" [2] ctime "Fri Jun 2 00:00:00 2000\n" [2] [3] http "Fri, 02 Jun 2000 00:00:00 GMT" [4] time "2000-06-02 00:00:00" time_short "20000602 00:00:00" time_xshort "000602 00:00:00" iso_short "2000-06-02T00:00:00" mtime "2000-06-02 00:00" xtime "2000-06-02 00:00:00.000000" tod "00:00:00" tod_short "000000" todz "00:00:00 CET" todz_iso "00:00:00 UTC+1" xtod "00:00:00.000000" mod "00:00"[1] note conflict (think 1 February 2003)
The iso variants aim to be compliant with ISO-8601.
float
fraction_no()
int
hour_no()
int
julian_day()
int
leap_year()
int
minute_no()
int
month_day()
int
month_no()
int
second_no()
int
utc_offset()
int
week_day()
int
week_no()
int
year_day()
int
year_no()
string
month_name()
string
month_shortname()
string
month_day_name()
string
week_day_name()
string
week_day_shortname()
string
week_name()
string
year_name()
string
tzname()
string
tzname_iso()
int
unix_time()
Returns the unix time integer corresponding to the start of the time range object. (An unix time integer is UTC.)
Second
second()
Second
second(int
n
)
Minute
minute(int
hour
, int
minute
, int
second
)
array
(Second
) seconds()
array
(Second
) seconds(int
first
, int
last
)
int
number_of_seconds()
Minute
minute()
Minute
minute(int
n
)
Minute
minute(int
hour
, int
minute
)
array
(Minute
) minutes()
array
(Minute
) minutes(int
first
, int
last
)
int
number_of_minutes()
Hour
hour()
Hour
hour(int
n
)
array
(Hour
) hours()
array
(Hour
) hours(int
first
, int
last
)
int
number_of_hours()
inherit TimeRange : TimeRange
int
number_of_days()
Get the number of days in the current range.
This is the time period of a year.
Calendar.YMD.Year Calendar.YMD.Year(
"unix"
, int
unix_time
)
Calendar.YMD.Year Calendar.YMD.Year(
"julian"
, int
|float
julian_day
)
Calendar.YMD.Year Calendar.YMD.Year(
int
year
)
Calendar.YMD.Year Calendar.YMD.Year(
string
year
)
Calendar.YMD.Year Calendar.YMD.Year(
TimeRange
range
)
It's possible to create the standard year by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from the year number.
inherit TimeRange : TimeRange
inherit YMD : YMD
Month
month()
Month
month(int
n
)
Month
month(string
name
)
The Year type overloads the month() method, so it is possible to get a specified month by string:
year->month("April")
The integer and no argument behavior is inherited
from YMD
().
Week
week()
Week
week(int
n
)
Week
week(string
name
)
The Year type overloads the week() method, so it is possible to get a specified week by name:
year->week("17") year->week("w17")
The integer and no argument behavior is inherited
from YMD
().
This is useful, since the first week of a year not always (about half the years, in the ISO calendar) is numbered '1'.
The Charset module supports a wide variety of different character sets, and
it is flexible in regard of the names of character sets it accepts. The
character case is ignored, as are the most common non-alaphanumeric
characters appearing in character set names. E.g. "iso-8859-1"
works just as well as "ISO_8859_1"
. All encodings specified in
RFC 1345 are supported.
First of all the Charset module is capable of handling the following encodings of Unicode:
UTF encodings
Most, if not all, of the relevant code pages are represented, as the following list shows. Prefix the numbers as noted in the list to get the wanted codec:
These may be prefixed with "cp"
, "ibm"
or
"ms"
.
These may be prefixed with "cp"
, "ibm"
,
"ms"
or "windows"
The default charset in MySQL, similar to cp1252
.
+359 more.
In Pike 7.8 and earlier this module was named Locale.Charset
.
void
decode_error(string
err_str
, int
err_pos
, string
charset
, void
|string
reason
, void
|mixed
... args
)
Throws a DecodeError
exception. See DecodeError.create
for
details about the arguments. If args
is given then the error
reason is formatted using sprintf(
.reason
, @args
)
Decoder
decoder(string
name
)
Returns a charset decoder object.
name
The name of the character set to decode from. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC1345.
If the asked-for name
was not supported, an error is thrown.
Decoder
decoder_from_mib(int
mib
)
Returns a decoder for the encoding schema denoted by MIB mib
.
void
encode_error(string
err_str
, int
err_pos
, string
charset
, void
|string
reason
, void
|mixed
... args
)
Throws an EncodeError
exception. See EncodeError.create
for
details about the arguments. If args
is given then the error
reason is formatted using sprintf(
.reason
, @args
)
Encoder
encoder(string
name
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
Returns a charset encoder object.
name
The name of the character set to encode to. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC1345.
replacement
The string to use for characters that cannot be represented in
the charset. It's used when repcb
is not given or when it returns
zero. If no replacement string is given then an error is thrown
instead.
repcb
A function to call for every character that cannot be
represented in the charset. If specified it's called with one
argument - a string containing the character in question. If it
returns a string then that one will replace the character in the
output. If it returns something else then the replacement
argument will be used to decide what to do.
If the asked-for name
was not supported, an error is thrown.
Encoder
encoder_from_mib(int
mib
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
Returns an encoder for the encoding schema denoted by MIB mib
.
string
normalize(string
in
)
All character set names are normalized through this function before compared.
void
set_decoder(string
name
, Decoder
decoder
)
Adds a custom defined character set decoder. The name is
normalized through the use of normalize
.
void
set_encoder(string
name
, Encoder
encoder
)
Adds a custom defined character set encoder. The name is
normalized through the use of normalize
.
Error thrown when decode fails (and no replacement char or replacement callback has been registered).
This error class is not actually used by this module yet - decode errors are still thrown as untyped error arrays. At this point it exists only for use by other modules.
string
Charset.DecodeError.charset
The decoding charset, typically as known to
Charset.decoder
.
Other code may produce errors of this type. In that case this
name is something that Charset.decoder
does not accept
(unless it implements exactly the same charset), and it should
be reasonably certain that Charset.decoder
never accepts that
name in the future (unless it is extended to implement exactly
the same charset).
int
Charset.DecodeError.err_pos
The failing position in err_str
.
string
Charset.DecodeError.err_str
The string that failed to be decoded.
inherit Error.Generic : Generic
Virtual base class for charset decoders.
string win1252_to_string( string data ) { return Charset.decoder("windows-1252")->feed( data )->drain(); }
string
Charset.Decoder.charset
Name of the charset - giving this name to decoder
returns an
instance of the same class as this object.
This is not necessarily the same name that was actually given to
decoder
to produce this object.
this_program
clear()
Clear buffers, and reset all state.
Returns the current object to allow for chaining of calls.
string
drain()
Get the decoded data, and reset buffers.
Returns the decoded string.
this_program
feed(string
s
)
Feeds a string to the decoder.
s
String to be decoded.
Returns the current object, to allow for chaining of calls.
Error thrown when encode fails (and no replacement char or replacement callback has been registered).
This error class is not actually used by this module yet - encode errors are still thrown as untyped error arrays. At this point it exists only for use by other modules.
string
Charset.EncodeError.charset
The encoding charset, typically as known to
Charset.encoder
.
Other code may produce errors of this type. In that case this
name is something that Charset.encoder
does not accept
(unless it implements exactly the same charset), and it should
be reasonably certain that Charset.encoder
never accepts that
name in the future (unless it is extended to implement exactly
the same charset).
int
Charset.EncodeError.err_pos
The failing position in err_str
.
string
Charset.EncodeError.err_str
The string that failed to be encoded.
inherit Error.Generic : Generic
Virtual base class for charset encoders.
string
Charset.Encoder.charset
Name of the charset - giving this name to encoder
returns
an instance of the same class as this one.
This is not necessarily the same name that was actually given to
encoder
to produce this object.
inherit Decoder : Decoder
An encoder only differs from a decoder in that it has an extra function.
void
set_replacement_callback(function
(string
:string
) rc
)
Change the replacement callback function.
rc
Function that is called to encode characters outside the current character encoding.
Codec for the ISO-8859-1 character encoding.
array
(int(8bit)
) cmyk_to_rgb(array
(int(0..100)
) cmyk
)
array
(int(8bit)
) cmyk_to_rgb(int(0..100)
c
, int(0..100)
m
, int(0..100)
y
, int(0..100)
k
)
This function return the RGB value of the color describe by the provided CMYK value. It is essentially calling Image.Color.cmyk(c,m,y,k)->rgb()
Colors.rgb_to_cmyk()
Image.Color.cmyk()
string
color_name(array
(int(8bit)
) rgb
)
Tries to find a name to color described by the provided RGB
values. Partially an inverse function to Colors.parse_color()
,
although it can not find all the names that Colors.parse_color()
can find RGB values for. Returns the colors rgb hex value prepended
with "#" upon failure.
array
(int(8bit)
) hsv_to_rgb(array
(int(8bit)
) hsv
)
array
(int(8bit)
) hsv_to_rgb(int(8bit)
h
, int(8bit)
s
, int(8bit)
v
)
This function returns the RGB value of the color described by the provided HSV value. It is essentially calling Image.Color.hsv(h,s,v)->rgb().
Colors.rgb_to_hsv()
Image.Color.hsv()
array
(int(8bit)
) parse_color(string
name
, void
|array
(int
) def
)
This function returns the RGB values that corresponds to the
color that is provided by name to the function. It is
essentially calling Image.Color.guess()
, but returns the
default value (or black if none is provided) if it failes.
array
(int(0..100)
) rgb_to_cmyk(array
(int(8bit)
) rgb
)
array
(int(0..100)
) rgb_to_cmyk(int(8bit)
r
, int(8bit)
g
, int(8bit)
b
)
This function returns the CMYK value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->cmyk().
Colors.cmyk_to_rgb()
Image.Color.Color.cmyk()
array
(int(8bit)
) rgb_to_hsv(array
(int(8bit)
) rgb
)
array
(int(8bit)
) rgb_to_hsv(int(8bit)
r
, int(8bit)
g
, int(8bit)
b
)
This function returns the HSV value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->hsv().
Colors.hsv_to_rgb()
Image.Color.Color.hsv()
The CommonLog module is used to parse the lines in a www server's logfile, which must be in "common log" format -- such as used by default for the access log by Roxen, Caudium, Apache et al.
int
read(function
(array
(int
|string
), int
:void
) callback
, Stdio.File
|string
logfile
, void
|int
offset
)
Reads the log file and calls the callback function for every parsed line. For lines that fails to be parsed the callback is not called not is any error thrown. The number of bytes read are returned.
callback
The callbacks first argument is an array with the different parts of the log entry.
Array | |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| One of "GET", "POST", "HEAD" etc. |
| |
| E.g. "HTTP/1.0" |
| One of 200, 404 etc. |
|
The second callback argument is the current offset to the end of the current line.
offset
The position in the file where the parser should begin.
Module for handling multiple concurrent events.
The Future
and Promise
API was inspired by
https://github.com/couchdeveloper/FutureLib.
local
variant
Future
all(array
(Future
) futures
)
local
variant
Future
all(Future
... futures
)
JavaScript Promise API equivalent of results()
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
results()
, Promise.depend()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
variant
Future
first_completed(array
(Future
) futures
)
variant
local
Future
first_completed(Future
... futures
)
A Future
that represents the first
of the futures
that completes.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
race()
, Promise.first_completed()
Future
fold(array
(Future
) futures
, mixed
initial
, function
(mixed
, mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
Return a Future
that represents the accumulated results of
applying fun
to the results of the futures
in turn.
initial
Initial value of the accumulator.
fun
Function to apply. The first argument is the result of
one of the futures
, the second the current accumulated
value, and any further from extra
.
If fun
throws an error it will fail the Future
.
fun
may be called in any order, and will be called
once for every Future
in futures
, unless one of
calls fails in which case no further calls will be
performed.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
void
on_failure(function
(mixed
:void
) f
)protected
function
(mixed
:void
) Concurrent.global_on_failure
Global failure callback, called when a promise without failure callback fails. This is useful to log exceptions, so they are not just silently caught and ignored.
variant
local
Future
race(array
(Future
) futures
)
variant
local
Future
race(Future
... futures
)
JavaScript Promise API equivalent of first_completed()
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
first_completed()
, Promise.first_completed()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Future
reject(mixed
reason
)
A new Future
that has already failed for the specified reason
.
The returned Future
does NOT have a backend set.
Future.on_failure()
, Promise.failure()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Future
resolve(mixed
value
)
A new Future
that has already been fulfilled with value
as result. If value
is an object which already
has on_failure
and on_success
methods, return it unchanged.
This function can be used to ensure values are futures.
The returned Future
does NOT have a backend set.
Future.on_success()
, Promise.success()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
variant
Future
results(array
(Future
) futures
)
local
variant
Future
results(Future
... futures
)
A Future
that represents the array of all the completed futures
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
all()
, Promise.depend()
Future
traverse(array
(Future
) futures
, function
(mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
Return a Future
that represents the array of mapping fun
over the results of the completed futures
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
final
void
use_backend(int
enable
)
enable
| A |
| A |
Be very careful about running in the backend disabled mode, as it may cause unlimited recursion and reentrancy issues.
As long as the backend hasn't started, it will default to false
.
Upon startup of the backend, it will change to true
unless you
explicitly called use_backend()
before that.
(Un)setting this typically alters the order in which some callbacks are called (depending on what happens in a callback).
Future()->set_backend()
, Future()->call_callback()
Value that will be provided asynchronously sometime in the future.
Promise
protected
void
apply(mixed
val
, Promise
p
, function
(mixed
, mixed
... :mixed
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with the result.
protected
void
apply_filter(mixed
val
, Promise
p
, function
(mixed
, mixed
... :bool
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with val
if fun
didn't return false.
If fun
returned false, fail p
with 0
as result.
protected
void
apply_flat(mixed
val
, Promise
p
, function
(mixed
, mixed
... :Future
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with the eventual result.
protected
void
apply_smart(mixed
val
, Promise
p
, function
(mixed
, mixed
... :mixed
|Future
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with the eventual result.
protected
void
call_callback(function
(:void
) cb
, mixed
... args
)
Call a callback function.
cb
Callback function to call.
args
Arguments to call cb
with.
The default implementation calls cb
via the
backend set via set_backend()
(if any), and
otherwise falls back the the mode set by
use_backend()
.
set_backend()
, use_backend()
this_program
delay(int
|float
seconds
)
Return a Future
that will be fulfilled with the fulfilled
result of this Future
, but not until at least seconds
have passed.
this_program
filter(function
(mixed
, mixed
... :bool
) fun
, mixed
... extra
)
This specifies a callback that is only called on success, and allows you to selectively alter the future into a failure.
fun
Function to be called. The first argument will be the
success result of this Future
.
If the return value is true
, the future succeeds with
the original success result.
If the return value is false
, the future fails with
an UNDEFINED
result.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
transform()
local
this_program
flat_map(function
(mixed
, mixed
... :this_program
) fun
, mixed
... extra
)
This is an alias for map_with()
.
map_with()
mixed
get()
Wait for fulfillment and return the value.
Throws on rejection.
wait()
, try_get()
Pike.Backend
get_backend()
Get the backend (if any) used to call any callbacks.
This returns the value set by set_backend()
.
set_backend()
this_program
map(function
(mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
This specifies a callback that is only called on success, and allows you to alter the future.
fun
Function to be called. The first argument will be the
success result of this Future
.
The return value will be the success result of the new Future
.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your fun
returns a regular value (i.e.
not a Future
).
map_with()
, transform()
, recover()
this_program
map_with(function
(mixed
, mixed
... :this_program
) fun
, mixed
... extra
)
This specifies a callback that is only called on success, and allows you to alter the future.
fun
Function to be called. The first argument will be the
success result of this Future
.
The return value must be a Future
that promises
the new result.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your fun
returns a Future
again.
map()
, transform_with()
, recover_with()
, flat_map
this_program
on_failure(function
(mixed
, mixed
... :void
) cb
, mixed
... extra
)
Register a callback that is to be called on failure.
cb
Function to be called. The first argument will be the
failure result of the Future
.
extra
Any extra context needed for cb
. They will be provided
as arguments two and onwards when cb
is called.
cb
will always be called from the main backend.
on_success()
, query_failure_callbacks()
this_program
on_success(function
(mixed
, mixed
... :void
) cb
, mixed
... extra
)
Register a callback that is to be called on fulfillment.
cb
Function to be called. The first argument will be the
result of the Future
.
extra
Any extra context needed for cb
. They will be provided
as arguments two and onwards when cb
is called.
cb
will always be called from the main backend.
on_failure()
, query_success_callbacks()
Promise
promise_factory()
Create a new Promise
with the same base settings
as the current object.
Overload this function if you need to propagate more state
to new Promise
objects.
The default implementation copies the backend
setting set with set_backend()
to the new Promise
.
Promise
, set_backend()
array
(function
(:void
)) query_failure_callbacks()
Query the set of active failure callbacks.
Returns an array with callback functions.
on_failure()
, query_success_callbacks()
array
(function
(:void
)) query_success_callbacks()
Query the set of active success callbacks.
Returns an array with callback functions.
on_success()
, query_failure_callbacks()
this_program
recover(function
(mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
This specifies a callback that is only called on failure, and allows you to alter the future into a success.
fun
Function to be called. The first argument will be the
failure result of this Future
.
The return value will be the success result of the new Future
.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your callbacks return a regular value (i.e.
not a Future
).
recover_with()
, map()
, transform()
this_program
recover_with(function
(mixed
, mixed
... :this_program
) fun
, mixed
... extra
)
This specifies a callback that is only called on failure, and allows you to alter the future into a success.
fun
Function to be called. The first argument will be the
failure result of this Future
.
The return value must be a Future
that promises
the new success result.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your callbacks return a Future
again.
recover()
, map_with()
, transform_with()
void
set_backend(Pike.Backend
backend
)
Set the backend to use for calling any callbacks.
This overides the mode set by use_backend()
.
get_backend()
, use_backend()
this_program
then(void
|function
(mixed
, mixed
... :mixed
) onfulfilled
, void
|function
(mixed
, mixed
... :mixed
) onrejected
, mixed
... extra
)
JavaScript Promise API close but not identical equivalent
of a combined transform()
and transform_with()
.
onfulfilled
Function to be called on fulfillment. The first argument will be the
result of this Future
.
The return value will be the result of the new Future
.
If the return value already is a Future
, pass it as-is.
onrejected
Function to be called on failure. The first argument will be the
failure result of this Future
.
The return value will be the failure result of the new Future
.
If the return value already is a Future
, pass it as-is.
extra
Any extra context needed for onfulfilled
and
onrejected
. They will be provided
as arguments two and onwards when the callbacks are called.
The new Future
.
transform()
, transform_with()
, thencatch()
,
on_success()
, Promise.success()
,
on_failure()
, Promise.failure()
,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
local
this_program
thencatch(function
(mixed
, mixed
... :mixed
) onrejected
, mixed
... extra
)
JavaScript Promise API equivalent of a combination of recover()
and recover_with()
.
onrejected
Function to be called. The first argument will be the
failure result of this Future
.
The return value will the failure result of the new Future
.
If the return value already is a Future
, pass it as-is.
extra
Any extra context needed for
onrejected
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
recover()
, recover_with()
, then()
, on_failure()
,
Promise.failure()
,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
this_program
timeout(int
|float
seconds
)
Return a Future
that will either be fulfilled with the fulfilled
result of this Future
, or be failed after seconds
have expired.
this_program
transform(function
(mixed
, mixed
... :mixed
) success
, function
(mixed
, mixed
... :mixed
)|void
failure
, mixed
... extra
)
This specifies callbacks that allow you to alter the future.
success
Function to be called. The first argument will be the
success result of this Future
.
The return value will be the success result of the new Future
.
failure
Function to be called. The first argument will be the
failure result of this Future
.
The return value will be the success result of the new Future
.
If this callback is omitted, it will default to the same callback as
success
.
extra
Any extra context needed for
success
and failure
. They will be provided
as arguments two and onwards when the callbacks are called.
The new Future
.
This method is used if your callbacks return a regular value (i.e.
not a Future
).
transform_with()
, map()
, recover()
this_program
transform_with(function
(mixed
, mixed
... :this_program
) success
, function
(mixed
, mixed
... :this_program
)|void
failure
, mixed
... extra
)
This specifies callbacks that allow you to alter the future.
success
Function to be called. The first argument will be the
success result of this Future
.
The return value must be a Future
that promises
the new result.
failure
Function to be called. The first argument will be the
failure result of this Future
.
The return value must be a Future
that promises
the new success result.
If this callback is omitted, it will default to the same callback as
success
.
extra
Any extra context needed for
success
and failure
. They will be provided
as arguments two and onwards when the callbacks are called.
The new Future
.
This method is used if your callbacks return a Future
again.
transform()
, map_with()
, recover_with
mixed
try_get()
Return the value if available.
Returns UNDEFINED
if the Future
is not yet fulfilled.
Throws on rejection.
wait()
this_program
wait()
Wait for fulfillment.
get()
, try_get()
this_program
zip(array
(this_program
) others
)
local
variant
this_program
zip(this_program
... others
)
others
The other futures (results) you want to append.
A new Future
that will be fulfilled with an
array of the fulfilled result of this object followed
by the fulfilled results of other futures.
results()
Promise to provide a Future
value.
Objects of this class are typically kept internal to the
code that provides the Future
value. The only thing
that is directly returned to the user is the return
value from future()
.
Future
, future()
this_program
any_results()
Sets the number of failures to be accepted in the list of futures
this promise
depends upon to unlimited. It is equivalent to max_failures(-1)
.
The new Promise
.
depend()
, max_failures()
Concurrent.Promise Concurrent.Promise(
void
|function
(function
(mixed
:void
), function
(mixed
:void
), mixed
... :void
) executor
, mixed
... extra
)
Creates a new promise, optionally initialised from a traditional callback
driven method via executor(success, failure, @extra)
.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
this_program
depend(array
(Future
) futures
)
local
variant
this_program
depend(Future
... futures
)
variant
this_program
depend()
Add futures to the list of futures which the current object depends upon.
If called without arguments it will produce a new Future
from a new Promise
which is implictly added to the dependency list.
futures
The list of futures
we want to add to the list we depend upon.
The new Promise
.
Can be called multiple times to add more.
Once the promise has been materialised (when either on_success()
,
on_failure()
or get()
has been called on this object), it is
not possible to call depend()
anymore.
fold()
, first_completed()
, max_failures()
, min_failures()
,
any_results()
, Concurrent.results()
, Concurrent.all()
this_program
failure(mixed
value
)
Reject the Future
value.
value
Failure result of the Future
.
Throws an error if the Future
already has been fulfilled
or failed.
Mark the Future
as failed, and schedule the on_failure()
callbacks to be called as soon as possible.
try_failure()
, success()
, on_failure()
this_program
first_completed()
It evaluates to the first future that completes of the list of futures it depends upon.
The new Promise
.
depend()
, Concurrent.first_completed()
this_program
fold(mixed
initial
, function
(mixed
, mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
initial
Initial value of the accumulator.
fun
Function to apply. The first argument is the result of
one of the futures
. The second argument is the current value
of the accumulator.
extra
Any extra context needed for fun
. They will be provided
as arguments three and onwards when fun
is called.
The new Promise
.
If fun
throws an error it will fail the Future
.
fun
may be called in any order, and will be called
once for every Future
it depends upon, unless one of the
calls fails in which case no further calls will be
performed.
depend()
, Concurrent.fold()
Future
future()
The future value that we promise.
inherit Future : Future
this_program
max_failures(int(-1..)
max
)
max
Specifies the maximum number of failures to be accepted in the list of futures this promise depends upon.
-1
means unlimited.
Defaults to 0
.
The new Promise
.
depend()
, min_failures()
, any_results()
this_program
min_failures(int(0..)
min
)
min
Specifies the minimum number of failures to be required in
the list of futures this promise depends upon. Defaults
to 0
.
The new Promise
.
depend()
, max_failures()
this_program
success(mixed
value
)
Fulfill the Future
.
value
Result of the Future
.
Throws an error if the Future
already has been fulfilled
or failed.
Mark the Future
as fulfilled, and schedule the on_success()
callbacks to be called as soon as possible.
try_success()
, try_failure()
, failure()
, on_success()
local
this_program
try_failure(mixed
value
)
Maybe reject the Future
value.
value
Failure result of the Future
.
Mark the Future
as failed if it hasn't already been fulfilled,
and in that case schedule the on_failure()
callbacks to be
called as soon as possible.
failure()
, success()
, on_failure()
local
this_program
try_success(mixed
value
)
Fulfill the Future
if it hasn't been fulfilled or failed already.
value
Result of the Future
.
Mark the Future
as fulfilled if it hasn't already been fulfilled
or failed, and in that case schedule the on_success()
callbacks
to be called as soon as possible.
success()
, try_failure()
, failure()
, on_success()
Various cryptographic classes and functions.
Hash functions
These are based on the Hash
API; MD2
, MD4
, MD5
,
SHA1
, SHA256
.
Stream cipher functions
These are based on the Cipher
API; AES
, Arcfour
,
Blowfish
, CAST
, DES
, DES3
, IDEA
, Serpent
,
Twofish
. The Substitution
program is compatible with the
CipherState. Also conforming to the API are the helper modules
Buffer
, CBC
, GCM
and Pipe
.
As the cryptographic services offered from this module isn't necessarily used for security applications, none of the strings input or output are marked as secure. This is up to the caller.
This module is only available if Pike has been compiled with
Nettle
enabled (this is the default).
__deprecated__
program
Crypto.Buffer
This class has moved to submodules of the respective ciphers.
string(8bit)
make_crypt_md5(string(8bit)
password
, void
|string(8bit)
salt
)
Hashes a password
together with a salt
with the
crypt_md5 algorithm and returns the result.
verify_crypt_md5
string(8bit)
rot13(string(8bit)
data
)
Convenience function that accesses the crypt function of a substitution object keyed to perform standard ROT13 (de)ciphering.
bool
verify_crypt_md5(string(8bit)
password
, string(7bit)
hash
)
Verifies the password
against the crypt_md5 hash.
May throw an exception if the hash value is bad.
make_crypt_md5
Abstract class for AE algorithms.
inherit __builtin.Nettle.AE : AE
Abstract class for AEAD algorithms.
inherit Nettle.AEAD : AEAD
Abstract class for block cipher algorithms. Contains some tools useful for all block ciphers.
Contains the CBC
submodule.
inherit Nettle.BlockCipher : BlockCipher
Abstract class for block cipher algorithms with a 16 byte block size. Contains some tools useful for all such block ciphers.
Contains the GCM
submodule.
inherit Nettle.BlockCipher16 : BlockCipher16
This class has moved to submodules of the respective ciphers.
Replaced by BlockCipher.Buffer
.
Crypto.Buffer Crypto.Buffer(
CipherState
|program
fun
, mixed
... args
)
Abstract class for block cipher meta algorithms.
Contains the Buffer
submodule.
inherit Nettle.BufferedCipher : BufferedCipher
This class has moved to submodules of the respective ciphers.
Replaced by BlockCipher.CBC
.
Crypto.CBC Crypto.CBC(
CipherState
|program
fun
, mixed
... args
)
Abstract class for crypto algorithms. Contains some tools useful for all ciphers.
Typically only inherited directly by stream ciphers.
It is however convenient for typing as it contains the minimum base level API for a cipher.
BufferedCipher
, BlockCipher
, BlockCipher16
inherit Nettle.Cipher : Cipher
HMAC, defined by RFC-2104
Crypto.MAC.State
res = Crypto.HMAC()
()
Calling the HMAC object with a password returns a new object that
can perform the actual HMAC hashing. E.g. doing a HMAC hash with
MD5 and the password "bar"
of the string "foo"
would require the code Crypto.HMAC(Crypto.MD5)("bar")("foo")
.
Crypto.HMAC Crypto.HMAC(
.Hash
h
, int
|void
b
)
h
The hash object on which the HMAC object should base its
operations. Typical input is Crypto.MD5
.
b
The block size of one compression block, in octets. Defaults to
block_size() of h
.
string(8bit)
pkcs_digest(string(8bit)
s
)
Makes a PKCS-1 digestinfo block with the message s
.
Standards.PKCS.Signature.build_digestinfo
string(8bit)
raw_hash(string(8bit)
s
)
Calls the hash function given to create
and returns the hash
value of s
.
Abstract class for hash algorithms. Contains some tools useful for all hashes.
inherit Nettle.Hash : Hash
Abstract class for Message Authentication Code (MAC) algorithms. Contains some tools useful for all MACs.
inherit Nettle.MAC : MAC
A wrapper class that connects several cipher algorithms into one
algorithm. E.g. triple DES can be emulated with
Crypto.Pipe(Crypto.DES, Crypto.DES, Crypto.DES)
.
Abstract class for signature algorithms. Contains some tools useful for all signatures.
State
res = Crypto.Sign()
()
Calling `() will return a State
object.
string(7bit)
name()
Returns the printable name of the signing algorithm.
Implements a simple substitution crypto, ie. one of the first crypto systems ever invented and thus one of the least secure ones available.
string(8bit)
decrypt(string(8bit)
c
)
Decrypts the cryptogram c
.
string(8bit)
encrypt(string(8bit)
m
)
Encrypts the message m
.
string
filter(string
m
, void
|multiset
(int
) save
)
Removes characters not in the encryption key or in
the save
multiset from the message m
.
this_program
set_ACA_K1_key(string
key
, void
|int
offset
, void
|array
(string
) alphabet
)
Sets the key according to ACA K1 key generation. The plaintext
alphabet is prepended with a keyword key
that shifts the alphabet
positions compared to the cryptogram alphabet. The plaintext
alphabet is then reduced with the characters in the keyword. It is
also optionally rotated offset
number of steps.
this_program
set_ACA_K2_key(string
key
, void
|int
offset
, void
|array
(string
) alphabet
)
Sets the key according to ACA K2 key generation. The cryptogram
alphabet is prepended with a keyword key
that shifts the alphabet
positions compared to the plaintext alphabet. The cryptogram
alphabet is then reduced with the characters in the keyword. It is
als optionally reotated offset
number of steps.
this_program
set_ACA_K3_key(string
key
, int
offset
, void
|array
(string
) alphabet
)
Sets the key according to ACA K3 key generation. Both the plaintext
and the cryptogram alphabets are prepended with a keyword key
,
which characters are removed from the rest of the alphabet. The
plaintext alphabet is then rotated offset
number of steps.
this_program
set_ACA_K4_key(string
key1
, string
key2
, void
|int
offset
, void
|array
(string
) alphabet
)
Sets the key according to ACA K4 key generation. Both the plaintext
and the cryptogram alphabets are prepended with the keywords key1
and key2
. The plaintext alphabet is then rotated offset
number
of steps.
this_program
set_key(mapping
(string
:string
|array
(string
)) key
)
Sets the encryption and decryption key. The decryption key is
derived from the encryption key
by reversing the mapping. If
one index maps to an array of strings, one element from the array
will be chosen at random in such substitution.
An error is thrown if the encryption key can not be made reversible.
this_program
set_null_chars(int
|float
p
, array
(string
) chars
)
Set null characters (fillers). Characters from chars
will be
inserted into the output stream with a probability p
.
p
A float between 0.0 and 1.0 or an integer between 0 and 100.
chars
An array of one character strings.
this_program
set_rot_key(void
|int
steps
, void
|array
(string
) alphabet
)
Sets the key to a ROT substitution system. steps
defaults
to 13 and alphabet
defaults to A-Z, i.e. this function
defaults to set the substitution crypto to be ROT13. If no
alphabet is given the key will be case insensitive, e.g. the
key will really be two ROT13 alphabets, one a-z and one A-Z,
used simultaneously.
AES (American Encryption Standard) is a quite new block cipher, specified by NIST as a replacement for the older DES standard. The standard is the result of a competition between cipher designers. The winning design, also known as RIJNDAEL, was constructed by Joan Daemen and Vincent Rijnmen.
Like all the AES candidates, the winning design uses a block size of 128 bits, or 16 octets, and variable key-size, 128, 192 and 256 bits (16, 24 and 32 octets) being the allowed key sizes. It does not have any weak keys.
inherit Nettle.AES : AES
State
`()(string(8bit)
password
)
Get a POLY1305 State
object initialized with a password.
inherit Nettle.POLY1305_AES : POLY1305_AES
UMAC is a familty of message digest functions based on universal hashing
and AES
that is specified in RFC 4418. They differ mainly in the size
of the resulting digest.
UMAC128
outputs a digest of 128 bits or 16 octets.
UMAC32
, UMAC64
, UMAC96
State
`()(string(8bit)
password
)
Get a UMAC128 State
object initialized with a password.
inherit Nettle.UMAC128_AES : UMAC128_AES
UMAC is a familty of message digest functions based on universal hashing
and AES
that is specified in RFC 4418. They differ mainly in the size
of the resulting digest.
UMAC32
outputs a digest of 32 bits or 4 octets.
UMAC64
, UMAC96
, UMAC128
State
`()(string(8bit)
password
)
Get a UMAC32 State
object initialized with a password.
inherit Nettle.UMAC32_AES : UMAC32_AES
UMAC is a familty of message digest functions based on universal hashing
and AES
that is specified in RFC 4418. They differ mainly in the size
of the resulting digest.
UMAC64
outputs a digest of 64 bits or 8 octets.
UMAC32
, UMAC96
, UMAC128
State
`()(string(8bit)
password
)
Get a UMAC64 State
object initialized with a password.
inherit Nettle.UMAC64_AES : UMAC64_AES
UMAC is a familty of message digest functions based on universal hashing
and AES
that is specified in RFC 4418. They differ mainly in the size
of the resulting digest.
UMAC96
outputs a digest of 96 bits or 12 octets.
UMAC32
, UMAC64
, UMAC128
State
`()(string(8bit)
password
)
Get a UMAC96 State
object initialized with a password.
inherit Nettle.UMAC96_AES : UMAC96_AES
Arcfour is a stream cipher, also known under the trade marked name
RC4, and it is one of the fastest ciphers around. A problem is
that the key setup of Arcfour is quite weak, you should never use
keys with structure, keys that are ordinary passwords, or
sequences of keys like "secret:1"
, "secret:2"
,
..... If you have keys that don't look like random bit strings,
and you want to use Arcfour, always hash the key before feeding it
to Arcfour.
inherit Nettle.ARCFOUR : ARCFOUR
Arctwo is a block cipher, also known under the trade marked name RC2.
The cipher is quite weak, and should not be used for new software.
inherit Nettle.ARCTWO : ARCTWO
BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block size of 64 bits (8 octets), and a variable key size, up to 448 bits. It has some weak keys.
inherit Nettle.BLOWFISH : BLOWFISH
CAST-128 is a block cipher, specified in RFC 2144. It uses a 64 bit (8 octets) block size, and a variable key size of up to 128 bits.
inherit Nettle.CAST128 : CAST128
The Camellia 128-bit block cipher.
inherit Nettle.CAMELLIA : CAMELLIA
ChaCha20 is a stream cipher by D. J. Bernstein.
This module is not available in all versions of Nettle.
inherit Nettle.CHACHA : CHACHA
This is an AEAD
cipher consisting of the CHACHA
cipher
and a MAC
based on the POLY1305 algorithm.
Note that this is an AEAD
cipher, while AES.POLY1305
(aka POLY1305-AES) is a MAC
.
Note also that the POLY1305 algorithm used here is NOT identical
to the one in the AES.POLY1305
MAC
. The iv/nonce handling
differs.
This module is not available in all versions of Nettle.
inherit Nettle.CHACHA_POLY1305 : CHACHA_POLY1305
DES is the old Data Encryption Standard, specified by NIST. It uses a block size of 64 bits (8 octets), and a key size of 56 bits. However, the key bits are distributed over 8 octets, where the least significant bit of each octet is used for parity. A common way to use DES is to generate 8 random octets in some way, then set the least significant bit of each octet to get odd parity, and initialize DES with the resulting key.
The key size of DES is so small that keys can be found by brute
force, using specialized hardware or lots of ordinary work
stations in parallel. One shouldn't be using plain DES at all
today, if one uses DES at all one should be using DES3
or "triple
DES".
DES also has some weak keys.
inherit Nettle.DES : DES
The inadequate key size of DES
has already been mentioned. One
way to increase the key size is to pipe together several DES boxes
with independent keys. It turns out that using two DES ciphers is
not as secure as one might think, even if the key size of the
combination is a respectable 112 bits.
The standard way to increase DES's key size is to use three DES boxes. The mode of operation is a little peculiar: the middle DES box is wired in the reverse direction. To encrypt a block with DES3, you encrypt it using the first 56 bits of the key, then decrypt it using the middle 56 bits of the key, and finally encrypt it again using the last 56 bits of the key. This is known as "ede" triple-DES, for "encrypt-decrypt-encrypt".
The "ede" construction provides some backward compatibility, as you get plain single DES simply by feeding the same key to all three boxes. That should help keeping down the gate count, and the price, of hardware circuits implementing both plain DES and DES3.
DES3 has a key size of 168 bits, but just like plain DES, useless parity bits are inserted, so that keys are represented as 24 octets (192 bits). As a 112 bit key is large enough to make brute force attacks impractical, some applications uses a "two-key" variant of triple-DES. In this mode, the same key bits are used for the first and the last DES box in the pipe, while the middle box is keyed independently. The two-key variant is believed to be secure, i.e. there are no known attacks significantly better than brute force.
inherit Nettle.DES3 : DES3
Diffie-Hellman key-exchange related stuff.
Parameters
Crypto.DH.FFDHE2048
Finite Field Diffie-Hellman 2048
From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.1.
Parameters
Crypto.DH.FFDHE2432
Finite Field Diffie-Hellman 2432
From Negotiated FF-DHE for TLS draft 03, November 2014, Appendix A.1.
Parameters
Crypto.DH.FFDHE3072
Finite Field Diffie-Hellman 3072
From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.2.
Parameters
Crypto.DH.FFDHE4096
Finite Field Diffie-Hellman 4096
From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.3.
Parameters
Crypto.DH.FFDHE6144
Finite Field Diffie-Hellman 6144
From Negotiated FF-DHE for TLS draft 02, October 2014, Appendix A.4.
Parameters
Crypto.DH.FFDHE8192
Finite Field Diffie-Hellman 8192
From Negotiated FF-DHE for TLS draft 04, December 2014, Appendix A.4.
Parameters
Crypto.DH.MODPGroup1
MODP Group 1 (768 bit) (aka First Oakley Group (aka ORM96 group 1)).
RFC 2409 6.1
Not allowed for use with FIPS 140.
Parameters
Crypto.DH.MODPGroup14
MODP Group 14 (2048 bit).
RFC 3526 3
Parameters
Crypto.DH.MODPGroup15
MODP Group 15 (3072 bit).
RFC 3526 3
Parameters
Crypto.DH.MODPGroup16
MODP Group 16 (4096 bit).
RFC 3526 5
Parameters
Crypto.DH.MODPGroup17
MODP Group 17 (6144 bit).
RFC 3526 6
Parameters
Crypto.DH.MODPGroup18
MODP Group 18 (8192 bit).
RFC 3526 7
Parameters
Crypto.DH.MODPGroup2
MODP Group 2 (1024 bit) (aka Second Oakley Group (aka ORM96 group 2)).
RFC 2409 6.2
Not allowed for use with FIPS 140.
Parameters
Crypto.DH.MODPGroup22
MODP Group 22 (1024-bit with 160-bit Subgroup).
RFC 5114 2.1
Parameters
Crypto.DH.MODPGroup23
MODP Group 23 (2048-bit with 224-bit Subgroup).
RFC 5114 2.2
Parameters
Crypto.DH.MODPGroup24
MODP Group 24 (2048-bit with 256-bit Subgroup).
RFC 5114 2.3
Parameters
Crypto.DH.MODPGroup5
MODP Group 5 (1536 bit).
RFC 3526 2
Not allowed for use with FIPS 140.
Diffie-Hellman parameters.
Crypto.DH.Parameters Crypto.DH.Parameters(
Gmp.mpz
|int
p
, Gmp.mpz
|int
|void
g
, Gmp.mpz
|int
|void
q
)
Initialize the set of Diffie-Hellman parameters.
p
The prime for the group.
g
The generator for the group. Defaults to 2
.
q
The order of the group. Defaults to (p-1)/2
.
Crypto.DH.Parameters Crypto.DH.Parameters(
this_program
other
)
Initialize the set of Diffie-Hellman parameters.
other
Copy the parameters from this object.
Crypto.DH.Parameters Crypto.DH.Parameters(
Crypto.DSA.State
dsa
)
Initialize the set of Diffie-Hellman parameters.
dsa
Copy the parameters from this object.
Gmp.mpz
Crypto.DH.Parameters.g
Generator.
array
(Gmp.mpz
) generate_keypair(function
(int(0..)
:string(8bit)
) rnd
)
Generate a Diffie-Hellman key pair.
Returns the following array:
Array | |
| The generated public key. |
| The corresponding private key. |
inherit Nettle.DH_Params : DH_Params
__deprecated__
Gmp.mpz
Crypto.DH.Parameters.order
Alias for q
.
Replaced by q
.
Gmp.mpz
Crypto.DH.Parameters.p
Prime.
Gmp.mpz
Crypto.DH.Parameters.q
Subgroup size.
bool
validate(int(0..)
effort
)
Validate that the DH Parameters doesn't have obvious security
weaknesses. It will first attempt to verify the prime p
using
Donald Knuth's probabilistic primality test with provided
effort
. This has a chance of pow(0.25,effort) to produce a
false positive. An effort
of 0 skipps this step. The second
test verifies that g
is of high order.
The Digital Signature Algorithm DSA is part of the NIST Digital Signature Standard DSS, FIPS-186 (1993).
protected
State
`()()
Calling `() will return a State
object.
inherit Crypto.Sign : Sign
string(8bit)
name()
Returns the string "DSA"
.
bool
equal(Crypto.DSA.State from, mixed
other
)
Compares the keys of this DSA object with something other.
variant
this_program
generate_key(int
p_bits
, int
q_bits
)
Generates DSA parameters (p, q, g) and key (x, y). Depending on
Nettle version q_bits
can be 160, 224 and 256 bits. 160 works
for all versions.
variant
this_program
generate_key()
Generates a public/private key pair. Needs the public parameters
p, q and g set, either through set_public_key
or
generate_key(int,int)
.
Gmp.mpz
get_g()
Returns the DSA generator (g).
Gmp.mpz
get_p()
Returns the DSA modulo (p).
Gmp.mpz
get_q()
Returns the DSA group order (q).
Gmp.mpz
get_x()
Returns the DSA private key (x).
Gmp.mpz
get_y()
Returns the DSA public key (y).
Gmp.mpz
hash(string(8bit)
msg
, .Hash
h
)
Makes a DSA hash of the messge msg
.
inherit ::this_program : this_program
string(8bit)
name()
Returns the string "DSA"
.
Sequence
pkcs_algorithm_identifier()
Returns the AlgorithmIdentifier as defined in RFC5280 section 4.1.1.2 including the DSA parameters.
Sequence
pkcs_public_key()
Creates a SubjectPublicKeyInfo ASN.1 sequence for the object. See RFC 5280 section 4.1.2.7.
string(8bit)
pkcs_sign(string(8bit)
message
, .Hash
h
)
Signs the message
with a PKCS-1 signature using hash algorithm
h
.
Sequence
pkcs_signature_algorithm_id(.Hash
hash
)
Returns the PKCS-1 algorithm identifier for DSA and the provided
hash algorithm. Only SHA1
supported.
bool
pkcs_verify(string(8bit)
message
, .Hash
h
, string(8bit)
sign
)
Verify PKCS-1 signature sign
of message message
using hash
algorithm h
.
bool
public_key_equal(this_program
dsa
)
Compares the public key in this object with that in the provided DSA object.
array
(Gmp.mpz
) raw_sign(Gmp.mpz
h
, void
|Gmp.mpz
k
)
Sign the message h
. Returns the signature as two Gmp.mpz
objects.
bool
raw_verify(Gmp.mpz
h
, Gmp.mpz
r
, Gmp.mpz
s
)
Verify the signature r
,s
against the message h
.
this_program
set_private_key(Gmp.mpz
secret
)
Sets the private key, the x parameter, in this DSA object.
this_program
set_public_key(Gmp.mpz
modulo
, Gmp.mpz
order
, Gmp.mpz
generator
, Gmp.mpz
key
)
Sets the public key in this DSA object.
modulo
This is the p parameter.
order
This is the group order q parameter.
generator
This is the g parameter.
kye
This is the public key y parameter.
this_program
set_random(function
(int(0..)
:string(8bit)
) r
)
Sets the random function, used to generate keys and parameters, to
the function r
. Default is Crypto.Random.random_string
.
__deprecated__
string(8bit)
sign_rsaref(string(8bit)
msg
)
Make a RSA ref signature of message msg
.
__deprecated__
string(8bit)
sign_ssl(string(8bit)
msg
)
Make an SSL signature of message msg
.
__deprecated__
bool
verify_rsaref(string(8bit)
msg
, string(8bit)
s
)
Verify a RSA ref signature s
of message msg
.
__deprecated__
bool
verify_ssl(string(8bit)
msg
, string(8bit)
s
)
Verify an SSL signature s
of message msg
.
Elliptic Curve Cipher Constants.
This module contains constants used with elliptic curve algorithms.
The definition of an elliptic curve.
Objects of this class are typically not created by the user.
SECP_192R1
, SECP_224R1
, SECP_256R1
, SECP_384R1
, SECP_521R1
inherit Nettle.ECC_Curve : ECC_Curve
Sequence
pkcs_algorithm_identifier()
Returns the AlgorithmIdentifier as defined in RFC5480 section 2.
Identifier
pkcs_ec_parameters()
Returns the PKCS-1 elliptic curve parameters for the curve. cf RFC 5480 2.1.1.
Identifier
pkcs_named_curve_id()
Returns the PKCS-1 elliptic curve identifier for the curve. cf RFC 5480 2.1.1.
Elliptic Curve Digital Signing Algorithm
bool
equal(Crypto.ECC.Curve.ECDSA from, mixed
other
)
Compares the keys of this ECDSA object with something other.
this_program
generate_key()
Generate a new set of private and public keys on the current curve.
Curve
get_curve()
Return the curve.
string(8bit)
get_public_key()
Get the ANSI x9.62 4.3.6 encoded uncompressed public key.
inherit ECC_Curve::ECDSA : ECDSA
array
(mapping
(string(7bit)
:string(7bit)
|int
)|string(8bit)
) jose_decode(string(7bit)
jws
)
Verify and decode a JOSE JWS ECDSA signed value.
jws
A JSON Web Signature as returned by jose_sign()
.
Returns 0
(zero) on failure, and an array
Array | |
| The JOSE header. |
| The signed message. |
pkcs_verify()
, RFC 7515 section 3.5
string(7bit)
jose_sign(string(8bit)
message
, .Hash
|void
h
, mapping
(string(7bit)
:string(7bit)
|int
)|void
headers
)
Signs the message
with a JOSE JWS ECDSA signature using hash
algorithm h
.
message
Message to sign.
h
Hash algorithm to use.
Returns the signature on success, and 0
(zero)
on failure.
pkcs_verify()
, salt_size()
, RFC 7515
string(7bit)
jwa(.Hash
hash
)
Get the JWS algorithm identifier for a hash.
Returns 0
(zero) on failure.
mapping
(string(7bit)
:string(7bit)
) jwk(bool
|void
private_key
)
Generate a JWK-style mapping of the object.
private_key
If true, include the private key in the result.
Returns a JWK-style mapping on success, and 0
(zero)
on failure.
create()
, Web.encode_jwk()
, RFC 7517 section 4, RFC 7518 section 6.2
int(0..)
key_size()
Return the size of the private key in bits.
Sequence
pkcs_algorithm_identifier()
Returns the AlgorithmIdentifier as defined in RFC5480 section 2.1.1 including the ECDSA parameters.
Sequence
pkcs_public_key()
Creates a SubjectPublicKeyInfo ASN.1 sequence for the object. See RFC 5280 section 4.1.2.7.
string(8bit)
pkcs_sign(string(8bit)
message
, .Hash
h
)
Signs the message
with a PKCS-1 signature using hash algorithm
h
.
Sequence
pkcs_signature_algorithm_id(.Hash
hash
)
Returns the PKCS-1 algorithm identifier for ECDSA and the provided hash algorithm. Only SHA-1 and SHA-2 based hashes are supported currently.
bool
pkcs_verify(string(8bit)
message
, .Hash
h
, string(8bit)
sign
)
Verify PKCS-1 signature sign
of message message
using hash
algorithm h
.
bool
public_key_equal(this_program
ecdsa
)
Compares the public key in this object with that in the provided ECDSA object.
this_program
set_private_key(Gmp.mpz
|int
k
)
Set the private key.
Throws errors if the key isn't valid for the curve.
this_program
set_public_key(Gmp.mpz
|int
x
, Gmp.mpz
|int
y
)
Change to the selected point on the curve as public key.
Throws errors if the point isn't on the curve.
variant
this_program
set_public_key(string(8bit)
key
)
Change to the selected point on the curve as public key.
key
The public key encoded according to ANSI x9.62 4.3.6.
Throws errors if the point isn't on the curve.
this_program
set_random(function
(int
:string(8bit)
) r
)
Set the random function, used to generate keys and parameters,
to the function r
.
int
size()
Return the curve size in bits.
inherit Curve : Curve
inherit Curve : Curve
inherit Curve : Curve
inherit Curve : Curve
inherit Curve : Curve
The GOST94 or GOST R 34.11-94 hash algorithm is a Soviet-era algorithm used in Russian government standards, defined in RFC 4357.
inherit Nettle.GOST94 : GOST94
The IDEA(tm) block cipher is covered by patents held by ETH and a Swiss company called Ascom-Tech AG. The Swiss patent number is PCT/CH91/00117, the European patent number is EP 0 482 154 B1, and the U.S. patent number is US005214703. IDEA(tm) is a trademark of Ascom-Tech AG. There is no license fee required for noncommercial use.
inherit Nettle.IDEA : IDEA
Quote from Koremutake home page http://shorl.com/koremutake:
In an attempt to temporarily solve the fact that human beings seem to be inable to remember important things (such as their names, car keys and seemingly random numbers with fourteen digits in 'em), we invented Koremutake.
It is, in plain language, a way to express any large number as a sequence of syllables. The general idea is that word-sounding pieces of information are a lot easier to remember than a sequence of digits.
int
decrypt(string
c
)
Decode a koremutake string into an integer.
string
encrypt(int
m
)
Encode an integer as a koremutake string.
MD2 is a message digest function constructed by Burton Kaliski, and is described in RFC 1319. It outputs message digests of 128 bits, or 16 octets.
inherit Nettle.MD2 : MD2
MD4 is a message digest function constructed by Ronald Rivest, and is described in RFC 1320. It outputs message digests of 128 bits, or 16 octets.
inherit Nettle.MD4 : MD4
MD5 is a message digest function constructed by Ronald Rivest, and is described in RFC 1321. It outputs message digests of 128 bits, or 16 octets.
string(7bit)
crypt_hash(string(8bit)
password
, string(7bit)
salt
, int
|void
rounds
)
This is a convenience alias for Nettle.crypt_md5()
,
that uses the same API as the other hashes.
The rounds
parameter is currently ignored.
For forward compatibility, either leave out,
or specify as 1000
.
Nettle.Hash()->crypt_hash()
, crypt_md5()
inherit Nettle.MD5 : MD5
Class representing an HCRYPTPROV handle.
Crypto.NT.CryptContext Crypto.NT.CryptContext(
string(8bit)
name
, string(8bit)
csp
, int
type
, int
flags
)
name
Key container name. When flags is set to CRYPT_VERIFYCONTEXT
the name must be 0
.
csp
The name of the Crypto Service Provider to use. If set to
0
the user default CSP will be used.
string(8bit)
read(int
size
, string(8bit)
|void
init
)
Retreive some random data. Calls CryptGenRandom in the NT API.
The plaintext algorithm.
This modules implements several of the crypto APIs, but without any crypto. It is intended to be used for testing of higher level algorithms.
inherit .AE : AE
Implements the empty AE algorithm.
inherit .MAC : MAC
Implements the empty MAC algorithm.
protected
constantstring
Crypto.None.mac_jwa_id
Implements the "none" JWS algorithm.
PGP stuff. See RFC 4880.
mapping
(string
:string
|mapping
) decode(string
s
)
Decodes PGP data.
mapping
(string
:mixed
) decode_radix64(string
data
)
Decode ASCII armour.
string
encode_radix64(string
data
, string
type
, void
|mapping
(string
:string
) extra
)
Encode PGP data with ASCII armour.
int
verify_signature(string
text
, string
sig
, string
pubkey
)
Verify text
against signature sig
with the public key
pubkey
.
Password handling.
This module handles generation and verification of password hashes.
verify()
, hash()
, crypt()
string(7bit)
hash(string(8bit)
password
, string(7bit)
|void
scheme
, int
|void
rounds
)
Generate a hash of password
suitable for verify()
.
password
Password to hash.
scheme
Password hashing scheme. If not specified the strongest available will be used.
If an unsupported scheme is specified an error will be thrown.
Supported schemes are:
Crypt(3C)-style:
| Use the strongest crypt(3C)-style hash that is supported. |
| |
| |
|
|
| |
|
|
| |
|
|
| |
|
|
LDAP (RFC2307)-style. Don't use these if you can avoid it, since they are suspectible to attacks. In particular avoid the unsalted variants at all costs:
|
|
| |
|
|
| |
|
|
| |
|
|
|
rounds
The number of rounds to use in parameterized schemes. If not specified the scheme specific default will be used.
Returns a string suitable for verify()
. This means that
the hashes will be prepended with the suitable markers.
Note that the availability of SHA512
depends on the version
of Nettle
that Pike has been compiled with.
This function was added in Pike 7.8.755.
verify()
, predef::crypt()
, Nettle.crypt_md5()
,
Nettle.Hash()->crypt_hash()
int
verify(string(8bit)
password
, string(8bit)
hash
)
Verify a password against a hash.
This function attempts to support most common
password hashing schemes. The hash
can be on any
of the following formats.
LDAP-style (RFC2307) hashes:
| The |
| The |
| The |
| The |
| The |
Crypt-style hashes:
| The string is interpreted according to the
"Unix crypt using SHA-256 and SHA-512" standard
Version 0.4 2008-4-3, where |
| This is the same algorithm as the one above, but with the
number of rounds specified by |
| The string is interpreted according to the
"Unix crypt using SHA-256 and SHA-512" standard
Version 0.4 2008-4-3, where |
| This is the same algorithm as the one above, but with the
number of rounds specified by |
| The string is interpreted according to the GNU libc2 extension
of |
| The |
| The empty password hash matches all passwords. |
Returns 1
on success, and 0
(zero) otherwise.
This function was added in Pike 7.8.755.
hash()
, predef::crypt()
RIPEMD160 is a hash function designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel, as a strengthened version of RIPEMD (which, like MD4 and MD5, fails the collision-resistance requirement). It produces message digests of 160 bits, or 20 octets.
inherit Nettle.RIPEMD160 : RIPEMD160
protected
State
`()(mapping
(string(8bit)
:Gmp.mpz
|int
)|void
params
)
Calling `() will return a State
object.
inherit Crypto.Sign : Sign
string(8bit)
name()
Returns the string "RSA"
.
bool
equal(Crypto.RSA.State from, mixed
other
)
Compares the keys of this RSA object with something other.
int
block_size()
Returns the crypto block size, or zero if not yet set.
__deprecated__
string(8bit)
cooked_get_d()
Returns the RSA private exponent (d) as a binary string, if known.
__deprecated__
string(8bit)
cooked_get_e()
Returns the RSA public exponent (e) as a binary string.
__deprecated__
string(8bit)
cooked_get_n()
Returns the RSA modulo (n) as a binary string.
__deprecated__
string(8bit)
cooked_get_p()
Returns the first RSA prime (p) as a binary string, if known.
__deprecated__
string(8bit)
cooked_get_q()
Returns the second RSA prime (q) as a binary string, if known.
__deprecated__
string(8bit)
cooked_sign(string(8bit)
digest
)
Signs digest
as raw_sign
and returns the signature as a byte
string.
Crypto.RSA.State Crypto.RSA.State(
mapping
(string(8bit)
:Gmp.mpz
|int
)|void
params
)
Can be initialized with a mapping with the elements n, e, d, p and q.
string(8bit)
crypt(string(8bit)
s
)
Encrypt or decrypt depending on set mode.
set_encrypt_key
, set_decrypt_key
string(8bit)
decrypt(string(8bit)
s
)
Decrypt a message encrypted with encrypt
.
string(8bit)
encrypt(string(8bit)
s
, function
(int
:string(8bit)
)|void
r
)
Pads the message s
with rsa_pad
type 2, signs it and returns
the signature as a byte string.
r
Optional random function to be passed down to rsa_pad
.
this_program
generate_key(int(128..)
bits
, void
|int
|Gmp.mpz
e
)
Generate a valid RSA key pair with the size bits
using the
random function set with set_random()
. The public exponent e
will be used, which defaults to 65537. Keys must be at least 89
bits.
variant
__deprecated__
this_program
generate_key(int(128..)
bits
, function
(int(0..)
:string(8bit)
) rnd
)
Compatibility with Pike 7.8.
Gmp.mpz
get_d()
Returns the RSA private exponent (d), if known.
Gmp.mpz
get_e()
Returns the RSA public exponent (e).
Gmp.mpz
get_n()
Returns the RSA modulo (n).
Gmp.mpz
get_p()
Returns the first RSA prime (p), if known.
Gmp.mpz
get_q()
Returns the second RSA prime (q), if known.
inherit ::this_program : this_program
array
(mapping
(string(7bit)
:string(7bit)
|int
)|string(8bit)
) jose_decode(string(7bit)
jws
)
Verify and decode a JOSE JWS RSASSA-PKCS-v1.5 signed value.
jws
A JSON Web Signature as returned by jose_sign()
.
Returns 0
(zero) on failure, and an array
Array | |
| The JOSE header. |
| The signed message. |
pkcs_verify()
, RFC 7515 section 3.5
string(7bit)
jose_sign(string(8bit)
message
, mapping
(string(7bit)
:string(7bit)
|int
)|void
headers
, .Hash
|void
h
)
Signs the message
with a JOSE JWS RSASSA-PKCS-v1.5 signature using hash
algorithm h
.
message
Message to sign.
headers
JOSE headers to use. Typically a mapping with a single element
"typ"
.
h
Hash algorithm to use. Currently defaults to SHA256
.
Returns the signature on success, and 0
(zero)
on failure (typically that the hash + salt combo is too
large for the RSA modulo).
pkcs_verify()
, salt_size()
, RFC 7515
mapping
(string(7bit)
:string(7bit)
) jwk(bool
|void
private_key
)
Generate a JWK-style mapping of the object.
private_key
If true, include the private key in the result.
Note that if the private key isn't known, the function
will fail (and return 0
).
Returns a JWK-style mapping on success, and 0
(zero)
on failure.
create()
, Web.encode_jwk()
, RFC 7517 section 4, RFC 7518 section 6.3
int(0..)
key_size()
Returns the size of the key in terms of number of bits.
string(8bit)
name()
Returns the string "RSA"
.
Sequence
pkcs_public_key()
Calls Standards.PKCS.RSA.build_public_key
with this object as
argument.
string(8bit)
pkcs_sign(string(8bit)
message
, .Hash
h
)
Signs the message
with a PKCS-1 signature using hash
algorithm h
. This is equivalent to
I2OSP(RSASP1(OS2IP(RSAES-PKCS1-V1_5-ENCODE(message)))) in PKCS#1
v2.2.
Sequence
pkcs_signature_algorithm_id(.Hash
hash
)
Calls Standards.PKCS.RSA.signatue_algorithm_id
with the
provided hash
.
bool
pkcs_verify(string(8bit)
message
, .Hash
h
, string(8bit)
sign
)
Verify PKCS-1 signature sign
of message message
using hash
algorithm h
.
bool
public_key_equal(this_program
rsa
)
Compares the public key of this RSA object with another RSA object.
Gmp.mpz
raw_sign(string(8bit)
digest
)
Pads the digest
with rsa_pad
type 1 and signs it. This is
equivalent to RSASP1(OS2IP(RSAES-PKCS1-V1_5-ENCODE(message))) in
PKCS#1 v2.2.
bool
raw_verify(string(8bit)
digest
, Gmp.mpz
s
)
Verifies the digest
against the signature s
, assuming pad
type 1.
rsa_pad
, raw_sign
Gmp.mpz
rsa_pad(string(8bit)
message
, int(1..2)
type
, function
(int(0..)
:string(8bit)
)|void
random
)
Pads the message
to the current block size with method
type
and returns the result as an integer. This is equivalent
to OS2IP(RSAES-PKCS1-V1_5-ENCODE(message)) in PKCS#1 v2.2.
type
| The message is padded with |
| The message is padded with random data, using the |
string(8bit)
rsa_unpad(Gmp.mpz
block
, int
type
)
Reverse the effect of rsa_pad
.
this_program
set_decrypt_key(array
(Gmp.mpz
) key
)
Sets the public key to key
and the mod to decryption.
set_encrypt_key
, crypt
this_program
set_encrypt_key(array
(Gmp.mpz
) key
)
Sets the public key to key
and the mode to encryption.
set_decrypt_key
, crypt
this_program
set_private_key(Gmp.mpz
|int
priv
, array
(Gmp.mpz
|int
)|void
extra
)
Sets the private key.
priv
The private RSA exponent, often called d.
extra
Array | |
| The first prime, often called p. |
| The second prime, often called q. |
this_program
set_public_key(Gmp.mpz
|int
modulo
, Gmp.mpz
|int
pub
)
Sets the public key.
modulo
The RSA modulo, often called n. This value needs to be >=12.
pub
The public RSA exponent, often called e.
this_program
set_random(function
(int(0..)
:string(8bit)
) r
)
Sets the random function, used to generate keys and parameters, to
the function r
. Default is Crypto.Random.random_string
.
This module contains a pseudo random number generator (PRNG) designed to give you the best possible random number generation. The current design is based on the Fortuna PRNG, but uses the system random source as input.
void
add_entropy(string(8bit)
data
)
Inject additional entropy into the random generator. One possible
use is to persist random data between executions of an
application. The internal state is approximately 256 bits, so
storing 32 bytes from random_string()
at shutdown and injecting
them through add_entropy()
agan at startup should carry over
the entropy. Note that this doesn't affect the independent
initialization that happens in the generator at startup, so the
output sequence will be different than if the application had
continued uninterrupted.
data
The random string.
Gmp.mpz
random(int
top
)
Returns a Gmp.mpz
object with a random value between 0
and top
. Uses random_string
.
string(8bit)
random_string(int
len
)
Returns a string of length len
with random content. The content
is generated by a Fortuna random generator that is updated with
output from /dev/urandom on UNIX and CryptGenRandom on NT.
The SALSA20 stream cipher.
inherit Nettle.SALSA20 : SALSA20
The SALSA20
stream cipher reduced to just 12 rounds.
inherit Nettle.SALSA20R12 : SALSA20R12
SHA1 is a hash function specified by NIST (The U.S. National Institute for Standards and Technology). It outputs hash values of 160 bits, or 20 octets.
inherit Nettle.SHA1 : SHA1
SHA224 is another hash function specified by NIST, intended as a
replacement for SHA1
, generating larger digests. It outputs hash
values of 224 bits, or 28 octets.
inherit Nettle.SHA224 : SHA224
SHA256 is another hash function specified by NIST, intended as a
replacement for SHA1
, generating larger digests. It outputs hash
values of 256 bits, or 32 octets.
inherit Nettle.SHA256 : SHA256
SHA384 is another hash function specified by NIST, intended as a
replacement for SHA1
, generating larger digests. It outputs hash
values of 384 bits, or 48 octets.
inherit Nettle.SHA384 : SHA384
SHA-3-224 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 224 bits, or 28 octets.
inherit Nettle.SHA3_224 : SHA3_224
SHA-3-256 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 256 bits, or 32 octets.
inherit Nettle.SHA3_256 : SHA3_256
SHA-3-386 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 256 bits, or 48 octets.
inherit Nettle.SHA3_384 : SHA3_384
SHA-3-512 is another hash function specified by NIST, intended as a replacement for SHA-2. It outputs hash values of 512 bits, or 64 octets.
inherit Nettle.SHA3_512 : SHA3_512
SHA512 is another hash function specified by NIST, intended as a
replacement for SHA1
, generating larger digests. It outputs hash
values of 512 bits, or 64 octets.
inherit Nettle.SHA512 : SHA512
SERPENT is one of the AES finalists, designed by Ross Anderson,
Eli Biham and Lars Knudsen. Thus, the interface and properties are
similar to AES
'. One peculiarity is that it is quite pointless to
use it with anything but the maximum key size, smaller keys are
just padded to larger ones.
inherit Nettle.SERPENT : SERPENT
Another AES
finalist, this one designed by Bruce Schneier and
others.
inherit Nettle.Twofish : Twofish
Implements Digital Video Broadcasting interface
Only Linux version is supported.
Object for controlling an audio subsystem on full featured cards.
DVB.Audio DVB.Audio(
int
card_number
)
DVB.Audio DVB.Audio()
Create a Audio object.
card_number
The number of card equipment.
int
mixer(int
left
, int
right
)
int
mixer(int
both
)
Sets output level on DVB audio device.
int
mute(int
mute
)
int
mute()
Mute or unmute audio device.
mapping
status()
Returns mapping of current audio device status.
Represents an elementary data stream (PES).
void
close()
Closes an open stream.
read()
int
destroy()
Purge a stream reader.
DVB.dvb()->stream()
, read()
string
|int
read()
Read data from a stream. It reads up to read buffer size data.
Read buffer size is 4096 by default.
DVB.dvb()->stream()
, close()
Main class.
mapping
analyze_pat()
Return mapping of all PMT.
sid:prognum
array
(mapping
)|int
analyze_pmt(int
sid
, int
prognum
)
Parse PMT table.
analyze_pat()
DVB.dvb DVB.dvb(
int
card_number
)
Create a DVB object.
card_number
The number of card equipment.
The number specifies which device will be opened. Ie. /dev/ost/demux0, /dev/ost/demux1 ... for DVB v0.9.4 or /dev/dvb/demux0, /dev/dvb/demux1 ... for versions 2.0+
mapping
fe_info()
Return info of a frondend device.
The information heavily depends on driver. Many fields contain dumb values.
mapping
|int
fe_status()
Return status of a DVB object's frondend device.
The resulting mapping contains the following fields:
| If 1 the frontend is powered up and is ready to be used. |
| If 1 the frontend detects a signal above a normal noise level |
| If 1 the frontend successfully locked to a DVB signal |
| If 1 carrier dectected in signal |
| If 1 then lock at viterbi state |
| If 1 then TS sync byte detected |
| If 1 then tuner has a frequency lock |
mapping
|int
get_pids()
Returns mapping with info of currently tuned program's pids.
tune()
DVB.Stream
stream(int
pid
, int
|function
(:void
) rcb
, int
ptype
)
DVB.Stream
stream(int
pid
, int
|function
(:void
) rcb
)
DVB.Stream
stream(int
pid
)
Create a new stream reader object for PID.
pid
PID of stream.
rcb
Callback function called whenever there is the data to read from stream. Only for nonblocking mode.
ptype
Type of payload data to read. By default, audio data is fetched.
Setting async callback doesn't set the object to nonblocking state.
DVB.Stream()->read()
int
tune(int(2bit)
lnb
, int
freq
, bool
|string
pol
, int
sr
)
Tunes to apropriate transponder's parameters.
lnb
DiSeQc number of LNB.
freq
Frequency divided by 1000.
pol
Polarization. 0
or "v"
for vertical type,
1
or "h"
for horizontal one.
sr
The service rate parameter.
int(0..)
assembler_debug(int(0..)
level
)
Set the assembler debug level.
The old assembler debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
int(0..)
compiler_trace(int(0..)
level
)
Set the compiler trace level.
The old compiler trace level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mapping
(string
:int
) count_objects()
Returns the number of objects of every kind in memory.
int(0..)
debug(int(0..)
level
)
Set the run-time debug level.
The old debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mixed
describe(mixed
x
)
Prints out a description of the thing x
to standard error.
The description contains various internal info associated with
x
.
This function only exists if the Pike runtime has been compiled with RTL debug.
int
describe_encoded_value(string
data
)
Describe the contents of an encode_value()
string.
Returns the number of encoding errors that were detected (if any).
array
(array
(int
|string
|type
)) describe_program(program
p
)
Debug function for showing the symbol table of a program.
Returns an array of arrays with the following information
for each symbol in p
:
Array | |
| Bitfield with the modifiers for the symbol. |
| Name of the symbol. |
| Value type for the symbol. |
| Type of symbol. |
| Offset into the code or data area for the symbol. |
| Offset in the inherit table to the inherit containing the symbol. |
| Depth in the inherit tree for the inherit containing the symbol. |
The API for this function is not fixed, and has changed since Pike 7.6. In particular it would make sense to return an array of objects instead, and more information about the symbols might be added.
void
disassemble(function
(:void
) fun
)
Disassemble a Pike function to Stdio.stderr
.
This function is only available if the Pike runtime has been compiled with debug enabled.
void
dmalloc_set_name(string
filename
, int(1..)
linenumber
)
Only available when compiled with dmalloc.
void
dump_backlog()
Dumps the 1024 latest executed opcodes, along with the source
code lines, to standard error. The backlog is only collected on
debug level 1 or higher, set with _debug
or with the -d
argument on the command line.
This function only exists if the Pike runtime has been compiled with RTL debug.
void
dump_dmalloc_locations(string
|array
|mapping
|multiset
|function
(:void
)|object
|program
|type
o
)
Only available when compiled with dmalloc.
void
dump_program_tables(program
p
, int(0..)
|void
indent
)
Dumps the internal tables for the program p
on stderr.
p
Program to dump.
indent
Number of spaces to indent the output.
In Pike 7.8.308 and earlier indent
wasn't supported.
void
gc_set_watch(array
|multiset
|mapping
|object
|function
(:void
)|program
|string
x
)
Sets a watch on the given thing, so that the gc will print a message whenever it's encountered. Intended to be used together with breakpoints to debug the garbage collector.
This function only exists if the Pike runtime has been compiled with RTL debug.
mapping
(string
:int
|float
) gc_status()
Get statistics from the garbage collector.
A mapping with the following content will be returned:
| Number of arrays, mappings, multisets, objects and programs. |
| Number of memory allocations since the last gc run. |
| Threshold for "num_allocs" when another automatic gc run is scheduled. |
| Estimation of the current amount of garbage. |
| Decaying average over the number of allocated objects between gc runs. |
| Decaying average over the number of freed objects in each gc run. |
| Garbage ratio in the last gc run. |
| Decaying average over the interval between gc runs, measured in real time nanoseconds. |
| Decaying average over the length of the gc runs, measured in real time nanoseconds. |
| The garbage accumulation goal that the gc aimed for when
setting "alloc_threshold" in the last run. The value is
either "garbage_ratio_low", "garbage_ratio_high" or
"garbage_max_interval". The first two correspond to the gc
parameters with the same names in |
| Time when the garbage-collector last ran. |
| The total amount of CPU time that has been consumed in implicit GC runs, in nanoseconds. 0 on systems where Pike lacks support for CPU time measurement. |
| The total amount of real time that has been spent in implicit GC runs, in nanoseconds. |
gc()
, Pike.gc_parameters()
, Pike.implicit_gc_real_time
mapping
Debug.globals
Can be custom filled from within your program in order to
have global references to explore live datastructures using
Inspect
; comes preinitialised with the empty mapping, ready for use.
void
list_open_fds()
Only available when compiled with dmalloc.
void
locate_references(string
|array
|mapping
|multiset
|function
(:void
)|object
|program
|type
o
)
This function is mostly intended for debugging. It will search through
all data structures in Pike looking for o
and print the
locations on stderr. o
can be anything but int
or
float
.
This function only exists if the Pike runtime has been compiled with RTL debug.
int
map_all_objects(function
(object
:void
) cb
)
Call cb for all objects that currently exist. The callback will not be called with destructed objects as it's argument.
Objects might be missed if cb
creates new objects or destroys
old ones.
This function is only intended to be used for debug purposes.
The total number of objects
next_object()
, find_all_clones()
mapping
(string
:int
) memory_usage()
Check memory usage.
This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use.
The entries in the mapping are typically paired, with one
named "num_" + SYMBOL + "s"
containing a count,
and the other named SYMBOL + "_bytes"
containing
a best effort approximation of the size in bytes.
Exactly what fields this function returns is version dependant.
_verify_internals()
int(0..)
optimizer_debug(int(0..)
level
)
Set the optimizer debug level.
The old optimizer debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
string
pp_memory_usage()
Returns a pretty printed version of the
output from memory_usage
.
string
pp_object_usage()
Returns a pretty printed version of the output from
count_objects
(with added estimated RAM usage)
void
reset_dmalloc()
Only available when compiled with dmalloc.
int
size_object(object
o
)
Return the aproximate size of the object, in bytes. This might not work very well for native objects
The function tries to estimate the memory usage of variables belonging to the object.
It will not, however, include the size of objects assigned to variables in the object.
If the object has a lfun::_size_object()
it will be called
without arguments, and the return value will be added to the final
size. It is primarily intended to be used by C-objects that
allocate memory that is not normally visible to pike.
lfun::_size_object()
, sizeof()
void
verify_internals()
Perform sanity checks.
This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.
This function does a more thorough check if the Pike runtime has been compiled with RTL debug.
Allows for interactive debugging and live data structure inspection
in both single- and multi-threaded programs.
Creates an independent background thread that every pollinterval
will show a list of running threads.
Optionally, a triggersignal
can be specified which allows the dump to
be triggered by a signal.
Example: In the program you'd like to inspect, insert the following one-liner:
Debug.Inspect("/tmp/test.pike");
Then start the program and keep it running. Next you create a /tmp/test.pike with the following content:
void create() {
werror("Only once per modification of test.pike\n");
}
int main() {
werror("This will run every iteration\n");
werror("By returning 1 here, we disable the stacktrace dumps\n");
return 0;
}
void destroy() {
werror("destroy() runs just as often as create()\n");
}
Whenever you edit /tmp/test.pike, it will automatically reload the file.
string
|function
(void
:void
) Debug.Inspect._callback
Either the callback function which is invoked on each iteration, or the name of a file which contains a class which is (re)compiled automatically and called on each iteration.
create
Thread.Thread
Debug.Inspect._loopthread
The inspect-thread. It will not appear in the displayed thread-list.
Debug.Inspect Debug.Inspect(
string
|function
(void
:void
)|void
cb
)
Starts up the background thread.
cb
Specifies either the callback function which is invoked on each iteration,
or the
name of a file which contains a class which is (re)compiled automatically
with an optional main()
method, which will be called on each
iteration.
If the main()
method returns 0, new stacktraces will be dumped
every iteration; if it returns 1, stacktrace dumping will be suppressed.
The compilation and the running of the callback is guarded by a catch(), so that failures (to compile) in that section will not interfere with the running program.
If the list of running threads did not change, displaying the list again will be suppressed.
triggersignal
, pollinterval
, _loopthread
, _callback
,
Debug.globals
void
inspect()
The internal function which does all the work each pollinterval. Run it directly to force a thread-dump.
int
Debug.Inspect.pollinterval
The polling interval in seconds, defaults to 4.
int
Debug.Inspect.triggersignal
If assigned to, it will allow the diagnostics inspection to be triggered by this signal.
This is a probe subject which you can send in somewhere to get probed (not to be confused with a probe object, which does some active probing). All calls to LFUNs will be printed to stderr. It is possible to name the subject by passing a string as the first and only argument when creating the subject object.
> object s = Debug.Subject(); create() > random(s); _random() (1) Result: 0 > abs(s); `<(0) _sprintf(79, ([ "indent":2 ])) (2) Result: Debug.Subject > abs(class { inherit Debug.Subject; int `<(mixed ... args) { return 1; } }()); create() `-() destroy() (3) Result: 0 > pow(s,2); `[]("pow") Attempt to call the NULL-value Unknown program: 0(2)
A class that when instatiated will turn on trace, and when it's destroyed will turn it off again.
Debug.Tracer Debug.Tracer(
int
level
)
Sets the level of debug trace to level
.
This wrapper can be placed around another object to get printouts about what is happening to it. Only a few LFUNs are currently supported.
> object x=Debug.Wrapper(Crypto.MD5()); Debug.Wrapper is proxying ___Nettle.MD5_State() > x->name(); ___Nettle.MD5_State()->name (1) Result: "md5" > !x; !___Nettle.MD5_State() (2) Result: 0
array
indices( Debug.Wrapper arg )
int
sizeof( Debug.Wrapper arg )
string sprintf(string format, ... Debug.Wrapper arg ... )
array
values( Debug.Wrapper arg )
bool
res = !Debug.Wrapper()
mixed
res = Debug.Wrapper()
->X
mixed
res = Debug.Wrapper()
[ x
]
Debug.Wrapper Debug.Wrapper(
object
x
)
void
display(int
|void
num
, string
|array
(string
)|void
pattern
, string
|array
(string
)|void
exclude
)
Show profiling information in a more-or-less readable manner. This only works if pike has been compiled with profiling support.
The function will print to stderr using werror.
This is mainly here for use from the Debug.Watchdog
class, if
you want to do your own formatting or output to some other channel
use get_prof_info
instead.
array
(array
(string
|float
|int
)) get_prof_info(string
|array
(string
)|void
include
, string
|array
(string
)|void
exclude
)
Collect profiling data.
This will return the CPU usage, by function, since the last time the function was called.
The returned array contains the following entries per entry:
Array | |
| The name of the function |
| The number of calls |
| The self CPU time |
| The self CPU time, including children. |
| The self CPU time as percentage of total time. |
| The self CPU time, including children, as percentage of total time. |
| This is the location in the source of the start of the function |
The CompilerEnvironment
object that is used
for loading C-modules and by predef::compile()
.
predef::compile()
is essentially an alias for the
CompilerEnvironment()->compile()
in this object.
CompilerEnvironment
, predef::compile()
object
mkerror(mixed
error
)
Returns an Error object for any argument it receives. If the argument already is an Error object or is empty, it does nothing.
Class for exception objects for errors of unspecified type.
bool
res = is_type(Error.Generic()
)
Claims that the error object is an array, for compatibility with old style error handling code.
string sprintf(string format, ... Error.Generic arg ... )
array
|string
res = Error.Generic()
[ index
]
Index operator.
Simulates an array
Array | |
| Error message as returned by |
| Backtrace as returned by |
The error message is always terminated with a newline.
backtrace()
array
backtrace()
Return the backtrace where the error occurred. Normally simply
returns error_backtrace
.
predef::backtrace()
(
array
)Error.Generic()
Cast operator.
The only supported type to cast to is "array"
, which
generates an old-style error ({
.message
(),
backtrace
()})
Error.Generic Error.Generic(
string
message
, void
|array
(backtrace_frame
|array
(mixed
)) backtrace
)
string
describe()
Return a readable error report that includes the backtrace.
array
(backtrace_frame
|array
(mixed
)) Error.Generic.error_backtrace
The backtrace as returned by backtrace
where the error
occurred.
Code that catches and rethrows errors should ensure that this remains the same in the rethrown error.
string
Error.Generic.error_message
The error message. It always ends with a newline ('\n'
)
character and it might be more than one line.
Code that catches and rethrows errors may extend this with more error information.
string
message()
Return a readable message describing the error. Normally simply
returns error_message
.
If you override this function then you should ensure that
error_message
is included in the returned message, since there
might be code that catches your error objects, extends
error_message
with more info, and rethrows the error.
function
(:void
) `()(void
|string
path
)
FIXME: Document this function
program
get_filesystem(string
what
)
FIXME: Document this function
int
parse_mode(int
old
, int
|string
mode
)
FIXME: Document this function
Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.
int
apply()
FIXME: Document this function
Base
cd(string
|void
directory
)
Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.
void
chmod(string
filename
, int
|string
mode
)
Change mode of a file or directory.
void
chown(string
filename
, int
|object
owner
, int
|object
group
)
Change ownership of the file or directory
Base
chroot(void
|string
directory
)
Change the root of the filesystem.
string
cwd()
Returns the current working directory within the filesystem.
array
find(void
|function
(Stat
:int
) mask
, mixed
... extra
)
FIXME: Document this function
array
(string
) get_dir(void
|string
directory
, void
|string
|array
glob
)
Returns an array of all files and directories within a given directory.
directory
Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.
glob
Return only files and dirs matching the glob (if given).
[get_stats]
array
(Stat
) get_stats(void
|string
directory
, void
|string
|array
glob
)
Returns stat-objects for the files and directories matching the given glob within the given directory.
[get_dir]
int
mkdir(string
directory
, void
|int
|string
mode
)
Create a new directory
Stdio.File
open(string
filename
, string
mode
)
Open a file within the filesystem
A Stdio.File object.
int
rm(string
filename
)
Remove a file from the filesystem.
Stat
stat(string
file
, int
|void
lstat
)
Return a stat-object for a file or a directory within the filesystem.
Describes the stat of a file
void
attach_statarray(array
(int
) a
)
Fills the stat-object with data from a Stdio.File.stat() call.
object
cd()
Change to the stated directory.
the directory if the stated object was a directory, 0 otherwise.
bool
Filesystem.Stat.isblk
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.ischr
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isdir
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isdoor
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isfifo
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.islnk
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isreg
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.issock
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
string
nice_date()
Returns the date of the stated object as cleartext.
Stdio.File
open(string
mode
)
Open the stated file within the filesystem
a [Stdio.File] object
[Stdio.File]
void
set_type(string
x
)
Set a type for the stat-object.
This call doesnot change the filetype in the underlaying filesystem.
x
Type to set. Type is one of the following:
[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]
Implements an abstraction of the normal filesystem.
Filesystem.System Filesystem.System(
void
|string
directory
, void
|string
root
, void
|int
fast
, void
|Filesystem.Base
parent
)
Instanciate a new object representing the filesystem.
directory
The directory (in the real filesystem) that should become the root of the filesystemobject.
root
Internal
fast
Internal
parent
Internal
inherit Filesystem.Base : Base
Iterator object that traverses a directory tree and returns files as values and paths as indices. Example that uses the iterator to create a really simple sort of make:
object i=Filesystem.Traversion("."); foreach(i; string dir; string file) { if(!has_suffix(file, ".c")) continue; file = dir+file; string ofile = file; ofile[-1]='o'; object s=file_stat(ofile); if(s && i->stat()->mtime<s->mtime) continue; // compile file }
Filesystem.Traversion Filesystem.Traversion(
string
path
, void
|bool
symlink
, void
|bool
ignore_errors
, void
|function
(array
:array
) sort_fun
)
path
The root path from which to traverse.
symlink
Don't traverse symlink directories.
ignore_errors
Ignore directories that can not be accessed.
sort_fun
Sort function to be applied to directory entries before traversing. Can also be a filter function.
float
progress(void
|float
share
)
Returns the current progress of the traversion as a value between 0.0 and 1.0. Note that this value isn't based on the number of files, but the directory structure.
Stdio.Stat
stat()
Returns the stat for the current index-value-pair.
Basic filesystem monitor.
This module is intended to be used for incremental scanning of a filesystem.
Supports FSEvents on MacOS X and Inotify on Linux to provide low overhead monitoring; other systems use a less efficient polling approach.
Filesystem.Monitor.symlinks
, System.FSEvents
, System.Inotify
protected
void
adjust_monitor(Monitor
m
)
Update the position in the monitor_queue
for the monitor m
to account for an updated next_poll value.
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute changed callback.
path
Path of the file or directory which has changed attributes.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
Overload this to do something useful.
protected
Pike.Backend
Filesystem.Monitor.basic.backend
Backend to use.
If 0
(zero) - use the default backend.
protected
void
backend_check()
Backend check callback function.
This function is intended to be called from a backend,
and performs a check()
followed by rescheduling
itself via a call to set_nonblocking()
.
check()
, set_nonblocking()
protected
string
canonic_path(string
path
)
Canonicalize a path.
path
Path to canonicalize.
The default implementation returns combine_path(path, ".")
,
i.e. no trailing slashes.
int
check(int
|void
max_wait
, int
|void
max_cnt
, mapping
(string
:int
)|void
ret_stats
)
Check for changes.
max_wait
Maximum time in seconds to wait for changes. -1
for infinite wait.
max_cnt
Maximum number of paths to check in this call. 0
(zero) for unlimited.
ret_stats
Optional mapping that will be filled with statistics (see below).
A suitable subset of the monitored files will be checked for changes.
The function returns when either a change has been detected
or when max_wait
has expired. The returned value indicates
the number of seconds until the next call of check()
.
If ret_stats
has been provided, it will be filled with
the following entries:
| The total number of active monitors when the scan completed. |
| The number of monitors that were scanned for updates during the call. |
| The number of monitors that were updated during the call. |
| The number of seconds that the call slept. |
Any callbacks will be called from the same thread as the one
calling check()
.
check_all()
, monitor()
void
check_all(mapping
(string
:int
)|void
ret_stats
)
Check all monitors for changes.
ret_stats
Optional mapping that will be filled with statistics (see below).
All monitored paths will be checked for changes.
You typically don't want to call this function, but instead
check()
.
Any callbacks will be called from the same thread as the one
calling check()
.
check()
, monitor()
protected
bool
check_monitor(Monitor
m
, MonitorFlags
|void
flags
)
Check a single Monitor
for changes.
m
Monitor
to check.
flags
| Don't recurse. |
| Check all monitors for the entire subtree rooted in |
This function is called by check()
for the Monitor
s
it considers need checking. If it detects any changes an
appropriate callback will be called.
Returns 1
if a change was detected and 0
(zero)
otherwise.
Any callbacks will be called from the same thread as the one
calling check_monitor()
.
The return value can not be trusted to return 1
for all
detected changes in recursive mode.
check()
, data_changed()
, attr_changed()
, file_created()
,
file_deleted()
, stable_data_change()
void
clear()
Clear the set of monitored files and directories.
Due to circular datastructures, it's recomended to call this function prior to discarding the object.
protected
mixed
Filesystem.Monitor.basic.co_id
Call-out identifier for backend_check()
if in
nonblocking mode.
set_nonblocking()
, set_blocking()
Filesystem.Monitor.basic Filesystem.Monitor.basic(
int
|void
max_dir_check_interval
, int
|void
file_interval_factor
, int
|void
stable_time
)
Create a new monitor.
max_dir_check_interval
Override of default_max_dir_check_interval
.
file_interval_factor
Override of default_file_interval_factor
.
stable_time
Override of default_stable_time
.
void
data_changed(string
path
)
File content changed callback.
path
Path of the file which has had content changed.
This function is called when a change has been detected for a monitored file.
Called by check()
and check_monitor()
.
Overload this to do something useful.
protected
constantint
Filesystem.Monitor.basic.default_file_interval_factor
The default factor to multiply default_max_dir_check_interval
with to get the maximum number of seconds between checks of files.
The value can be changed by calling create()
.
The value can be overridden for individual files or directories
by calling monitor()
.
Overload this constant to change the default.
protected
constantint
Filesystem.Monitor.basic.default_max_dir_check_interval
The default maximum number of seconds between checks of directories in seconds.
This value is multiplied with default_file_interval_factor
to
get the corresponding default maximum number of seconds for files.
The value can be changed by calling create()
.
The value can be overridden for individual files or directories
by calling monitor()
.
Overload this constant to change the default.
protected
constantint
Filesystem.Monitor.basic.default_stable_time
The default minimum number of seconds without changes for a change
to be regarded as stable (see stable_data_change()
.
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
path
Path of the new file or directory.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check()
and check_monitor()
.
Overload this to do something useful.
void
file_deleted(string
path
)
File deletion callback.
path
Path of the new file or directory that has been deleted.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check()
and check_monitor()
.
Overload this to do something useful.
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
path
Path of the file or directory.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
Overload this to do something useful.
protected
void
inotify_event(int
wd
, int
event
, int
cookie
, string(8bit)
path
)
Event callback for Inotify.
bool
is_monitored(string
path
)
Check whether a path is monitored or not.
path
Path to check.
Returns 1
if there is a monitor on path
,
and 0
(zero) otherwise.
monitor()
, release()
protected
void
low_eventstream_callback(string
path
, int
flags
, int
event_id
)
This function is called when the FSEvents EventStream detects a change in one of the monitored directories.
Monitor
|void
monitor(string
path
, MonitorFlags
|void
flags
, int(0..)
|void
max_dir_check_interval
, int(0..)
|void
file_interval_factor
, int(0..)
|void
stable_time
)
Register a path
for monitoring.
path
Path to monitor.
flags
| Don't recurse. |
| Monitor the entire subtree, and any directories or files that may appear later. |
| Monitor the entire subtree, and any directories
or files that may appear later. Remove the monitor
automatically when |
max_dir_check_interval
Override of default_max_dir_check_interval
for this path
or subtree.
file_interval_factor
Override of default_file_interval_factor
for this path
or subtree.
stable_time
Override of default_stable_time
for this path
or subtree.
release()
protected
DefaultMonitor
monitor_factory(string
path
, MonitorFlags
|void
flags
, int(0..)
|void
max_dir_check_interval
, int(0..)
|void
file_interval_factor
, int(0..)
|void
stable_time
)
Create a new Monitor
for a path
.
This function is called by monitor()
to create a new Monitor
object.
The default implementation just calls DefaultMonitor
with the
same arguments.
monitor()
, DefaultMonitor
protected
Thread.Mutex
Filesystem.Monitor.basic.monitor_mutex
Mutex controlling access to monitor_queue
.
protected
ADT.Heap
Filesystem.Monitor.basic.monitor_queue
Heap containing active Monitor
s that need polling.
The heap is sorted on Monitor()->next_poll
.
protected
mapping
(string
:Monitor
) Filesystem.Monitor.basic.monitors
Mapping from monitored path to corresponding Monitor
.
The paths are normalized to canonic_path(path)
,
All filesystems are handled as if case-sensitive. This should not be a problem for case-insensitive filesystems as long as case is maintained.
void
release(string
path
, MonitorFlags
|void
flags
)
Release a path
from monitoring.
path
Path to stop monitoring.
flags
| Don't recurse. |
| Release the entire subtree. |
| Release the entire subtree, but only those paths that were added automatically by a recursive monitor. |
monitor()
protected
void
release_monitor(Monitor
m
)
Release a single Monitor
from monitoring.
release()
protected
void
report(SeverityLevel
level
, string(7bit)
fun
, sprintf_format
format
, sprintf_args
... args
)
Event tracing callback.
level
Severity level of the event.
fun
Name of the function that called report()
.
format
sprintf()
formatting string describing the event.
args
Optional extra arguments for the format
string.
This function is called in various places to provide granular tracing of the monitor state.
The default implementation calls werror()
with
format
and args
if level
is ERROR
or higher,
or if FILESYSTEM_MONITOR_DEBUG has been defined.
protected
void
reschedule_backend_check(int
|void
suggested_t
)
Reschedule beckend check.
suggested_t
Suggested time in seconds until next call of check()
.
Register suitable callbacks with the backend to automatically
call check()
.
check()
and thus all the callbacks will be called from the
backend thread.
void
set_backend(Pike.Backend
|void
backend
)
Change backend.
backend
Backend to use. 0
(zero) for the default backend.
void
set_blocking()
Turn off nonblocking mode.
set_nonblocking()
void
set_file_interval_factor(int
file_interval_factor
)
Set the file_interval_factor
.
void
set_max_dir_check_interval(int
max_dir_check_interval
)
Set the max_dir_check_interval
.
void
set_nonblocking(int
|void
suggested_t
)
Turn on nonblocking mode.
suggested_t
Suggested time in seconds until next call of check()
.
Register suitable callbacks with the backend to automatically
call check()
.
check()
and thus all the callbacks will be called from the
backend thread.
If nonblocking mode is already active, this function will be a noop.
set_blocking()
, check()
.
void
set_stable_time(int
stable_time
)
Set the stable_time
.
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
path
Path of the file or directory that has stopped changing.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
Called by check()
and check_monitor()
.
Overload this to do something useful.
Flags for Monitor
s.
This symbol evaluates to the Monitor
class used by
the default implementation of monitor_factory()
.
It is currently one of the values Monitor
, EventStreamMonitor
or InotifyMonitor
.
monitor_factory()
inherit Monitor : Monitor
FSEvents EventStream-accelerated Monitor
.
inherit Monitor : Monitor
Inotify-accelerated Monitor
.
inherit Monitor : Monitor
Monitoring information for a single filesystem path.
monitor()
protected
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute or content changed callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
void
bump(MonitorFlags
|void
flags
, int
|void
seconds
)
Bump the monitor to an earlier scan time.
flags
| Don't recurse. |
| Check all monitors for the entire subtree. |
seconds
Number of seconds from now to run next scan. Defaults to half of the remaining interval.
protected
void
call_callback(function
(string
, Stdio.Stat
|void
:void
) cb
, string
path
, Stdio.Stat
|void
st
)
Call a notification callback.
cb
Callback to call or UNDEFINED
for no operation.
path
Path to notify on.
st
Stat for the path
.
bool
check(MonitorFlags
|void
flags
)
Check for changes.
flags
| Don't recurse. |
| Check all monitors for the entire subtree rooted in |
This function is called by check()
for the Monitor
s
it considers need checking. If it detects any changes an
appropriate callback will be called.
Returns 1
if a change was detected and 0
(zero)
otherwise.
Any callbacks will be called from the same thread as the one
calling check_monitor()
.
The return value can not be trusted to return 1
for all
detected changes in recursive mode.
check()
, data_changed()
, attr_changed()
, file_created()
,
file_deleted()
, stable_data_change()
void
check_for_release(int
mask
, int
flags
)
Check if this monitor should be removed automatically.
Filesystem.Monitor.basic.Monitor Filesystem.Monitor.basic.Monitor(
string
path
, MonitorFlags
flags
, int
max_dir_check_interval
, int
file_interval_factor
, int
stable_time
)
protected
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check()
and check_monitor()
.
protected
void
file_deleted(string
path
, Stdio.Stat
|void
old_st
)
File deletion callback.
path
Path of the new file or directory that has been deleted.
old_st
Stat for the file prior to deletion (if known). Note that this argument is not passed along to top level function.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check()
and check_monitor()
.
protected
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
string
Filesystem.Monitor.basic.Monitor.path
MonitorFlags
Filesystem.Monitor.basic.Monitor.flags
int
Filesystem.Monitor.basic.Monitor.max_dir_check_interval
int
Filesystem.Monitor.basic.Monitor.file_interval_factor
int
Filesystem.Monitor.basic.Monitor.stable_time
inherit ADT.Heap.Element : Element
protected
void
monitor(string
path
, int
flags
, int
max_dir_interval
, int
file_interval_factor
, int
stable_time
)
Called to create a sub monitor.
this_program
parent()
Returns the parent monitor, or UNDEFINED if no such monitor exists.
protected
void
register_path(int
|void
initial
)
Register the Monitor
with the monitoring system.
initial
Indicates that the Monitor
is newly created.
protected
void
report(SeverityLevel
level
, string(7bit)
fun
, sprintf_format
format
, sprintf_args
... args
)
Event tracing callback.
level
Severity level of the event.
fun
Name of the function that called report()
.
format
sprintf()
formatting string describing the event.
args
Optional extra arguments for the format
string.
This function is called in various places to provide granular tracing of the monitor state.
The default implementation just calls global::report()
with the same arguments.
protected
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
Called by check()
and check_monitor()
.
protected
bool
status_change(Stdio.Stat
old_st
, Stdio.Stat
st
, int
orig_flags
, int
flags
)
Called when the status has changed for an existing file.
void
submonitor_released(this_program
submon
)
To be called when a (direct) submonitor is released.
protected
void
unregister_path(int
|void
dying
)
Unregister the Monitor
from the monitoring system.
dying
Indicates that the Monitor
is being destructed.
It is the destruction cause value offset by one.
protected
void
update(Stdio.Stat
st
)
Calculate and set a suitable time for the next poll of this monitor.
st
New stat for the monitor.
This function is called by check()
to schedule the
next check.
Debugging filesystem monitor.
This module behaves as symlinks
, but has default implementations
of all callbacks that call report()
, as well as an implementation
of [report()] that logs everything to Stdio.stderr
.
Filesystem.Monitor.basic
, Filesystem.Monitor.symlinks
mapping
(string
:Monitor
) get_monitors()
Return the set of active monitors.
inherit "symlinks.pike" : "symlinks.pike"
Filesystem monitor with support for symbolic links.
This module extends Filesystem.Monitor.basic
with
support for symbolic links.
For operating systems where symbolic links aren't supported,
this module will behave exactly like Filesystem.Monitor.basic
.
Filesystem.Monitor.basic
protected
int
allocate_symlink(string
sym
)
Allocates a symlink id for the link sym
.
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute changed callback.
path
Path of the file or directory which has changed attributes.
st
Status information for path
as obtained by file_stat(path)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Overload this to do something useful.
protected
int
Filesystem.Monitor.symlinks.available_ids
Bitmask of all unallocated symlink ids.
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
path
Path of the new file or directory.
st
Status information for path
as obtained by file_stat(path)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Called by check()
and check_monitor()
.
Overload this to do something useful.
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
path
Path of the file or directory.
st
Status information for path
as obtained by file_stat(path)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
Overload this to do something useful.
inherit Filesystem.Monitor.basic : basic
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
path
Path of the file or directory that has stopped changing.
st
Status information for path
as obtained by file_stat(path)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Called by check()
and check_monitor()
.
Overload this to do something useful.
protected
mapping
(string
:int
) Filesystem.Monitor.symlinks.symlink_ids
Mapping from symlink name to symlink id.
protected
mapping
(string
:string
) Filesystem.Monitor.symlinks.symlink_targets
Mapping from symlink name to symlink target.
Monitoring information for a single filesystem path.
With support for expansion of symbolic links.
monitor()
protected
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute or content changed callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
protected
void
call_callback(function
(string
, mixed
... :void
) cb
, string
path
, Stdio.Stat
|void
st
)
Call a notification callback and handle symlink expansion.
cb
Callback to call or UNDEFINED
for no operation.
extras
Extra arguments after the path
argument to cb
.
void
check_for_release(int
mask
, int
flags
)
Check if this monitor should be removed automatically.
protected
void
check_symlink(string
path
, Stdio.Stat
st
, int
|void
inhibit_notify
)
Check whether a symlink has changed.
protected
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check()
and check_monitor()
.
protected
void
file_deleted(string
path
, Stdio.Stat
old_st
)
File deletion callback.
path
Path of the new file or directory that has been deleted.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check()
and check_monitor()
.
protected
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
inherit basic::DefaultMonitor : DefaultMonitor
Based on Filesystem.Monitor.basic.DefaultMonitor
.
void
low_call_callback(function
(string
, mixed
... :void
) cb
, mapping
(string
:int
) state
, mapping
(string
:string
) symlink_targets
, string
path
, Stdio.Stat
|void
st
, string
|void
symlink
)
Call a notification callback and handle symlink expansion.
cb
Callback to call or UNDEFINED
for no operation.
state
State mapping to avoid multiple notification and infinite loops. Call with an empty mapping.
symlinks
Symlinks that have not been expanded yet.
path
Path to notify on.
extras
Extra arguments to cb
.
symlink
Symbolic link that must have been followed for the callback to be called.
protected
void
monitor(string
path
, int
flags
, int
max_dir_interval
, int
file_interval_factor
, int
stable_time
)
Called to create a sub monitor.
protected
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
Called by check()
and check_monitor()
.
protected
bool
status_change(Stdio.Stat
old_st
, Stdio.Stat
st
, int
orig_flags
, int
flags
)
Called when the status has changed for an existing file.
int
Filesystem.Monitor.symlinks.DefaultMonitor.symlinks
Mask of symlink ids that can reach this monitor.
protected
void
zap_symlink(string
path
)
Called when the symlink path
is no more.
Filesystem which can be used to mount a Tar file.
Two kinds of extended tar file records are supported:
| POSIX ustar (Version 0?). |
| GNU tar (POSIX draft) |
For a quick start, you probably want to use `()()
.
`()()
constant
int
Filesystem.Tar.EXTRACT_CHOWN
Set owning user and group from the tar records.
constant
int
Filesystem.Tar.EXTRACT_ERR_ON_UNKNOWN
Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise.
constant
int
Filesystem.Tar.EXTRACT_SKIP_EXT_MODE
Don't set set-user-ID, set-group-ID, or sticky bits from the tar records.
constant
int
Filesystem.Tar.EXTRACT_SKIP_MODE
Don't set any permission bits from the tar records.
constant
int
Filesystem.Tar.EXTRACT_SKIP_MTIME
Don't set mtime from the tar records.
Low-level Tar Filesystem.
void
extract(string
src_dir
, string
dest_dir
, void
|string
|function
(string
, Filesystem.Stat
:int
|string
) filter
, void
|int
flags
)
Extracts files from the tar file in sequential order.
src_dir
The root directory in the tar file system to extract.
dest_dir
The root directory in the real file system that will receive
the contents of src_dir
. It is assumed to exist and be
writable.
filter
A filter for the entries under src_dir
to extract. If it's
a string then it's taken as a glob pattern which is matched
against the path below src_dir
. That path always begins
with a /
. For directory entries it ends with a
/
too, otherwise not.
If it's a function then it's called for every entry under
src_dir
, and those where it returns nonzero are extracted.
The function receives the path part below src_dir
as the
first argument, which is the same as in the glob case above,
and the stat struct as the second. If the function returns a
string, it's taken as the path below dest_dir
where this
entry should be extracted (any missing directories are created
automatically).
If filter
is zero, then everything below src_dir
is
extracted.
flags
Bitfield of flags to control the extraction:
| Don't set any permission bits from the tar records. |
| Don't set set-user-ID, set-group-ID, or sticky bits from the tar records. |
| Don't set mtime from the tar records. |
| Set owning user and group from the tar records. |
| Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise. |
Files and directories are supported on all platforms, and
symlinks are supported whereever symlink
exists. Other record
types are currently not supported.
I/O errors are thrown.
void
chmod(string
filename
, int
|string
mode
)
Not implemented yet.
void
chown(string
filename
, int
|object
owner
, int
|object
group
)
Not implemented yet.
Filesystem.Tar._TarFS Filesystem.Tar._TarFS(
_Tar
_tar
, string
_wd
, string
_root
, Filesystem.Base
_parent
)
inherit Filesystem.System : System
int
rm(string
filename
)
Not implemented yet.
Filesystem.Tar.`() Filesystem.Tar.`()(
string
filename
, void
|Filesystem.Base
parent
, void
|object
file
)
filename
The tar file to mount.
parent
The parent filesystem. If none is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.
file
If specified, this should be an open file descriptor. This object
could e.g. be a Stdio.File
, Gz.File
or Bz2.File
object.
inherit _TarFS : _TarFS
Fuse - Filesystem in USErspace
FUSE (Filesystem in USErspace) provides a simple interface for userspace programs to export a virtual filesystem to the Linux kernel. FUSE also aims to provide a secure method for non privileged users to create and mount their own filesystem implementations.
See http://sourceforge.net/projects/fuse/ for more information
This module maps the Fuse library more or less directly to pike.
In order to create a filesystem, create a subclass of the
Operations
class, clone it and pass it to the run
method.
You do not need to implemnent all functions, but at least getattr, readdir and read are needed to make a useable filesystem.
A tip: ERRNO constants are available in the System module, and if one is missing /usr/include/asm[-generic]/errno.h can be included in pike programs on Linux.
inherit "___Fuse" : "___Fuse"
void
run(Operations
handler
, array
(string
) args
)
Start fuse. Args is as in argv in main(). This function will not return.
The first argument (argv[0], program name) is used as the filesystem name. The first non-flag argument after argv[0] is used as the mountpoint. Otherwise these arguments are supported:
-d enable debug output (implies -f) -f foreground operation -s disable multithreaded operation -r mount read only (equivalent to '-o ro') -o opt,[opt...] mount options -h print help
Mount options:
rootmode=M permissions of the '/' directory in the filesystem (octal) user_id=N user of '/' (numeric) group_id=N group of '/' (numeric) default_permissions enable permission checking By default FUSE doesn't check file access permissions, the filesystem is free to implement it's access policy or leave it to the underlying file access mechanism (e.g. in case of network filesystems). This option enables permission checking, restricting access based on file mode. It is usually useful together with the 'allow_other' mount option. allow_other allow access to other users This option overrides the security measure restricting file access to the user mounting the filesystem. This option is by default only allowed to root, but this restriction can be removed with a (userspace) configuration option (in fuse.ini). large_read issue large read requests (2.4 only) max_read=N set maximum size of read requests (default 128K) hard_remove immediate removal (don't hide files) debug enable debug output fsname=NAME set filesystem name in mtab (overrides argv[0])
This is the interface you have to implement to write a FUSE filesystem If something goes wrong in your callback, always return errno. Unless the function returns a specific value (Stat, string or similar), return 0 if all is well.
You do not have to implement all functions. Unimplemented functions have a default implementation that returns -ENOIMPL.
final
constantint
Fuse.Operations.DT_BLK
Block special directory entry
final
constantint
Fuse.Operations.DT_CHR
Character special directory entry
final
constantint
Fuse.Operations.DT_DIR
Directory directory entry
final
constantint
Fuse.Operations.DT_FIFO
FIFO directory entry
final
constantint
Fuse.Operations.DT_LNK
Symlink directory entry
final
constantint
Fuse.Operations.DT_REG
Normal file directory entry
final
constantint
Fuse.Operations.DT_SOCK
Socket directory entry
final
constantint
Fuse.Operations.DT_UNKNOWN
Unkown directory entry type
Fuse.Operations.final
constantF_GETLK
Fuse.Operations.final
constantF_SETLK
Fuse.Operations.final
constantF_SETLKW
Fuse.Operations.final
constantF_RDLCK
Fuse.Operations.final
constantF_WRLCK
Fuse.Operations.final
constantF_UNLCK
lock() mode operations.
final
constantint
Fuse.Operations.O_ACCMODE
Mask for read/write/rdwr
final
constantint
Fuse.Operations.O_APPEND
Open for append
final
constantint
Fuse.Operations.O_RDONLY
Open read only
final
constantint
Fuse.Operations.O_RDWR
Open read/write only
final
constantint
Fuse.Operations.O_WRONLY
Open write only
int
access(string
path
, int
mode
)
Return if the user is allowed to access the path
. If the
'default_permissions' mount option is given, this method is not
called.
int
chmod(string
path
, int
mode
)
Change the permission of a file or directory
errno or 0
int
chown(string
path
, int
uid
, int
gid
)
Change the owner of a file or directory
errno or 0
int
creat(string
path
, int
mode
, int
flag
)
Create and open or just open the given path
int
flush(string
path
, int
flags
)
Write unwritten data.
int
fsync(string
path
, int
datasync
)
Flush data and user-data to disk. Not required.
If the datasync
parameter is non-zero, then only the user data
should be flushed, not the meta data.
Stdio.Stat
|int(1..)
getattr(string
path
)
Stat a file.
This function is required.
A Stdio.Stat
object or an errno.
string
getxattr(string
path
, string
name
)
Get the extended attribute name
on path
int
link(string
source
, string
destination
)
Create a hard link from source to destination.
errno or 0
array
(string
)|int
listxattr(string
path
)
Return a list of all available extended attributes on path
mapping
(string
:int
)|int
lock(string
path
, int
mode
, mapping
(string
:int
) how
)
Lock, unlock or test for the existence of record locks (POSIX
file locking). The owner of the lock is identified by how->owner
If you only need local file-locking on the computer the filesystem is mounted on you do not need to implement this interface. This is only needed for network filesystems that want locking to work over the network.
The operation mode depends on the mode argument.
F_SETLK
Acquire a lock (when how->type
is F_RDLCK
or F_WRLCK
) or
release a lock (when how->type
is F_UNLCK
) on the bytes
specified by the how->whence, how->start, and how->len fields
of lock. If a conflicting lock is held by another process,
you should return EACCES or EAGAIN.
F_SETLKW
Identical to SETLK, but if a lock is held on the file, wait for it to be released before returning. You are allowed to return EINTR, to signal that the waiting has been interrupted and must be restarted.
F_GETLK
Identical to SETLK, but do not actually aquire the lock if it
can be aquired. If one or more incompatible locks would
prevent this lock being placed, then fcntl() returns details
about one of these locks in the type, whence, start, and len
fields of how
and set pid
to be the PID of the process
holding that lock. Then return the mapping.
int
mkdir(string
path
, int
mode
)
Create a directory.
errno or 0
int
mknod(string
path
, int
mode
, int
rdev
)
Create a node (file, device special, or named pipe). See man 2 mknod
errno or 0
int
open(string
path
, int
mode
)
Open path
. mode
is as for the system call open.
(mode & O_ACCMODE) is one of O_RDONLY, O_WRONLY and O_RDWR.
The mode can also contain other flags, most notably O_APPEND.
You do not really have to implement this function. It's useful to start prefetch and to cache open files, and check that the user has permission to read/write the file.
errno or 0
string
|int(1..)
read(string
path
, int
len
, int
offset
)
Read data from a file. You have to return at most len
bytes, wunless an error occurs, or there is less than len bytes
of data still left to read.
errno or the data
int
readdir(string
path
, function
(string
:void
) callback
)
Get directory contents.
Call the callback once per file in the directory with the filename as the argument.
This function is required.
errno or 0
string
|int(1..)
readlink(string
path
)
Read a symlink.
The symlink contents or errno
int
release(string
path
)
The inverse of open.
The file might very well be openend multiple times. Keep reference counts.
int
removexattr(string
path
, string
name
)
Remove the extended attribute name
from path
int
rename(string
source
, string
destination
)
Rename source
to destination
.
errno or 0
int
rmdir(string
path
)
Remove a directory
errno or 0
int
setxattr(string
path
, string
name
, string
value
, int
flags
)
Set the extended attrbiute name
on path
to value
mapping
(string
:int
) statfs(string
path
)
Stat a filesystem.
Mapping as from filesystem_stat
required for 'df' support, without this function there is an error each time 'df' is run.
int
symlink(string
source
, string
destination
)
Create a symlink from source to destination.
errno or 0
int
truncate(string
path
, int
new_length
)
Shrink or enlarge a file
errno or 0
int
unlink(string
path
)
Remove a file
errno or 0
int
utime(string
path
, int
atime
, int
mtime
)
Set access and modification time. The arguments are the number of seconds since jan 1 1970 00:00.
This function is deprecated, utimens is the recommended method.
errno or 0
int
utimens(string
path
, int
atime
, int
mtime
)
Set access and modification time, with nanosecond resolution. The arguments are the number of nanoseconds since jan 1 1970 00:00.
errno or 0
int
write(string
path
, string
data
, int
offset
)
Write data to the file. Should write all data.
errno or amount written (bytes)
GDK wrapper module.
This is a convenience module that is identical to either
either the GDK2
or the GDK1
module depending on
which (if any) of them is available.
GDK1
, GDK2
constant
GDK.Atom
constant
GDK1.Atom
A bitmap is a black and white pixmap. Most commonly used as masks for images, widgets and pixmaps.
NOIMG
GDK1.Bitmap GDK1.Bitmap(
int
|Image.Image
xsize_or_image
, int
|void
ysize
, string
|void
bitmap
)
Create a new GDK1.Bitmap object. Argument is either an Image.Image object, or {xsisze,ysize,xbitmapdata}.
GDK1.Bitmap
destroy()
Destructor. Destroys the bitmap. This will free the bitmap on the X-server.
inherit GDK1.Drawable : Drawable
GDK1.Bitmap
ref()
Add a reference
GDK1.Bitmap
unref()
Remove a reference
The GDK1.Color object is used to represent a color. When you call GDK1.Color(r,g,b) the color will be allocated from the X-server. The constructor can return an exception if there are no more colors to allocate. NOIMG
int
blue()
Returns the blue color component.
GDK1.Color GDK1.Color(
object
|int
color_or_r
, int
|void
g
, int
|void
b
)
r g and b are in the range 0 to 255, inclusive. If color is specified, it should be an Image.Color object, and the only argument.
GDK1.Color
destroy()
Destroys the color object. Please note that this function does not free the color from the X-colormap (in case of pseudocolor) right now.
int
green()
Returns the green color component.
Image.Color.Color
image_color_object()
Return a Image.Color.Color instance. This gives better precision than the rgb function.
int
pixel()
Returns the pixel value of the color. See GDK1.Image->set_pixel.
int
red()
Returns the red color component.
array
rgb()
Returns the red green and blue color components as an array.
The drag context contains all information about the drag'n'drop connected to the signal to which it is an argument.
NOIMG
GDK1.DragContext
drag_abort(int
time
)
Abort the drag
GDK1.DragContext
drag_drop(int
time
)
GDK1.DragContext
drag_finish(int
success
, int
del
, int
time
)
If success is true, the drag succeded. If del is true, the source should be deleted. time is the current time.
GDK1.DragContext
drag_set_icon_default()
Use the default drag icon associated with the source widget.
GDK1.DragContext
drag_set_icon_pixmap(GDK1.Pixmap
p
, GDK1.Bitmap
b
, int
hot_x
, int
hot_y
)
Set the drag pixmap, and optionally mask. The hot_x and hot_y coordinates will be the location of the mouse pointer, relative to the upper left corner of the pixmap.
GDK1.DragContext
drag_set_icon_widget(GTK1.Widget
widget
, int
hot_x
, int
hot_y
)
Set the drag widget. This is a widget that will be shown, and then dragged around by the user during this drag.
GDK1.DragContext
drag_status(int
action
, int
time
)
Setting action to -1 means use the suggested action
GDK1.DragContext
drop_reply(int
ok
, int
time
)
int
get_action()
One of GDK_ACTION_ASK
, GDK_ACTION_COPY
, GDK_ACTION_DEFAULT
, GDK_ACTION_LINK
, GDK_ACTION_MOVE
and GDK_ACTION_PRIVATE
;
int
get_actions()
A bitwise or of one or more of GDK_ACTION_ASK
, GDK_ACTION_COPY
, GDK_ACTION_DEFAULT
, GDK_ACTION_LINK
, GDK_ACTION_MOVE
and GDK_ACTION_PRIVATE
;
int
get_is_source()
Is this application the source?
int
get_protocol()
One of GDK_DRAG_PROTO_MOTIF
, GDK_DRAG_PROTO_ROOTWIN
and GDK_DRAG_PROTO_XDND
GTK1.Widget
get_source_widget()
Return the drag source widget.
int
get_start_time()
The start time of this drag, as a unix time_t (seconds since 0:00 1/1 1970)
int
get_suggested_action()
One of GDK_ACTION_ASK
, GDK_ACTION_COPY
, GDK_ACTION_DEFAULT
, GDK_ACTION_LINK
, GDK_ACTION_MOVE
and GDK_ACTION_PRIVATE
;
The GDK1.Bitmap, GDK1.Window and GDK1.Pixmap classes are all GDK drawables.
This means that you can use the same set of functions to draw in them.
Pixmaps are offscreen drawables. They can be drawn upon with the standard drawing primitives, then copied to another drawable (such as a GDK1.Window) with window->draw_pixmap(), set as the background for a window or widget, or otherwise used to show graphics (in a W(Pixmap), as an example). The depth of a pixmap is the number of bits per pixels. Bitmaps are simply pixmaps with a depth of 1. (That is, they are monochrome bitmaps - each pixel can be either on or off).
Bitmaps are mostly used as masks when drawing pixmaps, or as a shape for a GDK1.Window or a W(Widget)
GDK1.Drawable
clear(int
|void
x
, int
|void
y
, int
|void
width
, int
|void
height
)
Either clears the rectangle defined by the arguments, of if no arguments are specified, the whole drawable.
GDK1.Drawable
copy_area(GDK1.GC
gc
, int
xdest
, int
ydest
, GTK1.Widget
source
, int
xsource
, int
ysource
, int
width
, int
height
)
Copies the rectangle defined by xsource,ysource and width,height from the source drawable, and places the results at xdest,ydest in the drawable in which this function is called.
GDK1.Drawable
draw_arc(GDK1.GC
gc
, int
filledp
, int
x1
, int
y1
, int
x2
, int
y2
, int
angle1
, int
angle2
)
Draws a single circular or elliptical arc. Each arc is specified by a rectangle and two angles. The center of the circle or ellipse is the center of the rectangle, and the major and minor axes are specified by the width and height. Positive angles indicate counterclockwise motion, and negative angles indicate clockwise motion. If the magnitude of angle2 is greater than 360 degrees, it is truncated to 360 degrees.
GDK1.Drawable
draw_bitmap(GDK1.GC
gc
, GDK1.Bitmap
bitmap
, int
xsrc
, int
ysrc
, int
xdest
, int
ydest
, int
width
, int
height
)
Draw a GDK(Bitmap) in this drawable. NOTE: This drawable must be a bitmap as well. This will be fixed in GTK 1.3
GDK1.Drawable
draw_image(GDK1.GC
gc
, GDK1.Image
image
, int
xsrc
, int
ysrc
, int
xdest
, int
ydest
, int
width
, int
height
)
Draw the rectangle specified by xsrc,ysrc+width,height from the GDK(Image) at xdest,ydest in the destination drawable
GDK1.Drawable
draw_line(GDK1.GC
gc
, int
x1
, int
y1
, int
x2
, int
y2
)
img_begin w = GTK1.DrawingArea()->set_usize(100,100); delay: g = GDK1.GC(w)->set_foreground( GDK1.Color(255,0,0) ); delay: for(int x = 0; x<10; x++) w->draw_line(g,x*10,0,100-x*10,99); img_end
GDK1.Drawable
draw_pixmap(GDK1.GC
gc
, GDK1.Pixmap
pixmap
, int
xsrc
, int
ysrc
, int
xdest
, int
ydest
, int
width
, int
height
)
Draw the rectangle specified by xsrc,ysrc+width,height from the GDK(Pixmap) at xdest,ydest in the destination drawable
GDK1.Drawable
draw_point(GDK1.GC
gc
, int
x
, int
y
)
img_begin w = GTK1.DrawingArea()->set_usize(10,10); delay: g = GDK1.GC(w)->set_foreground( GDK1.Color(255,0,0) ); delay: for(int x = 0; x<10; x++) w->draw_point(g, x, x); img_end
GDK1.Drawable
draw_rectangle(GDK1.GC
gc
, int
filledp
, int
x1
, int
y1
, int
x2
, int
y2
)
img_begin w = GTK1.DrawingArea()->set_usize(100,100); delay: g = GDK1.GC(w)->set_foreground( GDK1.Color(255,0,0) ); delay: for(int x = 0; x<10; x++) w->draw_rectangle(g,0,x*10,0,100-x*10,99); img_end img_begin w = GTK1.DrawingArea()->set_usize(100,100); delay: g = GDK1.GC(w); delay: for(int x = 0; x<30; x++) { delay: g->set_foreground(GDK1.Color(random(255),random(255),random(255)) ); delay: w->draw_rectangle(g,1,x*10,0,100-x*10,99); delay: } img_end
GDK1.Drawable
draw_text(GDK1.GC
gc
, GDK1.Font
font
, int
x
, int
y
, string
text
, int
forcewide
)
y is used as the baseline for the text. If forcewide is true, the string will be expanded to a wide string even if it is not already one. This is useful when writing text using either unicode or some other 16 bit font.
mapping
get_geometry()
Get width, height position and depth of the drawable as a mapping.
([ "x":xpos, "y":ypos, "width":xsize, "height":ysize, "depth":bits_per_pixel ])
int
xid()
int
xsize()
Returns the width of the drawable specified in pixels
int
ysize()
Returns the height of the drawable specified in pixels
protected
mixed
_index(string
ind
)
(
mapping
)GDK1.Event()
GDK1.Event
destroy()
The GdkFont data type represents a font for drawing on the screen. These functions provide support for loading fonts, and also for determining the dimensions of characters and strings when drawn with a particular font.
Fonts in X are specified by a X Logical Font Description. The following description is considerably simplified. For definitive information about XLFD's see the X reference documentation. A X Logical Font Description (XLFD) consists of a sequence of fields separated (and surrounded by) '-' characters. For example, Adobe Helvetica Bold 12 pt, has the full description: "-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"
The fields in the XLFD are:
Foundry | the company or organization where the font originated. |
Family | the font family (a group of related font designs). |
Weight | A name for the font's typographic weight For example, 'bold' or 'medium'). |
Slant | The slant of the font. Common values are 'R' for Roman, 'I' for italoc, and 'O' for oblique. |
Set Width | A name for the width of the font. For example, 'normal' or 'condensed'. |
Add Style | Additional information to distinguish a font from other fonts of the same family. |
Pixel Size | The body size of the font in pixels. |
Point Size | The body size of the font in 10ths of a point. (A point is 1/72.27 inch) |
Resolution X | The horizontal resolution that the font was designed for. |
Resolution Y | The vertical resolution that the font was designed for . |
Spacing | The type of spacing for the font - can be 'p' for proportional, 'm' for monospaced or 'c' for charcell. |
Average Width | The average width of a glyph in the font. For monospaced and charcell fonts, all glyphs in the font have this width |
Charset Registry | The registration authority that owns the encoding for the font. Together with the Charset Encoding field, this defines the character set for the font. |
Charset Encoding | An identifier for the particular character set encoding. |
When specifying a font via a X logical Font Description, '*' can be used as a wildcard to match any portion of the XLFD. For instance, the above example could also be specified as "-*-helvetica-bold-r-normal--*-120-*-*-*-*-iso8859-1"
It is generally a good idea to use wildcards for any portion of the XLFD that your program does not care about specifically, since that will improve the chances of finding a matching font.
int
char_width(int
character
)
Return the width, in pixels, of the specified character, if rendered with this font. The character can be between 0 and 65535, the character encoding is font specific.
GDK1.Font GDK1.Font(
string
|void
font_name
)
Create a new font object. The string is the font XLFD.
GDK1.Font
destroy()
Free the font, called automatically by pike when the object is destroyed.
A GC, or Graphics Context, is used for most low-level drawing operation.
As an example, the foreground color, background color and drawing function is stored in the GC.
NOIMG
GDK1.GC
copy(GDK1.GC
source
)
Copy all attributes from the source GC
GDK1.GC GDK1.GC(
GTK1.Widget
context
, mapping
|void
attributes
)
The argument is a either a W(Widget) or a GDK(Drawable) in which the gc will be valid.
GDK1.GC
destroy()
Free the gc, called automatically by pike when the object is destroyed.
mapping
get_values()
Get all (or rather most) values from the GC.
GDK1.GC
set_background(GDK1.Color
color
)
Set the background to the specified GDK1.Color.
GDK1.GC
set_clip_mask(GDK1.Bitmap
mask
)
Set the clip mask to the specified GDK1.Bitmap
GDK1.GC
set_clip_origin(int
x
, int
y
)
Set the clip mask origin to the specified point.
GDK1.GC
set_clip_rectangle(GDK1.Rectangle
rect
)
Sets the clip mask for a graphics context from a rectangle. The clip mask is interpreted relative to the clip origin.
GDK1.GC
set_clip_region(GDK1.Region
rect
)
Sets the clip mask for a graphics context from a region. The clip mask is interpreted relative to the clip origin.
GDK1.GC
set_dashes(int
offset
, array
dashes
)
Sets the way dashed-lines are drawn. Lines will be drawn with alternating on and off segments of the lengths specified in dashes. The manner in which the on and off segments are drawn is determined by the line_style value of the GC.
GDK1.GC
set_fill(int
fill
)
Set the fill method to fill.
GDK1.GC
set_font(GDK1.Font
font
)
Set the font to the specified GDK1.Font.
GDK1.GC
set_foreground(GDK1.Color
color
)
Set the foreground to the specified GDK1.Color.
GDK1.GC
set_function(int
fun
)
Set the function to the specified one. One of GDK1.Xor, GDK1.Invert and GDK1.Copy.
GDK1.GC
set_line_attributes(int
line_width
, int
line_style
, int
cap_style
, int
join_style
)
Control how lines are drawn. line_style is one of GDK1.LineSolid, GDK1.LineOnOffDash and GDK1.LineDoubleDash. cap_style is one of GDK1.CapNotLast, GDK1.CapButt, GDK1.CapRound and GDK1.CapProjecting. join_style is one of GDK1.JoinMiter, GDK1.JoinRonud and GDK1.JoinBevel.
GDK1.GC
set_stipple(GDK1.Bitmap
stipple
)
Set the background type. Fill must be GDK_STIPPLED or GDK_OPAQUE_STIPPLED
GDK1.GC
set_subwindow(int
draw_on_subwindows
)
If set, anything drawn with this GC will draw on subwindows as well as the window in which the drawing is done.
GDK1.GC
set_tile(GDK1.Pixmap
tile
)
Set the background type. Fill must be GDK_TILED
GDK1.GC
set_ts_origin(int
x
, int
y
)
Set the origin when using tiles or stipples with the GC. The tile or stipple will be aligned such that the upper left corner of the tile or stipple will coincide with this point.
A gdk (low level) image. Mainly used for W(Image) objects.
NOIMG
GDK1.Image GDK1.Image(
int
|void
fast_mode
, Image.Image
|void
image
)
Create a new GDK1.Image object. The firstargument is either 0, which indicates that you want a 'slow' image. If you use '1', you indicate that you want a 'fast' image. Fast images are stored in shared memory, and thus are not sent over any network. But please limit your usage of fast images, they use up a possibly limited system resource set. See the man page for shmget(2) for more information on the limits on shared segments on your system.
A 'fast' image will automatically revert back to 'slow' mode if no shared memory is available.
If the second argument is specified, it is the actual image data.
GDK1.Image
destroy()
Destructor. Destroys the image. Automatically called by pike when the object is destructed.
int
get_pixel(int
x
, int
y
)
Get the pixel value of a pixel as a X-pixel value. It is usualy not very easy to convert this value to a rgb triple. See get_pnm.
string
get_pnm()
Returns the data in the image as a pnm object. Currently, this is always a P6 (true color raw) image. This could change in the future. To get a pike image object do 'Image.PNM.decode( gdkimage->get_pnm() )'
GDK1.Image
grab(GTK1.Widget
widget
, int
xoffset
, int
yoffset
, int
width
, int
height
)
Call this function to grab a portion of a widget (argument 1) to the image. Grabbing non-toplevel widgets may produce unexpected results. To get the size of a widget use ->xsize() and ->ysize(). To get the offset of the upper left corner of the widget, relative to it's X-window (this is what you want for the offset arguments), use ->xoffset() and ->yoffset().
GDK1.Image
set(Image.Image
|int
image_or_xsize
, int
|void
ysize
)
Call this to set this image to either the contents of a pike image or a blank image of a specified size.
GDK1.Image
set_pixel(int
x
, int
y
, int
pixel
)
Set the pixel value of a pixel. Please note that the pixel argument is a X-pixel value, which is not easily gotten from a RGB color. See get_pixel and set.
This class creates a GDK1.Pixmap from either an GDK1.Image or Image.Image object (or a numeric ID, see your X-manual for XIDs). The GDK1.Pixmap object can be used in a lot of different GTK widgets. The most notable is the W(Pixmap) widget.
NOIMG
GDK1.Pixmap GDK1.Pixmap(
int
|object
image
)
Create a new GDK1.Pixmap object. Argument is a GDK1.Image object or a Image.Image object
GDK1.Pixmap
destroy()
Destructor. Destroys the pixmap.
inherit GDK1.Drawable : Drawable
GDK1.Pixmap
ref()
GDK1.Pixmap
set(GDK1.Image
image
)
Argument is a GDK1.Image object or an Image.Image object. It is much faster to use an gdkImage object, especially one allocated in shared memory. This is only an issue if you are going to change the contents of the pixmap often, toggling between a small number of images.
GDK1.Pixmap
unref()
(
mapping
)GDK1.Rectangle()
(array
)GDK1.Rectangle()
Normally used like (mapping)rectangle or (array)rectangle.
GDK1.Rectangle GDK1.Rectangle(
int
x
, int
y
, int
width
, int
height
)
Create a new rectangle
NOIMG
GDK1.Rectangle
destroy()
GDK1.Rectangle
set(int
x
, int
y
, int
width
, int
height
)
Set the upper left corner and the size of the rectangle.
GDK1.Region GDK1.Region()
Create a new (empty) region
NOIMG
GDK1.Region
destroy()
int
equal(GDK1.Region
victim
)
Return true if the region used as an argument is equal to the current region. Also available as a==b when a is a region.
GDK1.Region
intersect(GDK1.Region
victim
)
Computes the intersection of the given region and the region. Also available as region & region
GDK1.Region
offset(int
dx
, int
dy
)
Offset(move) the region by dx,dy pixels.
int
point_in(int
x
, int
y
)
Returns true if the given point resides in the given region
int
rect_in(GDK1.Rectangle
r
)
Returns true if the given rectangle resides inside the given region
GDK1.Region
shrink(int
dx
, int
dy
)
reduces the size of a region by a specified amount. Positive values shrink the size of the region, and negative values expand the region.
GDK1.Region
subtract(GDK1.Region
victim
)
Computes the difference of the given region and the region. Also available as region - region
GDK1.Region
union(GDK1.Region
victim
)
Computes the union of the given rectangle or region and the region. Also available as region | rectangle, region | region, region + region and region + rectangle.
GDK1.Region
xor(GDK1.Region
victim
)
Computes the exlusive or of the given region and the region. Also available as region ^ region
a GDK1.Window object.
NOIMG
GDK1.Window
change_property(GDK1.Atom
property
, GDK1.Atom
type
, int
mode
, string
data
)
mode is one of GDK_PROP_MODE_APPEND
, GDK_PROP_MODE_PREPEND
and GDK_PROP_MODE_REPLACE
array
children()
Returns an array of GDK1.Window objects.
GDK1.Window GDK1.Window(
GDK1.Window
parent
, mapping
|void
attributes
)
Not for non-experts. I promise.
GDK1.Window
delete_property(GDK1.Atom
a
)
mapping
get_geometry()
Returns ([ "x":xpos, "y":ypos, "width":width, "height":height, "depth":bits_per_pixel ])
mapping
get_pointer(int
deviceid
)
Get the position of the specified device in this window.
mapping
get_property(GDK1.Atom
atom
, int
|void
offset
, int
|void
delete_when_done
)
Returns the value (as a string) of the specified property. The arguments are:
property: The property atom, as an example GDK1.Atom.__SWM_VROOT offset (optional): The starting offset, in elements delete_when_done (optional): If set, the property will be deleted when it has been fetched.
Example usage: Find the 'virtual' root window (many window managers put large windows over the screen)
GDK1.Window root = GTK1.root_window(); array maybe=root->children()-> get_property(GDK1.Atom.__SWM_VROOT)-({0}); if(sizeof(maybe)) root=GDK1.Window( maybe[0]->data[0] );
inherit GDK1.Drawable : Drawable
int
is_viewable()
Return 1 if the window is mapped.
int
is_visible()
Return 1 if the window, or a part of the window, is visible right now.
GDK1.Window
lower()
Lower this window if the window manager allows that.
GDK1.Window
move_resize(int
x
, int
y
, int
w
, int
h
)
Move and resize the window in one call.
GDK1.Window
raise()
Raise this window if the window manager allows that.
GDK1.Window
set_background(GDK1.Color
to
)
Set the background color or image. The argument is either a GDK1.Pixmap or a GDK1.Color object.
GDK1.Window
set_bitmap_cursor(GDK1.Bitmap
image
, GDK1.Bitmap
mask
, GDK1.Color
fg
, GDK1.Color
bg
, int
xhot
, int
yhot
)
xhot,yhot are the locations of the x and y hotspot relative to the upper left corner of the cursor image.
GDK1.Window
set_cursor(int
new_cursor
)
Change the window cursor.<table border="0" cellpadding="3" cellspacing="0"> CURS(GDK1.Arrow) CURS(GDK1.BasedArrowDown) CURS(GDK1.BasedArrowUp) CURS(GDK1.Boat) CURS(GDK1.Bogosity) CURS(GDK1.BottomLeftCorner) CURS(GDK1.BottomRightCorner) CURS(GDK1.BottomSide) CURS(GDK1.BottomTee) CURS(GDK1.BoxSpiral) CURS(GDK1.CenterPtr) CURS(GDK1.Circle) CURS(GDK1.Clock) CURS(GDK1.CoffeeMug) CURS(GDK1.Cross) CURS(GDK1.CrossReverse) CURS(GDK1.Crosshair) CURS(GDK1.DiamondCross) CURS(GDK1.Dot) CURS(GDK1.Dotbox) CURS(GDK1.DoubleArrow) CURS(GDK1.DraftLarge) CURS(GDK1.DraftSmall) CURS(GDK1.DrapedBox) CURS(GDK1.Exchange) CURS(GDK1.Fleur) CURS(GDK1.Gobbler) CURS(GDK1.Gumby) CURS(GDK1.Hand1) CURS(GDK1.Hand2) CURS(GDK1.Heart) CURS(GDK1.Icon) CURS(GDK1.IronCross) CURS(GDK1.LeftPtr) CURS(GDK1.LeftSide) CURS(GDK1.LeftTee) CURS(GDK1.Leftbutton) CURS(GDK1.LlAngle) CURS(GDK1.LrAngle) CURS(GDK1.Man) CURS(GDK1.Middlebutton) CURS(GDK1.Mouse) CURS(GDK1.Pencil) CURS(GDK1.Pirate) CURS(GDK1.Plus) CURS(GDK1.QuestionArrow) CURS(GDK1.RightPtr) CURS(GDK1.RightSide) CURS(GDK1.RightTee) CURS(GDK1.Rightbutton) CURS(GDK1.RtlLogo) CURS(GDK1.Sailboat) CURS(GDK1.SbDownArrow) CURS(GDK1.SbHDoubleArrow) CURS(GDK1.SbLeftArrow) CURS(GDK1.SbRightArrow) CURS(GDK1.SbUpArrow) CURS(GDK1.SbVDoubleArrow) CURS(GDK1.Shuttle) CURS(GDK1.Sizing) CURS(GDK1.Spider) CURS(GDK1.Spraycan) CURS(GDK1.Star) CURS(GDK1.Target) CURS(GDK1.Tcross) CURS(GDK1.TopLeftArrow) CURS(GDK1.TopLeftCorner) CURS(GDK1.TopRightCorner) CURS(GDK1.TopSide) CURS(GDK1.TopTee) CURS(GDK1.Trek) CURS(GDK1.UlAngle) CURS(GDK1.Umbrella) CURS(GDK1.UrAngle) CURS(GDK1.Watch) CURS(GDK1.Xterm) </table>
GDK1.Window
set_events(int
events
)
events is a bitwise or of one or more of the following constants: GDK1.ExposureMask, GDK1.PointerMotionMask, GDK1.PointerMotion_HINTMask, GDK1.ButtonMotionMask, GDK1.Button1MotionMask, GDK1.Button2MotionMask, GDK1.Button3MotionMask, GDK1.ButtonPressMask, GDK1.ButtonReleaseMask, GDK1.KeyPressMask, GDK1.KeyReleaseMask, GDK1.EnterNotifyMask, GDK1.LeaveNotifyMask, GDK1.FocusChangeMask, GDK1.StructureMask, GDK1.PropertyChangeMask, GDK1.VisibilityNotifyMask, GDK1.ProximityInMask, GDK1.ProximityOutMask and GDK1.AllEventsMask
GDK1.Window
set_icon(GDK1.Pixmap
pixmap
, GDK1.Bitmap
mask
, GDK1.Window
window
)
Set the icon to the specified image (with mask) or the specified GDK1.Window. It is up to the window manager to display the icon. Most window manager handles window and pixmap icons, but only a few can handle the mask argument. If you want a shaped icon, the only safe bet is a shaped window.
GDK1.Window
set_icon_name(string
name
)
Set the icon name to the specified string.
GDK1.Window
shape_combine_mask(GDK1.Bitmap
mask
, int
xoffset
, int
yoffset
)
Set the shape of the widget, or, rather, it's window, to that of the supplied bitmap.
An X-atom. You most likely want to use GDK1.Atom.atom_name instead of GDK1._Atom(name).
GDK1._Atom GDK1._Atom(
string
atom_name
, int
|void
only_if_exists
)
Create a new low-level atom. You should normally not call this function directly. Use GDK1.Atom[name] instead of GDK1._Atom(name,0).
string
get_name()
Returns the name of the atom.
constant
GDK2.Atom
GL Universal Environment
void
PushPop(function
(:void
) f
)
Performs function f
between GL.glPushMatrix
and
GL.glPopMatrix
calls.
PushPop() { GL.glTranslate( 0.01, -0.9, 0.0 ); write_text( "Press esc to quit" ); };
void
add_reinit_callback(function
(void
:void
) f
)
Add a callback that will be called every time the resolution is about to change.
remove_reinit_callback
int
allocate_light()
Allocate a hardwareaccelerated lightsource from OpenGL.
an id which may be added to the GL.GL_LIGHT0 constant.
free_light
mapping
(string
:mixed
) debug_stuff()
Returns some internal states for debug purposes. The actual content may change.
void
draw_box(float
x0
, float
y0
, float
x1
, float
y1
, array
(Image.Color.Color
)|Image.Color.Color
c
, void
|array
(float
)|float
a
)
Draw a box at the specified coordinates. c
is either a single
color, in which case it will be used for all corners, or an array
of four colors, which will be used for each corner.
a
is similar to c
, but is the alpha values for each coordinate.
void
draw_line(float
x0
, float
y0
, float
x1
, float
y1
, Image.Color.Color
c
, void
|float
a
)
void
draw_line(float
x0
, float
y0
, float
z0
, float
x1
, float
y1
, float
z1
, Image.Color.Color
c
, void
|float
a
)
void
draw_obox(float
x0
, float
y0
, float
x1
, float
y1
, array
(Image.Color.Color
)|Image.Color.Color
c
, void
|array
(float
)|float
a
)
Draw a box outline around the specified coordinates. c
is
either a single color, in which case it will be used for all
corners, or an array of four colors, which will be used for each
corner.
a
is similar to c
, but is the alpha values for each coordinate.
void
draw_polygon(array
(float
) coords
, Image.Color.Color
c
, float
a
)
void
free_light(int
l
)
Call this function to free a lightsource that has been allocated with
allocate_light
.
l
Id which has been allocated using allocate_light
.
allocate_light
array
(List
) get_all_lists()
Returns all defined lists. Only available on Windows.
array
(BaseTexture
) get_all_textures()
Returns a list of all current textures.
float
get_aspect()
Returns the screen aspect.
set_aspect
int
get_depth()
Returns the current color depth.
set_depth
array
(string
) get_drivers()
Returns the name of the available drivers.
init
int
get_gl_flags()
Returns the GL flags currently used.
set_gl_flags
bool
get_screen_mode()
Returns 1 if in fullscreen mode, otherwise 0.
toggle_fullscreen
int
get_texture_mem_usage()
Returns the number of bytes used by the textures.
bool
has_extension(string
ext
)
Checks if the GL extension ext
is currently supported.
void
hide_cursor()
Hide the mouse cursor.
void
init(void
|mapping
(string
:mixed
) options
)
Initializes GLUE and loads a driver from a list of drivers. If a driver fails to load or initialize, the next driver is tried.
driver_names
not listed in the result from get_drivers
will cause an error to be thrown.
options
| The name of a driver or a list of drivers to try, in given
order. If no driver name is given, the list given by
|
| This callback is called with a |
| This callback is called with the aspect whenever the drawing area is resized, either by an event or explicitly by the program. |
| Set fullscreen/window mode. 1 is fullscreen, 0 is window. Defaults to fullscreen. |
| Sets the resolution of the drawing area. Defaults to ({ 800, 600 }). |
| Sets the aspect of the drawing area. Defaults to 1.333333 (4:3). |
| Sets the color depth of the drawing area. Defaults to 32. |
| Sets the window title to this string. |
| Sets the icon title to this string. |
| Use GL_NEAREST_MIMAP_NEAREST instead of GL_LINEAR_MIPMAP_LINEAR, which also is the default. |
| The rotation in z-axis of the drawing field. |
| Mirroring in x and/or y axis. |
get_drivers
BaseTexture
make_rect_texture(mapping
|Image.Image
image
, string
|void
name
)
Create a texture with the specified image as contents. Will try
to use the TEXTURE_RECTANGLE_NV extension if available, otherwise
normal textures will be used (like make_texture
).
make_texture
BaseTexture
make_texture(mapping
|Image.Image
image
, string
|void
name
)
Create a texture. Mainly here for symetry with make_rect_texture
Texture
, make_rect_texture
void
mirror_screen(string
how
)
Mirrors the screen in x and/or y axis. Useful e.g. when drawing for backlight projection.
how
A string that contains the mirror axis, e.g. "x"
or
"xy"
.
bool
only_dynlists()
Returns 1
if all defined lists are DynList
lists.
int(0..)
pushpop_depth()
Returns the PushPop depth, i.e. the number of pushes awaiting corresponding pops.
void
remove_reinit_callback(function
(void
:void
) f
)
Removes a reinitialization callback.
add_reinit_callback
void
set_aspect(float
asp
)
void
set_aspect(int
w
, int
h
)
Set the aspect of the draw area. Does nothing if the provided aspect is equal to the one currently used.
get_aspect
void
set_depth(int
_depth
)
Sets the color depth.
get_depth
void
set_gl_flags(int
_gl_flags
)
Sets the GL flags.
get_gl_flags
void
set_resolution(int
w
, int
h
)
Sets the resolution to w
xh
pixels.
xsize
, ysize
void
set_screen_rotation(float
deg
)
Rotates the drawing area deg
degrees. Useful e.g. when drawing
for tilted monitors.
void
show_cursor()
Show the mouse cursor.
void
swap_buffers()
Swap the drawing buffer and the viewing buffer.
void
toggle_fullscreen(void
|bool
_fullscreen
)
Toggles between fullscreen and window mode. If a screen mode is provided, that mode will be assumed.
get_screen_mode
int
xsize()
int
ysize()
Returns the screen width/height.
set_resolution
A mixin class with a dwim create function.
GLUE.BaseDWIM GLUE.BaseDWIM(
mixed
... args
)
This create function has the following heuristic:
If a mapping is encountered, the following information will be attempted to be extracted.
| The texture image. |
| The image dimensions. If not provided, the dimensions of the
|
| |
| |
| |
| The alpha mode. |
| Should the texture be mipmapped or not. |
| Should the texture be clamped or not. |
| The texture mode. |
| The debug name associated with this texture. |
If an object is encountered in the argument list, the first object will be used as texture image and the second as texture alpha.
If a string is encountered in the argument list, it will be used as debug name associated with this texture.
Once all mappings, strings and objects are removed from the argument list, the remaining integers will be interpreted as width, height, alpha, mipmap and mode, unless there is only one argument. In that case it will be interpreted as the alpha mode.
The texture base class. Using e.g. Texture
might be more
convenient.
int
sizeof( GLUE.BaseTexture arg )
Returns the size of memory allocated by the texture.
bool
res = GLUE.BaseTexture()
> x
Textures can be sorted according to texture id.
void
clear()
Clears the texture.
void
construct(int
width
, int
height
, int
_alpha
, mapping
|void
imgs
, int(2bit)
|void
flags
, int
|void
_mode
, string
|void
debug_text
)
Construct a new texture. Processes _alpha
, _mode
and
debug_text
and calls resize
.
_alpha
The alpha mode the texture is operating in.
| RGB |
| RGBA |
| ALPHA |
| LUM |
| LUM+ALPHA |
_mode
The mode the texture is operating in. Autoselected wrt _alpha
if 0
.
debug_text
A string that can be used to identify this texture.
void
coords(float
x
, float
y
)
Sets the texture coordinates to x
*width,y
*height.
GLUE.BaseTexture GLUE.BaseTexture(
mixed
... args
)
Calls construct
with args
.
void
create_texture(mapping
|void
imgs
, int(2bit)
|void
flags
, int
|void
width
, int
|void
height
)
Actually creates the texture.
imgs
If zero, a black texture with the dimensions width
*
height
will be generated. Otherwise imgs
should be a
mapping as follows.
| The actual image to be used as texture. It will be
cropped/padded to meet the dimensions given in |
| Optional image to be used as alpha channel, depending on the
alpha value given to |
flags
If 1
, the texture will be mipmapped.
If bit 1 (2
) is set, texture will not be wrapped but clamped.
width
height
The dimensions of the texture. If omitted the dimensions of
the images in imgs
will be used.
resize
string
GLUE.BaseTexture.debug
A string to identify the texture.
protected
void
destroy()
Properly deallocates the texture.
void
draw(float
x
, float
y
, float
z
, float
w
, float
h
)
Draw the texture at x
,y
,z
with dimensions w
*h
.
void
draw_region(float
x
, float
y
, float
z
, float
w
, float
h
, float
s0
, float
q0
, float
ss
, float
qs
)
Draw texture region s0
,q0
- ss
,qs
at x
,y
,z
with dimensions w
*h
.
int
get_id()
Returns the id of this texture.
float
GLUE.BaseTexture.width_u
float
GLUE.BaseTexture.height_u
Utilization in percent.
int
GLUE.BaseTexture.i_width
int
GLUE.BaseTexture.i_height
Image dimensions
void
make_mipmap(mapping
imgs
, int
|void
imode
, int
|void
dx
, int
|void
dy
)
Renders a mipmap of the image/partial image imgs
.
imgs
Image data mapping to feed GL.glTexImage2D
or
GL.glTexSubImage2D
.
imode
Internal format to feed GL.glTexImage2D
, or UNDEFINED for
partial images.
dx
dy
Xoffs, yoffs to feed GL.glTexSubImage2D
for partial images.
create_texture
void
paste(Image.Image
i
, Image.Image
a
, int
x
, int
y
)
Paste the image i
with alpha channel a
at coordinates x
and y
in the current texture.
void
resize(int
width
, int
height
, mapping
|void
imgs
, int(2bit)
|void
flags
, bool
|void
nocreate
)
Resizes/creates a texture to meet the dimensions width
and
height
. If nocreate
isn't given, create_texture
is
called to actually perform the resize/creation.
construct
void
set_image_data(Image.Image
|mapping
(string
:mixed
) data
, bool
|void
no_resize
)
Set the contents (and size) of the texture from the supplied
data. The data
is identical to what would normally be sent as
the last argument to glTex[Sub]Image2D() or an Image.Image object.
If no_resize
is specified, it is assumed that the data will
fit in the texture, otherwise the parts that extend beyond it
will be discarded.
data
Besides being an Image.Image
object, data
can be either of
two types of mappins. First it can be a mapping with Image data.
| Texture image data. |
| Optional alpha channel. |
| Optional luminance channel. |
Second it can be a mapping pointing out a shared memory segment.
| The shared memory segment. |
| The width and height of the memory segment. |
| |
| The format of the memory segment, e.g. |
| The low level format of the memory segment, e.g.
|
int
GLUE.BaseTexture.t_width
int
GLUE.BaseTexture.t_height
Texture dimensions
int
GLUE.BaseTexture.texture_type
The texture type, e.g. GL.GL_TEXTURE_2D
.
void
use()
Use the generated texture (GL.glBindTexture
).
A displaylist that is generated on demand.
On Windows lists needs to be regenerated when the video driver
mode is changed. Thus the DynList is to prefer over List
, since
regeneration is done automatically upon video mode change.
void
call()
Call the displaylist, ie draw it.
GLUE.DynList GLUE.DynList(
function
(:void
)|void
f
)
Create a new DynList object and optionally set a function that can generate the displaylist
f
Function which contains the GL commands that generates the displaylist.
inherit List : List
void
init()
Generates the displaylist, ie calls the function set in
set_generator
. Called only when the display list needs to
be generated.
void
modeswitch()
Called by videodriver when a video mode change occurs.
void
set_generator(function
(:void
) _generator
)
Sets a function which can generate a displaylist. Hint: Use implicit lambda...
A font.
GLUE.Font GLUE.Font(
Image.Fonts.Font
f
, float
|void
_scale_width
, float
|void
_scale_spacing
)
array
(int
|BaseTexture
|Region
) get_character(int
c
)
Returns the advance (in pixels), the texture and the texture coordinates for the specified character, or 0 if it's nonprintable.
If the font->write call fails, the backtrace will be written to stderr.
array
(float
) text_extents(string
text
, float
h
)
Get the width and height of the area that the string text
in
size h
would cover.
array
(List
|float
) write(string
text
, float
h
, void
|float
|Region
roi
, string
|void
align
)
Create a display list that writes text.
text
The text to write.
h
The font height
roi
The region, if supplied, to restrict writing to.
align
The text justification; "left" (default), "center" or "right".
array
(float
) write_now(string
text
, float
h
, void
|float
|Region
roi
, string
|void
align
)
Write the text
in size [h], possibly restricted by region roi
.
Return the width and height of the resulting text area. If roi
is
a float, Region(0.0, 0.0, roi, 10000.0)
will be used.
A character to draw.
void
draw()
Draw the character using the texture txt
with the
texture-coordinates indicated in pos
, possible cropped with
slice
.
inherit Region : Region
Region
GLUE.Font.Character.pos
Character position in texture txt
.
void
set_data(Region
_pos
, BaseTexture
_txt
, void
|Region
_slice
)
Set character to be region _slice
of region _pos
of
texture _txt
.
Region
GLUE.Font.Character.slice
Slice of character to be shown.
BaseTexture
GLUE.Font.Character.txt
Texture holding the character.
A display list abstraction. Automatically allocates a display list id upon creation and correctly deallocate it upon destruction.
DynList
bool
res = GLUE.List()
> x
List
objects can be sorted according to list id.
get_id
void
begin(bool
|void
run
)
Start defining the list. If run
is provided, the list will
be executed as it is compiled (GL.GL_COMPILE_AND_EXECUTE
).
end
, compile
void
call()
Execute the commands in the list.
void
compile(function
(:void
) f
)
Compile a list be executing the list code f
. Exceptions in
f
will be thrown after GL.glEndList
has been called.
begin
GLUE.List GLUE.List(
void
|function
(:void
) f
)
When creating a new list, the list code can be compiled upon
creation by supplying a function f
that performs the GL
operations.
call
List list = List() { // GL code };
protected
void
destroy()
Deletes this list and frees the list id from the id pool.
void
end()
Finish the list definition.
begin
, compile
int
get_id()
Returns this lists' id.
Convenience version of the RectangleTexture
class.
inherit BaseDWIM : BaseDWIM
Convenience methods
inherit RectangleTexture : RectangleTexture
Texture base
Uses the NVidia RECT texture extension for non-power-of-two textures.
inherit BaseTexture : BaseTexture
A rectangle. Used by the text routines to avoid drawing outside the current region.
Region
res = GLUE.Region()
& R
Creates a new region with the intersection of this region and R
.
GLUE.Region GLUE.Region(
float
x
, float
y
, float
w
, float
h
)
float
GLUE.Region.x
float
GLUE.Region.y
float
GLUE.Region.w
float
GLUE.Region.h
bool
inside(Region
R
)
Returns 1 if the region R
is fully inside this region.
constant
int
GLUE.Region.is_region
All region objects have this constant.
void
move(float
xp
, float
yp
)
Move the region xp
units right and yp
units down.
bool
outside(Region
R
)
Returns 1 if the region R
is fully outside this region.
void
resize(float
xs
, float
ys
)
Make the region xs
units wider and ys
units higher.
A mesh of squares.
GLUE.SquareMesh GLUE.SquareMesh(
function
(float
, float
:Math.Matrix
) calculator
)
The calculator
will be called for each corner and should
return a 1x3 matrix describing the coordinates for the given
spot om the surface.
void
draw()
Draw the mesh.
void
recalculate()
Recalculate the mesh.
void
set_lighting(bool
do_lighting
)
Indicate whether or not lighting is used. If it is, the normals of each vertex will be calculated as well as the coordinates.
void
set_size(int
x
, int
y
)
Set the size of the mesh
void
set_texture(BaseTexture
tex
)
Set a texture to be mapped on the mesh.
Math.Matrix
surface_normal(int
x
, int
y
)
Return the normal for the surface at coordinates x,y. Used internally.
Convenience version of the Texture
class.
inherit BaseDWIM : BaseDWIM
Convenience methods
inherit BaseTexture : BaseTexture
Texture base
GLUE Event abstraction.
constant
int
GLUE.Events.BACKSPACE
constant
int
GLUE.Events.DELETE
constant
int
GLUE.Events.TAB
constant
int
GLUE.Events.F1
constant
GLUE.Events.F2
constant
GLUE.Events.F3
constant
GLUE.Events.F4
constant
GLUE.Events.F5
constant
GLUE.Events.F6
constant
GLUE.Events.F7
constant
GLUE.Events.F8
constant
GLUE.Events.F9
constant
GLUE.Events.F10
constant
GLUE.Events.F11
constant
GLUE.Events.F12
constant
int
GLUE.Events.ESCAPE
constant
int
GLUE.Events.UP
constant
int
GLUE.Events.DOWN
constant
int
GLUE.Events.LEFT
constant
int
GLUE.Events.RIGHT
constant
int
GLUE.Events.PGUP
constant
int
GLUE.Events.PGDWN
constant
int
GLUE.Events.ENTER
constant
int
GLUE.Events.SPACE
constant
int
GLUE.Events.HOME
constant
int
GLUE.Events.END
constant
int
GLUE.Events.PAUSE
constant
int
GLUE.Events.INSERT
constant
int
GLUE.Events.SCROLL_LOCK
constant
int
GLUE.Events.SYS_REQ
constant
int
GLUE.Events.PRINT_SCRN
constant
int
GLUE.Events.CAPSLOCK
constant
int
GLUE.Events.MENU
constant
int
GLUE.Events.NUMLOCK
constant
int
GLUE.Events.A
constant
int
GLUE.Events.B
constant
int
GLUE.Events.C
constant
int
GLUE.Events.D
constant
int
GLUE.Events.E
constant
int
GLUE.Events.F
constant
int
GLUE.Events.G
constant
int
GLUE.Events.H
constant
int
GLUE.Events.I
constant
int
GLUE.Events.J
constant
int
GLUE.Events.K
constant
int
GLUE.Events.L
constant
int
GLUE.Events.M
constant
int
GLUE.Events.N
constant
int
GLUE.Events.O
constant
int
GLUE.Events.P
constant
int
GLUE.Events.Q
constant
int
GLUE.Events.R
constant
int
GLUE.Events.S
constant
int
GLUE.Events.T
constant
int
GLUE.Events.U
constant
int
GLUE.Events.V
constant
int
GLUE.Events.W
constant
int
GLUE.Events.X
constant
int
GLUE.Events.Y
constant
int
GLUE.Events.Z
Numeric constant representing a key.
Event
ALT(int
|Event
X
)
array
(Event
) ALT(array
(int
|Event
) X
)
Adds the _ALT
modifier to an Event
, key or array of Events
and/or keys.
constant
int
GLUE.Events.BUTTON_1
constant
int
GLUE.Events.BUTTON_2
constant
int
GLUE.Events.BUTTON_3
constant
int
GLUE.Events.BUTTON_4
constant
int
GLUE.Events.BUTTON_5
Numeric constant representing a mouse button.
Event
CTRL(int
|Event
X
)
array
(Event
) CTRL(array
(int
|Event
) X
)
Adds the _CTRL
modifier to an Event
, key or array of Events
and/or keys.
constant
int
GLUE.Events.EXIT
Numeric constant representing an exit event.
constant
GLUE.Events.KNOWN_MODIFIERS
Integer constant with the union of all known modifiers, i.e.
_SHFT | _CTRL | _ALT
.
constant
int
GLUE.Events.LSHIFT
constant
int
GLUE.Events.RSHIFT
constant
int
GLUE.Events.LCTRL
constant
int
GLUE.Events.RCTRL
constant
int
GLUE.Events.LALT
constant
int
GLUE.Events.RALT
Numeric constant representing a modifier key.
constant
GLUE.Events.MODIFIERS
Mapping that maps a modifier key to any of the symbolic modifiers
_SHFT
, _CTRL
and _ALT
.
constant
int
GLUE.Events.MOUSE_UP
constant
int
GLUE.Events.MOUSE_DOWN
constant
int
GLUE.Events.MOUSE_LEFT
constant
int
GLUE.Events.MOUSE_RIGHT
constant
int
GLUE.Events.MOUSE_ABS
Numeric constant representing a mouse movement.
Event
SHFT(int
|Event
X
)
array
(Event
) SHFT(array
(int
|Event
) X
)
Adds the _SHFT
modifier to an Event
, key or array of Events
and/or keys.
constant
int
GLUE.Events._ALT
Integer constant representing alternate.
constant
int
GLUE.Events._CTRL
Integer constant representing control.
constant
int
GLUE.Events._SHFT
Integer constant representing shift.
bool
is_modifier(int
k
)
Returns 1
if the key code k
is a modifier key, e.g.
LSHIFT
or RSHIFT
.
constant
GLUE.Events.key_names
Mapping that maps key identifiers with a printable name, e.g.
LSHIFT
to "Left shift"
.
Contains an event.
GLUE.Events.Event GLUE.Events.Event(
int
|void
_key
, bool
|void
_press
, string
|void
_data
, int
|void
_modifiers
, float
|void
pressure
)
this_program
dup()
Returns a copy of this Event object.
bool
GLUE.Events.Event.press
Press event or release event.
float
GLUE.Events.Event.pressure
The pressure of the key stroke. A value between 0.0 and 1.0. Unknown values are represented as 0.
This is pike glue for GSS-API ver 2 as specified in RFC 2743.
GSS-API is used to authenticate users and servers, and optionally also to encrypt communication between them. The API is generic and can be used without any knowledge of the actual implementation of these security services, which is typically provided by the operating system.
The most common implementation at the time of writing is Kerberos, which means that the main benefit of this API is to allow clients and servers to authenticate each other using Kerberos, thereby making single sign-on possible in a Kerberized environment.
All functions in this module that wraps GSS-API routines might throw
GSSAPI.Error
, and by default they do for all such errors. Only in
some special cases do they return when a GSS-API error has happened,
and that is noted in the documentation.
constant
int
GSSAPI.INITIATE
constant
int
GSSAPI.ACCEPT
constant
int
GSSAPI.BOTH
Flags for indicating how a GSSAPI.Cred
object may be used:
The credential can only be used to initiate security contexts
(i.e. using GSSAPI.InitContext
).
The credential can only be used to accept security contexts
(i.e. using GSSAPI.AcceptContext
).
The credential may be used both to initiate or accept security contexts.
constant
int
GSSAPI.DELEG_FLAG
constant
int
GSSAPI.MUTUAL_FLAG
constant
int
GSSAPI.REPLAY_FLAG
constant
int
GSSAPI.SEQUENCE_FLAG
constant
int
GSSAPI.CONF_FLAG
constant
int
GSSAPI.INTEG_FLAG
constant
int
GSSAPI.ANON_FLAG
constant
int
GSSAPI.PROT_READY_FLAG
constant
int
GSSAPI.TRANS_FLAG
Bitfield flags returned by e.g. GSSAPI.Context.services
to
denote various services that are available in the context.
Brief descriptions of the flags:
Delegation. See RFC 2743 section 1.2.9.
Mutual authentication (actually, acceptor authentication). See RFC 2743 sections 1.1.1.3 and 1.2.5.
Per-message replay detection. See RFC 2743 section 1.2.3.
Per-message sequencing. See RFC 2743 section 1.2.3.
Per-message confidentiality. See RFC 2743 section 1.2.2.
Per-message integrity. See RFC 2743 section 1.2.2.
Anonymous authentication. See RFC 2743 section 1.2.5.
Might be set before the context establishment has finished, to
denote that per-message protection already is available. See RFC
2743 section 1.2.7. Is always set in GSSAPI.Context
and derived
classes when the context is established.
The context can be transferred between processes using
GSSAPI.Context.export
. See RFC 2743 section 1.2.10.
constant
int
GSSAPI.BAD_MECH
constant
int
GSSAPI.BAD_NAME
constant
int
GSSAPI.BAD_NAMETYPE
constant
int
GSSAPI.BAD_BINDINGS
constant
int
GSSAPI.BAD_STATUS
constant
int
GSSAPI.BAD_SIG
constant
int
GSSAPI.NO_CRED
constant
int
GSSAPI.NO_CONTEXT
constant
int
GSSAPI.DEFECTIVE_TOKEN
constant
int
GSSAPI.DEFECTIVE_CREDENTIAL
constant
int
GSSAPI.CREDENTIALS_EXPIRED
constant
int
GSSAPI.CONTEXT_EXPIRED
constant
int
GSSAPI.FAILURE
constant
int
GSSAPI.BAD_QOP
constant
int
GSSAPI.UNAUTHORIZED
constant
int
GSSAPI.UNAVAILABLE
constant
int
GSSAPI.DUPLICATE_ELEMENT
constant
int
GSSAPI.NAME_NOT_MN
Constants for routine errors in major status codes like
GSSAPI.Error.major_status
. See RFC 2743 section 1.2.1.1. Note
that major status codes have to be masked with
GSSAPI.ERROR_MASK
before comparison with these.
Brief descriptions of the flags:
Channel binding mismatch.
Unsupported mechanism requested.
Invalid name provided.
Name of unsupported type provided.
Invalid input status selector.
Token had invalid integrity check.
Specified security context expired.
Expired credentials detected.
Defective credential detected.
Defective token detected.
Failure, unspecified at GSS-API level.
GSSAPI.Error.minor_status
should provide further details.
No valid security context specified.
No valid credentials provided.
Unsupported QOP value.
Operation unauthorized.
Operation unavailable.
Duplicate credential element requested.
Name contains multi-mechanism elements.
constant
int
GSSAPI.CONTINUE_NEEDED
constant
int
GSSAPI.DUPLICATE_TOKEN
constant
int
GSSAPI.OLD_TOKEN
constant
int
GSSAPI.UNSEQ_TOKEN
constant
int
GSSAPI.GAP_TOKEN
Bitfield flags for informatory codes in major status codes like
GSSAPI.Error.major_status
. See RFC 2743 section 1.2.1.1. Any
combination of these might optionally be combined with one routine
error constant to form a major status code.
Brief descriptions of the flags:
Continuation call to routine required.
Duplicate per-message token detected.
Timed-out per-message token detected.
Reordered (early) per-message token detected.
Skipped predecessor token(s) detected.
constant
int
GSSAPI.ERROR_MASK
Bitfield mask for the routine error part of major status codes
like GSSAPI.Error.major_status
. After applying this mask, the
status values may be compared to any of the routine error
constants.
constant
int
GSSAPI.INFO_MASK
Bitfield mask for the informatory part of major status codes like
GSSAPI.Error.major_status
.
constant
string
GSSAPI.NT_HOSTBASED_SERVICE
constant
string
GSSAPI.NT_USER_NAME
constant
string
GSSAPI.NT_MACHINE_UID_NAME
constant
string
GSSAPI.NT_STRING_UID_NAME
constant
string
GSSAPI.NT_ANONYMOUS
constant
string
GSSAPI.NT_EXPORT_NAME
constant
string
GSSAPI.KRB5_NT_PRINCIPAL_NAME
OIDs on dotted-decimal form for the GSS-API mechanism-independent name types, and some selected mechanism-specific ones:
Name type for a service associated with a host computer. The syntax is service@hostname where the @hostname part may be omitted for the local host. See RFC 2743 section 4.1.
Name type for a named user on a local system. The syntax is username. See RFC 2743 section 4.2.
Name type for a numeric user identifier corresponding to a user on a local system. The string representing a name of this type should contain a locally-significant user ID, represented in host byte order. See RFC 2743 section 4.3.
Name type for a string of digits representing the numeric user identifier of a user on a local system. This name type is similar to the Machine UID Form, except that the buffer contains a string representing the user ID. See RFC 2743 section 4.4.
Name type to identify anonymous names. See RFC 2743 section 4.5.
Name type for the Mechanism-Independent Exported Name Object
type, which is the type of the names returned by
GSSAPI.Name.export
. See RFC 2743 section 4.7.
Name type for a Kerberos principal. See RFC 1964 section 2.1.1.
string
describe_services(int
services
)
Returns a string that compactly describes the given services
,
which is taken as a bitfield of GSSAPI.*_FLAG flags.
The returned string contains capitalized names for the flags
reminiscent of the GSSAPI.*_FLAG
constants, separated by
"|"
.
multiset
(string
) indicate_mechs()
Returns the OIDs for the available mechanism in the GSS-API implementation. The OIDs are returned on dotted-decimal form.
This wraps GSS_Indicate_mechs according to RFC 2743 section 2.4.2.
array
(string
) major_status_messages(int
major_status
)
Given a major status code like GSSAPI.Error.major_status
(or
more commonly GSSAPI.Context.last_major_status
in this case),
returns an array containing messages for all the status values in
it. The returned string(s) presumably don't end with linefeeds.
This wraps GSS_Display_status according to RFC 2743 section 2.4.1.
array
(string
) minor_status_messages(int
minor_status
, void
|string
mech
)
Given a mechanism-specific minor status code like
GSSAPI.Error.minor_status
, returns an array containing messages
for all the status values in it. The returned string(s) presumably
don't end with linefeeds.
This wraps GSS_Display_status according to RFC 2743 section 2.4.1.
minor_status
The mechanism-specific minor status.
mech
The mechanism that produced the status code. If this is zero or left out, a system default mechanism is used.
multiset
(string
) names_for_mech(string
mech
)
Returns the OIDs for the name types that the given mech
supports. Both mech
and the returned OID strings are on
dotted-decimal form.
This wraps GSS_Inquire_names_for_mech according to RFC 2743 section 2.4.12.
Variant of Context
which is used on the acceptor side.
string
accept(string
remote_token
)
Accepts a remotely initiated security context.
This wraps GSS_Accept_sec_context according to RFC 2743 section 2.2.2.
The underlying mechanism might require several tokens to be
passed back and forth to establish the context. If
is_established
returns zero after a call to this function
then the caller must wait for a token from the remote peer to
feed as remote_token
in another call to this function.
remote_token
A token from the remote peer, as returned by a call to
GSSAPI.InitContext.init
or some other
GSS_Init_sec_context wrapper.
If a string is returned then it must be passed to the remote
peer which will feed it to GSSAPI.InitContext.init
or some
other GSS_Init_sec_context wrapper. An empty string is
never returned.
Zero is returned if there is no token to send to the remote
peer. Note that is_established
might still return zero in
that case, meaning more remote tokens are necessary.
This function might block on network connections to remote authentication servers.
GSSAPI.AcceptContext GSSAPI.AcceptContext(
void
|Cred
cred
, void
|int
required_services
)
Creates a context for acceptor use. This function only accepts
parameters to be used later during the accept
call. If there
are semantic problems with them, such as if the credentials are
stale, then they will be signalled later by accept
.
cred
Credentials for the identity this context claims. The credentials for the default principal (if any) is used if zero or left out.
required_services
Bitfield of GSSAPI.*_FLAG flags specifying all services
that must be provided in the context. If the context fail to
provide any of them then it is closed and a
GSSAPI.MissingServicesError
is thrown.
GSSAPI.PROT_READY_FLAG
is ignored in this parameter. The fact
that a user calls a per-message function indicates that this
service is required at that point, and a
GSSAPI.MissingServicesError
is thrown if it isn't.
Channel bindings (RFC 2743, section 1.1.6) are not yet implemented since that feature appear to not be in much active use, and its format is not completely specified (RFC 2744, section 3.11).
Cred
delegated_cred()
Returns the delegated credentials from the initiator if the
delegation (c.f. GSSAPI.DELEG_FLAG
) service is in use.
inherit Context : Context
Class representing a security context; see RFC 2743 section 1.1.3.
The user usually instantiates one of the two inheriting classes
GSSAPI.InitContext
or GSSAPI.AcceptContext
, based on whether
the context should act as initiator or acceptor for the
connection. This class is instantiated directly for imported
contexts.
If a Context
object for a partly or completely established
context is destructed, GSS_Delete_sec_context (RFC 2743,
section 2.2.3) is called. That function might do blocking
network I/O, which due to pike's object management might occur
essentially anytime in any thread if the object isn't explicitly
destructed. To avoid that, it's strongly recommended to call
delete
in contexts that are no longer used.
GSSAPI.Context GSSAPI.Context(
string
interprocess_token
, void
|int
required_services
)
Creates a context by importing an inter-process token.
This wraps GSS_Import_sec_context according to RFC 2743 section 2.2.9.
interprocess_token
The inter-process token which has been created by export
or
some other GSS_Export_sec_context wrapper.
required_services
Bitfield of GSSAPI.*_FLAG flags specifying all services
that must be provided in the context. If the context fail to
provide any of them then it is closed and a
GSSAPI.MissingServicesError
is thrown.
GSSAPI.PROT_READY_FLAG
is ignored in this parameter. The fact
that a user calls a per-message function indicates that this
service is required at that point, and a
GSSAPI.MissingServicesError
is thrown if it isn't.
It is not possible to retrieve delegated credentials from an imported context. That is a GSS-API limitation.
void
delete()
Frees the resources for the context, provided it is in use. Does nothing otherwise.
This wraps GSS_Delete_sec_context according to RFC 2743 section 2.2.3.
This function might block on network connections to remote authentication servers.
In compliance with recommendations in GSS-API v2, the optional output token is never used in the call to GSS_Delete_sec_context.
string
export()
Exports this context so that it can be imported in another
process, providing the inter-process context transfer service is
available (c.f. GSSAPI.TRANS_FLAG
).
This wraps GSS_Export_sec_context according to RFC 2743 section 2.2.8.
The returned string is intended to be fed to
GSSAPI.Context.create
(or some other
GSS_Import_sec_context wrapper) in the receiving process.
This operation frees the context in this object.
string
get_mic(string
message
, void
|int
qop
)
Calculates and returns a MIC (message integrity checksum) for
the given message that allows the receiver to verify its origin
and integrity through verify_mic
or some other
GSS_VerifyMIC wrapper.
This wraps GSS_GetMIC according to RFC 2743 section 2.3.1.
This function requires that the context is established, or that
the early per-message protection service is available (c.f.
GSSAPI.PROT_READY_FLAG
. If not, a
GSSAPI.MissingServicesError
is thrown (but the context is not
closed).
message
The message for which the MIC is to be calculated. It may be of zero length.
qop
The quality of protection. This is a mechanism-specific value that lets the user direct how the underlying mechanism calculates the MIC. See RFC 2743, section 1.2.4.
Zero or left out means use the default method.
int
is_established()
int
services()
int
locally_initiated()
Name
source_name()
Name
target_name()
int(0..)
lifetime()
string
mech()
Functions to query various properties about the context.
These wrap GSS_Inquire_context according to RFC 2743 section 2.2.6.
Returns nonzero as soon as the context has been established.
That means no further rounds through
GSSAPI.InitContext.init
or GSSAPI.AcceptContext.accept
,
that the remote peer is authenticated as required, and that
the set of available services is complete (see services
).
Returns a bitfield of GSSAPI.*_FLAG flags for the
services that the context (currently) provides. This field is
complete only when the context establishment has finished,
i.e. when is_established
returns nonzero.
See also GSSAPI.describe_services
.
Returns nonzero if the context is an initiator, zero if it is an acceptor. (This is mainly useful in imported contexts.)
Returns the name of the context initiator. The name is always
an MN. Returns an anonymous name if used on the acceptor side
and the anonymous authentication service (c.f.
GSSAPI.ANON_FLAG
) was used.
Returns the name of the context acceptor. If a name is returned then it is always an MN.
Zero is returned on the initiator side if the initiator didn't
specify a target name and the acceptor did not authenticate
itself (should never happen if mutual authentication (c.f.
GSSAPI.MUTUAL_FLAG
) is a required service).
The returned object is not necessarily the same one as was
passed to GSSAPI.InitContext.create
, even though they are
likely to compare as equal (they might not be equal if the
passed name wasn't an MN).
Returns the validity lifetime left for the context. Returns
zero if the context has expired, or Int.inf
if there is no
time limit (in older pikes without Int.inf
a large positive
integer is returned instead).
Returns the mechanism that provides the context. The returned value is its OID on dotted-decimal form.
These functions don't throw errors if the context is missing or not completely established, even though they might not be able to query the proper values then (GSS-API implementations are known to not be completely reliable in handling these queries for partly established contexts). The functions instead return zero.
int
last_confidential()
Returns nonzero if the last call to wrap
or unwrap
provided
confidentiality for the message, i.e. if wrap
encrypted it or
if unwrap
decrypted it. Zero is returned otherwise.
int
last_major_status()
int
last_minor_status()
Returns the major and minor status codes from the last operation that called a GSS-API routine, with the exception of those that wrap GSS_Inquire_context.
int
last_qop()
Returns the quality of protection provided by the last call to
verify_mic
or unwrap
.
void
process_token(string
remote_token
)
Passes the given remote_token
to the mechanism.
This wraps GSS_Process_context_token according to RFC 2743 section 2.2.4.
This is used for tokens that are received outside the
handshaking between GSS_Init_sec_context
(GSSAPI.InitContext.init
) and GSS_Accept_sec_context
(GSSAPI.AcceptContext.accept
).
An example is when GSSAPI.InitContext.init
returns a final
token and flags the context as established, but the acceptor
context detects an error and sends a failure token back. That
token is processed using this function since
GSSAPI.InitContext.init
doesn't handle any more tokens by
then.
This function might change context state.
This function might block on network connections to remote authentication servers. However, if the remote token is the result of GSS_Delete_sec_context on the remote side then it will not block.
int
required_services(void
|int
services
)
Gets and optionally sets the set of services that must be provided in the context. The returned and given value is a bitfield of the GSSAPI.*_FLAG constants.
This is mainly useful to change the per-message service flags that
verify_mic
and unwrap
use to decide whether a condition is
an error or not.
services
New set of required services. If this is not given then the set is not changed.
If the context is established and services
contain a service
which isn't currently provided then the context is closed and a
GSSAPI.MissingServicesError
is thrown immediately.
GSSAPI.PROT_READY_FLAG
is ignored in this parameter.
Returns the current set of required services (after setting them
to services
, if provided).
GSSAPI.describe_services
string
unwrap(string
message
, void
|int
accept_encrypted_only
)
Verifies the origin and integrity of the given message using the
MIC included in it, and also decrypts the message if it was
encrypted. The message has been calculated by the sender using
wrap
or some other GSS_Wrap wrapper.
This wraps GSS_Unwrap according to RFC 2743 section 2.3.4.
This function requires that the context is established, or that
the early per-message protection service is available (c.f.
GSSAPI.PROT_READY_FLAG
. If not, a
GSSAPI.MissingServicesError
is thrown (but the context is not
closed).
message
The message to be unwrapped.
accept_encrypted_only
If this is nonzero then it is an error if message
isn't
encrypted, and zero is returned in that case (the status
returned by last_major_status
will still indicate success,
though).
Zero is returned if the verification fails with
GSSAPI.DEFECTIVE_TOKEN
or GSSAPI.BAD_MIC
.
Zero is also returned if message
isn't encrypted and
accept_encrypted_only
is set.
Otherwise the message is successfully decrypted (provided it was
encrypted to begin with), and its origin and integrity checks
out, but it might still be considered wrong depending on whether
the replay detection or sequencing services are required (see
required_services
):
If replay detection (c.f. GSSAPI.REPLAY_FLAG
) is required
then zero is returned if the message is duplicated
(GSSAPI.DUPLICATE_TOKEN
) or old (GSSAPI.OLD_TOKEN
).
If sequencing (c.f. GSSAPI.SEQUENCE_FLAG
) is required then in
addition to the replay detection conditions, zero is also
returned if the message is out of sequence
(GSSAPI.UNSEQ_TOKEN
or GSSAPI.GAP_TOKEN
).
Otherwise the unwrapped message is returned, which is valid
according to the currently required services (note however that
requiring the confidentiality service does not imply that an
error is signalled whenever an unencrypted message is received -
see instead accept_encrypted_only
above).
Any GSS-API errors except GSSAPI.DEFECTIVE_TOKEN
and
GSSAPI.BAD_MIC
are thrown.
This function sets the value returned by last_confidential
and last_qop
.
Even if the message is considered valid by the return value,
last_major_status
may be called to check for the informatory
codes mentioned above.
int
verify_mic(string
message
, string
mic
)
Verifies the origin and integrity of the given message
using
the given mic
, which has been calculated by the sender using
get_mic
or some other GSS_GetMIC wrapper.
This wraps GSS_VerifyMIC according to RFC 2743 section 2.3.2.
This function requires that the context is established, or that
the early per-message protection service is available (c.f.
GSSAPI.PROT_READY_FLAG
. If not, a
GSSAPI.MissingServicesError
is thrown (but the context is not
closed).
Zero is returned if the verification fails with
GSSAPI.DEFECTIVE_TOKEN
or GSSAPI.BAD_MIC
.
Otherwise the message origin and integrity checks out, but it
might still be considered wrong depending on whether the replay
detection or sequencing services are required (see
required_services
):
If replay detection (c.f. GSSAPI.REPLAY_FLAG
) is required
then zero is returned if the message is duplicated
(GSSAPI.DUPLICATE_TOKEN
) or old (GSSAPI.OLD_TOKEN
).
If sequencing (c.f. GSSAPI.SEQUENCE_FLAG
) is required then in
addition to the replay detection conditions, zero is also
returned if the message is out of sequence
(GSSAPI.UNSEQ_TOKEN
or GSSAPI.GAP_TOKEN
).
Otherwise nonzero is returned to indicate that the message is valid according to the currently required services.
Any GSS-API errors except GSSAPI.DEFECTIVE_TOKEN
and
GSSAPI.BAD_MIC
are thrown.
This function sets the value returned by last_qop
.
Regardless whether the message is considered valid or not by the
return value, last_major_status
may be called to check for
routine errors or the informatory codes mentioned above.
string
wrap(string
message
, void
|int
encrypt
, void
|int
qop
)
Calculates a MIC (message integrity checksum) for the given
message, and returns it together with the message, which is
optionally encrypted. The returned value can be verified and (if
applicable) decrypted by the receiver using unwrap
or some
other GSS_Unwrap wrapper.
This wraps GSS_Wrap according to RFC 2743 section 2.3.3.
This function requires that the context is established, or that
the early per-message protection service is available (c.f.
GSSAPI.PROT_READY_FLAG
. If not, a
GSSAPI.MissingServicesError
is thrown (but the context is not
closed).
message
The message to be wrapped. It may be of zero length.
encrypt
Set to nonzero to request that the message is encrypted. Otherwise only a MIC is calculated and the returned value contains the unencrypted message.
If this is set and the confidentiality service (c.f.
GSSAPI.CONF_FLAG
) is required then the returned value is
always encrypted. Otherwise it might not be encrypted anyway,
and a call to last_confidential
will tell if it is or not.
qop
The quality of protection. This is a mechanism-specific value that lets the user direct how the underlying mechanism calculates the MIC. See RFC 2743, section 1.2.4.
Zero or left out means use the default method.
This function sets the value returned by last_confidential
.
wrap_size_limit
int(0..)
wrap_size_limit(int(0..)
output_size
, int
encrypt
, void
|int
qop
)
Returns the maximum size of an input string to wrap
that
would produce no more than output_size
bytes in the resulting
output.
This wraps GSS_Wrap_size_limit according to RFC 2743 section 2.2.7.
with_confidentiality
and qop
are the same as in the call
to wrap
.
Objects of this class hold one or more credentials that the current process can use to assert identities; see RFC 2743 section 1.1.1.
If a Cred
object is destructed, GSS_Release_cred
(RFC 2743, section 2.1.2) is called. The RFC doesn't preclude
that that function might do blocking network I/O, which due to
pike's object management might occur essentially anytime in any
thread if the object isn't explicitly destructed. To avoid that,
it's recommended to call release
in credential objects that
are no longer used.
GSSAPI.Name
name(void
|string
mech
)
int
cred_usage(void
|string
mech
)
multiset
(string
) mechs()
int(0..)
|Int.inf
lifetime()
int(0..)
|Int.inf
init_lifetime(string
mech
)
int(0..)
|Int.inf
accept_lifetime(string
mech
)
Functions to query various properties about the credentials.
These wrap GSS_Inquire_cred according to RFC 2743 section
2.1.3 if mech
is not given, and
GSS_Inquire_cred_by_mech according to section 2.1.5
otherwise.
mech
If this is given then the credential for that specific
mechanism is queried. mech
contains the OID of the
mechanism on dotted-decimal form.
Some of the query functions can only be used for a specific
mechanism, in which case mech
is required. Some can only be
used on the credentials in general, and the mech
argument
is not applicable. Some can be used both ways, and then
mech
is optional.
name (void|string mech)
Returns the name of the identity that the credential(s)
assert. If mech
is given then the returned name is a
Mechanism Name (MN).
The returned GSSAPI.Name
object is always a newly created
one, even though it typically compares as equal with the ones
given to acquire
or add
.
cred_usage (void|string mech)
Returns how the credential(s) may be used, one of
GSSAPI.INITIATE
, GSSAPI.ACCEPT
or GSSAPI.BOTH
.
If mech
is not given then the returned usage value reflects
the union of the capabilities in all credentials.
mechs() Returns the set of mechanisms supported by the credential. The returned value is a multiset of strings with OIDs on dotted-decimal form.
lifetime() Returns the shortest validity lifetime left in any of the mechanisms that are part of the credentials, for either initiator or acceptor use.
Returns zero if some part of the credentials has expired.
Returns Int.inf
if there is no time limit (in older pikes
without Int.inf
a large positive integer is returned
instead).
init_lifetime (string mech) Returns the validity lifetime left for initiator use.
Returns zero if the credential has expired for this use or if
its usage is GSSAPI.ACCEPT
.
Returns Int.inf
if there is no time limit (in older pikes
without Int.inf
a large positive integer is returned
instead).
accept_lifetime (string mech) Returns the validity lifetime left for acceptor use.
Returns zero if the credential has expired for this use or if
its usage is GSSAPI.INITIATE
.
Returns Int.inf
if there is no time limit (in older pikes
without Int.inf
a large positive integer is returned
instead).
RFC 2743 doesn't preclude that these functions might block on network connections to remote authentication servers.
void
acquire(Name
|string
name
, int
cred_usage
, void
|multiset
(string
) desired_mechs
, void
|int(0..)
desired_time
)
Acquire initial credentials for this object. It is an error if it already has some credentials.
This wraps GSS_Acquire_cred according to RFC 2743 section 2.1.1.
name
The name of the identity for which credentials should be acquired. It is up to the GSS-API implementation to check whether the running process is authorized to act on behalf of this identity.
This can be either a GSSAPI.Name
object or a string. In the
latter case, the string is converted to a GSS-API name
according to a mechanism-specific default printable syntax,
i.e. just like if it would be given as the sole argument to
GSSAPI.Name.create
.
If this is zero then credentials for the default principal (if any) are retrieved.
cred_usage
Specifies how the credential will be used. One of
GSSAPI.INITIATE
, GSSAPI.ACCEPT
or GSSAPI.BOTH
.
desired_mechs
The mechanisms that the credentials should cover, as a multiset containing their OIDs on dotted-decimal form. If zero or left out then a default set provided by the GSS-API implementation is used.
It is an error to pass an empty multiset.
desired_time
Number of seconds the credentials should remain valid. The GSS-API implementation may return credentials that are valid both longer and shorter than this. Zero or left out means use the maximum permitted time.
This function might block on network connections to remote authentication servers.
void
add(Name
|string
name
, int
cred_usage
, string
desired_mech
, void
|int(0..)
|array
(int(0..)
) desired_time
)
Adds another credential element to this object. If this object has no credentials already then it will get the default credentials in addition to this specified one.
This wraps GSS_Add_cred according to RFC 2743 section 2.1.4.
name
The name of the identity for which a credential should be acquired. It is up to the GSS-API implementation to check whether the running process has sufficient privileges to act on behalf of this identity.
This can be either a GSSAPI.Name
object or a string. In the
latter case, the string is converted to a GSS-API name
according to a mechanism-specific default printable syntax,
i.e. just like if it would be given as the sole argument to
GSSAPI.Name.create
.
If this is zero then a credential for the default principal (if any) are retrieved.
cred_usage
Specifies how the credential will be used. One of
GSSAPI.INITIATE
, GSSAPI.ACCEPT
or GSSAPI.BOTH
.
desired_mech
The mechanism that the credential should cover, as an OID on dotted-decimal form.
desired_time
Number of seconds the credential should remain valid. The GSS-API implementation may return a credential that is valid both longer and shorter than this. Zero or left out means use the maximum permitted time.
This can also be an array containing two elements. In that case the first element applies to the credential when it is used to initiate contexts, and the second element applies to use for acceptor contexts.
This function might block on network connections to remote authentication servers.
void
release()
Frees the resources for the credential.
This wraps GSS_Release_cred according to RFC 2743 section 2.1.2.
This function might block on network connections to remote authentication servers.
Error object used for GSS-API errors.
GSSAPI.Error GSSAPI.Error(
void
|int
major
, void
|int
minor
, void
|string
mech
, void
|string
message
, void
|array
backtrace
)
major
Initial value for major_status
.
minor
Initial value for minor_status
.
mech
Object identifier on dotted-decimal form for the mechanism that
minor
applies to.
message
Error message. This is prepended to the message generated from
major_status
and/or minor_status
. ": "
is inserted
in between.
backtrace
Backtrace. The current backtrace for the calling function is used if left out.
constant
int
GSSAPI.Error.is_gssapi_error
constant
string
GSSAPI.Error.error_type
Object recognition constants.
inherit Error.Generic : Error.Generic
int
GSSAPI.Error.major_status
The major status code. This is a bitwise OR of one routine error code and zero or more supplementary error info bits.
See RFC 2743 section 1.2.1.1 and RFC 2744 section 3.9.1. Note that the calling errors mentioned in RFC 2744 are never thrown.
major_status_messages
array
(string
) major_status_messages()
Returns an array containing messages for all the status values in
major_status
. See GSSAPI.major_status_messages
for further
details.
int
GSSAPI.Error.minor_status
The minor status code specific for the mechanism.
minor_status_messages
, minor_status_mech
string
minor_status_mech()
Returns the OID for the mechanism that is used to interpret the minor status, or zero if no mechanism has been set. It is returned on dotted-decimal form.
array
(string
) minor_status_messages()
Returns an array containing messages for all the status values in
minor_status
. See GSSAPI.minor_status_messages
for further
details.
Variant of Context
which is used on the initiator side.
GSSAPI.InitContext GSSAPI.InitContext(
void
|Cred
cred
, void
|Name
|string
target_name
, void
|string
mech
, void
|int
required_services
, void
|int
desired_services
, void
|int(0..)
desired_time
)
Creates a context for initiator use. This function only accepts
parameters to be used later during the init
call. If there
are semantic problems with them, such as if the credentials are
stale or the mechanism isn't supported, then they will be
signalled later by init
.
cred
Credentials for the identity this context claims. The credentials for the default principal (if any) is used if zero or left out.
target_name
The name of the target.
This can be either a GSSAPI.Name
object or a string. In the
latter case, the string is converted to a GSS-API name
according to a mechanism-specific default printable syntax,
i.e. just like if it would be given as the sole argument to
GSSAPI.Name.create
.
Some mechanisms support unnamed targets (as allowed in GSS-API v2, update 1) and in such cases this may be zero or left out.
mech
The mechanism to use. It is given as an OID on dotted-decimal form. The GSS-API implementation chooses this using system settings if it's zero or left out, which is the recommended way.
required_services
Bitfield of GSSAPI.*_FLAG flags specifying all services
that must be provided in the context. If the context fail to
provide any of them then it is closed and a
GSSAPI.MissingServicesError
is thrown.
GSSAPI.PROT_READY_FLAG
is ignored in this parameter. The fact
that a user calls a per-message function indicates that this
service is required at that point, and a
GSSAPI.MissingServicesError
is thrown if it isn't.
desired_services
Bitfield of GSSAPI.*_FLAG flags specifying the context
services that are wanted but not required. I.e. errors won't
be thrown if any of these aren't provided. The services
specified in required_services
are implicit, so they need
not be repeated here.
GSSAPI.PROT_READY_FLAG
is ignored in this parameter.
desired_time
The desired context validity time in seconds. Zero or left out means use the default.
Channel bindings (RFC 2743, section 1.1.6) are not yet implemented since that feature appear to not be in much active use, and its format is not completely specified (RFC 2744, section 3.11).
inherit Context : Context
string
init(void
|string
remote_token
)
Initiates a security context to send to a remote peer.
This wraps GSS_Init_sec_context according to RFC 2743 section 2.2.1.
The underlying mechanism might require several tokens to be
passed back and forth to establish the context. If
is_established
returns zero after a call to this function
then the caller must wait for a token from the remote peer to
feed as remote_token
in another call to this function.
remote_token
A token from the remote peer, as returned by a call to
GSSAPI.AcceptContext.accept
(or some other
GSS_Accept_sec_context wrapper) in it. This is zero or
left out on the initial call, but used later if the remote
peer sends back tokens to process as part of the context
establishment.
If a string is returned then it must be passed to the remote
peer which will feed it to GSSAPI.AcceptContext.accept
or
some other GSS_Accept_sec_context wrapper. An empty
string is never returned.
Zero is returned if there is no token to send to the remote
peer. Note that is_established
might still return zero in
that case, meaning more remote tokens are necessary.
This function might block on network connections to remote authentication servers.
Error object used when one or more required services are missing
in a GSSAPI.Context
object.
GSSAPI.MissingServicesError GSSAPI.MissingServicesError(
void
|int
missing_services
)
missing_services
Initial value for services
.
constant
int
GSSAPI.MissingServicesError.is_gssapi_missing_services_error
constant
string
GSSAPI.MissingServicesError.error_type
Object recognition constants.
inherit Error.Generic : Error.Generic
int
GSSAPI.MissingServicesError.services
Bitfield of GSSAPI.*_FLAG flags for the missing services that caused the error.
GSSAPI.describe_services
An object of this class contains a name on the internal form which is required by the GSS-API functions. See RFC 2743, section 1.1.5.
int
hash_value( GSSAPI.Name arg )
Tries to export the name (see export
) and if that succeeds
returns a hash made from the exported name string. Otherwise a
normal hash based on this object is returned.
This means that mechanism names (MNs) can be used as indices in mappings without getting duplicate entries for the same identity.
int
res = GSSAPI.Name()
== other
Returns true if other
is a GSSAPI.Name
which contains a
name that refers to the same identity as this one.
This wraps GSS_Compare_name according to RFC 2743 section 2.4.3.
If either GSSAPI.Name
object is uninitialized or contains an
anonymous identity then they are considered different, unless it
is the very same GSSAPI.Name
object (that is an inherent pike
behavior).
An error is thrown if the names are incomparable, or if either of them are ill-formed.
Name
canonicalize(string
mech
)
Returns a GSSAPI.Name
containing the canonical mechanism name
(MN) of this name. The mechanism is given as a dotted-decimal
OID in mech
.
This wraps GSS_Canonicalize_name according to RFC 2743 section 2.4.14.
This function might block on network connections to remote authentication servers.
GSSAPI.Name GSSAPI.Name(
string
name
, void
|string
name_type
)
This wraps GSS_Import_name according to RFC 2743 section 2.4.5.
name
A name on string form (a contiguous string name in GSS-API parlance).
name_type
The OID on dotted-decimal form for the type of the name in
name
. If left out, name
is parsed according to a
mechanism-specific default printable syntax.
If name
is the result of export
or a similar function
then name_type
should be GSSAPI.NT_EXPORT_NAME
.
string
display_name()
string
display_name_type()
display_name
returns a representation of the name for display
purposes, and display_name_type
returns an OID on
dotted-decimal form for the type of that name.
If no type was given to create
then display_name_type
might return zero.
This wraps GSS_Display_name according to RFC 2743 section 2.4.4.
The GSSAPI.NT_* constants.
string
export(void
|string
mech
)
Returns the name on the exported format. If mech
isn't given
then the name has to be a mechanism name (MN). If mech
is
given then the name is canonicalized according to that mechanism
before being exported (see canonicalize
).
This wraps GSS_Export_name according to RFC 2743 section 2.4.15.
This function might block on network connections to remote
authentication servers if mech
is specified.
multiset
(string
) mechs()
Returns the OIDs for the mechanisms that might be able to process this name. The returned OID strings are on dotted-decimal form.
This wraps GSS_Inquire_mechs_for_name according to RFC 2743 section 2.4.13.
Some older GSS-API v2 implementations lack this funcion.
GTKSupport.Alert GTKSupport.Alert(
string
text
, string
|void
title
)
inherit GTK1.Dialog : Dialog
GTK1.Button
ok()
Returns the ok Button
object.
A Clist
with scrollbars. Defines the same interface as
Clist
.
A Drawing area with backing store. Basically, the only difference from a drawing area widget is that this one never loose it's contents unless you do paint over them.
It also use quite a significant amount of memory if the backing pixmap has many bitplanes, and the drawing area is large.
GTK1.DrawingArea
inherit GTK1.DrawingArea : DrawingArea
array
(object
) MenuFactory(MenuDef
... definition
)
This is the function that actually builds the menubar.
import GTK1.MenuFactory; [GTK1.MenuBar bar, GTK1.AcceleratorTable map] = MenuFactory( MenuDef( "File/New", new_file, 0, "A-N" ), MenuDef( "File/Open", new_file, 1, "A-O" ), MenuDef( "File/Save", save_file, 0, "A-S" ), MenuDef( "File/<separator>", 0, 0 ), MenuDef( "File/Quit", _exit, 0, "A-Q" ), );
Array | |
| GTK1.MenuBar |
| GTK1.AcceleratorTable |
array
(object
) PopupMenuFactory(MenuDef
... definition
)
Identical to MenuFactory
, but creates popup menus instead.
Array | |
| GTK1.Menu |
| GTK1.AccelGroup |
mapping
get_menubar_mapping()
Returns a (flat) mapping ([ path:GTK1.MenuItem ])
.
This function can only be called after the menubar is created.
void
set_menubar_modify_callback(function
(:void
) to
)
The function passed as the argument to this function will be called each time the accelerator key mapping is changed by the user with the new mapping as the argument.
This function is only used when the menubar is created, once you are done with the menubar creation, the callbacks for that menubar will be fixed.
Definition of a menu item.
void
assign_shortcut(string
sc
)
Sets a new shortcut as the current one.
The shortcut syntax is: m[m[..]]-key, where m is one or more modifier character, and key is the desired key (NOTE: Key must be in the range 0-255 currently, this will hopefully be fixed by the GTK people in the future)
The modifiers are:
| Shift |
| Control |
| Modifier 1 (called alt by the GTK people, that's not true, though) |
| |
| Modifier 2 (called altgr by the GTK people, that's not true, though) |
| |
| Modifier 3 (not mapped by the GTK people, meta on _my_ keyboard) |
| |
| Modifier 4 (not mapped by the GTK people, hyper on _my_ keyboard) |
| |
| Modifier 5 (not mapped by the GTK people, super on _my_ keyboard) |
|
GTKSupport.MenuFactory.MenuDef GTKSupport.MenuFactory.MenuDef(
string
path
, function
(:void
)|void
cb
, mixed
|void
cbarg
, string
|void
binding
, int
|void
right
)
path
Path is the menupath. A submenu will be created for each
"Directory" in the path, and menuitems will be created for the
"files". There are two special cases: The "file"
"<separator>"
will create a thin line. The "file"-prefix
"<check>"
will make the menuitem a checkmenuitem instead
of a normal menuitem.
cb
cbarg
The second and third arguments are the callback function and the
first callback function argument. If the callback function
argument is an array, the indices of the array will be pushed as
arguments. To call the function with an array as the only
argument, make an array with the array in. The callback function
will be called like callback( arg, widget )
, or if arg
is an array, callback( arg[0], arg[1], ..., widget )
.
shortcut
The fourth argument, shortcut, is the shortcut to bind to this
menu item. The shortcut can be changed later on by calling
assign_shortcut
, or by the user by pressing the desired
keycombination over the menu item.
The shortcut syntax is: m[m[..]]-key, where m is one or more modifier character, and key is the desired key (NOTE: Key must be in the range 0-255 currently, this will hopefully be fixed by the GTK people in the future)
The modifiers are:
| Shift |
| Control |
| Modifier 1 (called alt by the GTK people, that's not true, though) |
| |
| Modifier 2 (called altgr by the GTK people, that's not true, though) |
| |
| Modifier 3 (not mapped by the GTK people, meta on _my_ keyboard) |
| |
| Modifier 4 (not mapped by the GTK people, hyper on _my_ keyboard) |
| |
| Modifier 5 (not mapped by the GTK people, super on _my_ keyboard) |
|
right
Currently ignored.
mapping
decode_image(string
data
, mapping
|array
|void
tocolor
)
Decodes an image as a GDK1.Pixmap
.
| The MIME content type of the image. |
| The alpha channel of the image, if any. Otherwise |
| The decoded image. |
mapping
load_image(string
filename
, array
|void
bgcol
)
Loads and decodes an image as a GDK1.Pixmap
.
| The MIME content type of the image. |
| The alpha channel of the image, if any. Otherwise |
| The decoded image. |
This class contains a geographical position, ie a point on the earths surface. The resulting position object implements comparision methods (__hash, `==, `< and `>) so that you can compare and sort positions as well as using them as index in mappings. Comparision is made primary on latidue and secondly on longitude. It does not currently take the ellipsoid into account.
It is possible to cast a position into an array, which will yield ({ float latitude, float longitude }), as well as into a string.
array
(float
) ECEF()
Returns the current position as Earth Centered Earth Fixed Cartesian Coordinates.
({ X, Y, Z })
string
GEOREF()
Gives the full GEOREF position for the current position, e.g. "LDJA0511".
array
(float
) RT38()
string
UTM(int
precision
)
Returns the current UTM coordinates position. An example output is "32T 442063.562 5247479.500" where the parts are zone number + zone designator, easting and northing.
array
(float
) UTM_offset()
Returns the offset within the present UTM cell. The result will be returned in an array of floats, containing easting and northing.
string
UTM_zone_designator()
Returns the UTM letter designator for the current latitude. Returns "Z" if latitude is outside the UTM limits of 84N to 80S.
int
UTM_zone_number()
Returns the UTM zone number for the current longitude, with correction for the Svalbard deviations.
int
hash_value( Geography.Position arg )
string sprintf(string format, ... Geography.Position arg ... )
int
res = Geography.Position()
< pos
int
res = Geography.Position()
== pos
int
res = Geography.Position()
> pos
float
Geography.Position.alt
Altitud of the position, in meters. Positive numbers is up. Zero is the shell of the current ellipsoid.
float
approx_height()
Returns a very crude approximation of where the ground level is at the current position, compared against the ellipsoid shell. WGS-84 is assumed, but the approximation is so bad that it doesn't matter which of the standard ellipsoids is used.
Geography.Position Geography.Position(
int
|float
lat
, int
|float
long
, void
|int
|float
alt
)
Geography.Position Geography.Position(
string
lat
, string
long
)
Geography.Position Geography.Position(
string
position
)
Geography.Position Geography.Position()
Constructor for this class. If fed with strings, it will perform a dwim scan on the strings. If they fails to be understood, there will be an exception.
float
eccentricity_squared()
Returns the first eccentricity squared for the selected earth approximation ellipsoid.
constant
Geography.Position.ellipsoids
A mapping with reference ellipsoids, which can be fed to the UTM converter. The mapping maps the name of the ellipsoid to an array where the first element is a float describing the equatorial radius and the second element is a float describing the polar radius.
float
Geography.Position.equatorial_radius
The equatorial radius is how many meters the earth radius is at the equator (east-west direction).
float
euclidian_distance(this_program
p
)
Calculate the euclidian distance between two Geography.Position. Result is in meter. This uses the ECEF function.
float
flattening()
Returns the flattening factor for the selected earth approximation ellipsoid.
float
Geography.Position.lat
Latitude (N--S) of the position, in degrees. Positive number is north, negative number is south.
string
latitude(void
|int
n
)
string
longitude(void
|int
n
)
Returns the nicely formatted latitude or longitude.
| "17°42.19'N" / "42°22.2'W" |
| "17.703°N" / "42.37°W" |
| "17°42.18'N" / "42°22.2'W" |
| "17°42'10.4"N" / "42°22'12"W" |
| "17.703" / "-42.37" |
float
Geography.Position.long
Longitude (W--E) of the position, in degrees. Positive number is east, negative number is west.
float
Geography.Position.polar_radius
The polar radius is how many meters the earth radius is at the poles (north-south direction).
bool
set_ellipsoid(string
name
)
bool
set_ellipsoid(float
equatorial_radius
, float
polar_radius
)
Sets the equatorial and polar radius to the provided values. A name can also be provided, in which case the radius will be looked up in the ellipsoid mapping. The function returns 1 upon success, 0 on failure.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The longitude and lattitude are not converted to the new ellipsoid.
void
set_from_RT38(int
|float
|string
x_n
, int
|float
|string
y_e
)
Sets the longitude and lattitude from the given RT38 coordinates.
void
set_from_UTM(int
zone_number
, string
zone_designator
, float
UTME
, float
UTMN
)
Sets the longitude and lattitude from the given UTM coordinates.
string
standard_grid()
Returns the standard map grid system for the current position. Can either be "UPS" or "UTM".
Create a Position object from a RT38 coordinate
inherit .Position : Position
mixed
`[](string
what
)
mixed
`->(string
what
)
Convenience functions for getting a country the name-space way; it looks up whatever it is in the name- and domain-space and returns that country if possible:
> Geography.Countries.se;
Result: Country(Sweden)
> Geography.Countries.djibouti;
Result: Country(Djibouti)
> Geography.Countries.com;
Result: Country(United States)
> Geography.Countries.wallis_and_futuna_islands->iso2;
Result: "WF"
mapping
(string
:array
(Country
)) continents()
Gives back a mapping from continent name to an array of the countries on that continent.
The continents are:
"Europe" "Africa" "Asia" "North America" "South America" "Oceania" "Antarctica"
Some countries are considered to be on more than one continent.
array
(Country
) Geography.Countries.countries
All known countries.
Country
from_domain(string
domain
)
Look up a country from a domain name. Returns zero if the domain doesn't map to a country. Note that there are some valid domains that don't:
International
US Military
Network
Non-Profit Organization
Old style Arpanet
Nato field
And that US has five domains, Great Britain and france two: <dl compact> <dt>EDU <dd>US Educational <dt>MIL <dd>US Military <dt>GOV <dd>US Government <dt>UM <dd>US Minor Outlying Islands <dt>US <dd>US <dt>GB <dd>Great Britain (UK) <dt>UK <dd>United Kingdom <dt>FR <dd>France <dt>FX <dd>France, Metropolitan <dt>There's also three domains that for convinience maps to US: <dt>NET <dd>Network <dt>ORG <dd>Organization <dt>COM <dd>Commercial </dl>
Country
from_domain(string
name
)
Look up a country from its name or aka. The search is case-insensitive but regards whitespace and interpunctation.
Country
string
Geography.Countries.Country.name
array
(string
) Geography.Countries.Country.aka
Country name and as-known-as, if any
(
string
)Geography.Countries.Country()
It is possible to cast a country to a string,
which will be the same as performing
country->name;
.
string
continent()
Returns the continent of the country.
Some countries are geographically in more then one continent; any of the continents might be returned then, but probably the continent in which the capital is resident - Europe for Russia, for instance.
string
Geography.Countries.Country.fips10
FIPS 10-character code; "Federal Information Processing Standards 10-3" etc, used by some goverments in the US.
int
Geography.Countries.Country.former
Flag that is set if this country doesn't exist anymore. (eg USSR.)
string
Geography.Countries.Country.iso2
ISO 2-character code aka domain name
void
parse_77(string
line
, object
tree
)
Parsing function for geoip databases in the format used my http://software77.net/.
void
parse_maxmind(string
line
, object
tree
)
Parsing function for geoip databases in the format used my http://www.maxmind.com/.
Base class for GeoIP lookups. Use Geography.GeoIP.IPv4
.
mixed
from_ip(string
ip
)
Returns the geographical location of the given ip address ip
.
When this object has been created using one of the standard parsing
functions the locations are instances of
Geography.Countries.Country
.
Class for GeoIP lookups of ipv4 addresses.
Uses ADT.CritBit.IPv4Tree
objects internally to map IPv4 addresses to
a geographical region.
Geography.GeoIP.IPv4 Geography.GeoIP.IPv4(
string
file_name
, function
(string
, ADT.CritBit.IPv4Tree
:void
) fun
)
Geography.GeoIP.IPv4 Geography.GeoIP.IPv4(
ADT.CritBit.IPv4Tree
tree
)
Objects of this class can either be created from a file
file_name
with an optional parsing function fun
.
When fun
is omitted, it defaults to
Geography.GeoIP.parse_maxmind
. fun
will be called for each line in
file_name
and the critbit tree to add the entry to.
Alternatively, an instance of ADT.CritBit.IPv4Tree
can be passed.
tree
is expected to map the first address of each range to
its geographical location.
inherit IP : IP
Getopt
is a group of functions which can be used to find command
line options.
Command line options come in two flavors: long and short. The short ones consists of a dash followed by a character (-t), the long ones consist of two dashes followed by a string of text (--test). The short options can also be combined, which means that you can write -tda instead of -t -d -a.
Options can also require arguments, in which case they cannot be combined. To write an option with an argument you write -t argument or -targument or --test=argument.
constant
int
Getopt.HAS_ARG
Used with find_all_options()
to indicate that an option
requires an argument.
find_all_options()
constant
int
Getopt.MAY_HAVE_ARG
Used with find_all_options()
to indicate that an option
takes an optional argument.
find_all_options()
constant
int
Getopt.NO_ARG
Used with find_all_options()
to indicate that an option
does not take an argument.
find_all_options()
array
(array
) find_all_options(array
(string
) argv
, array
(array
(array
(string
)|string
|int
)) options
, void
|int(-1..1)
posix_me_harder
, void
|int
throw_errors
)
This function does the job of several calls to find_option()
.
The main advantage of this is that it allows it to handle the
POSIX_ME_HARDER environment variable better. When either
the argument posix_me_harder
or the environment variable
POSIX_ME_HARDER is true, no arguments will be parsed after
the first non-option on the command line.
argv
The should be the array of strings that was sent as the second
argument to your main()
function.
options
Each element in the array options
should be an array on the
following form:
Array | |
| Name is a tag used to identify the option in the output. |
| Type is one of |
| This is a string or an array of string of options that will be
looked for. Short and long options can be mixed, and short options
can be combined into one string. Note that you must include the
dashes so that |
| This is a string or an array of strings containing names of environment variables that can be used instead of the command line option. |
| This is the default value a |
Only the first three elements need to be included.
posix_me_harder
Don't scan for arguments after the first non-option.
throw_errors
If throw_errors
has been specified find_all_options()
will
throw errors on failure. If it has been left out, or is
0
(zero), it will instead print an error message on
Stdio.stderr
and exit the program with result code 1 on
failure.
The good news is that the output from this function is a lot simpler.
find_all_options()
returns an array where each element is an array on
this form:
Array | |
| Option identifier name from the input. |
| Value given. If no value was specified, and no default has been specified, the value will be 1. |
find_all_options()
modifies argv
.
Index 0
(zero) of argv
is not scanned for options,
since it is reserved for the program name.
Getopt.get_args()
, Getopt.find_option()
string
|bool
find_option(array
(string
) argv
, array
(string
)|string
shortform
, array
(string
)|string
|void
longform
, array
(string
)|string
|void
envvars
, string
|bool
|void
def
, int
|void
throw_errors
)
This is a generic function to parse command line options of the type -f, --foo or --foo=bar.
argv
The first argument should be the array of strings that was sent as
the second argument to your main()
function.
shortform
The second is a string with the short form of your option. The short form must be only one character long. It can also be an array of strings, in which case any of the options in the array will be accepted.
longform
This is an alternative and maybe more readable way to give the
same option. If you give "foo"
as longform
your program
will accept --foo as argument. This argument can also be
an array of strings, in which case any of the options in the
array will be accepted.
envvars
This argument specifies an environment variable that can be used to specify the same option, to make it easier to customize program usage. It can also be an array of strings, in which case any of the mentioned variables in the array may be used.
def
This argument has two functions: It specifies if the option takes an
argument or not, and it informs find_option()
what to return if the
option is not present.
The value may be one of:
| The option does not require a value. |
| The option requires a value, and Note that a set option will always return a |
throw_errors
If throw_errors
has been specified find_option()
will
throw errors on failure. If it has been left out, or is
0
(zero), it will instead print an error message on
Stdio.stderr
and exit the program with result code 1 on
failure.
Returns the value the option has been set to if any.
If the option is present, but has not been set to anything
1
will be returned.
Otherwise if any of the environment variables specified in envvars
has
been set, that value will be returned.
If all else fails, def
will be returned.
If an option that requires an argument lacks an argument and
throw_errors
is set an error will be thrown.
find_option()
modifies argv
. Parsed options will be removed
from argv
. Elements of argv
that have been removed entirely will
be replaced with zeroes.
This function reads options even if they are written after the first non-option on the line.
Index 0
(zero) of argv
is not scanned for options,
since it is reserved for the program name.
Only the first ocurrance of an option will be parsed. To parse
multiple ocurrances, call find_option()
multiple times.
Getopt.get_args()
array
(string
) get_args(array
(string
) argv
, void
|int(-1..1)
posix_me_harder
, void
|int
throw_errors
)
This function returns the remaining command line arguments after
you have run find_option()
or find_all_options()
to find
all the options in the argument list. If there are any options
left not handled by find_option()
or find_all_options()
this function will fail.
If throw_errors
has been specified get_args()
will throw errors
on failure. If it has been left out, or is 0 (zero), it will
instead print an error message on Stdio.stderr
and exit the
program with result code 1 on failure.
On success a new argv
array without the parsed options is
returned.
Getopt.find_option()
, Getopt.find_all_options()
This is a module for interacting with the Git distributed version control system.
constant
int
Git.MODE_DIR
A subdirectory.
constant
int
Git.MODE_EXE
A normal, but executable file.
constant
int
Git.MODE_FILE
A normal (non-executable) file.
constant
int
Git.MODE_GITLINK
A gitlink (aka submodule reference).
constant
int
Git.MODE_SYMLINK
A symbolic link.
constant
string
Git.NULL_SHA1
The NULL SHA1.
string
git(string
git_dir
, string
command
, string
... args
)
Run a git command, and get the output.
git_dir
Directory containing the Git repository. May be UNDEFINED
to specify the Git repository for the current directory.
command
Git subcommand to execute.
args
Arguemnts for command
.
Returns the output on stdout from running the command on success, and throws and error on failure.
string
Git.git_binary
The git binary to use.
Defaults to "git"
, but may be overridden
to select a different binary.
string
hash_blob(string
data
)
Hash algorithm for blobs that is compatible with git.
Process.Process
low_git(mapping
(string
:mixed
) options
, string
git_dir
, string
command
, string
... args
)
Start a git process.
options
Options for Process.Process()
.
git_dir
Directory containing the Git repository. May be UNDEFINED
to specify the Git repository for the current directory.
command
Git subcommand to execute.
args
Arguemnts for command
.
Returns the corresponding Process.Process
object.
Framework for creating a command-stream suitable for git-fast-import.
void
blob(string
blob
, string
|void
marker
)
Upload data.
blob
Data to upload.
marker
Optional export marker for referring to the data.
void
cat_blob(string
dataref
)
Output a blob on the cat-blob-fd
.
dataref
Reference to the blob to output.
void
checkpoint()
Flush state to disk.
void
command(sprintf_format
cmd
, sprintf_args
... args
)
Send a raw command.
void
commit(string
ref
, string
|void
commit_marker
, string
|void
author_info
, string
committer_info
, string
message
, string
|void
... parents
)
Create a new commit on a branch.
ref
Reference to add the commit to.
Typically "refs/heads/"
followed by a branchname,
or "refs/notes/commits"
.
commit_marker
Optional export marker for referring to the new commit.
author_info
Optional author information. Defaults to committer_info
.
committer_info
Name, email and timestamp for the committer.
See format_author()
for details.
message
Commit message.
parents
The ordered set of parents for the commit.
Defaults to the current HEAD for ref
, if it exists,
and to the empty set otherwise.
The set of files for the commit defaults to the set
for the first of the parents
, and can be modified
with filemodify
, filedelete
, filecopy
, filerename
,
filedeleteall
and notemodify
.
Git.Export Git.Export()
Git.Export Git.Export(
Stdio.File
fd
)
Git.Export Git.Export(
string
git_dir
)
Create a new fast-import command-stream.
fd
File to write the command-stream to.
git_dir
Git directory to modify. If the directory doesn't exist, it will be created empty. A git-fast-import session will be started for the directory to receive the command-stream.
If neither fd
nor git_dir
has been specified, the
command stream will be output to Stdio.stdout
.
verbosity
The amount of verbosity on Stdio.stderr
for various commands.
int
done()
End the command-stream and wait for completion.
void
export(string
file_name
, string
|void
git_name
)
Convenience funtion for exporting a filesystem file or directory (recursively) to git.
file_name
Name of the file on disc.
git_name
Name of the file in git. Defaults to file_name
.
void
feature(string
feature
, string
|void
arg
)
Require that the backend for the stream supports a certian feature.
feature
Feature to require support for. Typically one of:
| Same as the corresponding command-line option. |
| |
| |
| |
| |
| |
| |
| Require the |
| |
| Require that the backend supports the |
| Require the stream to terminate with a |
void
filecopy(string
from
, string
to
)
Copy a file or directory.
void
filedelete(string
path
)
Delete a file.
void
filedeleteall()
Delete all files.
Used to start a commit from a clean slate.
void
filemodify(int
mode
, string
path
, string
|void
dataref
)
Create or modify a file.
mode
Mode for the file. See the MODE_* constants.
path
Path to the file relative to the repository root.
dataref
Reference to the data for the file. One of:
| A mark reference set by a prior |
| Left out, |
void
filerename(string
from
, string
to
)
Rename a file or directory.
void
ls(string
path
, string
|void
dataref
)
Output a file to the cat-blob-fd
.
path
Path to the file to output.
dataref
Marker, tag, commit or tree for the root. Defaults to the commit in progress.
void
notemodify(string
commit
, string
|void
dataref
)
Annotate a commit.
commit
Commit to annotate.
dataref
Reference to the data for the annotation. One of:
| A mark reference set by a prior |
| Left out, |
Note that this command is typically only used when
a commit on a ref under "refs/notes/"
is active.
void
option(string
option
)
Set backend options.
void
progress(string
message
)
Output a progress message.
message
Message to output.
Note that each line of the message will be prefixed
with "progress "
.
void
reset(string
ref
, string
|void
committish
)
Move a reference.
ref
Reference to move.
committish
Commit to reference.
This command can also be used to make light-weight tags.
tag
void
tag(string
name
, string
committish
, string
tagger_info
, string
message
)
Create an annotated tag referring to a specific commit.
name
Tag name. Note that it is automatically
prefixed with "refs/tags/"
.
committish
Commit to tag.
tagger_info
Name, email and timestamp for the tagger.
See format_author()
for details.
message
Message for the tag.
reset
GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. http://www.swox.com/gmp/
Gmp.mpz
fac(int
x
)
Returns the factorial of x
(x
!).
This program is used by the internal auto-bignum conversion. It can be used to explicitly type integers that are too big to be INT_TYPE. Best is however to not use this program unless you really know what you are doing.
Due to the auto-bignum conversion, all integers can be treated as
Gmp.mpz
objects insofar as that they can be indexed with the
functions in the Gmp.mpz
class. For instance, to calculate the
greatest common divisor between 51
and 85
, you can
do 51->gcd(85)
. In other words, all the functions in
Gmp.mpz
are also available here.
GMP floating point number.
The mantissa of each float has a user-selectable precision, limited only by available memory. Each variable has its own precision, and that can be increased or decreased at any time.
The exponent of each float is a fixed precision, one machine word on most systems. In the current implementation the exponent is a count of limbs, so for example on a 32-bit system this means a range of roughly 2^-68719476768 to 2^68719476736, or on a 64-bit system this will be greater.
Each variable keeps a size for the mantissa data actually in use. This means that if a float is exactly represented in only a few bits then only those bits will be used in a calculation, even if the selected precision is high.
All calculations are performed to the precision of the destination variable. Each function is defined to calculate with "infinite precision" followed by a truncation to the destination precision, but of course the work done is only what's needed to determine a result under that definition.
The precision selected for a variable is a minimum value, GMP may increase it a little to facilitate efficient calculation. Currently this means rounding up to a whole limb, and then sometimes having a further partial limb, depending on the high limb of the mantissa. But applications shouldn't be concerned by such details.
The mantissa in stored in binary, as might be imagined from the fact precisions are expressed in bits. One consequence of this is that decimal fractions like 0.1 cannot be represented exactly. The same is true of plain IEEE double floats. This makes both highly unsuitable for calculations involving money or other values that should be exact decimal fractions. (Suitably scaled integers, or perhaps rationals, are better choices.)
mpf functions and variables have no special notion of infinity or not-a-number, and applications must take care not to overflow the exponent or results will be unpredictable. This might change in a future release.
Note that the mpf functions are not intended as a smooth extension to IEEE P754 arithmetic. In particular results obtained on one computer often differ from the results on a computer with a different word size.
int
hash_value( Gmp.mpf arg )
bool
res = is_type(Gmp.mpf()
)
The Gmp.mpf object will claim to be a "float"
.
Perhaps it should also return true for "object"
?
string sprintf(string format, ... Gmp.mpf arg ... )
bool
res = !Gmp.mpf()
Gmp.mpf
res = Gmp.mpf()
* a
Gmp.mpf
res = Gmp.mpf()
+ a
Gmp.mpf()
+= a
Gmp.mpf
res = Gmp.mpf()
- a
Gmp.mpf
res = Gmp.mpf()
/ a
bool
res = Gmp.mpf()
< q
bool
res = Gmp.mpf()
== q
bool
res = Gmp.mpf()
> q
Gmp.mpf
res = a
* Gmp.mpf()
Gmp.mpf
res = sv
- Gmp.mpf()
Gmp.mpf
res = sv
/ Gmp.mpf()
Gmp.mpf
res = ~Gmp.mpf()
(
string
)Gmp.mpf()
(int
)Gmp.mpf()
(float
)Gmp.mpf()
Gmp.mpf Gmp.mpf(
void
|int
|string
|float
|object
x
, void
|int(0..)
precision
)
Gmp.mpf Gmp.mpf(
string
x
, int(0..)
precision
, int(2..36)
base
)
float
get_float()
Returns the value of the object as a float.
int
|object
get_int()
int(0..)
get_precision()
Returns the current precision, in bits.
string
get_string()
Gmp.mpf
set_precision(int(0..)
prec
)
Sets the precision of the current object to be at
least prec
bits. The precision is limited to 128Kb.
The current object will be returned.
int
sgn()
Rational number stored in canonical form. The canonical from means that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1. All functions canonicalize their result.
int
hash_value( Gmp.mpq arg )
bool
res = is_type(Gmp.mpq()
)
string sprintf(string format, ... Gmp.mpq arg ... )
bool
res = !Gmp.mpq()
Gmp.mpq
res = Gmp.mpq()
% a
a%b = a - floor(a/b)*b
Gmp.mpq
res = Gmp.mpq()
* a
Gmp.mpq
res = Gmp.mpq()
+ a
Gmp.mpq()
+= a
Gmp.mpq
res = Gmp.mpq()
- a
Gmp.mpq
res = Gmp.mpq()
/ a
bool
res = Gmp.mpq()
< q
bool
res = Gmp.mpq()
== q
bool
res = Gmp.mpq()
> q
Gmp.mpq
res = a
% Gmp.mpq()
Gmp.mpq
res = a
* Gmp.mpq()
Gmp.mpq
res = a
+ Gmp.mpq()
Gmp.mpq
res = sv
- Gmp.mpq()
Gmp.mpq
res = sv
/ Gmp.mpq()
Gmp.mpq
res = ~Gmp.mpq()
Defined as -1-x
.
(
int
)Gmp.mpq()
(string
)Gmp.mpq()
(float
)Gmp.mpq()
Casting to a string returns the number in the decimal fraction
format, where both decimal point and quotient is included only
if required. I.e. it is the same as calling get_string
with 1
as argument.
Gmp.mpq Gmp.mpq(
void
|string
|int
|float
|Gmp.mpz
|Gmp.mpq
x
)
Gmp.mpq Gmp.mpq(
int
numerator
, int
denominator
)
Gmp.mpq Gmp.mpq(
string
x
, int
base
)
int
den()
Returns the denominator. It is always positive.
float
get_float()
int
get_int()
string
get_string(void
|int
decimal_fraction
)
If decimal_fraction
is zero or left out, the number is
returned as a string on the form "numerator/denominator"
,
where both parts are decimal integers. The numerator may be
negative, but the denominator is always positive.
If decimal_fraction
is set, then the number is returned as a
(possibly negative) decimal fraction, i.e. a decimal number with
a decimal point somewhere inside. There is always at least one
digit before and after the decimal point.
If the number can be accurately described that way, i.e. without
an infinite number of decimals, then no denominator is included.
Otherwise the remaining denominator is added to the decimal
fraction after a "/". For example, 4711/100 is returned as
"47.11"
, 4711/200 as "23.555"
, and 4711/300 as
"47.11/3"
.
If decimal_fraction
is 1 then the decimal fraction contains a
'.' only if there are decimals in it. If it is 2 or higher then
the decimal fraction always contains a '.' with at least one
digit before and after it.
In any case, there are no unnecessary padding zeroes at the beginning or end of any decimal number.
Gmp.mpq
invert()
int
num()
Returns the numerator.
int(-1..1)
sgn()
Gmp.mpz implements very large integers. In fact, the only limitation on these integers is the available memory. The mpz object implements all the normal integer operations.
Note that the auto-bignum feature also makes these operations
available "in" normal integers. For instance, to calculate the
greatest common divisor between 51
and 85
, you can
do 51->gcd(85)
.
int
hash_value( Gmp.mpz arg )
Calculate a hash of the value.
Prior to Pike 7.8.359 this function returned the low 32-bits as an unsigned integer. This could in some common cases lead to very unbalanced mappings.
hash_value()
Gmp.mpz decode_value(string(8bit) data)
string(8bit) encode_value(Gmp.mpz data)
Gmp.mpz
random( Gmp.mpz arg )
string sprintf(string format, ... Gmp.mpz arg ... )
bool
res = !Gmp.mpz()
Gmp.mpz
res = Gmp.mpz()
% x
Gmp.mpz
res = Gmp.mpz()
& x
Gmp.mpz
res = Gmp.mpz()
* x
Gmp.mpz
res = Gmp.mpz()
+ x
Gmp.mpz
res = Gmp.mpz()
- x
Gmp.mpz
res = Gmp.mpz()
/ x
bool
res = Gmp.mpz()
< with
Gmp.mpz
res = Gmp.mpz()
<< x
bool
res = Gmp.mpz()
== with
bool
res = Gmp.mpz()
> with
Gmp.mpz
res = Gmp.mpz()
>> x
Gmp.mpz
res = Gmp.mpz()
^ x
Gmp.mpz
res = x
% Gmp.mpz()
Gmp.mpz
res = x
* Gmp.mpz()
Gmp.mpz
res = x
+ Gmp.mpz()
Gmp.mpz
res = x
- Gmp.mpz()
Gmp.mpz
res = x
/ Gmp.mpz()
Gmp.mpz
res = x
<< Gmp.mpz()
Gmp.mpz
res = x
>> Gmp.mpz()
Gmp.mpz
res = Gmp.mpz()
| x
Gmp.mpz
res = ~Gmp.mpz()
Gmp.mpz
bin(int
k
)
Return the binomial coefficient n
over k
, where
n
is the value of this mpz object. Negative values of
n
are supported using the identity
(-n)->bin(k) == (-1)->pow(k) * (n+k-1)->bin(k)
(See Knuth volume 1, section 1.2.6 part G.)
The k
value can't be arbitrarily large. An error is thrown if
it's too large.
This function is currently (Pike 7.8) not available with old releases of the gmp libraries.
(
string
)Gmp.mpz()
(int
)Gmp.mpz()
(float
)Gmp.mpz()
Cast this mpz object to another type. Allowed types are string, int and float.
cast_to_int
, cast_to_float
, cast_to_string
float
cast_to_float()
Casts the object to a float.
Use (float)
instead.
int
cast_to_int()
Casts the object to an integer.
Use (int)
instead.
string
cast_to_string()
Casts the object to a string.
Use (string)
instead.
Gmp.mpz Gmp.mpz()
Gmp.mpz Gmp.mpz(
string
|int
|float
|object
value
)
Gmp.mpz Gmp.mpz(
string
value
, int(2..36)
|int(256..256)
|int(-256..-256)
base
)
Create and initialize a Gmp.mpz
object.
value
Initial value. If no value is specified, the object will be initialized to zero.
base
Base the value is specified in. The default base is base 10.
The base can be either a value in the range [2..36] (inclusive),
in which case the numbers are taken from the ASCII range
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ (case-insensitive),
or either of the values 256
or -256
, in which
case value
is taken to be the unsigned binary representation in
network byte order or reversed byte order respectively.
Values in base [2..36] can be prefixed with "+"
or
"-"
. Values prefixed with "0b"
or "0B"
will be interpreted as binary. Values prefixed with "0x"
or "0X"
will be interpreted as hexadecimal. Values
prefixed with "0"
will be interpreted as octal.
Leading zeroes in value
are not significant when a base is
explicitly given. In particular leading NUL characters are not
preserved in the base 256 modes.
string
digits(void
|int(2..36)
|int(256..256)
|int(-256..-256)
base
)
Convert this mpz object to a string. If a base
is given the
number will be represented in that base. Valid bases are 2-36 and
256
and -256
. The default base is 10.
cast_to_string
Gmp.mpz
fac()
Return the factorial of this mpz object.
Since factorials grow very quickly, only small integers are supported. An error is thrown if the value in this mpz object is too large.
Gmp.mpz
gcd(object
|int
|float
|string
... args
)
Return the greatest common divisor between this mpz object and all the arguments.
array
(Gmp.mpz
) gcdext(int
|float
|Gmp.mpz
x
)
Compute the greatest common divisor between this mpz object and
x
. An array ({g,s,t})
is returned where g
is
the greatest common divisor, and s
and t
are the
coefficients that satisfies
this * s + x * t = g
gcdext2
, gcd
array
(Gmp.mpz
) gcdext2(int
|float
|Gmp.mpz
x
)
Compute the greatest common divisor between this mpz object and
x
. An array ({g,s})
is returned where g
is the
greatest common divisor, and s
is a coefficient that
satisfies
this * s + x * t = g
where t
is some integer value.
gcdext
, gcd
Gmp.mpz
invert(int
|float
|Gmp.mpz
x
)
Return the inverse of this mpz value modulo x
. The returned
value satisfies 0 <= result < x
.
An error is thrown if no inverse exists.
Gmp.mpz
next_prime()
Returns the next higher prime for positive numbers and the next lower for negative.
The prime number testing is using Donald Knuth's probabilistic primality test. The chance for a false positive is pow(0.25,25).
int
popcount()
For values >= 0, returns the population count (the number of set bits). For negative values (who have an infinite number of leading ones in a binary representation), -1 is returned.
Gmp.mpz
res = pow([Gmp.mpz]a, b) or Gmp.mpz
pow(int
|float
|Gmp.mpz
x
)
Return this mpz object raised to x
. The case when zero is
raised to zero yields one.
powm
Gmp.mpz
powm(int
|string
|float
|Gmp.mpz
exp
, int
|string
|float
|Gmp.mpz
mod
)
Return ( this->pow(
.exp
) ) % mod
pow
int(0..2)
probably_prime_p(void
|int
count
)
Return 2 if this mpz object is a prime, 1 if it probably is a prime, and 0 if it definitely is not a prime. Testing values below 1000000 will only return 2 or 0.
count
The prime number testing is using Donald Knuth's probabilistic primality test. The chance for a false positive is pow(0.25,count). Default value is 25 and resonable values are between 15 and 50.
int
sgn()
Return the sign of the integer, i.e. 1
for positive
numbers and -1
for negative numbers.
int(0..)
size(void
|int
base
)
Return how long this mpz would be represented in the specified
base
. The default base is 2.
int
small_factor(void
|int(1..)
limit
)
Gmp.mpz
res = sqrt([Gmp.mpz]a) or Gmp.mpz
sqrt()
Return the the truncated integer part of the square root of this mpz object.
array
(Gmp.mpz
) sqrtrem()
A standard way of providing a small about box for your application. You provide the name of your application, version, copyright, a list of authors and some comments about your application. It also allows the programmer to provide a logo to be displayed.
Gnome.About( "Example", "1.0", "(c) Roxen IS 2000\n(c) IDA, LiU 2002", ({"Per Hedbor"}), "Some nice documentation\nabout this example" );
Gnome.About Gnome.About(
string
title
, string
version
, string
copyright
, array
authors
, string
comment
, string
|void
logo
)
Creates a new GNOME About dialog. title, version, copyright, and authors are displayed first, in that order. comments is typically the location for multiple lines of text, if necessary. (Separate with "\n".) logo is the filename of a optional pixmap to be displayed in the dialog, typically a product or company logo of some sort; omit this argument if no logo file is available.
inherit Gnome.Dialog : Dialog
Toplevel GNOME applications would normally use one Gnome.App widget as their toplevel window. You can create as many Gnome.App widgets as you want, for example, some people use one GnomeApp per document their application loads.
Once you have created one instance of this widget, you would add your main application view information to this window by using set_contents() routine.
The GnomeApp has support for including a menubar, one or more toolbars and a statusbar for your application. It also takes care of intalling the accelerators for you when used in conjuction with the gnome-app-helper routines. The toolbars are inserted into Gnome.Dock widgets.
The gnome-app-helper module provides various helper routines to simplify the configuration of your menus and toolbars, but you can create those yourself and use the set_menus(), add_toolbar(), set_toolbar(), add_dock_item() and add_docked().
Gnome.App
add_dock_item(Gnome.DockItem
item
, int
placement
, int
band_num
, int
band_position
, int
|void
offset
)
Create a new Gnome.DockItem widget containing widget, and add it to app's dock with the specified layout information. Notice that, if automatic layout configuration is enabled, the layout is overridden by the saved configuration, if any.
item : Item to be added to app's dock placement : Placement for the new dock item, one of Gnome.DockTop, Gnome.DockRight, Gnome.DockBottom, Gnome.DockLeft and Gnome.DockFloating band_num : Number of the band where the dock item should be placed band_position : Position of the new dock item in band band_num offset : Offset from the previous dock item in the band; if there is no previous item, offset from the beginning of the band.
Gnome.App
add_docked(GTK1.Widget
widget
, string
name
, int
behavior
, int
placement
, int
band_num
, int
band_position
, int
|void
offset
)
Create a new Gnome.DockItem widget containing widget, and add it to app's dock with the specified layout information. Notice that, if automatic layout configuration is enabled, the layout is overridden by the saved configuration, if any.
widget : Widget to be added to app's dock
name : Name for the dock item that will contain toolbar
behavior : Behavior for the new dock item. One of GNOME_DOCK_ITEM_BEH_EXCLUSIVE
, GNOME_DOCK_ITEM_BEH_LOCKED
, GNOME_DOCK_ITEM_BEH_NEVER_FLOATING
, GNOME_DOCK_ITEM_BEH_NEVER_HORIZONTAL
, GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL
and GNOME_DOCK_ITEM_BEH_NORMAL
placement : Placement for the new dock item, one of Gnome.DockTop, Gnome.DockRight, Gnome.DockBottom, Gnome.DockLeft and Gnome.DockFloating
band_num : Number of the band where the dock item should be placed
band_position : Position of the new dock item in band band_num
offset : Offset from the previous dock item in the band; if there is no previous item, offset from the beginning of the band.
Gnome.App
add_toolbar(GTK1.Toolbar
toolbar
, string
name
, int
behavior
, int
placement
, int
band_num
, int
band_position
, int
|void
offset
)
Create a new Gnome.DockItem widget containing toolbar, and add it to app's dock with the specified layout information. Notice that, if automatic layout configuration is enabled, the layout is overridden by the saved configuration, if any.
toolbar : Toolbar to be added to app's dock
name : Name for the dock item that will contain toolbar
behavior : Behavior for the new dock item. One or more of GNOME_DOCK_ITEM_BEH_EXCLUSIVE
, GNOME_DOCK_ITEM_BEH_LOCKED
, GNOME_DOCK_ITEM_BEH_NEVER_FLOATING
, GNOME_DOCK_ITEM_BEH_NEVER_HORIZONTAL
, GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL
and GNOME_DOCK_ITEM_BEH_NORMAL
placement : Placement for the new dock item, one of Gnome.DockTop, Gnome.DockRight, Gnome.DockBottom, Gnome.DockLeft and Gnome.DockFloating
band_num : Number of the band where the dock item should be placed
band_position : Position of the new dock item in band band_num
offset : Offset from the previous dock item in the band; if there is no previous item, offset from the beginning of the band.
Gnome.App Gnome.App(
string
appname
, string
|void
title
)
Create a new (empty) application window. You must specify the application's name (used internally as an identifier). title can be left as 0, in which case the window's title will not be set.
Gnome.App
enable_layout_config(int
enable
)
Specify whether the the dock's layout configuration should be automatically saved via gnome-config whenever it changes, or not.
Gnome.Dialog
error(string
error
)
An important fatal error; if it appears in the statusbar, it might gdk_beep() and require acknowledgement.
Gnome.App
flash(string
flash
)
Flash the message in the statusbar for a few moments; if no statusbar, do nothing. For trivial little status messages, e.g. "Auto saving..."
Gnome.Dock
get_dock()
retrieved the Gnome.Dock widget contained in the App
Gnome.DockItem
get_dock_item_by_name(string
name
)
inherit GTK1.Window : Window
Gnome.Dialog
message(string
message
)
A simple message, in an OK dialog or the status bar. Requires confirmation from the user before it goes away. Returns 0 or a dialog widget. If 0, the message is displayed in the status bar.
Gnome.App
ok_cancel(string
question
, function
(:void
) callback
, mixed
cb_arg2
)
Ask a ok or cancel question and call the callback when it's answered.
Gnome.App
ok_cancel_modal(string
question
, function
(:void
) callback
, mixed
cb_arg2
)
Ask a ok or cancel question, block the application while it is asked, and call the callback when it's answered.
Gnome.AppProgressKey
progress_manual(string
prompt
)
Gnome.AppProgressKey
progress_timeout(string
prompt
, int
interval
, function
(:void
) cb
, mixed
cb_arg1
)
Gnome.App
question(string
question
, function
(:void
) reply_callback
, mixed
cb_arg2
)
Ask a yes or no question, and call the callback when it's answered.
Gnome.App
question_modal(string
question
, function
(:void
) callback
, mixed
cb_arg2
)
Ask a yes or no question, block the application while it is asked, and call the callback when it's answered.
Gnome.App
request_password(string
question
, function
(:void
) callback
, mixed
cb_arg2
)
As request string, but do not show the string
Gnome.App
request_string(string
question
, function
(:void
) callback
, mixed
cb_arg2
)
Request a string, and call the callback when it's answered.
Gnome.App
set_contents(GTK1.Widget
contents
)
Sets the status bar of the application window.
Gnome.App
set_menus(GTK1.MenuBar
menu_bar
)
Sets the menu bar of the application window.
Gnome.App
set_statusbar(GTK1.Widget
statusbar
)
Sets the status bar of the application window.
Gnome.App
set_toolbar(GTK1.Toolbar
toolbar
)
Sets the main toolbar of the application window.
Gnome.Dialog
warning(string
warning
)
A not-so-important error, but still marked better than a flash
Wrapper for the opaque GnomeAppProgressKey type
Gnome.AppProgressKey
destroy()
Gnome.AppProgressKey
done()
Gnome.AppProgressKey
set(float
percent
)
A bar that GNOME applications put on the bottom of the windows to
display status, progress, hints for menu items or a minibuffer for
getting some sort of response. It has a stack for status messages
Gnome.Appbar( 1, 1, Gnome.PreferencesUser )->set_progress( 0.4 );
Signals: clear_prompt Emitted when the prompt is cleared
user_response Emitted when the user hits enter after a prompt
Gnome.Appbar
clear_prompt()
Remove any prompt.
Gnome.Appbar
clear_stack()
Remove all status messages from appbar, and display default status message (if present).
Gnome.Appbar Gnome.Appbar(
int
has_progress
, int
has_status
, int
interactivity
)
Create a new GNOME application status bar. If has_progress is TRUE, a small progress bar widget will be created, and placed on the left side of the appbar. If has_status is TRUE, a status bar, possibly an editable one, is created.
interactivity determines whether the appbar is an interactive "minibuffer" or just a status bar. If it is set to Gnome.PREFERENCES_NEVER, it is never interactive. If it is set to Gnome.PREFERENCES_USER we respect user preferences from ui-properties. If it's Gnome.PREFERENCES_ALWAYS we are interactive whether the user likes it or not. Basically, if your app supports both interactive and not (for example, if you use the gnome-app-util interfaces), you should use Gnome.PREFERENCES_USER. Otherwise, use the setting you support. Please note that "interactive" mode is not functional now; GtkEntry is inadequate and so a custom widget will be written eventually.
GTK1.Progress
get_progress()
Returns GTK1.Progress widget pointer, so that the progress bar may be manipulated further.
string
get_response()
Get the response to the prompt, if any.
inherit GTK1.Hbox : Hbox
Gnome.Appbar
pop()
Remove current status message, and display previous status message, if any. It is OK to call this with an empty stack.
Gnome.Appbar
push(string
what
)
Push a new status message onto the status bar stack, and display it.
Gnome.Appbar
refresh()
Reflect the current state of stack/default. Useful to force a set_status to disappear.
Gnome.Appbar
set_default(string
default_status
)
What to show when showing nothing else; defaults to "".
Gnome.Appbar
set_progress(float
percentage
)
Sets progress bar to the given percentage. Pure sugar - with a bad name, in light of the get_progress name which is not the opposite of set_progress. Maybe this function should die.
Gnome.Appbar
set_prompt(string
prompt
, int
modal
)
Put a prompt in the appbar and wait for a response. When the user responds or cancels, a user_response signal is emitted.
Gnome.Appbar
set_status(string
status
)
Sets the status label without changing widget state; next set or push will destroy this permanently.
Applets are basically GNOME applications whose window sits inside the panel. Also the panel "takes care" of the applets by providing them with session saving and restarting, window management (inside of the panel), and a context menu.
The simplest applet one can write would be along the lines of:
int main( int argc, array argv ) { Gnome.init( "hello", "1.0", argv, 0 ); Gnome.AppletWidget("hello")->add(GTK1.Label("Hello World!"))->show_all(); GTK1.applet_widget_gtk_main(); }This creates an applet which just sits on the panel, not really doing anything, in real life the label would be substituted by something which actually does something useful. As you can see the applet doesn't really take care of restarting itself.
For the applet to be added to the menus, you need to install two files. Your x.gnorba file goes into $sysconfdir/CORBA/servers/ and the x.desktop file goes into $prefix/share/applets/<category>/.
Example hello.desktop:
[Desktop Entry] Name=Hello Applet Comment=An example Hello World type Applet Type=PanelApplet Exec=hello.pike Icon=gnome-hello.png Terminal=0Example hello.gnorba:
[hello] type=exe repo_id=IDL:GNOME/Applet:1.0 description=Hello Applet location_info=hello.pikeOne thing to keep in mind is that the Exec line for the .desktop doesn't actually get executed when the Type is PanelApplet. The Exec line should be the GOAD ID specified in the .gnorba file (the "hello" enclosed by brackets). For a simple applet all you need to do is replace the hello.pike with the name of your applet executable.
When the user right clicks on the applet, a menu appears, this is all handeled by the panel, so in order to add items to it you use a special interface to "add callbacks" to the menu. A very simple example would be (making our hello applet even more feature full):
void hello_there() { write( "Hello there, indeed!\n" ); } int main( int argc, array argv ) { Gnome.AppletWidget w; Gnome.init( "hello", "1.0", argv, 0 ); w = Gnome.AppletWidget("hello"); w->add(GTK1.Label("Hello World!"))->show_all(); w->register_callback( "hello", "Hello there", hello_there, 0 ); GTK1.applet_widget_gtk_main(); }Now the user will see a "Hello There" menu item on the applet menu, and when selected, the applet will print "Hello There". Useful huh?
Note that the first argument to the register_callback is just a string identifier of this callback, and can really be whatever you want. But it should NOT be translated as the label (the 2nd argument) should be.
Signals: back_change
change_orient
change_pixel_size
change_position
tooltip_state
Gnome.AppletWidget
abort_load()
Abort the applet loading, once applet has been created, this is a way to tell the panel to forget about us if we decide we want to quit before we add the actual applet to the applet-widget. This is only useful before before add() is called.
Gnome.AppletWidget
add(GTK1.Widget
what
)
Add a child (widget) to the applet. This finishes the handshaking with the panel started in applet_widget_new. You should never call this function twice for the same applet. If you have already created an applet widget, but need to cancel the loading of the applet, use abort_load.
Gnome.AppletWidget
callback_set_sensitive(string
name
, int
sensitive
)
Sets the sensitivity of a menu item in the applet's context menu.
Gnome.AppletWidget Gnome.AppletWidget(
string
applet_name
)
Make a new applet and register us with the panel, if you decide to cancel the load before calling add, you should call abort_load.
int
get_free_space()
Gets the free space left that you can use for your applet. This is the number of pixels around your applet to both sides. If you strech by this amount you will not disturb any other applets. If you are on a packed panel 0 will be returned.
string
get_globcfgpath()
int
get_panel_orient()
Gets the orientation of the panel this widget is on. it can be one
of GNOME_Panel_ORIENT_DOWN
, GNOME_Panel_ORIENT_LEFT
, GNOME_Panel_ORIENT_RIGHT
and GNOME_Panel_ORIENT_UP
. This is not the position of the
panel, but rather the direction that the applet should be "reaching
out". So any arrows should for example point in this direction. It
will be OrientUp or OrientDown for horizontal panels and OrientLeft
or OrientRight for vertical panels
int
get_panel_pixel_size()
Gets the width of the panel in pixels. This is not the actual size, but the recomended one. The panel may be streched if the applets use larger sizes then this.
string
get_privcfgpath()
inherit GTK1.Plug : Plug
Gnome.AppletWidget
register_callback(string
name
, string
menutext
, function
(:void
) callback_cb
, mixed
callback_arg
)
Adds a menu item to the applet's context menu. The name should be a path that is separated by '/' and ends in the name of this item. You need to add any submenus with register_callback_dir.
Gnome.AppletWidget
register_callback_dir(string
name
, string
menutext
)
Adds a submenu to the applet's context menu. The name should be the full path of the new submenu with the name of the new submenu as the last part of the path. The name can, but doesn't have to be terminated with a '/'.
Gnome.AppletWidget
register_stock_callback(string
name
, string
stock_type
, string
menutext
, function
(:void
) callback_cb
, mixed
callback_arg
)
Adds a menu item to the applet's context menu with a stock GNOME pixmap. This works almost exactly the same as register_callback.
Gnome.AppletWidget
register_stock_callback_dir(string
name
, string
stock_type
, string
menutext
)
Adds a submenu to the applet's context menu with a stock GNOME pixmap. This is similiar to register_callback_dir.
Gnome.AppletWidget
remove()
Remove the plug from the panel, this will destroy the applet. You can only call this once for each applet.
Gnome.AppletWidget
send_position(int
enable
)
If you need to get a signal everytime this applet changes position relative to the screen, you need to run this function with TRUE for enable and bind the change_position signal on the applet. This signal can be quite CPU/bandwidth consuming so only applets which need it should use it. By default change_position is not sent.
Gnome.AppletWidget
set_tooltip(string
to
)
Set a tooltip on the entire applet that will follow the tooltip setting from the panel configuration.
Gnome.AppletWidget
set_widget_tooltip(GTK1.Widget
widget
, string
text
)
Set a tooltip on the widget that will follow the tooltip setting from the panel configuration.
Gnome.AppletWidget
sync_config()
Tell the panel to save our session here (just saves, no shutdown). This should be done when you change some of your config and want the panel to save it's config, you should NOT call this in the session_save handler as it will result in a locked panel, as it will actually trigger another session_save signal for you. However it also asks for a complete panel save, so you should not do this too often, and only when the user has changed some preferences and you want to sync them to disk. Theoretically you don't even need to do that if you don't mind loosing settings on a panel crash or when the user kills the session without logging out properly, since the panel will always save your session when it exists.
Gnome.AppletWidget
unregister_callback(string
name
)
Remove a menu item from the applet's context menu. The name should be the full path to the menu item. This will not remove any submenus.
Gnome.AppletWidget
unregister_callback_dir(string
name
)
Removes a submenu from the applet's context menu. Use this instead of unregister_callback to remove submenus. The name can be, but doesn't have to be terminated with a '/'. If you have not removed the subitems of this menu, it will still be shown but without it's title or icon. So make sure to first remove any items and submenus before calling this function.
This widget provides a simple calculator that you can embed in your applications for doing quick computations.
The widget consists of a fully functional calculator including
standard arithmetic functions as well as trigonometric
capabilities, exponents, factorials, nested equations, and others.
Gnome.Calculator()
Signals: result_changed This signal is emited by the widget when the result has been changed.
Gnome.Calculator
clear(int
reset
)
Resets the calculator back to zero. If reset is TRUE, results stored in memory and the calculator mode are cleared also.
Gnome.Calculator Gnome.Calculator()
Create a new calculator widget
float
get_result()
Value currently stored in calculator buffer.
inherit GTK1.Vbox : Vbox
Gnome.Calculator
set(float
result
)
Sets the value stored in the calculator's result buffer to the given result.
This widget provides color selection facilities to your application. The widget appears as a button which contains a "color swatch" of the currently selected color. When the button is pressed, the widget presents the user with a color selection dialog where the color can be selected.
You can select the color to be displayed in a number of ways:
floating point values for the red, green and blue channels,
integers in the range 0 to 65,535, or integers in the range 0 to
255, depending on your needs.
Gnome.ColorPicker();
Signals: color_set This signal is emitted when the user changes the color on the color selector. The values passed to this signal are the red, green, blue and alpha channels selected in integer form in the range 0 to 65535.
Gnome.ColorPicker Gnome.ColorPicker()
Creates a new GNOME color picker widget. This returns a widget in the form of a small button containing a swatch representing the current selected color. When the button is clicked, a color-selection dialog will open, allowing the user to select a color. The swatch will be updated to reflect the new color when the user finishes.
mapping
get()
Returns a mapping ([ "d":([ "r":rvalue, "g":gvalue, "b":bvalue, "a":avalue ]), "i8":([ ... ]), "i16":([ .. ]) ]);
inherit GTK1.Button : Button
Gnome.ColorPicker
set_d(float
r
, float
g
, float
b
, float
a
)
Set color shown in the color picker widget using floating point values. The values range between 0.0 and 1.0.
Gnome.ColorPicker
set_dither(int
dither
)
Sets whether the picker should dither the color sample or just paint a solid rectangle.
Gnome.ColorPicker
set_i16(int
r
, int
g
, int
b
, int
a
)
Set color shown in the color picker widget using integer values. The values range between 0 and 65535.
Gnome.ColorPicker
set_i8(int
r
, int
g
, int
b
, int
a
)
Set color shown in the color picker widget using integer values. The values range between 0 and 255.
Gnome.ColorPicker
set_title(string
title
)
Sets the title for the color selection dialog
Gnome.ColorPicker
set_use_alpha(int
use_alpha
)
Sets whether or not the picker should use the alpha channel.
The GnomeDateEdit widget provides a way to enter dates and times
with a helper calendar to let the user select the date.
Gnome.DateEdit(time(),1,1);
Gnome.DateEdit(time(),0,1);
Signals: date_changed
time_changed
Gnome.DateEdit Gnome.DateEdit(
int
the_time
, int
show_time
, int
use_24_format
)
Creates a new GnomeDateEdit widget which can be used to provide an easy to use way for entering dates and times.
int
get_date()
Returns the configured time
inherit GTK1.Hbox : Hbox
Gnome.DateEdit
set_popup_range(int
low_hour
, int
high_hour
)
Sets the range of times that will be provide by the time popup selectors.
Gnome.DateEdit
set_time(int
the_time
)
Changes the displayed date and time in the GnomeDateEdit widget to be the one represented by the_time.
Gnome.Dialog gives dialogs a consistent look and feel, while making them more convenient to program. Gnome.Dialog makes it easy to use stock buttons, makes it easier to handle delete_event, and adds some cosmetic touches (such as a separator above the buttons, and a bevel around the edge of the window).
Signals: clicked
close
Gnome.Dialog
append_button_with_pixmap(string
name
, string
pixmap_file
)
Gnome.Dialog
button_connect(int
button
, function
(:void
) callback_cb
, mixed
callback_arg
)
Simply a signal_connect to the "clicked" signal of the specified button.
Gnome.Dialog
close()
See also close_hides(). This function emits the "close" signal( which either hides or destroys the dialog (destroy by default). If you connect to the "close" signal, and your callback returns TRUE, the hide or destroy will be blocked. You can do this to avoid closing the dialog if the user gives invalid input, for example.
Using close() in place of hide() or destroy() allows you to easily catch all sources of dialog closure, including delete_event and button clicks, and handle them in a central location.
Gnome.Dialog Gnome.Dialog(
string
title
, string
... buttons
)
Creates a new Gnome.Dialog, with the given title, and any button names in the arg list. Buttons can be simple names, such as "My Button", or gnome-stock defines such as GNOME.StockButtonOK, etc. The last argument should be NULL to terminate the list.
Buttons passed to this function are numbered from left to right, starting with 0. So the first button in the arglist is button 0, then button 1, etc. These numbers are used throughout the Gnome.Dialog API.
Gnome.Dialog
editable_enters(GTK1.Editable
widget
)
Normally if there's an editable widget (such as GtkEntry) in your dialog, pressing Enter will activate the editable rather than the default dialog button. However, in most cases, the user expects to type something in and then press enter to close the dialog. This function enables that behavior.
GTK1.Vbox
get_vbox()
inherit GTK1.Window : Window
int
run()
Blocks until the user clicks a button or closes the dialog with the window manager's close decoration (or by pressing Escape).
You need to set up the dialog to do the right thing when a button is clicked or delete_event is received; you must consider both of those possibilities so that you know the status of the dialog when run() returns. A common mistake is to forget about Escape and the window manager close decoration; by default, these call close(), which by default destroys the dialog. If your button clicks do not destroy the dialog, you don't know whether the dialog is destroyed when run() returns. This is bad.
So you should either close the dialog on button clicks as well, or change the close() behavior to hide instead of destroy. You can do this with close_hides().
int
run_and_close()
See run(). The only difference is that this function calls close() before returning if the dialog was not already closed.
Gnome.Dialog
set_accelerator(int
button
, int
accelerator_key
, int
accelerator_mode
)
Gnome.Dialog
set_close(int
click_closes
)
This is a convenience function so you don't have to connect callbacks to each button just to close the dialog. By default, Gnome.Dialog has this parameter set the FALSE and it will not close on any click. (This was a design error.) However, almost all the Gnome.Dialog subclasses, such as Gnome.MessageBox and Gnome.PropertyBox, have this parameter set to TRUE by default.
Gnome.Dialog
set_default(int
button
)
The default button will be activated if the user just presses return. Usually you should make the least-destructive button the default. Otherwise, the most commonly-used button.
Gnome.Dialog
set_parent(GTK1.Window
parent
)
Dialogs have "parents," usually the main application window which spawned them. This function will let the window manager know about the parent-child relationship. Usually this means the dialog must stay on top of the parent, and will be minimized when the parent is. Gnome also allows users to request dialog placement above the parent window (vs. at the mouse position, or at a default window manger location).
Gnome.Dialog
set_sensitive(int
button
, int
sensitive
)
Calls set_sensitive() on the specified button number.
GnomeDock is a container widget designed to let users move around widgets such as toolbars, menubars and so on.
Every GnomeDock contains a widget called the "client area". On the four sides of the client area, there are four "dock areas", which can contain an arbitrary number of dockable widgets. All the dockable widgets should be GnomeDockItem widgets; the GnomeDockItem widget can in turn contain any kind of widget, and implements the dragging functionality: every GnomeDockItem has a handle that users can use to move them within the dock, or even move them outside it, so that they become "floating items".
Every "dock area" is implemented by means of zero or more "dock bands": a dock band is a horizontal or vertical stripe containing one or more dock items, and is implemented by the GnomeDockBand widget. Items are ordered from top to bottom in vertical bands, and from left to right in horizontal bands. Every dock item in a band is given an offset value that defines the distance, in pixels, from the previous item in the same band; if the item is first in the band, the offset defines the distance from the start of the band.
As a consequence, the position of an item in the dock can be specified by means of the following values: a "placement" specifying what area is being used (top, bottom, left, right), a "band number" specifying the number of the band within the specified area, a "position" within the band and a "offset" from the previous item in the same band.
Signals: layout_changed
Gnome.Dock
add_floating_item(Gnome.DockItem
item
, int
x
, int
y
, int
orientation
)
Add item to dock and make it floating at the specified (x, y) coordinates (relative to the root window of the screen).
Gnome.Dock
add_item(Gnome.DockItem
item
, int
placement
, int
band_num
, int
position
, int
offset
, int
new_band
)
Add item to dock. placement can be either Gnome.DOCK_TOP, Gnome.DOCK_RIGHT, Gnome.DOCK_BOTTOM or Gnome.DOCK_LEFT, and specifies what area of the dock should contain the item. If in_new_band is TRUE, a new dock band is created at the position specified by band_num; otherwise, the item is added to the band_num'th band.
Gnome.Dock
allow_floating_items(int
allow
)
Gnome.Dock Gnome.Dock()
GTK1.Widget
get_client_area()
Gnome.DockItem
get_item_by_name(string
name
)
inherit GTK1.Container : Container
Gnome.Dock
set_client_area(GTK1.Widget
area
)
Specify a widget for the dock's client area.
Gnome.DockBand is a widget implementing a "dock band", i.e. a horizontal or vertical stripe containing dockable widgets.
The application programmer does not normally need to use Gnome.DockBand directly; they are mostly used by the W(GnomeDock) widget to implement its functionality. For an explanation of the way dock bands are used within a dock, check out the documentation for the W(GnomeDock) widget.
int
append(Gnome.DockItem
child
, int
offset
)
Add child to the band with the specified offset as the last element.
Gnome.DockBand Gnome.DockBand()
Create a new Gnome.DockBand widget.
int
get_child_offset(GTK1.Widget
child
)
Retrieve the offset of the child
Gnome.DockItem
get_item_by_name(string
name
)
Retrieve a named item from the band.
int
get_num_children()
Retrieve the number of children
int
get_orientation()
Retrieve the orientation
inherit GTK1.Container : Container
int
insert(Gnome.DockItem
child
, int
offset
, int
position
)
Add child to the band at the specified position, with the specified offset from the previous item (or from the beginning of the band, if this is the first item).
Gnome.DockBand
layout_add(Gnome.DockLayout
layout
, int
placement
, int
band_num
)
int
prepend(Gnome.DockItem
child
, int
offset
)
Add child to the band with the specified offset as the first element.
Gnome.DockBand
set_child_offset(GTK1.Widget
child
, int
offset
)
Set the offset for the specified child of the band.
Gnome.DockBand
set_orientation(int
orientation
)
Set the orientation.
Gnome.DockItem Gnome.DockItem(
string
name
, int
behavior
)
Create a new GnomeDockItem named name, with the specified behavior. Gnome.DockItemBehExclusive specifies that the dock item is always the only one in its band. Gnome.DockItemBehNeverFloating specifies that users cannot detach the dock item from the dock. Gnome.DockItemBehNeverVertical specifies that the dock item must be kept horizontal, and users cannot move it to a vertical band. Gnome.DockItemBehNeverHorizontal specifies that the dock item must be kept horizontal, and users cannot move it to a vertical band. Gnome.DockItemBehLocked specifies that users cannot drag the item around.
int
get_behavior()
GTK1.Widget
get_child()
Retrieve the child of the item.
string
get_name()
Retrieve the name
int
get_orientation()
int
get_shadow_type()
One of SHADOW_ETCHED_IN
, SHADOW_ETCHED_OUT
, SHADOW_IN
, SHADOW_NONE
and SHADOW_OUT
inherit GTK1.Bin : Bin
Gnome.DockItem
set_orientation(int
orientation
)
Gnome.DockItem
set_shadow_type(int
shadow_type
)
One of SHADOW_ETCHED_IN
, SHADOW_ETCHED_OUT
, SHADOW_IN
, SHADOW_NONE
and SHADOW_OUT
The Gnome.DockLayout widget is meant to make it simple for programmers to handle the layout of a GnomeDock widget.
Gnome.DockLayout can contain an arbitrary number of W(Gnome.DockItem) widgets, each of them with its own placement information. It is possible to "extract" a layout from an existing W(GnomeDock) widget, as well as adding the items present in a Gnome.DockLayout to it. Moreover, Gnome.DockLayout is able to create a layout configuration string that can be later used to re-construct the layout on a brand new Gnome.DockLayout widget.
As a consequence, Gnome.DockLayout is very useful to save and retrieve W(GnomeDock) configurations into files. For example, W(GnomeApp) uses Gnome.DockLayout to create a default layout configuration, override it with the user-specific configuration file, and finally apply it to it's W(GnomeDock).
int
add_floating_item(Gnome.DockItem
item
, int
x
, int
y
, int
orientation
)
Add item to the layout as a floating item with the specified (x, y) position and orientation.
int
add_item(Gnome.DockItem
item
, int
placement
, int
band_num
, int
band_position
, int
offset
)
Add item to the layout with the specified parameters.
int
add_to_dock(Gnome.Dock
dock
)
Add all the items in this layout to the specified dock
Gnome.DockLayout Gnome.DockLayout()
Create a new Gnome.DockLayout widget.
string
create_string()
Generate a string describing the layout
Gnome.DockLayoutItem
get_item(Gnome.DockItem
item
)
Retrieve a dock layout item.
Gnome.DockLayoutItem
get_item_by_name(string
name
)
Retrieve the dock layout item named name
inherit GTK1.Object : Object
Gnome.DockLayout
parse_string(string
str
)
Parse the layout string str, and move around the items in layout accordingly.
int
remove_item(Gnome.DockItem
item
)
Remove the specified item from the layout.
int
remove_item_by_name(string
name
)
Remove the specified item from the layout.
Information about an item in a gnome_dock_layout
Gnome.DockItem
get_item()
The W(gnome_dock_item) this information applies to.
int
get_placement()
One of
mapping
position()
Get the position of the item
The GNOME druid is a system for assisting the user with installing a service. It is roughly equivalent in functionality to the "Wizards" available in Windows.
There are two major parts of the druid, the Gnome.Druid widget, and the set of W(Gnome.DruidPage) widgets. The Gnome.Druid widget is the main widget that interacts with the user. It has a Next, a Prev, and a Cancel button, and acts as a container for the pages. It is not a top-level window, so it needs to be put in a W(GTK1.Window) in almost all cases. The W(Gnome.DruidPage) is a virtual widget, from which all of the actual content of the page inherits from. There are currently three of these available within gnome-libs.
GNOME druids are fairly simple to program with. You start by creating a GnomeDruid into which you put all of your pages. This widget will handle the presentation of the W(GnomeDruidPage) widgets.
You then create all appropriate W(GnomeDruidPage) widgets. There are three implementations of these, although there is no reason why more couldn't be written. They are the W(GnomeDruidPageStart), the W(GnomeDruidPageStandard), and the W(GnomeDruidPageFinish). The W(GnomeDruidPageStandard) acts as a W(Container), and is probably the most commonly used druid page. The other ones, as their names might suggest, are used at the endpoints of the druid. More information on the specific properties of these widgets can be found on their respective pages.
You will need to add the pages to the druid in order for them to appear. The druid itself keeps an internal list of all pages, and using the prepend_page(), append_page(), and insert_page() functions will place them into it.
Signals: cancel This signal is emitted when the "cancel" button has been pressed. Note that the current druid page has the option to trap the signal and use it, if need be, preventing this signal from being emitted.
Gnome.Druid
append_page(Gnome.DruidPage
page
)
This will append a GnomeDruidPage into the internal list of pages that the druid has.
Gnome.Druid Gnome.Druid()
Create a new druid
inherit GTK1.Container : Container
Gnome.Druid
insert_page(Gnome.DruidPage
back_page
, Gnome.DruidPage
page
)
This will insert page after back_page into the list of internal pages that the druid has. If back_page is not present in the list or is 0, page will be prepended to the list.
Gnome.Druid
prepend_page(Gnome.DruidPage
page
)
This will prepend a GnomeDruidPage into the internal list of pages that the druid has.
Gnome.Druid
set_buttons_sensitive(int
beck_sensitive
, int
next_sensitive
, int
cancel_sensitive
)
Sets the sensitivity of the druid's control-buttons. If the variables are TRUE, then they will be clickable. This function is used primarily by the actual W(GnomeDruidPage) widgets.
Gnome.Druid
set_page(Gnome.DruidPage
page
)
This will make page the currently showing page in the druid. page must already be in the druid.
Gnome.Druid
set_show_finish(int
show_finish
)
Sets the text on the last button on the druid. If show_finish is TRUE, then the text becomes "Finish". If show_finish is FALSE, then the text becomes "Cancel".
This widget is a virtual widget to define the interface to a druid page. It's descendants are placed in a W(Gnome.Druid) widget.
Signals: back
cancel
finish
next
prepare
inherit GTK1.Bin : Bin
This is a W(GnomeDruidPage).
Gnome.DruidPageFinish Gnome.DruidPageFinish()
Creates a new Gnome.DruidPageStandard widget.
inherit Gnome.DruidPage : DruidPage
Gnome.DruidPageFinish
set_bg_color(GDK1.Color
color
)
This will set the background color to be the specified color.
Gnome.DruidPageFinish
set_logo_bg_color(GDK1.Color
color
)
This will set the background color of the logo
Gnome.DruidPageFinish
set_text(string
text
)
Set the text
Gnome.DruidPageFinish
set_text_color(GDK1.Color
color
)
Set the text color
Gnome.DruidPageFinish
set_textbox_color(GDK1.Color
color
)
This will set the textbox color to be the specified color.
Gnome.DruidPageFinish
set_title(string
title
)
Set the title
Gnome.DruidPageFinish
set_title_color(GDK1.Color
color
)
Set the title color
This is a W(GnomeDruidPage).
Gnome.DruidPageStandard Gnome.DruidPageStandard()
Creates a new Gnome.DruidPageStandard widget.
inherit Gnome.DruidPage : DruidPage
Gnome.DruidPageStandard
set_bg_color(GDK1.Color
color
)
This will set the background color to be the specified color.
Gnome.DruidPageStandard
set_logo_bg_color(GDK1.Color
color
)
This will set the background color of the logo
Gnome.DruidPageStandard
set_title(string
title
)
Set the title
Gnome.DruidPageStandard
set_title_color(GDK1.Color
color
)
Set the title color
This is a W(GnomeDruidPage). It is meant to be used to introduce the user to what is being installed in a consistent manner.
Gnome.DruidPageStart Gnome.DruidPageStart()
Creates a new Gnome.DruidPageStart widget.
inherit Gnome.DruidPage : DruidPage
Gnome.DruidPageStart
set_bg_color(GDK1.Color
color
)
This will set the background color to be the specified color.
Gnome.DruidPageStart
set_logo_bg_color(GDK1.Color
color
)
This will set the background color of the logo
Gnome.DruidPageStart
set_text(string
text
)
Set the text
Gnome.DruidPageStart
set_text_color(GDK1.Color
color
)
Set the text color
Gnome.DruidPageStart
set_textbox_color(GDK1.Color
color
)
This will set the textbox color to be the specified color.
Gnome.DruidPageStart
set_title(string
title
)
Set the title
Gnome.DruidPageStart
set_title_color(GDK1.Color
color
)
Set the title color
This widget is a wrapper around the GtkEntry widget, but it provides a history mechanism for all the input entered into the widget. The way this works is that a special identifier is provided when creating the GnomeEntry widget, and this identifier is used to load and save the history of the text.
Gnome.Entry( "history" )
Gnome.Entry
append_history(int
save
, string
text
)
Adds a history item of the given text to the tail of the history list inside gentry. If save is TRUE, the history item will be saved in the config file (assuming that gentry's history id is not 0).
Gnome.Entry Gnome.Entry(
string
|void
history_id
)
Creates a new GnomeEntry widget. If history_id is not 0, then the history list will be saved and restored between uses under the given id.
GTK1.Entry
gtk_entry()
Obtain pointer to Gnome.Entry's internal GTK1.Entry text entry
inherit GTK1.Combo : Combo
Gnome.Entry
load_history()
Loads a stored history list from the GNOME config file, if one is available. If the history id of gentry is 0, nothing occurs.
Gnome.Entry
prepend_history(int
save
, string
text
)
Adds a history item of the given text to the head of the history list inside gentry. If save is TRUE, the history item will be saved in the config file (assuming that gentry's history id is not 0).
Gnome.Entry
save_history()
Force the history items of the widget to be stored in a configuration file. If the history id of gentry is 0, nothing occurs.
Gnome.Entry
set_history_id(string
|void
history_id
)
Set or clear the history id of the GnomeEntry widget. If history_id is 0, the widget's history id is cleared. Otherwise, the given id replaces the previous widget history id.
This widget provides an entry box with history (a W(GnomeEntry))
and a button which can pop up a file selector dialog box
W(GtkFileSelection). It also accepts DND drops from the filemanager
and other sources.
Gnome.FileEntry("","")
Signals: browse_clicked Signal emitted when the "browse" button is clicked. This is so that you can add stuff to the file selector or to override this method.
Gnome.FileEntry Gnome.FileEntry(
string
history_id
, string
browse_dialog_title
)
Creates a new Gnome.FileEntry widget.
string
get_full_path(int
file_must_exist
)
Gets the full absolute path of the file from the entry. If file_must_exist is false, nothing is tested and the path is returned. If file_must_exist is true, then the path is only returned if the path actually exists. In case the entry is a directory entry (see set_directory), then if the path exists and is a directory then it's returned; if not, it is assumed it was a file so we try to strip it, and try again.
Gnome.Entry
gnome_entry()
Get the W(GnomeEntry) component of the widget for lower-level manipulation.
GTK1.Entry
gtk_entry()
Get the W(Entry) component of the widget for lower-level manipulation.
inherit GTK1.Hbox : Hbox
Gnome.FileEntry
set_default_path(string
path
)
Set the default path of browse dialog to path. The default path is only used if the entry is empty or if the current path of the entry is not an absolute path, in which case the default path is prepended to it before the dialog is started.
Gnome.FileEntry
set_directory(int
directory_entry
)
Sets whether this is a directory only entry. If directory_entry is true, then get_full_path will check for the file being a directory, and the browse dialog will have the file list disabled.
Gnome.FileEntry
set_modal(int
is_modal
)
Sets the modality of the browse dialog.
Gnome.FileEntry
set_title(string
browse_dialog_title
)
Set the title of the browse dialog to browse_dialog_title. The new title will go into effect the next time the browse button is pressed.
GnomeFontPicker - Button that displays current font; click to select new font.
Gnome.FontPicker();
Gnome.FontPicker()->set_mode( Gnome.FontPickerModeFontInfo );
Signals: font_set
Gnome.FontPicker Gnome.FontPicker()
Create a new font pick button
Gnome.FontPicker
fi_set_show_size(int
show_size
)
If show_size is TRUE, font size will be displayed along with font chosen by user. This only applies if current button mode is Gnome.FontPickerModeFontInfo.
Gnome.FontPicker
fi_set_use_font_in_label(int
use_font_in_label
, int
size
)
If use_font_in_label is TRUE, font name will be written using font chosen by user and using size passed to this function. This only applies if current button mode is Gnome.FontPickerModeFontInfo.
GDK1.Font
get_font()
Retrieves the font from the font selection dialog.
string
get_font_name()
Retrieve name of font from font selection dialog.
int
get_mode()
Returns current font picker button mode (or what to show).
string
get_preview_text()
Retrieve preview text from font selection dialog if available.
inherit GTK1.Button : Button
int
set_font_name(string
fontname
)
Set or update the currently displayed font in the font picker dialog
Gnome.FontPicker
set_mode(int
mode
)
Set value of subsequent font picker button mode (or what to show).
Mode is one of GNOME_FONT_PICKER_MODE_FONT_INFO
, GNOME_FONT_PICKER_MODE_PIXMAP
, GNOME_FONT_PICKER_MODE_UNKNOWN
and GNOME_FONT_PICKER_MODE_USER_WIDGET
Gnome.FontPicker
set_preview_text(string
text
)
Set preview text in font picker, and in font selection dialog if one is being displayed.
Gnome.FontPicker
set_title(string
title
)
Sets the title for the font selection dialog.
Gnome.FontPicker
uw_set_widget(GTK1.Widget
widget
)
Set the user-supplied widget as the inside of the font picker. This only applies with Gnome.FontPickerModeUserWidget.
This widget is a GtkButton button that contains a URL. When clicked it invokes the configured browser for the URL you provided.
Gnome.Href( "http://www.gnome.org", "GNOME Web Site" )
Gnome.Href( "http://www.gnome.org" )
Gnome.Href Gnome.Href(
string
url
, string
|void
label
)
Created a GNOME href object, a label widget with a clickable action and an associated URL. If label is set to 0, url is used as the label.
string
get_label()
Returns the contents of the label widget used to display the link text.
string
get_url()
Return the url
inherit GTK1.Button : Button
Gnome.Href
set_label(string
label
)
Sets the internal label widget text (used to display a URL's link text) to the given value.
Gnome.Href
set_url(string
url
)
Sets the internal URL
This widget provides the facilities to select an icon. An icon is displayed inside a button, when the button is pressed, an Icon selector (a dialog with a W(GnomeIconSelection) widget) pops up to let the user choose an icon. It also allows one to Drag and Drop the images to and from the preview button.
Gnome.IconEntry Gnome.IconEntry(
string
history_id
, string
title
)
Creates a new icon entry widget
string
get_filename()
Gets the file name of the image if it was possible to load it into the preview. That is, it will only return a filename if the image exists and it was possible to load it as an image.
Gnome.Entry
gnome_entry()
Get the W(GnomeEntry) widget that's part of the entry
Gnome.FileEntry
gnome_file_entry()
Get the W(GnomeFileEntry) widget that's part of the entry
GTK1.Entry
gtk_entry()
Get the W(Entry) widget that's part of the entry
inherit GTK1.Vbox : Vbox
Gnome.IconEntry
set_pixmap_subdir(string
subdir
)
Sets the subdirectory below gnome's default pixmap directory to use as the default path for the file entry.
The GNOME icon list widget can hold a number of icons with captions. The icons on the list can be selected (various selection methods are supported). The programmer can enable caption-editing for the icons. This parameters is configured when you create the icon list widget. You can control the type of selection mode you desire by using the set_selection_mode() function.
Signals: select_icon
text_changed
unselect_icon
Gnome.IconList
append(string
icon_filename
, string
text
)
Appends an icon to the specified icon list. The icon's image is loaded from the specified file, and it is inserted at the pos index.
Gnome.IconList
clear()
Clears the contents for the icon list by removing all the icons. If destroy handlers were specified for any of the icons, they will be called with the appropriate data.
Gnome.IconList Gnome.IconList(
int
icon_widt
, int
flags
)
Creates a new icon list widget. The icon columns are allocated a width of icon_width pixels. Icon captions will be word-wrapped to this width as well.
If flags has the Gnome.IconListIsEditable flag set, then the user will be able to edit the text in the icon captions, and the "text_changed" signal will be emitted when an icon's text is changed.
int
find_icon_from_data(object
data
)
Find a icon in the list that has the given user data. If no icon is found, -1 is returned.
Gnome.IconList
freeze()
Freezes an icon list so that any changes made to it will not be reflected on the screen until it is thawed with thaw(). It is recommended to freeze the icon list before inserting or deleting many icons, for example, so that the layout process will only be executed once, when the icon list is finally thawed.
You can call this function multiple times, but it must be balanced with the same number of calls to thaw() before the changes will take effect.
int
get_icon_at(int
x
, int
y
)
Returns the index of the icon that is under the specified coordinates, which are relative to the icon list's window. If there is no icon in that position, -1 is returned.
object
get_icon_data(int
icon
)
Return the data associated with a icon, or 0.
array
get_selected_icons()
Return an array with the currently selected icons
int
icon_is_visible(int
pos
)
returns 1 if the icon whose index is pos is visible.
inherit GTK1.Widget : Widget
Gnome.IconList
insert(int
pos
, string
icon_filename
, string
text
)
Inserts an icon in the specified icon list. The icon's image is loaded from the specified file, and it is inserted at the pos index.
Gnome.IconList
moveto(int
pos
, float
yalign
)
Makes the icon whose index is pos be visible on the screen. The icon list gets scrolled so that the icon is visible. An alignment of 0.0 represents the top of the visible part of the icon list, and 1.0 represents the bottom. An icon can be centered on the icon list using 0.5 as the yalign.
Gnome.IconList
remove(int
pos
)
Removes the icon at index position pos. If a destroy handler was specified for that icon, it will be called with the appropriate data.
Gnome.IconList
select_icon(int
idx
)
Selects the specified icon.
Gnome.IconList
set_col_spacing(int
pixels
)
Sets the spacing to be used between columns of icons.
Gnome.IconList
set_hadjustment(GTK1.Adjustment
hadj
)
Sets the adjustment to be used for horizontal scrolling. This is normally not required, as the icon list can be simply inserted in a W(ScrolledWindow) and scrolling will be handled automatically.
Gnome.IconList
set_icon_border(int
pixels
)
Set the width of the border to be displayed around an icon's image. This is currently not implemented.
Gnome.IconList
set_icon_data(int
icon
, object
data
)
Set the user data associated with the specified icon. This data can be used to find icons, and when an icon is selected it can be easily retrieved using get_icon_data.
You can only use objects as icon data right now
Gnome.IconList
set_icon_width(int
w
)
Sets the amount of horizontal space allocated to the icons, i.e. the column width of the icon list
Gnome.IconList
set_row_spacing(int
pixels
)
Sets the spacing to be used between rows of icons.
Gnome.IconList
set_selection_mode(int
mode
)
One of SELECTION_BROWSE
, SELECTION_EXTENDED
, SELECTION_MULTIPLE
and SELECTION_SINGLE
.
Gnome.IconList
set_separators(string
sep
)
Set the characters that can be used as word separators when doing word-wrapping of the text captions.
Gnome.IconList
set_text_spacing(int
pixels
)
Sets the spacing to be used between the icon and its caption
Gnome.IconList
set_vadjustment(GTK1.Adjustment
hadj
)
Sets the adjustment to be used for vertical scrolling. This is normally not required, as the icon list can be simply inserted in a W(ScrolledWindow) and scrolling will be handled automatically.
Gnome.IconList
thaw()
Unfreeze the icon list
Gnome.IconList
unselect_all()
Unselect all icons.
Gnome.IconList
unselect_icon(int
idx
)
Unselects the specified icon.
Gnome.IconSelection
add_defaults()
Adds the default pixmap directory into the selection widget.
Gnome.IconSelection
add_directory(string
dir
)
Adds the icons from the directory dir to the selection widget.
Gnome.IconSelection
clear(int
|void
not_shown
)
Clear the currently shown icons, the ones that weren't shown yet are not cleared unless the not_shown parameter is given, in which case even those are cleared.
Gnome.IconSelection Gnome.IconSelection()
reates a new icon selection widget, it uses a W(GnomeIconList) for the listing of icons
string
get_icon(int
full_path
)
Gets the currently selected icon name, if full_path is true, it returns the full path to the icon, if none is selected it returns 0.
inherit GTK1.Vbox : Vbox
Gnome.IconSelection
select_icon(string
filename
)
Selects the icon filename. This icon must have already been added and shown
Gnome.IconSelection
show_icons()
Shows the icons inside the widget that were added with add_defaults and add_directory. Before this function isf called the icons aren't actually added to the listing and can't be picked by the user.
This widget implements a graphical "more" command. It allows the user to view a text file. There are various possible ways to specify the contents to display: loading the data from a file (by providing a filename) or by loading it from an open file data stream or from the output of a Unix command.
Gnome.Less()->show_string("Example string\nshown in this\nwidget")
Gnome.Less()->show_file("/usr/dict/words" );
Gnome.Less()->show_command( "psrinfo -v" )
Gnome.Less
clear()
Clears all the text
Gnome.Less Gnome.Less()
Creates a new GnomeLess widget.
inherit GTK1.Vbox : Vbox
Gnome.Less
reshow()
Re-displays all of the text in the GnomeLess widget gl. If the font has changed since the last show/reshow of text, it will update the current text to the new font.
Gnome.Less
set_fixed_font(int
fixed
)
Specifies whether or not new text should be displayed using a fixed font. Pass TRUE in fixed to use a fixed font, or FALSE to revert to the default GtkText font.
Note: This will not affect text already being displayed. If you use this function after adding text to the widget, you must show it again by using gnome_less_reshow or one of the gnome_less_show commands.
Gnome.Less
set_font(GDK1.Font
font
)
Sets the font of the text to be displayed in the GnomeLess widget gl to font. Note: This will not affect text already being displayed. If you use this function after adding text to the widget, you must show it again by using reshow or one of the show commands.
Gnome.Less
show_command(string
command_line
)
Runs the shell command specified in command_line, and places the output of that command in the GnomeLess widget specified by gl. Replaces any text already being displayed in the widget.
Gnome.Less
show_file(string
file
)
Displays a file in a GnomeLess widget. Replaces any text already being displayed in the widget.
Gnome.Less
show_filestream(Stdio.File
stream
)
Gnome.Less
show_string(string
data
)
Displays a string in the GnomeLess widget gl. Replaces any text already being displayed.
int
write_file(string
path
)
Writes the text displayed in the GnomeLess widget gl to the file specified by path.
int
write_filestream(Stdio.File
fd
)
The GnomeMessageBox widget creates dialog boxes (of type GnomeDialog) that contain a severity level (indicated by an icon and a title), a message to be displayed and a list of buttons that will be in the dialog.
The programmer will use strings desired for each button. If the strings are any of the GNOME_STOCK macros, then instead of creating a button with the text, the button will be a GNOME stock button with a stock icon.
The list of known types for message boxes are:
GNOME_MESSAGE_BOX_ERROR
, GNOME_MESSAGE_BOX_GENERIC
, GNOME_MESSAGE_BOX_INFO
, GNOME_MESSAGE_BOX_QUESTION
and GNOME_MESSAGE_BOX_WARNING
.
Gnome.MessageBox( "This is a nice message", Gnome.MessageBoxInfo, Gnome.StockButtonOk, Gnome.StockButtonCancel );
Gnome.MessageBox( "This is another not so nice message", Gnome.MessageBoxError, Gnome.StockButtonClose, Gnome.StockButtonCancel );
Gnome.MessageBox Gnome.MessageBox(
string
message
, string
messagebox_type
, string
... buttons
)
Creates a dialog box of type message_box_type with message. A number of buttons are inserted on it. You can use the GNOME stock identifiers to create gnome stock buttons.
inherit Gnome.Dialog : Dialog
Provides an entry line for numbers. This routine does not attempt
to do any validation on the valid number ranges, but provides a
button that will let the user bring up a calculator to fill in the
value of the entry widget.
Gnome.NumberEntry("", "Select a number...");
Gnome.NumberEntry Gnome.NumberEntry(
string
history_id
, string
calc_dialog_title
)
Creates a new number entry widget, with a history id and title for the calculator dialog.
float
get_number()
Get the current number from the entry
Gnome.Entry
gnome_entry()
Get the W(GnomeEntry) component of the Gnome.NumberEntry for lower-level manipulation.
GTK1.Entry
gtk_entry()
Get the W(Entry) component of the Gnome.NumberEntry for Gtk+-level manipulation.
inherit GTK1.Hbox : Hbox
Gnome.NumberEntry
set_title(string
title
)
Set the title of the calculator dialog to calc_dialog_title. Takes effect the next time the calculator button is pressed.
Gnome.PaperSelector()
Gnome.PaperSelector Gnome.PaperSelector()
float
get_bottom_margin()
float
get_height()
float
get_left_margin()
string
get_name()
float
get_right_margin()
float
get_top_margin()
float
get_width()
inherit GTK1.Vbox : Vbox
Entry for large images with a preview. Unlike GnomeIconEntry, it
does not scale the images to a specific size and shows them
1:1. This is perfect for selection of backgrounds and such. It also
allows DND to be performed on the preview box. It also provides all
the GnomeEntry functionality as well.
Gnome.PixmapEntry("","browse...",1);
Gnome.PixmapEntry Gnome.PixmapEntry(
string
history_id
, string
browse_dialog_title
, int
do_preview
)
Creates a new pixmap entry widget, if do_preview is false, the preview is hidden but the files are still loaded so that it's easy to show it. For a pixmap entry without preview, use the W(GnomeFileEntry) widget.
string
get_filename()
Gets the filename of the image if the preview successfully loaded.
Gnome.Entry
gnome_entry()
Get the W(GnomeEntry) component of the W(GnomePixmapEntry) widget for lower-level manipulation.
Gnome.FileEntry
gnome_file_entry()
Get the W(GnomeFileEntry) component of the W(GnomePixmapEntry) widget for lower-level manipulation.
inherit GTK1.Vbox : Vbox
Gnome.PixmapEntry
set_pixmap_subdir(string
dir
)
Sets the default path for the file entry. The new subdirectory should be specified relative to the default GNOME pixmap directory.
Gnome.PixmapEntry
set_preview(int
do_preview
)
Sets whether or not previews of the currently selected pixmap should be shown in the file selector.
Gnome.PixmapEntry
set_preview_size(int
min_w
, int
min_h
)
Sets the minimum size of the preview frame in pixels.
The Gnome.PropertyBox widget simplifies coding a consistent dialog box for configuring properties of any kind.
The Gnome.PropertyBox is a toplevel widget (it will create its own window), inside it contains a GtkNotebook which is used to hold the various property pages.
The box will include ok, cancel, apply and help buttons (the actual buttons depends on the settings the user has, for example, apply can be hidden). The ok and apply buttons will start up in non-sensitive state, the programmer needs to configure the widgets inserted into the property box to inform the widget of any state changes to enable the ok and apply buttons. This is done by calling the changed() function.
To use this widget, you create the widget and then you call append_page() for each property page you want in the property box.
The widget emits two signals: "apply" and "help". To make a functional dialog box you will want to connect to at least the "apply" signal. Your function will be invoked once for each page and one more time at the end, passing a special value of -1 for the page number.
Signals: apply This signal is invoked with the page number that is being applied. The signal is emited with the special page number -1 when it has finished emiting the signals for all of the property pages.
help This signal is invoked when the user clicks on the help button in the property box. An argument is passed that identifies the currently active page number.
int
append_page(GTK1.Widget
child
, GTK1.Widget
tab_label
)
Appends a new page to the Gnome.PropertyBox. widget is the widget that is being inserted, and tab_label will be used as the label for this configuration page.
Gnome.PropertyBox
changed()
When a setting has changed, the code needs to invoke this routine to make the Ok/Apply buttons sensitive.
Gnome.PropertyBox Gnome.PropertyBox()
Creates a new Gnome.PropertyBox widget.
inherit Gnome.Dialog : Dialog
Gnome.PropertyBox
set_state(int
state
)
This is a high-scores dialog box. The GNOME libraries also handle loading/saving systemwide high scores in a secure way.
Gnome.Scores( 17, ({ "per" })*17, map((array(float))indices(allocate(17)),`*,42), map(indices(allocate(17)), `*, 10 ), 1 )
Gnome.Scores Gnome.Scores(
int
n_scores
, array
names
, array
scores
, array
times
, int
clear
)
inherit Gnome.Dialog : Dialog
Gnome.Scores
set_color(int
pos
, GDK1.Color
color
)
Gnome.Scores
set_current_player(int
index
)
Gnome.Scores
set_def_color(GDK1.Color
color
)
Gnome.Scores
set_logo_label_title(string
txt
)
Gnome.Scores
set_logo_pixmap(string
logofile
)
Gnome.Scores
set_logo_widget(GTK1.Widget
widget
)
Some apps want to embed a very small icon or widget in the panel to display the status of the app. This can be done without the operational overhead of an applet. The status docklet will embed a 22 by 22 window inside the panel. This is not a separate applet and thus is minimally intrusive to the user and is meant for very temporary status displays for which a full applet would not be appropriate.
The way StatusDocklet works is a little different from how the AppletWidget works. Firstly, StatusDocklet object is not a widget, it is just an abstract GTK+ object. You create a new StatusDocklet object and then bind the "build_plug" signal which is emitted when the panel was contacted and a widget must be built. After binding the "build_plug" signal, you call run() to actually start trying to contacting the panel. StatusDocklet is safe to use without a panel. By default it will try to locate a panel for 15 minutes and after that it will give up. It will also handle panel restarts by default. If it does, your widget will be destroyed and "build_plug" will be emitted again when the new panel starts. Even though the panel will never restart by itself, the user might not run session management and thus might restart panel by hand, or due to a bug, the panel might crash and restart itself.
Docklets are not available in GNOME 1.0.
Signals: build_plug This signal is emitted when you actually need to build the widget that you want to place inside the plug in the status docklet. It should be 22 by 22, and if it is larger it will be cropped.
Gnome.StatusDocklet Gnome.StatusDocklet()
Creates a new status docklet object with the default parameters. By default the docklet object will try to contact a panel 20 times. It will try to find a panel every 15 seconds. You need to bind the build_plug signal in which you build your own widget and add it to the provided container. By default the docklet object will handle a panel restart, in which case your widget will be destroyed and when the panel is contacted again the build_plug signal will be emitted again. You also must call the status_docklet_run function after you bind the build_plug signal.
GTK1.Plug
get_plug()
the current W(plug) holding the docklet
inherit GTK1.Object : Object
Gnome.StatusDocklet
run()
Search for the panel and add the plug if it finds it. This function is also called internally from the timeout. If called externally more times, a panel lookup will be forced and one try will be wasted. You need to call this function at least once after binding the build_plug signal to tell the status docklet to start looking for the panel. If the status docklet handles restarts you don't have to call this function ever again.
Image.Image
pie(mapping
(string
:mixed
) diagram_data
)
Image.Image
bars(mapping
(string
:mixed
) diagram_data
)
Image.Image
sumbars(mapping
(string
:mixed
) diagram_data
)
Image.Image
line(mapping
(string
:mixed
) diagram_data
)
Image.Image
norm(mapping
(string
:mixed
) diagram_data
)
Image.Image
graph(mapping
(string
:mixed
) diagram_data
)
Generate a graph of the specified type. See check_mapping
for an explanation of diagram_data.
mapping
(string
:mixed
) check_mapping(mapping
(string
:mixed
) diagram_data
, string
type
)
This function sets all unset elements in diagram_data to its
default value as well as performing some simple sanity checks.
This function is called from within pie
, bars
, sumbars
,
line
, norm
and graph
.
diagram_data
| Default: "linear" Will be set to "2D" for pie below Only "linear" works for now. |
| Default: 0 If present a Pie-chart will be toned. |
| Default: 10 How much 3D-depth a graph will have in pixels Default is 10. |
| Default: ({({1.0}), ({2.0}), ({4.0})}) Will be set to something else with graph An array of arrays. Each array describing a data-set. The graph-function however should be fed with an array of arrays with X,Y-pairs. Example: ({({1.0, 2.0, 3.0}),({1.2, 2.2, 3.8})}) draws stuff in yellow with the values (1.0, 2.0, 3.0), and (1.2, 2.2, 3.8) in blue. |
| Default: 0 Should have four elements ({xquantity, yquantity, xunit, yunit}). The strings will be written on the axes. |
| Default: 0 An array(string) with the text that will be written under the X-axis. This should be the same size as sizeof(data). |
| Default: 0 An array(string) with the text that will be written to the left of the Y-axis. |
| Default: 10 The size of the text. Default is 10. |
| Default: 1.0 Width of the lines that draws data in Graph and line. Default is 1.0 |
| Default: same as fontsize The size of the text for labels. |
| Default: same as fontsize The size of the text for the legend. |
| Default: 0 The texts that will be written the legend. |
| Default: 0 An array(float) that describes where the ynames should be placed. The numbers are like the data-numbers. Default is equally distributed. |
| Default: 0 An array(float) that describes where the ynames should be placed. The numbers are like the data-numbers. Default is equally distributed. |
| Default: 100 X-size of the graph in pixels. |
| Default: 100 Y-size of the graph in pixels. |
| Default: 0 An image that the graph will be drawn on. |
| Default: 0 The color of the text in the legend. Default is? |
| Default: 0 I have no idea. |
| Default: 0 The bakground-color. If the the background is a image this color is used for antialias the texts. |
| Default: 0 Some sort of image... |
| Default: ({0,0,0}) The color of the axis. |
| Default: 0 An array of colors for the datasets. |
| Default: 0 An array of color that do something... |
| Default: ({0,0,0}) Color of the text. Default is black. |
| Default: 0 Color of the labeltexts. |
| Default: "hor" Can be "hor" or "vert". Orientation of the graph. |
| Default: 0 Width of lines (the axis and their like). |
| Default: 0 Width of the outline-lines. Default is 0. |
| Default: 0 If the vertical grid should be present. |
| Default: 0 If the horizontal grid should be present. |
| Default: 0 Width of the grid. Default is linewidth/4. |
| Default: 0 How much a the Pie in a Pie-shart should be rotated in degrees. |
| Default: 0 Makes the first Pie-slice be centered. |
| Default: 0 Draws the graph black and white. |
| Default: 0 Writes the numbers in eng format. |
| Default: 0 Writes the numbers in engformat except for 0.1 < x < 1.0 |
| Default: 0 Where the X-axis should start. This will be overrided by datavalues. |
| Default: 0 Where the Y-axis should start. This will be overridden by datavalues. |
| Default: 0 A string with the name of the graph that will be written at top of the graph. |
| Default: 0 The color of the name. |
| Default: Image.Font() The font that will be used. |
| Default: ({0,0,0} The color of the grid. Default is black. |
protected
inherit .create_pie : create_pie
Graph sub-module for drawing bars.
inherit .create_graph : create_graph
Graph sub-module for drawing graphs.
create_graph
draws a graph but there are also some other functions
used by create_pie
and create_bars
.
inherit .polyline : polyline
Graph sub-module for drawing pie-charts.
inherit .create_bars : create_bars
Graph sub-module providing draw functions.
The Gz module contains functions to compress and uncompress strings using the same algorithm as the program gzip. Compressing can be done in streaming mode or all at once.
The Gz module consists of two classes; Gz.deflate and Gz.inflate. Gz.deflate is used to pack data and Gz.inflate is used to unpack data. (Think "inflatable boat")
Note that this module is only available if the gzip library was available when Pike was compiled.
Note that although these functions use the same algorithm as gzip, they do not use the exact same format, so you cannot directly unzip gzipped files with these routines. Support for this will be added in the future.
string(8bit)
compress(string(8bit)
|String.Buffer
|System.Memory
|Stdio.Buffer
data
, void
|bool
raw
, void
|int(0..9)
level
, void
|int
strategy
, void
|int(8..15)
window_size
)
Encodes and returns the input data
according to the deflate
format defined in RFC 1951.
data
The data to be encoded.
raw
If set, the data is encoded without the header and footer defined in RFC 1950. Example of uses is the ZIP container format.
level
Indicates the level of effort spent to make the data compress well. Zero means no packing, 2-3 is considered 'fast', 6 is default and higher is considered 'slow' but gives better packing.
strategy
The strategy to be used when compressing the data. One of the following.
| The default strategy as selected in the zlib library. |
| This strategy is intented for data created by a filter or predictor and will put more emphasis on huffman encoding and less on LZ string matching. This is between DEFAULT_STRATEGY and HUFFMAN_ONLY. |
| This strategy is even closer to the HUFFMAN_ONLY in that it only looks at the latest byte in the window, i.e. a window size of 1 byte is sufficient for decompression. This mode is not available in all zlib versions. |
| This strategy will turn of string matching completely, only doing huffman encoding. Window size doesn't matter in this mode and the data can be decompressed with a zero size window. |
| In this mode dynamic huffman codes are disabled, allowing for a simpler decoder for special applications. This mode is not available in all zlib versions. |
window_size
Defines the size of the LZ77 window from 256 bytes to 32768 bytes, expressed as 2^x.
deflate
, inflate
, uncompress
int
crc32(string(8bit)
data
, void
|int
start_value
)
This function calculates the standard ISO3309 Cyclic Redundancy Check.
inherit "___Gz" : "___Gz"
string(8bit)
uncompress(string(8bit)
|String.Buffer
|System.Memory
|Stdio.Buffer
data
, void
|bool
raw
)
Uncompresses the data
and returns it. The raw
parameter
tells the decoder that the indata lacks the data header and footer
defined in RFC 1950.
Allows the user to open a Gzip archive and read and write
it's contents in an uncompressed form, emulating the Stdio.File
interface.
An important limitation on this class is that it may only be used for reading or writing, not both at the same time. Please also note that if you want to reopen a file for reading after a write, you must close the file before calling open or strange effects might be the result.
Gz.File Gz.File(
void
|string
|int
|Stdio.Stream
file
, void
|string
mode
)
file
Filename or filedescriptor of the gzip file to open, or an already open Stream.
mode
mode for the file. Defaults to "rb".
open
Stdio.File
inherit _file : _file
int
open(string
|int
|Stdio.Stream
file
, void
|string
mode
)
file
Filename or filedescriptor of the gzip file to open, or an already open Stream.
mode
mode for the file. Defaults to "rb". May be one of the following:
read mode
write mode
append mode
For the wb and ab mode, additional parameters may be specified. Please se zlib manual for more info.
non-zero if successful.
int
|string
read(void
|int
length
)
Reads data from the file. If no argument is given, the whole file is read.
Low-level implementation of read/write support for GZip files
int
close()
closes the file
1 if successful
Gz._file Gz._file(
void
|string
|Stdio.Stream
gzFile
, void
|string
mode
)
Opens a gzip file for reading.
bool
eof()
1 if EOF has been reached.
int
open(string
|int
|Stdio.Stream
file
, void
|string
mode
)
Opens a file for I/O.
file
The filename or an open filedescriptor or Stream for the GZip file to use.
mode
Mode for the fileoperations. Defaults to read only.
If the object already has been opened, it will first be closed.
int
|string
read(int
len
)
Reads len (uncompressed) bytes from the file. If read is unsuccessful, 0 is returned.
int
seek(int
pos
, void
|int
type
)
Seeks within the file.
pos
Position relative to the searchtype.
type
SEEK_SET = set current position in file to pos SEEK_CUR = new position is current+pos SEEK_END is not supported.
New position or negative number if seek failed.
int
setparams(void
|int(-9..9)
level
, void
|int
strategy
, void
|int(8..15)
window_size
)
Sets the encoding level, strategy and window_size.
Gz.deflate
int
tell()
the current position within the file.
int
write(string
data
)
Writes the data to the file.
the number of bytes written to the file.
This class interfaces with the compression routines in the libz library.
This class is only available if libz was available and found when Pike was compiled.
Gz.inflate()
, Gz.compress()
, Gz.uncompress()
Gz.deflate
clone()
Clones the deflate object. Typically used to test compression of new content using the same exact state.
Gz.deflate Gz.deflate(
int(-9..9)
|void
level
, int
|void
strategy
, int(8..15)
|void
window_size
)
Gz.deflate Gz.deflate(
mapping
options
)
This function can also be used to re-initialize a Gz.deflate object so it can be re-used.
If a mapping is passed as the only argument, it will accept the
parameters described below as indices, and additionally it accepts
a string
as dictionary
.
level
Indicates the level of effort spent to make the data compress well. Zero means no packing, 2-3 is considered 'fast', 6 is default and higher is considered 'slow' but gives better packing.
If the argument is negative, no headers will be emitted. This is needed to produce ZIP-files, as an example. The negative value is then negated, and handled as a positive value.
strategy
The strategy to be used when compressing the data. One of the following.
| The default strategy as selected in the zlib library. |
| This strategy is intented for data created by a filter or predictor and will put more emphasis on huffman encoding and less on LZ string matching. This is between DEFAULT_STRATEGY and HUFFMAN_ONLY. |
| This strategy is even closer to the HUFFMAN_ONLY in that it only looks at the latest byte in the window, i.e. a window size of 1 byte is sufficient for decompression. This mode is not available in all zlib versions. |
| This strategy will turn of string matching completely, only doing huffman encoding. Window size doesn't matter in this mode and the data can be decompressed with a zero size window. |
| In this mode dynamic huffman codes are disabled, allowing for a simpler decoder for special applications. This mode is not available in all zlib versions. |
window_size
Defines the size of the LZ77 window from 256 bytes to 32768 bytes, expressed as 2^x.
string(8bit)
deflate(string(8bit)
|String.Buffer
|System.Memory
|Stdio.Buffer
data
, int
|void
flush
)
This function performs gzip style compression on a string data
and
returns the packed data. Streaming can be done by calling this
function several times and concatenating the returned data.
The optional argument flush
should be one of the following:
| Only data that doesn't fit in the internal buffers is returned. |
| All input is packed and returned. |
| All input is packed and returned. |
| All input is packed and an 'end of data' marker is appended. |
Gz.inflate->inflate()
This class interfaces with the uncompression routines in the libz library.
This program is only available if libz was available and found when Pike was compiled.
deflate
, compress
, uncompress
Gz.inflate Gz.inflate(
int
|void
window_size
)
Gz.inflate Gz.inflate(
mapping
options
)
If called with a mapping as only argument, create
accepts
the entries window_size
(described below) and
dictionary
, which is a string to be set as dictionary.
The window_size value is passed down to inflateInit2 in zlib.
If the argument is negative, no header checks are done, and no verification of the data will be done either. This is needed for uncompressing ZIP-files, as an example. The negative value is then negated, and handled as a positive value.
Positive arguments set the maximum dictionary size to an exponent of 2, such that 8 (the minimum) will cause the window size to be 256, and 15 (the maximum, and default value) will cause it to be 32Kb. Setting this to anything except 15 is rather pointless in Pike.
It can be used to limit the amount of memory that is used to uncompress files, but 32Kb is not all that much in the great scheme of things.
To decompress files compressed with level 9 compression, a 32Kb window size is needed. level 1 compression only requires a 256 byte window.
If the options
version is used you can specify your own dictionary in addition to the window size.
|
|
string(8bit)
end_of_stream()
This function returns 0 if the end of stream marker has not yet been encountered, or a string (possibly empty) containg any extra data received following the end of stream marker if the marker has been encountered. If the extra data is not needed, the result of this function can be treated as a logical value.
string(8bit)
inflate(string(8bit)
|String.Buffer
|System.Memory
|Stdio.Buffer
data
)
This function performs gzip style decompression. It can inflate a whole file at once or in blocks.
// whole file
write(Gz.inflate()->inflate(stdin->read(0x7fffffff)); // streaming (blocks) function inflate=Gz.inflate()->inflate; while(string s=stdin->read(8192)) write(inflate(s));
Gz.deflate->deflate()
, Gz.decompress
High performance webserver optimized for somewhat static content.
HTTPAccept is a less capable WWW-server than the
Protocols.HTTP.Server
server, but for some applications it can be
preferable. It is significantly more optimized, for most uses, and
can handle a very high number of requests per second on even
low end machines.
string
HTTPAccept.LogEntry.from
string
HTTPAccept.LogEntry.method
string
HTTPAccept.LogEntry.protocol
string
HTTPAccept.LogEntry.raw
int
HTTPAccept.LogEntry.received_bytes
int
HTTPAccept.LogEntry.reply
int
HTTPAccept.LogEntry.sent_bytes
int
HTTPAccept.LogEntry.time
string
HTTPAccept.LogEntry.url
mapping
(string
:int
) cache_status()
Returns information about the cache.
| The number of hits since start |
| The number of misses since start |
| The number of misses that were stale hits, and not used |
| The total current size |
| The number of entries in the cache |
| The maximum size of the cache |
| The number of bytes sent since the last call to cache_status |
| The number of bytes received since the last call to cache_status |
| The number of requests received since the last call to cache_status |
HTTPAccept.Loop HTTPAccept.Loop(
Stdio.Port
port
, RequestProgram
program
, function
(RequestProgram
:void
) request_handler
, int
cache_size
, bool
keep_log
, int
timeout
)
Create a new HTTPAccept
.
This will start a new thread that will listen for requests on the
port, parse them and pass on requests, instanced from the
program
class (which has to inherit RequestProgram
to the
request_handler
callback function.
cache_size
is the maximum size of the cache, in bytes.
keep_log
indicates if a log of all requests should be kept.
timeout
if non-zero indicates a maximum time the server will wait for requests.
array
(LogEntry
) log_as_array()
Return the current log as an array of LogEntry objects.
int
log_as_commonlog_to_file(Stdio.Stream
fd
)
Write the current log to the specified file in a somewhat common commonlog format.
Will return the number of bytes written.
int
log_size()
Returns the number of entries waiting to be logged.
bool
logp()
Returns true if logging is enabled
string
HTTPAccept.RequestProgram.client
The user agent
string
HTTPAccept.RequestProgram.data
Any payload that arrived with the request
mapping
(string
:array
(string
)) HTTPAccept.RequestProgram.headers
All received headers
string
HTTPAccept.RequestProgram.method
The method (GET, PUT etc)
Stdio.NonblockingStream
HTTPAccept.RequestProgram.my_fd
The filedescriptor for this request.
string
HTTPAccept.RequestProgram.not_query
The part of the URL before the first '?'.
void
output(string
data
)
Send data
directly to the remote side.
multiset
(string
) HTTPAccept.RequestProgram.pragma
Tokenized pragma headers
string
HTTPAccept.RequestProgram.prot
The protocol part of the request. As an example "HTTP/1.1"
string
HTTPAccept.RequestProgram.query
The part of the URL after the first '?'
string
HTTPAccept.RequestProgram.raw
The full request
string
HTTPAccept.RequestProgram.raw_url
The raw URL received, the part after the method and before the protocol.
string
HTTPAccept.RequestProgram.referer
The referer header
string
HTTPAccept.RequestProgram.remoteaddr
The remote address
void
reply(string
data
)
void
reply(string
headers
, Stdio.File
fd
, int
len
)
void
reply(int(0..0)
ignore
, Stdio.File
fd
, int
len
)
Send a reply to the remote side.
In the first case the data
will be sent.
In the second case the headers
will be sent, then len
bytes from fd
.
In the last case len
bytes from fd
will be sent.
void
reply_with_cache(string
data
, int(1..)
stay_time
)
Send data
as the reply, and keep it as a cache entry to
requests to this URL for stay_time
seconds.
string
HTTPAccept.RequestProgram.rest_query
The part of the URL after the first '?' that does not seem to be query variables.
string
HTTPAccept.RequestProgram.since
The get-if-not-modified, if set.
int
HTTPAccept.RequestProgram.time
The time_t when the request arrived to the server
mapping
(string
:string
) HTTPAccept.RequestProgram.variables
Parsed query variables
jobject
JArray(array
a
)
jobject
JBoolean(int
i
)
jobject
JFloat(float
f
)
jobject
JHashMap(mapping
m
)
jobject
JInteger(int
i
)
jobject
JString(string
s
)
inherit "___Java" : "___Java"
object
Java.pkg
Singleton 'package' object.
Usage: object cls = Java.pkg.java.lang.String;
or: object cls = Java.pkg["java/lang/String"];
cls is a jclass object; call it to create a jobject, which will have all the methods of the Java class.
Example: Java.pkg.FooClass()->getResult();
Interface to one Java class. Can be called to construct a jobject.
Obtained normally via Java.pkg.`[] and not created directly.
An instantiated Java object. Has methods for all the Java object's methods. Can be cast to string.
NOTE: Use indices(x) to get a list of the available methods.
Constructed from a jclass object.
PLIS, Permuted Lisp. A Lisp language somewhat similar to scheme.
Environment
default_environment()
Creates a new environment on which it runs init_functions, init_specials and the following boot code.
(begin
(defmacro (cddr x)
(list (quote cdr) (list (quote cdr) x)))
(defmacro (cadr x)
(list (quote car) (list (quote cdr) x)))
(defmacro (cdar x)
(list (quote cdr) (list (quote car) x)))
(defmacro (caar x)
(list (quote car) (list (quote car) x)))
(defmacro (when cond . body)
(list (quote if) cond
(cons (quote begin) body)))
(define (map fun list)
(if (null? list) (quote ())
(cons (fun (car list))
(map fun (cdr list)))))
(defmacro (let decl . body)
(cons (cons (quote lambda)
(cons (map car decl) body))
(map cadr decl))))
void
init_functions(Environment
environment
)
Adds the functions +, *, -, =, <, >,
concat, read-string, eval,
apply, global-environment, var, cdr, null?,
setcar!, setcdr!, cons and list to the
environment
.
void
init_specials(Environment
environment
)
Adds the special functions quote, set!, setq,
while, define, defmacro, lambda, if, and, or,
begin and catch to the environment
.
void
main()
Instantiates a copy of the default environment and starts an interactive main loop that connects to standard I/O. The main loop is as follows:
(begin
(define (loop)
(let ((line (read-line
Local
gives a local module namespace used for locally
installed pike modules.
Modules are searched for in the directory pike_modules which can be located in the user's home directory or profile directory, or in any of the system directories /opt/share, /usr/local/share, /opt or /usr/local/.
The user's home directory is determined by examining the environment variable HOME, and if that fails the environment variable USERPROFILE.
If the environment variable PIKE_LOCAL_PATH is set, the paths specified there will be searched first.
If the user has installed the pike module Mine.pmod in the directory $HOME/pike_modules. it can be accessed as Local.Mine.
Local.add_path()
, Local.remove_path()
bool
add_path(string
path
)
This function prepends path
to the Local
module
searchpath.
path
The path to the directory to be added.
Returns 1 on success, otherwise 0.
inherit __joinnode : __joinnode
void
remove_path(string
path
)
This function removes path
from the Local
module
searchpath. If path
is not in the search path, this is
a noop.
path
The path to be removed.
The functions and classes in the top level of the Locale module implements a dynamic localization system, suitable for programs that needs to change locale often. It is even possible for different threads to use different locales at the same time.
The highest level of the locale system is called projects. Usually one program consists of only one project, but for bigger applications, or highly modular applications it is possible for several projects to coexist.
Every project in turn contains several unique tokens, each one representing an entity that is different depending on the currently selected locale.
// The following line tells the locale extractor what to // look for. // <locale-token project="my_project">LOCALE</locale-token>
// The localization macro. #define LOCALE(X,Y) Locale.translate("my_project", \ get_lang(), X, Y)
string get_lang() { return random(2)?"eng":"swe"; }
int(0..0) main() { write(LOCALE(0, "This is a line.")+"\n"); write(LOCALE(0, "This is another one.\n"); return 0; }
In order to update your code to actually use the locale strings you need to run the locale extractor.
This is available as pike -x extract_locale
Syntax: pike -x extract_locale [arguments] infile(s)
Arguments: --project=name default: first found in infile
--config=file default: [project].xml
--out=file default: [project]_eng.xml
--nocopy update infile instead of infile.new
--notime don
function
(:void
) call(string
project
, string
lang
, string
name
, void
|function
(:void
)|string
fb
)
Returns a localized function If function not found, tries fallback function fb, or fallback language fb instead
mapping
(string
:object
) get_objects(string
lang
)
Reads in and returns a mapping with all the registred projects' LocaleObjects in the language 'lang'
array
(string
) list_languages(string
project
)
Returns a list of all registered languages for a specific project.
void
register_project(string
name
, string
path
, void
|string
path_base
)
Make a connection between a project name and where its localization files can be found. The mapping from project name to locale file is stored in projects.
void
set_default_project_path(string
path
)
In the event that a translation is requested in an unregistered project, this path will be used as the project path. %P will be replaced with the requested projects name.
string
translate(string
project
, string
lang
, string
|int
id
, string
fallback
)
Returns a translation for the given id, or the fallback string
This class simulates a multi-language "string". The actual language to use is determined as late as possible.
Locale.DeferredLocale Locale.DeferredLocale(
string
project
, function
(:string
) get_lang
, string
|int
key
, string
fallback
)
protected
string
Locale.DeferredLocale.project
protected
function
(:string
) Locale.DeferredLocale.get_lang
protected
string
|int
Locale.DeferredLocale.key
protected
string
Locale.DeferredLocale.fallback
array
get_identifier()
Return the data nessesary to recreate this "string".
This is the old location for the predef::Charset
module.
Replaced by predef::Charset
.
inherit predef::Charset : Charset
This module enables access to localization functions from within Pike.
The message conversion functions in this module do not handle Unicode strings. They only provide thin wrappers to gettext(3) etc, which means strings are assumed to be encoded according to the LC_* and LANG variables. See the docs for gettext(3) for details.
constant
Locale.Gettext.LC_ALL
Locale category for all of the locale.
constant
Locale.Gettext.LC_COLLATE
Locale category for the functions strcoll() and strxfrm() (used by pike, but not directly accessible).
constant
Locale.Gettext.LC_CTYPE
Locale category for the character classification and conversion routines.
constant
Locale.Gettext.LC_MESSAGES
Document this constant.
This category isn't available on all platforms.
constant
Locale.Gettext.LC_MONETARY
Locale category for localeconv().
constant
Locale.Gettext.LC_NUMERIC
Locale category for the decimal character.
constant
Locale.Gettext.LC_TIME
Locale category for strftime() (currently not accessible from Pike).
string
bindtextdomain(string
|void
domainname
, string
|void
dirname
)
Binds the path predicate for a message domainname
domainname to
the directory name specified by dirname
.
If domainname
is a non-empty string and has not been bound
previously, bindtextdomain() binds domainname
with dirname
.
If domainname
is a non-empty string and has been bound previously,
bindtextdomain() replaces the old binding with dirname
.
The dirname
argument can be an absolute or relative pathname
being resolved when gettext()
, dgettext()
or dcgettext()
are called.
If domainname
is zero or an empty string, bindtextdomain()
returns 0.
User defined domain names cannot begin with the string "SYS_"
.
Domain names beginning with this string are reserved for system use.
The return value from bindtextdomain()
is a string containing
dirname
or the directory binding associated with domainname
if
dirname
is unspecified. If no binding is found, the default locale
path is returned. If domainname
is unspecified or is an empty string,
bindtextdomain()
takes no action and returns a 0.
textdomain
, gettext
, setlocale
, localeconv
string
dcgettext(string
domain
, string
msg
, int
category
)
Return a translated version of msg
within the context of the
specified domain
and current locale for the specified
category
. Calling dcgettext with category Locale.Gettext.LC_MESSAGES
gives the same result as dgettext.
If there is no translation available, msg
is returned.
Obsoleted by gettext()
in Pike 7.3.
bindtextdomain
, textdomain
, gettext
, setlocale
, localeconv
string
dgettext(string
domain
, string
msg
)
Return a translated version of msg
within the context
of the specified domain
and current locale. If there is
no translation available, msg
is returned.
Obsoleted by gettext()
in Pike 7.3.
bindtextdomain
, textdomain
, gettext
, setlocale
, localeconv
string
gettext(string
msg
)
string
gettext(string
msg
, string
domain
)
string
gettext(string
msg
, string
domain
, int
category
)
msg
Message to be translated.
domain
Domain from within the message should be translated. Defaults to the current domain.
category
Category from which the translation should be taken.
Defaults to Locale.Gettext.LC_MESSAGES
.
Return a translated version of msg
within the context
of the specified domain
and current locale. If there is no
translation available, msg
is returned.
Prior to Pike 7.3 this function only accepted one argument,
and the other functionality was provided by dgettext()
and dcgettext()
.
bindtextdomain
, textdomain
, setlocale
, localeconv
mapping
localeconv()
The localeconv() function returns a mapping with settings for
the current locale. This mapping contains all values
associated with the locale categories LC_NUMERIC
and
LC_MONETARY
.
| The decimal-point character used to format non-monetary quantities. | ||||||||||
| The character used to separate groups of digits to the left of the decimal-point character in formatted non-monetary quantities. | ||||||||||
| The international currency symbol applicable to the current locale, left-justified within a four-character space-padded field. The character sequences should match with those specified in ISO 4217 Codes for the Representation of Currency and Funds. | ||||||||||
| The local currency symbol applicable to the current locale. | ||||||||||
| The decimal point used to format monetary quantities. | ||||||||||
| The separator for groups of digits to the left of the decimal point in formatted monetary quantities. | ||||||||||
| The string used to indicate a non-negative-valued formatted monetary quantity. | ||||||||||
| The string used to indicate a negative-valued formatted monetary quantity. | ||||||||||
| The number of fractional digits (those to the right of the decimal point) to be displayed in an internationally formatted monetary quantity. | ||||||||||
| The number of fractional digits (those to the right of the decimal point) to be displayed in a formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a non-negative formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a non-negative formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a negative formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a negative formatted monetary quantity. | ||||||||||
| Set to a value indicating the positioning of the positive_sign for a non-negative formatted monetary quantity. The value of p_sign_posn is interpreted according to the following:
| ||||||||||
| Set to a value indicating the positioning of the negative_sign for a negative formatted monetary quantity. The value of n_sign_posn is interpreted according to the rules described under p_sign_posn. |
bindtextdomain
, textdomain
, gettext
, dgettext
, dcgettext
, setlocale
int
setlocale(int
category
, string
locale
)
The setlocale() function is used to set the program's
current locale. If locale
is "C" or "POSIX", the current
locale is set to the portable locale.
If locale
is "", the locale is set to the default locale which
is selected from the environment variable LANG.
The argument category
determines which functions are
influenced by the new locale are LC_ALL
, LC_COLLATE
, LC_CTYPE
,
LC_MONETARY
, LC_NUMERIC
and LC_TIME
.
Returns 1 if the locale setting successed, 0 for failure
bindtextdomain
, textdomain
, gettext
, dgettext
, dcgettext
, localeconv
string
textdomain(void
|string
domain
)
The textdomain() function sets or queries the name of the
current domain of the active LC_MESSAGES
locale category. The
domain
argument is a string that can contain only the
characters allowed in legal filenames. It must be non-empty.
The domain argument is the unique name of a domain on the
system. If there are multiple versions of the same domain on
one system, namespace collisions can be avoided by using
bindtextdomain()
. If textdomain() is not called, a default
domain is selected. The setting of domain made by the last
valid call to textdomain() remains valid across subsequent
calls to setlocale()
, and gettext()
.
The normal return value from textdomain() is a string containing the current setting of the domain. If domainname is void, textdomain() returns a string containing the current domain. If textdomain() was not previously called and domainname is void, the name of the default domain is returned.
bindtextdomain
, gettext
, setlocale
, localeconv
Abstract language locale class, inherited by all the language locale classes.
string
date(int
timestamp
, string
|void
mode
)
Returns the date for posix time timestamp
as a textual string.
mode
Determines what kind of textual string should be produced.
| I.e. "06:36" |
| I.e. "January the 17th in the year of 2002" |
| I.e. "06:37, January the 17th, 2002" |
> Locale.Language.eng()->date(time()); Result: "today, 06:36"
string
day(int(1..7)
num
)
Returns the name of weekday number num
.
constant
Locale.Language.abstract.days
Array(string) with the days of the week, beginning with Sunday.
constant
string
Locale.Language.abstract.english_name
The name of the language in english.
optional
constantint
Locale.Language.abstract.iso_639_1
String with the language code in ISO-639-1 (two character code). Note that all languages does not have a ISO-639-1 code.
constant
int
Locale.Language.abstract.iso_639_2
String with the language code in ISO-639-2/T (three character code).
constant
int
Locale.Language.abstract.iso_639_2B
String with the language code in ISO-639-2/B (three character code). This
is usually the same as the ISO-639-2/T code (iso_639_2
).
constant
Locale.Language.abstract.languages
Mapping(string:string) that maps an ISO-639-2/T id code to the name of that language.
string
month(int(1..12)
num
)
Returns the name of month number num
.
constant
Locale.Language.abstract.months
Array(string) with the months of the year, beginning with January.
constant
string
Locale.Language.abstract.name
The name of the langauge. E.g. "svenska" for Swedish.
string
number(int
i
)
Returns the number i
as a string.
string
ordered(int
i
)
Returns the ordered number i
as a string.
string
short_day(int(1..7)
num
)
Returns an abbreviated weekday name from the weekday number
num
.
string
short_month(int(1..12)
num
)
Returns an abbreviated month name from the month number num
.
Catalan language locale.
inherit "abstract" : "abstract"
Czech language locale by Jan Petrous 16.10.1997, based on Slovenian language module by Iztok Umek.
inherit "abstract" : "abstract"
German language locale by Tvns Böker.
inherit "abstract" : "abstract"
English language locale.
inherit "abstract" : "abstract"
Finnish language locale created by Janne Edelman, Turku Unix Users Group ry, Turku, Finland
inherit "abstract" : "abstract"
French language locale by Patrick Kremer.
inherit "abstract" : "abstract"
Croatian language locale by Klara Makovac 1997/07/02
inherit "abstract" : "abstract"
Hungarian language locale by Zsolt Varga.
inherit "abstract" : "abstract"
Italian language locale by Francesco Chemolli
inherit "abstract" : "abstract"
Japanese language locale.
inherit "abstract" : "abstract"
Maaori (New Zealand) language locale by Jason Rumney
inherit "abstract" : "abstract"
Dutch language locale by Stephen R. van den Berg
inherit "abstract" : "abstract"
Norwegian language locale
inherit "abstract" : "abstract"
Polish language locale by Piotr Klaban <makler@man.torun.pl>.
inherit "abstract" : "abstract"
Portuguese language locale
inherit "abstract" : "abstract"
Russian language locale
inherit "abstract" : "abstract"
Slovenian language locale by Iztok Umek 7. 8. 1997
inherit "abstract" : "abstract"
Spanish language locale
inherit "abstract" : "abstract"
Serbian language locale by Goran Opacic 1996/12/11
inherit "abstract" : "abstract"
Swedish language locale
inherit "abstract" : "abstract"
RFC 1521, the Multipurpose Internet Mail Extensions memo, defines a structure which is the base for all messages read and written by modern mail and news programs. It is also partly the base for the HTTP protocol. Just like RFC 0822, MIME declares that a message should consist of two entities, the headers and the body. In addition, the following properties are given to these two entities:
A MIME-Version header must be present to signal MIME compatibility
A Content-Type header should be present to describe the nature of the data in the message body. Seven major types are defined, and an extensive number of subtypes are available. The header can also contain attributes specific to the type and subtype.
A Content-Transfer-Encoding may be present to notify that the data of the body is encoded in some particular encoding.
Raw data to be interpreted according to the Content-Type header
Can be encoded using one of several Content-Transfer-Encodings to allow transport over non 8bit clean channels
The MIME module can extract and analyze these two entities from a stream
of bytes. It can also recreate such a stream from these entities.
To encapsulate the headers and body entities, the class MIME.Message
is
used. An object of this class holds all the headers as a mapping from
string to string, and it is possible to obtain the body data in either
raw or encoded form as a string. Common attributes such as message type
and text char set are also extracted into separate variables for easy
access.
The Message class does not make any interpretation of the body
data, unless the content type is multipart. A multipart
message contains several individual messages separated by boundary
strings. The Message->create
method of the Message class will
divide a multipart body on these boundaries, and then create
individual Message objects for each part. These objects will be
collected in the array Message->body_parts
within the original
Message object. If any of the new Message
objects have a body of
type multipart, the process is of course repeated recursively.
string
|StringRange
decode(string
|StringRange
data
, string
encoding
)
Extract raw data from an encoded string suitable for transport between systems.
The encoding can be any of
|
|
|
|
|
|
|
The encoding string is not case sensitive.
MIME.encode()
string
decode_base64(string
encoded_data
)
This function decodes data encoded using the base64 transfer encoding.
MIME.encode_base64()
, MIME.decode()
string(8bit)
decode_base64url(string(7bit)
x
)
Decode strings according to RFC 4648 base64url encoding.
string
decode_qp(string
encoded_data
)
This function decodes data encoded using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.
MIME.encode_qp()
, MIME.decode()
string
decode_uue(string
encoded_data
)
This function decodes data encoded using the x-uue transfer encoding. It can also be used to decode generic UUEncoded files.
MIME.encode_uue()
, MIME.decode()
array
(string
) decode_word(string
word
)
Extracts the textual content and character set from an encoded word as specified by RFC 1522. The result is an array where the first element is the raw text, and the second element the name of the character set. If the input string is not an encoded word, the result is still an array, but the char set element will be set to 0.
Note that this function can only be applied to individual encoded words.
MIME.encode_word()
array
(array
(string
)) decode_words_text(string
txt
)
Separates a header value containing text into units and calls
MIME.decode_word()
on them. The result is an array where each element
is a result from decode_word()
.
MIME.decode_words_tokenized
MIME.decode_words_text_remapped
string
decode_words_text_remapped(string
txt
)
Like MIME.decode_words_text()
, but the extracted strings are
also remapped from their specified character encoding into UNICODE,
and then pasted together. The result is thus a string in the original
text format, without RFC 1522 escapes, and with all characters in UNICODE
encoding.
MIME.decode_words_tokenized_remapped
array
(array
(string
)|int
) decode_words_tokenized(string
phrase
, int
|void
flags
)
Tokenizes a header value just like MIME.tokenize()
, but also
converts encoded words using MIME.decode_word()
. The result is
an array where each element is either an int
representing
a special character, or an array
as returned by
decode_word()
representing an atom or a quoted string.
MIME.decode_words_tokenized_labled
MIME.decode_words_tokenized_remapped
MIME.decode_words_text
array
(array
(string
|int
|array
(array
(string
)))) decode_words_tokenized_labled(string
phrase
, int
|void
flags
)
Tokenizes and labels a header value just like MIME.tokenize_labled()
,
but also converts encoded words using MIME.decode_word()
. The result
is an array where each element is an array of two or more elements, the
first being the label. The rest of the array depends on the label:
| One additional element, containing the character code for the special
character as an |
| Two additional elements, the first being the word, and the second being the character set of this word (or 0 if it did not originate from an encoded word). |
| One additional element, containing the domain literal as a string. |
| One additional element, containing an array as returned by
|
MIME.decode_words_tokenized_labled_remapped
array
(array
(string
|int
)) decode_words_tokenized_labled_remapped(string
phrase
, int
|void
flags
)
Like MIME.decode_words_tokenized_labled()
, but the extracted words are
also remapped from their specified character encoding into UNICODE.
The result is identical to that of MIME.tokenize_labled()
, but
without RFC 1522 escapes, and with all characters in UNICODE encoding.
array
(string
|int
) decode_words_tokenized_remapped(string
phrase
, int
|void
flags
)
Like MIME.decode_words_tokenized()
, but the extracted atoms are
also remapped from their specified character encoding into UNICODE.
The result is thus identical to that of MIME.tokenize()
, but
without RFC 1522 escapes, and with all characters in UNICODE encoding.
MIME.decode_words_tokenized_labled_remapped
MIME.decode_words_text_remapped
string
encode(string
data
, string
encoding
, void
|string
filename
, void
|int
no_linebreaks
)
Encode raw data into something suitable for transport to other systems.
The encoding can be any of
|
|
|
|
|
|
|
The encoding string is not case sensitive. For the x-uue encoding,
an optional filename
string may be supplied.
If a nonzero value is passed as no_linebreaks
, the result string
will not contain any linebreaks (base64 and quoted-printable
only).
MIME.decode()
string
encode_base64(string
data
, void
|int
no_linebreaks
)
This function encodes data using the base64 transfer encoding.
If a nonzero value is passed as no_linebreaks
, the result string
will not contain any linebreaks.
MIME.decode_base64()
, MIME.encode()
string(7bit)
encode_base64url(string(8bit)
x
)
Encode strings according to RFC 4648 base64url encoding.
string
encode_qp(string
data
, void
|int
no_linebreaks
)
This function encodes data using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.
If a nonzero value is passed as no_linebreaks
, the result
string will not contain any linebreaks.
Please do not use this function. QP is evil, and there's no excuse for using it.
MIME.decode_qp()
, MIME.encode()
string
encode_uue(string
encoded_data
, void
|string
filename
)
This function encodes data using the x-uue transfer encoding.
The optional argument filename
specifies an advisory filename to include
in the encoded data, for extraction purposes.
This function can also be used to produce generic UUEncoded files.
MIME.decode_uue()
, MIME.encode()
string
encode_word(string
|array
(string
) word
, string
encoding
)
Create an encoded word as specified in RFC 1522 from an array containing a raw text string and a char set name.
The text will be transfer encoded according to the encoding argument,
which can be either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
If either the second element of the array (the char set name), or the encoding argument is 0, the raw text is returned as is.
MIME.decode_word()
string
encode_words_quoted(array
(array
(string
)|int
) phrase
, string
encoding
)
The inverse of decode_words_tokenized()
, this functions accepts
an array like the argument to quote()
, but instead of simple strings
for atoms and quoted-strings, it will also accept pairs of strings to
be passed to encode_word()
.
encoding
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
MIME.encode_words_quoted_remapped()
MIME.encode_words_quoted_labled()
string
encode_words_quoted_labled(array
(array
(string
|int
|array
(string
|array
(string
)))) phrase
, string
encoding
)
The inverse of decode_words_tokenized_labled()
, this functions accepts
an array like the argument to quote_labled()
, but "word" labled
elements can optionally contain an additional string element specifying
a character set, in which case an encoded-word will be used. Also, the
format for "comment" labled elements is entirely different; instead of
a single string, an array of strings or pairs like the first argument to
encode_words_text()
is expected.
encoding
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
MIME.encode_words_quoted()
MIME.encode_words_quoted_labled_remapped()
string
encode_words_quoted_labled_remapped(array
(array
(string
|int
)) phrase
, string
encoding
, string
|function
(string
:string
) charset
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
The inverse of decode_words_tokenized_labled_remapped()
, this function
accepts an array equivalent to the argument of quote_labled()
, but also
performs on demand word encoding in the same way as
encode_words_text_remapped()
.
string
encode_words_quoted_remapped(array
(string
|int
) phrase
, string
encoding
, string
|function
(string
:string
) charset
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
The inverse of decode_words_tokenized_remapped()
, this functions
accepts an array equivalent to the argument of quote()
, but also
performs on demand word encoding in the same way as
encode_words_text_remapped()
.
MIME.encode_words_text_remapped()
MIME.encode_words_quoted_labled_remapped()
string
encode_words_text(array
(string
|array
(string
)) phrase
, string
encoding
)
The inverse of decode_words_text()
, this function accepts
an array of strings or pairs of strings which will each be encoded
by encode_word()
, after which they are all pasted together.
encoding
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
MIME.encode_words_text_remapped
string
encode_words_text_remapped(string
text
, string
encoding
, string
|function
(string
:string
) charset
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
This is the reverse of MIME.decode_words_text_remapped()
. A
single UNICODE string is provided, which is separated into
fragments and transcoded to selected character sets by this
function as needed.
encoding
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
charset
Either the name of a character set to use, or a function returning a character set to use given a text fragment as input.
replacement
The replacement
argument to use when calling Charset.encoder
repcb
The repcb
argument to use when calling Charset.encoder
MIME.encode_words_tokenized_remapped
string
ext_to_media_type(string
extension
)
Returns the MIME media type for the provided filename extension
.
Currently 469 file extensions are known to this method. Zero will
be returned on unknown file extensions.
string
generate_boundary()
This function will create a string that can be used as a separator string
for multipart messages. If a boundary prefix has been set
using MIME.set_boundary_prefix()
, the generated string will be prefixed
with the boundary prefix.
The generated string is guaranteed not to appear in base64, quoted-printable, or x-uue encoded data. It is also unlikely to appear in normal text. This function is used by the cast method of the Message class if no boundary string is specified.
MIME.set_boundary_prefix()
string(8bit)
get_boundary_prefix()
Returns the boundary_prefix set via set_boundary_prefix()
.
MIME.set_boundary_prefix()
, MIME.Message.setboundary()
string
guess_subtype(string
type
)
Provide a reasonable default for the subtype field.
Some pre-RFC 1521 mailers provide only a type and no subtype in the
Content-Type header field. This function can be used to obtain a
reasonable default subtype given the type of a message. (This is done
automatically by the MIME.Message
class.)
Currently, the function uses the following guesses:
|
|
|
|
|
|
inherit ___MIME : ___MIME
array
(mapping
(string
:string
)|string
) parse_headers(string
message
)
array
(mapping
(string
:array
(string
))|string
) parse_headers(string
message
, int(1..1)
use_multiple
)
This is a low level function that will separate the headers from the body of an encoded message. It will also translate the headers into a mapping. It will however not try to analyze the meaning of any particular header. This means that the body is returned as is, with any transfer-encoding intact.
It is possible to call this function with just the header part of a message, in which case an empty body will be returned.
The result is returned in the form of an array containing two elements. The first element is a mapping containing the headers found. The second element is a string containing the body.
Headers that occurr multiple times will have their contents NUL separated,
unless use_multiple
has been specified, in which case the contents will
be arrays.
string
quote(array
(string
|int
) lexical_elements
)
This function is the inverse of the MIME.tokenize
function.
A header field value is constructed from a sequence of lexical elements.
Characters (int
s) are taken to be special-characters, whereas
strings are encoded as atoms or quoted-strings, depending on whether
they contain any special characters.
There is no way to construct a domain-literal using this function. Neither can it be used to produce comments.
MIME.tokenize()
string
quote_labled(array
(array
(string
|int
)) tokens
)
This function performs the reverse operation of tokenize_labled()
.
MIME.quote()
, MIME.tokenize_labled()
int
|object
reconstruct_partial(array
(object
) collection
)
This function will attempt to reassemble a fragmented message from its parts.
The array collection
should contain MIME.Message
objects forming
a complete set of parts for a single fragmented message.
The order of the messages in the array is not important, but every part
must exist at least once.
Should the function succeed in reconstructing the original message, a
new MIME.Message
object will be returned.
If the function fails to reconstruct an original message, an integer indicating the reason for the failure will be returned:
| Returned if empty |
| If more fragments are needed to reconstruct the entire message, the number of additional messages needed is returned. |
| If more fragments are needed, but the function can't determine exactly how many. |
Note that the returned message may in turn be a part of another, larger, fragmented message.
MIME.Message->is_partial()
void
set_boundary_prefix(string(8bit)
boundary_prefix
)
Set a message boundary prefix. The MIME.generate_boundary()
will use this
prefix when creating a boundary string.
An error is thrown if boundary_prefix
doesn't adhere to RFC 1521.
MIME.generate_boundary()
, MIME.get_boundary_prefix()
boundary_prefix
This must adhere to RFC 1521 and can not be longer than 56 characters.
array
(string
|int
) tokenize(string
header
, int
|void
flags
)
A structured header field, as specified by RFC 0822, is constructed from a sequence of lexical elements.
header
The header value to parse.
flags
An optional set of flags. Currently only one flag is defined:
| Keep backslash-escapes in quoted-strings. |
The lexical elements parsed are:
individual special characters
quoted-strings
domain-literals
comments
atoms
This function will analyze a string containing the header value, and produce an array containing the lexical elements.
Individual special characters will be returned as characters (i.e.
int
s).
Quoted-strings, domain-literals and atoms will be decoded and returned as strings.
Comments are not returned in the array at all.
As domain-literals are returned as strings, there is no way to tell the domain-literal [127.0.0.1] from the quoted-string "[127.0.0.1]". Hopefully this won't cause any problems. Domain-literals are used seldom, if at all, anyway...
The set of special-characters is the one specified in RFC 1521
(i.e. "<", ">", "@", ",", ";", ":", "\", "/", "?", "="
),
and not the set specified in RFC 0822.
MIME.quote()
, tokenize_labled()
,
decode_words_tokenized_remapped()
.
array
(array
(string
|int
)) tokenize_labled(string
header
, int
|void
flags
)
Similar to tokenize()
, but labels the contents, by making
arrays with two elements; the first a label, and the second
the value that tokenize()
would have put there, except
for that comments are kept.
header
The header value to parse.
flags
An optional set of flags. Currently only one flag is defined:
| Keep backslash-escapes in quoted-strings. |
The following labels exist:
| Word encoded according to =?... |
| Special character. |
| Word. |
| Domain literal. |
| Comment. |
MIME.quote()
, tokenize()
,
decode_words_tokenized_labled_remapped()
This class is used to hold a decoded MIME message.
array
(object
) MIME.Message.body_parts
If the message is of type multipart, this is an array
containing one Message object for each part of the message.
If the message is not a multipart, this field is 0
(zero).
type
, boundary
string
MIME.Message.boundary
For multipart messages, this Content-Type parameter gives a delimiter string for separating the individual messages. As multiparts are handled internally by the module, you should not need to access this field.
setboundary()
(
string
)MIME.Message()
Casting the message object to a string will yield a byte stream suitable for transmitting the message over protocols such as ESMTP and NNTP.
The body will be encoded using the current transfer encoding, and
subparts of a multipart will be collected recursively. If the message
is a multipart and no boundary string has been set, one will be
generated using generate_boundary()
.
create()
string
MIME.Message.charset
One of the possible parameters of the Content-Type header is the charset attribute. It determines the character encoding used in bodies of type text.
If there is no Content-Type header, the value of this field
is "us-ascii"
.
type
MIME.Message MIME.Message()
MIME.Message MIME.Message(
string
message
)
MIME.Message MIME.Message(
string
message
, mapping
(string
:string
|array
(string
)) headers
, array
(object
)|void
parts
)
MIME.Message MIME.Message(
string
message
, mapping
(string
:string
|array
(string
)) headers
, array
(object
)|void
parts
, bool
guess
)
There are several ways to call the constructor of the Message class:
With zero arguments, you will get a dummy message with neither headers nor body. Not very useful.
With one argument, the argument is taken to be a byte stream containing a message in encoded form. The constructor will analyze the string and extract headers and body.
With two or three arguments, the first argument is taken to be the raw body data, and the second argument a desired set of headers. The keys of this mapping are not case-sensitive. If the given headers indicate that the message should be of type multipart, an array of Message objects constituting the subparts should be given as a third argument.
With the guess
argument set to 1 (headers
and parts
may be 0
if you don't want to give any), you get a more forgiving MIME Message
that will do its best to guess what broken input data really meant. It
won't always guess right, but for applications like mail archives and
similar where you can't get away with throwing an error at the user,
this comes in handy. Only use the guess
mode only for situations
where you need to process broken MIME messages silently; the
abuse of overly lax tools is what poisons standards.
cast()
string
MIME.Message.data
This variable contains the raw data of the message body entity.
The type
and subtype
attributes indicate how this data should
be interpreted.
In Pike 7.6 and earlier you had to use getdata()
and
setdata()
to access this value.
getdata()
, setdata()
mapping
(string
:string
) MIME.Message.disp_params
A mapping containing all the additional parameters to the Content-Disposition header.
setdisp_param()
, get_filename()
string
MIME.Message.disposition
The first part of the Content-Disposition header, hinting on how this part of a multipart message should be presented in an interactive application.
If there is no Content-Disposition header, this field
is 0
.
string
get_filename()
This method tries to find a suitable filename should you want to save the body data to disk.
It will examine the filename attribute of the Content-Disposition header, and failing that the name attribute of the Content-Type header. If neither attribute is set, the method returns 0.
An interactive application should always query the user for the actual filename to use. This method may provide a reasonable default though.
string
getdata()
This method returns the raw data of the message body entity.
The type
and subtype
attributes indicate how this data should
be interpreted.
setdata()
, getencoded()
, data
string
getencoded()
This method returns the data of the message body entity, encoded using the current transfer encoding.
You should never have to call this function.
getdata()
mapping
(string
:string
) MIME.Message.headers
This mapping contains all the headers of the message.
The key is the header name (in lower case) and the value is the header value.
Although the mapping contains all headers, some particular headers get special treatment by the module and should not be accessed through this mapping. These fields are currently:
|
|
|
|
The contents of these fields can be accessed and/or modified through a set of variables and methods available for this purpose.
type
, subtype
, charset
, boundary
, transfer_encoding
,
params
, disposition
, disp_params
, setencoding()
,
setparam()
, setdisp_param()
, setcharset()
, setboundary()
array
(string
|int
) is_partial()
If this message is a part of a fragmented message (i.e. has a Content-Type of message/partial), an array with three elements is returned.
The first element is an identifier string. This string should be used to group this message with the other fragments of the message (which will have the same id string).
The second element is the sequence number of this fragment. The first part will have number 1, the next number 2 etc.
The third element of the array is either the total number of fragments that the original message has been split into, or 0 of this information is not available.
If this method is called in a message that is not a part of a fragmented message, it will return 0.
MIME.reconstruct_partial()
mapping
(string
:string
) MIME.Message.params
A mapping containing all the additional parameters to the Content-Type header.
Some of these parameters have fields of their own, which should be accessed instead of this mapping wherever applicable.
charset
, boundary
, setparam()
protected
void
parse_param(mapping
(string
:string
) params
, array
(string
|int
) entry
, string
header
, int
|void
guess
, array
(string
|int
)|void
entry2
)
Parse a Content-Type or Content-Disposition parameter.
params
Mapping to add parameters to.
entry
Array of tokens containing a parameter declaration.
header
Name of the header from which entry
originated.
This is only used to report errors.
guess
Make a best-effort attempt to parse broken entries.
entry2
Same as entry
, but tokenized with MIME.TOKENIZE_KEEP_ESCAPES
.
create()
void
setboundary(string
boundary
)
Sets the boundary parameter of the Content-Type header.
This is equivalent of calling setparam("boundary",
.boundary
)
setparam()
void
setcharset(string
charset
)
Sets the charset parameter of the Content-Type header.
This is equivalent of calling setparam("charset",
.charset
)
setparam()
void
setdata(string
data
)
Replaces the body entity of the data with a new piece of raw data.
The new data should comply to the format indicated by the
type
and subtype
attributes.
Do not use this method unless you know what you are doing.
getdata()
, setencoded
, data
void
setdisp_param(string
param
, string
value
)
Set or modify the named parameter of the Content-Disposition header.
A common parameters is e.g. filename.
It is not allowed to modify the Content-Disposition header directly, please use this function instead.
setparam()
, get_filename()
void
setencoding(string
encoding
)
Select a new transfer encoding for this message.
The Content-Transfer-Encoding header will be modified accordingly,
and subsequent calls to getencoded
will produce data encoded using
the new encoding.
See MIME.encode()
for a list of valid encodings.
getencoded()
, MIME.encode()
void
setparam(string
param
, string
value
)
Set or modify the named parameter of the Content-Type header.
Common parameters include charset for text messages, and boundary for multipart messages.
It is not allowed to modify the Content-Type header directly, please use this function instead.
setcharset()
, setboundary()
, setdisp_param()
string
MIME.Message.subtype
The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the subtype attribute extracted from the header.
If there is no Content-Type header, the value of this field
is "plain"
.
type
, params
string
MIME.Message.transfer_encoding
The contents of the Content-Transfer-Encoding header.
If no Content-Transfer-Encoding header is given, this field
is 0
(zero).
Transfer encoding and decoding is done transparently by the module, so this field should be interesting only to applications wishing to do auto conversion of certain transfer encodings.
setencoding()
string
MIME.Message.type
The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the type attribute extracted from the header.
If there is no Content-Type header, the value of this field
is "text"
.
subtype
, params
Class representing a substring of a larger string.
This class is used to reduce the number of string copies
during parsing of MIME.Message
s.
int
choose(int
n
, int
k
)
Calculate binomial koefficient n
choose k
.
This is equivalent to n
!/(k
!*(n
-k
)!).
int
|float
convert_angle(int
|float
angle
, string
from
, string
to
)
This function converts between degrees, radians and gons. The
from
and to
arguments may be any of the follwoing
strings: "deg", "rad", "gon" and "str" for degrees, radians, gon
and streck respectivly. The output is not guaranteed to be within
the first turn, e.g. converting 10 radians yields almost 573
degrees as output.
constant
Math.e
The constant e (2.7182818284590452354).
array
(int
) factor(int
x
)
Factorize the integer x
. The returned list of factors will
be sorted biggest to smallest factor.
This function is only available when Pike has been compiled with bignums.
In Pike versions prior to v8.0, only primes <= 8161
were
considered.
constant
Math.inf
Floating point infinity.
inherit "___Math" : "___Math"
float
log10(int
|float
x
)
The 10-logarithm of x
.
float
log2(int
|float
x
)
The 2-logarithm of x
.
float
logn(int
|float
n
, int
|float
x
)
The n
-logatirhm of x
.
constant
Math.nan
Floating point not-a-number (e.g. inf/inf).
constant
Math.pi
The constant pi (3.14159265358979323846).
Represents an angle.
int
hash_value( Math.Angle arg )
float
|int
|Angle
res = Math.Angle()
% _angle
Returns this result of this angle modulo the provided value. If differenced with an angle, a new angle object is returned.
float
|int
|Angle
res = Math.Angle()
* _angle
Returns the product between this angle and the provided value. If differenced with an angle, a new angle object is returned.
float
|int
|Angle
res = Math.Angle()
+ _angle
Returns the sum of this angle and what it is added with. If added with an angle, a new angle object is returnes.
float
|int
|Angle
res = Math.Angle()
- _angle
Returns the difference between this angle and the provided value. If differenced with an angle, a new angle object is returned.
float
|int
|Angle
res = Math.Angle()
/ _angle
Returns the fraction between this angle and the provided value. If differenced with an angle, a new angle object is returned.
int
res = Math.Angle()
< _angle
Compares the unnormalized angle of two Angle objects.
int
res = Math.Angle()
== _angle
Compares the unnormalized angle of two Angle objects.
int
res = Math.Angle()
> _angle
Compares the unnormalized angle of two Angle objects.
void
about_face()
Turns the direction of the angle half a turn. Equal to
add(180,"deg")
.
Angle
add(float
|int
angle
)
Angle
add(float
|int
angle
, string
type
)
Angle
add(Angle
angle
)
Adds the provided angle to the current angle. The result is normalized within 360 degrees.
int
|float
Math.Angle.angle
The actual keeper of the angle value.
(
float
)Math.Angle()
(int
)Math.Angle()
(string
)Math.Angle()
An angle can be casted to float, int and string.
Angle
clone_me()
Returns a copy of the object.
float
cos()
Returns the cosinus for the angle.
Math.Angle Math.Angle()
Math.Angle Math.Angle(
int
|float
radians
)
Math.Angle Math.Angle(
int
|float
angle
, string
type
)
If an angle object is created without arguments it will have the value 0 radians.
int
|float
degree()
Returns the number of degrees, including minutes and seconds as decimals.
string
format_dms()
Returns degrees, minutes and seconds as a string, e.g. 47°6'36.00".
int
|float
get(string
type
)
Gets the value in the provided type.
int
|float
gon()
Returns the number of gons.
void
left_face()
Turns the direction of the angle a quarter of a turn to the left.
Equal to add(90,"deg")
.
int
minute()
Returns the number of minute.
void
normalize()
Normalizes the angle to be within one turn.
float
rad()
Returns the number of radians.
void
right_face()
Turns the direction of the angle a quarter of a turn to the right.
Equal to subtract(90,"deg")
.
float
second()
Returns the number of seconds.
Angle
set(string
type
, int
|float
_angle
)
Sets the angle value and type to the given value and type.
Angle
set_degree(int
|float
degree
)
Sets the angle to the provided degree. Alters the type to degrees. Returns the current object.
Angle
set_dms(int
degrees
)
Angle
set_dms(int
degrees
, int
minutes
)
Angle
set_dms(int
degrees
, int
minutes
, float
seconds
)
Set degrees, minues and seconds. Returns the current angle object.
Angle
set_gon(int
|float
gon
)
Set the angle to the provided gons. Alters the type to gons. Returns the current angle object.
Angle
set_rad(int
|float
rad
)
Set the angle to the provided radians. Alters the type to radians. Returns the current angle object.
Angle
set_streck(int
|float
str
)
Set the angle to the provided strecks. Alters the type to streck. Returns the current angle object.
float
sin()
Returns the sinus for the angle.
float
|int
streck()
Returns the number of strecks.
Angle
subtract(float
|int
angle
)
Angle
subtract(float
|int
angle
, string
type
)
Angle
subtract(Angle
angle
)
Subtracts the provided angle from the current angle. The result is normalized within 360 degrees.
float
tan()
Returns the tangen for the angle.
string
Math.Angle.type
The type of the angle value. Is either "deg", "rad", "gon" or "str".
Matrix representation with single precision floating point values.
inherit Matrix : Matrix
Matrix representation with 32 bit integer values.
inherit Matrix : Matrix
Matrix representation with 64 bit integer values.
inherit Matrix : Matrix
Matrix representation with double precision floating point values.
Matrix
res = Math.Matrix()
* with
Matrix
res = with
* Math.Matrix()
Matrix
mult(object
with
)
Matrix multiplication.
Matrix
res = Math.Matrix()
+ with
Matrix
res = with
+ Math.Matrix()
Matrix
add(object
with
)
Add this matrix to another matrix. A new matrix is returned. The matrices must have the same size.
Matrix
res = Math.Matrix()
- x
Matrix
res = Math.Matrix()
- with
Matrix
res = with
- Math.Matrix()
Matrix
sub(object
with
)
Subtracts this matrix from another. A new matrix is returned.
-m
is equal to -1*m
.
(
array
(array
(float
)))Math.Matrix()
(
array
(array
(float
)))Math.Matrix()
It is possible to cast the matrix to an array and get back a double array of floats with the matrix values.
vect
Matrix
convolve(object
with
)
Convolve called matrix with the argument.
Math.Matrix Math.Matrix(
array
(array
(int
|float
)) matrix_2d
)
Math.Matrix Math.Matrix(
array
(int
|float
) matrix_1d
)
Initializes the matrix as a 1D or 2D matrix, e.g.
Math.Matrix( ({({1,2}),({3,4})}) )
.
Math.Matrix Math.Matrix(
int
n
, int
m
)
Math.Matrix Math.Matrix(
int
n
, int
m
, string
type
)
Math.Matrix Math.Matrix(
int
n
, int
m
, float
|int
init
)
Initializes the matrix as to be a n
*m
matrix with init
in
every value. If no third argument is given, or the third argument
is "identity"
, the matrix will be initialized with all
zeroes except for the diagonal which will be 1
.
Math.Matrix Math.Matrix(
string
type
, int
size
)
When type
is "identity"
the matrix is initializes as a
square identity matrix.
Math.Matrix Math.Matrix(
string
type
, int
size
, float
rads
, Matrix
axis
)
Math.Matrix Math.Matrix(
string
type
, int
size
, float
rads
, float
x
, float
y
, float
z
)
When type
is "rotate"
the matrix is initialized as a
rotation matrix.
Matrix
cross(object
with
)
Matrix cross-multiplication.
float
dot_product(object
with
)
Matrix dot product.
Matrix
max()
Matrix
min()
Produces the maximum or minimum value of all the elements in the matrix.
float
norm()
float
norm2()
Matrix
normv()
Norm of the matrix, and the square of the norm of the matrix. (The later method is because you may skip a square root sometimes.)
This equals |A| or sqrt( A02 + A12 + ... + An2 ).
It is only usable with 1xn or nx1 matrices.
m->normv()
is equal to m*(1.0/m->norm())
,
with the exception that the zero vector will still be
the zero vector (no error).
Matrix
sum()
Produces the sum of all the elements in the matrix.
Matrix
transpose()
Returns the transpose of the matrix as a new object.
array
vect()
Return all the elements of the matrix as an array of numbers
int
xsize()
Returns the width of the matrix.
int
ysize()
Returns the height of the matrix.
Matrix representation with 16 bit integer values.
inherit Matrix : Matrix
Math.Transforms.FFT Math.Transforms.FFT(
void
|int
n
, void
|bool
exact
)
Creates a new transform object. If n is specified, a plan is created for transformations of n-size arrays.
n
Size of the transform to be preformed. Note that the transform object will be initialized for this size, but if an array of different size is sent to the object, it will be reinitialized. This can be used to gain preformace if all transforms will be of a given size.
exact
If exact is 1, a "better" plan for the transform will be created. This will take more time though. Use only if preformance is needed.
array
(array
(float
)) rFFT(array
(int
|float
) real_input
)
Returns the FFT of the input array. The input must be real and the output is complex. The output consists of an array. It's first element is the amplitudes and the second element is the phases.
real_input
The array of floats and/or ints to transform.
rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.
rIFFT()
array
(float
) rIFFT(array
(array
(float
)) input
)
Returns the inverse FFT of the input array. The input must be complex and guaranteed to generate a real output.
The input is an array. It's first element is the amplitudes and the second element is the phases.
The output is an array of the real values for the iFFT.
real_input
The array of floats and/or ints to transform.
rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.
rFFT()
Various networking-related utility functions.
string
NetUtils.ANY
Returns either 0 or "::" depending on whether or not this computer has IPv6 support.
The intent is to use this when binding addresses, like port->bind(portno,callback,NetUtils.ANY) to get ipv6 support if present.
The reason for the existence of this function is that using "::" on a computer that does not actually have any ipv6 addresses (and thus no support for ipv6), at least on linux, causes the bind call to fail entirely.
Read only
mapping
(string
:array
(string
)) broadcast_addresses()
Returns a mapping from interface name to the broadcast addresses on that interface.
array
(int
) cidr_to_netmask(string
cidr
)
Converts a string with an IP address and mask (in CIDR notation) into a binary IP address and bitmask.
cidr
The CIDR-notation input string.
An array containing:
Array | |
| The binary representation of the IP address. |
| The bitmask. |
Returns 0 if the string could not be parsed.
void
clear_cache()
Clear any caches. This might be needed if the network setup on the system changes.
array
(NetworkType
) connectable_network_types()
Returns network types in priority order according to RFC 3484.
This function assumes a network category (ipv4 or ipv6) is available if the local host has a configured address (excluding localhost) of that network type.
This function will always list the v6 and non-v6 addresses separately.
NetworkType
get_network_type(int
|string
ipstr
, bool
|void
separate_6
)
Determine the network type of a given host
ipstr
IP address in string or numerical form
separate_6
Adds a 'v6' to the category for ipv6 addresses (ie, "global" and "globalv6")
"localhost", "local", "private", "multicast", "teredo", "6to4" or "global"
"localhost" is the local computer.
"local" is the local network
"private" is a private network, such as 10.0.0.0/8 or fc00::/7 that is not also a local network.
"multicast" is a multicast address
"teredo" and "6to4" is an address in the teredo and 6to4 tunneling system, respectively.
"global" is a global address that does not match any other category
bool
has_ipv4()
Returns true if the local host has a public IPv4 address
bool
has_ipv6()
Returns true if the local host has a public IPv6 address
string
host_to_cidr(int
|string
ip
)
Return the CIDR notation for the single host defined by x
.
ip
The host ip in either string or raw form
either ip
/128 or ip
/32 depending on the IPV6-ness of the host IP.
array
(string
) ip_and_port_of(RemoteAddressObject
|string
|int(0..0)
inc
, bool
|void
local_address
)
Similar to ip_of. Returns 2-element array containing IP address and port number. Second element will be 0 if no port number can be retrieved.
This function can return 0 if inc
is a RemoteAddressObject
and query_address throws an error or does not return a string.
bool
ip_in_block(int
net
, int
mask
, int
|string
ip
)
Checks whether an IP address is in a block.
The net and mask parameters should be as returned from cidr_to_netmask
.
Throws an error if the IP address could not be parsed.
net
The network component of the block.
mask
The bitmask of the block.
ip
The IP address to check, in either string or binary representation.
true if the IP is in the given block, false otherwise.
bool
ip_less_global(int
|string
which
, int
|string
towhat
, bool
|void
prefer_v4
)
Returns true if which
is less globally accessible than
towhat
.
string
ip_of(RemoteAddressObject
|string
|int(0..0)
inc
, bool
|void
local_address
, string
|void
def
)
If the argument is an object with a query_address
method,
return the IP# part of the string returned by calling that
function with local_address
as the argument.
This means that for Stdio.File objects the remote address is
returned by default, but if local_address
is true the local
address is returned.
If the argument is a string instead, the part of the string before the first space is returned.
If the argument is 0 the default def
value is returned,
UNDEFINED unless specified.
If def
is supplied, it is used both when query_address() fails
or something that is not a file descriptor object or a string is
passed as the argument to this function.
string
ip_to_string(int
ip
, bool
|void
v6_only
)
Converts a binary representation of an IP address into the IPv4 or IPv6 string representation.
The reverse of string_to_ip.
ip
The binary representation of the address.
v6_only
Always return IPV6 addresses. IPV4 addresses will be formatted as ::FFFF:<ipv4>
The string representation of the address, or 0 if the IP was invalid.
bool
is_ipv6(int
|string
ip
)
Returns true if the IP ip
is a IPV6 IP.
bool
is_local_host(RemoteAddressObject
|string
|int
host
, bool
|void
only_localhost
)
Returns true if host points to the local host.
host
The host to check
only_localhost
Only check if it is ipv6 or ipv4 localhost, not if it is one of the public IP# of this host.
true if the given host
is the local host, false otherwise
string
is_local_network(RemoteAddressObject
|int
|string
host
)
Returns non-zero if host is on one of the local networks, and if so which interface it is on.
string
local_host()
Returns either ::1 or 127.0.0.1 depending on the availability of IPV6.
mapping
(string
:array
(string
)) local_interfaces()
Return a mapping from interface to address/netmask (only returns non link-local addresses for ipv6)
multiset
(string
) local_ips(bool
|void
include_localhost
)
Return an array with locally configured IP-numbers, excluding the
ones configured on the loopback inteface, unless
include_localhost
is specified.
multiset
(int
) local_ips_raw(bool
|void
include_localhost
)
Much like local_ips, but returns the IP:s parsed to the integer raw format.
IpRangeLookup
local_networks()
Returns an IpRangeLookup that can be used to find the interface for an IP address.
constant
NetUtils.locality
Mapping from NetworkType
to an integer between 0 and 10 that
describes how local that type of network is.
int
netmask_to_cidr(string
mask
)
Returns the CIDR of a given netmask. Only returns the correct value for netmasks with all-zeroes at the end (eg, 255.255.255.128 works, while 255.255.255.3 will give the wrong return value)
http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation
string
normalize_address(string
a
)
Normalize the IP specified in a
. This normalizes IPv6
addresses and converts ::FFFF:<ipv4> and ::<ipv4> to "normal" IPV4
addresses.
Will return 0 if a
is not a valid address.
string
port_of(RemoteAddressObject
|string
|int(0..0)
inc
, bool
|void
local_address
, string
|void
def
)
Similar to ip_of but instead of IP returns port number.
If the argument is an object with a query_address
method,
return the port# part of the string returned by calling that
function with local_address
as the argument.
This means that for Stdio.File objects the remote address is
returned by default, but if local_address
is true the local
address is returned.
If the argument is a string instead, the part of the string after the first space is returned.
If the argument is 0 the default def
value is returned,
UNDEFINED unless specified.
If def
is supplied, it is used both when query_address() fails
or something that is not a file descriptor object or a string is
passed as the argument to this function.
array
(string
) sort_addresses(array
(string
) addresses
, array
(NetworkType
)|void
exclude_types
, bool
|void
separate_v6
)
Given a list of addresses, sort them according to connectable priority order (RFC 3484).
If exclude_types
is specified, addresses that match any of the
network types (({"local", "localhost"}) for the local network as an example)
in the given array will be exluded from the result.
If separate_v6
is true, exclude_types
separates v6 from
v4. That is, you can disable "localhost" without also disabling
"localhostv6".
The addresses inside each group will be returned in random order.
IpRangeLookup
special_networks()
Return an IpRangeLookup
instance useful for finding out the
address category of a ip. Basically like get_network_type
without the "local" category.
int
string_to_ip(string
ips
)
Converts a string representation of an IPv4 address into the binary representation.
ips
The string representation of the address. For convenience this function accepts the notation returned from fd->query_adddress() ("ip port")
The binary representation of the address, or -1 if the string could not be parsed.
bool
valid_domain_name(string
hostname
)
Perform a basic sanity check on hostname based on total and subdomain label length. Does not test for invalid chars.
hostname
Domain name string to test.
True if hostname
looks like a valid domain name
A list of all known network type/classes
constant
NetUtils.LOCALHOST
constant
NetUtils.LOCAL
constant
NetUtils.MULTICAST
constant
NetUtils.GLOBAL
constant
NetUtils.PRIVATE
V4 and in non-v6-separate mode also used for V6
constant
NetUtils.LOCALHOSTV6
constant
NetUtils.LOCALV6
constant
NetUtils.PRIVATEV6
constant
NetUtils.MULTICASTV6
constant
NetUtils.GLOBALV6
V6 only versions
constant
NetUtils.TEREDO
constant
NetUtils.V6TO4
Tunneling reserved addresses
Class used for checking an IP against a list of IP ranges and looking up some associated information.
NetUtils.IpRangeLookup NetUtils.IpRangeLookup(
mapping
(mixed
:array
(string
)) ranges
, int
|void
_debug
)
Creates a new IpRangeLookup object and initialises the IP range
table. Errors will be thrown if ranges
contains invalid
data.
ranges
A mapping from information data to arrays of IP ranges.
Each range can be a single addresses ("192.168.1.1"), a range of addresses ("192.168.1.1-192.168.1.5") or be written in CIDR notation ("192.168.1.0/24").
mapping
(string
:array
(Range
)) get_ranges()
Return a copy of the internal range to info mapping.
mixed
lookup(int
|string
ipstr
)
Looks up an IP address and returns the associated information, if any.
ipstr
The IP address in string or binary form.
The information associated with the most-specific IP range matching ipstr.
Range
lookup_range(int
|string
ipstr
)
Looks up an IP address and returns the associated Range
, if any.
ipstr
The IP address in string or binary form.
The matching net-range
Represents a single range in a IpRangeLoopup.
mixed
NetUtils.IpRangeLookup.Range.info
inherit NetMask : NetMask
Persistent representation of a network + mask.
(int)NetUtils.NetMask()
(float)NetUtils.NetMask()
(string)NetUtils.NetMask()
(array)NetUtils.NetMask()
(mapping)NetUtils.NetMask()
(multiset)NetUtils.NetMask()
Convert to either a string (back to CIDR notation) or an array (net,mask)
NetUtils.NetMask NetUtils.NetMask(
string
cidr
)
Construct a new NetMask object from the given CIDR.
cidr
An IP and mask in CIDR notation.
bool
ip_in(int
|string
ip
)
Match an IP number against the mask.
true if the ip
is in the network, false otherwise.
ip
The IP address to check, in either string or binary representation.
int
NetUtils.NetMask.mask
The network mask
int
NetUtils.NetMask.net
The network number
Interface for objects that can be sent to ip_of and friends.
This matches at least Stdio.File and Stdio.Port, Stdio.UDP and some other classes.
Low level crypto functions used by the Crypto
module. Unless
you are doing something very special, you would want to use the
Crypto module instead.
string(7bit)
crypt_md5(string(8bit)
password
, string(8bit)
salt
, void
|string(8bit)
magic
)
Does the crypt_md5 abrakadabra (MD5 + snakeoil). It is assumed
that salt
does not contain "$".
The password
memory will be cleared before released.
array
(Gmp.mpz
) dsa_generate_keypair(int
p_bits
, int
q_bits
, function
(int(0..)
:string(8bit)
) rnd
)
Generates a DSA key pair with p_bits
number of bits (sometimes
referred to as L) for p, and q_bits
number of bits (sometimes
referred to as N) for q, using the random function rnd
.
Valid combinations as per FIPS 186-3 are
p_bits q_bits 1024 160 2048 224 (rejected by some versions of Hogweed) 2048 256 3072 256
Array | |
| The value p, the modulo. |
| The value q, the group order. |
| The value g, the generator. |
| The value y, the public value. |
| The value x, the private value. |
array
(Gmp.mpz
) rsa_generate_keypair(int
bits
, int
e
, function
(int(0..)
:string(8bit)
) rnd
)
Generates an RSA key pair with a bits
sized modulus (n), using
the provided value for e
and random function rnd
.
Array | |
| The value n, the modulo. |
| The value d, the private exponent. |
| The value p, a prime. |
| The value q, a prime. |
int(0..)
rsa_unpad(string(8bit)
data
, int
type
)
Unpads a message that has been padded according to
RSAES-PKCS1-V1_5-ENCODE(message) in PKCS#1 v2.2. The padding
method used on the original message must be provided in the
type
parameter. All content dependent processing is done in
constant time for the same padding type and data
length.
string
version()
Returns the version of the Nettle library, e.g. "3.1". 0 is returned when runtime version is unknown.
Represents information about an Authenticated Encryption with Associated Data (AEAD) algorithm, such as name, key size, digest size, and block size.
int(0..)
block_size()
The block size of the AEAD algorithm.
Note that AEAD algorithms often support automatic padding, so that the last block does not need to be complete.
int(0..)
digest_size()
Returns the size of a MAC digest.
inherit __builtin.Nettle.AEAD : AEAD
int(0..)
iv_size()
Returns the size of the iv/nonce of the AEAD algorithm (if any).
Returns 0
(zero) if there is no configurable iv/nonce.
int(0..)
key_size()
The recommended key size for the cipher.
string(8bit)
name()
A human readable name for the algorithm.
Base class for AEAD contexts.
int(0..)
block_size()
The block size for this cipher.
The default implementation just calls Cipher::block_size()
in the parent.
string(8bit)
crypt(string(8bit)
data
)
Encrypts or decrypts data, using the current key. Neither the
input nor output data is automatically memory scrubbed,
unless String.secure
has been called on them.
data
Data must be an integral number of blocks, except for the last segment.
The encrypted or decrypted data.
string(8bit)
digest(int
|void
length
)
Generates a digest, and resets the AEAD contents.
Also updates the iv/nonce (if any).
length
If the length argument is provided, the digest is truncated to the given length.
The digest.
int(0..)
digest_size()
Returns the size of a MAC digest.
inherit AEAD::State : State
int(0..)
iv_size()
Returns the size of the iv/nonce of the AEAD algorithm (if any).
Returns 0
(zero) if there is no configurable iv/nonce.
int(0..)
key_size()
The actual key size for this cipher.
string(8bit)
make_key()
Generate a key by calling Crypto.Random.random_string
and
initialize this object for encryption with that key.
The generated key. The key memory will be cleared before released.
set_encrypt_key
string(8bit)
name()
A human readable name for the algorithm.
The default implementation just calls Cipher::name()
in the parent.
State
set_decrypt_key(string(8bit)
key
)
Initializes the object for decryption. The key
memory will be
cleared before released.
set_encrypt_key
, crypt
State
set_encrypt_key(string(8bit)
key
)
Initializes the object for encryption. The key
memory will be
cleared before released.
set_decrypt_key
, crypt
State
set_iv(string(8bit)
iv
)
Set the iv/nonce (if supported) for the AEAD.
Returns this
in order to simplify chaining
of function calls.
State
update(string(8bit)
data
)
Add some more associated data.
All associated data typically needs to be added before any data to actually encrypt.
Returns this
in order to simplify chaining
of function calls.
Implementation of the AES cipher.
inherit BlockCipher16 : BlockCipher16
State for AES encyption.
inherit Cipher::State : State
Implementation of the ARCFOUR cipher.
inherit Cipher : Cipher
State for ARCFOUR encyption.
inherit Cipher::State : State
Implementation of the ARCTWO cipher.
inherit BlockCipher : BlockCipher
State for PIKE_NAME encyption.
inherit Cipher::State : State
State
set_decrypt_key(string(8bit)
key
, void
|int
ekb
)
Initializes the object for decryption. The key
memory will be
cleared before released.
ekb
The effective number of bits in the key.
| Derive from the key size (ie |
| Convenience alias for max (ie |
| Reduce the effective key size to the specified number of bits. |
set_encrypt_key
, crypt
State
set_encrypt_key(string(8bit)
key
, int
|void
ekb
)
Initializes the object for encryption. The key
memory will be
cleared before released.
ekb
The effective number of bits in the key.
| Derive from the key size (ie |
| Convenience alias for max (ie |
| Reduce the effective key size to the specified number of bits. |
set_decrypt_key
, crypt
Implementation of the BLOWFISH cipher.
inherit BlockCipher : BlockCipher
State for BLOWFISH encyption.
inherit Cipher::State : State
Base class for all block ciphers.
Extends the BufferedCipher
class with various operating modes.
inherit __builtin.Nettle.BlockCipher : BlockCipher
inherit BufferedCipher : BufferedCipher
Implementation of the cipher block chaining mode (CBC).
Works as a wrapper for the cipher implemented by overloading
the parent class (Cipher
).
Crypto.CBC
, GCM
inherit BufferedCipher : BufferedCipher
int(1..)
block_size()
Returns the block size of the encapsulated cipher.
Nettle.BlockCipher.CBC.State Nettle.BlockCipher.CBC.State()
Initialize the CBC state with the Cipher::State
object
returned by substate_factory()
. This is usually
the State for the cipher implemented in the parent module.
string(8bit)
crypt(string(8bit)
data
)
Encrypt/decrypt data
and return the result. data
must
be an integral number of blocks.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
inherit Cipher::State : State
int(1..)
iv_size()
Returns the size for the initialization vector
int(1..)
key_size()
Returns the key size of the encapsulated cipher.
string(8bit)
name()
Returns the string "CBC(x)"
where x is the
encapsulated algorithm.
this_program
set_decrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for decrypting with the given
key
. The key
memory will be cleared before released.
this_program
set_encrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for encrypting with the given
key
. The key
memory will be cleared before released.
this_program
set_iv(string(8bit)
iv
)
Set the initialization vector to iv
. The iv
memory will be
cleared before released.
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
Implementation of Cipher Feed-Back mode (CFB).
CBC
, GCM
State
res = Nettle.BlockCipher()
()
Returns a new State
object.
inherit BufferedCipher : BufferedCipher
string(8bit)
name()
Returns the base cipher name appended with the string ".CFB"
.
The state for a CFB instance.
int(1..)
block_size()
Returns the block size of the encapsulated cipher.
Nettle.BlockCipher.CFB.State Nettle.BlockCipher.CFB.State()
Initialize the CFB state with the Cipher::State
object
returned by substate_factory()
. This is usually
the State for the cipher implemented in the parent module.
string(8bit)
crypt(string(8bit)
data
)
Encrypt/decrypt data
and return the result. data
must
be an integral number of blocks.
The length of data
MUST be a multiple of the block size
for all calls except the last.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
update()
, digest()
inherit BufferedCipher::State : State
int(1..)
iv_size()
Returns the size for the initialization vector
int(1..)
key_size()
Returns the key size of the encapsulated cipher.
string(8bit)
name()
Returns the string "CFB(x)"
where x is the
encapsulated algorithm.
object
Nettle.BlockCipher.CFB.State.obj
Read only
this_program
set_decrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for decrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_encrypt_key()
, set_iv()
this_program
set_encrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for encrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_decrypt_key()
, set_iv()
this_program
set_iv(string(8bit)
iv
)
Set the initialization vector to iv
. The iv
memory will be
cleared before released.
iv
must have the length reported by iv_size()
.
set_encrypt_key()
, set_decrypt_key()
.
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
Implementation of Counter Mode (CTR).
This cipher mode works like a stream cipher with a block size >= 1. This means that the same key and initialization vector (aka counter) should never be reused, since a simple xor would reveal information about the plain text. It also means that it should never be used without a suiteable Message Authentication Code (MAC).
CBC
, GCM
, Buffer
State
res = Nettle.BlockCipher()
()
Returns a new State
object.
inherit __builtin.Nettle.Cipher : Cipher
string(8bit)
name()
Returns the base cipher name appended with the string ".CTR"
.
The state for a CTR instance.
int(1..)
block_size()
Returns the block size of the encapsulated cipher.
Nettle.BlockCipher.CTR.State Nettle.BlockCipher.CTR.State()
Initialize the CTR state with the Cipher::State
object
returned by substate_factory()
. This is usually
the State for the cipher implemented in the parent module.
string(8bit)
crypt(string(8bit)
data
)
Encrypt/decrypt data
and return the result. data
must
be an integral number of blocks.
The length of data
MUST be a multiple of the block size
for all calls except the last.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
update()
, digest()
inherit Cipher::State : State
int(1..)
iv_size()
Returns the size for the initialization vector
int(1..)
key_size()
Returns the key size of the encapsulated cipher.
string(8bit)
name()
Returns the string "CTR(x)"
where x is the
encapsulated algorithm.
object
Nettle.BlockCipher.CTR.State.obj
Read only
this_program
set_decrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for decrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_encrypt_key()
, set_iv()
this_program
set_encrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for encrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_decrypt_key()
, set_iv()
this_program
set_iv(string(8bit)
iv
)
Set the initialization vector to iv
. The iv
memory will be
cleared before released.
iv
must have the length reported by iv_size()
.
set_encrypt_key()
, set_decrypt_key()
.
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
Implementation of Output Feed-Back mode (OFB).
This cipher mode works like a stream cipher with a block size >= 1. This means that the same key and initialization vector (aka counter) should never be reused, since a simple xor would reveal information about the plain text. It also means that it should never be used without a suiteable Message Authentication Code (MAC).
CFB
, CBC
, CTR
, GCM
State
res = Nettle.BlockCipher()
()
Returns a new State
object.
inherit BufferedCipher : BufferedCipher
string(8bit)
name()
Returns the base cipher name appended with the string ".OFB"
.
The state for a OFB instance.
int(1..)
block_size()
Returns the block size of the encapsulated cipher.
Nettle.BlockCipher.OFB.State Nettle.BlockCipher.OFB.State()
Initialize the OFB state with the Cipher::State
object
returned by substate_factory()
. This is usually
the State for the cipher implemented in the parent module.
string(8bit)
crypt(string(8bit)
data
)
Encrypt/decrypt data
and return the result. data
must
be an integral number of blocks.
The length of data
MUST be a multiple of the block size
for all calls except the last.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
update()
, digest()
inherit BufferedCipher::State : State
int(1..)
iv_size()
Returns the size for the initialization vector
int(1..)
key_size()
Returns the key size of the encapsulated cipher.
string(8bit)
name()
Returns the string "OFB(x)"
where x is the
encapsulated algorithm.
object
Nettle.BlockCipher.OFB.State.obj
Read only
this_program
set_decrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for decrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_encrypt_key()
, set_iv()
this_program
set_encrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for encrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_decrypt_key()
, set_iv()
this_program
set_iv(string(8bit)
iv
)
Set the initialization vector to iv
. The iv
memory will be
cleared before released.
iv
must have the length reported by iv_size()
.
set_encrypt_key()
, set_decrypt_key()
.
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
Implementation of the propagating cipher block chaining mode (PCBC).
This mode is also known as plaintext cipher block chaining (from Kerberos v4).
Works as a wrapper for the cipher implemented by overloading
the parent class (Cipher
).
CBC
, GCM
inherit _CBC : _CBC
string(8bit)
crypt(string(8bit)
data
)
Encrypt/decrypt data
and return the result. data
must
be an integral number of blocks.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
inherit _CBC::State : State
string(8bit)
name()
Returns the string "PCBC(x)"
where x is the
encapsulated algorithm.
This is the BlockCipher
class extended with algorithms
that require a block size of 16
bytes.
Cipher
, BlockCipher
, BufferedCipher
, GCM
inherit BlockCipher : BlockCipher
Implementation of the Counter with Cipher Block Chaining Message Authentication Code mode (CCM).
Works as a wrapper for the cipher implemented by overloading
the parent class (BlockCipher16
).
This is a so-called authenticated encryption with associated data (AEAD) algorithm, and in addition to encryption also provides message digests.
The operation of CCM is specified in NIST Special Publication 800-38C.
This mode of operation is not suited for streaming operation,
as the sizes of the associated data and payload data need to
be known for the CBC-MAC operation to start. Currently this
means that the associated data and payload data are buffered
until State()->digest()
is called.
CCM8
, CBC
, GCM
, CTR
int(4..16)
digest_size()
Default digest size.
Returns 16
, but overloading via inherit is supported,
and may return any even number in the range [4..16]
.
Note that the digest length is folded into the digest, so it doesn't simply imply a truncation.
inherit __builtin.Nettle.AEAD : AEAD
inherit BlockCipher::CTR : CTR
string(8bit)
name()
Returns the name of the base cipher with ".CCM"
appended.
Nettle.BlockCipher16.CCM.State Nettle.BlockCipher16.CCM.State()
string(8bit)
digest(int(4..16)
|void
bytes
)
Returns the CBC-MAC digest of the specified size.
bytes
Size in bytes for the desired digest. Any even number in
the range [4..16]
. If not specified the value from
calling digest_size()
will be used.
Note that the digest length is folded into the digest, so it doesn't simply imply a truncation.
digest_size()
, global::digest_size()
int(4..16)
digest_size()
Default digest size.
This function is used by digest()
to determine the digest
size if no argument was given.
The default implementation returns the result from calling
global::digest_size()
, but overloading via inherit is supported,
and may return any even number in the range [4..16]
.
Note that the digest length is folded into the digest, so it doesn't simply imply a truncation.
digest()
, CCM::digest_size()
inherit CTR::State : State
Special case of CCM
where the default digest size
has been truncated to 8
bytes.
CCM
, CBC
, GCM
, CTR
int(4..16)
digest_size()
Default digest size.
Returns 8
, but overloading via inherit is supported,
and may return any even number in the range [4..16]
.
inherit CCM : CCM
string(8bit)
name()
Returns the name of the base cipher with ".CCM8"
appended.
Implementation of the EAX mode.
Works as a wrapper for the cipher implemented by overloading
the parent class (BlockCipher16
).
This is a so-called authenticated encryption with associated data (AEAD) algorithm, and in addition to encryption also provides message digests.
This mode of operation was specified as a reaction to the
limitiations of the BlockCipher16.CCM
mode.
Note that this module is not available in all versions of Nettle.
CBC
, CTR
, BlockCipher16.CCM
, BlockCipher16.GCM
int(1..)
digest_size()
Default digest size.
Returns BlockCipher::block_size()
, but overloading via
inherit is supported, and may return any positive number
<= BlockCipher::block_size()
.
inherit __builtin.Nettle.AEAD : AEAD
string(8bit)
name()
Returns the name of the base cipher with ".EAX"
appended.
int(16..16)
block_size()
Returns the block size of the encapsulated cipher,
which is always 16
for EAX.
Nettle.BlockCipher16.EAX.State Nettle.BlockCipher16.EAX.State()
string(8bit)
digest(int(1..16)
|void
bytes
)
Returns the OMAC digest of the specified size.
bytes
Size in bytes for the desired digest. Any number in the
range [1..16]
. If not specified the value from
calling digest_size()
will be used.
digest_size()
, global::digest_size()
int(1..16)
digest_size()
Default digest size.
This function is used by digest()
to determine the digest
size if no argument was given.
The default implementation returns the result from calling
EAX::digest_size()
, but overloading via inherit is supported,
and may return any even number in the range [1..16]
.
digest()
, EAX::digest_size()
inherit AEAD::State : State
int(16..16)
iv_size()
Returns the recommended size for the initialization vector
(ie 16
).
Other sizes are allowed, but will be compressed or expanded to this size using the encapsulated cipher.
int(1..)
key_size()
Returns the key size of the encapsulated cipher.
string(8bit)
name()
Returns the string "x.EAX"
where x is the
encapsulated algorithm.
this_program
set_decrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for decrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_encrypt_key()
, set_iv()
this_program
set_encrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for encrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_decrypt_key()
, set_iv()
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
Implementation of the Galois Counter Mode (GCM).
Works as a wrapper for the cipher implemented by overloading
the parent class (BlockCipher16
).
This is a so-called authenticated encryption with associated data (AEAD) algorithm, which in addition to encryption also provides message digests.
The operation of GCM is specified in NIST Special Publication 800-38D.
Typically accessed as Crypto.AES.GCM
or
Crypto.Camellia.GCM
Note that this module is not available in all versions of Nettle.
CBC
int(16..16)
block_size()
Returns the block size of the encapsulated cipher,
which is always 16
for GCM.
int(16..16)
digest_size()
Returns the size of the generated digest,
which is always 16
for GCM.
inherit __builtin.Nettle.AEAD : AEAD
int(12..12)
iv_size()
Returns the recommended size for the initialization vector
(ie 12
).
Other sizes are allowed, but will be compressed or expanded to this size using the encapsulated cipher.
string(8bit)
name()
Returns the name of the base cipher with ".GCM"
appended.
The state for a GCM instance.
int(16..16)
block_size()
Returns the block size of the encapsulated cipher,
which is always 16
for GCM.
Nettle.BlockCipher16.GCM.State Nettle.BlockCipher16.GCM.State()
Initialize the GCM state with the Cipher::State
object
returned by substate_factory()
. This is usually
the State for the cipher implemented in the parent module.
string(8bit)
crypt(string(8bit)
data
)
Encrypt/decrypt data
and return the result. data
must
be an integral number of blocks.
The length of data
MUST be a multiple of the block size
(ie 16
) for all calls except the last.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
update()
, digest()
string(8bit)
digest()
Generate a message digest for the data accumulated so far.
set_iv()
needs to be called to start the next message.
update()
, digest()
int(16..16)
digest_size()
Returns the size of the generated digest,
which is always 16
for GCM.
inherit AEAD::State : State
int(12..12)
iv_size()
Returns the recommended size for the initialization vector
(ie 12
).
Other sizes are allowed, but will be compressed or expanded to this size using the encapsulated cipher.
int(1..)
key_size()
Returns the key size of the encapsulated cipher.
string(8bit)
name()
Returns the string "x.GCM"
where x is the
encapsulated algorithm.
this_program
set_decrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for decrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_encrypt_key()
, set_iv()
this_program
set_encrypt_key(string(8bit)
key
, int
|void
flags
)
Prepare the cipher and the wrapper for encrypting with the given
key
. The key
memory will be cleared before released.
Note that this operation does not by itself reset the
context sufficiently to start a new message; set_iv()
needs to be called too.
set_decrypt_key()
, set_iv()
this_program
set_iv(string(8bit)
iv
)
Set the initialization vector to iv
. The iv
memory will be
cleared before released.
Also resets all state needed to start a new message.
For iv
s of length other than 12
, an encryption or
decryption key must have been set first.
set_encrypt_key()
, set_decrypt_key()
.
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
void
update(string(8bit)
public_data
)
Add public_data
to be authenticated.
The length of public_data
MUST be a multiple of the
block size (ie 16
) for all calls except the last.
All calls of update()
need to be performed before
any calls of crypt()
.
Extends the Cipher
class with the Buffer
meta cipher. This is in turn inherited by the
BlockCipher
class, which is the base class
for all block ciphers.
inherit Cipher : Cipher
Acts as a buffer so that data can be fed to the cipher in blocks that don't correspond to cipher block sizes.
class Encrypter { protected Crypto.Cipher buffer;
void create(string key) { buffer = Crypto.AES.CBC.Buffer(); buffer->set_encrypt_key(key); }
string feed(string data) { return buffer->crypt(data); }
string drain() { return buffer->pad(Crypto.PAD_PKCS7); } }
BlockCipher.CBC
, BlockCipher16.GCM
State
res = Nettle.BufferedCipher()
()
Returns a new State
object.
inherit __builtin.Nettle.Cipher : Cipher
Acts as a buffer so that data can be fed to the cipher in blocks that don't correspond to cipher block sizes.
class Encrypter { protected Crypto.Cipher buffer;
void create(string key) { buffer = Crypto.AES.CBC.Buffer(); buffer->set_encrypt_key(key); }
string feed(string data) { return buffer->crypt(data); }
string drain() { return buffer->pad(Crypto.PAD_PKCS7); } }
BlockCipher.CBC
, BlockCipher16.GCM
int(1..)
block_size()
Get the block size of the contained block crypto.
Nettle.BufferedCipher.Buffer.State Nettle.BufferedCipher.Buffer.State()
Initialize the buffer with the Cipher::State
object
returned by substate_factory()
. This is usually
the State for the cipher implemented in the parent module.
string(8bit)
crypt(string(8bit)
data
)
Encrypt or decrypt some data.
Adds data to be en/decrypted to the buffer. If there's enough data to en/decrypt a block, that will be done, and the result returned. Any unprocessed data will be left in the buffer.
Neither the input or output data is not automatically memory
scrubbed, unless String.secure
has been called on the data.
int(0..)
iv_size()
Get the iv size of the contained block crypto.
int(1..)
key_size()
Get the key size of the contained block crypto.
string(8bit)
name()
Returns the name of the wrapped cipher with ".Buffer"
appended.
string(8bit)
pad(void
|int
method
)
Pad and encrypt any data left in the buffer. The output data is
not automatically memory scrubbed, unless String.secure
is
called on the data.
method
The type of padding to apply to the buffer.
| Pads according to ISO 10126, which means filling all extra space with random data and putting the size of the non-payload data last. |
| Pads according to RFC 5246 section 6.2.3.2, meaning that all extra space is filled with the size of the padding. Note that this size has an off by one difference to the other schemas, so 0 means 1 byte of padding. |
| |
| Pads according to ANSI X.923, which means filling all extra space with zero and putting the size of the non-payload data last. |
| Pads according to PKCS7 / RFC 3852, which means filling all extra space with the size of the extra space. |
| Fills the extra space with null bytes. To correctly remove
the padding the clear text data must not end with a null
byte. In that case the data would have to be manually
padded/unpadded before/after calling |
Defaults to Crypto.PAD_SSL for compatibility reasons.
unpad()
this_program
set_decrypt_key(string(8bit)
key
, void
|int
flags
)
Set the decryption key. The key
memory will be cleared before
released.
As a side-effect any buffered data will be cleared.
this_program
set_encrypt_key(string(8bit)
key
, void
|int
flags
)
Set the encryption key. The key
memory will be cleared before
released.
As a side-effect any buffered data will be cleared.
this_program
set_iv(string(8bit)
iv
)
Set the initialization vector to iv
.
Cipher::State
substate_factory()
Returns the Cipher::State
object that this object
is to operate on.
Defaults to creating the State for the cipher implemented in the parent module.
string(8bit)
unpad(string(8bit)
data
, void
|int
method
)
Decrypt and unpad a block of data. Neither the input or output
data is not automatically memory scrubbed, unless
String.secure
has been called on the data.
This performs the reverse operation of pad()
. The padding
will be verified to be correct, if possible. If not, zero is
returned.
method
The type of padding that was applied to the original buffer.
|
|
|
|
|
|
Defaults to Crypto.PAD_SSL for compatibility reasons.
pad()
Implementation of the CAMELLIA cipher.
inherit BlockCipher16 : BlockCipher16
State for CAMELLIA encyption.
inherit Cipher::State : State
Implementation of the CAST128 cipher.
inherit BlockCipher : BlockCipher
State for CAST128 encyption.
inherit Cipher::State : State
Implementation of the CHACHA stream cipher.
Note that this class is not available in all versions of Nettle.
inherit BlockCipher : BlockCipher
State for CHACHA encyption.
string(8bit)
crypt(string(8bit)
data
)
Encrypts or decrypts data, using the current key. Neither the
input nor output data is automatically memory scrubbed,
unless String.secure
has been called on them.
data
Usually an integral number of blocks, except for the last segement in a run. The decoder must get partial blocks at the same places as the encoder, otherwise they will get out of sync.
The encrypted or decrypted data.
inherit Cipher::State : State
object
set_iv(string(8bit)
iv
)
Set the initialization vector (aka nonce) and reset the block counter to zero.
iv
An 8-byte long string which is only to be used once for every key.
This function MUST be called in addition to
set_encrypt_key()
or set_decrypt_key()
.
The same iv
should NEVER be reused with the same key!
Implementation of the CHACHA_POLY1305 AEAD algorithm.
inherit AEAD : AEAD
State for CHACHA_POLY1305 encyption.
inherit AEAD::State : State
Represents information about a cipher algorithm, such as name, key size, and block size.
int(1..)
block_size()
The block size of the cipher (1 for stream ciphers).
inherit __builtin.Nettle.Cipher : Cipher
int(1..)
key_size()
The recommended key size for the cipher.
string(8bit)
name()
A human readable name for the algorithm.
Base class for cipher contexts.
int(1..)
block_size()
The block size for this cipher.
The default implementation just calls Cipher::block_size()
in the parent.
string(8bit)
crypt(string(8bit)
data
)
Encrypts or decrypts data, using the current key. Neither the
input nor output data is automatically memory scrubbed,
unless String.secure
has been called on them.
data
For block ciphers, data must be an integral number of blocks.
The encrypted or decrypted data.
inherit Cipher::State : State
int(1..)
key_size()
The actual key size for this cipher.
string(8bit)
make_key()
Generate a key by calling Crypto.Random.random_string
and
initialize this object for encryption with that key.
The generated key. The key memory will be cleared before released.
set_encrypt_key
string(8bit)
name()
A human readable name for the algorithm.
The default implementation just calls Cipher::name()
in the parent.
State
set_decrypt_key(string(8bit)
key
, void
|int
flags
)
Initializes the object for decryption. The key
memory will be
cleared before released.
set_encrypt_key
, crypt
State
set_encrypt_key(string(8bit)
key
, void
|int
flags
)
Initializes the object for encryption. The key
memory will be
cleared before released.
set_decrypt_key
, crypt
Implementation of the Data Encryption Standard (DES) crypto algorithm.
string(8bit)
fix_parity(string(8bit)
key
)
Sets the last bit in every byte in key
to reflect the parity.
If a seven byte key is used, it will be expanded into eight
bytes. If a key longer than eight characters is used, it will
be truncated to eight characters.
inherit BlockCipher : BlockCipher
State for DES encyption
string(8bit)
fix_parity(string(8bit)
key
)
Sets the last bit in every byte in key
to reflect the parity.
If a seven byte key is used, it will be expanded into eight
bytes. If a key longer than eight characters is used, it will
be truncated to eight characters.
inherit Cipher::State : State
Implementation of the DES3 cipher algorithm.
string(8bit)
fix_parity(string(8bit)
key
)
Sets the last bit in every byte in key
to reflect the parity.
If a 21 byte key is used, it will be expanded into 24
bytes. If a key longer than 24 characters is used, it will
be truncated to 24 characters.
inherit BlockCipher : BlockCipher
State for DES3 encyption
inherit Cipher::State : State
Diffie-Hellman Parameters.
Gmp.mpz
Nettle.DH_Params.g
Generator.
void
generate(int
p_bits
, int
q_bits
, function
(int(0..)
:string(8bit)
) rnd
)
Generate a new set of Diffie-Hellman parameters.
Throws errors for unsupported parameters.
This function is not available in all installations of Pike.
array
(Gmp.mpz
) generate_keypair(function
(int(0..)
:string(8bit)
) rnd
)
Generate a Diffie-Hellman key pair.
Returns the following array:
Array | |
| The generated public key. |
| The corresponding private key. |
Gmp.mpz
Nettle.DH_Params.p
Prime.
Gmp.mpz
Nettle.DH_Params.q
Order.
Elliptic Curve Definition
Point
res = Nettle.ECC_Curve()
* scalar
Multiply the curve by a scalar.
This can be used to get the public key from a private key.
Returns a new Point
on the curve.
Nettle.ECC_Curve Nettle.ECC_Curve(
int(0..)
family
, int(0..)
field_size
, int(0..)
revision
)
Initialize the curve.
inherit __builtin.Nettle.ECC_Curve : ECC_Curve
string(7bit)
name()
Returns the name of the curve.
Gmp.mpz
new_scalar(function
(int(0..)
:string(8bit)
) rnd
)
rnd
Randomness function to use as source.
Returns a random scalar suitable to use as an ECDSA
private key
or as an ECDH exponent.
Point
point_mul(Gmp.mpz
|int
x
, Gmp.mpz
|int
y
, Gmp.mpz
|int
scalar
)
Multiply a point on the curve by a scalar.
A typical use is for Elliptic Curve Diffie Hellman (ECDH) key exchange.
This is equivalent to (Point(x, y) * scalar)
.
Returns the new Point
on the curve.
Throws an error if the point (x
, y
) isn't on the curve.
int
size()
Returns the size in bits for a single coordinate on the curve.
Elliptic Curve Digital Signing Algorithm
void
generate_key()
Generate a new set of private and public keys on the current curve.
ECC_Curve
get_curve()
Get the elliptic curve that is in use.
Gmp.mpz
get_private_key()
Get the private key.
Gmp.mpz
get_x()
Get the x coordinate of the public key.
get_y()
Gmp.mpz
get_y()
Get the y coordinate of the public key.
get_x()
inherit __builtin.Nettle.Sign : Sign
string(7bit)
name()
Returns the string "ECDSA"
followed by
the parenthesized name of the curve.
array
(Gmp.mpz
) raw_sign(string(8bit)
digest
)
Sign the message digest digest
. Returns the signature
as two Gmp.mpz
objects.
bool
raw_verify(string(8bit)
digest
, Gmp.mpz
r
, Gmp.mpz
s
)
Verify the signature r
, s
against the message digest digest
.
void
set_private_key(Gmp.mpz
|int
k
)
Set the private key (and corresponding private key).
Throws errors if the key isn't valid for the curve.
void
set_public_key(Gmp.mpz
|int
x
, Gmp.mpz
|int
y
)
Change to the selected point on the curve as public key.
Throws errors if the point isn't on the curve.
void
set_random(function
(int(0..)
:string(8bit)
) r
)
Set the random function, used to generate keys and parameters,
to the function r
.
A point on an elliptic curve.
Point
res = Nettle.ECC_Curve.Point()
* scalar
Multiply the point on the curve by a scalar.
A typical use is for Elliptic Curve Diffie Hellman (ECDH) key exchange.
Returns the new point on the curve.
ECC_Curve
get_curve()
Get the elliptic curve that is in use.
Gmp.mpz
get_x()
Get the x coordinate of the point.
get_y()
Gmp.mpz
get_y()
Get the y coordinate of the point.
get_x()
inherit ECC_Curve::Point : Point
string(7bit)
name()
Returns the string "Point"
followed by
the parenthesized name of the curve.
void
set(Gmp.mpz
|int
x
, Gmp.mpz
|int
y
)
Change to the selected point on the curve.
Throws errors if the point isn't on the curve.
Implements the Fortuna PRNG generator, designed by Niels Ferguson and Bruce Schneier and described in Practical Cryptography. Web published exerpt at https://www.schneier.com:443/fortuna.pdf
This implementation uses AES256 to generate output and SHA256 to generate keys.
To use this class an entropy accumulator needs to be implemented
and supply the reseed()
method with new entopy.
string(8bit)
random_string(int(0..)
len
)
Generates len
amount of pseudo random data. In contrast with
the Fortuna PseudoRandomData function, which only allows 2^20
bytes of random data per call, the necessary rekey operations
are here performed internally, so no such restrictions apply.
void
reseed(string(8bit)
data
)
Generates new a new key based on the provided additional entropy.
Implementation of the GOST94 hash algorithm.
inherit Hash : Hash
State for GOST94 hashing.
inherit Hash::State : State
Represents information about a hash algorithm, such as name, digest size, and internal block size.
int(0..)
block_size()
Returns the internal block size of the hash algorithm.
string(7bit)
crypt_hash(string(8bit)
password
, string(8bit)
salt
, int
rounds
)
Password hashing function in crypt_md5()
-style.
Implements the algorithm described in http://www.akkadia.org/drepper/SHA-crypt.txt.
This is the algorithm used by crypt(2) in methods $5$ (SHA256) and $6$ (SHA512).
The password
memory will be cleared before released.
crypt_md5()
int(0..)
digest_size()
Returns the size of a hash digest.
string(8bit)
hash(string(8bit)
data
)
Works as a (faster) shortcut for
State()->update(data)->digest()
, where State is
the hash state class corresponding to this Hash.
State()->update()
and State()->digest()
.
string(8bit)
hash(Stdio.File
file
, void
|int
bytes
)
Works as a (faster) shortcut for
State()->update(Stdio.read_file(file))->digest()
,
where State is the hash state class corresponding to this
Hash.
bytes
The number of bytes of the file object file
that should be
hashed. Negative numbers are ignored and the whole file is
hashed.
Stdio.File
, State()->update()
and
State()->digest()
.
inherit __builtin.Nettle.Hash : Hash
string(8bit)
name()
Returns a human readable name for the algorithm.
Base class for hashing contexts.
string(8bit)
digest(int
|void
length
)
Generates a digest, and resets the hashing contents.
length
If the length argument is provided, the digest is truncated to the given length.
The digest.
inherit Hash::State : State
State
update(string(8bit)
data
)
Hashes more data.
Returns this
in order to simplify chaining
of function calls.
Implementation of the IDEA cipher.
inherit BlockCipher : BlockCipher
State for IDEA encyption.
inherit Cipher::State : State
Represents information about a MAC algorithm, such as name, key size, digest size, and internal block size.
int(0..)
block_size()
Returns the internal block size of the MAC algorithm.
int(0..)
digest_size()
Returns the size of a MAC digest.
inherit __builtin.Nettle.MAC : MAC
int(0..)
iv_size()
Returns the size of the iv/nonce of the MAC algorithm (if any).
Returns 0
(zero) if there is no configurable iv/nonce.
int(0..)
key_size()
Returns the recommended size for the secret key for the MAC algorithm.
string(8bit)
name()
Returns a human readable name for the algorithm.
Base class for MAC contexts.
string(8bit)
res = Nettle.MAC.State()
()
Acts as the combination of update()
followed by digest()
.
Also updates the iv/nonce (if any).
Nettle.MAC.State Nettle.MAC.State(
string(8bit)
key
)
Initialize the MAC with a password.
It also resets any iv/nonce to it's default.
string(8bit)
digest(int
|void
length
)
Generates a digest, and resets the MAC contents.
Also updates the iv/nonce (if any).
length
If the length argument is provided, the digest is truncated to the given length.
The digest.
inherit MAC::State : State
State
set_iv(string(8bit)
iv
)
Set the iv/nonce (if supported) for the MAC.
Returns this
in order to simplify chaining
of function calls.
State
update(string(8bit)
data
)
Hashes more data.
Returns this
in order to simplify chaining
of function calls.
Implementation of the MD2 hash algorithm.
inherit Hash : Hash
State for MD2 hashing.
inherit Hash::State : State
Implementation of the MD4 hash algorithm.
inherit Hash : Hash
State for MD4 hashing.
inherit Hash::State : State
Implementation of the MD5 hash algorithm.
inherit Hash : Hash
State for MD5 hashing.
inherit Hash::State : State
Implementation of the POLY1305_AES MAC algorithm.
inherit MAC : MAC
State for POLY1305_AES macing.
inherit MAC::State : State
Implementation of the RIPEMD160 hash algorithm.
inherit Hash : Hash
State for RIPEMD160 hashing.
inherit Hash::State : State
Implementation of the SALSA20 cipher.
inherit BlockCipher : BlockCipher
State for SALSA20 encyption.
inherit Cipher::State : State
object
set_iv(string(8bit)
iv
)
Set the initialization vector (aka nonce) and reset the block counter to zero.
iv
An 8-byte long string which is only to be used once for every key.
This function MUST be called in addition to
set_encrypt_key()
or set_decrypt_key()
.
The same iv
should NEVER be reused with the same key!
Implementation of the SALSA20
cipher reduced to 12 rounds.
inherit SALSA20 : SALSA20
Implementation of the SERPENT cipher.
inherit BlockCipher16 : BlockCipher16
State for SERPENT encyption.
inherit Cipher::State : State
Implementation of the SHA1 hash algorithm.
inherit Hash : Hash
State for SHA1 hashing.
inherit Hash::State : State
Implementation of the SHA224 hash algorithm.
inherit Hash : Hash
State for SHA224 hashing.
inherit Hash::State : State
Implementation of the SHA256 hash algorithm.
inherit Hash : Hash
State for SHA256 hashing.
inherit Hash::State : State
Implementation of the SHA384 hash algorithm.
inherit Hash : Hash
State for SHA384 hashing.
inherit Hash::State : State
Implementation of the SHA3_224 hash algorithm.
inherit Hash : Hash
State for SHA3_224 hashing.
inherit Hash::State : State
Implementation of the SHA3_256 hash algorithm.
inherit Hash : Hash
State for SHA3_256 hashing.
inherit Hash::State : State
Implementation of the SHA3_384 hash algorithm.
inherit Hash : Hash
State for SHA3_384 hashing.
inherit Hash::State : State
Implementation of the SHA3_512 hash algorithm.
inherit Hash : Hash
State for SHA3_512 hashing.
inherit Hash::State : State
Implementation of the SHA512 hash algorithm.
inherit Hash : Hash
State for SHA512 hashing.
inherit Hash::State : State
Implementation of the Twofish cipher.
inherit BlockCipher16 : BlockCipher16
State for Twofish encyption.
inherit Cipher::State : State
Implementation of the UMAC128_AES MAC algorithm.
inherit MAC : MAC
State for UMAC128_AES macing.
inherit MAC::State : State
Implementation of the UMAC32_AES MAC algorithm.
inherit MAC : MAC
State for UMAC32_AES macing.
inherit MAC::State : State
Implementation of the UMAC64_AES MAC algorithm.
inherit MAC : MAC
State for UMAC64_AES macing.
inherit MAC::State : State
Implementation of the UMAC96_AES MAC algorithm.
inherit MAC : MAC
State for UMAC96_AES macing.
inherit MAC::State : State
Yarrow is a family of pseudo-randomness generators, designed for cryptographic use, by John Kelsey, Bruce Schneier and Niels Ferguson. Yarrow-160 is described in a paper at http://www.schneier.com/paper-yarrow.html, and it uses SHA1 and triple-DES, and has a 160-bit internal state. Nettle implements Yarrow-256, which is similar, but uses SHA256 and AES to get an internal state of 256 bits.
Nettle.Yarrow Nettle.Yarrow(
void
|int
sources
)
The number of entropy sources that will feed entropy to the random number generator is given as an argument to Yarrow during instantiation.
update
void
force_reseed()
By calling this function entropy is moved from the slow pool to the fast pool. Read more about Yarrow before using this.
string(8bit)
get_seed()
Returns part of the internal state so that it can be saved for
later seeding. This method is deprecated. Instead read the
min_seed_size
number of bytes from the random_string
method.
seed()
, random_string()
bool
is_seeded()
Returns 1 if the random generator is seeded and ready to generator output. 0 otherwise.
seed
int(0..)
min_seed_size()
Returns the minimal number of characters that the seed
needs to properly seed the random number generator.
seed
int(0..)
needed_sources()
The number of sources that must reach the threshold before a slow reseed will happen.
string(8bit)
random_string(int
length
)
Returns a pseudo-random string of the requested length
.
Yarrow
seed(string(8bit)
data
)
The random generator needs to be seeded before it can be used.
The seed must be at least 32 characters long. The seed could be
stored from a previous run by inserting the value returned from
previous random_string
call.
Returns the called object.
min_seed_size
, is_seeded
bool
update(string(8bit)
data
, int
source
, int
entropy
)
Inject additional entropy into the random number generator.
create
constant
Object.DESTRUCT_EXPLICIT
constant
Object.DESTRUCT_NO_REFS
constant
Object.DESTRUCT_GC
constant
Object.DESTRUCT_CLEANUP
Flags passed to lfun::destroy
.
Object.DESTRUCT_EXPLICIT
is 0
and
Object.DESTRUCT_CLEANUP
is 1
for compatibility.
object
secure(object
str
)
Marks the object as secure, which will clear the memory area before freeing the object.
String.secure()
Low-level interface to Open DataBase Connectivity SQL-drivers.
You typically don't want to access this module directly, but
instead use Sql.Sql()
with an "odbc://"
or
"dsn://"
URL.
Sql.Sql()
bool
connect_lock(void
|int
enable
)
Enable or disable a mutex that serializes all ODBC SQLConnect calls (i.e. when ODBC connections are created). This lock might be necessary to work around bugs in ODBC drivers.
enable
Enables the mutex if nonzero, disables it otherwise. The state is not changed if this argument is left out.
The old state of the flag.
This is currently enabled by default due to bugs in the current FreeTDS library (version 0.63), but that might change if the demand for this kludge ceases in the future. Therefore, if this setting is important to you then always set it explicitly. Hopefully most users don't need to bother with it.
array
(string
) list_dbs()
List the configured ODBC database sources.
Low-level connection to an ODBC or DSN database.
You typically don't want to access this module directly, but
instead use the Sql.odbc
or Sql.dsn
created by Sql.Sql()
.
Sql.odbc
, Sql.dsn
constant
PDF.a0_width
constant
PDF.a0_height
constant
PDF.a1_width
constant
PDF.a1_height
constant
PDF.a2_width
constant
PDF.a2_height
constant
PDF.a3_width
constant
PDF.a3_height
constant
PDF.a4_width
constant
PDF.a4_height
constant
PDF.a5_width
constant
PDF.a5_height
constant
PDF.a6_width
constant
PDF.a6_height
constant
PDF.b5_width
constant
PDF.b5_height
constant
PDF.letter_width
constant
PDF.letter_height
constant
PDF.legal_width
constant
PDF.legal_height
constant
PDF.ledger_width
constant
PDF.ledger_height
constant
PDF.p11x17_width
constant
PDF.p11x17_height
Interface to the pdflib pdf generator. For more information see http://www.pdflib.com
int
add_bookmark(string
text
, int
parent
, int
open
)
object
add_launchlink(float
llx
, float
lly
, float
urx
, float
ury
, string
filename
)
object
add_locallink(float
llx
, float
lly
, float
urx
, float
ury
, int
page
, string
dest
)
object
add_pdflink(float
llx
, float
lly
, float
urx
, float
ury
, string
filename
, int
page
, string
dest
)
object
add_weblink(float
llx
, float
lly
, float
urx
, float
ury
, string
url
)
object
arc(float
x
, float
y
, float
r
, float
start
, float
end
)
object
attach_file(float
llx
, float
lly
, float
urx
, float
ury
, string
filename
, string
description
, string
author
, string
mimetype
, string
icon
)
PDF
begin_page()
PDF
begin_page(float
width
, float
height
)
note: Defaults to a4, portrait
object
circle(float
x
, float
y
, float
r
)
PDF
close()
object
close_image(int
image
)
object
concat(float
a
, float
b
, float
c
, float
d
, float
e
, float
f
)
PDF
continue_text(string
s
)
PDF.PDFgen PDF.PDFgen()
object
curveto(float
x1
, float
y1
, float
x2
, float
y2
, float
x3
, float
y3
)
PDF
end_page()
int
findfont(string
fontname
)
int
findfont(string
fontname
, void
|string
encoding
, void
|int
embed
)
string
get_parameter(string
key
)
string
get_parameter(string
key
, float
modifier
)
float
get_value(string
key
)
float
get_value(string
key
, float
modifier
)
object
lineto(float
x
, float
y
)
object
moveto(float
x
, float
y
)
int
open_CCITT(string
filename
, int
width
, int
height
, int
BitReverse
, int
K
, int
BlackIs1
)
int
open_file(string
filename
)
int
open_image(string
type
, string
source
, string
data
, int
width
, int
height
, int
components
, int
bpc
, string
params
)
int
open_image_file(string
type
, string
filename
)
int
open_image_file(string
type
, string
filename
, void
|string
stringparam
, void
|int
intparam
)
object
place_image(int
image
, float
x
, float
y
, float
scale
)
object
rect(float
x
, float
y
, float
width
, float
height
)
object
rotate(float
phi
)
object
scale(float
sx
, float
sy
)
object
set_border_color(float
red
, float
green
, float
blue
)
object
set_border_dash(float
b
, float
w
)
object
set_border_style(string
style
, float
width
)
float
set_info(string
key
, string
info
)
float
set_parameter(string
key
, string
parameter
)
object
set_text_pos(float
x
, float
y
)
float
set_value(string
key
, float
value
)
object
setdash(float
b
, float
w
)
object
setflat(float
flatness
)
PDF
setfont(int
n
, float
size
)
object
setgray(float
gray
)
object
setgray_fill(float
gray
)
object
setgray_stroke(float
gray
)
object
setlinecap(int
linecap
)
object
setlinejoin(int
linejoin
)
object
setlinewidth(float
width
)
object
setmiterlimit(float
miter
)
object
setrgbcolor(float
red
, float
green
, float
blue
)
object
setrgbcolor_fill(float
red
, float
green
, float
blue
)
object
setrgbcolor_stroke(float
red
, float
green
, float
blue
)
PDF
show(string
s
)
int
show_boxed(string
text
, float
x
, float
y
, float
width
, float
height
, string
mode
)
int
show_boxed(string
text
, float
x
, float
y
, float
width
, float
height
, string
mode
, string
feature
)
PDF
showxy(string
s
, float
x
, float
y
)
object
skew(float
alpha
, float
beta
)
float
stringwidth(string
text
, int
font
, float
size
)
object
translate(float
tx
, float
ty
)
constant
Pike.Backend
The class of the DefaultBackend
.
Typically something that has inherited __Backend
.
__Backend
, DefaultBackend
constant
Pike.INDEX_FROM_BEG
constant
Pike.INDEX_FROM_END
constant
Pike.OPEN_BOUND
Used with predef::`[..]
and lfun::`[..]
to specify how the
corresponding index maps to an upper or lower range bound:
The index is relative to the beginning of the string or array (or any other sequence implemented through an object). Sequences typically start at zero.
The index is relative to the end of the sequence. In strings and arrays, the last element is at zero, the one before that at one, etc.
The range is open in the corresponding direction. The index is irrelevant in this case.
program
Pike.SmallBackend
This is the most suitable backend implementation if you only want
to monitor a small number of Stdio.File
objects.
constant
Pike.WEAK_INDICES
constant
Pike.WEAK_VALUES
constant
Pike.WEAK
Flags for use together with set_weak_flag
and get_weak_flag
.
See set_weak_flag
for details.
constant
Pike.__HAVE_CPP_PREFIX_SUPPORT__
This constant exists and has the value 1 if cpp supports the prefix feature.
cpp()
int
count_memory(int
|mapping
(string
:int
) options
, array
|multiset
|mapping
|object
|program
|string
|type
|int
... things
)
In brief, if you call Pike.count_memory(0,x)
you get back
the number of bytes x
occupies in memory.
The detailed story is a bit longer:
This function calculates the number of bytes that all things
occupy. Or put another way, it calculates the number of bytes that
would be freed if all those things would lose their references at
the same time, i.e. not only the memory in the things themselves,
but also in all the things that are directly and indirectly
referenced from those things and not from anywhere else.
The memory counted is only that which is directly occupied by the things in question, including any overallocation for mappings, multisets and arrays. Other memory overhead that they give rise to is not counted. This means that if you would count the memory occupied by all the pike accessible things you would get a figure significantly lower than what the OS gives for the pike process.
Also, if you were to actually free the things, you should not expect the size of the pike process to drop the amount of bytes returned by this function. That since Pike often retains the memory to be reused later.
However, what you should expect is that if you actually free the things and then later allocates some more things for which this function returns the same size, there should be essentially no increase in the size of the pike process (some increase might occur due to internal fragmentation and memory pooling, but it should be small in general and over time).
The search for things only referenced from things
can handle
limited cyclic structures. That is done by doing a "lookahead",
i.e. searching through referenced things that apparently have
other outside references. You can control how long this lookahead
should be through options
(see below). If the lookahead is too
short to cover the cycles in a structure then a too low value is
returned. If the lookahead is made gradually longer then the
returned value will eventually become accurate and not increase
anymore. If the lookahead is too long then unnecessary time might
be spent searching through things that really have external
references.
Objects that are known to be part of cyclic structures are
encouraged to have an integer constant or variable
pike_cycle_depth
that specifies the lookahead needed to
discover those cycles. When Pike.count_memory
visits such
objects, it uses that as the lookahead when going through the
references emanating from them. Thus, assuming objects adhere to
this convention, you should rarely have to specify a lookahead
higher than zero to this function.
Note that pike_cycle_depth
can also be set to zero to
effectively stop the lookahead from continuing through the object.
That can be useful to put in objects you know have global
references, to speed up the traversal.
options
If this is an integer, it specifies the maximum lookahead
distance. -1 counts only the memory of the given things
,
without following any references. 0 extends the count to all
their referenced things as long as there are no cycles (except
if pike_cycle_depth
is found in objects - see above). 1
makes it cover cycles of length 1 (e.g. a thing points to
itself), 2 handles cycles of length 2 (e.g. where two things
point at each other), and so on.
However, the lookahead is by default blocked by programs, i.e. it never follows references emanating from programs. That since programs seldom are part of dynamic data structures, and they also typically contain numerous references to global data which would add a lot of work to the lookahead search.
To control the search in more detail, options
can be a
mapping instead:
| The maximum lookahead distance, as described above. Defaults to 0 if missing. |
| When any of these are given with a nonzero value, the corresponding type is blocked when lookahead references are followed. They are unblocked if the flag is given with a zero value. Only programs are blocked by default. These blocks are only active during the lookahead, so blocked things are still recursed and memory counted if they are given as arguments or only got internal references. |
| |
| |
| |
| |
| If positive then strings are always excluded (except any
given directly in |
| Do not heed |
| Return the number of things that memory was counted for,
instead of the byte count. (This is the same number
|
| If this is nonzero then its value is replaced with an array that contains the things that memory was counted for. |
| If set then the value is replaced with an array containing the things that were visited but turned out to have external references (within the limited lookahead). |
| If set then the value is replaced with an array containing
the things found during the lookahead that (appears to) have
direct external references. This list is a subset of the
|
| If this is nonzero then the mapping is extended with more elements containing statistics from the search; see below. |
When the collect_stats
flag is set, the mapping is
extended with these elements:
| Number of things that were marked internal and hence memory counted. It includes the things given as arguments. |
| Number of things that were marked internal only after resolving cycles. |
| Number of things that were visited through the lookahead but were found to be external. |
| Number of times things were visited in total. This figure includes visits to various internal things that aren't visible from the pike level, so it might be larger than what is apparently motivated by the numbers above. |
| Number of times the same things were revisited. This can
occur in the lookahead when a thing is encountered through a
shorter path than the one it first got visited through. It
also occurs in resolved cycles. Like |
| Number of search rounds. This is usually 1 or 2. More rounds are necessary only when blocked types turn out to be (acyclic) internal, so that they need to be counted and recursed anyway. |
| The number of elements that were allocated to store the work queue which is used to keep track of the things to visit during the lookahead. This is usually bigger than the maximum number of things the queue actually held. |
| The memory occupied by the internal things. This is the same as the normal return value, but it's put here too for convenience. |
things
One or more things to count memory size for. Only things passed by reference are allowed, except for functions which are forbidden because a meaningful size calculation can't be done for them.
Integers are allowed because they are bignum objects when they become sufficiently large. However, passing an integer that is small enough to fit into the native integer type will return zero.
Returns the number of bytes occupied by the counted things. If
the return_count
option is set then the number of things
are returned instead.
The result of Pike.count_memory(0,a,b)
might be larger
than the sum of Pike.count_memory(0,a)
and
Pike.count_memory(0,b)
since a
and b
together might reference things that aren't referenced from
anywhere else.
It's possible that a string that is referenced still isn't counted, because strings are always shared in Pike and the same string may be in use in some unrelated part of the program.
mapping
(string
:float
) gc_parameters(void
|mapping
(string
:mixed
) params
)
Set and get various parameters that control the operation of the garbage collector. The passed mapping contains the parameters to set. If a parameter is missing from the mapping, the current value will be filled in instead. The same mapping is returned. Thus an empty mapping, or no argument at all, causes a mapping with all current settings to be returned.
The following parameters are recognized:
| If this is 1 then the gc is enabled as usual. If it's 0 then all
automatically scheduled gc runs are disabled and the parameters
below have no effect, but explicit runs through the | ||||
| As long as the gc time is less than time_ratio below, aim to run the gc approximately every time the ratio between the garbage and the total amount of allocated things is this. | ||||
| When more than this fraction of the time is spent in the gc, aim for garbage_ratio_high instead of garbage_ratio_low. | ||||
| Upper limit for the garbage ratio - run the gc as often as it takes to keep it below this. | ||||
| This puts an upper limit on the gc interval, in addition to the factors above. It is specified as the minimum amount of time spent doing gc, as a factor of the total time. The reason for this limit is that the current amount of garbage can only be measured in a gc run, and if the gc starts to run very seldom due to very little garbage, it might get too slow to react to an increase in garbage generation. Set to 0.0 to turn this limit off. | ||||
| When predicting the next gc interval, use a decaying average with this slowness factor. It should be a value between 0.0 and 1.0 that specifies the weight to give to the old average value. The remaining weight up to 1.0 is given to the last reading. | ||||
| This function is called when the gc starts. | ||||
| This function is called when the mark and sweep pass of the gc is done. | ||||
| This function is called once for each object that is part of a cycle just before the gc will destruct it. The arguments are:
| ||||
| This function is called when the gc is done and about to exit. The argument is the same value as will be returned by gc(). |
gc
, Debug.gc_status
type
get_first_arg_type(type
fun_type
)
Check if a function of the type fun_type
may be called
with an argument, and return the type of that argument.
Returns the expected type of the first argument to the function.
Returns 0 (zero) if a function of the type fun_type
may not be called with any argument, or if it is not callable.
type
get_return_type(type
fun_type
)
Check what a function of the type fun_type
will
return if called with no arguments.
Returns the type of the returned value on success
Returns 0 (zero) on failure.
mapping
(string
:int
|string
) get_runtime_info()
Get information about the Pike runtime.
Returns a mapping with the following content:
| A string describing the bytecode method used by the Pike interpreter. |
| The number of bits in the ABI. Usually |
| The byte order used by the native cpu.
Usually |
| The number of bits in the native integer type.
Usually |
| The number of bits in the native floating point type.
Usually |
| Present if integers larger than the native size are automatically converted into bignums. |
array
(string
) get_type_attributes(type
t
)
Get the attribute markers for a type.
Returns an array with the attributes for the type t
.
get_return_type()
, get_first_arg_type()
array
(mixed
) identify_cycle(mixed
x
)
Identify reference cycles in Pike datastructures.
This function is typically used to identify why certain
datastructures need the gc
to run to be freed.
x
Value that is believed to be involved in a reference cycle.
| Returns |
| Otherwise returns an array identifying a cycle with |
int
implicit_gc_real_time(void
|int
nsec
)
Returns the total amount of real time that has been spent in
implicit GC runs. The time is normally returned in microseconds,
but if the optional argument nsec
is nonzero it's returned in
nanoseconds.
Debug.gc_status
type
low_check_call(type
fun_type
, type
arg_type
)
type
low_check_call(type
fun_type
, type
arg_type
, int
flags
)
Check whether a function of type fun_type
may be called
with a first argument of type arg_type
.
flags
The following flags are currently defined:
| Strict types. Fail if not all possible values in |
| Last argument. |
| Both strict types and last argument as above. |
Returns a continuation type on success.
Returns 0 (zero) on failure.
type
soft_cast(type
to
, type
from
)
Return the resulting type from a soft cast of from
to to
.
bool
res = is_type(Pike.BacktraceFrame()
)
This object claims to be an array for backward compatibility.
int(3..)
sizeof( Pike.BacktraceFrame arg )
string sprintf(string format, ... Pike.BacktraceFrame arg ... )
mixed
res = Pike.BacktraceFrame()
[ index
]
The BacktraceFrame object can be indexed as an array.
Pike.BacktraceFrame()
[ index
] = value
An empty class that can be inherited to get the PROGRAM_DESTRUCT_IMMEDIATE flag set.
Used as a place holder in eg backtraces for objects that are unsuitable to have references to in backtraces.
Examples of such objects are instances of Thread.MutexKey
,
and Nettle.Cipher.State
.
backtrace()
This is a bare-bones codec that is used when loading a dumped master.
Codec
object
decode_object(object
obj
, mixed
data
)
Calls obj->_decode(
.data
)
mixed
functionof(mixed
symbol
)
Look up a function in all_constants()
.
mixed
objectof(mixed
symbol
)
Look up an object in all_constants()
.
mixed
programof(mixed
symbol
)
Look up a program in all_constants()
.
Backend
implemented with poll(2) (SVr4, POSIX).
Backend
float
|int(0..0)
res = Pike.PollBackend()
()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_time
Wait at most sleep_time
seconds. The default when
unspecified or the integer 0
is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0
is returned.
Pike.DefaultBackend
, main()
inherit __Backend : __Backend
Backend
implemented with /dev/poll (Solaris, OSF/1 and IRIX),
epoll(2) (Linux) or kqueue(2) (MacOS X, FreeBSD, OpenBSD, etc).
Backend
float
|int(0..0)
res = Pike.PollDeviceBackend()
()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_time
Wait at most sleep_time
seconds. The default when
unspecified or the integer 0
is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0
is returned.
Pike.DefaultBackend
, main()
int
enable_core_foundation(bool
enable
)
On systems with CoreFoundation (OSX, iOS, etc), use CoreFoundation to poll for events. This enables system level technologies that rely on CoreFoundation Runloops to function properly.
enable
enable or disable this functionality
the previous value of this setting.
int
enable_external_runloop(bool
enable
)
On systems with CoreFoundation (OSX, iOS, etc), delegate running of the Pike Backend to the main runloop of the process (such as a Cocoa application's NSRunLoop).
Enabling the external runloop allows Pike callouts and callback-based I/O to function normally while greatly reducing cpu utilization compared to running the external runloop manually.
enable
enable or disable this functionality
the previous value of this setting.
inherit __Backend : __Backend
int
query_core_foundation_enabled()
On systems with CoreFoundation (OSX, iOS, etc), indicate whether CoreFoundation is being used by this backend to poll for events.
the current state of CoreFoundation polling: 1=enabled, 0=disabled
optional
void
set_signal_event_callback(int
signum
, function
(:void
) cb
)
Request cb
to be called from the backend when the signal
signum
is received.
This function is a noop except for the kqueue case.
Caveat emptor: Unlikely to work.
signal()
Backend based on the classic select(2) system call from BSD.
float
|int(0..0)
res = Pike.SelectBackend()
()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_time
Wait at most sleep_time
seconds. The default when
unspecified or the integer 0
is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0
is returned.
Pike.DefaultBackend
, main()
inherit __Backend : __Backend
A Watchdog that ensures that the process is not hung for an extended period of time. The definition of 'hung' is: Has not used the default backend.
An important and useful side-effect of this class is that the process will start to respond to kill -QUIT by printing a lot of debug information to stderr, including memory usage, and if pike is compiled with profiling, the CPU used since the last time kill -QUIT was called.
void
add_debug(function
(void
:void
) f
)
The function f
will be called if the watchdog triggers, before
the normal watchdog output is written.
void
add_probe(function
(void
:bool
) f
)
Add additional functions to be called each time the watchdog is checked. If any of the probes return false, the watchdog will trigger.
void
alarm_alarm_alarm()
Explicitly trigger the watchdog, if enough CPU time has been used. This is not normally called manually.
Pike.Watchdog Pike.Watchdog(
int
t
)
Create a new watchdog, with the intended delay.
Even though the actual watchdog functionality is currently not available on systems without sigalarm, such as Windows, the functionality can still be triggered by adding probe functions
add_probe()
and set_delay()
void
ping()
Tell the watchdog that all is well, and the CPU is not really blocked. Can be used during long calculations that block the normal backend, note that this basically bypasses the main functionality of the watchdog, that is, detecting blocked backend threads.
void
print_debug()
Output thread stacktraces, memory and profiling (if available) debug information to stderr.
void
really_trigger_watchdog_promise()
Really trigger the watchdog, killing the current process. This is not normally called manually.
void
set_delay(int
t
)
Set the watchdog interval to t
seconds.
The change will not take effect until the previous probe has been triggered.
Base class for the various backend implementations.
Implements callback registration functions and defines the main backend APIs.
int
_do_call_outs()
Do all pending call_outs.
This function runs all pending call_outs that should have been run if Pike returned to the backend. It should not be used in normal operation.
As a side-effect, this function sets the value returned by
time(1)
to the current time.
Zero if no call outs were called, nonzero otherwise.
call_out()
, find_call_out()
, remove_call_out()
float
|int(0..0)
res = Pike.__Backend()
()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_time
Wait at most sleep_time
seconds. The default when
unspecified or the integer 0
is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0
is returned.
If multiple threads concurrently call this function, then:
One of the threads will be the controlling thread.
All callbacks will be called from the controlling thread.
All threads will be woken up when the controlling thread is done. This may be prematurely if the controlling thread had a shorter timeout.
The backend may also be woken up prematurely if the set of events to monitor is changed.
Multiple concurrent calls was not supported prior to Pike 8.0.
Pike.DefaultBackend
, main()
void
add_file(Stdio.File
|Stdio.FILE
f
)
Register a file to be handled by this backend.
f
File to register.
Registers f
to be handled by this backend.
This simply does f->set_backend(backend)
where
backend
is this object.
Pike.DefaultBackend
, main()
function
(Backend
:void
) Pike.__Backend.before_callback
function
(Backend
:void
) Pike.__Backend.after_callback
If set, these are called just before and after the backend waits for an event.
If an error is thrown from these callbacks then it is reported
using master()->handle_error()
- it doesn't interrupt
the operation of the backend.
array
call_out(function
(:void
) f
, float
|int
delay
, mixed
... args
)
Make a delayed call to a function.
call_out()
places a call to the function f
with the argument
args
in a queue to be called in about delay
seconds.
If f
returns -1
, no other call out or callback will be
called by the backend in this round. I.e. `()
will return right
away. For the main backend that means it will immediately start
another round and check files and call outs anew.
Returns a call_out identifier that identifies this call_out.
This value can be sent to eg find_call_out()
or remove_call_out()
.
remove_call_out()
, find_call_out()
, call_out_info()
,
CallOut
array
(array
) call_out_info()
Get info about all call_outs.
This function returns an array with one entry for each entry in the call out queue. The first in the queue will be at index 0. Each index contains an array that looks like this:
Array | |
| Time remaining in seconds until the call_out is to be performed. |
| Used to be the object that scheduled the call_out. |
| Function to be called. |
| Arguments to the function. |
call_out()
, find_call_out()
, remove_call_out()
Pike.__Backend Pike.__Backend()
Thread.Thread
executing_thread()
int
executing_thread()
Return the thread currently executing in the backend. I.e. the
thread that has called `()
and hasn't exited from that call.
Zero is returned if there's no thread in the backend.
If Pike is compiled without thread support then 1
is
returned if we're inside the backend, 0
otherwise.
int
find_call_out(function
(:void
) f
)
int
find_call_out(array
id
)
Find a call out in the queue.
This function searches the call out queue. If given a function as argument, it looks for the first call out scheduled to that function.
The argument can also be a call out id as returned by call_out()
, in
which case that call_out will be found (Unless it has already been
called).
find_call_out()
returns the remaining time in seconds before that
call_out will be executed. If no call_out is found,
zero_type
(find_call_out
(f)) will return 1.
call_out()
, remove_call_out()
, call_out_info()
mapping
(string
:int
) get_stats()
Get some statistics about the backend.
Returns a mapping with the follwoing content:
| The number of active call-outs. |
| The amount of memory used by the call-outs. |
int
id()
Return an integer that uniquely identifies this backend. For
the default backend that integer is 0
.
int
remove_call_out(function
(:void
) f
)
int
remove_call_out(array
id
)
Remove a call out from the call out queue.
This function finds the first call to the function f
in the call_out
queue and removes it. You can also give a call out id as argument (as
returned by call_out()
).
The remaining time in seconds left to that call out will be returned.
If no call_out was found, zero_type
(remove_call_out
(f
))
will return 1.
call_out_info()
, call_out()
, find_call_out()
Represents a single call_out in the call_out list.
call_out()
protected
array
Pike.__Backend.CallOut.args
The array containing the function and arguments.
Pike.__Backend.CallOut Pike.__Backend.CallOut(
int
|float
seconds
, mixed
fun
, mixed
... args
)
Start a new call out.
This is the low-level implementation of call_out()
.
call_out()
is essentially implemented as:
array call_out(mixed fun, int|float seconds, mixed ... args)
{
return CallOut(seconds, fun, @args)->args;
}
call_out()
This is the Backend
object that files and call_outs are
handled by by default.
This is also the Backend
object that will be used if main()
returns -1
.
Backend
, Stdio.File()->set_nonblocking()
, call_out()
Pike has an optional internal security system, which can be enabled with the configure-option --with-security.
The security system is based on attaching credential objects
(Pike.Security.Creds
) to objects, programs, arrays,
mappings or multisets.
A credential object in essence holds three values:
user -- The owner.
allow_bits -- Run-time access permissions.
data_bits -- Data access permissions.
constant
Pike.Security.BIT_CALL
Allow calling of functions.
constant
Pike.Security.BIT_CONDITIONAL_IO
Allow conditional useage of I/O. The callbacks valid_open
and valid_io
will be called in the User
object in the
current Creds
object to determine if the I/O is allowed or not.
constant
Pike.Security.BIT_DESTRUCT
Allow use of destruct
.
constant
Pike.Security.BIT_INDEX
Allow indexing.
constant
Pike.Security.BIT_NOT_SETUID
Don't change active credentials on function call.
constant
Pike.Security.BIT_SECURITY
Allow usage of security related functions.
constant
Pike.Security.BIT_SET_INDEX
Allow setting of indices.
mixed
call_with_creds(Creds
creds
, mixed
func
, mixed
... args
)
Call with credentials.
Sets the current credentials to creds
, and calls
. If func
(@args
)creds
is 0
(zero), the
credentials from the current object will be used.
The current creds or the current object must have the allow bit
BIT_SECURITY
set to allow calling with creds
other than
0
(zero).
Creds
get_current_creds()
Get the current credentials
Returns the credentials that are currently active.
Returns 0
(zero) if no credentials are active.
call_with_creds()
Creds
get_object_creds(object
|program
|function
(:void
)|array
|mapping
|multiset
o
)
Get the credentials from o
.
Returns 0
if o
does not have any credentials.
The credentials object.
void
apply(object
|program
|function
(:void
)|array
|mapping
|multiset
o
)
Set the credentials for o
to this credentials object.
To perform this operation the current credentials needs to have the bit
BIT_SECURITY
set, or have the same user as the old credentials
and not change the user by performing the operation.
Pike.Security.Creds Pike.Security.Creds(
User
user
, int
allow_bits
, int
data_bits
)
Initialize a new credentials object.
allow_bits
Any of the flags BIT_SECURITY
and BIT_CONDITIONAL_IO
or:ed together.
data_bits
Any of the flags BIT_INDEX
, BIT_SET_INDEX
, BIT_CALL
,
BIT_NOT_SETUID
and BIT_DESTRUCT
or:ed together.
Throws an exception if the current creds doesn't have the allow
bit BIT_SECURITY
set.
int
get_allow_bits()
Get the allow_bit bitmask.
int
get_data_bits()
Get the data_bits bitmask.
Creds
get_default_creds()
Get the default credentials.
Returns the default credentials object if it has been set.
Returns 0
(zero) if it has not been set.
set_default_creds()
object
get_user()
Get the user part.
void
set_default_creds(Creds
creds
)
Set the default credentials
The current creds must have the allow bit
BIT_SECURITY
set.
get_default_creds()
Virtual class for User objects, used in Creds
objects.
int(2bit)
|array
valid_io(string
fun
, string
type
, mixed
... args
)
This callback gets called when I/O operations not performed on file objects are performed.
int(2bit)
|string
valid_open(string
type
, object
current
, string
filename
, string
flags
, int
access
)
This callback gets called when a new file is to be opened (and
the Creds
object has BIT_CONDITIONAL_IO
set).
type
The type of file operation requested. Can either be "read"
or "write"
.
current
The current object, i.e. the Fd object the user is trying to open.
filename
The file name requested.
flags
The flag string passed to open, e.g. "cwt"
.
access
The access flags requested for the file, e.g. 0666
.
The function can either return a string, which means that the user is allowed to open a file, but the returned file should be opened instead, or it can return an integer. The integers are intepreted as follows.
| The user was not allowed to open the file. ERRNO will be set to EPERM and an exception is thrown. |
| Do nothing, i.e. valid_open has initilized the |
| The user was allowed to open the file and the open code proceeds. |
| The user was not allowed to open the file and an exception is thrown. |
Single socket output.
Regular file output and (multiple, adding) socket output with no mmap input.
Multiple socket output without regular file output illegal.
It is preferable to use the Shuffler
API, it is significantly
more flexible.
Concatenation pipe.
int
bytes_sent()
Return the number of bytes sent.
void
finish()
Terminate and reinitialize the pipe.
void
input(object
obj
)
Add an input file to this pipe.
void
output(object
obj
, int
|void
start_pos
)
Add an output file object.
void
set_done_callback(void
|function
(mixed
:mixed
) done_cb
, void
|mixed
id
)
Set the callback function to be called when all the outputs have been sent.
void
set_output_closed_callback(void
|function
(mixed
, object
:mixed
) close_cb
, void
|mixed
id
)
Set the callback function to be called when one of the outputs has been closed from the other side.
void
start()
Start sending the input(s) to the output(s).
string
version()
Return the version of the module.
void
write(string
bytes
)
Add an input string to this pipe.
void
daemon(int
nochdir
, int
noclose
, void
|mapping
(string
:string
|Stdio.File
) modifiers
)
A function to run current program in the background.
nochdir
If 0 the process will continue to run in / or the directory dictadet by modifiers.
noclose
If this is not 0 the process will keep current file descriptors open.
modifiers
Optional extra arguments. The parameters passed in this mapping will override the arguments nochdir and noclose.
| Change current working directory to this directory. |
| If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard input to the process. If this is a Stdio.File object the process will use this as standard input. |
| If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard output to the process. If this is a Stdio.File object the process will use this as standard output. |
| If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard error to the process. If this is a Stdio.File object the process will use this as standard error. |
System.daemon
This function only works on UNIX-like operating systems.
/* close all fd:s and cd to '/' */ Process.daemon(0, 0);
/* Do not change working directory. Write stdout to a file called access.log and stderr to error.log. */ Process.daemon(1, 0, ([ "stdout": "access.log", "stderr": "error.log" ]) );
int
exec(string
file
, string
... foo
)
bool
get_forkd_default()
Get the default value for the "forkd"
modifier
to Process
.
The default default value is 0
(zero).
set_forkd_default()
, Process()->create()
string
popen(string
command
)
Executes command
as a shell statement ("/bin/sh -c
" for Unix, "command
cmd /c
" for Windows),
waits until it has finished and returns the result as a string.command
system
, spawn
Stdio.FILE
popen(string
command
, string
mode
)
Open a "process" for reading or writing. The command
is executed
as a shell statement ("/bin/sh -c
" for Unix,
"command
cmd /c
" for Windows). The parameter command
mode
should be one of the following letters:
| Open for reading. Data written by the process to stdout is available for read. |
| Open for writing. Data written to the file is available to the process on stdin. |
system
, spawn
mapping
run(string
|array
(string
) cmd
, void
|mapping
modifiers
)
Easy and lazy way of using Process.Process
that runs a process
and returns a mapping with the output and exit code without
having to make sure you read nonblocking yourself.
args
Either a command line array, as the command_args
argument to create_process()
, or a string that
will be splitted into a command line array by
calling split_quoted_string()
in an operating
system dependant mode.
modifiers
It takes all the modifiers Process.Process
accepts, with
the exception of stdout and stderr. Since the point of this
function is to handle those you can not supply your own.
If modifiers->stdin
is set to a string it will automaticly be
converted to a pipe that is fed to stdin of the started process.
Process.Process
create_process
| Everything the process wrote on stdout. |
| Everything the process wrote on stderr. |
| The process' exitcode. |
As the entire output of stderr and stdout is stored in the returned mapping it could potentially grow until memory runs out. It is therefor adviceable to set up rlimits if the output has a potential to be very large.
Process.run( ({ "ls", "-l" }) ); Process.run( ({ "ls", "-l" }), ([ "cwd":"/etc" ]) ); Process.run( "ls -l" ); Process.run( "awk -F: '{print $2}'", ([ "stdin":"foo:2\nbar:17\n" ]) );
string
search_path(string
command
)
Search for the path to an executable.
command
Executable to search for.
Searches for command
in the directories listed in the
environment variable $PATH.
Returns the path to command
if found, and
0
(zero) on failure.
This function is NOT thread safe if the environment variable $PATH is being changed concurrently.
In Pike 7.8.752 and earlier the environment variable $PATH was only read once.
void
set_forkd_default(bool
mode
)
Set the default value for the "forkd"
modifier
to Process
.
The default default value is 0
(zero).
get_forkd_default()
, Process()->create()
string
sh_quote(string
s
)
Process
spawn(string
command
, void
|Stdio.Stream
stdin
, void
|Stdio.Stream
stdout
, void
|Stdio.Stream
stderr
, )
Spawns a process that executes command
as a command shell
statement ("/bin/sh -c
" for Unix, "command
cmd /c
" for Windows).command
stdin
stdout
stderr
Stream objects to use as standard input, standard output and standard error, respectively, for the created process. The corresponding streams for this process are used for those that are left out.
Returns a Process.Process
object for the created process.
system
, popen
Process
spawn_pike(array
(string
) argv
, void
|mapping
(string
:mixed
) options
, array
(string
)|void
launcher
)
Spawn a new pike process similar to the current.
argv
Arguments for the new process.
options
Process creation options. See Process.Process
for details. May also
specify "add_predefines", "add_program_path", or "add_include_path" in
order to include these components in command path (module path is
included by default.)
launcher
Optional launcher prefix command used to spawn the pike binary.
When used this is typically something like
({ "/usr/bin/valgrind" })
.
Defaults to the empty array.
Process.Process
array
(string
) split_quoted_string(string
s
, bool
|void
nt_mode
)
Splits the given string into a list of arguments, according to
common (i.e. /bin/sh
-based) command line quoting rules:
Sequences of whitespace, i.e. space, tab, \n
or
\r
, are treated as argument separators by default.
Single or double quotes ('
or "
) can be used
around an argument to avoid whitespace splitting inside it. If
such quoted strings are used next to each other then they get
concatenated to one argument; e.g. a"b"'c'
becomes a
single argument abc
.
Backslash (\
) can be used in front of one of the space
or quote characters mentioned above to treat them literally.
E.g. x\ y
is a single argument with a space in the
middle, and x\"y
is a single argument with a double
quote in the middle.
A backslash can also be used to quote itself; i.e. \\
becomes \
.
Backslashes in front of other characters are removed by default.
However, if the optional nt_mode
flag is set then they are
retained as-is, to work better with Windows style paths.
Backslashes are treated literally inside quoted strings, with
the exception that \"
is treated as a literal "
inside a "
-quoted string. It's therefore possible to
include a literal "
in a "
-quoted string, as
opposed to '
-quoted strings which cannot contain a
'
.
int
system(string
command
, void
|Stdio.Stream
stdin
, void
|Stdio.Stream
stdout
, void
|Stdio.Stream
stderr
)
Executes command
as a shell statement ("/bin/sh -c
" for Unix, "command
cmd /c
" for Windows),
waits until it has finished and returns its return value.command
stdin
stdout
stderr
Stream objects to use as standard input, standard output and standard error, respectively, for the created process. The corresponding streams for this process are used for those that are left out.
spawn
, popen
Decoder for data received by Tools.Standalone.forkd
.
ForkdEncoder
Process.ForkdDecoder Process.ForkdDecoder(
array
(Stdio.Fd
) fds
)
array
(Stdio.Fd
) Process.ForkdDecoder.fds
Encoder for data to be sent to Tools.Standalone.forkd
.
ForkdDecoder
Process.ForkdEncoder Process.ForkdEncoder(
Stdio.File
remote_fd
)
Stdio.File
Process.ForkdEncoder.remote_fd
Slightly polished version of create_process
.
In addition to the features supported by create_process
,
it also supports:
Callbacks on timeout and process termination.
Using Tools.Standalone.forkd
via RPC to
spawn the new process.
create_process
, Tools.Standalone.forkd
Process.Process Process.Process(
string
|array
(string
) command_args
, void
|mapping
(string
:mixed
) modifiers
)
command_args
Either a command line array, as the command_args
argument to create_process()
, or a string that
will be splitted into a command line array by
calling split_quoted_string()
in an operating
system dependant mode.
modifiers
In addition to the modifiers that create_process
accepts,
this object also accepts
| This callback is called when there is data to be read from the process. |
| This callback is called if the process times out. |
| The time it takes for the process to time out. Default is 15 seconds. |
| Use |
The default value for the "forkd"
modifier may be
set via set_forkd_default()
.
create_process
, create_process()->create()
,
split_quoted_string()
, Tools.Standalone.forkd
,
set_forkd_default()
, get_forkd_default()
inherit create_process : create_process
Based on create_process
.
Process.Spawn Process.Spawn(
string
cmd
, void
|array
(string
) args
, void
|mapping
(string
:string
) env
, string
|void
cwd
, void
|array
(Stdio.File
|void
) ownpipes
, void
|array
(Stdio.File
|void
) fds_to_close
)
int
kill(int
signal
)
int
wait()
Class that enables tracing of processes.
The new process will be started in stopped state.
Use cont()
to let it start executing.
This class currently only exists on systems that implement ptrace().
void
cont(int
|void
signal
)
Allow a traced process to continue.
signal
Deliver this signal to the process.
This function may only be called for stopped processes.
wait()
void
exit()
Cause the traced process to exit.
This function may only be called for stopped processes.
cont()
, wait()
inherit create_process : create_process
int
wait()
Waits for the process to stop.
| The exit code of the process. |
| The process was killed by a signal. |
| The process has stopped. |
create_process::wait()
Interface to the current register contents of a stopped process.
TraceProcess
int
res = Process.TraceProcess.Registers()
[ regno
]
Get the contents of register regno
.
This is the recommended and most portable way to start processes in Pike. The process object is a pike abstraction of the running system process, with methods for various process housekeeping.
Process
Process.create_process Process.create_process(
array
(string
) command_args
, void
|mapping
modifiers
)
command_args
The command name and its command-line arguments. You do not have to worry about quoting them; pike does this for you.
modifiers
This optional mapping can can contain zero or more of the following parameters:
| Function called when the created process changes state. Note that this function is called in a signal handler context, which means that it may be called by any thread at any time after the child process has changed state, and is thus not only called by the main thread when the main backend is idle. Indeed, you can specify a callback even if your program does not use a backend. | ||||||||||||||||
| Execute the command in another directory than the current directory of this process. Please note that if the command is given is a relative path, it will be relative to this directory rather than the current directory of this process. Note also that the path is relative to the | ||||||||||||||||
| Chroot to this directory before executing the command. Note that the current directory will be changed to | ||||||||||||||||
| These parameters allows you to change the standard input, output
and error streams of the newly created process. This is
particularly useful in combination with | ||||||||||||||||
| |||||||||||||||||
| |||||||||||||||||
| This mapping will become the environment variables for the
created process. Normally you will want to only add or change
variables which can be achived by getting the environment mapping
for this process with | ||||||||||||||||
| This parameter changes which user the new process will execute as. Note that the current process must be running as UID 0 to use this option. The uid can be given either as an integer as a string containing the login name of that user. The "gid" and "groups" for the new process will be set to the right values for that user unless overriden by options below. (See | ||||||||||||||||
| This parameter changes the primary group for the new process.
When the new process creates files, they will will be created
with this group. The group can either be given as an int or a
string containing the name of the group. (See | ||||||||||||||||
| Set this to | ||||||||||||||||
| This parameter allows you to the set the list of groups that the new process belongs to. It is recommended that if you use this parameter you supply at least one and no more than 16 groups. (Some system only support up to 8...) The groups can be given as gids or as strings with the group names. | ||||||||||||||||
| This parameter overrides a behaviour of the "uid" parameter. If this parameter is used, the gid and groups of the new process will be inherited from the current process rather than changed to the approperiate values for that uid. | ||||||||||||||||
| This sets the priority of the new process, see
| ||||||||||||||||
| This sets the nice level of the new process; the lower the number, the higher the priority of the process. Note that only UID 0 may use negative numbers. | ||||||||||||||||
| This prevents Pike from restoring all signal handlers to their default values for the new process. Useful to ignore certain signals in the new process. | ||||||||||||||||
| This parameter allows you to map files to filedescriptors 3 and
up. The file | ||||||||||||||||
| There are two values for each limit, the soft limit and the hard
limit. Processes that do not have UID 0 may not raise the hard
limit, and the soft limit may never be increased over the hard
limit. The indices of the mapping indicate what limit to impose,
and the values dictate what the limit should be. (See also
| ||||||||||||||||
| Bind the process to the console associated with this pty slave. NT only. |
Process.create_process(({ "/usr/bin/env" }), (["env" : getenv() + (["TERM":"vt100"]) ]));
//! Spawn a new process with the args @[args] and optionally a //! standard input if you provide such a @[Stdio.File] object. //! @returns //! Returns the new process and a pipe from which you can read //! its output. array(Process.Process|Stdio.File) spawn(Stdio.File|void stdin, string ... args) { Stdio.File stdout = Stdio.File(); mapping opts = ([ "stdout" : stdout->pipe() ]); if( stdin ) opts->stdin = stdin; return ({ Process.create_process( args, opts ), stdout }); }
All parameters that accept both string or int input can be noticeably slower using a string instead of an integer; if maximum performance is an issue, please use integers.
On NT the only supported modifiers are: "cwd"
,
"conpty"
, "stdin"
, "stdout"
, "stderr"
and "env"
. All other modifiers are silently ignored.
Support for "callback"
was added in Pike 7.7.
Chroot changing directory to "/"
was added in Pike 7.9.
bool
kill(int
signal
)
Send a signal to the process.
| Success. |
| Failure. |
This function is only available on platforms that support signals.
predef::kill()
int(0..)
last_signal()
Returns the last signal that was sent to the process.
constant
Process.create_process.limit_value
Each limit_value may be either of:
sets current limit, max is left as it is.
([ "hard":int, "soft":int ]) Both values are optional, hard <= soft.
({ hard, soft }), both can be set to the string "unlimited". A value of -1 means 'keep the old value'.
The string "unlimited" sets both the hard and soft limit to unlimited
int
pid()
Returns the process identifier of the process.
int
set_priority(string
priority
)
Sets the priority of the process. priority
is one of the strings
int(-1..2)
status()
Returns the status of the process:
| Unknown |
| Running |
| Stopped |
| Exited |
Prior to Pike 7.5 the value 1 was returned for exited processes.
int
wait()
Waits for the process to end.
| The exit code of the process. |
| The process was killed by a signal. |
| The process is stopped. |
TraceProcess()->wait()
SimpleRegexp
`()(void
|string
regexp
)
Convenience/compatibility method to get a SimpleRegexp
object.
inherit "___Regexp" : "___Regexp"
bool
match(string
regexp
, string
data
)
Calls Regexp.PCRE.Plain.match
in a temporary regexp object.
Faster to type but slower to run...
string
replace(string
regexp
, string
data
, string
|function
(string
:string
) transform
)
Calls Regexp.PCRE.Plain.replace
in a temporary regexp object.
Faster to type but slower to run...
array
split(string
regexp
, string
data
)
Calls Regexp.PCRE.Plain.split
in a temporary regexp object.
Faster to type but slower to run...
array
split2(string
regexp
, string
data
)
Calls Regexp.PCRE.Plain.split2
in a temporary regexp object.
Faster to type but slower to run...
This class implements the interface to a simple regexp engine with the following capabilities:
. | Matches any character. |
[abc] | Matches a, b or c. |
[a-z] | Matches any character a to z inclusive. |
[^ac] | Matches any character except a and c. |
(x) | Matches x (x might be any regexp) If used with split, this also puts the string matching x into the result array. |
x* | Matches zero or more occurances of 'x' (x may be any regexp). |
x+ | Matches one or more occurances of 'x' (x may be any regexp). |
x|y | Matches x or y. (x or y may be any regexp). |
xy | Matches xy (x and y may be any regexp). |
^ | Matches beginning of string (but no characters). |
$ | Matches end of string (but no characters). |
\< | Matches the beginning of a word (but no characters). |
\> | Matches the end of a word (but no characters). |
Note that \ can be used to quote these characters in which case they match themselves, nothing else. Also note that when quoting these something in Pike you need two \ because Pike also uses this character for quoting.
string(8bit) encode_value(Regexp.SimpleRegexp data)
Regexp.SimpleRegexp decode_value(string(8bit) data)
Regexp objects can be encoded and decoded.
encode_value
, decode_value
Regexp.SimpleRegexp Regexp.SimpleRegexp(
string
re
)
When create is called, the current regexp bound to this object is
cleared. If a string is sent to create(), this string will be compiled
to an internal representation of the regexp and bound to this object
for laters calls to e.g. match
or split
. Calling create() without
an argument can be used to free up a little memory after the regexp has
been used.
inherit _SimpleRegexp : _SimpleRegexp
array
(string
) match(array
(string
) strs
)
Returns an array containing strings in strs
that match the
regexp bound to the regexp object.
The current implementation doesn't support searching in strings containing the NUL character or any wide character.
split
int
match(string
str
)
Returns 1 if str
matches the regexp bound to the regexp object.
Zero otherwise.
string
replace(string
in
, string
|function
(string
:string
) transform
)
array
(string
) split(string
s
)
Works as match
, but returns an array of the strings that
matched the subregexps. Subregexps are those contained in "( )" in
the regexp. Subregexps that were not matched will contain zero.
If the total regexp didn't match, zero is returned.
You can currently only have 39 subregexps.
The current implementation doesn't support searching in strings containing the NUL character or any wide character.
match
StudiedWidestring
`()(string
pattern
, void
|int
options
, void
|object
table
)
Convenience function to create a suitable PCRE Regexp object; will create a StudiedWidestring from the arguments.
That means the result will be able to handle widestrings, and will produce fast matchings by studying the pattern, but the widestring wrapping will on the other hand add overhead.
If you need a faster regexp and doesn't use widestring, create a Regexp.PCRE.Studied instead.
Widestring support will not be used if the linked libpcre lacks UTF8 support. This can be tested with checking that the Regexp.PCRE.Widestring class exist.
constant
Regexp.PCRE.buildconfig_LINK_SIZE
(from the pcreapi man-page) "The output is an integer that contains the number of bytes used for internal linkage in compiled regular expressions. The value is 2, 3, or 4. Larger values allow larger regular expressions to be compiled, at the expense of slower match- ing. The default value of 2 is sufficient for all but the most massive patterns, since it allows the compiled pattern to be up to 64K in size." This constant is calculated when the module is initiated by using pcre_config(3).
constant
Regexp.PCRE.buildconfig_MATCH_LIMIT
(from the pcreapi man-page) "The output is an integer that gives the default limit for the number of internal matching function calls in a pcre_exec() execution. Further details are given with pcre_exec() below." This constant is calculated when the module is initiated by using pcre_config(3).
constant
Regexp.PCRE.buildconfig_NEWLINE
(from the pcreapi man-page) "The output is an integer that is set to the value of the code that is used for the newline character. It is either linefeed (10) or carriage return (13), and should normally be the standard character for your operating system." This constant is calculated when the module is initiated by using pcre_config(3).
constant
Regexp.PCRE.buildconfig_POSIX_MALLOC_THRESHOLD
(from the pcreapi man-page) "The output is an integer that contains the threshold above which the POSIX interface uses malloc() for output vectors. Further details are given in the pcreposix documentation." This constant is calculated when the module is initiated by using pcre_config(3).
constant
Regexp.PCRE.buildconfig_UTF8
(from the pcreapi man-page) "The output is an integer that is set to one if UTF-8 support is available; otherwise it is set to zero." This constant is calculated when the module is initiated by using pcre_config(3).
inherit "____Regexp_PCRE" : "____Regexp_PCRE"
array
(string
) split_subject(string
subject
, array
(int
) previous_result
)
Convenience function that splits a subject string on the result from _pcre->exec()
equal to map(previous_result/2, lambda(array v) { return subject[v[0]..v[1]-1]; })
The main regexp class. Will provide anything needed for matching regexps.
There are subclasses that adds wrappers for widestrings, and to optimize the regexp pattern.
inherit _pcre : _pcre
bool
match(string
subject
, void
|int
startoffset
)
returns true (1) if a match is found, false otherwise
example:
> Regexp.PCRE.Plain("is fun")->match("pike is fun");
Result: 1
> Regexp.PCRE.Plain("is fun")->match("pike isn't fun");
Result: 0
this_program
matchall(string
subject
, function
(array
(string
)|void
, array
(int
)|void
:mixed
|void
) callback
)
Will give a callback for each match in a subject. Called arguments will be matching patterns and subpatterns in an array and as second argument the exec result array.
returns called object
example:
> Regexp.PCRE("b(a*)([^-\1234]*)(\1234*)m")
->matchall("abam-boom-fooabado\1234m",
lambda(mixed s) { werror("%O\n",s); return "gurka"; });
({ /* 4 elements */
"bam",
"a",
"",
""
})
({ /* 4 elements */
"boom",
"",
"oo",
""
})
({ /* 4 elements */
"bado\1234m",
"a",
"do",
"\1234"
})
Result: Regexp.PCRE.StudiedWidestring("b(a*)([^-Ê\234]*)(Ê\234*)m")
string
replace(string
subject
, string
|function
(:void
) with
, mixed
|void
... args
)
replace all occurances of a pattern in a subject; callbacks and replacements will be from the first occurance, not from the last as in Regexp.Builtin.replace.
if with is a function, the first argument will be the total match string, and the subsequent arguments will contain any submatches
example:
> Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom","gurka");
Result: "agurka-gurka-fooagurka"
> Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom",
lambda(string s) { werror("%O\n",s); return "gurka"; });
"bam"
"boom"
"badoom"
Result: "agurka-gurka-fooagurka"
example:
> Regexp.PCRE("([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})")
->replace("foo@bar.org",
lambda(string whole, string user, string loc, string domain)
{ return user + " from " + loc + " dot " + domain; }
);
(4) Result: "foo from bar dot org"
string
replace1(string
subject
, string
|function
(string
:string
) with
)
replace one (first) occurance of a pattern in a subject
example:
> Regexp.PCRE("b[^-]*m")->replace1("abam-boom-fooabadoom","gurka");
Result: "agurka-boom-fooabadoom"
string
replace_positional(string
subject
, string
subst
)
replaces matches in a string, with support for backreferences (matched groups)
subject
the string to be tested against the regular expression
subst
string to be inserted in place of each match. backreferences can be inserted into the string to be substituted using the syntax %[n]s where n is the nth matching string group, and 0 (zero) is the full match.
example:
> Regexp.PCRE.Plain("my name is ([a-zA-Z]+)")
->replace_positional("allow me to introduce myself: my name is john",
"%[0]s is my name");
(1) Result: "allow me to introduce myself: john is my name"
array
(string
)|int(0..0)
split(string
subject
, void
|int
startoffset
)
Matches a subject against the pattern, compatible with the old split method: returns an array of the subpatterns, or if there are no subpattern but still a match, ({0}). Returns 0 if there was no match.
example:
> Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split("pike is fun");
(1) Result: ({
"ke",
"f"
})
> Regexp.PCRE.Plain("is fun")->split("pike is fun");
(4) Result: ({
0
})
array
(string
)|int(0..0)
split2(string
subject
, void
|int
startoffset
)
Matches a subject against the pattern, returns an array where the first element are the whole match, and the subsequent are the matching subpatterns. Returns 0 if there was no match.
example:
> Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split2("pike is fun");
Result: ({
"ike is fu",
"ke",
"f"
})
Same as Plain, but will be studied to match faster; useful if you're doing many matches on the same pattern
inherit Plain : Plain
Same as Widestring, but will be studied to match faster; useful if you're doing many matches on the same pattern
inherit Widestring : Widestring
Wrapper class around Plain, that will allow widestring patterns and subjects.
Widestring support and this class will not be implemented if the linked libpcre lacks UTF8 support.
array
(int
)|int
exec(string
subject
, void
|int
startoffset
)
The exec function is wrapped to give the correct indexes for the widestring.
inherit Plain : Plain
string sprintf(string format, ... Regexp.PCRE._pcre arg ... )
Regexp.PCRE._pcre Regexp.PCRE._pcre(
string
pattern
, void
|int
options
, void
|object
table
)
The option bits are:
| Force pattern anchoring |
| Do caseless matching |
| $ not to match newline at end |
| . matches anything including NL |
| Ignore whitespace and # comments |
| PCRE extra features (not much use currently) |
| ^ and $ match newlines within data |
| Disable numbered capturing parentheses (named ones available) |
| Invert greediness of quantifiers |
| Run in UTF-8 mode |
int
|array
exec(string
subject
, void
|int
startoffset
)
Matches the regexp against subject
, starting at
startoffset
if it is given.
If the match is successful, the return value is an array that holds the offsets of all matches:
Elements 0 and 1 have the start and end offsets, respectively,
of the match for the whole regexp. The start offset is
inclusive while the end is exclusive, i.e. the matching
string is
.subject
[res[0]..res[1]-1]
Elements 2 and 3 have the offsets of the first capturing submatch (if any) in the same way, elements 4 and 5 are for the second capturing submatch, etc. If a submatch didn't match anything, the corresponding elements are set to -1. If a submatch has matched successfully several times, the offsets of the last match are returned.
The returned array is always of length 2*n + 1, where n is the total number of capturing submatches in the regexp.
If there is an error, an integer error code is returned:
| The subject string did not match the pattern. |
| Either code or subject was passed as NULL, or ovector was NULL and oversize was not zero. |
| An unrecognized bit was set in the options argument. |
| PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch the case when it is passed a junk pointer. This is the error it gives when the magic number isn't present. |
| While running the pattern match, an unknown item was encountered in the compiled pattern. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern. |
| If a pattern contains back references, but the ovector that is passed to pcre_exec() is not big enough to remember the referenced substrings, PCRE gets a block of memory at the start of matching to use for this purpose. If the call via pcre_malloc() fails, this error is given. The memory is freed at the end of matching. |
| This error is used by the pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() functions (see below). It is never returned by pcre_exec(). |
| The recursion and backtracking limit, as specified by the match_limit field in a pcre_extra structure (or defaulted) was reached. See the description above. |
| This error is never generated by pcre_exec() itself. It is provided for use by callout functions that want to yield a distinctive error code. See the pcrecallout documentation for details. |
int
get_stringnumber(string
stringname
)
returns the number of a named subpattern
mapping
info()
Returns additional information about a compiled pattern. Only available if PCRE was compiled with Fullinfo.
| Return the number of the highest back reference in the pattern. The fourth argument should point to an int variable. Zero is returned if there are no back references. | ||||||||
| Return the number of capturing subpatterns in the pattern. The fourth argument should point to an int variable. | ||||||||
| Return information about the first byte of any matched string, for a non-anchored pattern. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name is still recognized for backwards compatibility.) If there is a fixed first byte, e.g. from a pattern such as (cat|cow|coyote), it is returned in the integer pointed to by where. Otherwise, if either (a) the pattern was compiled with the PCRE_MULTILINE
option, and every branch starts with (b) every branch of the pattern starts with | ||||||||
| Return the value of the rightmost literal byte that must
exist in any matched string, other than at its start, if
such a byte has been recorded. The fourth argument should
point to an int variable. If there is no such byte,
| ||||||||
| |||||||||
| |||||||||
| Return a copy of the options with which the pattern was compiled. The fourth argument should point to an unsigned long int variable. These option bits are those specified in the call to pcre_compile(), modified by any top-level option settings within the pattern itself. A pattern is automatically anchored by PCRE if all of its top-level alternatives begin with one of the following:
For such patterns, the PCRE_ANCHORED bit is set in the options returned. | ||||||||
| Return the size of the compiled pattern, that is, the value that was passed as the argument to pcre_malloc() when PCRE was getting memory in which to place the compiled data. The fourth argument should point to a size_t variable. | ||||||||
| Returns the size of the data block pointed to by the study_data field in a pcre_extra block. That is, it is the value that was passed to pcre_malloc() when PCRE was getting memory into which to place the data created by pcre_study(). The fourth argument should point to a size_t variable. |
object
study()
(from the pcreapi man-page) "When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for match- ing."
constant
Regexp.PCRE.ERROR.NOMATCH
constant
Regexp.PCRE.ERROR.NULL
constant
Regexp.PCRE.ERROR.BADOPTION
constant
Regexp.PCRE.ERROR.BADMAGIC
constant
Regexp.PCRE.ERROR.UNKNOWN_NODE
constant
Regexp.PCRE.ERROR.NOMEMORY
constant
Regexp.PCRE.ERROR.NOSUBSTRING
constant
Regexp.PCRE.ERROR.MATCHLIMIT
constant
Regexp.PCRE.ERROR.CALLOUT
Documented in exec
.
contains all option constants
constant
Regexp.PCRE.OPTION.ANCHORED
(from the pcreapi manpage) If this bit is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
constant
Regexp.PCRE.OPTION.CASELESS
(from the pcreapi manpage) If this bit is set, letters in the pattern match both upper and lower case letters. It is equivalent to Perl's /i option, and it can be changed within a pattern by a (?i) option setting.
constant
Regexp.PCRE.OPTION.DOLLAR_ENDONLY
(from the pcreapi manpage) If this bit is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. There is no equivalent to this option in Perl, and no way to set it within a pattern.
constant
Regexp.PCRE.OPTION.DOTALL
(from the pcreapi manpage) If this bit is set, a dot metacharater in the pattern matches all characters, including newlines. Without it, newlines are excluded. This option is equivalent to Perl's /s option, and it can be changed within a pattern by a (?s) option setting. A negative class such as [^a] always matches a newline character, independent of the setting of this option.
constant
Regexp.PCRE.OPTION.EXTENDED
(from the pcreapi manpage) If this bit is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT character (code 11). In addition, characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x option, and it can be changed within a pattern by a (?x) option setting.
This option makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
constant
Regexp.PCRE.OPTION.EXTRA
(from the pcreapi manpage) This option was invented in order to turn on additional functionality of PCRE that is incompatible with Perl, but it is currently of very little use. When set, any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this option. It can also be set by a (?X) option setting within a pattern.
constant
Regexp.PCRE.OPTION.MULTILINE
(from the pcreapi manpage) By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless PCRE_DOL- LAR_ENDONLY is set). This is the same as Perl.
When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs match immediately following or immediately before any new- line in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no "\n" charac- ters in a subject string, or no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect.
constant
Regexp.PCRE.OPTION.NO_AUTO_CAPTURE
(from the pcreapi manpage) If this option is set, it disables the use of numbered capturing paren- theses in the pattern. Any opening parenthesis that is not followed by ? behaves as if it were followed by ?: but named parentheses can still be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl.
constant
Regexp.PCRE.OPTION.UNGREEDY
(from the pcreapi manpage) This option inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) option setting within the pattern.
constant
Regexp.PCRE.OPTION.UTF8
(from the pcreapi manpage) This option causes PCRE to regard both the pattern and the subject as strings of UTF-8 characters instead of single-byte character strings. However, it is available only if PCRE has been built to include UTF-8 support. If not, the use of this option provokes an error. Details of how this option changes the behaviour of PCRE are given in the section on UTF-8 support in the main pcre page.
Remote RPC system.
Wrapper for a remote function.
mixed
res = Remote.Call()
()
Call the wrapped function.
args
Arguments to pass to the wrapped function.
This function can operate in two modes depending
on whether asynchronous mode has been activated
or not. If it has it is equivalent to a call of
async()
and if not of sync()
with the same
arguments.
async()
, sync()
, is_async()
, set_async()
void
async(mixed
... args
)
Call the wrapped remote function asynchronously.
args
Arguments to send to the remote function.
sync()
, `()()
Remote.Call Remote.Call(
string
objectid
, string
name
, object
connection
, object
context
, int
async
)
int
exists()
Check whether the wrapped function actually exists at the other end.
int
is_async()
Whether asynchronous mode is active or not.
set_async()
void
set_async(int
a
)
Change to/from asynchronous mode.
is_async()
mixed
sync(mixed
... args
)
Call the wrapped remote function synchronously.
args
Arguments to send to the remote function.
Returns (the possibly wrapped) result from the remote function.
async()
, `()()
Remote RPC Client.
void
close()
Close the connection.
int
closed()
Check if the connection is closed.
Remote.Connection
Remote.Client.con
Connection to the Remote.Server
.
Remote.Client Remote.Client(
string
host
, int
port
, void
|int
nice
, void
|int
timeout
, void
|int
max_call_threads
)
Connect to a Remote.Server
.
host
port
Hostname and port for the Remote.Server
.
nice
If set, inhibits throwing of errors from call_sync()
.
timeout
Connection timeout in seconds.
max_call_threads
Maximum number of concurrent threads.
object
get(string
name
)
Get a named object from the remote server.
void
provide(string
name
, mixed
thing
)
Provide a named thing
to the Remote.Server
.
name
Name to provide thing
under.
thing
Thing to provide.
void
set_close_callback(function
(:void
) f
)
Set the callback to call when the connection is closed.
void
add_close_callback(function
(:void
) f
, mixed
... args
)
Add a function that is called when the connection is closed.
void
call_async(array
data
)
Make a call but don't wait for the result
mixed
call_sync(array
data
)
Make a call and wait for the result
void
close()
Closes the connection nicely, after waiting in outstanding calls in both directions.
int
connect(string
host
, int
port
, void
|int
timeout
)
This function is called by clients to connect to a server.
Remote.Connection Remote.Connection(
void
|int
nice
, void
|int
max_call_threads
)
nice
If set, no errors will be thrown.
string
error_message()
Returns an error message for the last error, in case connect
returns zero. Returns zero if the last connect
call was
successful.
object
get_named_object(string
name
)
Get a named object provided by the server.
void
remove_close_callback(array
f
)
Remove a function that is called when the connection is closed.
void
start_server(object
c
, object
cx
)
This function is called by servers when they have got a connection from a client. The first argument is the connection file object, and the second argument is the context to be used.
Remote context tracker.
This class keeps track of what local things correspond to what remote things, and the reverse.
void
add(object
o
, string
id
)
Remote.Context Remote.Context(
string
b
, object
|void
cn
)
mixed
decode(array
a
)
function
(:void
)|object
decode_call(array
data
)
int
decode_existp(array
data
)
string
describe(array
data
)
array
encode(mixed
val
)
array
encode_call(object
|string
o
, string
|function
(:void
) f
, array
args
, int
type
)
object
function_for(string
id
)
string
id_for(mixed
thing
)
object
object_for(string
id
)
void
set_server_context(object
ctx
, object
cn
)
Wrapper for a remote object.
mixed
res = Remote.Obj()
->X
mixed
res = Remote.Obj()
[ f
]
Remote.Obj Remote.Obj(
string
id
, object
connection
, object
context
)
int
exists()
mixed
get_function(string
f
)
Remote RPC server.
void
close()
Shut down the Remote.Server
for new connections.
void
close_all()
Shut down the Remote.Server
and terminate all current clients.
int
closed()
Check if the Remote.Server
is closed.
array
(Connection
) Remote.Server.connections
Open connections.
Remote.Server Remote.Server(
string
host
, int
port
, void
|int
max_call_threads
)
Create a Remote.Server
.
host
port
Hostname and port for the Remote.Server
.
max_call_threads
Maximum number of concurrent threads.
Stdio.Port
Remote.Server.port
Port for the Remote.Server
.
void
provide(string
name
, mixed
thing
)
Provide a named thing
to the Remote.Client
(s).
name
Name to provide thing
under.
thing
Thing to provide.
Minicontext
Remote.Server.sctx
Server context.
The server Context
class.
This module enables access to the SANE (Scanner Access Now Easy) library from pike
constant
SANE.FrameGray
constant
SANE.FrameRGB
constant
SANE.FrameRed
constant
SANE.FrameGreen
constant
SANE.FrameBlue
array
(mapping
) list_scanners()
Returns an array with all available scanners.
Pike v0.7 release 120 running Hilfe v2.0 (Incremental Pike Frontend) > SANE.list_scanners(); Result: ({ ([ "model":"Astra 1220S ", "name":"umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]), ([ "model":"Astra 1220S ", "name":"net:lain.idonex.se:umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]) })
void
cancel_scan()
SANE.Scanner SANE.Scanner(
string
name
)
mixed
get_option(string
name
)
mapping
(string
:int
) get_parameters()
|
|
|
|
|
|
array
(mapping
) list_options()
This method returns an array where every element is a mapping, layed out as follows.
| |||||||||||||||||
| |||||||||||||||||
| |||||||||||||||||
|
| ||||||||||||||||
|
| ||||||||||||||||
| |||||||||||||||||
|
| ||||||||||||||||
| Constraints can be of three different types; range, word list or string list. Constraint contains 0 if there are no constraints.
|
void
nonblocking_row_scan(function
(Image.Image
, int
, Scanner
, int
:void
) callback
)
void
row_scan(function
(Image.Image
, int
, Scanner
:void
) callback
)
void
set_option(string
name
, mixed
new_value
)
void
set_option(string
name
)
If no value is specified, the option is set to it's default value
Image.Image
simple_scan()
SDL or Simple DirectMedia Layer is a cross-platform multimedia library designed to provide fast access to the graphics framebuffer, audio device, input and other devices. This module implements a wrapper for SDL and other relevant libraries like SDL_mixer. The interface is similar to the C one, but using generally accepted Pike syntax.
This means that classes are used when appropriate and that method
names use all lowercase letters with words separated by _. For
example SDL_SetVideoMode is named SDL.set_video_mode
. Also note
that unless otherwise noted, errors result in an error being
thrown rather than returning -1
or 0
, as commonly
done in SDL methods.
int
blit_surface(SDL.Surface
src
, SDL.Surface
dst
, SDL.Rect
|void
srcrect
, SDL.Rect
|void
dstrect
)
Peforms a fast blit from the source surface to the destination surface.
The final blit rectangle is stored in dstrect. This may differ from srcrect if there was clipping.
This function should not be called on a locked surface.
src
The surface to be copied.
dst
The destination surface. This will usually be your main screen,
initialized with a call to SDL.set_video_mode()
.
srcrect
The rectangular section of src to copy. If the whole surface is to be copied, you can set this to 0.
dstrect
Where the source surface should be copied to on the destination surface.
Only the x and y fields of the SDL.Rect
object are used.
To copy src to the top-left corner of dst, i.e. at coordinates
<0,0>, you can set this to 0.
If successful, 0, otherwise -1.
SDL.Surface()->blit()
string
|void
cd_name(int
drive
)
Returns a human-readable and system-dependent name for the given drive.
drive
The CD drive index.
A human-readable and system-dependent name for the given drive,
or 0
if no name is available.
SDL.cd_num_drives()
int
cd_num_drives()
The number of CD-ROM drives on the system.
SDL.cd_name()
int
enable_unicode(int
enable
)
Enables/Disables UNICODE keyboard translation.
If you wish to translate a keysym to its printable
representation, you need to enable UNICODE translation using this
function and then look in the unicode member of the
SDL.Keysym
class. This value will be zero for keysyms that do
not have a printable representation. UNICODE translation is
disabled by default as the conversion can cause a slight
overhead.
enable
A value of 1
enables Unicode translation, 0
disables
it and -1
leaves it unchanged (useful for querying the current
translation mode).
The previous translation mode (1
enabled, 0
disabled).
If enable is -1
, the return value is the current translation
mode.
SDL.Keysym
int
flip(SDL.Surface
|void
screen
)
On hardware that supports double-buffering, this function
sets up a flip and returns. The hardware will wait for
vertical retrace, and then swap video buffers before the
next video surface blit or lock will return. On hardware
that doesn't support double-buffering, this is equivalent
to calling SDL.update_rect(screen, 0, 0, 0, 0)
The SDL.DOUBLEBUF
flag must have been passed to
SDL.set_video_mode()
when setting the video mode for this
function to perform hardware flipping.
screen
The screen object to flip. If missing, the default screen is used.
This function returns 1 if successful, or 0 if there was an error.
SDL.update_rect()
array
(string
) get_caption()
A 2-element array holding the window title and icon name.
SDL.set_caption()
void
|string
get_error()
Get the last internal SDL error.
The error string, or zero if there was no error.
string
get_key_state()
Gets a snapshot of the current keyboard state.
The current state is returned as a string.
The string is indexed by the SDL.K_* symbols.
A value of 1
means the key is pressed and
a value of 0
means it's not.
Call SDL.pump_events()
to update the state array.
SDL.get_mod_state()
, SDL.pump_events()
// Test if the 'Escape' key is pressed. SDL.pump_events(); string ks = SDL.get_key_state(); if ( ks[SDL.K_ESCAPE] ) { // handle key press...
int
get_mod_state()
Returns the current state of the modifier keys (CTRL, ALT, etc.).
The return value can be an OR'd combination of the following: SDL.KMOD_NONE, SDL.KMOD_LSHIFT, SDL.KMOD_RSHIFT, SDL.KMOD_LCTRL, SDL.KMOD_RCTRL, SDL.KMOD_LALT, SDL.KMOD_RALT, SDL.KMOD_LMETA, SDL.KMOD_RMETA, SDL.KMOD_NUM, SDL.KMOD_CAPS, and SDL.KMOD_MODE.
For convenience, the following are also defined: SDL.KMOD_CTRL, SDL.KMOD_SHIFT, SDL.KMOD_ALT and SDL.KMOD_META
SDL.get_key_state()
, SDL.pump_events()
void
|object
get_video_info()
Returns an SDL.VideoInfo
object, which holds information about the video
hardware, or 0 if the video device has not yet been initialized (with a
call to SDL.init()
).
void
|object
get_video_surface()
Returns the current display surface.
If SDL is doing format conversion on the display surface, this method returns the publicly visible surface, not the real video surface.
The current display surface, or 0 if there is no display surface.
SDL.set_video_mode()
int
gl_get_attribute(int
attribute
)
Returns the value of the given SDL/OpenGL attribute. You might want
to call this after SDL.set_video_mode()
to check that attributes
have been set as you expected.
attribute
The SDL/OpenGL attribute to query.
The value of the given attribute.
// Has double-buffering been set? int db = SDL.gl_get_attribute( SDL.GL_DOUBLEBUFFER ); if ( db ) { // yes...
void
gl_set_attribute(int
attribute
, int
value
)
Sets an SDL/OpenGL attribute to the given value.
This won't take effect until after a call to SDL.set_video_mode()
.
attribute
The attribute to set. This will be one of SDL.GL_RED_SIZE
,
SDL.GL_GREEN_SIZE
, SDL.GL_BLUE_SIZE
,
SDL.GL_DEPTH_SIZE
or SDL.GL_DOUBLEBUFFER
.
value
The value to set for this attribute.
SDL.gl_get_attribute()
void
gl_swap_buffers()
Swaps the OpenGL buffers on a double-buffered screen.
SDL.gl_set_attribute()
, SDL.gl_get_attribute()
,
SDL.set_video_mode()
int
grab_input(int
mode
)
Sets or queries the current 'grab' mode.
Grabbing input means asking that all mouse activity be confined to this application window and that nearly all keyboard events are passed directly to the application, bypassing the window manager.
mode
One of the following constants:
SDL.GRAB_ON
SDL.GRAB_OFF
SDL.GRAB_QUERY
The current grab mode, either SDL.GRAB_ON
or SDL.GRAB_OFF
.
int
iconify_window()
Attempts to iconify (i.e. minimize) the application window.
If the call is successful, the application will receive an
SDL.APPACTIVE
loss event.
Non-zero if successful, otherwise 0
.
void
init(int
flags
)
Initializes SDL. This should be called before all other SDL functions.
flags
The flags parameter specifies what part(s) of SDL to initialize. It can be one of many of the following ORed together.
Initializes the timer subsystem.
Initializes the audio subsystem.
Initializes the video subsystem.
Initializes the cdrom subsystem.
Initializes the joystick subsystem.
Initialize all of the above.
Prevents SDL from catching fatal signals.
Run event polling in a separate thread. Not always supported.
SDL.quit()
, SDL.init_sub_system()
, SDL.quit_sub_system()
void
init_sub_system(int
flags
)
After SDL has been initialized with SDL.init()
you may initialize
uninitialized subsystems with this method.
flags
The same as what is used in SDL.init()
.
SDL.init()
, SDL.quit()
, SDL.quit_sub_system()
int
joystick_event_state(int
state
)
Enables, disables or queries the state of joystick event processing.
state
One of the following constants:
SDL.ENABLE
Enables joystick event processing.
SDL.IGNORE
Disables joystick event processing.
SDL.QUERY
Queries the current state and returns it.
The current state of joystick event processing. If state
was
SDL.ENABLE
or SDL.IGNORE
, then processing will now be enabled
or disabled, respectively.
string
joystick_name(int
device_index
)
Returns the implementation-dependent name of the nth joystick device available to the system.
device_index
The nth joystick device.
The implementation-dependent name of the given joystick device.
SDL.Joystick->name()
int
joystick_opened(int
device_index
)
Determines whether the given joystick device has already been opened.
device_index
The nth joystick device.
1
if this device has already been opened, otherwise 0
.
void
joystick_update()
Updates the state of all open joysticks attached to the system.
int
num_joysticks()
The number of joysticks available to the system.
SDL.Joystick
void
open_audio(int
frequency
, int
format
, int
channels
, int
bufsize
)
Initializes the audio API.
Throws an exception if audio can't be initialized.
frequency
Output sampling frequency, measured in samples per second (Hz).
A value of 44100
provides CD-quality playback.
A less CPU-intensive value for games is 22050
.
format
Output sample format. One of the following constants:
Unsigned 8-bit samples.
Signed 8-bit samples.
Unsigned 16-bit samples in little-endian byte order.
Signed 16-bit samples in little-endian byte order.
Unsigned 16-bit samples in big-endian byte order.
Signed 16-bit samples in big-endian byte order.
Same as SDL.AUDIO_U16LSB.
Same as SDL.AUDIO_S16LSB.
Unsigned 16-bit samples in system byte order.
Signed 16-bit samples in system byte order. If in doubt, try this one first.
channels
Number of sound channels in output: 1
for mono,
2
for stereo.
bufsize
How many bytes to use per output sample.
1024
is a typical value for games. If just playing
music you might set this to 4096
or higher.
void
pump_events()
Pumps the event loop, gathering events from the input devices.
Normally you won't need to call this method, as it's called implicitly
by SDL.Event->poll()
.
get_key_state()
, get_mod_state()
void
quit()
Shuts down all SDL subsystems and frees the resources allocated to them. This should always be called before you exit.
You can use the atexit()
method to ensure that this method is always
called when Pike exits normally.
SDL.init()
, SDL.init_sub_system()
, SDL.quit_sub_system()
void
quit_sub_system(int
flags
)
After an SDL subsystem has been initialized with SDL.init()
or
SDL.init_sub_system()
, it may be shut down with this method.
flags
A bitwise OR'd combination of the subsystems
you wish to shut down (see SDL.init()
for a list of subsystem flags).
SDL.init()
, SDL.init_sub_system()
, SDL.quit()
void
set_caption(string
title
, string
icon
)
Sets the window's title and icon name. Icon name refers to the text that appears next to the application's icon in its minimized window.
title
The window's title.
icon
The minimized window's icon name.
SDL.get_caption()
int
set_gamma(float
red
, float
green
, float
blue
)
Document this function
object
set_video_mode(int
width
, int
height
, int
bpp
, int
flags
)
Sets up a video mode with the specified width, height and bits per pixel.
width
The desired width. Setting this to <= 0 results in an SDL error.
height
The desired height. Setting this to <= 0 results in an SDL error.
bpp
The bits per pixel. This should be either 0, 8, 16, 24 or 32. If you set this to 0, the bits-per-pixel value of the current display will be used.
flags
An OR'd combination of the desired SDL.Surface
flags.
The framebuffer surface. An error is thrown if the video mode can't be set.
SDL.Surface
, SDL.video_mode_ok()
int
show_cursor(int
show
)
Sets the state of the mouse cursor on the SDL screen (visible or hidden), or queries its current state.
By default, the cursor is visible.
show
One of these constants:
Show the cursor.
Hide the cursor.
Determine the current state of the cursor.
The current state of the mouse cursor, either SDL.ENABLE
or
SDL.DISABLE
.
int
toggle_fullscreen(void
|SDL.Surface
screen
)
Toggles the application between windowed and fullscreen mode, if supported. X11 is the only target currently supported.
screen
The framebuffer surface, as returned by SDL.set_video_mode()
.
Returns 1 on success or 0 on failure.
void
update_rect(int
x
, int
y
, int
w
, int
h
, SDL.Surface
|void
screen
)
Makes sure the given area is updated on the given screen. The rectangle must be confined within the screen boundaries (no clipping is done).
If 'x', 'y', 'w' and 'h' are all 0, SDL.update_rect()
will update
the entire screen.
This function should not be called while screen
is locked.
x
y
Top left corner of the rectangle to update.
w
h
Width and height of the rectangle to update.
screen
The screen object to flip. If missing, the default screen is used.
SDL.flip()
void
|string
video_driver_name()
Obtains the name of the video driver. This is a simple one-word identifier such as 'x11' or 'windib'.
The name of the video driver, or 0 if video has not yet been initialized
(with a call to SDL.init()
).
int
video_mode_ok(int
width
, int
height
, int
bpp
, int
flags
)
Checks to see if a particular video mode is supported.
Returns 0 if the requested mode isn't supported under any bit depth, or the
bits-per-pixel of the closest available mode with the given width, height
and SDL.Surface
flags.
SDL.Surface
, SDL.set_video_mode()
, SDL.get_video_info()
void
warp_mouse(int
xpos
, int
ypos
)
Sets the position of the mouse cursor to the given coordinates. This generates an SDL.MOUSEMOTION event.
xpos
Requested position of the mouse cursor along the x-axis.
ypos
Requested position of the mouse cursor along the y-axis.
int
was_init(int
flags
)
This method allows you to see which SDL subsytems have been initialized.
flags
A bitwise OR'd combination of the subsystems
you wish to check (see SDL.init()
for a list of subsystem flags).
A bitwised OR'd combination of the initialized subsystems
SDL.init()
, SDL.init_sub_system()
SDL.CD SDL.CD(
int
drive
)
Document this function
int
SDL.CD.current_frame
Document this variable
int
SDL.CD.current_track
Document this variable
int
eject()
Document this function
int
SDL.CD.id
Document this variable
int
SDL.CD.numtracks
Document this variable
int
pause()
Document this function
int
play(int
start
, int
length
)
Document this function
int
play_tracks(int
start_track
, int
start_frame
, int
ntracks
, int
nframes
)
Document this function
int
resume()
Document this function
int
status()
Document this function
int
stop()
Document this function
CDTrack
track(int
track
)
Document this function
int
SDL.CDTrack.id
int
SDL.CDTrack.length
int
SDL.CDTrack.offset
int
SDL.CDTrack.type
Document this variable
int
SDL.Event.axis
int
SDL.Event.ball
int
SDL.Event.button
int
SDL.Event.code
int
SDL.Event.gain
int
SDL.Event.h
int
SDL.Event.hat
Keysym
SDL.Event.keysym
int
SDL.Event.state
int
SDL.Event.type
int
SDL.Event.value
int
SDL.Event.w
int
SDL.Event.which
int
SDL.Event.x
int
SDL.Event.xrel
int
SDL.Event.y
int
SDL.Event.yrel
int
get()
Removes the next event (if any) from the queue and stores it in this
SDL.Event
object.
1 if there was an event to 'get', otherwise 0.
int
poll()
Polls for currently pending events.
1 if there are currently pending events, otherwise 0.
int
wait()
Waits indefinitely for the next available event, which is then removed
from the queue and stored in this SDL.Event
object.
Returns 1 on success, or 0 if there was an error while waiting for the next event.
Represents a joystick, gamepad or other similar input device attached to the system.
You must call SDL.init()
with the SDL.INIT_JOYSTICK
flag to
enable joystick support.
All index numbers count from 0
.
All SDL.Joystick
methods throw an exception if they are called on
an uninitialized object.
SDL.Joystick SDL.Joystick(
int
device_index
)
Opens the given joystick device for use.
device_index
The nth joystick device available to the system.
SDL.num_joysticks()
float
get_axis(int
axis
)
Returns the current position of the given axis.
The returned value is a float between -1.0
and 1.0
.
axis
The axis index.
The current position of the given axis.
num_axes()
array
(int
) get_ball(int
ball
)
Returns the axis change of the given trackball.
This is its relative motion along both axes since the last call to
get_ball()
. It is returned as a 2-element array holding the values
of dx and dy (- the motion deltas).
The axis change of the given trackball.
num_balls()
int
get_button(int
button
)
Returns the current state of the given button.
This is 1
if the button is pressed, otherwise 0
.
button
The button index.
The current state of the given button.
num_buttons()
int
get_hat(int
hat
)
Returns the current state of the given hat.
This is represented as an OR'd combination of one or more of the following constants:
SDL.HAT_CENTERED
SDL.HAT_UP
SDL.HAT_RIGHT
SDL.HAT_DOWN
SDL.HAT_LEFT
SDL.HAT_RIGHTUP
SDL.HAT_RIGHTDOWN
SDL.HAT_LEFTUP
SDL.HAT_LEFTDOWN
hat
The hat index.
The current state of the given hat.
num_hats()
int
index()
The index of this joystick.
string
name()
The implementation-dependent name of this joystick.
SDL.joystick_name()
int
num_axes()
The number of axes available for this joystick.
int
num_balls()
The number of trackballs available for this joystick.
int
num_buttons()
The number of buttons available for this joystick.
int
num_hats()
The number of hats available for this joystick.
The Keysym class is used to report key presses and releases. It's
available from the SDL.Event
class for keyboard events.
int
SDL.Keysym.mod
Current key modifiers
mod
stores the current state of the keyboard modifiers as
explained in SDL.get_mod_state()
.
int
SDL.Keysym.scancode
Hardware specific scancode
The scancode
field should generally be left alone - it is the
hardware dependent scancode returned by the keyboard.
int
SDL.Keysym.sym
SDL virtual keysym
The sym
field is extremely useful.
It is the SDL-defined value of the key.
This field is very useful when you are checking for certain key presses.
int
SDL.Keysym.unicode
Translated character
The unicode
field is only used
when UNICODE translation has beed enabled with SDL.enable_unicode()
.
If unicode
is non-zero then this the UNICODE character corresponding
to the keypress.
UNICODE translation does have a slight overhead so don't enable it unless its needed.
Use an SDL.Music
object to load in a music file or sample and
then play it back using an internal player.
You must call SDL.init()
with the SDL.INIT_AUDIO
flag for
audio support to be available. You must also first set up some
audio parameters with a call to SDL.open_audio()
.
SDL.open_audio()
SDL.Music SDL.Music(
string
fname
)
Loads in the given music file and initializes the object ready for playback.
Supported formats are OGG, MP3, MOD, MID and WAV.
An exception is thrown if the file fails to load.
fname
The name of the music file to be loaded.
object
fade_in(int
ms
, int
|void
loops
)
Fades the music in over the given number of milliseconds. Playback is repeated loops number of times.
The fade-in will only happen on the first play, not on subsequent loops.
Likewise, calling this method on an object that is already playing has
the same effect as rewind()
: playback will start over at the
beginning but without fading in.
ms
Music fades in over this number of milliseconds.
loops
How many times the music should be repeated (looped).
Passing a value of 0
here means the music
plays once over - i.e. no repeats. A value of -1
loops the music indefinitely. This is the default if you
don't specify a value.
The SDL.Music
object.
fade_out()
, fading()
object
fade_out(int
ms
)
Fades the music out over the given number of milliseconds.
After ms milliseconds have passed, the music will be stopped;
i.e. playing()
will return 0
.
ms
The number of milliseconds it will take to fade out the music, starting from now.
The SDL.Music
object.
int
fading()
Determines the current state of fading for this SDL.Music
object.
One of the following constants:
SDL.MIX_NO_FADING
SDL.MIX_FADING_IN
SDL.MIX_FADING_OUT
fade_in()
, fade_out()
object
halt()
Stops music playback immediately, including any fader effects.
The SDL.Music
object.
object
pause()
Pauses the music playback.
It is safe to call this method when the music is already paused.
The SDL.Music
object.
resume()
, paused()
int
paused()
Determines if the music is already paused.
1
if the music is paused, otherwise 0
.
object
play(int
|void
loops
)
Starts playback. Repeats loops number of times.
loops
The number of times the music should be looped (i.e. repeated).
If loops is -1
or omitted, the music will repeat
indefinitely.
The SDL.Music
object.
int
playing()
Determines if the music is already playing.
This method will return 1
even if the music has been paused.
1
if the music is playing, otherwise 0
.
object
resume()
Resume music playback after a call to pause()
.
It is safe to call this method when the music isn't paused.
The SDL.Music
object.
pause()
, paused()
object
rewind()
Rewinds the music to the start and resumes playback.
If the music was paused at the time of this call, you will still
need to call resume()
to restart playback.
This function works only for MOD, OGG, MP3 and Native MIDI streams.
The SDL.Music
object.
float
set_volume(float
vol
)
Sets the volume for music playback.
vol
The volume to set. This is a float value from 0.0
(silent) to 1.0
(full volume). Values
above and below these limits will be clamped.
The previous volume setting.
float
volume()
The current volume setting. This is a float value from
0.0
(silent) to 1.0
(full volume).
This describes the format of the pixel data stored at the pixels field
of a SDL.Surface
. Every surface stores a PixelFormat
in the format
field.
int
SDL.PixelFormat.rloss
int
SDL.PixelFormat.gloss
int
SDL.PixelFormat.bloss
int
SDL.PixelFormat.aloss
Precision loss of each color component.
int
SDL.PixelFormat.alpha
Overall surface alpha value.
int
SDL.PixelFormat.rmask
int
SDL.PixelFormat.gmask
int
SDL.PixelFormat.bmask
int
SDL.PixelFormat.amask
Binary mask used to retrieve individual color values.
int
SDL.PixelFormat.rshift
int
SDL.PixelFormat.gshift
int
SDL.PixelFormat.bshift
int
SDL.PixelFormat.ashift
Binary left shift of each color component in the pixel value.
int
SDL.PixelFormat.bits_per_pixel
The number of bits used to represent each pixel in a surface. Usually 8, 16, 24 or 32.
int
SDL.PixelFormat.bytes_per_pixel
The number of bytes used to represent each pixel in a surface. Usually one to four.
int
SDL.PixelFormat.colorkey
Pixel value of transparent pixels.
Image.Color.Color
get_rgb(int
pixel
)
Get RGB component values from a pixel stored in this pixel format.
pixel
A pixel retrieved from a surface with this pixel format or a color
previously mapped with map_rgb()
or map_rgba()
.
A Image.Color.Color
object with the RGB components of the pixel.
map_rgb()
, map_rgba()
, get_rgba()
mapping
(string
:Image.Color.Color
|int
) get_rgba(int
pixel
)
Get RGB component values from a pixel stored in this pixel format.
pixel
A pixel retrieved from a surface with this pixel format or a color
previously mapped with map_rgb()
or map_rgba()
.
A mapping containing the RGBA components of the pixel:
| The RGB color value of the pixel. |
| The alpha value of the pixel in the range 0-255. |
map_rgb()
, map_rgba()
, get_rgb()
array
(int
) losses()
Convenience method returning the RGBA precision loss as an array.
int
map_rgb(int
r
, int
g
, int
b
)
int
map_rgb(Image.Color.Color
color
)
Maps the RGB color value to the specified pixel format and returns the pixel value as an integer.
If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.
If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).
r
g
b
The red, green and blue components specified as an integer between 0 and 255.
color
The color as represented by an Image.Color.Color
object.
A pixel value best approximating the given RGB color value for a given pixel format.
map_rgba()
, get_rgb()
, get_rgba()
int
map_rgba(int
r
, int
g
, int
b
, int
a
)
int
map_rgba(Image.Color.Color
color
, int
a
)
Maps the RGBA color value to the specified pixel format and returns the pixel value as an integer.
If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.
If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).
r
g
b
a
The red, green and blue components specified as an integer between 0 and 255.
color
The color as represented by an Image.Color.Color
object.
A pixel value best approximating the given RGB color value for a given pixel format.
map_rgb()
, get_rgb()
, get_rgba()
array
(int
) masks()
Convenience method returning the RGBA masks as an array.
array
(int
) shifts()
Convenience method returning the RGBA shifts as an array.
Used in SDL to define a rectangular area. It is sometimes also used to specify only points or sizes (i.e only one of the position and dimension is used).
(
array
)SDL.Rect()
(mapping
)SDL.Rect()
It is possible to cast a Rect object to an array or to a mapping. The array will have the values in the order x, y, w, h and the mapping will have the values associated with the corresponding names.
SDL.Rect SDL.Rect()
SDL.Rect SDL.Rect(
int(-32768..32767)
x
, int(-32768..32767)
y
)
SDL.Rect SDL.Rect(
int(-32768..32767)
x
, int(-32768..32767)
y
, int(16bit)
w
, int(16bit)
h
)
Create a new Rect
.
x
y
Optional initial values for Rect()->x
and Rect()->y
.
w
h
Optional initial values for Rect()->w
and Rect()->h
.
int(16bit)
SDL.Rect.w
int(16bit)
SDL.Rect.h
The width and height of the rectangle. Internally these are 16 bit unsigned integers. A runtime error will be generated when integer values are used that are too big.
int(-32768..32767)
SDL.Rect.x
int(-32768..32767)
SDL.Rect.y
Position of the upper-left corner of the rectangle. Internally these are 16 bit signed integers. A runtime error will be generated when integer values are used that are too big.
Surface's represent areas of "graphical" memory, memory that can
be drawn to. The video framebuffer is returned as a
SDL.Surface
by SDL.set_video_mode()
and
SDL.get_video_surface()
.
object
blit(SDL.Surface
dst
, SDL.Rect
|void
srcrect
, SDL.Rect
|void
dstrect
)
Perform a blit from this surface to the dst
surface.
dst
Destination Surface
for the blit.
srcrect
Optional source Rect
. If UNDEFINED
the entire source Surface
will be copied.
dstrect
Optional destination Rect
. Only the position fields
x and y values are used. If UNDEFINED
the
blit will be performed to position 0, 0.
SDL.Rect
SDL.Surface.clip_rect
This is the clipping rectangle as set by set_clip_rect()
.
object
convert_surface(SDL.PixelFormat
fmt
, int
flags
)
Document this function
SDL.Surface
display_format()
This function takes a surface and copies it to a new surface
of the pixel format and colors of the video framebuffer,
suitable for fast blitting onto the display surface. It calls
convert_surface()
.
If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.
If you want an alpha channel, see display_format_alpha()
.
The new surface. An error is thrown if the conversion fails.
SDL.Surface
display_format_alpha()
This function takes a surface and copies it to a new surface
of the pixel format and colors of the video framebuffer,
suitable for fast blitting onto the display surface. It calls
convert_surface()
.
If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.
This function can be used to convert a colourkey to an alpha channel, if the SDL.SRCCOLORKEY flag is set on the surface. The generated surface will then be transparent (alpha=0) where the pixels match the colourkey, and opaque (alpha=255) elsewhere.
The new surface. An error is thrown if the conversion fails.
object
fill(int
color
)
Fill the entire surface with a solid color.
fill_rect()
object
fill_rect(int
color
, SDL.Rect
dstrect
)
Fill a rectangle with a solid color.
fill()
int
SDL.Surface.flags
The following are supported in the flags field.
Surface is stored in system memory
Surface is stored in video memory
Surface uses asynchronous blits if possible.
Allows any pixel-format (Display surface).
Surface has exclusive palette.
Surface is double buffered (Display surface).
Surface is full screen (Display Sur face).
Surface has an OpenGL context (Display Surface).
Surface supports OpenGL blitting (Display Surface).
Surface is resizable (Display Surface).
Surface blit uses hardware acceleration.
Surface use colorkey blitting.
Colorkey blitting is accelerated with RLE.
Surface blit uses alpha blending.
Surface uses preallocated memory.
SDL.PixelFormat
SDL.Surface.format
The pixel format of this surface.
int
get_pixel(int
x
, int
y
)
Get the value of the specified pixel. The surface needs to be locked before this method can be used.
x
y
Pixel coordinate to get.
The value of the specified pixel.
set_pixel()
, unlock()
, lock()
int
SDL.Surface.w
int
SDL.Surface.h
The width and height of the surface in pixels.
SDL.Surface
init(int
flags
, int
width
, int
height
, int
depth
, int
Rmask
, int
Gmask
, int
Bmask
, int
Amask
)
This (re)initializes this surface using the specified parameters.
Any previously allocated data will be freed.
depth
Rmask
Gmask
Bmask
Amask
If depth
is 8 bits an empty palette is allocated for the surface,
otherwise a 'packed-pixel' SDL.PixelFormat
is created using
the [RGBA]mask's provided.
width
height
width
and height
specify the desired size of the image.
flags
flags
specifies the type of surface that should be created.
It is an OR'd combination of the following possible values:
SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.
SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).
This flag turns on colourkeying for blits from this
surface. If SDL.HWSURFACE is also specified and colourkeyed
blits are hardware-accelerated, then SDL will attempt to
place the surface in video memory. Use set_color_key()
to
set or clear this flag after surface creation.
This flag turns on alpha-blending for blits from this
surface. If SDL.HWSURFACE is also specified and alpha
blending blits are hardware-accelerated, then the surface
will be placed in video memory if possible. Use
set_alpha()
to set or clear this flag after surface
creation.
If an alpha-channel is specified (that is, if Amask is
nonzero), then the SDL.SRCALPHA flag is automatically set. You
may remove this flag by calling set_alpha()
after surface
creation.
A reference to itself.
If this method fails, the surface will become uninitialized.
set_image()
int
lock()
This methods locks the surface to allow direct access to the pixels
using the get_pixel()
and set_pixel()
methods.
Note that although all surfaces in SDL don't require locking, you still need to call this method to enable the set/get pixel methods. You should unlock the surface when you're doing modifying it.
Calling this method multiple times means that you need to call unlock an equal number of times for the surface to become unlocked.
1 for success or 0 if the surface couldn't be locked.
unlock()
, set_pixel()
, get_pixel()
object
set_alpha(int
flag
, int
alpha
)
Document this function
object
set_clip_rect(SDL.Rect
rect
)
Document this function
object
set_color_key(int
flag
, int
key
)
Set or clear the color key (aka transparent pixel) for a the surface. Also control whether RLE-accelleration is enabled or not.
flag
Document this function
SDL.Surface
set_image(Image.Image
image
, int
|void
flags
)
SDL.Surface
set_image(Image.Image
image
, Image.Image
alpha
, int
|void
flags
)
This (re)initializes this surface from the Image.Image
in
image
.
Any previously allocated data will be freed.
If initialization is successful, this surface will use RGBA8888
format. For good blitting performance, it should be converted to
the display format using display_format()
.
image
The source image.
alpha
Optional alpha channel. In Pike, the alpha channel can have different alpha values for red, green and blue. Since SDL doesn't support this, only the alpha value of the red color is used in the conversion. When this calling convention is used, the surface alpha value of image is ignored.
flags
When present this specifies the type of surface that should be created. It is an OR'd combination of the following possible values:
SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.
SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).
This flag turns on colourkeying for blits from this
surface. If SDL.HWSURFACE is also specified and colourkeyed
blits are hardware-accelerated, then SDL will attempt to
place the surface in video memory. Use set_color_key()
to
set or clear this flag after surface creation.
This flag turns on alpha-blending for blits from this
surface. If SDL.HWSURFACE is also specified and alpha
blending blits are hardware-accelerated, then the surface
will be placed in video memory if possible. Note that if
this surface has an alpha value specified, this flag is
enabled automatically. Use set_alpha()
to modify this
flag at a later point.
If this method fails, the surface will become uninitialized.
A reference to itself.
init()
int
set_pixel(int
x
, int
y
, int
pixel
)
Set the value of the specified pixel. The surface needs to be locked before this method can be used.
x
y
Pixel coordinate to modify.
pixel
Pixel value to set to the specified pixel.
A reference to the surface itself.
get_pixel()
, unlock()
, lock()
void
unlock()
Surfaces that were previously locked using lock()
must be
unlocked with unlock()
.
Surfaces should be unlocked as soon as possible.
lock()
This (read-only) class is returned by SDL.get_video_info()
. It
contains information on either the 'best' available mode (if
called before SDL.set_video_mode()
) or the current video mode.
int
SDL.VideoInfo.blit_fill
Are color fills accelerated?
int
SDL.VideoInfo.blit_hw
Are hardware to hardware blits accelerated?
int
SDL.VideoInfo.blit_hw_a
Are hardware to hardware alpha blits accelerated?
int
SDL.VideoInfo.blit_hw_cc
Are hardware to hardware colorkey blits accelerated?
int
SDL.VideoInfo.blit_sw
Are software to hardware blits accelerated?
int
SDL.VideoInfo.blit_sw_a
Are software to hardware alpha blits accelerated?
int
SDL.VideoInfo.blit_sw_cc
Are software to hardware colorkey blits accelerated?
SDL.PixelFormat
SDL.VideoInfo.format
Pixel format of the video device.
int
SDL.VideoInfo.hw_available
Is it possible to create hardware surfaces?
int
SDL.VideoInfo.video_mem
Total amount of video memory in KB.
int
SDL.VideoInfo.wm_available
Is there a window manager available
ResultSet
do_query_and(array
(string
) words
, array
(int
) field_coefficients
, array
(int
) proximity_coefficients
, int
cutoff
, function
(string
, int
, int
:string
) blobfeeder
)
words
Arrays of word ids. Note that the order is significant for the ranking.
field_coefficients
An array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:
Array | |
| body |
| Special field 0..63. |
proximity_coefficients
An array of ranking coefficients for the different proximity categories. Always has 8 elements, in the range of [0x0000-0xffff].
Array | |
| spread: 0 (Perfect hit) |
| spread: 1-5 |
| spread: 6-10 |
| spread: 11-20 |
| spread: 21-40 |
| spread: 41-80 |
| spread: 81-160 |
| spread: 161- |
blobfeeder
This function returns a Pike string containing the word hits for a
certain word. Call repeatedly until it returns 0
.
ResultSet
do_query_or(array
(string
) words
, array
(int
) field_coefficients
, array
(int
) proximity_coefficients
, int
cutoff
, function
(string
, int
, int
:string
) blobfeeder
)
words
Arrays of word ids. Note that the order is significant for the ranking.
field_coefficients
An array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:
Array | |
| body |
| Special field 0..63. |
proximity_coefficients
An array of ranking coefficients for the different proximity categories. Always has 8 elements, in the range of [0x0000-0xffff].
Array | |
| spread: 0 (Perfect hit) |
| spread: 1-5 |
| spread: 6-10 |
| spread: 11-20 |
| spread: 21-40 |
| spread: 41-80 |
| spread: 81-160 |
| spread: 161- |
blobfeeder
This function returns a Pike string containing the word hits for a
certain word. Call repeatedly until it returns 0
.
ResultSet
do_query_phrase(array
(string
) words
, array
(int
) field_coefficients
, function
(string
, int
, int
:string
) blobfeeder
)
words
Arrays of word ids. Note that the order is significant for the ranking.
field_coefficients
An array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:
Array | |
| body |
| Special field 0..63. |
blobfeeder
This function returns a Pike string containing the word hits for a
certain word. Call repeatedly until it returns 0
.
void
add(int
docid
, int
field
, int
offset
)
Search.Blob Search.Blob(
void
|string
initial
)
string
data()
int
memsize()
void
merge(string
data
)
void
remove(int
doc_id
)
void
remove_list(array
(int
) docs
)
void
add_words(int
docid
, array
(string
) words
, int
field_id
)
Add all the words in the 'words' array to the blobs
int
memsize()
Returns the in-memory size of the blobs
array
read()
returns ({ string word_id, string blob }) or ({0,0}) As a side-effect,
this function frees the blob and the word_id, so you can only read
the blobs struct once. Also, once you have called read
,
add_words
will no longer work as expected.
array
(array
(string
)) read_all_sorted()
returns ({({ string word1_id, string blob1 }),...}), sorted by word_id in octed order.
As a side-effect,
this function frees the blobs and the word_ids, so you can only read
the blobs struct once. Also, once you have called read
or read_all_sorted
,
add_words
will no longer work as expected.
void
add(int
, array
, int
, int
)
int
memsize()
Returns the in-memory size of the linkfarm
array
read()
returns ({ int word_id, Blob
b }) or 0
Search.MergeFile Search.MergeFile(
Stdio.File
_fd
)
void
merge_mergefiles(Search.MergeFile
a
, Search.MergeFile
b
)
void
write_blobs(_WhiteFish.Blobs
blobs
)
this_program
copy()
Returns a copy of this object.
Search.RankingProfile Search.RankingProfile(
void
|int
cutoff
, void
|array
(int
) proximity_ranking
, void
|Search.Database.Base
db
, void
|array
(int
)|mapping
(string
:int
) field_ranking
)
cutoff
defaults to 8, proximity_ranking
defaults to
({ 8, 7, 6, 5, 4, 3, 2, 1, })
and field_ranking
defaults to ({ 17, 0, 147 }) + allocate(62)
.
db
is only
needed if field_ranking
is provided as a mapping.
int
Search.RankingProfile.cutoff
array
(int
) Search.RankingProfile.field_ranking
array
(int
) Search.RankingProfile.proximity_ranking
A resultset is basically an array of hits from the search.
Note: inheriting this class is _not_ supported (for performance reasons)
int
sizeof( Search.ResultSet arg )
int
size()
Return the size of this resultset, in entries.
ResultSet
intersect(ResultSet
a
)
ResultSet
res = Search.ResultSet()
& a
Return a new resultset with all entries that are present in _both_ sets. Only the document_id is checked, the resulting ranking is the sum of the rankings if the two sets.
ResultSet
res = Search.ResultSet()
| a
ResultSet
res = Search.ResultSet()
+ a
ResultSet
or(ResultSet
a
)
Add the given resultsets together, to generate a resultset with both sets included. The rankings will be added if a document exists in both resultsets.
ResultSet
sub(ResultSet
a
)
ResultSet
res = Search.ResultSet()
- a
Return a new resultset with all entries in a removed from the current ResultSet.
Only the document_id is checked, the ranking is irrelevalt.
ResultSet
add_ranking(ResultSet
a
)
Return a new resultset. All entries are the same as in this set,
but if an entry exists in a
, the ranking from a
is added to
the ranking of the entry
(
array
)Search.ResultSet()
Only works when type == "array"
. Returns the resultset
data as a array.
ResultSet
dup()
Return a new resultset with the same contents as this one.
int
memsize()
Return the size of this resultset, in bytes.
int
overhead()
Return the size of the memory overhead, in bytes.
You can minimize the overhead by calling dup(), which will create a new resultset with the exact size needed.
array
(array
(int
)) slice(int
first
, int
nelems
)
Return nelems entries from the result-set, starting with first. If 'first' is outside the resultset, or nelems is 0, 0 is returned.
void
sort()
Sort this ResultSet according to ranking.
void
sort()
Sort this ResultSet according to ranking.
void
sort_docid()
Sort this ResultSet according to document id.
ResultSet
test(int
nelems
, int
start
, int
incr
)
Fills the resulttest with nelems entries, the document IDs are
strictly raising, starting with start
, ending with
start
+nelems
*incr
.
Used for debug and testing.
Base class for Search database storage abstraction implementations.
int
allocate_field_id(string
field
)
Allocate a field id.
field
The (possibly wide string) field name wanted.
An allocated numeric id, or -1 if the allocation failed.
Search.Database.Base Search.Database.Base(
string
db_url
)
Initialize the database object.
path
The URL that identifies the underlying database storage
string
get_blob(string
word
, int
num
, void
|mapping
(string
:mapping
(int
:string
)) blobcache
)
Retrieves a blob from the database.
word
The wanted word. Possibly in wide-string format. (Not UTF-8 encoded.)
num
blobcache
The blob requested, or 0 if there's no more blobs.
int
get_database_size()
Returns the size, in bytes, of the search database.
int
get_document_id(string
uri
, void
|string
language
, void
|int
do_not_create
)
Retrieve and possibly creates the document id corresponding to the given URI and language code.
uri
The URI to be retrieved or created.
language
A two letter ISO-639-1 language code, or 0 if the document is language neutral.
do_not_create
If non-zero, do not create the document.
The non-zero numeric identifier if the document identified by uri
and language_code
exists, or 0 otherwise.
int
get_field_id(string
field
, void
|int
do_not_create
)
Retrieve and possibly creates the numeric id of a field
field
The (possibly wide string) field name wanted.
do_not_create
If non-zero, do not allocate a field id for this field
An allocated numeric id, or -1 if it did not exist, or allocation failed.
mapping
(string
|int
:int
) get_language_stats()
Retrieve statistics about the number of documents in different languages.
A mapping with the the language code in the index part, and the corresponding number of documents as values.
int
get_lastmodified(Standards.URI
|string
|array
(Standards.URI
|string
) uri
, void
|string
language
)
Get last modification time for uri
, language
.
Returns modification time in seconds since
1970-01-01T00:00:00 UTC) if known,
and 0
(zero) otherwise.
mapping
(string
:string
) get_metadata(int
|Standards.URI
|string
uri
, void
|string
language
, void
|array
(string
) wanted_fields
)
Retrieve a metadata collection for a document.
uri
The URI of the resource being indexed.
language
A two letter ISO-639-1 language code, or 0 if the document is language neutral.
wanted_fields
An array containing the wanted metadata field names, or 0.
The metadata fields in wanted_fields
or all existing fields
if wanted_fields
is 0.
array
(array
) get_most_common_words(void
|int
count
)
Returns a list of the count
most common words in the database.
count
defaults to 10
.
int
get_num_deleted_documents()
Returns the number of deleted documents in the database.
int
get_num_words()
Returns the number of distinct words in the database.
mapping
get_uri_and_language(int
|array
(int
) doc_id
)
Retrieve the URI and language code associated with doc_id
.
| The URI of the document. |
| The ISO-639-1 language code of the document, or 0 if not set. |
int
get_uri_id(string
uri
, void
|int
do_not_create
)
Retrieve and possibly creates the URI id corresponding to the given URI.
uri
The URI to be retrieved or created.
do_not_create
If non-zero, do not create the URI.
The non-zero numeric identifier if uri
exists, or 0 otherwise.
void
insert_words(Standards.URI
|string
uri
, void
|string
language
, string
field
, array
(string
) words
)
Index words into the database. The data may be buffered until the
next sync
call.
uri
The URI of the resource being indexed.
language
A two letter ISO-639-1 language code, or 0 if the document is language neutral.
field
The field name for the words being indexed.
words
The words being indexed. Possibly in wide-string format. (Not UTF8 encoded.)
mapping
(string
:int
) list_fields()
Lists all fields in the search database.
A mapping with the fields in the index part, and the corresponding numeric field id as values.
void
list_url_by_prefix(string
url_prefix
, function
(string
:void
) cb
)
Calls cb
for all uri:s that match uri_prefix
.
void
remove_document(string
|Standards.URI
uri
, void
|string
language
)
Remove a document from the database.
uri
The URI of the resource being indexed.
language
A two letter ISO-639-1 language code. If zero, delete all
existing language forks with the URI of uri
.
void
remove_document_prefix(string
|Standards.URI
uri
)
Removes all documents that matches the provided uri prefix.
uri
The URI prefix of the documents to delete.
void
remove_field(string
field
)
Remove a field from the database. Also removes all stored metadata with this field, but not all indexed words using this field id.
field
The (possibly wide string) field name to be removed.
void
remove_metadata(Standards.URI
|string
uri
, void
|string
language
)
Remove all metadata for a document
uri
The URI of the resource whose metadata should be removed.
language
A two letter ISO-639-1 language code, or 0 if the document is language neutral.
void
remove_uri(string
|Standards.URI
uri
)
Remove URI from the database.
uri
The URI of the resource being removed.
void
remove_uri_prefix(string
|Standards.URI
uri
)
Remove URI prefix from the database.
uri
The URI prefix of the resource being removed.
void
safe_remove_field(string
field
)
Remove a field from the database if it isn't used by the filters. Also removes all stored metadata with this field, but not all indexed words using this field id.
field
The (possibly wide string) field name to be removed.
void
set_lastmodified(Standards.URI
|string
uri
, void
|string
language
, int
when
)
Set last modification time for uri
, language
to
mtime
(seconds since 1970-01-01T00:00:00 UTC).
void
set_metadata(Standards.URI
|string
uri
, void
|string
language
, mapping
(string
:string
) metadata
)
Set a metadata collection for a document.
uri
The URI of the resource being indexed.
language
A two letter ISO-639-1 language code, or 0 if the document is language neutral.
metadata
A collection of metadata strings to be set for a document. The strings may be wide. The "body" metadata may be cut off at 64K.
void
set_sync_callback(function
(:void
) f
)
Sets a function to be called when sync
has been completed.
void
sync()
Writes the data stored in temporary buffers to permanent storage.
Calls the function set by set_sync_callback
] when done.
constant
Search.Filter.Base.contenttypes
The MIME content types this class can filter.
.Output
filter(Standards.URI
uri
, string
|Stdio.File
data
, string
content_type
, mixed
... more
)
This object is returned from Search.Filter
plugins.
int
Search.Filter.Output.document_size
The size of the document.
mapping
(string
:string
) Search.Filter.Output.fields
Data extracted from input, grouped by type. Standard fields are
"body"
, "title"
, "description"
,
"keywords"
and "mtime"
.
Note that all field values (even "mtime"
) are strings.
void
fix_relative_links(Standards.URI
base_uri
)
Modifies relative links in links
to be relative to base_uri
.
array
(Standards.URI
|string
) Search.Filter.Output.links
All links collected from the document.
mapping
(string
:string
) Search.Filter.Output.uri_anchors
Maps un-normalized URLs to raw text, e.g.
([ "http://pike.lysator.liu.se": "Pike language" ])
.
multiset
(string
) getDefaultFields()
ParseNode
optimize(ParseNode
node
, string
|void
parentOp
)
void
remove_stop_words(ParseNode
node
, array
(string
) stop_words
)
Search.Grammar.AbstractParser Search.Grammar.AbstractParser(
void
|mapping
(string
:mixed
) options
)
options
| Either of the strings: "and", "or". If not supplied, default to "or". |
| The words that should be recognized as fields. If not supplied, it should default to Search.Grammar.getDefaultFields() |
And node.
inherit ParseNode : ParseNode
Date node.
inherit ParseNode : ParseNode
Search.Grammar.DefaultParser Search.Grammar.DefaultParser(
mapping
(string
:mixed
)|void
opt
)
protected
inherit .AbstractParser : AbstractParser
protected
inherit .Lexer : Lexer
mapping
(string
:mixed
) Search.Grammar.DefaultParser.options
ParseNode
parse(string
q
)
Or node.
inherit ParseNode : ParseNode
Abstract parse tree node.
Text node.
inherit ParseNode : ParseNode
string
|array
(array
(Token
|string
)) tokenize(string
query
)
Tokenizes a query into tokens for later use by a parser.
query
The query to tokenize.
An array containing the tokens: ({ ({ TOKEN_WORD, "foo" }), ... }) Or, in case of an error, a string with the error message.
string
extension_to_type(string
extension
)
string
filename_to_type(string
filename
)
Search.Filter.Output
filter_and_index(Search.Database.Base
db
, string
|Standards.URI
uri
, void
|string
language
, string
|Stdio.File
data
, string
content_type
, void
|mapping
headers
, void
|string
default_charset
)
void
index_document(Search.Database.Base
db
, string
|Standards.URI
uri
, void
|string
language
, mapping
fields
)
void
remove_document(Search.Database.Base
db
, string
|Standards.URI
uri
, void
|string
language
)
array
(Search.ResultSet
|array
(string
)) execute(Search.Database.Base
db
, Search.Grammar.AbstractParser
parser
, string
query
, Search.RankingProfile
ranking
, void
|array
(string
) stop_words
, void
|search_order
order
)
query
The query string entered by user.
db
The search database.
defaultRanking
Used when searching in the field "any:".
An array with three elements:
Array | |
| The ResultSet containing the hits. |
| All wanted words in the query. (I.e. not the words that were preceded by minus.) |
| All wanted globs in the query. (I.e. not the globs that were preceded by minus.) |
Virtual base class for the Search
crawler state.
void
add_uri(Standards.URI
uri
, int
recurse
, string
template
, void
|int
force
)
Add an URI to be crawled.
void
clear()
Clear and empty the entire queue.
void
clear_cache()
Clear any RAM caches.
void
clear_md5(int
... stages
)
Clear the content MD5 for all URIs at the specified stages.
void
clear_stage(int
... stages
)
Reset all URIs at the specified stage to stage 0
(zero).
int
|Standards.URI
get()
mapping
get_extra(Standards.URI
uri
)
Returns a mapping with the current state for the URI.
|
|
|
|
Currently this function always returns a
mapping(string:string)
, but this
may change to the above in the future.
array
(Standards.URI
) get_uris(void
|int
stage
)
Returns all URIs if no stage
is specified,
otherwise returns the URIs at the specified stage
.
State 0
(zero) is a special case,
and returns all URIs. This may change in
the future.
inherit Web.Crawler.Queue : Queue
int
num_with_stage(int
... stage
)
Returns the number of URIs at the specified stage(s).
void
put(string
|array
(string
)|Standards.URI
|array
(Standards.URI
) uri
)
Add one or multiple URIs to the queue.
All the URIs will be added with recursion enabled and an empty template.
void
remove_stage(int
stage
)
Remove all URIs at the specified stage.
void
remove_uri(string
|Standards.URI
uri
)
Remove an URI from the queue.
void
remove_uri_prefix(string
|Standards.URI
uri
)
Remove all URIs with the specified prefix from the queue.
void
set_md5(Standards.URI
uri
, string
md5
)
Set the content MD5 for an URI.
void
set_recurse(Standards.URI
uri
, int
recurse
)
Set the recurse mode for an URI.
void
set_stage(Standards.URI
uri
, int
stage
)
Set the stage for a single URI.
The queue stage levels.
Search
crawler state stored in a Mysql
database.
Search.Queue.MySQL Search.Queue.MySQL(
Web.Crawler.Stats
_stats
, Web.Crawler.Policy
_policy
, string
_url
, string
_table
, void
|Web.Crawler.RuleSet
_allow
, void
|Web.Crawler.RuleSet
_deny
)
_url
Sql.Sql
URL for the database to store the queue.
_table
Sql.Sql
table name to store the queue in.
If the table doesn't exist it will be created.
array
(string
) get_schemes()
Returns an array with all URI schemes currently used in the queue.
int
get_stage(Standards.URI
uri
)
Returns the current stage for the specified URI.
set_stage()
inherit .Base : Base
void
reset_stage(string
|void
uri_prefix
)
Reset the stage to 0
(zero) for all URIs with the specified
uri_prefix
. If no uri_prefix
is specified reset the stage for
all URIs.
void
flush_profile(int
p
)
Flushes the profile p
from all ProfileCache
objects
obtained with get_profile_cache
.
ProfileCache
get_profile_cache(string
db_name
)
Returns a ProfileCache
for the profiles stored
in the database db_name
.
mapping
get_profile_storage(string
db_name
)
Returns a profile storage mapping, which will be shared
between all callers with the same db_name
given.
Scheduler
get_scheduler(string
db_name
)
Returns a scheduler for the given profile database.
string
normalize(string
in
)
Normalize the input string. Performs unicode NFKD normalization and then lowercases the whole string
array
(string
) tokenize(string
in
)
Tokenize the input string (Note: You should first call normalize on it)
array
(string
) tokenize_and_normalize(string
what
)
This can be optimized quite significantly when compared to tokenize( normalize( x ) ) in the future, currently it's not all that much faster, but still faster.
int
add_program_name(int
code
, string
name
)
Search.Utils.Logger Search.Utils.Logger(
Sql.Sql
db_object
, int
profile
, int
stderr_logging
)
Search.Utils.Logger Search.Utils.Logger(
string
db_url
, int
profile
, int
stderr_logging
)
array
(array
(string
|int
)) get_log(int
profile
, array
(string
) types
, int
from
, int
to
)
void
log_error(int
code
, void
|string
extra
, void
|int
log_profile
)
void
log_event(int
code
, string
type
, void
|string
extra
, void
|int
log_profile
)
void
log_notice(int
code
, void
|string
extra
, void
|int
log_profile
)
void
log_warning(int
code
, void
|string
extra
, void
|int
log_profile
)
Search.Utils.ProfileCache Search.Utils.ProfileCache(
string
db_name
)
string
Search.Utils.ProfileCache.db_name
void
flush_cache()
Empty the whole cache.
void
flush_profile(int
p
)
Flushes profile entry p
from the profile cache.
int
get_db_profile_number(string
name
)
Returns the profile number for the given database profile.
ProfileEntry
get_profile_entry(string
db_name
, void
|string
query_name
)
Returns a ProfileEntry
object with the states needed for
commiting searches in the database profile db_name
with
the rules from query profile query_name
.
int
get_query_profile_number(string
name
)
Returns the profile number for the given query profile.
mapping
get_value_mapping(int
profile
)
Returns the value mapping for the given profile.
array
(string
) list_db_profiles()
Returns a list of available database profiles.
array
(string
) list_query_profiles()
Returns a list of available query profiles.
int(-1..1)
up_to_datep(int
profile_id
)
Checks if the profile profile_id
has been changed, and clears
related caches if so.
| The profile is deleted. |
| The profile is not up to date. |
| The profile is up to date. |
A result entry from the ProfileCache
.
bool
check_timeout()
Checks if it is time to check if the profile values are to old.
Search.Utils.ProfileEntry Search.Utils.ProfileEntry(
int
database_profile_id
, int
query_profile_id
, ProfileCache
cache
)
cache
The parent cache object.
Search.Database.MySQL
get_database()
Returns a cached search database for the current database profile.
mixed
get_database_value(string
index
)
Returns the database profile value index
.
mixed
get_query_value(string
index
)
Returns the query profile value index
.
Search.RankingProfile
get_ranking()
Returns a cached ranking profile for the current database and query profile.
array
(string
) get_stop_words()
Returns a cached array of stop words for the current query profile.
void
new_entry(int
latency
, array
(int
) profiles
)
Call this method to indicate that a new entry has been added
to the queue. The scheduler will delay indexing with at most
latency
minutes.
Serialization interface.
This module contains APIs to simplify serialization and deserialization of objects.
serialize()
, deserialize()
void
deserialize(object
o
, function
(function
(mixed
:void
), string
, type
:void
) deserializer
)
Call lfun::_deserialize()
in o
.
serialize()
, lfun::_deserialize()
,
Serializable()->_deserialize()
void
serialize(object
o
, function
(mixed
, string
, type
:void
) serializer
)
Call lfun::_serialize()
in o
.
deserialize()
, lfun::_serialize()
,
Serializable()->_serialize()
Simple base for an object that can be serialized by encode_value. Also supports decoding.
Uses Serializable
as it's base.
Simply inherit this class in the classes you want to have encoded and decoded.
Note that it's not automatically recursive, objects assigned to variables in this object have to be Encodeable on their own for encode to work.
When decoding only variables that existed at the time the object was encoded are assigned, that is, if the class now has more variables they new variables will be set to 0.
Serializer.Encodeable decode_value(string(8bit) data)
Callback for decoding the object. Sets variables in the object from the values in the mapping.
Called automatically by decode_value
, not normally called
manually.
string(8bit) encode_value(Serializer.Encodeable data)
Callback for encoding the object. Returns a mapping from variable name to value.
Called automatically by encode_value
, not normally called
manually.
inherit Serializable : Serializable
The base class for serializable objects.
Inherit this class in classes that need to be serializable.
Serializer.serialize()
, Serializer.deserialize()
protected
void
_deserialize(object
o
, function
(function
(mixed
:void
), string
, type
:void
) deserializer
)
Dispatch function for deserialization.
o
Object to serialize. Always a context of the current object.
deserializer
Function to typically be called once for every variable in the inheriting class.
This function calls _deserialize_variable()
once
for every variable in the inheriting class, which
in turn will call deserializer
with the arguments:
The setter for the variable.
The name of the variable.
The declared type of the variable.
The symbols will be listed in the order they were defined in the class.
This function is typically called via Serializer.deserialize()
.
Serializer.deserialize()
, _deserialize_variable()
,
_serialize()
, Builtin.Setter
protected
void
_deserialize_variable(function
(function
(mixed
:void
), string
, type
:void
) deserializer
, function
(mixed
:void
) setter
, string
symbol
, type
symbol_type
)
Default deserialization function for variables.
deserializer
Function to be called in turn.
setter
Function that sets the value of the variable.
symbol
Variable name.
symbol_type
Type of the variable.
This function is typically called from _deserialize()
, and does
something like:
if (object_typep(symbol_type)) {
program p = program_from_type(symbol_type);
if (p && !needs_parent(p) && is_deserializable(p)) {
object value = p();
setter(value);
Serializer.deserialize(value, deserializer);
return;
}
}
deserializer(setter, symbol, symbol_type);
The above takes care of the most common cases, but
Does not support anonymous object types.
Does not support objects needing a parent.
Does not support non-serializable objects.
Selects one of the object types in case of a complex
symbol_type
. The selected type is NOT deterministic
in case there are multiple choices that satisfy the above.
Is likely to throw errors if p() requires arguments.
These issues can all be solved by overloading this function.
_deserialize()
, _serialize_variable()
, Builtin.Setter
protected
void
_serialize(object
o
, function
(mixed
, string
, type
:void
) serializer
)
Dispatch function for serialization.
o
Object to serialize. Always a context of the current object.
serializer
Function to typically be called once for every variable in the inheriting class.
This function calls _serialize_variable()
once
for every variable in the inheriting class, which
in turn will call serializer
with the arguments:
The value of the variable.
The name of the variable.
The declared type of the variable.
The symbols will be listed in the order they were defined in the class.
This function is typically called via Serializer.serialize()
.
Serializer.serialize()
, _serialize_variable()
,
_deserialize()
protected
void
_serialize_variable(function
(mixed
, string
, type
:void
) serializer
, mixed
value
, string
symbol
, type
symbol_type
)
Default serialization function for variables.
serializer
Function to be called in turn.
value
Value of the variable.
symbol
Variable name.
symbol_type
Type of the variable.
This function is typically called from _serialize()
, and just does
serializer(value, symbol, symbol_type);
It is provided for overloading for eg filtering or validation purposes.
_serialize()
, _deserialize_variable()
Module implementing sending to and from nonblocking streams and other sources.
Most useful when implementing sending of data from strings, files and other sources to a network connection. The module also supports generic bandwidth throttling.
Multiple Shuffler
object can be created, each optionally with
their own backend.
This makes it easier to use more than one CPU for pure data transmission, just have multiple backends each in their own thread, with their own shuffle object.
constant
Shuffler.INITIAL
constant
Shuffler.RUNNING
constant
Shuffler.PAUSED
constant
Shuffler.DONE
constant
Shuffler.WRITE_ERROR
constant
Shuffler.READ_ERROR
constant
Shuffler.USER_ABORT
The state of an individual Shuffle
object.
This class contains the state for one ongoing data
shuffling operation. To create a Shuffle
instance, use the
Shuffler()->shuffle
method.
void
add_source(mixed
source
, int
|void
start
, int
|void
length
)
Add a new source to the list of data sources. The data from the sources will be sent in order.
If start and length are not specified, the whole source will be
sent, if start but not length is specified, the whole source,
excluding the first start
bytes will be sent.
Currently supported sources
An ordinary 8-bit wide pike string.
An initialized instance of the System.Memory class.
Stdio.File instance pointing to a normal file.
Stdio.File instance pointing to a stream of some kind (network socket, named pipe, stdin etc). Blocking or nonblocking.
An object implementing the callback based reading (set_read_callback and set_close_callback).
Shuffler.Shuffle Shuffler.Shuffle(
object
fd
, object
shuffler
, mixed
throttler
, mixed
backend
)
This object is normally not created directly, instead use
Shuffler()->shuffle
void
pause()
Temporarily pause all data transmission
int
sent_data()
Returns the amount of data that has been sent so far.
void
set_done_callback(function
(Shuffle
, int
:void
) cb
)
Sets the done callback. This function will be called when all sources have been processed, or if an error occurs.
void
set_request_arg(mixed
arg
)
Sets the extra argument sent to Throttler()->request()
and
Throttler()->give_back
.
void
set_throttler(Throttler
t
)
Calling this function overrides the Shuffler
global throttler.
Shuffler
Shuffler.Shuffle.shuffler
The Shuffler
that owns this Shuffle
object
void
start()
Start sending data from the sources.
int
state()
Returns the current state of the shuffler.
This is one of the following:
INITIAL
,
RUNNING
,
PAUSED
,
DONE
,
WRITE_ERROR
,
READ_ERROR
and
USER_ABORT
void
stop()
Stop all data transmission, and then call the done callback
Throttler
Shuffler.Shuffle.throttler
The Throttler
that is associated with this Shuffle
object,
if any.
A data shuffler. An instance of this class handles a list of
Shuffle
objects. Each Shuffle
object can send data from one
or more sources to a destination in the background.
void
pause()
Pause all Shuffle
objects associated with this Shuffler
void
set_backend(Pike.Backend
b
)
Set the backend that will be used by all Shuffle
objects created
from this shuffler.
void
set_throttler(Throttler
t
)
Set the throttler that will be used in all Shuffle
objects
created from this shuffler, unless overridden in the
Shuffle
objects.
Shuffle
shuffle(Stdio.NonblockingStream
destination
)
Create a new Shuffle
object.
The destination has to support nonblocking I/O.
void
start()
Unpause all Shuffle
objects associated with this Shuffler
This is an interface that all Throttler
s must implement.
It's not an actual class in this module.
void
give_back(Shuffle
shuffle
, int
amount
)
This function will be called by the Shuffle
object to report
that some data assigned to it by this throttler was unusued, and
can be given to another Shuffle
object instead.
void
request(Shuffle
shuffle
, int
amount
, function
(int
:void
) callback
)
This function is called when the Shuffle
wants to send some
data to a client.
When data can be sent, the callback
function should be called
with the amount of data that can be sent as the argument.
This class implements URI parsing and resolving of relative references to absolute form, as defined in RFC 2396 and RFC 3986.
Standards.URI()
->X = value
Standards.URI()
[ property
] = value
Assign a new value to a property of URI
property
When any of the following properties are used, properties that depend on them are recalculated: user, password, host, port, authority, base_uri.
value
The value to assign to property
int
res = Standards.URI()
== something
Compare this URI to something, in a canonical way.
something
Compare the URI to this
void
add_query_variable(string
name
, string
value
)
Adds the provided query variable to the already existing ones. Will overwrite an existing variable with the same name.
void
add_query_variables(mapping
(string
:string
) vars
)
Appends the provided set of query variables with the already existing ones. Will overwrite all existing variables with the same names.
string
Standards.URI.authority
Authority component of URI (formerly called net_loc, from RFC 2396 known as authority)
this_program
Standards.URI.base_uri
The base URI object, if present
(
string
)Standards.URI()
(mapping
)Standards.URI()
When cast to string, return the URI (in a canonicalized form). When cast to mapping, return a mapping with scheme, authority, user, password, host, port, path, query, fragment, raw_uri, base_uri as documented above.
Standards.URI Standards.URI(
URI
uri
)
Standards.URI Standards.URI(
URI
uri
, URI
base_uri
)
Standards.URI Standards.URI(
URI
uri
, string
base_uri
)
Standards.URI Standards.URI(
string
uri
)
Standards.URI Standards.URI(
string
uri
, URI
base_uri
)
Standards.URI Standards.URI(
string
uri
, string
base_uri
)
base_uri
When supplied, will root the URI a the given location. This is needed to correctly verify relative URIs, but may be left out otherwise. If left out, and uri is a relative URI, an error is thrown.
uri
When uri is another URI object, the created URI will inherit all properties of the supplied uri except, of course, for its base_uri.
An exception is thrown if the uri
is a relative URI or only a
fragment, and missing a base_uri
.
string
Standards.URI.fragment
The fragment part of URI. May be 0 if not present.
string
get_http_path_query()
Return the path and query part of the URI, coded according to RFC 1738.
string
get_http_query()
Return the query part, coded according to RFC 1738, or zero.
string
get_path_query()
Returns path and query part of the URI if present.
mapping
(string
:string
) get_query_variables()
Returns the query variables as a mapping(string:string)
.
string
Standards.URI.host
string
Standards.URI.user
string
Standards.URI.password
Certain classes of URI (e.g. URL) may have these defined
string
Standards.URI.path
Path component of URI. May be empty, but not undefined.
int
Standards.URI.port
If no port number is present in URI, but the scheme used has a default port number, this number is put here.
string
Standards.URI.query
Query component of URI. May be 0 if not present.
void
reparse_uri()
void
reparse_uri(URI
base_uri
)
void
reparse_uri(string
base_uri
)
Reparse the URI with respect to a new base URI. If no base_uri was supplied, the old base_uri is thrown away. The resolving is performed according to the guidelines outlined by RFC 2396, Uniform Resource Identifiers (URI): Generic Syntax.
base_uri
Set the new base URI to this.
An exception is thrown if the uri
is a relative URI or only a
fragment, and missing a base_uri
.
string
Standards.URI.scheme
Scheme component of URI
void
set_query_variables(mapping
(string
:string
) vars
)
Sets the query variables from the provided mapping.
string
decode_der_oid(string
der_oid
)
Convenience function to convert a DER/BER encoded oid (object identifier) to the human readable dotted-decimal form.
encode_der_oid
string
encode_der_oid(string
dotted_decimal
)
Convenience function to convert an oid (object identifier) on
dotted-decimal form (e.g. "1.3.6.1.4.1.1466.115.121.1.38"
)
to its DER (and hence also BER) encoded form.
decode_der_oid
Decodes a DER object.
.Types.Object
der_decode(Stdio.Buffer
data
, mapping
(int
:program
) types
)
data
An instance of Stdio.Buffer containing the DER encoded data.
types
A mapping from combined tag numbers to classes from or derived
from Standards.ASN1.Types
. Combined tag numbers may be
generated using Standards.ASN1.Types.make_combined_tag
.
An object from Standards.ASN1.Types
or, either
Standards.ASN1.Decode.Primitive
or
Standards.ASN1.Decode.constructed
, if the type is unknown.
Throws an exception if the data could not be decoded.
Handling of implicit and explicit ASN.1 tagging, as well as other context dependence, is next to non_existant.
.Types.Object
secure_der_decode(string(8bit)
data
, mapping
(int
:program
)|void
types
)
Works just like simple_der_decode
, except it will return
0
if there is trailing data in the provided ASN.1 data
.
simple_der_decode
.Types.Object
simple_der_decode(string(8bit)
data
, mapping
(int
:program
)|void
types
)
decode a DER encoded object using universal data types
data
a DER encoded object
types
An optional set of application-specific types. Should map
combined tag numbers to classes from or derived from
Standards.ASN1.Types
. Combined tag numbers may be generated
using Standards.ASN1.Types.make_combined_tag
. This set is
used to extend universal_types
.
an object from Standards.ASN1.Types
or
either Standards.ASN1.Decode.Primitive
or
Standards.ASN1.Decode.Constructed
if the type is unknown.
Constructed type
int
Standards.ASN1.Decode.Constructed.cls
int
Standards.ASN1.Decode.Constructed.tag
string(8bit)
Standards.ASN1.Decode.Constructed.raw
array
(.Types.Object
) Standards.ASN1.Decode.Constructed.elements
Standards.ASN1.Decode.Constructed Standards.ASN1.Decode.Constructed(
int
cls
, int
tag
, string(8bit)
raw
, array
(.Types.Object
) elements
)
string(8bit)
get_der_content()
Get raw encoded contents of object
inherit .Types.Compound : Compound
Primitive unconstructed ASN1 data type.
int
Standards.ASN1.Decode.Primitive.cls
int
Standards.ASN1.Decode.Primitive.tag
string(8bit)
Standards.ASN1.Decode.Primitive.raw
Standards.ASN1.Decode.Primitive Standards.ASN1.Decode.Primitive(
int
cls
, int
tag
, string(8bit)
raw
)
string(8bit)
get_der_content()
Get raw encoded contents of object
inherit Types.Object : Object
Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)
MetaExplicit
Standards.ASN1.Types.TaggedType0
MetaExplicit
Standards.ASN1.Types.TaggedType1
MetaExplicit
Standards.ASN1.Types.TaggedType2
MetaExplicit
Standards.ASN1.Types.TaggedType3
Some common explicit tags for convenience.
These are typically used to indicate which of several optional fields are present.
Eg RFC 5915 section 3:
ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), privateKey OCTET STRING, parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, publicKey [1] BIT STRING OPTIONAL }
The presence of the fields parameters and publicKey above are indicated with
TaggedType0
andTaggedType1
respectively.
bool
asn1_IA5_valid(string
s
)
bool
asn1_bmp_valid(string
s
)
bool
asn1_broken_teletex_valid(string
s
)
bool
asn1_printable_valid(string
s
)
Checks if a Pike string can be encoded as a PrintableString
.
int(0..0)
asn1_universal_valid(string
s
)
int(1..1)
asn1_utf8_valid(string
s
)
Checks if a Pike string can be encoded with UTF8. That is always the case...
int(2bit)
extract_cls(int
i
)
Extract ASN1 type class from a combined tag.
make_combined_tag
int
extract_tag(int
i
)
Extract ASN1 type tag from a combined tag.
make_combined_tag
int
make_combined_tag(int
cls
, int
tag
)
Combines tag and class to a single integer, for internal uses.
cls
ASN1 type class (0..3).
tag
ASN1 type tag (1..).
The combined tag.
extract_tag
, extract_cls
BMP String object
Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 2 octets per character.
FIXME: The encoding is very likely UCS-2, but that's not yet verified.
inherit OctetString : OctetString
Bit string object
inherit Object : Object
this_program
set_from_ascii(string(8bit)
s
)
Set the bitstring value as a string with "1"
and
"0"
.
this_program
set_length(int
len
)
Sets the length of the bit string to len
number of bits. Will
only work correctly on strings longer than len
bits.
string(8bit)
Standards.ASN1.Types.BitString.value
value of object
boolean object
inherit Object : Object
int
Standards.ASN1.Types.Boolean.value
value of object
(broken) TeletexString object
Encodes and decodes latin1, but labels it TeletexString, as is common in many broken programs (e.g. Netscape 4.0X).
inherit String : String
Compound object primitive
array
(Object
) Standards.ASN1.Types.Compound.elements
Contents of compound object.
inherit Object : Object
Enumerated object
inherit Integer : Integer
int
get_posix()
inherit UTC : UTC
variant
this_program
set_posix(Calendar.ISO_UTC.Second
second
)
IA5 String object
Character set: ASCII. Fixed width encoding with 1 octet per character.
inherit String : String
Object identifier object
this_program
append(int
... args
)
Returns a new Identifier
object with args
appended to the
ID path.
array
(int
) Standards.ASN1.Types.Identifier.id
value of object
inherit Object : Object
Integer object All integers are represented as bignums, for simplicity
inherit Object : Object
Gmp.mpz
Standards.ASN1.Types.Integer.value
value of object
Meta-instances handle a particular explicit tag and set of types. Once cloned this object works as a factory for Compound objects with the cls and tag that the meta object was initialized with.
MetaExplicit m = MetaExplicit(1,2); Compound c = m(Integer(3));
Standards.ASN1.Types.MetaExplicit Standards.ASN1.Types.MetaExplicit(
int
cls
, int
tag
, mapping
(int
:program
)|void
types
)
Null object
inherit Object : Object
Generic, abstract base class for ASN1 data types.
int
get_cls()
Get the class of this object.
The class of this object.
int
get_combined_tag()
Get the combined tag (tag + class) for this object.
the combined tag header
string(8bit)
get_der()
Get the DER encoded version of this object.
DER encoded representation of this object.
string(8bit)
get_der_content()
Return the DER payload.
int
get_tag()
Get the tag for this object.
The tag for this object.
Octet string object
inherit String : String
PrintableString object
inherit String : String
Sequence object
inherit Compound : Compound
Set object
inherit Compound : Compound
string object primitive
inherit Object : Object
string
Standards.ASN1.Types.String.value
value of object
This used to be a string encoded with the T.61 character coding, and has been obsolete since the early 1990:s.
BrokenTeletexString
inherit BrokenTeletexString : BrokenTeletexString
UTCTime
RFC 2459 4.1.2.5.1
int
get_posix()
inherit String : String
variant
this_program
set_posix(Calendar.ISO_UTC.Second
second
)
UTF8 string object
Character set: ISO/IEC 10646-1 (compatible with Unicode).
Variable width encoding, see rfc2279.
inherit String : String
Universal String object
Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.
The encoding is very likely UCS-4, but that's not yet verified.
inherit OctetString : OctetString
inherit String : String
Tools for handling the BSON structured data format. See http://www.bsonspec.org/.
object
Standards.BSON.MaxKey
object
Standards.BSON.MinKey
mixed
decode(string
bson
)
Decode a BSON formatted document string into a native Pike data structure.
array
decode_array(string
bsonarray
)
Decode a BSON formatted string containing multiple data structures
string
encode(array
|mapping
m
, int
|void
query_mode
)
Encode a data structure as a BSON document.
query_mode
if set to true, encoding will allow "$" and "." in key names, which would normally be disallowed.
string
encode_array(array
(mapping
) documents
)
Encode an array of data structures as a BSON formatted string
Standards.BSON.Binary Standards.BSON.Binary(
string
_data
, int
|void
_subtype
)
Standards.BSON.Javascript Standards.BSON.Javascript(
string
_data
)
Standards.BSON.ObjectId Standards.BSON.ObjectId(
string
|void
_id
)
Standards.BSON.Regex Standards.BSON.Regex(
string
_regex
, string
_options
)
Standards.BSON.Symbol Standards.BSON.Symbol(
string
_data
)
Standards.BSON.Timestamp Standards.BSON.Timestamp(
int
|void
_timestamp
)
This module implements EXIF (Exchangeable image file format for Digital Still Cameras) 2.2 parsing.
mapping
(string
:mixed
) get_properties(Stdio.File
file
, void
|mapping
tags
)
Parses and returns all EXIF properties.
file
A JFIF file positioned at the start.
tags
An optional list of tags to process. If given, all unknown tags will be ignored.
A mapping with all found EXIF properties.
This module implements the FIPS10-4 standard for short-form codes of "Countries, Dependencies, Areas of Special Sovereignty, and Their Principal Administrative Divisions."
This is a list of two-letter country codes used by the US government until 2008-10-02, when GENC, based on ISO 3166 replaced it as the prefered standard. The subdivisions are named using the main region name followed by two digits.
This list is similar to, but not entirely compatible with, ISO-3166 alpha-2.
array
(string
) division_code_to_line(string
code
)
Convert a division code to the information about the division. As an example division_code_to_line("sw16") would return
({ "SW","SW16","Ostergotlands Lan","province/lan"})
Array |
|
|
|
|
string
division_code_to_name(string
code
)
Similar to division_code_to_line()
, but only returns the name
array
(string
) division_guess_to_codes(string
code
)
Return an array of possible division codes given a division name.
Array | ||||||
|
|
array
(array
(string
)) division_guess_to_lines(string
name
)
Return an array of possible divisions given a division name.
Array | ||||||
|
|
array
(string
) division_name_to_line(string
name
)
string
division_name_to_code(string
code
)
Lookup a division by name.
These aren't really all that useful, since there might very well be multiple divisions with the same name.
division_guess_to_lines()
and division_guess_to_codes()
are
more useful.
string
region_code_to_name(string
code
)
Convert a region (country etc) code to the name of the region. As an example, region_code_to_name("se") would return "SEYCHELLES".
string
region_name_to_code(string
code
)
The reverse of region_code_to_name()
,
region_name_to_code("Sweden") would return "SW".
array
(string
) region_to_division_codes(string
region
)
Given a region (country etc) return all divisions codes in that region
array
(array
(string
)) region_to_divisions(string
region
)
Given a region (country etc) return all divisions in that region
Array | ||||||
|
|
ID3 decoder/encoder. Supports versions 1.0, 1.1, 2.2-2.4. For more info see http://www.id3.org
Note that this implementation is far from complete and that interface changes might be necessary during the implementation of the full standard.
string
decode_string(string
in
, int
type
)
Decodes the string in
from the type
, according to
ID3v2.4.0-structure section 4, into a wide string.
encode_string
array
(string
|int
) encode_string(string
in
)
Encodes the string in
to an int-string pair, where the
integer is the encoding mode, according to ID3v2.4.0-structure,
and the string is the encoded string. This function tries to
minimize the size of the encoded string by selecting the most
apropriate encoding method.
decode_string
, encode_strings
array
(string
|int
) encode_strings(array
(string
) in
)
Encodes several strings in the same way as encode_string
, but
encodes all the strings with the same method, selected as in
encode_string
. The first element in the resulting array is the
selected method, while the following elements are the encoded strings.
decode_string
, encode_string
array
(int
) int_to_synchsafe(int
in
, void
|int
no_bytes
)
Encodes a integer to a synchsafe integer according to ID3v2.4.0-structure section 6.2.
synchsafe_to_int
string
resynchronise(string
in
)
Reverses the effects of unsyncronisation done according to ID3v2.4.0-structure section 6.1.
unsynchronise
int
synchsafe_to_int(array
(int
) bytes
)
Decodes a synchsafe integer, generated according to ID3v2.4.0-structure section 6.2.
int_to_synchsafe
string
unsynchronise(string
in
)
Unsynchronises the string according to ID3v2.4.0-structure section 6.1.
resynchronise
A wrapper around a Stdio.File
object that provides a read
limit capability.
Stdio.File
Standards.ID3.Buffer.buffer
int
bytes_left()
The number of bytes left before reaching the limit set by
set_limit
.
Standards.ID3.Buffer Standards.ID3.Buffer(
Stdio.File
buffer
)
string
peek()
Preview the next byte. Technically it is read from the encapsulated buffer and put locally to avoid seeking.
string
read(int
bytes
)
Read bytes
bytes from the buffer. Throw an exception
if bytes
is bigger than the number of bytes left in the
buffer before reaching the limit set by set_limit
.
void
set_limit(int
bytes
)
Set an artificial EOF bytes
bytes further into the
buffer.
Standards.ID3.ExtendedHeader Standards.ID3.ExtendedHeader(
void
|Buffer
buffer
)
void
decode(Buffer
buffer
)
string
encode()
Manages the common frame information.
Standards.ID3.Frame Standards.ID3.Frame(
string
|Buffer
in
, TagHeader
thd
)
Abstract class for frame data.
bool
changed()
Is the content altered?
Standards.ID3.FrameData Standards.ID3.FrameData(
void
|string
data
)
This is a ID3 tag super object, which encapsulates all versions ID3 tags. This is useful if you are only interested in the metadata of a file, and care not about how it is stored or have no interest in changing the data.
Version 1 tag is searched only if version 2 isn't found.
Tagv2
, Tagv1
array
indices( Standards.ID3.Tag arg )
Indices will return the indices of the tag object.
array
values( Standards.ID3.Tag arg )
Values will return the values of the tag object.
mixed
res = Standards.ID3.Tag()
[ index
]
mixed
res = Standards.ID3.Tag()
->X
The index operators are overloaded to index the encapsulated Tagv1 or Tagv2 object.
Standards.ID3.Tag Standards.ID3.Tag(
Stdio.File
fd
)
The file object fd
is searched for version 2 tags, and if
not found, version 1 tags.
If no tag was found in the file an error is thrown.
mapping
(string
:string
) friendly_values()
Returns tag values in a mapping. Only tag values that exists in ID3v1.1 is used. Nonexisting or undefined values will not appear in the mapping.
| Takes its value from TPE1 or TP1 frames. |
| Takes its value from TALB or TAL frames. |
| Takes its value from TIT2 or TT2 frames. |
| Takes its value from TCON or TCM frames. |
| Takes its value from TYER or TYE frames. |
| Takes its value from TRCK or TRK frames.
The string may be either in the |
constant
Standards.ID3.Tag.version
The version of the encapsulated tag in the form "%d.%d.%d"
.
Represents an ID3v2 header.
Standards.ID3.TagHeader Standards.ID3.TagHeader(
void
|Buffer
buffer
)
void
decode(Buffer
buffer
)
Decode a tag header from buffer
and store its data in
this object.
string
encode()
Encode the data in this tag and return as a string.
bool
set_flag_unsynchronisation(array
(Frame
) frames
)
Should the unsynchronisation flag be set or not?
ID3 version 1.0 or 1.1 tag. This is really a clumsy way of reading ID3v1 tags, but it has the same interface as the v2 reader.
ID3 version 2 (2.2, 2.3, 2.4) Tags
Standards.ID3.Tagv2 Standards.ID3.Tagv2(
void
|Buffer
|Stdio.File
buffer
, void
|bool
_best_effort
)
This module implements various algorithms specified by the Internationalizing Domain Names in Applications (IDNA) memo by the Internet Engineering Task Force (IETF), see ftp://ftp.rfc-editor.org/in-notes/rfc3490.txt.
object
Standards.IDNA.Punycode
Punycode transcoder, see
ftp://ftp.rfc-editor.org/in-notes/rfc3492.txt.
Punycode is used by to_ascii
as an "ASCII Compatible Encoding" when
needed.
string
nameprep(string
s
, bool
|void
allow_unassigned
)
Prepare a Unicode string for ACE transcoding. Used by to_ascii
.
Nameprep is a profile of Stringprep, which is described in RFC 3454.
s
The string to prep.
allow_unassigned
Set this flag the the string to transform is a "query string", and not a "stored string". See RFC 3454.
string
to_ascii(string
s
, bool
|void
allow_unassigned
, bool
|void
use_std3_ascii_rules
)
The to_ascii operation takes a sequence of Unicode code points that make up one label and transforms it into a sequence of code points in the ASCII range (0..7F). If to_ascci succeeds, the original sequence and the resulting sequence are equivalent labels.
s
The sequence of Unicode code points to transform.
allow_unassigned
Set this flag if the the string to transform is a "query string", and not a "stored string". See RFC 3454.
use_std3_ascii_rules
Set this flag to enforce the restrictions on ASCII characters in host names imposed by STD3.
string
to_unicode(string
s
)
The to_unicode operation takes a sequence of Unicode code points that make up one label and returns a sequence of Unicode code points. If the input sequence is a label in ACE form, then the result is an equivalent internationalized label that is not in ACE form, otherwise the original sequence is returned unaltered.
s
The sequence of Unicode code points to transform.
string
zone_to_ascii(string
s
, bool
|void
allow_unassigned
, bool
|void
use_std3_ascii_rules
)
Takes a sequence of labels separated by '.' and applies
to_ascii
on each.
string
zone_to_unicode(string
s
)
Takes a sequence of labels separated by '.' and applies
to_unicode
on each.
IPTC Information Interchange Model data (aka "IPTC header") extraction.
mapping
get_information(Stdio.File
fd
)
Get IPTC information from an open file.
Supported embedding formats are:
PhotoShop Document (aka PSD).
Postscript and Embedded Postscript.
Joint Picture Experts Group (aka JPEG).
Returns a mapping containing any found IPTC IIM data.
string
convert_b_to_t(string
code
)
Converts an ISO 639-2/B code to an ISO 639-2/T code.
string
convert_t_to_b(string
code
)
Converts an ISO 639-2/T code to an ISO 639-2/B code.
string
get_language(string
code
)
Look up the language name given an ISO 639-2 code in lower case. It will first be looked up in the ISO 639-2/T table and then in ISO 639-2/B if the first lookup failed. Returns zero typed zero on failure.
string
get_language_b(string
code
)
Look up the language name given an ISO 639-2/B code in lower case. Returns zero typed zero on failure.
string
get_language_t(string
code
)
Look up the language name given an ISO 639-2/T code in lower case. Returns zero typed zero on failure.
mapping
(string
:string
) list_639_1()
Return a mapping from ISO 639-1 code to ISO 639-2/T code.
mapping
(string
:string
) list_languages()
Return a mapping from ISO 639-2/T + ISO 639-2/B codes to language names.
mapping
(string
:string
) list_languages_b()
Return a mapping from ISO 639-2/B codes to language names.
mapping
(string
:string
) list_languages_t()
Return a mapping from ISO 639-2/T codes to language names.
string
map_639_1(string
code
)
Look up the ISO 639-2/T code given an ISO 639-1 code in lower case.
string
map_to_639_1(string
code
)
Look up the ISO 639-1 code given an ISO 639-2/T code in lower case.
Tools for handling the JSON structured data format. See http://www.json.org/ and RFC 4627.
constant
Standards.JSON.ASCII_ONLY
constant
Standards.JSON.HUMAN_READABLE
constant
Standards.JSON.PIKE_CANONICAL
Bit field flags for use with encode
:
Use \uxxxx
escapes for all non-ascii characters and DEL
(U+007f). The default is to escape only the characters that must
be escaped. The flag value is 1.
Characters above U+FFFF are encoded using escaped surrogate pairs, as per RFC 4627.
Pretty print with indentation to make the result easier on human eyes. The default is to use no extra whitespace at all. The flag value is 2.
Make the output canonical, so that the same value always
generates the same char-by-char equal string. In practice this
means that mapping elements are sorted on their indices. Note
that the other flags take precedence, so e.g. the canonical form
with HUMAN_READABLE
is not the same as the canonical form
without it. The flag value is 4.
This canonical form is stable for the encode
function,
providing floats aren't used (their formatting is currently
affected by float size and libc formatting code). In the future
there may be a standardized canonical form which quite likely
will be different from this one. In that case a separate flag
has to be added so this one doesn't change - hence the name
PIKE_CANONICAL
.
array
|mapping
|string
|float
|int
|object
decode(string
s
)
Decodes a JSON string.
Throws an exception in case the data contained in s
is not valid
JSON.
array
|mapping
|string
|float
|int
|object
decode_utf8(string
s
)
Decodes an utf8 encoded JSON string.
Should give the same result as Standards.JSON.decode(utf8_to_string(s))
.
Throws an exception in case the data contained in s
is not valid
JSON.
string
encode(int
|float
|string
|array
|mapping
|object
val
, void
|int
flags
, void
|function
(:void
)|object
|program
|string
callback
)
Encodes a value to a JSON string.
val
The value to encode. It can contain integers, floats (except the
special numbers NaN and infinity), strings, arrays, mappings
with string indices, and the special object values null
,
true
and false
defined in this module (or really any
object that implements an encode_json
callback or
is handled by the supplied callback argument).
flags
Flag bit field to control formatting. See ASCII_ONLY
,
HUMAN_READABLE
and PIKE_CANONICAL
for further details.
callback
A function that will be called for types that can not be encoded otherwise. It will be called with the value to be encoded as the first argument, and optionally with flags and indent arguments. If a string is supplied, it will be used to replace the value verbatim. The callback must return a string or throw an error.
8-bit and wider characters in input strings are neither escaped
nor utf-8 encoded by default. string_to_utf8
can be used safely
on the returned string to get a valid transport encoded JSON
string. See escape_string
for further details on string
escaping.
escape_string
string
escape_string(string
str
, void
|int
flags
)
Escapes string data for use in a JSON string.
8-bit and wider characters in input strings are neither escaped
nor utf-8 encoded by default. string_to_utf8
can be used safely
on the returned string to get a valid transport encoded JSON
string.
The characters U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) are exceptions - they are encoded with \u escapes for compatibility. The reason is that those characters are not allowed in Javascript strings, so JSON parsers built in Javascript may have trouble with them otherwise.
val
The string to escape.
flags
Flag bit field to control formatting. ASCII_ONLY
is the only
flag that has any effect for this function.
The difference between using this function and encode
on a
string is that encode
returns quotations marks around the
result.
encode
Val.True
Standards.JSON.true
Val.False
Standards.JSON.false
Val.Null
Standards.JSON.null
Compat aliases for the corresponding Val
objects. These are
used to represent the three JSON literals true
,
false
and null
.
Replaced by Val.true
, Val.false
and Val.null
.
int
validate(string
s
)
Checks if a string is valid JSON.
In case the string contains valid JSON -1
is returned. It is then guaranteed to be parsed
without errors by decode()
.
In case the string is not valid JSON, the error position is returned.
int
validate_utf8(string
s
)
Checks if a string is valid utf8 encoded JSON.
In case the string contains valid JSON -1
is returned. It is then guaranteed to be parsed
without errors by decode()
.
In case the string is not valid JSON, the integer position inside the string
where the error occurs is returned.
Error thrown when JSON decode fails.
int
Standards.JSON.DecodeError.err_pos
The failing position in err_str
.
string
Standards.JSON.DecodeError.err_str
The string that failed to be decoded.
inherit Error.Generic : Generic
An instance of this class can be used to validate a JSON object against a JSON schema.
string schema_s = "{\n" + " \"name\": \"SomeExample\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": { \"type\": \"string\" },\n" + " \"id\": {\n" + " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " }\n" + " }\n" + "}"; string example_s = "{\n" + " \"name\": \"An Example\",\n" + " \"id\": 17\n" + "}"; mixed schema =
Standards.JSON.decode
(schema_s); mixed example =Standards.JSON.decode
(example_s); if (string error =Standards.JSON.Validator(schema).validate
(example)) werror("Error: JSON string %O did not validate: %s\n", example_s, error); else write("JSON ok\n");
This class validates only a subset of the JSON schema specification.
Currently dependencies and references are not handled and regular
expressions (for pattern properties) are limited to those that can be
handled by Regexp.SimpleRegexp
.
For more information of JSON schema look at http://json-schema.org/documentation.html "The home of JSON Schema".
Standards.JSON.Validator Standards.JSON.Validator(
mixed
_schema
)
Create a JSON validator for some JSON schema.
_schema
The JSON schema to use in validate()
. This must be a valid JSON
object.
Throws an error if the schema is invalid.
private
bool
has_schema_array(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is an array.
Throws an error if the value of the property is no array.
1 if the schema has the specified property.
private
bool
has_schema_array_mapping(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is an array(mapping).
Throws an error if the value of the property is no array(mapping).
1 if the schema has the specified property.
private
bool
has_schema_array_string(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is an array(string).
Throws an error if the value of the property is no array(string).
1 if the schema has the specified property.
private
bool
has_schema_boolean(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value
of the property is a boolean (with values Standards.JSON.true
or Standards.JSON.false
).
Throws an error if the value of the property is no boolean.
1 if the schema has the specified property.
private
bool
has_schema_integer(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is an integer.
Throws an error if the value of the property is no integer.
1 if the schema has the specified property.
private
bool
has_schema_mapping(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is a mapping.
Throws an error if the value of the property is no mapping.
1 if the schema has the specified property.
private
bool
has_schema_mapping_mapping(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is a mapping(string:mapping).
Throws an error if the value of the property is no mapping(string:mapping).
1 if the schema has the specified property.
private
bool
has_schema_number(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is a number (integer or float).
Throws an error if the value of the property is no number.
1 if the schema has the specified property.
private
bool
has_schema_string(mapping
(string
:mixed
) schema
, string
property
)
Test if the schema has the specified property and the value of the property is a string.
Throws an error if the value of the property is no string.
1 if the schema has the specified property.
private
bool
is_JSON_boolean(mixed
value
)
1 if the specified value is either Standards.JSON.true
or
Standards.JSON.false
.
string
validate(mixed
json
)
This function validates a JSON object against the JSON schema that was specified in the Validator's constructor. If the JSON object is not valid, a string with an error-message is returned. If the JSON object is valid, 0 is returned.
json
The JSON object to validate.
0, if the json object is valid, and an error-message if it is not valid.
private
string
validate_array(string
key
, mixed
value
, mapping
(string
:mixed
) schema
)
Verify that the specified value is an array according to the specified schema. The following properties of schema are verified:
If schema has the property "minItems", then the array must have at least the specified number of items.
If schema has the property "maxItems", then the array must not have more than the specified number of items.
If schema has the property "items", which is an array of schema objects, then each element in the value array must be valid according the corresponding schema in the "items" array.
private
string
validate_integer(string
key
, mixed
value
, mapping
(string
:mixed
) schema
)
Verify that the specified value is an integer according to the specified
schema. This is the similar to validate_number()
, but the
value must be an int and not a float.
The following properties of schema are verified:
If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.
If the schema has the properties "minimum" and
"exclusiveMinimum" is Standards.JSON.true
, then the
value must be greater than the specified minimum.
If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.
If the schema has the properties "maximum" and
"exclusiveMaximum" is Standards.JSON.true
, then the
value must be lower than the specified minimum.
If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.
private
string
validate_item_type(string
key
, mixed
value
, mapping
schema
)
Verify that the specified value has the correct type that is defined by schema->type. schema->type can be any of
"boolean",
"integer",
"number",
"string",
"array",
"object",
"null",
or an array of these.
private
string
validate_number(string
key
, mixed
value
, mapping
(string
:mixed
) schema
)
Verify that the specified value is a number (integer or float) according to the specified schema. The following properties of schema are verified:
If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.
If the schema has the properties "minimum" and
"exclusiveMinimum" is Standards.JSON.true
, then the
value must be greater than the specified minimum.
If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.
If the schema has the properties "maximum" and
"exclusiveMaximum" is Standards.JSON.true
, then the
value must be lower than the specified minimum.
If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.
private
string
validate_object(string
key
, mixed
value
, mapping
(string
:mixed
) schema
)
Verify that the specified value is an object according to the specified schema. The following properties of schema are verified:
If schema has the property "minProperties", then the object must have at least the specified number of properties.
If schema has the property "maxProperties", then the object must not have more than the specified number of items.
If schema has the property "required", which is an array of strings, then the object must have all properties that are listed in the specified array.
If schema has the property "properties", which is a mapping of property-name to a schema, then each property of the object that has a corresponding schema in "properties" must be valid according to that schema.
If schema has the property "properties", which is a mapping of property-name-pattern to a schema, then each property of the object must be valid according to all schema objects for which the pattern matches the property-name.
If schema has the property "additionalProperties", it can be either a boolean value, or a schema.
If it is a boolean with value Standards.JSON.false
, then all
properties of the object must be validated either by a schema from
"properties" or "patternProperties".
If it is a boolean with value Standards.JSON.true
, then the
object is allowed to have additional properties without validation.
If it is a schema, then any propery of the object that is not validated by a schema from "properties" or "patternProperties" must be validated by the specified schema.
TODO: We use Regexp.SimpleRegexp
to handle
schema->patternProperties, but that covers only some part of the
possible regular expressions.
private
string
validate_properties(string
key
, mixed
value
, mapping
schema
)
Verify that the specified value matches the specified schema. The following properties of schema are verified:
If the schema has a property "type", then the value
must match the specified type (see validate_item_type()
).
If the schema has a property "allOf", which is an array of
schema objects, then the value must match each schema specified
in that array (via another call to validate_properties()
).
If the schema has a property "anyOf", which is an array of
schema objects, then the value must match at least one schema
specified in that array (via another call to
validate_properties()
).
If the schema has a property "oneOf", which is an array of
schema objects, then the value must match exactly one schema
specified in that array (via another call to
validate_properties()
).
If the schema has a property "not", then the value
must not match the schema specified by that property (via another
call to validate_properties()
).
If the schema has a property "enum", then the value must be equal to any of the values specified in the enum array.
If the schema is empty (i.e., it has none of the above specified properties, then the value is valid).
private
string
validate_string(string
key
, mixed
value
, mapping
(string
:mixed
) schema
)
Verify that the specified value is a string according to the specified schema. The following properties of schema are verified:
If schema has the property "minLength", then the value must not be shorter than the specified length.
If schema has the property "maxLength", then the value must not be longer than the specified length.
If schema has the property "pattern", then the value must match the specified pattern.
TODO: We use Regexp.SimpleRegexp
to handle schema->pattern,
but that covers only some part of the possible regular expressions.
Support for parsing PEM-style messages, defined in RFC1421. Encapsulation defined in RFC934.
string
build(string
tag
, string
data
, void
|mapping
(string
:string
) headers
, void
|string
checksum
)
Creates a PEM message, wrapped to 64 character lines.
tag
The encapsulation boundary string.
data
The data to be encapsulated.
headers
Optional mapping containing encapsulated headers as name value pairs.
checksum
Optional checksum string, added as per RFC4880.
string
decrypt_body(string(8bit)
dek_info
, string(8bit)
body
, string(8bit)
password
)
Decrypt a PEM body.
dek_info
"dek-info"
header from the Message
.
body
Encypted PEM body.
password
Decryption password.
Returns the decrypted body text.
string
decrypt_fragment(Message
m
, string(8bit)
pwd
)
Decrypt a PEM Message.
body
Fragment with encypted PEM body.
password
Decryption password.
Returns the decrypted body text.
string(8bit)
derive_key(string(8bit)
password
, string(8bit)
salt
, int
bytes
)
Key derivation function used in PEM.
Derived from OpenSSL. Is there any proper specification?
It seems to be related to PBKDF1 from RFC2898.
string
simple_decode(string
pem
)
Convenience function that decodes a PEM message containing only
one part, and returns it as a string. Returns 0
for indata
containing no or multiple parts.
Represents a PEM-style message.
string
Standards.PEM.Message.body
The decode message body.
mapping
(string
:string
) Standards.PEM.Message.headers
Encapsulated headers. If headers occurred multiple times, they will be concatenated to the value with a null character as delimiter.
string
Standards.PEM.Message.post
Post-encapsulation boundary string.
string
Standards.PEM.Message.pre
Pre-encapsulation boundary string.
string
Standards.PEM.Message.trailer
Message trailer, like RFC4880 checksum.
The Messages class acts as an envelope for a PEM message file or stream.
Standards.PEM.Messages Standards.PEM.Messages(
string
data
)
A Messages object is created with the file or stream data.
array
(string
|Message
) Standards.PEM.Messages.fragments
The fragments array contains the different message fragments, as Message objects for decoded messages and strings for non-messages or incomplete messages.
string
get_certificate()
Convenience wrapper for get_certificates
that returns the
first available certificate, or 0
.
array
(string
) get_certificates()
Returns an array of all the bodies of "CERTIFICATE"
and
"X509 CERTIFICATE"
fragments.
string
get_encrypted_private_key(string(8bit)
pwd
)
Returns the first key, decoded by the pwd
password.
array
(string
) get_fragment_bodies(multiset
labels
)
Returns an array of the string bodies of all fragments with any
of the given labels
in the boundy preamble.
array
(Message
) get_fragments(multiset
labels
)
Returns an array of all fragments with any of the given
labels
in the boundy preamble.
string
get_private_key()
Convenience wrapper for get_private_key
that returns the
first available key, or 0
.
array
(string
) get_private_keys()
Returns an array of all the bodies of "RSA PRIVATE KEY"
,
"DSA PRIVATE KEY"
, "EC PRIVATE KEY"
and
"ANY PRIVATE KEY"
fragments.
mapping
(string
:array
(Message
)) Standards.PEM.Messages.parts
This is a mapping from encapsulation boundary string to Message
objects. All message objects and surrounding text will be
listed, in order, in fragments
.
Public-Key Cryptography Standards (PKCS).
This is the Pike API for dealing with a set of standards initially published by RSA Security Inc, and later by IETF and others in various RFCs.
Standards.ASN1
, Crypto
,
RFC 2314, RFC 2459, RFC 2986, RFC 3279, RFC 3280,
RFC 4055, RFC 4985, RFC 5208, RFC 5280, RFC 5480,
RFC 5639, RFC 5915, RFC 5958, RFC 7292, RFC 7468
variant
Crypto.Sign.State
parse_private_key(string
key
)
Crypto.Sign.State
parse_private_key(Sequence
seq
)
Parse a PKCS#8 PrivateKeyInfo (cf RFC 5208 section 5).
parse_public_key()
, RSA.parse_private_key()
, DSA.parse_private_key()
Crypto.Sign.State
parse_public_key(Sequence
seq
)
Parse a PKCS#10 SubjectPublicKeyInfo (cf RFC 5280 section 4.1 and RFC 7468 section 13).
parse_private_key()
, RSA.parse_public_key()
, DSA.parse_public_key()
variant
Crypto.Sign.State
parse_public_key(string
key
)
Handling of Certificate Signing Requests (PKCS-10, RFC 2314, RFC 2986)
Sequence
build_csr(Crypto.Sign
sign
, Sequence
name
, mapping
(string
:array
(Object
)) attributes
, Crypto.Hash
|void
hash
)
Build a Certificate Signing Request.
sign
Signature algorithm for the certificate. Both private and public keys must be set.
name
The distinguished name for the certificate.
attributes
Attributes from PKCS #9 to add to the certificate.
hash
Hash algoritm to use for the CSR signature.
Defaults to Crypto.SHA256
.
Prior to Pike 8.0 this function only supported signing
with Crypto.RSA
and the default (and only) hash was
Crypto.MD5
.
Sequence
sign_cri(CRI
cri
, Crypto.Sign
sign
, Crypto.Hash
hash
)
Sign a CRI
to generate a Certificate Signing Request.
cri
CertificationRequestInfo to sign.
sign
Signature to use. Must have a private key set that matches
the public key in the keyinfo in cri
.
hash
Hash algorithm to use for the signature.
CertificationRequestInfo
This is the data that is signed by sign_cri()
.
void
Standards.PKCS.CSR.CRI.attributes
Subject attributes.
inherit Sequence : Sequence
void
Standards.PKCS.CSR.CRI.keyinfo
Public key information.
void
Standards.PKCS.CSR.CRI.subject
Certificate subject.
void
Standards.PKCS.CSR.CRI.version
inherit .Certificate.Attributes : Attributes
Handle PKCS-6 and PKCS-10 certificates and certificate requests.
variant
Sequence
build_distinguished_name(mapping
args
)
variant
Sequence
build_distinguished_name(array
args
)
Creates an ASN.1 Sequence
with the distinguished name of the
list of pairs given in args
. Supported identifiers are
args
Either a mapping that lists from id string to string or ASN.1 object, or an array with mappings, each containing one pair. No type validation is performed.
array
(mapping
(string(7bit)
:string
)) decode_distinguished_name(Sequence
dn
)
Perform the reverse operation of build_distinguished_name()
.
build_distinguished_name()
__deprecated__
Sequence
get_certificate_issuer(string
cert
)
Return the certificate issuer RDN from a certificate string.
cert
A string containing an X509 certificate.
Note that the certificate usually must be decoded using
Standards.PEM.simple_decode()
.
An Standards.ASN1.Sequence object containing the certificate issuer Distinguished Name (DN).
Replaced by Standards.X509.decode_certificate
.
__deprecated__
Sequence
get_certificate_subject(string
cert
)
Return the certificate subject RDN from a certificate string.
cert
A string containing an X509 certificate.
Note that the certificate usually must be decoded using
PEM.simpe_decode()
.
An Standards.ASN1.Sequence object containing the certificate subject Distinguished Name (DN).
Replaced by Standards.X509.decode_certificate
.
string
get_dn_string(Sequence
dnsequence
)
Converts an RDN (relative distinguished name) Seqeunce object to a human readable string in X500 format.
A string containing the certificate issuer Distinguished Name (DN) in human readable X500 format.
We don't currently handle attributes with multiple values, not all attribute types are understood.
DSA operations as defined in RFC-2459.
Sequence
algorithm_identifier(Crypto.DSA
|void
dsa
)
Returns the AlgorithmIdentifier as defined in RFC5280 section 4.1.1.2. Optionally the DSA parameters are included, if a DSA object is given as argument.
Sequence
build_private_key(Crypto.DSA
dsa
)
Creates a PrivateKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5208 section 5.
Sequence
build_public_key(Crypto.DSA
dsa
)
Creates a SubjectPublicKeyInfo ASN.1 sequence for the given dsa
object. See RFC 5280 section 4.1.2.7.
Crypto.DSA
parse_private_key(Sequence
seq
)
variant
Crypto.DSA
parse_private_key(string
key
)
Crypto.DSA
parse_public_key(string
key
, Gmp.mpz
p
, Gmp.mpz
q
, Gmp.mpz
g
)
Decodes a DER-encoded DSAPublicKey structure.
key
DSAPublicKey provided in ASN.1 DER-encoded format
p
Public parameter p, usually transmitted in the algoritm identifier.
q
Public parameter q, usually transmitted in the algoritm identifier.
g
Public parameter g, usually transmitted in the algoritm identifier.
Crypto.DSA
object
string
private_key(Crypto.DSA
dsa
)
string
public_key(Crypto.DSA
dsa
)
Generates the DSAPublicKey value, as specified in RFC2459.
Sequence
signature_algorithm_id(Crypto.Hash
hash
)
Returns the PKCS-1 algorithm identifier for DSA and the provided
hash algorithm. One of SHA1
, SHA224
or SHA256
.
ECDSA operations.
protected
mapping
(string
:Crypto.ECC.Curve
) Standards.PKCS.ECDSA.curve_lookup
Lookup from ASN.1 DER encoded ECC named curve identifier to
the corresponding Crypto.ECC.Curve
.
Crypto.ECC.Curve
parse_ec_parameters(string
ec_parameters
)
Get the ECC curve corresponding to an ASN.1 DER encoded named curve identifier.
Returns UNDEFINED
if the curve is unsupported.
variant
Crypto.ECC.Curve
parse_ec_parameters(Standards.ASN1.Types.Identifier
|void
named_curve
)
Crypto.ECC.SECP_521R1.ECDSA
parse_private_key(Sequence
a
, Crypto.ECC.Curve
|void
c
)
Get an initialized ECDSA object from an ECC curve and an ASN.1 ec private key sequence.
As specified in RFC 5915 section 3.
variant
Crypto.ECC.SECP_521R1.ECDSA
parse_private_key(string(8bit)
ec_private_key
, Crypto.ECC.Curve
|void
c
)
Get an initialized ECDSA object from an ECC curve and an ASN.1 DER encoded ec private key.
As specified in RFC 5915 section 3.
Crypto.ECC.SECP_521R1.ECDSA
parse_public_key(string(8bit)
key
, Crypto.ECC.Curve
c
)
Get an initialized ECDSA object from an ECC curve and an ec public key.
string(8bit)
private_key(Crypto.ECC.SECP_521R1.ECDSA
ecdsa
)
Create a DER-coded ECPrivateKey structure
ecdsa
Crypto.ECC.Curve()->ECDSA
object.
ASN.1 coded ECPrivateKey structure as specified in RFC 5915 section 3.
string(8bit)
public_key(Crypto.ECC.SECP_521R1.ECDSA
ecdsa
)
Create a DER-coded ECPublicKey structure
ecdsa
Crypto.ECC.Curve()->ECDSA
object.
ASN.1 coded ECPublicKey structure as specified in RFC 5480 section 2.
Various ASN.1 identifiers used by PKCS.
RSA operations and types as described in PKCS-1.
Sequence
algorithm_identifier()
Returns the AlgorithmIdentifier as defined in RFC5280 section 4.1.1.2.
Sequence
build_private_key(Crypto.RSA
rsa
)
Creates a PrivateKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5208 section 5.
Sequence
build_public_key(Crypto.RSA
rsa
)
Creates a SubjectPublicKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5280 section 4.1.2.7.
Crypto.RSA.State
parse_private_key(Sequence
seq
)
Decode a RSAPrivateKey structure
key
RSAPrivateKey provided in ASN.1 format
Crypto.RSA
object
variant
Crypto.RSA.State
parse_private_key(string
key
)
Decode a DER-coded RSAPrivateKey structure
key
RSAPrivateKey provided in ASN.1 DER-encoded format
Crypto.RSA
object
Crypto.RSA.State
parse_public_key(string
key
)
Decode a DER-coded RSAPublicKey structure
key
RSAPublicKey provided in ASN.1 DER-encoded format
Crypto.RSA
object
string
private_key(Crypto.RSA
rsa
)
Create a DER-coded RSAPrivateKey structure
rsa
Crypto.RSA
object
ASN1 coded RSAPrivateKey structure
string
public_key(Crypto.RSA
rsa
)
Create a DER-coded RSAPublicKey structure
rsa
Crypto.RSA
object
ASN1 coded RSAPublicKey structure
Sequence
signature_algorithm_id(Crypto.Hash
hash
)
Returns the PKCS-1 algorithm identifier for RSA and the provided
hash algorithm. One of MD2
, MD5
, SHA1
, SHA256
,
SHA384
or SHA512
.
string
build_digestinfo(string
msg
, Crypto.Hash
hash
)
Construct a PKCS-1 digestinfo.
msg
message to digest
hash
crypto hash object such as Crypto.SHA1
or Crypto.MD5
Crypto.RSA()->sign
Signed
sign(Sequence
tbs
, Crypto.Sign
sign
, Crypto.Hash
hash
)
Generic PKCS signing.
tbs
Standards.ASN1
structure to be signed.
sign
Signature to use. Must have a private key set.
hash
Hash algorithm to use for the signature. Must be valid for the signature algorithm.
Returns a Standards.ASN1.Types.Sequence
with
the signature.
This is an ASN.1 structure from PKCS #10 v1.7 and others, which represents a signed block of data.
sign()
, Standards.X509.sign_tbs()
.
Sequence
Standards.PKCS.Signature.Signed.algorithm
Getting
Signing algorithm that was used to sign with.
Setting
Signing algorithm that was used to sign with.
inherit Sequence : Sequence
this_program
sign(Crypto.Sign
sign
, Crypto.Hash
hash
)
Sign tbs
with the provided sign
and hash
.
Sets algorithm
and signature
.
Returns the Signed
object.
BitString
Standards.PKCS.Signature.Signed.signature
Getting
The signature.
Setting
The signature.
Object
Standards.PKCS.Signature.Signed.tbs
Getting
ASN.1 structure that has been signed.
Setting
ASN.1 structure that has been signed.
constant
Standards.TLD.cc
A mapping between country TLDs and the name of the country.
multiset
Standards.TLD.generic
A multiset containing the generic TLDs, such as "com" and "info".
Support for Universal Unique Identifiers (UUID) and Globally Unique Identifiers (GUID).
RFC4122: A Universally Unique IDentifier (UUID) URN Namespace ITU-T X.667: Generation and registration of Universally Unique Identifiers (UUIDs) and their use as ASN.1 object identifier components
constant
string
Standards.UUID.NameSpace_DNS
Name space UUID for DNS.
constant
string
Standards.UUID.NameSpace_OID
Name space UUID for OID.
constant
string
Standards.UUID.NameSpace_URL
Name space UUID for URL.
constant
string
Standards.UUID.NameSpace_X500
Name space UUID for X500.
constant
string
Standards.UUID.Nil_UUID
The Nil UUID.
string
format_uuid(string
uuid
)
Returns the string representation of the binary UUID uuid
.
array
(int
) get_clock_state()
Returns the internal clock state. Can be used for persistent storage when an application is terminated.
set_clock_state
UUID
make_dns(string
name
)
Creates a DNS UUID with the given DNS name.
UUID
make_dns(string
name
)
Creates a DNS UUID with the given DNS name.
UUID
make_null()
Creates a null UUID object.
UUID
make_oid(string
name
)
Creates an OID UUID with the given OID.
UUID
make_oid(string
name
)
Creates an OID UUID with the given OID.
UUID
make_url(string
name
)
Creates a URL UUID with the given URL.
UUID
make_url(string
name
)
Creates a URL UUID with the given URL.
UUID
make_version1(int
node
)
Creates a new version 1 UUID.
node
Either the 48 bit IEEE 802 (aka MAC) address of the system or -1.
UUID
make_version3(string
name
, string
|UUID
namespace
)
Creates a version 3 UUID with a name
string and a binary
representation of a name space UUID.
UUID
make_version4()
Creates a version 4 (random) UUID.
UUID
make_version5(string
name
, string
|UUID
namespace
)
Creates a version 5 UUID with a name
string and a binary
representation of a name space UUID.
UUID
make_x500(string
name
)
Creates an X500 UUID with the gived X500 address.
UUID
make_x500(string
name
)
Creates an X500 UUID with the gived X500 address.
string
parse_uuid(string
uuid
)
Returns the binary representation of the UUID uuid
.
void
set_clock_state(int
last_time
, int
seq
)
Sets the internal clock state.
get_clock_state
Represents an UUID
int
Standards.UUID.UUID.clk_seq
The clock sequence. Should be 13 to 15 bits depending on UUID version.
Standards.UUID.UUID Standards.UUID.UUID(
void
|string
in
)
Optionally created with a string or binary representation of a UUID.
string
encode()
Encodes a binary representation of the UUID.
int
Standards.UUID.UUID.node
The UUID node. Should be 48 bit.
int
posix_time()
Returns the posix time of the UUID.
string
str()
Creates a string representation of the UUID.
string
str_variant()
Returns a string representation of the variant, e.g.
"IETF draft variant"
.
string
str_version()
Returns a string representation of the version, e.g.
"Name-based (MD5)"
.
int
time_hi_and_version()
Returns the time_hi_and_version field.
int
time_low()
Returns the time_low field.
int
time_mid()
Returns the time_mid field.
int
Standards.UUID.UUID.timestamp
60 bit value representing the time stamp.
string
urn()
Creates a URN representation of the UUID.
void
validate()
Validates the current UUID.
int
Standards.UUID.UUID.var
The variant of the UUID.
int
Standards.UUID.UUID.version
The version of the UUID.
Functions to generate and validate RFC2459 style X.509 v3 certificates.
TBSCertificate
decode_certificate(string
|object
cert
)
Decodes a certificate and verifies that it is structually sound.
Returns a TBSCertificate
object if ok, otherwise 0
.
mapping
(Identifier
:Crypto.Hash
) get_algorithms()
Returns the mapping of signature algorithm to hash algorithm
supported by Verifier
and thus verify_ca_certificate()
,
verify_certificate()
, and verify_certificate_chain()
.
mapping
(string
:array
(Verifier
)) load_authorities(string
|array
(string
)|void
root_cert_dirs
)
Convenience function for loading known root certificates.
root_cert_dirs
Directory/directories containing the PEM-encoded root certificates
to load. Defaults to a rather long list of directories, including
"/etc/ssl/certs"
, "/etc/pki/tls/certs"
and
"/System/Library/OpenSSL/certs"
, which seem to be the most
common locations.
Returns a mapping from DER-encoded issuer to Verifier
s
compatible with eg verify_certificate()
If a certificate directory contains a file named
"ca-certificates.crt"
, it is assumed to
contain a concatenation of all the certificates
in the directory.
verify_certificate()
, verify_certificate_chain()
Sequence
make_extension(Identifier
id
, Object
ext
, void
|int
critical
)
Creates a certificate extension with the id
as identifier and
ext
as the extension payload. If the critical
flag is set
the extension will be marked as critical.
string
make_selfsigned_certificate(Crypto.Sign.State
c
, int
ttl
, mapping
|array
name
, mapping
(Identifier
:Sequence
)|void
extensions
, void
|Crypto.Hash
h
, void
|int
serial
)
Creates a selfsigned certificate, i.e. where issuer and subject
are the same entity. This entity is derived from the list of pairs
in name
, which is encoded into an distinguished_name by
Standards.PKCS.Certificate.build_distinguished_name
.
c
The public key cipher used for the certificate, Crypto.RSA
,
Crypto.DSA
or Crypto.ECC.Curve.ECDSA
. The object should be
initialized with both public and private keys.
ttl
The validity of the certificate, in seconds, starting from creation date.
name
List of properties to create distinguished name from.
extensions
Mapping with extensions as ASN.1 structures, as produced by
make_extension
. The extensions subjectKeyIdentifier, keyUsage
(flagged critical) and basicConstraints (flagged critical) will
automatically be added if not present.
h
The hash function to use for the certificate. Must be one of the
standardized PKCS hashes to be used with the given Crypto. By
default Crypto.SHA256
is selected for both RSA and DSA.
serial
Serial number of the certificate. Defaults to generating a UUID version1 value with random node. Some browsers will refuse different certificates from the same signer with the same serial number.
sign_key()
, sign_tbs()
TBSCertificate
make_tbs(Sequence
issuer
, Sequence
algorithm
, Sequence
subject
, Sequence
keyinfo
, Integer
serial
, Sequence
validity
, array
|int(0..0)
|void
extensions
)
Creates the ASN.1 TBSCertificate sequence (see RFC2459 section
4.1) to be signed (TBS) by the CA. version is explicitly set to
v3, and extensions
is optionally added to the sequence.
issuerUniqueID and subjectUniqueID are not supported.
variant
TBSCertificate
make_tbs(Sequence
issuer
, Sequence
algorithm
, Sequence
subject
, Sequence
keyinfo
, Integer
serial
, int
ttl
, array
|int(0..0)
|void
extensions
)
Creates the ASN.1 TBSCertificate sequence (see RFC2459 section
4.1) to be signed (TBS) by the CA. version is explicitly set to
v3, validity is calculated based on time and ttl
, and
extensions
is optionally added to the sequence.
issuerUniqueID and subjectUniqueID are not supported.
Prior to Pike 8.0 this function returned a plain Sequence
object.
Crypto.Sign.State
parse_private_key(Sequence
seq
)
DWIM-parse the ASN.1-sequence for a private key.
variant
Crypto.Sign.State
parse_private_key(string
private_key
)
DWIM-parse the DER-sequence for a private key.
string
sign_key(Sequence
issuer
, Crypto.Sign.State
c
, Crypto.Sign.State
ca
, Crypto.Hash
h
, Sequence
subject
, int
serial
, int
ttl
, array
|mapping
|void
extensions
)
Low-level function for creating a signed certificate.
issuer
Distinguished name for the issuer.
See Standards.PKCS.Certificate.build_distinguished_name
.
c
RSA, DSA or ECDSA parameters for the subject. Only the public
key needs to be set. See Crypto.RSA
, Crypto.DSA
and
Crypto.ECC.Curve.ECDSA
.
ca
RSA, DSA or ECDSA parameters for the issuer. Only the private
key needs to be set. See Crypto.RSA
, Crypto.DSA
and
Crypto.ECC.Curve.ECDSA
.
h
The hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto.
subject
Distinguished name for the subject.
See Standards.PKCS.Certificate.build_distinguished_name
.
public_key
DER-encoded RSAPublicKey structure.
See Standards.PKCS.RSA.public_key()
.
serial
Serial number for this key and subject.
ttl
Validity time in seconds for this signature to be valid.
extensions
Set of extensions.
Returns a DER-encoded certificate.
make_selfsigned_certificate()
, make_tbs()
, sign_tbs()
Sequence
sign_tbs(TBSCertificate
tbs
, Crypto.Sign.State
sign
, Crypto.Hash
hash
)
Sign the provided TBSCertificate.
tbs
A TBSCertificate
as returned by decode_certificate()
or make_tbs()
.
sign
RSA, DSA or ECDSA parameters for the issuer.
See Crypto.RSA
, Crypto.DSA
and Crypto.ECC.Curve.ECDSA
.
Must be initialized with the private key.
hash
The hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto.
decode_certificate()
, make_tbs()
TBSCertificate
verify_ca_certificate(string
|TBSCertificate
tbs
)
Verifies that all extensions mandated for certificate signing certificates are present and valid.
TBSCertificate
verify_certificate(string
s
, mapping
(string
:Verifier
|array
(Verifier
)) authorities
, mapping
(Standards.ASN1.Types.Identifier
:Crypto.Hash
)|void
options
)
Decodes a certificate, checks the signature. Returns the TBSCertificate structure, or 0 if decoding or verification fails. The valid time range for the certificate is not checked.
authorities
A mapping from (DER-encoded) names to a verifiers.
options
| A mapping of verifier algorithm identifier to hash algorith implementation. |
This function allows self-signed certificates, and it doesn't check that names or extensions make sense.
mapping
verify_certificate_chain(array
(string
) cert_chain
, mapping
(string
:Verifier
|array
(Verifier
)) authorities
, int
|void
require_trust
, bool
|void
strict
)
mapping
verify_certificate_chain(array
(string
) cert_chain
, mapping
(string
:Verifier
|array
(Verifier
)) authorities
, int
|void
require_trust
, mapping
(string
:mixed
) options
)
Decodes a certificate chain, ordered from leaf to root, and checks the signatures. Verifies that the chain can be decoded correctly, is unbroken, and that all certificates are in effect (time-wise.) and allowed to sign its child certificate.
No verifications are done on the leaf certificate to determine what it can and can not be used for.
Returns a mapping with the following contents, depending on the verification of the certificate chain:
| Error describing type of verification failurew, if
verification failed. May be one of the following, OR:ed
together: |
| Index number of the certificate that caused the verification failure. |
| Non-zero if the certificate is self-signed. |
| Non-zero if the certificate is verified. |
| The authority RDN that verified the chain. |
| The common name RDN of the leaf certificate. |
| An array with the decoded certificates, ordered from root to leaf. |
cert_chain
An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate.
authorities
A mapping from (DER-encoded) names to verifiers.
require_trust
Require that the certificate be traced to an authority, even if it is self signed.
strict
By default this function only requires that the certificates are in order, it ignores extra certificates we didn't need to verify the leaf certificate.
If you specify strict
, this will change, each certificate has
to be signed by the next in the chain.
Some https-servers send extraneous intermediate certificates that aren't used to validate the leaf certificate. So strict mode will be incompatible with such servers.
options
| A mapping of verifier algorithm identifier to hash algorithm implementation. |
| See |
get_algorithms()
See Standards.PKCS.Certificate.get_dn_string
for converting the
RDN to an X500 style string.
Unique identifier for the certificate issuer.
X.509v2 (deprecated).
inherit BitString : BitString
Unique identifier for the certificate subject.
X.509v2 (deprecated).
inherit BitString : BitString
Represents a TBSCertificate.
Was not compatible with Standards.ASN1.Types.Sequence
prior to Pike 8.0.
void
Standards.X509.TBSCertificate.algorithm
Algorithm Identifier.
multiset
Standards.X509.TBSCertificate.critical
optional
Read only
void
Standards.X509.TBSCertificate.der
string
dn_str(Sequence
dn
)
Try to extract a readable name from dn
. This is one of
commonName, organizationName or organizationUnitName. The first
that is found is returned. Suitable for subjects and issuer
sequences.
bool
Standards.X509.TBSCertificate.ext_authorityKeyIdentifier
Set if the certificate contains a valid authorityKeyIdentifier extension. RFC3280 4.2.1.1.
Gmp.mpz
Standards.X509.TBSCertificate.ext_authorityKeyIdentifier_authorityCertSerialNumber
Set to the CertificateSerialNumber, if set in the extension.
string
Standards.X509.TBSCertificate.ext_authorityKeyIdentifier_keyIdentifier
Set to the KeyIdentifier, if set in the extension.
bool
Standards.X509.TBSCertificate.ext_basicConstraints
Set if the certificate contains a valid basicConstraints extension. RFC3280 4.2.1.10.
bool
Standards.X509.TBSCertificate.ext_basicConstraints_cA
If set, the certificate may be used as a CA certificate, i.e. sign other certificates.
int
Standards.X509.TBSCertificate.ext_basicConstraints_pathLenConstraint
The maximum number of certificates that may follow this
certificate in a certificate chain. 0
in case no limit is
imposed. Note that this variable is off by one compared to the
RFC 3280 definition, which only counts intermediate certificates
(i.e. 0 intermediates means this variable would be 1, as in one
following certificate).
array
(Identifier
) Standards.X509.TBSCertificate.ext_extKeyUsage
Set to the list of extended key usages from anyExtendedKeyUsage,
if the certificate contains the extKeyUsage extensions. These
Identifier objects are typically found in
.PKCS.Identifiers.reverse_kp_ids
. RFC3280 4.2.1.13.
keyUsage
Standards.X509.TBSCertificate.ext_keyUsage
Set to the value of the KeyUsage if the certificate contains the keyUsage extension. RFC3280 4.2.1.3.
string
Standards.X509.TBSCertificate.ext_subjectKeyIdentifier
Set to the value of the SubjectKeyIdentifier if the certificate contains the subjectKeyIdentifier extension. RFC3280 4.2.1.2.
mapping
(Identifier
:Object
) Standards.X509.TBSCertificate.extensions
optional
Read only
inherit Sequence : Sequence
this_program
init(array
|Object
asn1
)
Populates the object from a certificate decoded into an ASN.1
Object. Returns the object on success, otherwise 0
. You
probably want to call decode_certificate
or even
verify_certificate
.
protected
multiset
Standards.X509.TBSCertificate.internal_critical
optional
protected
mapping
(Identifier
:Object
) Standards.X509.TBSCertificate.internal_extensions
optional
void
Standards.X509.TBSCertificate.issuer
Certificate issuer.
void
Standards.X509.TBSCertificate.issuer_id
optional
string
issuer_str()
Return the issuer of the certificate as a human readable string. Mainly useful for debug.
void
Standards.X509.TBSCertificate.keyinfo
protected
void
low_set(int
index
, Sequence
|Integer
val
)
index
Index in a v1 certificate.
val
New value for index.
void
Standards.X509.TBSCertificate.not_after
void
Standards.X509.TBSCertificate.not_before
void
Standards.X509.TBSCertificate.public_key
void
Standards.X509.TBSCertificate.raw_extensions
The raw ASN.1 objects from which extensions
and critical
have been generated.
optional
void
Standards.X509.TBSCertificate.serial
void
Standards.X509.TBSCertificate.subject
void
Standards.X509.TBSCertificate.subject_id
optional
string
subject_str()
Attempt to create a presentable string from the subject DER.
void
Standards.X509.TBSCertificate.validity
void
Standards.X509.TBSCertificate.version
bool
verify(Sequence
algorithm
, string(8bit)
msg
, string(8bit)
signature
, mapping
(Identifier
:Crypto.Hash
)|void
verifier_algorithms
)
Verifies the signature
of the certificate msg
using the
indicated hash algorithm
, choosing from verifier_algorithms
.
get_algorithms()
Helper module for generating Windows Installer XML structures.
Parser.XML.Tree.SimpleNode
WixNode
get_module_xml(Directory
dir
, string
id
, string
version
, string
|void
manufacturer
, string
|void
description
, string
|void
guid
, string
|void
comments
, string
|void
installer_version
)
Modifies dir
if it contains files at the root level.
This module embodies common operating system calls, making them available to the Pike programmer.
int
AllocConsole()
Allocates a new console for the calling process.
Only available on certain Windows systems.
0 on success, non-zero otherwise.
int
AttachConsole(int
pid
)
Attaches calling process to a specific console.
pid
Only available on certain Windows systems.
0 on success, non-zero otherwise.
constant
string
System.CPU_TIME_IMPLEMENTATION
This string constant identifies the internal interface used to get the CPU time. It is an implementation detail - see rusage.c for possible values and their meanings.
gethrvtime
, gauge
constant
string
System.CPU_TIME_IS_THREAD_LOCAL
This string constant tells whether or not the CPU time, returned
by e.g. gethrvtime
, is thread local or not. The value is "yes"
if it is and "no" if it isn't. The value is also "no" if there is
no thread support.
gethrvtime
, gauge
constant
int
System.CPU_TIME_RESOLUTION
The resolution of the CPU time, returned by e.g. gethrvtime
, in
nanoseconds. It is -1
if the resolution isn't known.
gethrvtime
, gauge
int
FreeConsole()
Detaches the calling process from its console.
Before calling this function, Stdio.stderr
, Stdio.stdout
and
Stdio.stdin
must be closed.
Only available on certain Windows systems.
0 on success, non-zero otherwise.
string
GetComputerName()
Retrieves the NetBIOS name of the local computer.
This function is Windows specific, and is not available on all systems.
int
GetFileAttributes(string
filename
)
Get the file attributes for the specified file.
This function is only available on Win32 systems.
SetFileAttributes()
mapping
(mixed
:mixed
) GetNamedSecurityInfo(string
name
, int
|void
type
, int
|void
flags
)
This function is only available on some Win32 systems.
SetNamedSecurityInfo()
string
GetUserName()
Retrieves the name of the user associated with the current thread.
This function is Windows specific, and is not available on all systems.
constant
System.ITIMER_PROF
Identifier for a timer that decrements both when the process is executing and when the system is executing on behalf of the process.
setitimer
, getitimer
constant
System.ITIMER_REAL
Identifier for a timer that decrements in real time.
setitimer
, getitimer
constant
System.ITIMER_VIRTUAL
Identifier for a timer that decrements only when the process is executing.
setitimer
, getitimer
object
LogonUser(string
username
, string
|int(0..0)
domain
, string
password
, int
|void
logon_type
, int
|void
logon_provider
)
Logon a user.
username
User name of the user to login.
domain
Domain to login on, or zero if local logon.
password
Password to login with.
logon_type
One of the following values:
| |
| |
| |
| This is the default. |
logon_provider
One of the following values:
| This is the default. |
Returns a login token object on success, and zero on failure.
This function is only available on some Win32 systems.
array
(mixed
) LookupAccountName(string
|int(0..0)
sys
, string
account
)
This function is only available on some Win32 systems.
string
NetGetAnyDCName(string
|int(0..0)
server
, string
domain
)
Get name of a domain controller from a server.
server
Server the domain exists on.
domain
Domain to get a domain controller for.
Returns the name of a domain controller on success. Throws errors on failure.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetLocalGroupEnum()
,
NetUserGetGroups()
, NetUserGetLocalGroups()
,
NetGroupGetUsers()
, NetLocalGroupGetMembers()
,
NetGetDCName()
string
NetGetDCName(string
|int(0..0)
server
, string
domain
)
Get name of the domain controller from a server.
server
Server the domain exists on.
domain
Domain to get the domain controller for.
Returns the name of the domain controller on success. Throws errors on failure.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetLocalGroupEnum()
,
NetUserGetGroups()
, NetUserGetLocalGroups()
,
NetGroupGetUsers()
, NetLocalGroupGetMembers()
,
NetGetAnyDCName()
array
(string
|array
(string
|int
)) NetGroupEnum(string
|int(0..0)
|void
server
, int
|void
level
)
Get information about network groups.
server
Server the groups exist on.
level
Information level. One of:
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetLocalGroupEnum()
, NetUserGetGroups()
,
NetUserGetLocalGroups()
, NetGroupGetUsers()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(string
|array
(int
|string
)) NetGroupGetUsers(string
|int(0..0)
server
, string
group
, int
|void
level
)
Get information about group membership for a network group.
server
Server the groups exist on.
group
Group to retrieve members for.
level
Information level. One of:
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetLocalGroupEnum()
,
NetUserGetGroups()
, NetUserGetLocalGroups()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(array
(string
|int
)) NetLocalGroupEnum(string
|int(0..0)
|void
server
, int
|void
level
)
Get information about local network groups.
server
Server the groups exist on.
level
Information level. One of:
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetUserGetGroups()
,
NetUserGetLocalGroups()
, NetGroupGetUsers()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(string
|array
(int
|string
)) NetLocalGroupGetMembers(string
|int(0..0)
server
, string
group
, int
|void
level
)
Get information about group membership for a network group.
server
Server the groups exist on.
group
Group to retrieve members for.
level
Information level. One of:
|
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetLocalGroupEnum()
,
NetUserGetGroups()
, NetUserGetLocalGroups()
,
NetGroupGetUsers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(int
|string
) NetSessionEnum(string
|int(0..0)
server
, string
|int(0..0)
client
, string
|int(0..0)
user
, int
level
)
Get session information.
level
One of
|
|
|
|
|
This function is only available on some Win32 systems.
array
(string
|array
(string
|int
)) NetUserEnum(string
|int(0..0)
|void
server
, int
|void
level
, int
|void
filter
)
Get information about network users.
server
Server the users exist on.
level
Information level. One of:
|
|
|
|
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetGroupEnum()
NetLocalGroupEnum()
, NetUserGetGroups()
,
NetUserGetLocalGroups()
, NetGroupGetUsers()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(array
(string
|int
)) NetUserGetGroups(string
|int(0..0)
server
, string
user
, int
|void
level
)
Get information about group membership for a network user.
server
Server the groups exist on.
user
User to retrieve groups for.
level
Information level. One of:
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetLocalGroupEnum()
,
NetUserGetLocalGroups()
, NetGroupGetUsers()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
string
|array
(string
|int
) NetUserGetInfo(string
username
, string
|int(0..0)
server
, int
|void
level
)
Get information about a network user.
username
User name of the user to get information about.
server
Server the user exists on.
level
Information level. One of:
|
|
|
|
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserEnum()
, NetGroupEnum()
NetLocalGroupEnum()
, NetUserGetGroups()
,
NetUserGetLocalGroups()
, NetGroupGetUsers()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(string
) NetUserGetLocalGroups(string
|int(0..0)
server
, string
user
, int
|void
level
, int
|void
flags
)
Get information about group membership for a local network user.
server
Server the groups exist on.
user
User to retrieve groups for.
level
Information level. One of:
|
flags
Zero, of one of the following:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo()
, NetUserEnum()
,
NetGroupEnum()
, NetLocalGroupEnum()
,
NetUserGetGroups()
, NetGroupGetUsers()
,
NetLocalGroupGetMembers()
, NetGetDCName()
,
NetGetAnyDCName()
array
(mixed
) NetWkstaUserEnum(string
|int(0..0)
server
, int
level
)
level
One of
|
|
This function is only available on some Win32 systems.
constant
string
System.REAL_TIME_IMPLEMENTATION
This string constant identifies the internal interface used to get the high resolution real time. It is an implementation detail - see rusage.c for possible values and their meanings.
gethrtime
constant
string
System.REAL_TIME_IS_MONOTONIC
This string constant tells whether or not the high resolution real
time returned by gethrtime
, is monotonic or not. The value is
"yes" if it is and "no" if it isn't.
Monotonic time is not affected by clock adjustments that might happen to keep the calendaric clock in synch. It's therefore more suited to measure time intervals in programs.
gethrtime
constant
int
System.REAL_TIME_RESOLUTION
The resolution of the real time returned by gethrtime
, in
nanoseconds. It is -1
if the resolution isn't known.
gethrtime
array
(string
) RegGetKeyNames_76(int
hkey
, string
key
)
Get a list of value key names from the register (COMPAT).
Pike 7.6 compatibility implementation of RegGetKeyNames()
.
The difference being that this function throws errors when
keys are missing.
This function is only available on Win32 systems.
RegGetValue()
, RegGetValues_76()
, RegGetKeyNames()
string
|int
|array
(string
) RegGetValue_76(int
hkey
, string
key
, string
index
)
Get a single value from the register (COMPAT).
Pike 7.6 compatibility implementation of RegGetValue()
.
The difference being that this function throws errors when
keys are missing.
This function is only available on Win32 systems.
RegGetKeyNames_76()
, RegGetValues_76()
, RegGetValue()
mapping
(string
:string
|int
|array
(string
)) RegGetValues_76(int
hkey
, string
key
)
Get multiple values from the register (COMPAT).
Pike 7.6 compatibility implementation of RegGetValues()
.
The difference being that this function throws errors when
keys are missing.
This function is only available on Win32 systems.
RegGetValue_76()
, RegGetKeyNames_76()
, RegGetValues()
int
SetFileAttributes(string
filename
)
Set the file attributes for the specified file.
This function is only available on Win32 systems.
GetFileAttributes()
array
(mixed
) SetNamedSecurityInfo(string
name
, mapping
(string
:mixed
) options
)
This function is only available on some Win32 systems.
GetNamedSecurityInfo()
void
chmod(string
path
, int
mode
)
Sets the protection mode of the specified path.
Throws errors on failure.
Stdio.File->open()
, errno()
void
chown(string
path
, int
uid
, int
gid
, void
|int
symlink
)
Sets the owner and group of the specified path.
If symlink
is set and path
refers to a symlink, then the
owner and group for the symlink are set. Symlinks are dereferenced
otherwise.
Throws errors on failure.
This function is not available on all platforms. On some
platforms the symlink
flag isn't supported. In that case, the
function does nothing if path
is a symlink.
int
chroot(string
newroot
)
int
chroot(Stdio.File
newroot
)
Changes the root directory for this process to the indicated directory.
A nonzero value is returned if the call is successful. If
there's an error then zero is returned and errno
is set
appropriately.
Since this function modifies the directory structure as seen from Pike, you have to modify the environment variables PIKE_MODULE_PATH and PIKE_INCLUDE_PATH to compensate for the new root-directory.
This function only exists on systems that have the chroot(2) system call.
The second variant only works on systems that also have the fchroot(2) system call.
On success the current working directory will be changed to
the new "/"
. This behavior was added in Pike 7.9.
This function could be interrupted by signals prior to Pike 7.9.
void
cleargroups()
Clear the supplemental group access list.
Throws errors on failure.
This function is not available on all platforms.
setgroups()
, initgroups()
, getgroups()
void
closelog()
Document this function.
int
daemon(int
nochdir
, int
noclose
)
Low level system daemon() function, see also Process.daemon()
bool
dumpable(bool
|void
val
)
Get and/or set whether this process should be able to dump core.
val
Optional argument to set the core dumping state.
| Disable core dumping for this process. |
| Enable core dumping for this process. |
Returns 1
if this process currently is capable of dumping core,
and 0
(zero) if not.
This function is currently only available on some versions of Linux.
int
endgrent()
Closes the /etc/groups file after using the getgrent
function.
get_all_groups()
getgrent()
setgrent()
int
endpwent()
Closes the passwd source opened by getpwent
function using the
systemfunction endpwent(3).
Always 0
(zero)
get_all_users()
getpwent()
setpwent()
string
get_home()
Get the full path for the current user's home directory
the full path to the current user's home directory, or zero if the appropriate environment variables have not been set.
This method uses the standard environment variables for various systems to determine the home directory.
array
(string
) get_netinfo_property(string
domain
, string
path
, string
property
)
Queries a NetInfo server for property values at the given path.
domain
NetInfo domain. Use "." for the local domain.
path
NetInfo path for the property.
property
Name of the property to return.
An array holding all property values. If the path
or property
cannot be not found 0 is returned instead. If the NetInfo domain
is not found or cannot be queried an exception is thrown.
system.get_netinfo_property(".", "/locations/resolver", "domain"); ({ "idonex.se" })
Only available on operating systems which have NetInfo libraries installed.
string
get_user()
Get the username of the user that started the process.
the username of the user "associated" with the current process, or zero if a method to find this information does not exist on the current system.
On NT systems, this returns the user the current thread is running as, while on Unix-like systems this function returns the user that started the process (rather than the effective user)..
int
getegid()
Get the effective group ID.
setuid
, getuid
, setgid
, getgid
,
seteuid
, geteuid
, setegid
int
geteuid()
Get the effective user ID.
setuid
, getuid
, setgid
, getgid
,
seteuid
, getegid
, setegid
int
getgid()
Get the real group ID.
setuid
, getuid
, setgid
,
seteuid
, geteuid
, getegid
, setegid
array
(int
|string
|array
(string
)) getgrent()
Get a group entry from /etc/groups file.
getgrent
interates thru the groups source and returns
one entry per call using the systemfunction getgrent(3).
Always call endgrent
when done using getgrent
!
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
get_all_groups()
getgrnam()
getgrgid()
array
(int
) getgroups()
Get the current supplemental group access list for this process.
Throws errors on failure.
This function is not available on all platforms.
setgroups()
, cleargroups()
, initgroups()
,
getgid()
, getgid()
, getegid()
, setegid()
array
(string
|array
(string
)) gethostbyaddr(string
addr
)
Returns an array with information about the specified IP address.
The returned array contains the same information as that returned
by gethostbyname()
.
This function only exists on systems that have the gethostbyaddr(2) or similar system call.
gethostbyname()
array
(string
|array
(string
)) gethostbyname(string
hostname
)
Returns an array with information about the specified host.
The returned array contains the following:
Array | |
| Name of the host. |
| Array of IP numbers for the host. |
| Array of alternative names for the host. |
This function only exists on systems that have the gethostbyname(2) or similar system call.
gethostbyaddr()
string
gethostname()
Returns a string with the name of the host.
This function only exists on systems that have the gethostname(2) or uname(2) system calls.
array
(float
) getitimer(int
timer
)
Shows the state of the selected timer
.
Array | |
| The interval of the timer. |
| The value of the timer. |
timer
One of ITIMER_REAL
, ITIMER_VIRTUAL
and ITIMER_PROF
.
array
(float
) getloadavg()
Get system load averages.
Array | |
| Load average over the last minute. |
| Load average over the last 5 minutes. |
| Load average over the last 15 minutes. |
int
getpgrp(int
|void
pid
)
Get the process group id for the process pid
.
With no argguments or with 'pid' equal to zero,
returns the process group ID of this process.
Not all platforms support getting the process group for other processes.
Not supported on all platforms.
getpid
, getppid
int
getpid()
Returns the process ID of this process.
getppid
, getpgrp
int
getppid()
Returns the process ID of the parent process.
getpid
, getpgrp
array
(int
|string
) getpwent()
When first called, the getpwent
function opens the passwd source
and returns the first record using the systemfunction getpwent(3).
For each following call, it returns the next record until EOF.
Call endpwent
when done using getpwent
.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
0 if EOF.
get_all_users()
getpwnam()
getpwent()
setpwent()
endpwent()
array
(int
) getrlimit(string
resource
)
Returns the current process limitation for the selected resource
.
resource
| The CPU time limit in seconds. |
| The maximum size of files the process may create. |
| The maximum size of the process's data segment. |
| The maximum size of process stack, in bytes. |
| |
| Specifies the limit of pages the process's resident set. |
| The maximum number of processes that can be created for the real user ID of the calling process. |
| The maximum number of file descriptors the process can open, +1. |
| The maximum number of bytes of virtual memory that may be locked into RAM. |
| |
|
Array | |
| The soft limit for the resource.
|
| The hard limit for the resource.
|
This function nor all the resources are available on all systems.
getrlimits
, setrlimit
mapping
(string
:array
(int
)) getrlimits()
Returns all process limits in a mapping.
getrlimit
, setrlimit
mapping
(string
:int
) getrusage()
Return resource usage about the current process. An error is thrown if it isn't supported or if the system fails to return any information.
Returns a mapping describing the current resource usage:
| Time in milliseconds spent in user code. |
| Time in milliseconds spent in system calls. |
| Maximum used resident size in kilobytes. [1] |
| Quote from GNU libc: An integral value expressed in kilobytes times ticks of execution, which indicates the amount of memory used by text that was shared with other processes. [1] |
| Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for data. [1] |
| Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for stack space. [1] |
| Minor page faults, i.e. TLB misses which required no disk I/O. |
| Major page faults, i.e. paging with disk I/O required. |
| Number of times the process has been swapped out entirely. |
| Number of block input operations. |
| Number of block output operations. |
| Number of IPC messsages sent. |
| Number of IPC messsages received. |
| Number of signals received. |
| Number of voluntary context switches (usually to wait for some service). |
| Number of preemptions, i.e. context switches due to expired time slices, or when processes with higher priority were scheduled. |
| Number of system calls. [2] |
| Number of characters read and written. [2] |
| Elapsed real time (ms). [2] |
| Elapsed system trap (system call) time (ms). [2] |
| Text page fault sleep time (ms). [2] |
| Data page fault sleep time (ms). [2] |
| Kernel page fault sleep time (ms). [2] |
| User lock wait sleep time (ms). [2] |
| Other sleep time (ms). [2] |
| Wait CPU (latency) time (ms). [2] |
| Time spent in stopped (suspended) state. [2] |
| Heap size. [3] |
| Stack size. [3] |
[1] Not if /proc rusage is used.
[2] Only from (Solaris?) /proc rusage.
[3] Only from /proc PRS usage.
On some systems, only utime will be filled in.
gethrvtime()
int
getsid(int
|void
pid
)
Get the process session ID for the given process. If pid is not specified, the session ID for the current process will be returned.
This function is not available on all platforms.
Throws an error if the system call fails.
getpid
, getpgrp
, setsid
array
(int
) gettimeofday()
Calls gettimeofday(); the result is an array of seconds, microseconds, and possible tz_minuteswes, tz_dstttime as given by the gettimeofday(2) system call (read the man page).
time()
, gethrtime()
int
getuid()
Get the real user ID.
setuid
, setgid
, getgid
, seteuid
,
geteuid
, setegid
, getegid
void
hardlink(string
from
, string
to
)
Create a hardlink named to
from the file from
.
This function is not available on all platforms.
symlink()
, mv()
, rm()
inherit _system : _system
void
initgroups(string
name
, int
base_gid
)
Initializes the supplemental group access list according to the system
group database. base_gid
is also added to the group access
list.
Throws errors on failure.
This function is not available on all platforms.
setuid()
, getuid()
, setgid()
, getgid()
, seteuid()
,
geteuid()
, setegid()
, getegid()
, getgroups()
, setgroups()
bool
innetgr(string
netgroup
, string
|void
machine
, string
|void
user
, string
|void
domain
)
Searches for matching entries in the netgroup database (usually
/etc/netgroup). If any of the machine
, user
or domain
arguments are zero or missing, those fields will match any
value in the selected netgroup
.
This function isn't available on all platforms.
float
nanosleep(int
|float
seconds
)
Call the system nanosleep() function.
This is not to be confused with the global function predef::sleep()
that does more elaborate things and can sleep with better precision
(although dependant on a normal functioning system clock).
Returns the remaining time to sleep (as the system function does).
predef::sleep()
sleep()
usleep()
May not be present; only exists if the function exists in the current system.
string(8bit)
normalize_path(string(8bit)
path
)
Normalize an existing Windows file system path.
The following transformations are currently done:
Forward slashes ('/'
) are converted to backward
slashes ('\'
).
Trailing slashes are removed, except a single slash after a
drive letter (e.g. "C:\"
is returned instead of
"C:"
).
Extraneous empty extensions are removed.
Short filenames are expanded to their corresponding long variants.
Relative paths are expanded to absolute paths.
Current- and parent-directory path components ("."
and ".."
) are followed, similar to combine_path
.
Case-information in directory and file names is restored.
Drive letters are returned in uppercase.
The host and share parts of UNC paths are returned in lowercase.
A normalized absolute path without trailing slashes.
Throws errors on failure, e.g. if the file or directory doesn't exist.
File fork information is currently not supported (invalid data).
In Pike 7.6 and earlier, this function didn't preserve a single slash after drive letters, and it didn't convert the host and share parts of an UNC path to lowercase.
combine_path()
, combine_path_nt()
void
openlog(string
ident
, int
options
, facility
)
Initializes the connection to syslogd.
ident.
The ident
argument specifies an identifier to tag all logentries
with.
options
A bitfield specifying the behaviour of the message logging. Valid options are:
| Log the process ID with each message. |
| Write messages to the console if they can't be sent to syslogd. |
| Open the connection to syslogd now and not later. |
| Do not wait for subprocesses talking to syslogd. |
facility
Specifies what subsystem you want to log as. Valid facilities are:
| Authorization subsystem |
| |
| Crontab subsystem |
| System daemons |
| Kernel subsystem (NOT USABLE) |
| For local use |
| |
| |
| |
| |
| |
| |
| |
| Line printer spooling system |
| Mail subsystem |
| Network news subsystem |
| |
| |
| UUCP subsystem |
Only available on systems with syslog(3).
LOG_NOWAIT should probably always be specified.
syslog
, closelog
int
rdtsc()
Executes the rdtsc (clock pulse counter) instruction and returns the result.
string
readlink(string
path
)
Returns what the symbolic link path
points to.
This function is not available on all platforms.
symlink()
string
resolvepath(string
path
)
Resolve all symbolic links of a pathname.
This function resolves all symbolic links, extra ``/'' characters and
references to /./ and /../ in pathname
, and returns the resulting
absolute path, or 0 (zero) if an error occurs.
This function is not available on all platforms.
readlink()
, symlink()
int
setegid(int
egid
)
Set the effective group ID to egid
. If egid
is
-1
the uid for "nobody" will be used.
Returns the current errno.
Throws an error if there is no "nobody" user when
egid
is -1
.
This function isn't available on all platforms.
int
seteuid(int
euid
)
Set the effective user ID to euid
. If euid
is
-1
the uid for "nobody" will be used.
Returns the current errno.
Throws an error if there is no
"nobody" user when euid
is -1
.
This function isn't available on all platforms.
int
setgid(int
gid
)
Sets the real group ID, effective group ID and saved group ID to gid
.
If gid
is -1
the uid for "nobody" will be used.
Throws an error if no "nobody" user when gid
is -1
.
Returns the current errno.
This function is not available on all platforms.
getuid()
, setuid()
, getgid()
, seteuid()
, geteuid()
,
setegid()
, getegid()
int
setgrent()
Rewinds the getgrent
pointer to the first entry
get_all_groups()
getgrent()
endgrent()
void
setgroups(array
(int
) gids
)
Set the supplemental group access list for this process.
Throws errors on failure.
This function is not available on all platforms.
initgroups()
, cleargroups()
, getgroups()
,
getgid()
, getgid()
, getegid()
, setegid()
float
setitimer(int
timer
, int
|float
value
)
Sets the timer
to the supplied value
. Returns the
current timer interval.
timer
One of ITIMER_REAL
, ITIMER_VIRTUAL
and ITIMER_PROF
.
int
setpgrp()
Make this process a process group leader.
Not supported on all platforms.
void
setproctitle(string
title
, mixed
... extra
)
Sets the processes title.
int
setpwent()
Resets the getpwent
function to the first entry in the passwd source
using the systemfunction setpwent(3).
Always 0
(zero)
get_all_users()
getpwent()
endpwent()
int
setresgid(int
rgid
, int
egid
, int
sgid
)
Sets the real, effective and saved group ID to rgid
,
egid
and sgid
respectively.
Returns zero on success and errno on failure.
int
setresuid(int
ruid
, int
euid
, int
suid
)
Sets the real, effective and saved set-user-ID to ruid
,
euid
and suid
respectively.
Returns zero on success and errno on failure.
bool
setrlimit(string
resource
, int
soft
, int
hard
)
Sets the soft
and the hard
process limit on a resource
.
getrlimit
, getrlimits
int
setsid()
Set a new process session ID for the current process, and return it.
This function isn't available on all platforms.
Throws an error if the system call fails.
getpid
, setpgrp
, getsid
int
setuid(int
uid
)
Sets the real user ID, effective user ID and saved user ID to uid
.
Returns the current errno.
This function isn't available on all platforms.
getuid()
, setgid()
, getgid()
, seteuid()
, geteuid()
,
setegid()
, getegid()
int
sleep(int
seconds
)
Call the system sleep() function.
This is not to be confused with the global function predef::sleep()
that does more elaborate things and can sleep with better precision
(although dependant on a normal functioning system clock).
The system's sleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.
If you don't need it to be independant of the system clock, use
predef::sleep()
instead.
May not be present; only exists if the function exists in the current system.
predef::sleep()
usleep()
nanosleep()
void
symlink(string
from
, string
to
)
Create a symbolic link named to
that points to from
.
This function is not available on all platforms.
hardlink()
, readlink()
, mv()
, rm()
void
sync()
Flush operating system disk buffers to permanent storage.
On some operating systems this may require administrative privileges.
void
syslog(int
priority
, string
msg
)
Writes the message msg
to the log with the priorities in
priority
.
priority
Priority is a bit vector with the wanted priorities or:ed together.
| LOG_EMERG, system is unusable. |
| LOG_ALERT, action must be taken immediately. |
| LOG_CRIT, critical conditions. |
| LOG_ERR, error conditions. |
| LOG_WARNING, warnind conditions. |
| LOG_NOTICE, normal, but significant, condition. |
| LOG_INFO, informational message. |
| LOG_DEBUG, debug-level message. |
int
umask(void
|int
mask
)
Set the current umask to mask
.
If mask
is not specified the current umask will not be changed.
Returns the old umask setting.
mapping
(string
:string
) uname()
Get operating system information.
The resulting mapping contains the following fields:
| Operating system name. |
| Hostname. |
| Operating system release. |
| Operating system version. |
| Hardware architecture. |
| Basic instruction set architecture. |
| List of upported instruction set architectures. Usually space-separated. |
| Specific model of hardware. |
| Manufacturer of the hardware. |
| Serial number of the hardware. |
| Secure RPC domain. |
This function only exists on systems that have the uname(2) or sysinfo(2) system calls.
Only the first five elements are always available.
void
usleep(int
usec
)
Call the system usleep() function.
This is not to be confused with the global function predef::sleep()
that does more elaborate things and can sleep with better precision
(although dependant on a normal functioning system clock).
The system's usleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.
If you don't need it to be independant of the system clock, use
predef::sleep()
instead.
May not be present; only exists if the function exists in the current system.
predef::sleep()
sleep()
nanosleep()
void
utime(string
path
, int
atime
, int
mtime
, void
|int
symlink
)
Set the last access time and last modification time for the path
path
to atime
and mtime
repectively. They are specified
as unix timestamps with 1 second resolution.
If symlink
is set and path
refers to a symlink, then the
timestamps for the symlink are set. Symlinks are dereferenced
otherwise.
Throws errors on failure.
This function is not available on all platforms. On some
platforms the symlink
flag isn't supported. In that case, the
function does nothing if path
is a symlink.
System.set_file_atime
, System.set_file_mtime
A popular demand is a class representing a raw piece of memory or a mmap'ed file. This is usually not the most effective way of solving a problem, but it might help in rare situations.
Using mmap can lead to segmentation faults in some cases. Beware, and read about mmap before you try anything. Don't blame Pike if you shoot your foot off.
int
sizeof( System.Memory arg )
returns the size of the memory (bytes). note: throws if not allocated
int
res = System.Memory()
[ pos
]
string
res = System.Memory()
[ pos1
]
System.Memory()
[ pos
] = char
System.Memory()
[ pos1
] = pos2
void
allocate(int
bytes
)
void
allocate(int
bytes
, int(8bit)
fill
)
(
string
)System.Memory()
(array
)System.Memory()
Cast to string or array.
Throws if not allocated.
System.Memory System.Memory()
System.Memory System.Memory(
string
|Stdio.File
filename_to_mmap
)
System.Memory System.Memory(
int
shmkey
, int
shmsize
, int
shmflg
)
System.Memory System.Memory(
int
bytes_to_allocate
)
Will call mmap()
or allocate()
depending on argument, either mmap'ing a file
(in shared mode, writeable if possible) or allocating
a chunk of memory.
void
free()
Free the allocated or <tt>mmap</tt>ed memory.
int
mmap(string
|Stdio.File
file
)
int
mmap(string
|Stdio.File
file
, int
offset
, int
size
)
int
mmap_private(string
|Stdio.File
file
)
int
mmap_private(string
|Stdio.File
file
, int
offset
, int
size
)
mmap a file. This will always try to mmap the file in PROT_READ|PROT_WRITE, readable and writable, but if it fails it will try once more in PROT_READ only.
string
pread(int(0..)
pos
, int(0..)
len
)
string
pread16(int(0..)
pos
, int(0..)
len
)
string
pread32(int(0..)
pos
, int(0..)
len
)
string
pread16i(int(0..)
pos
, int(0..)
len
)
string
pread32i(int(0..)
pos
, int(0..)
len
)
string
pread16n(int(0..)
pos
, int(0..)
len
)
string
pread32n(int(0..)
pos
, int(0..)
len
)
Read a string from the memory. The 16 and 32 variants reads widestrings, 16 or 32 bits (2 or 4 bytes) wide, the i variants in intel byteorder, the normal in network byteorder, and the n variants in native byteorder.
len
is the number of characters, wide or not. pos
is the byte position (!).
int
pwrite(int(0..)
pos
, string
data
)
int
pwrite16(int(0..)
pos
, string
data
)
int
pwrite32(int(0..)
pos
, string
data
)
int
pwrite16i(int(0..)
pos
, string
data
)
int
pwrite32i(int(0..)
pos
, string
data
)
Write a string to the memory (and to the file, if it's mmap()ed). The 16 and 32 variants writes widestrings, 16 or 32 bits (2 or 4 bytes) wide, the 'i' variants in intel byteorder, the other in network byteorder.
returns the number of bytes (not characters) written
bool
valid()
returns 1 if the memory is valid, 0 if not allocated
bool
writeable()
returns 1 if the memory is writeable, 0 if not
A wrapper for the system struct tm time keeping structure. This can be used as a (very) lightweight alternative to Calendar.
string
asctime()
Return a string representing the time. Mostly useful for debug
purposes, the exact format is very locale (see
Gettext.setlocale
) and OS dependent.
(
int
)System.TM()
(string
)System.TM()
Casted to an integer unix_time
will be returned.
Casting to a string will call asctime
.
System.TM System.TM(
int
|Gmp.mpz
t
)
Create a new TM
initialized from a unix time_t.
The timezone will always be UTC when using this function.
System.TM System.TM()
Construct a new TM, all fields will be set to 0.
System.TM System.TM(
int
year
, int(0..11)
mon
, int(1..31)
mday
, int(0..24)
hour
, int(0..59)
min
, int(0..59)
sec
, string
|void
timezone
)
Construct a new time using the given values. Slightly faster than setting them individually.
bool
gmtime(int
time
)
Initialize the struct tm to the UTC time for the specified unix time_t.
bool
gmtime(Gmp.mpz
time
)
Initialize the struct tm to the UTC time for the specified unix time_t.
int
System.TM.gmtoff
The offset from GMT for the time in this tm-struct
int(0..60)
System.TM.sec
int(0..59)
System.TM.min
int(0..59)
System.TM.hour
int(1..31)
System.TM.mday
int(0..11)
System.TM.mon
int
System.TM.year
The various fields in the structure. Note that setting these might cause other fields to be recalculated, as an example, adding 1000 to the hour field would advance the 'mday', 'mon' and possibly 'year' fields.
When read the fields are always normalized.
Unlike the system struct tm the 'year' field is not year-1900, instead it is the actual year.
int
System.TM.isdst
True if daylight-saving is in effect. If this field is -1 (the default) it (and the timezone info) will be updated automatically using the timezone rules.
bool
localtime(int
time
)
Initialize the struct tm to the local time for the specified unix time_t.
string(1..255)
strftime(string(1..255)
format
)
See also Gettext.setlocale
Convert the structure to a string.
The abbreviated weekday name according to the current locale
The full weekday name according to the current locale.
The abbreviated month name according to the current locale.
The full month name according to the current locale.
The preferred date and time representation for the current locale.
The century number (year/100) as a 2-digit integer.
The day of the month as a decimal number (range 01 to 31).
Equivalent to %m/%d/%y
. (for Americans only.
Americans should note that in other countries %d/%m/%y
is rather common. This means that in international context
this format is ambiguous and should not be used.)
Like %d
, the day of the month as a decimal number,
but a leading zero is replaced by a space.
Modifier: use alternative format, see below.
Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
The ISO 8601 week-based year (see NOTES) with century as a
decimal number. The 4-digit year corresponding to the ISO
week number (see %V
). This has the same format and
value as %Y
, except that if the ISO week number
belongs to the previous or next year, that year is used instead.
Like %G
, but without century, that is,
with a 2-digit year (00-99). (TZ)
Equivalent to %b.
The hour as a decimal number using a 24-hour clock (range 00 to 23).
The hour as a decimal number using a 12-hour clock (range 01 to 12).
The day of the year as a decimal number (range 001 to 366).
The month as a decimal number (range 01 to 12).
The minute as a decimal number (range 00 to 59).
A newline character. (SU)
Modifier: use alternative format, see below. (SU)
Either "AM"
or "PM"
according to the given time
value, or the corresponding strings for the current locale.
Noon is treated as "PM"
and midnight as "AM"
.
Like %p
but in lowercase: "am"
or "pm"
or a corresponding string for the current locale.
The time in a.m. or p.m. notation. In the POSIX locale this is
equivalent to %I:%M:%S %p
.
The time in 24-hour notation (%H:%M
). (SU)
For a version including the seconds, see %T
below.
The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)
The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)
A tab character. (SU)
The time in 24-hour notation (%H:%M:%S
). (SU)
The day of the week as a decimal, range 1 to 7, Monday being 1.
See also %w
. (SU)
The week number of the current year as a decimal number,
range 00 to 53, starting with the first Sunday as the first
day of week 01. See also %V
and %W
.
The ISO 8601 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least
4 days in the new year. See also %U
and %W
.
The day of the week as a decimal, range 0 to 6, Sunday being 0.
See also %u
.
bool
strptime(string(1..255)
format
, string(1..255)
data
)
Parse the given data
using the format in format
as a date.
The % character.
The weekday name according to the C locale, in abbreviated form or the full name.
The month name according to the C locale, in abbreviated form or the full name.
The date and time representation for the C locale.
The century number (0-99).
The day of month (1-31).
Equivalent to %m/%d/%y.
The hour (0-23).
The hour on a 12-hour clock (1-12).
The day number in the year (1-366).
The month number (1-12).
The minute (0-59).
Arbitrary whitespace.
The C locale's equivalent of AM or PM.
Equivalent to %H:%M.
The second (0-60; 60 may occur for leap seconds; earlier also 61 was allowed).
Arbitrary whitespace.
Equivalent to %H:%M:%S.
The week number with Sunday the first day of the week (0-53).
The weekday number (0-6) with Sunday = 0.
The week number with Monday the first day of the week (0-53).
The date, using the C locale's date format.
The time, using the C locale's time format.
The year within century (0-99). When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969-1999); values in the range 00-68 refer to years in the twenty-first century (2000-2068).
The year, including century (for example, 1991).
int
unix_time()
Return the unix time corresponding to this time_t. If no time can be parsed from the structure -1 is returned.
int
System.TM.wday
The day of the week, sunday is 0, saturday is 6. This is calculated from the other fields and can not be changed directly.
int
System.TM.yday
The day of the year, from 0 (the first day) to 365 This is calculated from the other fields and can not be changed directly.
string
System.TM.zone
The timezone of this structure
The current time as a structure containing a sec and a usec member.
System.Time System.Time(
int
fast
)
If fast
is true, do not request a new time from the system,
instead use the global current time variable.
This will only work in callbacks, but can save significant amounts of CPU.
int
System.Time.sec
int
System.Time.usec
The number of seconds and microseconds since the epoch and the
last whole second, respectively. (See also predef::time()
)
Please note that these variables will continually update when they are requested, there is no need to create new Time() objects.
int
System.Time.usec_full
The number of microseconds since the epoch. Please note that pike needs to have been compiled with bignum support for this variable to contain sensible values.
System.Timer System.Timer(
int
|void
fast
)
Create a new timer object. The timer keeps track of relative time with sub-second precision.
If fast
is specified, the timer will not do system calls to get
the current time but instead use the one maintained by pike. This
will result in faster but more or less inexact timekeeping.
The pike maintained time is only updated when a Pike.Backend
object stops waiting and starts executing code.
float
get()
Return the time in seconds since the last time get was called. The first time this method is called the time since the object was created is returned instead.
float
peek()
Return the time in seconds since the last time get
was called.
string
describe_event_flag(int
mask
)
describe the event flags associated with an event.
a string describing the flags set.
inherit System._FSEvents : _FSEvents
The System.FSEvents
module provides an interface to FSEvents.
FSEvents is an API in Mac OS X which allows an application to register
for notifications of changes to a given directory tree without forcing
the application to continously poll the directory tree.
This module is designed for use in asynchronous, or backend mode. That is, rather than polling for changes, a function you specify will be called when events of interest occur.
This module requires the presence and use of a CFRunLoop based Backend object, otherwise this module will not receive events from the OS. CFRunLoop based backends are avilable on Mac OS X 10.5 and higher.
Pike.PollDeviceBackend.enable_core_foundation
A variation of EventStream
that provides a blocking interface.
A quirk of the underlying IO subsystem in CoreFoundation is that
there is exactly one runloop per thread. Because FSEvents uses
CoreFoundation, this means that there's no meaningful way to
specify which backend should process these events. Therefore,
always make sure that the thread you create the EventStream
object is the same one you read events from, otherwise
read_event
will run not run the EventLoop that this
EventStream is registered with, resulting in events never being
delivered.
System.FSEvents.BlockingEventStream System.FSEvents.BlockingEventStream(
array
(string
) paths
, float
latency
, int
|void
since_when
, int
|void
flags
)
inherit .EventStream : EventStream
mixed
read_event(void
|float
timeout
)
wait for an event to be received, and return it.
timeout
an optional limit to the amount of time we're willing to wait
void
add_path(string
path
)
Add a path to the monitor list.
path
this can only be called when the monitor is stopped.
System.FSEvents.EventStream System.FSEvents.EventStream(
array
(string
) paths
, float
latency
, int
|void
since_when
, int
|void
flags
)
Creates a new Public.System.FSEvents.EventStream object
paths
An array with each element containing a path to a directory, signifying the root of a filesystem hierarchy to be watched for modifications.
Additional paths may be added later using add_path()
, though only if the stream is stopped.
latency
The number of seconds the service should wait after hearing about an event from the kernel before passing it along to the client via its callback. Specifying a larger value may result in more effective temporal coalescing, resulting in fewer callbacks and greater overall efficiency.
since_when
The service will supply events that have happened after the given event ID. To ask for events "since now" pass the constant kFSEventStreamEventIdSinceNow. Do not pass zero for this value unless you want to receive events for the requested directories "since the beginning of time".
flags
Flags that modify the behavior of the stream being created. See Apple's FSEvents documentation for details of the various flags available.
void
flush_async()
Requests that the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created.
This flushing occurs asynchronously -- events most likely will not have been delivered by the time this call returns.
Only call this function after the stream has been started, via start().
void
flush_sync()
Requests that the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created.
Flushing synchronously when using this method; clients will have received all the callbacks by the time this call returns to them.
Only call this function after the stream has been started, via start().
int
is_started()
Has start() been called?
constant
System.FSEvents.EventStream.kFSEventStreamCreateFlagFileEvents
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamCreateFlagIgnoreSelf
Available in MacOS X 10.6 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamCreateFlagNoDefer
constant
System.FSEvents.EventStream.kFSEventStreamCreateFlagNone
constant
System.FSEvents.EventStream.kFSEventStreamCreateFlagWatchRoot
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagChangeOwner
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagEventIdsWrapped
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagFinderInfoMod
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagHistoryDone
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagInodeMetaMod
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagIsDir
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagIsFile
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagIsSymlink
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagItemCreated
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagItemModified
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagItemRemoved
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagKernelDropped
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagMount
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagMustScanSubDirs
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagNone
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagRenamed
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagRootChanged
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagUnmount
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagUserDropped
constant
System.FSEvents.EventStream.kFSEventStreamEventFlagXattrMod
Available in MacOS X 10.7 and newer.
constant
System.FSEvents.EventStream.kFSEventStreamEventIdSinceNow
void
set_callback(function
(:void
) callback
)
Sets the function that will be called when a file notification event is received.
The method signature for the callback is:
void event_callback(string path, int flags, int event_id)
void
start()
Requests that new events be delivered to this EventStream.
If a value was supplied for the since_when parameter then "historical" events will be sent via your callback first, then a HistoryDone event, then "contemporary" events will be sent on an ongoing basis.
void
stop()
Stops watching for new events.
This module implements an API to linux inotify. It is available on all kernels from version 2.6.13 onwards. Inotify offers fast and scalable file notifications.
constant
System.Inotify.IN_ACCESS
constant
System.Inotify.IN_ATTRIB
constant
System.Inotify.IN_CLOSE
constant
System.Inotify.IN_CLOSE_WRITE
constant
System.Inotify.IN_CLOSE_NOWRITE
constant
System.Inotify.IN_CREATE
constant
System.Inotify.IN_DELETE
constant
System.Inotify.IN_DELETE_SELF
constant
System.Inotify.IN_MODIFY
constant
System.Inotify.IN_MOVE_SELF
constant
System.Inotify.IN_MOVED_FROM
constant
System.Inotify.IN_MOVED_TO
constant
System.Inotify.IN_OPEN
constant
System.Inotify.IN_MOVE
constant
System.Inotify.IN_CLOSE
constant
System.Inotify.IN_DONT_FOLLOW
constant
System.Inotify.IN_MASK_ADD
constant
System.Inotify.IN_ONESHOT
constant
System.Inotify.IN_ONLYDIR
constant
System.Inotify.IN_IGNORED
constant
System.Inotify.IN_ISDIR
constant
System.Inotify.IN_Q_OVERFLOW
constant
System.Inotify.IN_UNMOUNT
Please have a look at the inotify(7) manpage for information about these constants.
Some constants may not be available when the module has been compiled on a machine with linux kernel before 2.6.15. See the manpage for more details.
constant
System.Inotify.IN_ALL_EVENTS
This is a derived constant that is not part of the standard inotify API. It is the union of all other constants.
string
describe_mask(int
mask
)
Turn an event mask into a human readable representation. This is used for debugging purpose.
array
(string
|int
) parse_event(string
data
)
Parses one inotify_event struct from data
.
Returns an array consisting of
Array | |
| The watch descriptor returned by |
| An integer that describes the event that occured. See the inotify manpage for a list of possible events and their numerical identifiers. |
| An integer cookie that can be used to group together different events that were triggered by moving a file from one location to another. |
| The name of the file. This will only be present if the
event happened to a file in a directory that was
watched, e.g. with |
| The length of the data that has been parsed. If the |
More convenient interface to inotify(7). Automatically reads events from the inotify file descriptor and parses them.
Objects of this class will be destructed when they go out of external
references. As such they behave differently from other classes which use
callbacks, e.g. Stdio.File
.
The number of inotify instances is limited by ulimits.
int
add_watch(string
filename
, int
mask
, function
(int
, int
, string
, mixed
... :void
) callback
, mixed
... extra
)
Add a watch for a certain file and a set of events specified by
mask
. The function callback
will be called when
such an event occurs. The arguments to the callback will be the
events mask, the cookie, the filename
and extra
.
Returns a watch descriptor which can be used to remove the watch.
When adding a second watch for the same file the old one
will be removed unless System.Inotify.IN_MASK_ADD
is
contained in mask
.
The mask of an event may be a subset of the mask given when adding the watch.
In case the watch is added for a regular file, the filename will be passed to the callback. In case the watch is added for a directory, the name of the file to which the event happened inside the directory will be concatenated.
inherit _Instance : _Instance
Simple wrapper class that gives direct access to the inotify(7)
interface. On create an inotify instance is initiated by calling
inotify_init(2). Every object of this class has its own inotify
file descriptor. Use this class only if you want direct access to
the file descriptor to read from it manually. For a more user
friendly interface use System.Inotify.Instance
.
System.Inotify.Instance
int
add_watch(string
path
, int
mask
)
Add a watch for a certain file or directory and specific events.
Adding more than one watch for a path will overwrite the
previous watch unless System.Inotify.IN_MASK_ADD
is contained
in the mask.
path
Path of the file or directory.
mask
Integer mask specifying the event type. This can be a
combination of different event types using bitwise OR.
See the inotify manpage for possible values and their
description. The values defined by the inotify header
file are exported by System.Inotify
as constants
using the same names (e.g. System.Inotify.IN_CREATE
).
Returns a watch descriptor on success, and -1
on filesystem-related failures, in which case errno()
will indicate the cause. These typically indicate time of
check, time of use race conditions. For other failures
errors are thrown.
Subdirectories are not watched. If you want to watch subdirectories as well, you need to add watches for them individually.
At creation of a watch for a directory, simulated
IN_CREATE
-events with cookie 0x7fffffff
will
be added for the initial contents of the directory.
This is to reduce the risk of losing state changes
due to races. Note that is is not known whether these
paths are in flux or not. Note also that there may
be multiple notifications for content that is created
at the moment the watch is created.
In old versions of Pike errors were thrown for all failures.
rm_watch()
, parse_event()
private
function
(int
, int
, int
, string
:void
) System.Inotify._Instance.event_callback
Callback function that is called when an event is triggered.
set_event_callback()
, query_event_callback()
function
(int
, int
, int
, string
:void
) get_event_callback()
Get the current event_callback
.
set_event_callback()
, event_callback
, poll()
void
poll()
Check for any pending events.
Any pending events will be read and parsed, and event_callback
will
be called once for each event. The arguments to the event_callback
will be:
Array | |
| The watch descriptor that was triggered. |
| The event that was triggerend (one of IN_*). |
| An integer cookie used to identify grouped events. |
| The name of the path segment (if any). |
This function is called by the backend when there are events pending.
set_event_callback()
int
query_fd()
Returns the file descriptor associated with this inotify instance.
int
rm_watch(int
wd
)
Remove a watch.
wd
The watch descriptor that was returned by add_watch()
.
void
set_backend(Pike.Backend
backend
)
Set the backend used for callbacks.
set_event_callback()
, set_nonblocking()
, poll()
void
set_blocking()
Disable backend callback mode.
The configured backend will stop calling poll()
, so
poll()
will need to be called by hand.
set_blocking()
, poll()
void
set_event_callback(function
(int
, int
, int
, string
:void
) cb
)
Set the event_callback
.
get_event_callback()
, event_callback
, poll()
void
set_nonblocking()
Enable backend callback mode.
The configured backend will call poll()
automatically
as soon as there are events pending.
set_blocking()
, poll()
An interface to Windows filesystem change information.
constant
System.Wnotify.FILE_NOTIFY_CHANGE_ATTRIBUTES
constant
System.Wnotify.FILE_NOTIFY_CHANGE_DIR_NAME
constant
System.Wnotify.FILE_NOTIFY_CHANGE_FILE_NAME
constant
System.Wnotify.FILE_NOTIFY_CHANGE_LAST_WRITE
constant
System.Wnotify.FILE_NOTIFY_CHANGE_SECURITY
constant
System.Wnotify.FILE_NOTIFY_CHANGE_SIZE
void
add_handle(NotificationHandle
handle
)
NotificationHandle
|int
poll(void
|float
timeout
)
System.Wnotify.NotificationHandle System.Wnotify.NotificationHandle(
string
path
, int
watch_subtree
, int
filter
)
int
get_error()
optional
__deprecated__
Thread
`()(mixed
f
, mixed
... args
)
Create a new thread.
Replaced by predef::Thread.Thread
.
array
(Thread.Thread
) all_threads()
This function returns an array with the thread ids of all threads.
Thread()
int(0..)
get_thread_quanta()
Returns the current thread quanta in nanoseconds.
set_thread_quanta()
, gethrtime()
int(0..)
set_thread_quanta(int(0..)
ns
)
Set the thread quanta.
ns
New thread quanta in nanoseconds. A value of zero (default) disables the thread quanta checks.
When enabled MasterObject.thread_quanta_exceeded()
will
be called when a thread has spent more time than the quanta
without allowing another thread to run.
Setting a non-zero value that is too small to allow for
MasterObject.thread_quanta_exceeded()
to run is NOT a
good idea.
Returns the previous thread quanta in nanoseconds.
set_thread_quanta()
, gethrtime()
Thread.Thread
this_thread()
This function returns the object that identifies this thread.
Thread()
void
thread_set_concurrency(int
concurrency
)
Document this function
Implementation of condition variables.
Condition variables are used by threaded programs to wait for events happening in other threads.
In order to prevent races (which is the whole point of condition variables), the modification of a shared resource and the signal notifying modification of the resource must be performed inside the same mutex lock, and the examining of the resource and waiting for a signal that the resource has changed based on that examination must also happen inside the same mutex lock.
Typical wait operation:
Take mutex lock
Read/write shared resource
Wait for the signal with the mutex lock in released state
Reacquire mutex lock
If needed, jump back to step 2 again
Release mutex lock
Typical signal operation:
Take mutex lock
Read/write shared resource
Send signal
Release mutex lock
You have some resource that multiple treads want to use. To protect this resource for simultaneous access, you create a shared mutex. Before you read or write the resource, you take the mutex so that you get a consistent and private view of / control over it. When you decide that the resource is not in the state you want it, and that you need to wait for some other thread to modify the state for you before you can continue, you wait on the conditional variable, which will temporarily relinquish the mutex during the wait. This way a different thread can take the mutex, update the state of the resource, and then signal the condition (which does not in itself release the mutex, but the signalled thread will be next in line once the mutex is released).
Condition variables are only available on systems with thread support. The Condition class is not simulated otherwise, since that can't be done accurately without continuations.
Mutex
void
broadcast()
broadcast()
wakes up all threads currently waiting for this condition.
signal()
void
signal()
signal()
wakes up one of the threads currently waiting for the
condition.
Sometimes more than one thread is woken up.
broadcast()
void
wait(Thread.MutexKey
mutex_key
)
void
wait(Thread.MutexKey
mutex_key
, int(0..)
|float
seconds
)
void
wait(Thread.MutexKey
mutex_key
, int(0..)
seconds
, int(0..999999999)
nanos
)
Wait for condition.
This function makes the current thread sleep until the condition variable is signalled or the timeout is reached.
mutex_key
A Thread.MutexKey
object for a Thread.Mutex
. It will be
unlocked atomically before waiting for the signal and then
relocked atomically when the signal is received or the timeout
is reached.
seconds
Seconds to wait before the timeout is reached.
nanos
Nano (1/1000000000) seconds to wait before the timeout is reached.
This value is added to the number of seconds specified by seconds
.
A timeout of zero seconds disables the timeout.
The thread that sends the signal should have the mutex locked
while sending it. Otherwise it's impossible to avoid races where
signals are sent while the listener(s) haven't arrived to the
wait
calls yet.
The support for timeouts was added in Pike 7.8.121, which was after the first public release of Pike 7.8.
Note that the timeout is approximate (best effort), and may be exceeded if eg the mutex is busy after the timeout.
In Pike 7.2 and earlier it was possible to call wait()
without arguments. This possibility was removed in later
versions since it unavoidably leads to programs with races
and/or deadlocks.
Note also that any threads waiting on the condition will be woken up when it gets destructed.
Mutex->lock()
A thread farm.
string
debug_status()
Get some statistics for the thread farm.
Result
run(function
(:void
) f
, mixed
... args
)
Register a job for the thread farm.
f
Function to call with @args
to
perform the job.
args
The parameters for f
.
Returns a Result
object for the job.
In Pike 7.8 and earlier this function
was broken and returned a Result
object that wasn't connected to the job.
run_async()
void
run_async(function
(:void
) f
, mixed
... args
)
Register a job for the thread farm
where the return value from f
is
ignored.
f
Function to call with @args
to
perform the job.
args
The parameters for f
.
run()
Result
run_multiple(array
(array
(function
(:void
)|array
)) fun_args
)
Register multiple jobs.
fun_args
An array of arrays where the first element is a function to call, and the second is a corresponding array of arguments.
Returns a Result
object with an array
with one element for the result for each
of the functions in fun_args
.
Do not modify the elements of fun_args
before the result is available.
If any of the functions in fun_args
throws
and error, all of the accumulated results
(if any) will be dropped from the result, and
the first backtrace be provided.
run_multiple_async()
void
run_multiple_async(array
fun_args
)
Register multiple jobs where the return values are to be ignored.
fun_args
An array of arrays where the first element is a function to call, and the second is a corresponding array of arguments.
Do not modify the elements of fun_args
before the result is available.
run_multiple()
int
set_max_num_threads(int(1..)
to
)
Set the maximum number of worker threads that the thread farm may have.
to
The new maximum number.
If there are more worker threads than to
,
the function will wait until enough threads
have finished, so that the total is to
or less.
The default maximum number of worker threads is 20
.
void
set_thread_name_cb(function
(object
, string
:void
) cb
, void
|string
prefix
)
Provide a callback function to track names of threads created by the farm.
cb
The callback function. This will get invoked with the thread as the
first parameter and the name as the second whenever a thread is
created. When the same thread terminates the callback is invoked
again with 0
as the second parameter. Set cb
to 0
to stop
any previously registered callbacks from being called.
prefix
An optional name prefix to distinguish different farms. If not given a prefix will be generated automatically.
A worker thread.
string
debug_status()
Get some statistics about the worker thread.
An asynchronous result.
mixed
res = Thread.Farm.Result()
()
Wait for completion.
void
provide(mixed
what
)
Register a completed result.
what
The result to register.
void
provide_error(mixed
what
)
Register a failure.
what
The corresponding backtrace.
mixed
result()
Returns the result if available, a backtrace on failure,
and 0
(zero) otherwise.
void
set_done_cb(function
(:void
) to
)
Register a callback to be called when the result is available.
to
Callback to be called. The first
argument to the callback will be
the result or the failure backtrace,
and the second 0
(zero) on
success, and 1
on failure.
int
status()
| Returns |
| Returns |
| Returns negative on failure. |
Fifo
implements a fixed length first-in, first-out queue.
A fifo is a queue of values and is often used as a stream of data
between two threads.
Queue
Thread.Fifo Thread.Fifo()
Thread.Fifo Thread.Fifo(
int
size
)
Create a fifo. If the optional size
argument is present it
sets how many values can be written to the fifo without blocking.
The default size
is 128.
inherit Mutex : lock
inherit Condition : r_cond
inherit Condition : w_cond
mixed
read()
This function retrieves a value from the fifo. Values will be returned in the order they were written. If there are no values present in the fifo the current thread will sleep until some other thread writes one.
try_read()
, read_array()
, write()
array
read_array()
This function returns all values in the fifo as an array. The values in the array will be in the order they were written. If there are no values present in the fifo the current thread will sleep until some other thread writes one.
read()
, try_read_array()
int
size()
This function returns the number of elements currently in the fifo.
read()
, write()
mixed
try_read()
This function retrieves a value from the fifo if there is any
there. Values will be returned in the order they were written.
If there are no values present in the fifo then UNDEFINED
will be returned.
read()
array
try_read_array()
This function returns all values in the fifo as an array but doesn't wait if there are no values there. The values in the array will be in the order they were written.
read_array()
int
try_write(mixed
value
)
Append a value
to the end of the fifo. If there is no more
room in the fifo then zero will be returned, otherwise the
number of items in the fifo after the write is returned.
read()
int
write(mixed
value
)
Append a value
to the end of the fifo. If there is no more
room in the fifo the current thread will sleep until space is
available. The number of items in the queue after the write is
returned.
read()
Thread local variable storage.
This class allows you to have variables which are separate for each
thread that uses it. It has two methods: get()
and set()
. A value
stored in an instance of Local
can only be retrieved by that
same thread.
This class is simulated when Pike is compiled without thread support, so it's always available.
mixed
get()
Get the thread local value.
This returns the value prevoiusly stored in the Local
object by
the set()
method by this thread.
set()
mixed
set(mixed
value
)
Set the thread local value.
This sets the value returned by the get
method.
Calling this method does not affect the value returned by get()
when
it's called by another thread (ie multiple values can be stored at the
same time, but only one value per thread).
This function returns its argument.
Note that the value set can only be retreived by the same thread.
get()
Mutex
is a class that implements mutual exclusion locks.
Mutex locks are used to prevent multiple threads from simultaneously
execute sections of code which access or change shared data. The basic
operations for a mutex is locking and unlocking. If a thread attempts
to lock an already locked mutex the thread will sleep until the mutex
is unlocked.
This class is simulated when Pike is compiled without thread support, so it's always available.
In POSIX threads, mutex locks can only be unlocked by the same thread that locked them. In Pike any thread can unlock a locked mutex.
string sprintf(string format, ... Thread.Mutex arg ... )
Describes the mutex including the thread that currently holds the lock (if any).
Thread.MutexKey
current_locking_key()
This mutex method returns the key object currently governing the lock on this mutex. 0 is returned if the mutex isn't locked.
Thread()
Thread.Thread
current_locking_thread()
This mutex method returns the object that identifies the thread that has locked the mutex. 0 is returned if the mutex isn't locked.
Thread()
MutexKey
lock()
MutexKey
lock(int
type
)
This function attempts to lock the mutex. If the mutex is already locked by a different thread the current thread will sleep until the mutex is unlocked. The value returned is the 'key' to the lock. When the key is destructed or has no more references the mutex will automatically be unlocked.
The type
argument specifies what lock()
should do if the
mutex is already locked by this thread:
| Throw an error. |
| Sleep until the mutex is unlocked. Useful if some other thread will unlock it. |
| Return zero. This allows recursion within a locked region of code, but in conjunction with other locks it easily leads to unspecified locking order and therefore a risk for deadlocks. |
If the mutex is destructed while it's locked or while threads are
waiting on it, it will continue to exist internally until the last
thread has stopped waiting and the last MutexKey
has
disappeared, but further calls to the functions in this class will
fail as is usual for destructed objects.
Pike 7.4 and earlier destructed any outstanding lock when the
mutex was destructed, but threads waiting in lock
still got
functioning locks as discussed above. This is inconsistent no
matter how you look at it, so it was changed in 7.6. The old
behavior is retained in compatibility mode for applications that
explicitly destruct mutexes to unlock them.
trylock()
MutexKey
trylock()
MutexKey
trylock(int
type
)
This function performs the same operation as lock()
, but if the mutex
is already locked, it will return zero instead of sleeping until it's
unlocked.
lock()
Objects of this class are returned by Mutex()->lock()
and Mutex()->trylock()
. They are also passed as arguments
to Condition()->wait()
.
As long as they are held, the corresponding mutex will be locked.
The corresponding mutex will be unlocked when the object is destructed (eg by not having any references left).
Mutex
, Condition
Queue
implements a queue, or a pipeline. The main difference
between Queue
and Fifo
is that Queue
will never block in write(), only allocate more memory.
Ought to be made API-compatible with ADT.Queue
.
Fifo
, ADT.Queue
inherit Mutex : lock
inherit Condition : r_cond
array
peek_array()
Returns a snapshot of all the values in the queue, in the order they were written. The values are still left in the queue, so if other threads are reading from it, the returned value should be considered stale already on return.
mixed
read()
This function retrieves a value from the queue. Values will be returned in the order they were written. If there are no values present in the queue the current thread will sleep until some other thread writes one.
try_read()
, write()
array
read_array()
This function returns all values in the queue as an array. The values in the array will be in the order they were written. If there are no values present in the queue the current thread will sleep until some other thread writes one.
read()
, try_read_array()
int
size()
This function returns the number of elements currently in the queue.
read()
, write()
mixed
try_read()
This function retrieves a value from the queue if there is any
there. Values will be returned in the order they were written.
If there are no values present in the fifo then UNDEFINED
will be returned.
write()
array
try_read_array()
This function returns all values in the queue as an array but doesn't wait if there are no values there. The values in the array will be in the order they were written.
read_array()
int
write(mixed
value
)
This function puts a value
last in the queue. If the queue is
too small to hold the value
it will be expanded to make room.
The number of items in the queue after the write is returned.
read()
Implements an inverted-semaphore-like resource
counter. A thread can poll or perform a blocking wait for the
resource-count to drop below a certain level
.
ResourceCountKey
, Condition
, Mutex
final
ResourceCountKey
acquire()
Increments the resource-counter.
A ResourceCountKey
to decrement the resource-counter again.
final
bool
drained(void
|int
level
)
level
The maximum level that is considered drained.
True if the resource counter drops to equal or below level
.
final
void
wait_till_drained(void
|int
level
)
Blocks until the resource-counter dips to max level
.
level
The maximum level that is considered drained.
When this key is destroyed, the corresponding resource counter will be decremented.
ResourceCount
, MutexKey
private
inherit Pike.DestructImmediate : DestructImmediate
string sprintf(string format, ... Thread.Thread arg ... )
Returns a string identifying the thread.
array
(mixed
) backtrace()
Returns the current call stack for the thread.
The result has the same format as for predef::backtrace()
.
predef::backtrace()
Thread.Thread Thread.Thread(
function
(mixed
... :mixed
|void
) f
, mixed
... args
)
This function creates a new thread which will run simultaneously
to the rest of the program. The new thread will call the function
f
with the arguments args
. When f
returns the thread will cease
to exist.
All Pike functions are 'thread safe' meaning that running a function at the same time from different threads will not corrupt any internal data in the Pike process.
The returned value will be the same as the return value of
this_thread()
for the new thread.
This function is only available on systems with POSIX or UNIX or WIN32 threads support.
Mutex
, Condition
, this_thread()
protected
int
id_number()
Returns an id number identifying the thread.
This function was added in Pike 7.2.204.
void
interrupt()
void
interrupt(string
msg
)
Interrupt the thread with the message msg
.
The argument msg
is currently ignored.
Interrupts are asynchronous, and are currently not queued.
void
kill()
Interrupt the thread, and terminate it.
Interrupts are asynchronous, and are currently not queued.
int
status()
Returns the status of the thread.
|
|
|
|
mixed
wait()
Waits for the thread to complete, and then returns the value returned from the thread function.
Rethrows the error thrown by the thread if it exited by throwing an error.
Display a image on the screen. Requires GTK.
typedef
Standards.URI
|string
|Image.Image
|Image.Layer
|array
(Image.Layer
) Tools.PV.PVImage
The image types accepted. If the image is a string, it is assumed to be a filename of a image that can be loaded with Image.load. This includes URLs.
Image.Image
get_as_image(PVImage
i
)
Return the current image as a Image object, with the alpha combining done.
inherit GTK.Window : Window
void
save(string
filename
, string
|void
format
)
Write the image to a file. If no format is specified, PNG is used. The alpha combination is done on the image before it's saved.
void
scale(float
factor
)
Scale the image before display with the specified factor.
void
set_alpha_colors(Image.Color.Color
c1
, Image.Color.Color
|void
c2
)
Set the colors used for the alpha combination. c2
is only used
for the Squares
alpha mode.
set_alpha_mode()
void
set_alpha_mode(AlphaMode
m
)
Set the alpha combining mode. m
is one of Squares
, Solid
,
None
and AlphaOnly
.
void
set_image(PVImage
i
)
Change the image.
The alpha combination modes.
Use set_alpha_mode()
to change the mode.
constant
Tools.PV.AlphaOnly
Only show the alpha channel (if any).
constant
Tools.PV.None
Ignore alpha.
constant
Tools.PV.Solid
Solid color.
constant
Tools.PV.Squares
Checkerboard pattern (default).
Flags affecting autodoc extractor behaviour.
ProcessXML.extractXML()
, MirarDocParser
,
Tools.Standalone.extract_autodoc()
constant
Tools.AutoDoc.FLAG_COMPAT
Attempt to be compatible with old Pike.
constant
Tools.AutoDoc.FLAG_DEBUG
Full verbosity.
constant
Tools.AutoDoc.FLAG_KEEP_GOING
Attempt to keep going after errors.
constant
Tools.AutoDoc.FLAG_NORMAL
Normal verbosity.
constant
Tools.AutoDoc.FLAG_NO_DYNAMIC
Reduce the amount of dynamic information in the generated files (line numbers, extractor version, extraction time, etc).
constant
Tools.AutoDoc.FLAG_QUIET
Keep quiet about non-fatal errors.
constant
Tools.AutoDoc.FLAG_VERBOSE
Extra verbosity.
constant
Tools.AutoDoc.FLAG_VERB_MASK
Verbosity mask.
Base class for errors generated by the autodoc extraction system.
Tools.AutoDoc.AutoDocError Tools.AutoDoc.AutoDocError(
SourcePosition
position
, string
part
, string
message
)
string
Tools.AutoDoc.AutoDocError.message
Error message.
string
Tools.AutoDoc.AutoDocError.part
Which part of the autodoc system.
SourcePosition
Tools.AutoDoc.AutoDocError.position
inherit Regexp.SimpleRegexp : is_example
protected
inherit Regexp.SimpleRegexp : lastident
protected
inherit Regexp.SimpleRegexp : megamagic
string
magic(string
s
, int
quote
)
Convert a block of tab-indented text to a set of paragraphs.
A very special purpose Pike parser that can parse some selected elements of the Pike language...
constant
string
Tools.AutoDoc.PikeParser.EOF
The end of file marker.
constant
int
Tools.AutoDoc.PikeParser.WITH_NL
Newline indicator flag value.
Tools.AutoDoc.PikeParser Tools.AutoDoc.PikeParser(
string
|void
s
, string
|SourcePosition
|void
_filename
, int
|void
line
, .Flags
|void
flags
)
SourcePosition
Tools.AutoDoc.PikeParser.currentPosition
The current position in the source.
string
eat(multiset
(string
)|string
token
)
Consume one token, error if not (one of) the expected in token
.
string
eatIdentifier(void
|int
allowScopePrefix
)
Expect an identifier.
Also ::ident
, scope::ident
.
This function also converts old-style getters and setters into new-style.
string
eatLiteral()
Expect a literal constant.
parseLiteral()
int
getReadDocComments()
Returns the number of documentation comments
that have been returned by readToken()
.
protected
inherit .PikeObjects : PikeObjects
Type
literalType(string
literal
)
Returns the type of a literal. Currently only recognizes the top level type. Currently does not thoroughly check that the literal is syntactically valid.
string
lookAhead(int
offset
, int
|void
with_newlines
)
Peek offset
tokens ahead, skipping newlines,
unless with_newlines
is set.
peekToken()
array
parseArgList(int
|void
allowLiterals
)
Parse the list of arguments in a function declaration.
allowLiterals
If allowLiterals != 0 then you can write a literal or Pike idents as an argument, like:
void convert("jpeg", Image image, float quality)
For a literal arg, the argname[] string contains the literal and the corresponding argtypes element is 0
Expects that the arglist is followed by a ")".
ArrayType
parseArray()
Parse an array type.
PikeObject
|array
(PikeObject
) parseDecl(mapping
|void
args
)
Parse the next Pike declaration from the token stream.
parseDecl()
reads ONLY THE HEAD, NOT the ";"
or "{" .. "}"
!!!
FunctionType
parseFunction()
Parse a function type.
string
|void
parseIdents()
Parse a '.'-separated identitifer string.
Also parses stuff preceded by "scope::"
or "::"
IntType
parseInt()
Parse an integer type.
void
|string
parseLiteral()
Parse the next literal constant (if any) from the token stream.
MappingType
parseMapping()
Parse a mapping type.
array
(string
) parseModifiers()
Parse a set of modifiers from the token stream.
MultisetType
parseMultiset()
Parse a multiset type.
Type
parseOrType()
Parse a union type.
StringType
parseString()
Parse a string type.
string
peekToken(int
|void
with_newlines
)
Peek at the next token in the stream without advancing.
with_newlines
If set will return "\n"
tokens, these will
otherwise silently be skipped.
Returns the next token.
readToken()
, lookAhead()
string
readToken(int
|void
with_newlines
)
Read the next token from the stream and advance.
with_newlines
If set will return "\n"
tokens, these will
otherwise silently be skipped.
Returns the next token.
peekToken()
void
setTokens(array
(string
) t
, array
(int
) p
)
void
skip(multiset
(string
)|string
tokens
)
Skip the next token if it is a member of the tokens
set.
The newline token ("\n"
) is not skipped implicitly
by this function.
readToken()
, peekToken()
, eat()
, skipUntil()
void
skipBlock()
Skip passed a matched pair of parenthesis, brackets or braces.
void
skipNewlines()
Skip past any newlines.
void
skipUntil(multiset
(string
)|string
tokens
)
Skip tokens until one of tokens
is the next to read.
The newline token ("\n"
) is not skipped implicitly
by this function.
skip()
array
(array
(string
)|array
(int
)) tokenize(string
s
, int
line
)
Tokenize a string of Pike code.
Class used to keep track of where in the source a piece of documentation originated.
SourcePosition
copy()
Returns a copy of the current object.
Tools.AutoDoc.SourcePosition Tools.AutoDoc.SourcePosition(
string
filename
, int
firstline
, int
|void
lastline
)
string
Tools.AutoDoc.SourcePosition.filename
int
Tools.AutoDoc.SourcePosition.firstline
int
Tools.AutoDoc.SourcePosition.lastline
Range of lines.
string
xml(Flags
|void
flags
)
Returns a string with an XML-fragment describing the source position.
constant
Tools.AutoDoc.DocParser.EOF
End of file marker.
inherit .PikeObjects : PikeObjects
mapping
(string
:DocTokenType
) Tools.AutoDoc.DocParser.keywordtype
The DocTokenType
s for the documentation @-keywords.
array
(array
(Token
)) splitDocBlock(string
block
, SourcePosition
position
)
Split a block
of documentation text into segments of Token
s
split on METAKEYWORD
s.
Each of the arrays in the returned array can be fed to
Parse::create()
Enum of documentation token types.
constant
Tools.AutoDoc.DocParser.BRACEKEYWORD
eg @i{@}
constant
Tools.AutoDoc.DocParser.CONTAINERKEYWORD
eg @mapping
constant
Tools.AutoDoc.DocParser.DELIMITERKEYWORD
eg @param
constant
Tools.AutoDoc.DocParser.ENDKEYWORD
eg @endmapping
constant
Tools.AutoDoc.DocParser.ENDTOKEN
End of documentation marker.
constant
Tools.AutoDoc.DocParser.ERRORKEYWORD
eg @invalid
constant
Tools.AutoDoc.DocParser.METAKEYWORD
eg @decl
constant
Tools.AutoDoc.DocParser.SINGLEKEYWORD
None existant.
constant
Tools.AutoDoc.DocParser.TEXTTOKEN
Documentation text.
Internal class for parsing documentation markup.
mapping
(string
:function
(string
, string
:string
)|function
(string
, string
:mapping
(string
:string
))) Tools.AutoDoc.DocParser.DocParserClass.argHandlers
Contains functions that handle keywords with non-standard arg list syntax. The function for each keyword can return a mapping or a string:
| If a |
| If a string is returned, it is an XML fragment that gets inserted inside the tag. |
SourcePosition
Tools.AutoDoc.DocParser.DocParserClass.currentPosition
string
getDoc(string
context
)
Returns the documentation corresponding to the context
as an XML string.
getMetaData()
must be called before this function.
MetaData
getMetaData()
Returns the MetaData
for the documentation string.
Metadata about a Documentation
object.
string
Tools.AutoDoc.DocParser.MetaData.belongs
string
Tools.AutoDoc.DocParser.MetaData.appears
Relocation information.
array
(PikeObject
) Tools.AutoDoc.DocParser.MetaData.decls
Set of declarations.
array
(PikeObject
) Tools.AutoDoc.DocParser.MetaData.inherits
Set of inherits.
string
Tools.AutoDoc.DocParser.MetaData.name
If type
is one of "class"
, "module"
,
"endmodule"
, or "endclass"
.
string
Tools.AutoDoc.DocParser.MetaData.type
Type of documented entity.
Documentation markup parser.
This is a class, because you need to examine the meta lines before you can determine which context to parse the actual doc lines in.
Tools.AutoDoc.DocParser.Parse Tools.AutoDoc.DocParser.Parse(
string
|array
(Token
) s
, SourcePosition
|void
sp
, .Flags
|void
flags
)
Parse a documentation string s
.
string
doc(string
context
)
Returns the documentation corresponding to the context
as an XML string.
metadata()
must be called before this function.
inherit DocParserClass : DocParserClass
MetaData
metadata()
Returns the MetaData
for the documentation string.
Class
extractClass(string
s
, void
|string
filename
, void
|string
className
, void
|.Flags
flags
)
Extract documentation for a Pike class (aka program).
extractNamespace()
, extractModule()
Module
extractModule(string
s
, void
|string
filename
, void
|string
moduleName
, void
|.Flags
flags
)
Extract documentation for a Pike module.
extractNamespace()
, extractClass()
NameSpace
extractNamespace(string
s
, void
|string
filename
, void
|string
namespaceName
, void
|.Flags
flags
)
Extract documentation for a Pike namespace.
extractModule()
, extractClass()
protected
inherit .DocParser : DocParser
This module contains classes to represent Pike objects such as classes, modules, methods, variables ... The classes can produce XML representations of themselves.
protected
Documentation
Tools.AutoDoc.PikeObjects.EmptyDoc
The empty Documentation
.
protected
inherit "module.pmod" : "module.pmod"
protected
inherit Parser.XML.Tree : Tree
The class for representing array types.
Type
Tools.AutoDoc.PikeObjects.ArrayType Tools.AutoDoc.PikeObjects.ArrayType()
inherit Type : Type
Type
Tools.AutoDoc.PikeObjects.ArrayType.valuetype
The Type
of the array elements.
The class for representing attributed types.
Type
string
Tools.AutoDoc.PikeObjects.AttributeType.attribute
The name of the attribute.
Tools.AutoDoc.PikeObjects.AttributeType Tools.AutoDoc.PikeObjects.AttributeType()
inherit Type : Type
int
Tools.AutoDoc.PikeObjects.AttributeType.prefix
Flag indicating:
| The attribute is on the type. |
| The attribute is a prefix and acts as a modifier. This is only used for functions. |
Type
Tools.AutoDoc.PikeObjects.AttributeType.subtype
The type that is attributed.
The top-level container. This container should only contain namespaces, and they in turn contain modules etc.
inherit _Class_or_Module : _Class_or_Module
constant
string
Tools.AutoDoc.PikeObjects.AutoDoc.objtype
Represents a class.
inherit _Class_or_Module : _Class_or_Module
constant
string
Tools.AutoDoc.PikeObjects.Class.objtype
Represents a named constant.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.Constant.objtype
Type
Tools.AutoDoc.PikeObjects.Constant.type
The type of the constant, if known.
Type
Tools.AutoDoc.PikeObjects.Constant.typedefType
Typedef Type
if it is a typedef.
Representation of an inherit.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.CppDirective.objtype
A class associating a piece of Documentation
with a set of PikeObject
s.
string
Tools.AutoDoc.PikeObjects.DocGroup.appears
string
Tools.AutoDoc.PikeObjects.DocGroup.belongs
Relocation information.
Tools.AutoDoc.PikeObjects.DocGroup Tools.AutoDoc.PikeObjects.DocGroup(
array
(PikeObject
) objs
, Documentation
doc
)
Documentation
Tools.AutoDoc.PikeObjects.DocGroup.documentation
The Documentation
for the objects
.
array
(PikeObject
) Tools.AutoDoc.PikeObjects.DocGroup.objects
The set of PikeObject
s that are documented.
string
xml(.Flags
|void
flags
)
Returns a string with an XML representation of the documentation.
The base class for documentation strings.
DocGroup
Tools.AutoDoc.PikeObjects.Documentation Tools.AutoDoc.PikeObjects.Documentation(
string
|void
text
, string
|void
xml
, SourcePosition
|void
position
)
string
|void
Tools.AutoDoc.PikeObjects.Documentation.text
string
|void
Tools.AutoDoc.PikeObjects.Documentation.xml
SourcePosition
|void
Tools.AutoDoc.PikeObjects.Documentation.position
The enum container.
void
addChild(DocGroup
c
)
Adds c
to the set of children
.
array
(DocGroup
) Tools.AutoDoc.PikeObjects.Enum.children
The set of children.
Documentation
Tools.AutoDoc.PikeObjects.Enum.documentation
Mimic the class { ... }
behaviour.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.Enum.objtype
The values inside enum Foo { ... }
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.EnumConstant.objtype
The class for representing the float type.
Type
Tools.AutoDoc.PikeObjects.FloatType Tools.AutoDoc.PikeObjects.FloatType()
inherit Type : Type
The class for representing function types.
Type
array
(Type
) Tools.AutoDoc.PikeObjects.FunctionType.argtypes
An array with types for the arguments to the function.
Tools.AutoDoc.PikeObjects.FunctionType Tools.AutoDoc.PikeObjects.FunctionType()
inherit Type : Type
Type
Tools.AutoDoc.PikeObjects.FunctionType.returntype
The type for the return value of the function.
Representation of an import.
inherit Inherit : Inherit
constant
string
Tools.AutoDoc.PikeObjects.Import.objtype
Representation of an inherit.
string
Tools.AutoDoc.PikeObjects.Inherit.classname
Name of the class that is inherited.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.Inherit.objtype
The class for representing integer types.
Type
Tools.AutoDoc.PikeObjects.IntType Tools.AutoDoc.PikeObjects.IntType()
inherit Type : Type
string
Tools.AutoDoc.PikeObjects.IntType.min
string
Tools.AutoDoc.PikeObjects.IntType.max
The minimum and maximum range limits for the integer type.
The class for representing mapping types.
Type
Tools.AutoDoc.PikeObjects.MappingType Tools.AutoDoc.PikeObjects.MappingType()
Type
Tools.AutoDoc.PikeObjects.MappingType.indextype
Type
Tools.AutoDoc.PikeObjects.MappingType.valuetype
The types for the indices and values of the mapping.
inherit Type : Type
Represents a function.
array
(string
) Tools.AutoDoc.PikeObjects.Method.argnames
The names of the arguments.
array
(Type
) Tools.AutoDoc.PikeObjects.Method.argtypes
The types for the arguments.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.Method.objtype
Type
Tools.AutoDoc.PikeObjects.Method.returntype
The return type for the function.
The class for representing the mixed type.
Type
Tools.AutoDoc.PikeObjects.MixedType Tools.AutoDoc.PikeObjects.MixedType()
inherit Type : Type
A modifier range, e.g.:
final protected {
...
<<declarations>>
...
}
inherit _Class_or_Module : _Class_or_Module
constant
string
Tools.AutoDoc.PikeObjects.Modifier.objtype
Represents a module.
inherit _Class_or_Module : _Class_or_Module
constant
string
Tools.AutoDoc.PikeObjects.Module.objtype
The class for representing multiset types.
Type
Tools.AutoDoc.PikeObjects.MultisetType Tools.AutoDoc.PikeObjects.MultisetType()
Type
Tools.AutoDoc.PikeObjects.MultisetType.indextype
The type for the indices of the multiset.
inherit Type : Type
Represents a name space, eg: predef::
or lfun::
.
inherit _Class_or_Module : _Class_or_Module
constant
string
Tools.AutoDoc.PikeObjects.NameSpace.objtype
The class for representing object types.
Type
string
Tools.AutoDoc.PikeObjects.ObjectType.classname
The name of the class for the object.
Tools.AutoDoc.PikeObjects.ObjectType Tools.AutoDoc.PikeObjects.ObjectType()
inherit Type : Type
The class for representing union types.
Type
Tools.AutoDoc.PikeObjects.OrType Tools.AutoDoc.PikeObjects.OrType()
inherit Type : Type
array
(Type
) Tools.AutoDoc.PikeObjects.OrType.types
An array with the types that are member of the union.
Base class for representing a documentable Pike lexical entity.
This class is inherited by classes for representing classes, functions, variables, etc.
Inherit
, Import
, Class
, Module
, NameSpace
, AutoDoc
,
Modifier
, Method
, Constant
, Typedef
, EnumConstant
,
Enum
, Variable
string
Tools.AutoDoc.PikeObjects.PikeObject.appears
string
Tools.AutoDoc.PikeObjects.PikeObject.belongs
Relocation information.
array
(string
) Tools.AutoDoc.PikeObjects.PikeObject.modifiers
The set of modifiers affecting this entity.
string
Tools.AutoDoc.PikeObjects.PikeObject.name
The name of the entity.
constant
string
Tools.AutoDoc.PikeObjects.PikeObject.objtype
The object type identifier.
SourcePosition
Tools.AutoDoc.PikeObjects.PikeObject.position
The source position where the entity was found.
string
print()
Returns a string with a Pike syntax representation of the entity.
Documentation
Tools.AutoDoc.PikeObjects.PikeObject.squeezedInDoc
string
xml(.Flags
|void
flags
)
Returns a string with an XML representation of the entity.
The class for representing program (aka class) types.
Type
string
Tools.AutoDoc.PikeObjects.ProgramType.classname
The name of the class (if any).
Tools.AutoDoc.PikeObjects.ProgramType Tools.AutoDoc.PikeObjects.ProgramType()
inherit Type : Type
The class for representing string types.
Type
Tools.AutoDoc.PikeObjects.StringType Tools.AutoDoc.PikeObjects.StringType()
inherit Type : Type
string
Tools.AutoDoc.PikeObjects.StringType.max
The maximum value for characters in the string.
string
Tools.AutoDoc.PikeObjects.StringType.min
The minimum value for characters in the string.
The base class for representing types.
Tools.AutoDoc.PikeObjects.Type Tools.AutoDoc.PikeObjects.Type(
string
name
)
string
Tools.AutoDoc.PikeObjects.Type.name
string
print()
Returns a string with a Pike-syntax representation of the type.
string
xml(.Flags
|void
flags
)
Returns a string with an XML representation of the type.
The class for representing type types.
Type
Tools.AutoDoc.PikeObjects.TypeType Tools.AutoDoc.PikeObjects.TypeType()
inherit Type : Type
Type
Tools.AutoDoc.PikeObjects.TypeType.subtype
The subtype of the type.
Represents a typedef.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.Typedef.objtype
Type
Tools.AutoDoc.PikeObjects.Typedef.type
Typedef Type
.
The class for representing varargs types.
Type
Tools.AutoDoc.PikeObjects.VarargsType Tools.AutoDoc.PikeObjects.VarargsType(
Type
t
)
inherit Type : Type
Type
Tools.AutoDoc.PikeObjects.VarargsType.type
The type that is varargs.
Represents a variable.
inherit PikeObject : PikeObject
constant
string
Tools.AutoDoc.PikeObjects.Variable.objtype
Type
Tools.AutoDoc.PikeObjects.Variable.type
Type
of the variable.
The class for representing the void type.
Type
Tools.AutoDoc.PikeObjects.VoidType Tools.AutoDoc.PikeObjects.VoidType()
inherit Type : Type
The class for representing the zero type.
Type
Tools.AutoDoc.PikeObjects.ZeroType Tools.AutoDoc.PikeObjects.ZeroType()
inherit Type : Type
Base class for representing classes, modules and namespaces.
Class
, Module
, NameSpace
, AutoDoc
, Modifier
void
AddChild(_Class_or_Module
c
)
Adds c
to the set of children
.
void
AddGroup(DocGroup
d
)
Adds d
to the set of docGroups
.
void
AddInherit(PikeObject
p
)
Adds p
to the set of inherits
.
array
(_Class_or_Module
) Tools.AutoDoc.PikeObjects._Class_or_Module.children
Entities that are children to this entity.
int
containsDoc()
Returns 1
if there is any documentation
at all for this entity.
array
(DocGroup
) Tools.AutoDoc.PikeObjects._Class_or_Module.docGroups
Documented entities that are children to this entity.
Documentation
Tools.AutoDoc.PikeObjects._Class_or_Module.documentation
The documentation appears as a child of the <class> or <module>
PikeObject
findChild(string
name
)
Returns the first child with the name name
if any.
DocGroup
findObject(string
name
)
Returns the first DocGroup
that documents an entity
with the name name
if any.
inherit PikeObject : PikeObject
array
(Inherit
|Import
) Tools.AutoDoc.PikeObjects._Class_or_Module.inherits
Inherit
s and Import
s that affect the symbol lookup
for the entity.
string
extractXML(string
filename
, int
|void
pikeMode
, string
|void
type
, string
|void
name
, array
(string
)|void
parentModules
, void
|.Flags
flags
)
This function extracts documentation from a file. The parameters
type
, name
, and parentModules
are used only when
pikeMode
!= 0 and no C-style doc comments are present.
filename
The file to extract from.
pikeMode
Non-zero if it is a Pike file. If the file contains style doc comments, C-mode is used despite pikeMode != 0.
type
"class"
, "module"
or "namespace"
.
name
The name of the class/module/namespace.
parentModules
The ancestors of the class/module/namespace.
flags
Flags adjusting the extractor behaviour.
Defaults to FLAG_NORMAL
.
// To extract doc for Foo.Bar.Ippa: string xml = extractXML("lib/modules/Foo.pmod/Bar.pmod/Ippa.pike", 1, "class", "Ippa", ({ "Foo", "Bar" }));
void
handleAppears(SimpleNode
root
, .Flags
|void
flags
)
Take care of all the @appears and @belongs directives everywhere, and rearranges the nodes in the tree accordingly
root
The root (<autodoc>) node of the documentation tree.
protected
inherit "module.pmod" : "module.pmod"
protected
inherit Parser.XML.Tree : Tree
void
mergeTrees(SimpleNode
dest
, SimpleNode
source
)
Puts all children of source
into the tree dest
, in their
correct place module-hierarchically.
Used to merge the results of extractions of different Pike and C files.
Some minor effort is expended to normalize the result to some sort of canonical order.
source
dest
The nodes source
and dest
are <class>, <module>,
<namespace> or <autodoc> nodes that are identical in
the sense that they represent the same module, class or namespace.
Typically they both represent <autodoc> nodes.
Both source
and dest
are modified destructively.
After calling this method, any <class> or <module> nodes
that have been marked with @appears or @belongs, are still in the
wrong place in the tree, so handleAppears()
(or postProcess()
)
must be called on the whole documentation tree to relocate them once
the tree has been fully merged.
string
moveImages(string
docXMLFile
, string
imageSourceDir
, string
imageDestDir
, int
|void
quiet
)
Copy all images to canonical files in a flat directory.
docXMLFile
The contents of the XML file. The XML file is the result of extraction
from a single C or Pike file, for example the result of calling
extractXML
.
imageSourceDir
The directory that is the base of the relative paths to images. This should be the directory of the source file that was the input to extract the XML file.
imageDestDir
The directory where the images should be copied.
quiet
Quiet operation.
The XML file contents (with decorated <image>-tags)
void
postProcess(SimpleNode
root
, string
|void
logfile
, .Flags
|void
flags
)
Perform the last steps on a completed documentation tree.
root
Root <autodoc> node of the completed documentation tree.
Calls handleAppears()
, cleanUndocumented()
and resolveRefs()
in turn.
handleAppears()
, cleanUndocumented()
, resolveRefs()
A symbol lookup scope.
void
addImplicitInherits(string
|void
fallback_namespace
)
This function improves the symbol resolution by adding implicit inherits for modules in compatibility namespaces.
string
format_hr_time(int
i
)
Helper function that formats a time span in nanoseconds to something more human readable (ns, ms or s).
Abstract class for Hilfe commands.
string
doc(string
what
, string
with
)
A more elaborate documentation of the command. This should be less than 68 characters per line.
void
exec(Evaluator
e
, string
line
, array
(string
) words
, array
(string
) tokens
)
The actual command callback. Messages to the user should be
written out by using the safe_write method in the Evaluator
object.
string
help(string
what
)
Returns a one line description of the command. This help should be shorter than 54 characters.
Variable reset command. Put ___Hilfe->commands->reset = Tools.Hilfe.CommandReset(); in your .hilferc to have this command defined when you open Hilfe.
inherit Command : Command
This class implements the actual Hilfe interpreter. It is accessible as ___Hilfe from Hilfe expressions.
void
add_buffer(string
s
)
Add buffer tokenizes the input string and determines if the
new line is a Hilfe command. If not, it updates the current
state with the new tokens and sends any and all complete
expressions to evaluation in parse_expression
.
void
add_input_hook(function
(:void
)|object
new
)
Adds a function to the input hook, making all user data be fed into the function.
remove_input_hook
void
add_input_line(string
s
)
Input a line of text into Hilfe. It checks if s
is
".", in which case it calls state->flush(). Otherwise
just calls add_buffer.
void
add_writer(object
|function
(string
:int(0..)
) new
)
Adds another output function.
int
Tools.Hilfe.Evaluator.assembler_debug_level
The current assembler debug level. Only available if Pike is compiled with RTL debug.
mapping
(string
:Command
) Tools.Hilfe.Evaluator.commands
This mapping contains the available Hilfe commands, including the built in ones (dump, exit, help, new, quit), so it is possible to replace or remove them. The name of a command should be 10 characters or less.
int
Tools.Hilfe.Evaluator.compiler_trace_level
The current compiler trace level. Only available if Pike is compiled with RTL debug.
mapping
(string
:mixed
) Tools.Hilfe.Evaluator.constants
The locally defined constants (name:value).
int
Tools.Hilfe.Evaluator.debug_level
The current debug level. Only available if Pike is compiled with RTL debug.
void
evaluate(string
a
, bool
show_result
)
Compiles the Pike code a
and evaluates it by
calling ___HilfeWrapper in the generated object.
If show_result
is set the result will be displayed
and the result buffer updated with its value.
mapping
(string
:function
(:void
)) Tools.Hilfe.Evaluator.functions
The locally defined functions (name:value).
object
hilfe_compile(string
f
, void
|string
new_var
)
Creates a wrapper and compiles the pike code f
in it.
If a new variable is compiled to be tested, its name
should be given in new_var
so that magically defined
entities can be undefined and a warning printed.
HilfeHistory
Tools.Hilfe.Evaluator.history
The current result history.
array
(string
) Tools.Hilfe.Evaluator.imports
The current imports.
array
(string
) Tools.Hilfe.Evaluator.inherits
The current inherits.
int(0..)
Tools.Hilfe.Evaluator.last_compile_time
The last compile time;
string
Tools.Hilfe.Evaluator.last_compiled_expr
The last created wrapper in which an expression was evaluated.
bool
Tools.Hilfe.Evaluator.last_else
Should an else expression be carried out?
int(0..)
Tools.Hilfe.Evaluator.last_eval_time
The last evaluation time;
string
parse_expression(Expression
expr
)
Parses a Pike expression. Returns 0 if everything went well, or a string with an error message otherwise.
void
print_version()
Displays the current version of Hilfe.
mapping
(string
:program
) Tools.Hilfe.Evaluator.programs
The locally defined programs (name:value).
void
remove_input_hook(function
(:void
)|object
old
)
Removes a function from the input hook.
add_input_hook
void
remove_writer(object
|function
(:void
) old
)
Removes an output function.
void
reset_evaluator()
Clears the current state, history and removes all locally defined variables, constants, functions and programs. Removes all imports and inherits. It does not reset the command mapping nor reevaluate the .hilferc file.
function
(:void
) Tools.Hilfe.Evaluator.reswrite
The function used to write results. Gets as arguments in order: The safe_write function (function(string, mixed ...:int), the result as a string (string), the history entry number (int), the result (mixed), the compilation time (int) and the evaluation time (int). If the evaluated expression didn't return anything (e.g. a for loop) then 0 will be given as the result string.
int
safe_write(array
(string
)|string
in
, mixed
... args
)
An output method that shouldn't crash.
ParserState
Tools.Hilfe.Evaluator.state
Keeps the state, e.g. multiline input in process etc.
void
std_reswrite(function
(:void
) w
, string
sres
, int
num
, mixed
res
)
The standard reswrite
function.
bool
Tools.Hilfe.Evaluator.strict_types
Strict types?
int
Tools.Hilfe.Evaluator.trace_level
The current trace level.
mapping
(string
:string
) Tools.Hilfe.Evaluator.types
The types of the locally defined variables (name:type).
mapping
(string
:mixed
) Tools.Hilfe.Evaluator.variables
The locally defined variables (name:value).
bool
Tools.Hilfe.Evaluator.warnings
Show warnings?
array
|object
|function
(string
:int(0..)
) Tools.Hilfe.Evaluator.write
The function to use when writing to the user.
Represents a Pike expression
int
sizeof( Tools.Hilfe.Expression arg )
The number of non-whitespace tokens in the expression.
string
res = Tools.Hilfe.Expression()
[ f
]
Returns a token or a token range without whitespaces.
Tools.Hilfe.Expression()
[ f
] = v
Replaces a token with a new token.
(int)Tools.Hilfe.Expression()
(float)Tools.Hilfe.Expression()
(string)Tools.Hilfe.Expression()
(array)Tools.Hilfe.Expression()
(mapping)Tools.Hilfe.Expression()
(multiset)Tools.Hilfe.Expression()
An Expression object can be cast to an array or a string. In both forms all tokens, including white spaces will be returned.
string
check_modifiers()
See if there are any forbidden modifiers used in the expression, e.g. "private int x;" is not valid inside Hilfe.
Returns an error message as a string if the expression
contains a forbidden modifier, otherwise 0
.
string
code()
Returns the expression verbatim.
Tools.Hilfe.Expression Tools.Hilfe.Expression(
array
(string
) t
)
t
An array of Pike tokens.
int
depth(int
f
)
Return the parenthesis depth at the given position.
int(-1..)
endoftype(int(-1..)
position
)
Returns at which position the type declaration that begins at
position position
ends. A return value of -1 means that the
token or tokens from position
can not be a type declaration.
int(-1..)
find_matching(string
token
, int(0..)
|void
pos
)
Returns the position of the matching parenthesis of the given kind, starting from the given position. The position should be the position after the opening parenthesis, or later. Assuming balanced code. Returns -1 on failure.
bool
in_sscanf(int
f
)
Returns 1 if the current position is within a sscanf expression.
bool
is_block(int
pos
)
Is there a block starting at pos
?
Tools.Hilfe.GenericAsyncHilfe Tools.Hilfe.GenericAsyncHilfe(
Stdio.File
infile
, Stdio.File
outfile
)
Stdio.File
Tools.Hilfe.GenericAsyncHilfe.infile
Stdio.File
Tools.Hilfe.GenericAsyncHilfe.outfile
inherit Evaluator : Evaluator
Tools.Hilfe.GenericHilfe Tools.Hilfe.GenericHilfe(
Stdio.FILE
in
, Stdio.File
out
)
inherit Evaluator : Evaluator
In every Hilfe object (Evaluator
) there is a HilfeHistory
object that manages the result history. That history object is
accessible both from __ and ___Hilfe->history in Hilfe expressions.
inherit ADT.History : History
In every Hilfe object (Evaluator
) there is a ParserState object
that manages the current state of the parser. Essentially tokens are
entered in one end and complete expressions are output in the other.
The parser object is accessible as ___Hilfe->state from Hilfe expressions.
int
datap()
Returns true if there is any waiting expression that can be fetched
with read
.
void
feed(array
(string
) tokens
)
Feed more tokens into the state.
bool
finishedp()
Are we in the middle of an expression. Used e.g. for changing the Hilfe prompt when entering multiline expressions.
void
flush()
Clear the current state.
array
(string
) push_string(string
line
)
Sends the input line
to Parser.Pike
for tokenization,
but keeps a state between each call to handle multiline
/**/ comments and multiline #"" strings.
array
(Expression
) read()
Read out completed expressions. Returns an array where every element is an expression represented as an array of tokens.
void
show_error(function
(array
(string
)|string
, mixed
... :int
) w
)
Prints out any error that might have occurred while
push_string
was executed. The error will be
printed with the print function w
.
string
status()
Returns the current parser state. Used by "dump state".
This is a wrapper containing a user interface to the Hilfe Evaluator
so that it can actually be used. This wrapper uses the Stdio.Readline
module to interface with the user. All input history is handled by
that module, and as a consequence loading and saving .hilfe_history is
handled in this class. Also .hilferc is handled by this class.
Tools.Hilfe.StdinHilfe Tools.Hilfe.StdinHilfe(
void
|array
(string
) init
)
Any hilfe statements given in the init array will be executed once .hilferc has been executed.
inherit Evaluator : Evaluator
Stdio.Readline
Tools.Hilfe.StdinHilfe.readline
The readline object,
void
save_history()
Saves the user input history, if possible, when called.
Common routines which are useful for various install scripts based on Pike.
array
(string
) features()
Return an array of enabled features.
Used by the master
when given the option --features.
Tools.Standalone.features
string
make_absolute_path(string
path
, string
|void
cwd
)
A class keeping some methods and state to conveniently render ASCII progress bars to stdout.
Tools.Install.ProgressBar Tools.Install.ProgressBar(
string
name
, int
cur
, int
max
, float
|void
phase_base
, float
|void
phase_size
)
name
The name (printed in the first 13 columns of the row)
cur
How much progress has been made so far
max
The amount of progress signifying 100% done. Must be greater than zero.
void
set_current(int
_cur
)
Change the amount of progress without updating on stdout.
void
set_name(string
_name
)
Change the name of the progress bar without updating on stdout.
void
set_phase(float
_phase_base
, float
_phase_size
)
int
update(int
increment
)
Write the current look of the progressbar to stdout.
increment
the number of increments closer to completion since last call
the length (in characters) of the line with the progressbar
string
absolute_path(string
path
)
string
edit(mixed
... args
)
string
edit_directory(mixed
... args
)
string
edit_filename(mixed
... args
)
inherit Stdio.Readline : Readline
void
set_cwd(string
_cwd
)
void
trap_signal(int
n
)
Contains functions and information to store and present copyright information about Pike and it's components.
void
add(string
what
, array
(string
) holders
)
Adds a copyright message for the copyright holders
for the
component what
.
An error is thrown if the copyrighted component what
is
already in the list of copyrights.
mapping
(string
:array
(string
)) get_all()
Returns a mapping containing all the stored copyrights. The mapping maps component name to an array of copyright holders.
string
get_latest_pike()
Return the latest copyright holder of Pike.
string
get_text()
Returns the copyrights as a string, suitable for saving as a file.
string
get_text()
Returns all the licenses as a string, suitable for saving as a file.
This module contains usage strings for the master()->_main()
.
string
do_help(string
|int
what
)
Select a suitable help message.
constant
Tools.MasterHelp.environment_help
The set of environment variables that the default master looks at.
constant
Tools.MasterHelp.kladdkaka_help
Useful recipe for when all else fails.
constant
Tools.MasterHelp.opt_summary
Summary of the options for the Pike interpreter binary, and the default master.
constant
Tools.MasterHelp.options_help
Complete set of options for the Pike interpreter binary, and the default master.
int
add_new_version(string
module_name
, string
version
, string
changes
, string
license
)
int
delete_dependency(string
module_name
, string
version
, string
dependency
, string
min_version
, string
max_version
)
array
get_dependencies(string
module_name
, string
version
)
void
set_auth(string
_username
, string
_password
)
set the username and password for accessing the remote repository.
void
set_default_directory()
sets the default directory for working and storing configurations ($HOME/.monger)
void
set_default_repository()
sets the default repository location (modules.gotpike.org)
int
set_dependency(string
module_name
, string
version
, string
dependency
, string
min_version
, string
max_version
, bool
required
)
void
set_directory(string
_directory
)
sets the monger directory to use for working and storing configurations.
int
set_module_source(string
module_name
, string
version
, string
filename
)
void
set_repository(string
_repository
)
specify an alternate repository location.
this should be a URL specifying the XMLRPC endpoint for the repository.
int
set_version_active(string
module_name
, string
version
, int
active
)
int
update_version(string
module_name
, string
version
, string
|void
changes
, string
|void
license
)
int
user_change_email(string
|void
_username
, string
_newemail
)
int
user_change_password(string
|void
_username
, string
_newpassword
)
Support for parsing PEM-style messages.
Replaced by Standards.PEM
.
Represents an encapsulated message.
string
Tools.PEM.EncapsulatedMsg.body
Contains the raw message body. Access through decoded_body
to
get the decoded message.
string
Tools.PEM.EncapsulatedMsg.boundary
Contains the raw boundary string. Access through get_boundary
to get the decoded boundary string.
string
canonical_body()
Returns the raw body with all newlines as "\r\n"
.
string
decoded_body()
Returns decoded base64 encoded message body
string
get_boundary()
Returns decoded boundary string.
mapping
(string
:string
) Tools.PEM.EncapsulatedMsg.headers
Contains the message headers, or 0
.
string
to_string()
Returns the message body and headers in the standard message format.
Disassembles PGP and PEM style messages with parts separated by "-----BEGIN FOO-----" and "-----END FOO-----".
Tools.PEM.Msg Tools.PEM.Msg(
string
s
)
Creates a decoded PEM message
s
A string containing a PEM encoded message to be decoded.
string
Tools.PEM.Msg.final_text
Contains any text following the PEM message.
string
Tools.PEM.Msg.initial_text
Contains any text preceeding the PEM message.
mapping
(string
:EncapsulatedMsg
) Tools.PEM.Msg.parts
The decoded PEM message, as an array of EncapsulatedMsg
objects indexed by message name, such as "CERTIFICATE".
Represents an RFC934 text message.
Tools.PEM.RFC934 Tools.PEM.RFC934(
string
data
)
Decodes an RFC 934 encoded message.
array
(EncapsulatedMsg
) Tools.PEM.RFC934.encapsulated
string
Tools.PEM.RFC934.final_boundary
string
Tools.PEM.RFC934.final_text
string
get_final_boundary()
string
Tools.PEM.RFC934.initial_text
string
to_string()
constant
string
Tools.Shoot.Test.name
The name of the test.
int
perform(mixed
|void
context
)
perform() is the function called in the tests, when it returns the test is complete.
The function returns the number of whatever the test did.
optional
mixed
prepare()
If this function exists, it computes the context to pass to the perform() function. The time consumed by this function will not count towards the test.
AutoDoc XML to HTML converter.
tree_split
string
image_prefix()
Path to where in the destination filesystem the images are.
mapping
Tools.Standalone.autodoc_to_html.lay
Layout template headers and trailers.
string
parse_text(Node
n
, void
|String.Buffer
ret
)
Typically called with a <group/> node or a sub-node that is a container.
Fork Daemon
This is a light-weight daemon that can be used via Process.Process
to spawn new processes (by specifying the "forkd"
modifier).
The typical use is when the main program is large and/or when it has lots of open file descriptors. This can cause considerable overhead in process creation.
Process.RemoteProcess
, Process.create_process
This is the main control Stdio.Fd
and is
always on fd number 3
.
To spawn a new process, a new Stdio.PROP_SEND_FD
capable Stdio.Fd
is sent over this fd, and a
single byte of data is sent as payload.
The sent fd will become a ForkFd
inside a ForkStream
.
inherit Stdio.File : File
This class maps 1 to 1 to Process.RemoteProcess, and implements the daemon side of the RPC protocol.
It contains an array (fds
) with the file descriptors
that have been received so far from the remote.
array
(Stdio.Fd
) Tools.Standalone.forkd.ForkStream.fds
The remote file descriptors received so far in order.
inherit Stdio.File : File
Tool for converting the Pike git repository to a corresponding git repository containing the extracted autodoc.xml and documentation.
It supports incremental operation, so that it can be used to keep track with the source.
Typical use: pike -x git_export_autodoc -v --git-dir=Autodoc.git
mapping
(string
:string
) Tools.Standalone.git_export_autodoc.autodoc_hash
Mapping from doc commit sha1 or export reference to sha1 for the autodoc.xml blob.
mapping
(string
:string
) Tools.Standalone.git_export_autodoc.doc_refs
Mapping from doc reference to doc commit sha1 or export reference.
mapping
(string
:array
(string
)) Tools.Standalone.git_export_autodoc.doc_to_parents
Mapping from doc commit sha1 or export reference to array of same for its direct parents.
mapping
(string
:array
(string
)) Tools.Standalone.git_export_autodoc.doc_to_src
Mapping from doc commit sha1 or export reference to the corresponding list of source commit sha1s.
string
get_version()
Attempt to get the version for the Pike source tree.
mapping
(string
:string
) Tools.Standalone.git_export_autodoc.refdoc_hash
Mapping from source commit to refdoc sha1.
mapping
(string
:multiset
(string
)) Tools.Standalone.git_export_autodoc.rev_refs
Lookup from source commit sha1 to the corresponding references (if any).
mapping
(string
:string
) Tools.Standalone.git_export_autodoc.src_refs
Mapping from source reference to source commit sha1.
mapping
(string
:string
) Tools.Standalone.git_export_autodoc.src_to_doc
Mapping from source commit sha1 to doc commit sha1 or export reference.
Convert Pike code to HTML with syntax highlighting
pike -x pike_to_html /path/to/file.pike > file.html
string
convert(string
code
)
Turn code
into HTML.
The following css classes will be used:
Delimiters: delim
Reserved words: lang
Data types: type
Constants: const
Modifiers: mods
Root namespaces: ns
Strings: string
Comments: comment
Macros: macro
code
a prototype installer for prepackaged modules
note: portions of this code are highly inefficient (wrt tar filehandling). we assume that this will be used infrequently enough that this is not going to be a problem.
a package file is a tar file that contains the following structure:
ROOTDIR/ METADATA.TXT a file containing metadata about the package format: KEY=value, where values include: PLATFORM, in the form of os/processor (either can be "any") MODULE, the name of the module, in Module.Submodule format. VERSION, the version of this module. MODULE/ any files that need to be installed in the module directory MODREF/ ??? documentation suitable for inclusion in the modref INCLUDE/ ??? any pike language include files to be installed SCRIPTS/ standalone (no bundled dependencies) scripts used to perform custom actions they receive the installer object (this) and the System.Filesystem object of the package archive as arguments to the constructor. The method "run()" should perform the actual action. The run() method should return true or false to indicate success or failure. preinstall.pike postinstall.pike
Boilerplate to quickly whip up rsif-like hacks for creating file processing to churn away at stdin, or files and/or directories provided on the command line, recursively or not, creating backup files or not, listing the paths of all files action was taken for, and returning an exit status of how many files that would have been taken action on which could not be written back.
The all-round quickest way of making one of these tools is nicking
the top portion of
lib/modules/Tools.pmod/Standalone.pmod/process_files.pike or
copying rsif.pike from the same directory. (The latter is 20
lines long, including docs, or about four lines of code.) Inherit
process_files, and define your own version
, description
,
usage
, process
, and, if you want arguments, want_args
.
string
Tools.Standalone.process_files.default_flag_docs
Flag docs to append to your usage
description. Explains default options.
string
Tools.Standalone.process_files.description
One-liner that gets shown for this tool when running pike -x without additional options. (Assuming your tool resides in Standalone.pmod.) Does not include the name of the tool itself; just provide a nice, terse description, ending with a period for conformity.
inherit Toole.Standalone.process_files : process_files
int(0..)
main(int
argc
, array
(string
) argv
)
Base implementation of main program, handling basic flags and returning an exit status matching the number of failures during operation.
No easy way of adding your own command-line flags implemented yet. This would be a rather natural next feature to add, once somebody needs some.
bool
Tools.Standalone.process_files.overwrite
0 to make backups, 1 to overwrite (default)
string
process(string
input
, string
... args
)
Gets called with the contents of a file (or stdin). Return your output, or
0 if you didn't do anything. args
are the first want_args
command-line options provided, before the list of files to process.
bool
process_file(string
path
, string
... args
)
Takes the path to a file and the first want_args
command-line options
provided, before the list of files to process. You might want to override
this method if your tool needs to see file paths.
process_path
int(0..)
process_path(string
path
, string
... args
)
Takes the path to a file or directory and the first want_args
first
command-line options provided, before the list of files to process. You
might want to override this method if your tool needs to see all paths.
process_file
bool
Tools.Standalone.process_files.recursive
1 to recurse into directories, 0 not to (default)
string
Tools.Standalone.process_files.usage
Long description of the purpose and usage of your tool, for --help and the case where not enough options are given on the command line. Its invocation mode (for instance "pike -x yourtool", when invoked that way) is prepended, and a list of available flags appended to this description.
int(0..)
Tools.Standalone.process_files.verbosity
0 in quiet mode, 1 by default, above = more output
string
Tools.Standalone.process_files.version
Your hack's version number. If you version control your file with cvs, we suggest you set the contents of this variable to something that that will automatically expand to a number for every new revision, for instance
string version = sprintf("%d.%d.%d",(int)__REAL_VERSION__,__REAL_MINOR__,__REAL_BUILD__);
int
Tools.Standalone.process_files.want_args
The number of (mandatory) command-line options your hack needs and which
your process
callback wants (beside the input file). By default 0.
void
log_msg(string
msg
, mixed
... args
)
Logs a testsuite message to stderr. The message is shown regardless of the verbosity level. If the previous message was logged without a trailing newline then a newline is inserted first.
The message should normally have a trailing newline - no extra
newline is added to it. Use log_status
to log a message
intended to be overwritten.
void
log_msg_cont(string
msg
, mixed
... args
)
Similar to log_msg
, but doesn't insert a newline first if the
previous message didn't end with one. Does however insert a
newline if the previous message was logged "in place" by
log_status
.
void
log_status(string
msg
, mixed
... args
)
Logs a testsuite status message to stdout. This is suitable for nonimportant progress messages.
If the verbosity is 0 then nothing is logged, but the message is
saved and will be logged if the next call is to log_msg
.
If the verbosity is 1, the message is "in place" on the current
line without a trailing line feed, so that the next
log_status
message will replace this one.
If the verbosity is 2 or greater, the message is logged with a trailing line feed.
The message should be short and not contain newlines, to work when the verbosity is 1, but if it ends with a newline then it's logged normally. It can be an empty string to just clear the last "in place" logged message - it won't be logged otherwise.
log_twiddler
void
log_twiddler()
Logs a rotating bar for showing progress. Only output at the end
of an "in place" message written by log_status
on verbosity
level 1.
void
report_result(int
succeeded
, int
failed
, void
|int
skipped
)
Use this to report the number of successful, failed, and skipped
tests in a script started using run_script
. Can be called
multiple times - the counts are accumulated.
array
(int
) run_script(string
|array
(string
) pike_script
)
Runs an external pike script from a testsuite. Use
Tools.Testsuite.report_result
in the script to report how many
tests succeeded, failed, and were skipped. Those numbers are
returned in the array from this function.
Functions to generate and validate RFC2459 style X.509 v3 certificates.
Replaced by Standards.X509
.
constant
int
Tools.X509.CERT_BAD_SIGNATURE
constant
int
Tools.X509.CERT_CHAIN_BROKEN
constant
int
Tools.X509.CERT_INVALID
constant
int
Tools.X509.CERT_ROOT_UNTRUSTED
constant
int
Tools.X509.CERT_TOO_NEW
constant
int
Tools.X509.CERT_TOO_OLD
constant
int
Tools.X509.CERT_UNAUTHORIZED_CA
__deprecated__
TBSCertificate
decode_certificate(string
|object
cert
)
__deprecated__
string
dsa_sign_key(Sequence
issuer
, Crypto.DSA
dsa
, Sequence
subject
, string
public_key
, int
serial
, int
ttl
, array
|void
extensions
)
issuer
Distinguished name for the issuer.
rsa
RSA parameters for the issuer.
subject
Distinguished name for the subject.
public_key
DER-encoded integer.
See Standards.PKCS.DSA.public_key()
.
serial
Serial number for this key and issuer.
ttl
Validity time in seconds for this signature to be valid.
extensions
Set of extensions.
Returns a DER-encoded certificate.
__deprecated__
string
make_selfsigned_dsa_certificate(Crypto.DSA
dsa
, int
ttl
, array
name
, array
|void
extensions
)
__deprecated__
string
make_selfsigned_rsa_certificate(Crypto.RSA
rsa
, int
ttl
, array
name
, array
|void
extensions
)
__deprecated__
Sequence
make_tbs(object
issuer
, object
algorithm
, object
subject
, object
keyinfo
, object
serial
, int
ttl
, array
extensions
)
__deprecated__
UTC
make_time(int
t
)
Creates a Standards.ASN1.Types.UTC
object from the posix
time t
.
__deprecated__
Verifier
make_verifier(Object
_keyinfo
)
__deprecated__
mapping
(string
:int
) parse_time(UTC
asn1
)
Returns a mapping similar to that returned by gmtime
|
|
|
|
|
|
__deprecated__
string
rsa_sign_digest(Crypto.RSA
rsa
, object
digest_id
, string
digest
)
__deprecated__
string
rsa_sign_key(Sequence
issuer
, Crypto.RSA
rsa
, Sequence
subject
, string
public_key
, int
serial
, int
ttl
, array
|void
extensions
)
issuer
Distinguished name for the issuer.
rsa
RSA parameters for the issuer.
subject
Distinguished name for the issuer.
public_key
DER-encoded RSAPublicKey structure.
See Standards.PKCS.RSA.public_key()
.
serial
Serial number for this key and subject.
ttl
Validity time in seconds for this signature to be valid.
extensions
Set of extensions.
Returns a DER-encoded certificate.
__deprecated__
bool
rsa_verify_digest(Crypto.RSA
rsa
, object
digest_id
, string
digest
, string
s
)
__deprecated__
int(-1..1)
time_compare(mapping
(string
:int
) t1
, mapping
(string
:int
) t2
)
Comparision function between two "date" mappings of the
kind that parse_time
returns.
__deprecated__
TBSCertificate
verify_certificate(string
s
, mapping
authorities
)
Decodes a certificate, checks the signature. Returns the TBSCertificate structure, or 0 if decoding or verification failes.
Authorities is a mapping from (DER-encoded) names to a verifiers.
This function allows self-signed certificates, and it doesn't check that names or extensions make sense.
__deprecated__
mapping
verify_certificate_chain(array
(string
) cert_chain
, mapping
authorities
, int
|void
require_trust
)
Decodes a certificate chain, checks the signatures. Verifies that the chain is unbroken, and that all certificates are in effect (time-wise.)
Returns a mapping with the following contents, depending on the verification of the certificate chain:
| Error describing type of verification failure, if verification failed.
May be one of the following: |
| Index number of the certificate that caused the verification failure. |
| Non-zero if the certificate is self-signed. |
| Non-zero if the certificate is verified. |
|
|
|
|
cert_chain
An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate.
authorities
A mapping from (DER-encoded) names to verifiers.
require_trust
Require that the certificate be traced to an authority, even if it is self signed.
See Standards.PKCS.Certificate.get_dn_string
for converting the
RDN to an X500 style string.
Sequence
Tools.X509.TBSCertificate.algorithm
string
Tools.X509.TBSCertificate.der
object
Tools.X509.TBSCertificate.extensions
optional
this_program
init(Object
asn1
)
Sequence
Tools.X509.TBSCertificate.issuer
BitString
Tools.X509.TBSCertificate.issuer_id
optional
mapping
Tools.X509.TBSCertificate.not_after
mapping
Tools.X509.TBSCertificate.not_before
Verifier
Tools.X509.TBSCertificate.public_key
Gmp.mpz
Tools.X509.TBSCertificate.serial
Sequence
Tools.X509.TBSCertificate.subject
BitString
Tools.X509.TBSCertificate.subject_id
optional
int
Tools.X509.TBSCertificate.version
inherit Verifier : Verifier
this_program
init(string
key
)
bool
verify(Sequence
algorithm
, string
msg
, string
signature
)
edit commands supported:
<firstline>,<lastline><edit command> ^^ numeral (17) ^^ or relative (+17, -17) or a search regexp (/regexp/) or multiple (17/regexp//regexp/+2)
Command | Action |
D | Delete first line in space |
G | Insert hold space |
H | Append current space to hold space |
P | Print current data |
a<string> | Insert |
c<string> | Change current space |
d | Delete current space |
h | Copy current space to hold space |
i<string> | Print string |
l | Print current space |
p | Print first line in data |
q | Quit evaluating |
s/regexp/with/x | Replace |
y/chars/chars/ | Replace chars |
where line is numeral, first 'line'==0
string
|array
`()(string
|array
(string
) commands
, string
|array
(string
) data
, void
|int
suppress
)
int
is_rtlchar(int
c
)
Returns 1
if the character is a RTL character or
indicator, otherwise 0
.
int
is_rtlstring(string
s
)
Returns 1
if the string contains RTL characters or
RTL indicators, otherwise 0
.
int
is_wordchar(int
c
)
Returns whether a unicode character c
is a word, part of a word or not.
| The character is an ideograph (a CJK single-word character) |
| The character is a letter, number or non-spacing mark, as defined by its unicode (general category) specification |
| Any other character (such as symbols, punctuation and separators) |
string
normalize(string
data
, string
method
)
Normalize the given unicode string according to the specified method.
The methods are:
NFC, NFD, NFKC and NFKD.
The methods are described in detail in the UAX #15 document, which can currently be found at http://www.unicode.org/unicode/reports/tr15/tr15-21.html
A short description:
C and D specifies whether to decompose (D) complex characters to their parts, or compose (C) single characters to complex ones.
K specifies whether or not do a canonical or compatibility conversion. When K is present, compatibility transformations are performed as well as the canonical transformations.
In the following text, 'X' denotes the single character 'X', even if there is more than one character inside the quotation marks. The reson is that it's somewhat hard to describe unicode in iso-8859-1.
The Unicode Standard defines two equivalences between characters: canonical equivalence and compatibility equivalence. Canonical equivalence is a basic equivalency between characters or sequences of characters.
'Å' and 'A' '° (combining ring above)' are canonically equivalent.
For round-trip compatibility with existing standards, Unicode has encoded many entities that are really variants of existing nominal characters. The visual representations of these character are typically a subset of the possible visual representations of the nominal character. These are given compatibility decompositions in the standard. Because the characters are visually distinguished, replacing a character by a compatibility equivalent may lose formatting information unless supplemented by markup or styling.
Examples of compatibility equivalences:
Font variants (thin, italic, extra wide characters etc)
Circled and squared characters
super/subscript ('²' -> '2')
Fractions ('½' -> '1/2')
Other composed characters ('fi' -> 'f' 'i', 'kg' -> 'k' 'g')
array
(string
) split_words(string
input
)
Splits the input string into an array of words, on the boundaries between
the different kinds of word characters as defined by is_wordchar
. The
result is an array of words, with the non-word characters between them
thrown away.
array
(string
) split_words_and_normalize(string
input
)
A less wasteful equivalent of
.split_words
(normalize
(input
, "NFKD"))
constant
Unicode.version
Contains the version of the current Unicode database as a string,
e.g. "5.0.0"
.
Pike glue for the open-vcdiff differential compression library. http://code.google.com/p/open-vcdiff/
Encoding and decoding relies on a common string that the differences are computed against - this string is called the dictionary.
Basic usage:
string dict = "abcdef";
VCDiff.Encoder encoder = VCDiff.Encoder (dict);
string encoded = encoder->encode ("abcdefghijklmnopqrstuvwxyz");
VCDiff.Decoder decoder = VCDiff.Decoder (dict);
string decoded = decoder->decode (encoded);
This module contains special values used by various modules, e.g.
a null value used both by Sql
and Standards.JSON
.
In many ways these values should be considered constant, but it is possible for a program to replace them with extended versions, provided they don't break the behavior of the base classes defined here. Since there is no good mechanism to handle such extending in several steps, pike libraries should preferably ensure that the base classes defined here provide required functionality directly.
Since resolving using the dot operator in e.g. Val.null
is
done at compile time, replacement of these values often must take
place very early (typically in a loader before the bulk of the
pike code is compiled) to be effective in such cases. For this
reason, pike libraries should use dynamic resolution through e.g.
->
or master()->resolv()
instead.
Boolean
Val.true
Boolean
Val.false
Objects that represent the boolean values true and false. In a boolean context these evaluate to true and false, respectively.
They produce 1
and 0
, respectively, when cast to
integer, and "1"
and "0"
when cast to string. They
do however not compare as equal to the integers 1 and 0, or any
other values. Val.true
only compares (and hashes) as equal with
other instances of True
(although there should be as few as
possible). Similarly, Val.false
is only considered equal to
other False
instances.
Protocols.JSON
uses these objects to represent the JSON
literals true
and false
.
The correct way to programmatically recognize these values is something like
if (objectp(something) && ([object]something)->is_val_true) ...
and
if (objectp(something) && ([object]something)->is_val_false) ...
respectively. See Val.null
for rationale.
Pike natively uses integers (zero and non-zero) as booleans. These objects don't change that, and unless there's a particular reason to use these objects it's better to stick to e.g. 0 and 1 for boolean values - that is both more efficient and more in line with existing coding practice. These objects are intended for cases where integers and booleans occur in the same place and it is necessary to distinguish them.
Null
Val.null
Object that represents a null value.
In general, null is a value that represents the lack of a real value in the domain of some type. For instance, in a type system with a null value, a variable of string type typically can hold any string and also null to signify no string at all (which is different from the empty string). Pike natively uses the integer 0 (zero) for this, but since 0 also is a real integer it is sometimes necessary to have a different value for null, and then this object is preferably used.
This object is false in a boolean context. It does not cast to
anything, and it is not equal to anything else but other instances
of Null
(which should be avoided).
This object is used by the Sql
module to represent SQL NULL,
and it is used by Protocols.JSON
to represent the JSON literal
null
.
Do not confuse the null value with UNDEFINED
. Although
UNDEFINED
often is used to represent the lack of a real value,
and it can be told apart from an ordinary zero integer with some
effort, it is transient in nature (for instance, it automatically
becomes an ordinary zero when inserted in a mapping). That makes
it unsuitable for use as a reliable null value.
The correct way to programmatically recognize Val.null
is
something like
if (objectp(something) && ([object]something)->is_val_null) ...
That way it's possible for other code to replace it with an
extended class, or create their own variants which needs to behave
like Val.null
.
The Oracle glue currently uses static null objects which won't be affected if this object is replaced.
Common base class for Val.True
and Val.False
, mainly to
facilitate typing. Do not create any instances of this.
constant
int
Val.Boolean.is_val_boolean
Nonzero recognition constant that can be used to recognize both
Val.true
and Val.false
.
Type for the Val.false
object. Do not create more instances of
this - use Val.false
instead.
inherit Boolean : Boolean
constant
int
Val.False.is_val_false
Nonzero recognition constant.
Type for the Val.null
object. Do not create more instances of
this - use Val.null
instead.
Type for the Val.true
object. Do not create more instances of
this - use Val.true
instead.
inherit Boolean : Boolean
constant
int
Val.True.is_val_true
Nonzero recognition constant.
Modules implementing various web standards.
Crypto.Sign.State
|Crypto.MAC.State
decode_jwk(mapping
(string(7bit)
:string(7bit)
) jwk
)
Decode a JSON Web Key (JWK).
Returns an initialized Crypto.Sign.State
or Crypto.MAC.State
on success and UNDEFINED
on failure.
variant
Crypto.Sign.State
|Crypto.MAC.State
decode_jwk(string(8bit)
jwk
)
Decode a JSON Web Key (JWK).
Returns an initialized Crypto.Sign.State
or Crypto.MAC.State
on success and UNDEFINED
on failure.
array
(Crypto.Sign.State
|Crypto.MAC.State
) decode_jwk_set(mapping
(string(8bit)
:array
(mapping
(string(7bit)
:string(7bit)
))) jwk_set
)
Decode a JSON Web Key (JWK) Set.
RFC 7517 section 5, decode_jwk()
variant
array
(Crypto.Sign.State
|Crypto.MAC.State
) decode_jwk_set(string(7bit)
jwk_set
)
Decode a JSON Web Key (JWK) Set.
RFC 7517 section 5, decode_jwk()
array
decode_jws(array
(Crypto.Sign.State
|Crypto.MAC.State
)|Crypto.Sign.State
|Crypto.MAC.State
sign
, string(7bit)
jws
)
Decode a JSON Web Signature (JWS).
sign
The asymetric public or MAC key(s) to validate the jws against.
jws
A JWS as eg returned by encode_jws()
.
Returns 0
(zero) on validation failure.
Returns an array with two elements on success:
Array | |
| The JOSE header. |
| The JWS payload. |
See RFC 7515 section 3.
encode_jws()
, decode_jwt()
, Crypto.Sign.State()->jose_decode()
,
RFC 7515
mapping
(string
:string
|int
) decode_jwt(array
(Crypto.Sign.State
|Crypto.MAC.State
)|Crypto.Sign.State
|Crypto.MAC.State
sign
, string(7bit)
jwt
)
Decode a JSON Web Token (JWT).
sign
The asymetric public or MAC key(s) to validate the jwt against.
jwt
A JWT as eg returned by encode_jwt()
.
Returns 0
(zero) on validation failure (this
includes validation of expiry times).
Returns a mapping of the claims for the token on success. See RFC 7519 section 4.
The time check of the "nbf"
value has a hard coded
60 second grace time (as allowed by RFC 7519 section 4.1.5).
encode_jwt()
, decode_jws()
, RFC 7519 section 4
string(7bit)
encode_jwk(mapping
(string(7bit)
:string(7bit)
) jwk
)
Encode a JSON Web Key (JWK).
variant
string(7bit)
encode_jwk(Crypto.Sign.State
|Crypto.MAC.State
sign
, bool
|void
private_key
)
Encode a JSON Web Key (JWK).
sign
The initialized Crypto.Sign.State
or Crypto.MAC.State
for which a JWK is to be generated.
private_key
If true the private fields of sign
will also be encoded into
the result.
Returns the corresponding JWK.
string(7bit)
encode_jws(Crypto.Sign.State
|Crypto.MAC.State
sign
, mixed
tbs
, string(7bit)
|void
media_type
)
Encode a JSON Web Signature (JWS).
sign
The asymetric private or MAC key to use for signing the result.
tbs
The value to sign.
media_type
The media type of tbs
, cf RFC 7515 section 4.1.9.
Returns 0
(zero) on encoding failure (usually
that sign
doesn't support JWS.
Returns a corresponding JWS on success.
decode_jwt()
, RFC 7515
string(7bit)
encode_jwt(Crypto.Sign.State
|Crypto.MAC.State
sign
, mapping
(string
:string
|int
) claims
)
Encode a JSON Web Token (JWT).
sign
The asymetric private or MAC key to use for signing the result.
claims
The set of claims for the token. See RFC 7519 section 4.
Returns 0
(zero) on encoding failure (usually
that sign
doesn't support JWS.
Returns a corresponding JWT on success.
The claim "iat"
(RFC 7519 section 4.1.6 is added unconditionally,
and the claim "jti"
(RFC 7519 section 4.1.7) is added
if not already present.
decode_jwt()
, RFC 7519 section 4
Represents an RDF tuple set from an OWL perspective.
inherit .RDFS : RDFS
Represents an RDF domain which can contain any number of complete statements.
int
sizeof( Web.RDF arg )
Returns the number of statements in the RDF domain.
Web.RDF
res = Web.RDF()
| x
Modifies the current object to create a union of the current object
and the object x
.
this_program
add_statement(Resource
|string
|multiset
(string
) subj
, Resource
|string
|multiset
(string
) pred
, Resource
|string
|multiset
(string
) obj
)
Adds a statement to the RDF set. If any argument is a string, it
will be converted into a LiteralResource
. If any argument is a
multiset with one string in it, it will be converted into a
URIResource
.
Throws an exception if any argument couldn't be converted into a Resouce object.
string
decode_n_triple_string(string
in
)
Decodes a string that has been encoded for N-triples serialization.
Doesn't correctly decode backslashes that has been encoded with with \u- or \U-notation.
bool
dereify(Resource
r
)
Turns the reified statement r
into a normal statement, if possible.
1 for success, 0 for failure.
int(0..)
dereify_all()
Dereifies as many statements as possible. Returns the number of dereified statements.
string
encode_n_triple_string(string
in
)
Encodes a string for use as tring in N-triples serialization.
array
(array
(Resource
)) find_statements(Resource
|int(0..0)
subj
, Resource
|int(0..0)
pred
, Resource
|int(0..0)
obj
)
Returns an array with the statements that matches the given
subject subj
, predicate pred
and object obj
. Any
and all of the resources may be zero to disregard from matching
that part of the statement, i.e. find_statements(0,0,0) returns
all statements in the domain.
An array with arrays of three elements.
Array | |
| The subject of the statement |
| The predicate of the statement |
| The object of the statement |
string
get_3_tuples()
Returns a 3-tuple serialization of all the statements in the RDF set.
string
get_n_triples()
Returns an N-triples serialization of all the statements in the RDF set.
array
(Resource
) get_properties()
Returns all properties in the domain, e.g. all resources that has been used as predicates.
Resource
get_reify(Resource
subj
, Resource
pred
, Resource
obj
)
Returns a resource that is the subject of the reified statement {subj, pred, obj}, if such a resource exists in the RDF domain.
URIResource
get_resource(string
uri
)
Returns an RDF resource with the given URI as identifier, or zero.
mapping
(Resource
:mapping
(Resource
:array
(Resource
))) get_subject_map()
Returns a mapping with all the domains subject resources as indices and a mapping with that subjects predicates and objects as value.
string
get_xml(void
|int
no_optimize
)
Serialize the RDF domain as an XML string.
no_optimize
If set, the XML serializer will refrain from doing most (size) optimizations of the output.
bool
has_statement(Resource
subj
, Resource
pred
, Resource
obj
)
Returns 1 if the RDF domain contains the relation {subj, pred, obj}, otherwise 0.
bool
is_object(Resource
r
)
Returns 1
if resource r
is used as an object, otherwise
0
.
bool
is_predicate(Resource
r
)
Returns 1
if resource r
is used as a predicate,
otherwise 0
.
bool
is_subject(Resource
r
)
Returns 1
if resource r
is used as a subject, otherwise
0
.
URIResource
make_resource(string
uri
)
Returns an RDF resource with the given URI as identifier, or if no such resrouce exists, creates it and returns it.
int
parse_n_triples(string
in
)
Parses an N-triples string and adds the found statements to the RDF set. Returns the number of added relations.
The parser will throw errors on invalid N-triple input.
Web.RDF
parse_xml(string
|Parser.XML.NSTree.NSNode
in
, void
|string
base
)
Adds the statements represented by the string or tree in
to the
RDF domain. If in
is a tree the in-node should be the RDF
node of the XML serialization. RDF documents take its default
namespace from the URI of the document, so if the RDF document relies
such ingenious mechanisms, pass the document URI in the base
variable.
RDFResource
Web.RDF.rdf_Seq
Seq resource.
RDFResource
Web.RDF.rdf_Statement
Statement resource.
RDFResource
Web.RDF.rdf_first
first resource.
RDFResource
Web.RDF.rdf_nil
nil resource.
constant
string
Web.RDF.rdf_ns
The RDF XML namespace.
RDFResource
Web.RDF.rdf_object
object resource.
RDFResource
Web.RDF.rdf_predicate
predicate resource.
RDFResource
Web.RDF.rdf_rest
rest resource.
RDFResource
Web.RDF.rdf_subject
subject resource.
RDFResource
Web.RDF.rdf_type
type resource.
Resource
reify(Resource
subj
, Resource
pred
, Resource
obj
)
Returns the result of get_reify
, if any. Otherwise calls
reify_low
followed by remove_statement
of the provided
statement {subj, pred, obj}.
The subject of the reified statement.
Resource
reify_low(Resource
subj
, Resource
pred
, Resource
obj
)
Reifies the statement { pred, subj, obj } and returns the resource that denotes the reified statement. There will not be any check to see if the unreified statement is already in the domain, making it possible to define the relation twice. The original statement will not be removed.
The subject of the reified statement.
bool
remove_statement(Resource
subj
, Resource
pred
, Resource
obj
)
Removes the relation from the RDF set. Returns 1 if the relation did exist in the RDF set.
Resource identified by literal.
Web.RDF.LiteralResource Web.RDF.LiteralResource(
string
literal
)
The resource will be identified by literal
.
string
Web.RDF.LiteralResource.datatype
Used to contain rdf:datatype value.
string
get_literal()
Returns the literal string.
string
get_xml()
Returns the literal as an XML string.
inherit Resource : Resource
Resource used for RDF-technical reasons like reification.
Web.RDF.RDFResource Web.RDF.RDFResource(
string
rdf_id
)
The resource will be identified by the identifier rdf_id
string
get_qname(void
|string
ns
)
Returns the qualifying name.
inherit URIResource : URIResource
Instances of this class represents resources as defined in RDF: All things being described by RDF expressions are called resources. A resource may be an entire Web page; such as the HTML document "http://www.w3.org/Overview.html" for example. A resource may be a part of a Web page; e.g. a specific HTML or XML element within the document source. A resource may also be a whole collection of pages; e.g. an entire Web site. A resource may also be an object that is not directly accessible via the Web; e.g. a printed book. This general resource is anonymous and has no URI or literal id.
Resources instantiated from this class should not be used in other RDF domain objects.
URIResource
, LiteralResource
string
get_3_tuple_name()
Returns the nodes' 3-tuple serialized ID.
string
get_n_triple_name()
Returns the nodes' N-triple serialized ID.
Resource identified by URI.
Web.RDF.URIResource Web.RDF.URIResource(
string
uri
)
Creates an URI resource with the uri
as identifier.
Throws an error if another resource with the same URI already exists in the RDF domain.
string
get_namespace()
Returns the namespace this resource URI references to.
string
get_qname(void
|string
ns
)
Returns the qualifying name, or zero.
string
get_uri()
Returns the URI the resource references to.
inherit Resource : Resource
RDF Schema.
void
add_Class(Resource
c
)
void
add_subClassOf(Resource
a
, Resource
b
)
void
add_subPropertyOf(Resource
a
, Resource
b
)
inherit .RDF : RDF
RDFSResource
Web.RDFS.rdfs_Class
RDFSResource
Web.RDFS.rdfs_subClassOf
RDFSResource
Web.RDFS.rdfs_Literal
RDFSResource
Web.RDFS.rdfs_subPropertyOf
RDFSResource
Web.RDFS.rdfs_domain
RDFSResource
Web.RDFS.rdfs_range
constant
string
Web.RDFS.rdfs_ns
The RDF Schema XML-namespace.
inherit URIResource : URIResource
The Web.Api has modules and classes for communicating with various
(RESTful) web api's such as Web.Api.Facebook
,
Web.Api.Instagram
, Web.Api.Twitter
etc.
constant
string
Web.Api.USER_AGENT
Default user agent in HTTP calls
Base class for implementing a (RESTful) WebApi like Facebook's Graph API, Instagram's API, Twitter's API and so on.
Note: This class is useless in it self, and is intended to be inherited by classes implementing a given Web.Api.
Look at the code in Web.Api.Github
, Web.Api.Instagram
,
Web.Api.Linkedin
etc to see some examples of implementations.
protected
constantstring
Web.Api.Api.ACCESS_TOKEN_PARAM_NAME
In some API's (LinkedIn f ex) this is named something else so it needs to be overridden i cases where it has a different name than the standard one
constant
int
Web.Api.Api.API_URI
The URI to the remote API
Web.Api.Api.protected
constantAuthClass
Authentication class to use
typedef
function
(mapping
, Protocols.HTTP.Query
:void
) Web.Api.Api.Callback
Typedef for the async callback method signature.
protected
constantint
Web.Api.Api.DECODE_UTF8
If 1
Standards.JSON.decode_utf8()
will be used when JSON data
is decoded.
typedef
mapping
|Web.Auth.Params
Web.Api.Api.ParamsArg
Typedef for a parameter argument
protected
Web.Auth.OAuth2.Client
Web.Api.Api._auth
Authorization object.
Web.Auth.OAuth2
protected
mapping
(int
:array
(Protocols.HTTP.Query
|Callback
)) Web.Api.Api._query_objects
The HTTP query objects when running async.
Web.Auth.OAuth2.Client
Web.Api.Api.auth
Getter for the authentication object. Most likely this will be a class
derived from Web.Auth.OAuth2.Client
.
Web.Auth.OAuth2.Client
or Web.Auth.OWeb.Auth.Client
Read only
mixed
call(string
api_method
, void
|ParamsArg
params
, void
|string
http_method
, void
|string
data
, void
|Callback
cb
)
Calls a remote API method.
An exception is thrown if the response status code is other than
200
, 301
or 302
.
api_method
The remote API method to call! This should be a Fully Qualified Domain Name
params
Additional params to send in the request
http_method
HTTP method to use. GET
is default
data
Inline data to send in a POST
request for instance.
cb
Callback function to get into in async mode
If JSON is available the JSON response from servie will be decoded
and returned. If not, the raw response (e.g a JSON string) will be
returned. The exception to this is if the status code in the response is a
30x
(a redirect), then the response headers mapping will be
returned.
void
close_connections()
Forcefully close all HTTP connections. This only has effect in async mode.
Web.Api.Api Web.Api.Api(
string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Creates a new Api instance
client_id
The application ID
client_secret
The application secret
redirect_uri
Where the authorization page should redirect back to. This must be fully qualified domain name.
scope
Extended permissions to use for this authentication.
protected
mapping
default_params()
Return default params
mixed
delete(string
api_method
, void
|ParamsArg
params
, void
|Callback
cb
)
Invokes a call with a DELETE method
api_method
The remote API method to call
params
cb
Callback function to get into in async mode
mixed
get(string
api_method
, void
|ParamsArg
params
, void
|Callback
cb
)
Invokes a call with a GET method
api_method
The remote API method to call
params
cb
Callback function to get into in async mode
protected
string
get_encoding(mapping
h
)
Returns the encoding from a response
h
The headers mapping from a HTTP respose
protected
string
get_uri(string
method
)
Convenience method for getting the URI to a specific API method
method
int(0..)
Web.Api.Api.http_request_timeout
Request timeout in seconds. Only affects async queries.
protected
array
(string
) make_multipart_message(mapping
p
, string
body
)
Creates the body of an Upload request
p
The API request parameters
body
Data of the document to upload
An array with two indices:
The value for the main Content-Type header
The request body
mapping
(string
:string
|mapping
) parse_canonical_url(string
url
)
This can be used to parse a link resource returned from a REST api. Many API returns stuff like:
{
...
"pagination" : {
"next" : "/api/v1/method/path?some=variables&page=2&per_page=20"
}
}
If pagination->next is passed to this method it will return a path of /method/path, given that the base URI of the web api is something along the line of https://some.url/api/v1, and a mapping containing the query variables (which can be passed as a parameter to any of the get, post, delete, put methods.
url
|
|
mixed
patch(string
api_method
, void
|ParamsArg
params
, void
|Callback
cb
)
Invokes a call with a PATCH method
api_method
The remote API method to call
params
cb
Callback function to get into in async mode
mixed
post(string
api_method
, void
|ParamsArg
params
, void
|string
data
, void
|Callback
cb
)
Invokes a call with a POST method
api_method
The remote API method to call
params
data
Eventual inline data to send
cb
Callback function to get into in async mode
mixed
put(string
api_method
, void
|ParamsArg
params
, void
|Callback
cb
)
Invokes a call with a PUT method
api_method
The remote API method to call
params
cb
Callback function to get into in async mode
protected
string
unescape_forward_slashes(string
s
)
Unescapes escaped forward slashes in a JSON string
bool
Web.Api.Api.utf8_decode
If 1
Standards.JSON.decode_utf8()
will be used when JSON data
is decoded.
Internal class ment to be inherited by implementing Api's classes that corresponds to a given API endpoint.
protected
constantint
Web.Api.Api.Method.METHOD_PATH
API method location within the API
https://api.instagram.com/v1/media/search
............................^^^^^^^
protected
mixed
_delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_patch(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_post(string
s
, void
|ParamsArg
p
, void
|string
data
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
Web.Api.Api.Method Web.Api.Api.Method()
Hidden constructor. This class can not be instantiated directly
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Facebook API.
See Web.Api.Api()
for further information.
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
constant
string
Web.Api.Facebook.Graph.API_URI
The base uri to the Graph API
Any
Web.Api.Facebook.Graph.any
Getter for the Any
object which is a generic object for making request
to the Facebook Graph API
Any
Read only
mapping
delete(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic DELETE
request to the Facebook Graph API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
mapping
get(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic GET
request to the Facebook Graph API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
inherit Web.Api.Api : parent
mapping
post(string
path
, void
|ParamsArg
params
, void
|string
data
, void
|Callback
cb
)
Make a generic POST
request to the Facebook Graph API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
data
cb
Callback for async requests
mapping
put(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic PUT
request to the Facebook Graph API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
A generic wrapper around Method
inherit Method : Method
mixed
delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
mixed
get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
inherit Web.Api.Api.Method : Method
mixed
post(string
s
, void
|ParamsArg
p
, void
|string
data
, void
|Callback
cb
)
Internal convenience method
mixed
put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Github API.
See Web.Api.Api()
for further information.
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
constant
string
Web.Api.Github.Github.API_URI
The base uri to the Github API
Any
Web.Api.Github.Github.any
Getter for the Any
object which is a generic object for making request
to the Github API
Any
Read only
mapping
delete(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic DELETE
request to the Github API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
mapping
get(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic GET
request to the Github API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
inherit Web.Api.Api : parent
mapping
post(string
path
, void
|ParamsArg
params
, void
|string
data
, void
|Callback
cb
)
Make a generic POST
request to the Github API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
data
cb
Callback for async requests
mapping
put(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic PUT
request to the Github API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
A generic wrapper around Method
inherit Method : Method
mixed
delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
mixed
get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
inherit Web.Api.Api.Method : Method
mixed
post(string
s
, void
|ParamsArg
p
, void
|string
data
, void
|Callback
cb
)
Internal convenience method
mixed
put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
Internal class ment to be inherited by other Google API's
inherit Web.Api.Api : parent
protected
mixed
_delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_post(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
inherit Web.Api.Api.Method : Method
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Analytics API.
See Web.Api.Api()
for further information.
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
protected
constantstring
Web.Api.Google.Analytics.V3.API_URI
API base URI.
protected
Core
Web.Api.Google.Analytics.V3._core
protected
RealTime
Web.Api.Google.Analytics.V3._realtime
protected
Management
Web.Api.Google.Analytics.V3._management
Internal singleton objects. Retrieve an instance via core
,
realtime
and management
.
Core
Web.Api.Google.Analytics.V3.core
Getter for the Core
API
Read only
inherit Web.Api.Google.Api : parent
Management
Web.Api.Google.Analytics.V3.management
Getter for the Management
API
Read only
RealTime
Web.Api.Google.Analytics.V3.realtime
Getter for the RealTime
API
Read only
Interface to the Google Analytics core API
mixed
get(mapping
params
, void
|Callback
cb
)
Get data from the core api
params
cb
inherit Method : Method
Interface to the Google Analytics managment API
mixed
account_summaries(void
|ParamsArg
params
, void
|Callback
cb
)
Get account summaries
params
cb
inherit Method : Method
Interface to the Google Analytics realtime API
mixed
get(mapping
params
, void
|Callback
cb
)
Get data from the realtime api
params
cb
inherit Method : Method
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Google+ API.
See Web.Api.Api()
for further information.
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
protected
constantstring
Web.Api.Google.Plus.V1.API_URI
API base URI.
private
People
Web.Api.Google.Plus.V1._people
private
Activities
Web.Api.Google.Plus.V1._activities
Internal singleton objects. Get an instance via people
and
activities
.
Activities
Web.Api.Google.Plus.V1.activities
Getter for the Activities
object which has methods for all
activities
related Google+ API methods.
Read only
inherit Web.Api.Google.Api : Api
People
Web.Api.Google.Plus.V1.people
Getter for the People
object which has methods for all people
related Google+ API methods.
Read only
Class implementing the Google+ Activities API. https://developers.google.com/+/api/latest/activities
Retreive an instance of this class through the
activities
property
inherit Method : Method
Class implementing the Google+ People API. https://developers.google.com/+/api/latest/people
Retreive an instance of this class through the
Social.Google.Plus()->people
property
mapping
get(void
|string
user_id
, void
|Callback
cb
)
Get info ablut a person.
user_id
If empty the currently authenticated user will be fetched.
cb
Callback for async request
inherit Method : Method
mapping
list(void
|string
user_id
, void
|string
collection
, void
|ParamsArg
params
, void
|Callback
cb
)
List all of the people in the specified collection
.
user_id
If empty the currently authenticated user will be used.
collection
If empty "public" activities will be listed. Acceptable values are:
The list of people who this user has added to one or more circles, limited to the circles visible to the requesting application.
params
| Max number of items ti list |
| The order to return people in. Acceptable values are:
|
| The continuation token, which is used to page through large result
sets. To get the next page of results, set this parameter to the value
of |
cb
Callback for async request
Instagram API implementation. https://instagram.com/developer/
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Instagram API.
See Web.Api.Api()
for further information.
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
Class for communicating with version 1 of the Instagram API.
protected
constantstring
Web.Api.Instagram.V1.API_URI
The URI to the Instagram API
private
Any
Web.Api.Instagram.V1._any
Singleton Any
object. Will be instantiated first time requested.
private
Comments
Web.Api.Instagram.V1._comments
Singleton Comments
object. Will be instantiated first time requested.
private
Likes
Web.Api.Instagram.V1._likes
Singleton Likes
object. Will be instantiated first time requested.
private
Locations
Web.Api.Instagram.V1._locations
Singleton Locations
object. Will be instantiated first time requested.
private
Media
Web.Api.Instagram.V1._media
Singleton Media
object. Will be instantiated first time requested.
private
Tags
Web.Api.Instagram.V1._tags
Singleton Tags
object. Will be instantiated first time requested.
private
Users
Web.Api.Instagram.V1._users
Singleton User
object. Will be instantiated first time requested.
Any
Web.Api.Instagram.V1.any
Getter for the Any
object which can be used to query any method in
the Instagram web api. The METHOD_PATH is set to / in
this object.
Read only
Comments
Web.Api.Instagram.V1.comments
Getter for the Comments
object which has methods for all
comments
related Instagram API methods.
Read only
mapping
delete(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic DELETE
request to the Instagram API.
path
What to request. Like me
, users/self
,
[some_id]/something
.
params
cb
Callback for async requests
mapping
get(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic GET
request to the Instagram API.
path
What to request. Like me
, users/self
,
[some_id]/something
.
params
cb
Callback for async requests
inherit Web.Api.Api : parent
Likes
Web.Api.Instagram.V1.likes
Getter for the Likes
object which has methods for all likes
related Instagram API methods.
Read only
Locations
Web.Api.Instagram.V1.locations
Getter for the Locations
object which has methods for all
locations
related Instagram API methods.
Read only
Media
Web.Api.Instagram.V1.media
Getter for the Media
object which has methods for all media
related Instagram API methods.
Read only
mapping
post(string
path
, void
|ParamsArg
params
, string
data
, void
|Callback
cb
)
Make a generic POST
request to the Instagram API.
path
What to request. Like me
, users/self
,
[some_id]/something
.
params
data
cb
Callback for async requests
mapping
put(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic PUT
request to the Instagram API.
path
What to request. Like me
, users/self
,
[some_id]/something
.
params
cb
Callback for async requests
Tags
Web.Api.Instagram.V1.tags
Getter for the Tags
object which has methods for all tags
related Instagram API methods.
Read only
Users
Web.Api.Instagram.V1.users
Getter for the Users
object which has methods for all users
related Instagram API methods.
Read only
A generic wrapper around Method
. This will query the root of the
API, and can be used to query methods not implemented in this module.
mixed
delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
DELETE data
s
The path to the Instagram API to query
p
Parameters to the query
cb
Async callback
mixed
get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
GET data
s
The path to the Instagram API to query
p
Parameters to the query
cb
Async callback
inherit Method : Method
mixed
post(string
s
, void
|ParamsArg
p
, string
data
, void
|Callback
cb
)
POST data
s
The path to the Instagram API to query
p
Parameters to the query
cb
Async callback
mixed
put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
PUT data
s
The path to the Instagram API to query
p
Parameters to the query
cb
Async callback
Class implementing the Instagram Comments API. http://instagram.com/developer/endpoints/comments/
Retreive an instance of this class via the comments
property.
mapping
add(string
media_id
, string
comment
, void
|Callback
cb
)
Get a full list of comments on a media.
This method is not allowed by default. You have to contact Instagram in order to activate this method. http://bit.ly/instacomments
Required scope: comments
media_id
The media to retreive comments for
cb
Callback for async mode
inherit Method : Method
mapping
list(string
media_id
, void
|Callback
cb
)
Get a full list of comments on a media.
Required scope: comments
media_id
The media to retreive comments for
cb
Callback for async mode
mapping
remove(string
media_id
, string
comment_id
, void
|Callback
cb
)
Remove a comment either on the authenticated user's media or authored by the authenticated user.
Required scope: comments
media_id
The media the comment is for
comment_id
The comment to remove
cb
Callback for async mode
Class implementing the Instagram Likes API. http://instagram.com/developer/endpoints/likes/
Retreive an instance of this class via the likes
property.
mapping
add(string
media_id
, void
|Callback
cb
)
Set a like on this media by the currently authenticated user.
Required scope: likes
media_id
cb
inherit Method : Method
mapping
list(string
media_id
, void
|Callback
cb
)
Get a list of users who have liked this media.
http://instagram.com/developer/endpoints/likes/#get_media_likes
Required scope: likes
media_id
cb
mapping
remove(string
media_id
, void
|Callback
cb
)
Remove a like on this media by the currently authenticated user.
http://instagram.com/developer/endpoints/likes/#delete_likes
Required scope: likes
media_id
cb
Class implementing the Instagram Likes API. http://instagram.com/developer/endpoints/likes/
Retreive an instance of this class via the locations
property.
inherit Method : Method
mapping
location(string
location_id
, void
|Callback
cb
)
Get information about a location.
http://instagram.com/developer/endpoints/locations/#get_locations
location_id
cb
mapping
recent_media(string
location_id
, void
|ParamsArg
params
, void
|Callback
cb
)
Get a list of recent media objects from a given location. May return a mix of both image and video types.
http://instagram.com/developer/endpoints/locations/#get_locations_media_recent
location_id
params
| Return media after this UNIX timestamp |
| Return media before this min_id. |
| Return media after this max_id. |
| Return media before this UNIX timestamp |
cb
mapping
search(ParamsArg
params
, void
|Callback
cb
)
Search for a location by geographic coordinate.
http://instagram.com/developer/endpoints/locations/#get_locations_search
params
| Latitude of the center search coordinate. If used, lng is required. |
| Default is 1000m (distance=1000), max distance is 5000. |
| Longitude of the center search coordinate. If used, lat is required. |
| Returns a location mapped off of a foursquare v2 api location id. If used, you are not required to use lat and lng. |
| Returns a location mapped off of a foursquare v1 api location id. If used, you are not required to use lat and lng. Note that this method is deprecated; you should use the new foursquare IDs with V2 of their API. |
cb
Class implementing the Instagram Media API. http://instagram.com/developer/endpoints/media/
Retreive an instance of this class via the media
property
inherit Method : Method
mapping
item(string
media_id
, void
|Callback
cb
)
Get information about a media object. The returned type key will allow you to differentiate between image and video media. Note: if you authenticate with an OAuth Token, you will receive the user_has_liked key which quickly tells you whether the current user has liked this media item.
media_id
cb
Callback function when in async mode
mapping
popular(void
|Callback
cb
)
Get a list of what media is most popular at the moment. Can return a mix of image and video types.
cb
Callback function when in async mode
mapping
search(void
|ParamsArg
params
, void
|Callback
cb
)
Search for media in a given area. The default time span is set to 5 days. The time span must not exceed 7 days. Defaults time stamps cover the last 5 days. Can return mix of image and video types.
params
Can have:
| Latitude of the center search coordinate. If used, lng is required. |
| A unix timestamp. All media returned will be taken later than this timestamp. |
| Longitude of the center search coordinate. If used, lat is required. |
| A unix timestamp. All media returned will be taken earlier than this timestamp. |
| Default is 1km (distance=1000), max distance is 5km. |
cb
Callback function when in async mode
Internal convenience class.
protected
mixed
_delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_post(string
s
, void
|ParamsArg
p
, string
data
, void
|Callback
cb
)
Internal convenience method
protected
mixed
_put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
inherit Web.Api.Api.Method : Method
Class implementing the Instagram Tags API. http://instagram.com/developer/endpoints/tags/
Retreive an instance of this class via the tags
property.
inherit Method : Method
mapping
recent(string
tag_name
, void
|ParamsArg
params
, void
|Callback
cb
)
Get a list of recently tagged media. Note that this media is ordered by when the media was tagged with this tag, rather than the order it was posted. Use the max_tag_id and min_tag_id parameters in the pagination response to paginate through these objects. Can return a mix of image and video types.
http://instagram.com/developer/endpoints/tags/#get_tags_media_recent
tag_name
params
Can be:
| Return media before this min_id. |
| Return media after this max_id. |
cb
Callback function when in async mode
mapping
search(string
tag_name
, Callback
cb
)
Search for tags by name. Results are ordered first as an exact match, then by popularity. Short tags will be treated as exact matches.
http://instagram.com/developer/endpoints/tags/#get_tags_search
tag_name
cb
Callback function when in async mode
mapping
tag(string
tag_name
, void
|Callback
cb
)
Get information about a tag object.
tag_name
cb
Callback function when in async mode
Class implementing the Instagram Users API. http://instagram.com/developer/endpoints/users/
Retreive an instance of this class via the users
property
mapping
feed(void
|ParamsArg
params
, void
|Callback
cb
)
Get the currently authenticated users feed. http://instagram.com/developer/endpoints/users/#get_users
params
Valida parameters are:
| Number of items to return. Default is 20. |
| Return media later than this min_id |
| Return media earlier than this max_id |
cb
Callback function when in async mode
mapping
followed_by(string
|void
user_id
, void
|Callback
cb
)
Get the list of users this user is followed by.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_users_followed_by
user_id
cb
Callback function when in async mode
mapping
follows(void
|string
user_id
, void
|Callback
cb
)
Get the list of users this user follows.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_users_follows
user_id
cb
Callback function when in async mode
inherit Method : Method
mapping
liked(void
|ParamsArg
params
, void
|Callback
cb
)
See the authenticated user's list of media they've liked. May return a mix of both image and video types. Note: This list is ordered by the order in which the user liked the media. Private media is returned as long as the authenticated user has permission to view that media. Liked media lists are only available for the currently authenticated user.
http://instagram.com/developer/endpoints/users/#get_users_feed_liked
params
Valida parameters are:
| Number of items to return. Default is 20. |
| Return media liked before this id. |
cb
Callback function when in async mode
mapping
recent(void
|string
uid
, void
|ParamsArg
params
, void
|Callback
cb
)
Get the most recent media published by a user. May return a mix of both image and video types. http://instagram.com/developer/endpoints/users/get_users_media_recent
uid
An Instagram user ID
params
Valida parameters are:
| Number of items to return. Default is 20. |
| Return media later than this min_id |
| Return media earlier than this max_id |
| Return media before this UNIX timestamp. |
| Return media after this UNIX timestamp. |
cb
Callback function when in async mode
mapping
relationship(string
user_id
, void
|Callback
cb
)
Get information about a relationship to another user.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_relationship
user_id
cb
Callback function when in async mode
mapping
relationship_change(string
user_id
, string
action
, void
|Callback
cb
)
Modify the relationship between the current user and the target user.
Required scope: relationships
user_id
The user to change the relationship to
action
How to change the relationship. Can be:
cb
Callback function if in async mode
mapping
requested_by(void
|Callback
cb
)
List the users who have requested this user's permission to follow.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_incoming_requests
cb
Callback function when in async mode
mapping
search(string
query
, void
|int
count
, void
|Callback
cb
)
Search for a user by name.
http://instagram.com/developer/endpoints/users/#get_users_search
query
A query string.
count
Max number of users to return
cb
Callback function when in async mode
mapping
user(void
|string
uid
, void
|Callback
cb
)
Get basic information about a user.
uid
An Instagram user ID. If not given the currently authenticated user will be fetched
cb
Callback function when in async mode
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Github API.
See Web.Api.Api()
for further information about the arguments
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
constant
string
Web.Api.Linkedin.V1.API_URI
The base uri to the API
Any
Web.Api.Linkedin.V1.any
Getter for the Any
object which is a generic object for making request
to the Linkedin API
Any
Read only
protected
mapping
default_params()
Default parameters that goes with every call
mapping
delete(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic DELETE
request to the Linkedin API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
mapping
get(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic GET
request to the Linkedin API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
inherit Web.Api.Api : parent
mapping
post(string
path
, void
|ParamsArg
params
, void
|string
data
, void
|Callback
cb
)
Make a generic POST
request to the Linkedin API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
data
cb
Callback for async requests
mapping
put(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic PUT
request to the Linkedin API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
A generic wrapper around Method
inherit Method : Method
mixed
delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
mixed
get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
inherit Web.Api.Api.Method : Method
mixed
post(string
s
, void
|ParamsArg
p
, void
|string
data
, void
|Callback
cb
)
Internal convenience method
mixed
put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
protected
this_program
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiates the default Twitter API.
See Web.Api.Api()
for further information.
client_id
Your application key/id
client_secret
Your application secret
redirect_uri
The redirect URI after an authentication
scope
The application scopes to grant access to
Any
Web.Api.Twitter.V1_1.any
Getter for the Any
object which is a generic object for making request
to the Twitter API
Any
Read only
protected
mapping
default_params()
Default parameters that goes with every call
mapping
delete(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic DELETE
request to the Twitter API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
mapping
get(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic GET
request to the Twitter API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
inherit Web.Api.Api : parent
mapping
post(string
path
, void
|ParamsArg
params
, void
|string
data
, void
|Callback
cb
)
Make a generic POST
request to the Twitter API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
data
cb
Callback for async requests
mapping
put(string
path
, void
|ParamsArg
params
, void
|Callback
cb
)
Make a generic PUT
request to the Twitter API.
path
What to request. Like me
, me/pictures
,
[some_id]/something
.
params
cb
Callback for async requests
A generic wrapper around Method
inherit Method : Method
mixed
delete(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
mixed
get(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
inherit Web.Api.Api.Method : Method
mixed
post(string
s
, void
|ParamsArg
p
, void
|string
data
, void
|Callback
cb
)
Internal convenience method
mixed
put(string
s
, void
|ParamsArg
p
, void
|Callback
cb
)
Internal convenience method
Various authentication modules and classes.
constant GOOGLE_KEY = "some-key-911bnn5s.apps.googleusercontent.com";
constant GOOGLE_SECRET = "5arQDOugDrtIOVklkIet2q2i";
Web.Auth.Google.Authorization auth;
int main(int argc, array(string) argv)
{
auth = Web.Auth.Google.Authorization(GOOGLE_KEY, GOOGLE_SECRET,
"http://localhost");
// The generated access token will be saved on disk.
string progname = replace(sprintf("%O", object_program(auth)), ".", "_");
string cookie = progname + ".cookie";
// If the cookie exists, set the authentication from the saved values
if (Stdio.exist(cookie)) {
auth->set_from_cookie(Stdio.read_file(cookie));
}
// Not authenticated, can mean no previous authentication is done, or that
// the authentication has expired. Some services have persistent access tokens
// some don't
if (!auth->is_authenticated()) {
// Try to renew the access token of it's renewable
if (auth->is_renewable()) {
write("Trying to refresh token...\n");
string data = auth->refresh_access_token();
Stdio.write_file(cookie, data);
}
else {
// No argument, start the authentication process
if (argc == 1) {
// Get the uri to the authentication page
string uri = auth->get_auth_uri();
write("Opening \"%s\" in browser.\nCopy the contents of the address "
"bar into here: ", Standards.URI(uri));
sleep(1);
string open_app;
// Mac
if (Process.run(({ "which", "open" }))->exitcode == 0) {
open_app = "open";
}
// Linux
else if (Process.run(({ "which", "xdg-open" }))->exitcode == 0) {
open_app = "xdg-open";
}
// ???
else {
open_app = "open";
}
Process.create_process(({ open_app, uri }));
// Wait for the user to paste the string from the address bar
string resp = Stdio.Readline()->read();
mapping p = Web.Auth.query_to_mapping(Standards.URI(resp)->query);
string code;
// This is if the service is OAuth1
if (p->oauth_token) {
auth->set_authentication(p->oauth_token);
code = p->oauth_verifier;
}
// OAuth2
else {
code = p->code;
}
// Get the access token and save the response to disk for later use.
string data = auth->request_access_token(code);
Stdio.write_file(cookie, data);
}
// If the user gives the access code from command line.
else {
string data = auth->request_access_token(argv[1]);
Stdio.write_file(cookie, data);
}
}
}
if (!auth->is_authenticated()) {
werror("Authentication failed");
}
else {
write("Congratulations you are now authenticated\n");
}
}
mapping
query_to_mapping(string
query
)
Turns a query string into a mapping
query
This class is used to OAuth2 authenticate agains Facebook
inherit .OAuth2.Client : Client
This class is used to OAuth2 authenticate against Github
inherit .OAuth2.Client : Client
This class is used to OAuth2 authenticate agains Instagram
constant
string
Web.Auth.Instagram.OAUTH_AUTH_URI
Instagram authorization URI
constant
string
Web.Auth.Instagram.OAUTH_TOKEN_URI
Instagram request access token URI
protected
string
Web.Auth.Instagram._scope
Default scope
inherit .OAuth2.Client : Client
protected
multiset
(string
) Web.Auth.Instagram.valid_scopes
Valid Instagram scopes
This class is used to OAuth2 authenticate against LinkedIn
Web.Auth.Linkedin.protected
constantDEFAULT_SCOPE
Default scope to use if none is set explicitly
protected
constantint
Web.Auth.Linkedin.STATE
Adds the state parameter to the request which will have the value of a random string
inherit .OAuth2.Client : Client
Representation of a parameter.
Many Social web services use a RESTful communication and have similiar API's. This class is suitable for many RESTful web services and if this class doesn't suite a particular service, just inherit this class and rewrite the behaviour where needed.
Params
string sprintf(string format, ... Web.Auth.Param arg ... )
String format method
t
bool
res = Web.Auth.Param()
< other
Checks if this object is less than other
other
bool
res = Web.Auth.Param()
== other
Comparer method. Checks if other
equals this object
other
bool
res = Web.Auth.Param()
> other
Checks if this object is greater than other
other
Web.Auth.Param Web.Auth.Param(
string
name
, mixed
value
)
Creates a new instance of Param
name
value
string
get_name()
Getter for the parameter name
string
get_value()
Getter for the parameter value
private
void
low_set_value(string
v
)
Makes sure v
to set as value
is in UTF-8 encoding
v
protected
string
Web.Auth.Param.name
The name of the parameter
string
name_value()
Returns the name and value as querystring key/value pair
string
name_value_encoded()
Same as name_value()
except this URL encodes the value.
void
set_name(string
name
)
Setter for the parameter name
name
void
set_value(mixed
value
)
Setter for the parameter value
value
protected
string
Web.Auth.Param.value
The value of the parameter
Parameter collection class
Param
array
(string
) indices( Web.Auth.Params arg )
Parameter keys
string sprintf(string format, ... Web.Auth.Params arg ... )
String format method
t
array
(string
) values( Web.Auth.Params arg )
Parameter values
this_program
res = Web.Auth.Params()
+ p
Add p
to the array of Param
eters
p
A new Params
object
this_program
res = Web.Auth.Params()
- p
Remove p
from the Param
eters array of the current object.
p
Param
res = Web.Auth.Params()
[ key
]
Index lookup
key
The name of a Param
erter to find.
this_program
add_mapping(mapping
value
)
Add a mapping of key/value pairs to the current instance
value
The object being called
(int)Web.Auth.Params()
(float)Web.Auth.Params()
(string)Web.Auth.Params()
(array)Web.Auth.Params()
(mapping)Web.Auth.Params()
(multiset)Web.Auth.Params()
Casting method
how
this_program
clone()
Clone the current instance
Web.Auth.Params Web.Auth.Params(
Param
... args
)
Creates a new instance of Params
args
array
(Param
) get_params()
Returns the array of Param
eters
protected
array
(Param
) Web.Auth.Params.params
The parameters.
string
sign(string
secret
)
Sign the parameters
secret
The API secret
mapping
(string
:mixed
) to_mapping()
Turns the parameters into a mapping
string
to_query()
Turns the parameters into a query string
Twitter authentication class
constant
string
Web.Auth.Twitter.ACCESS_TOKEN_URL
The endpoint to send request for an access token
constant
string
Web.Auth.Twitter.REQUEST_TOKEN_URL
The endpoint to send request for a request token
constant
string
Web.Auth.Twitter.USER_AUTH_URL
The enpoint to redirect to when authenticating an application
inherit Web.Auth.OAuth.Authentication : Authentication
Google authentication classes.
Google Analytics authorization class
constant
string
Web.Auth.Google.Analytics.SCOPE_RO
constant
string
Web.Auth.Google.Analytics.SCOPE_RW
constant
string
Web.Auth.Google.Analytics.SCOPE_EDIT
constant
string
Web.Auth.Google.Analytics.SCOPE_MANAGE_USERS
constant
string
Web.Auth.Google.Analytics.SCOPE_MANAGE_USERS_RO
Authentication scopes
protected
string
Web.Auth.Google.Analytics._scope
Default scope
inherit Authorization : Authorization
protected
multiset
(string
) Web.Auth.Google.Analytics.valid_scopes
All valid scopes
Default Google authorization class For more info see https://developers.google.com/+/web/api/rest/oauth
constant
string
Web.Auth.Google.Authorization.OAUTH_AUTH_URI
constant
string
Web.Auth.Google.Authorization.OAUTH_TOKEN_URI
constant
string
Web.Auth.Google.Authorization.SCOPE_EMAIL
constant
string
Web.Auth.Google.Authorization.SCOPE_OPENID
constant
string
Web.Auth.Google.Authorization.SCOPE_PROFILE
inherit Web.Auth.OAuth2.Client : Client
protected
multiset
(string
) Web.Auth.Google.Authorization.valid_scopes
All valid socpes
Google+ authorization class
constant
string
Web.Auth.Google.Plus.SCOPE_ME
constant
string
Web.Auth.Google.Plus.SCOPE_LOGIN
Authentication scopes
protected
string
Web.Auth.Google.Plus._scope
Default scope
inherit Authorization : Authorization
protected
multiset
(string
) Web.Auth.Google.Plus.valid_scopes
All valid scopes
OAuth module
Example
import Web.Auth.OAuth;
string endpoint = "http://twitter.com/users/show.xml";
Consumer consumer = Consumer(my_consumer_key, my_consumer_secret);
Token token = Token(my_access_token_key, my_access_token_secret);
Params params = Params(Param("user_id", 12345));
Request request = request(consumer, token, params);
request->sign_request(Signature.HMAC_SHA1, consumer, token);
Protocols.HTTP.Query query = request->submit();
if (query->status != 200)
error("Bad response status: %d\n", query->status);
werror("Data is: %s\n", query->data());
constant
string
Web.Auth.OAuth.CALLBACK_KEY
Query string variable name for a callback URL.
constant
string
Web.Auth.OAuth.CONSUMER_KEY_KEY
Query string variable name for the consumer key.
constant
string
Web.Auth.OAuth.NONCE_KEY
Query string variable name for the nonce.
constant
string
Web.Auth.OAuth.SIGNATURE_KEY
Query string variable name for the signature.
constant
string
Web.Auth.OAuth.SIGNATURE_METHOD_KEY
Query string variable name for the signature method.
constant
string
Web.Auth.OAuth.TIMESTAMP_KEY
Query string variable name for the timestamp.
constant
string
Web.Auth.OAuth.TOKEN_KEY
Query string variable name for the token key.
constant
string
Web.Auth.OAuth.TOKEN_SECRET_KEY
Query string variable name for the token secret.
constant
string
Web.Auth.OAuth.VERSION
Verion
constant
string
Web.Auth.OAuth.VERSION_KEY
Query string variable name for the version.
Params
get_default_params(Consumer
consumer
, Token
token
)
Returns the default params for authentication/signing.
string
nonce()
Generates a nonce.
string
normalize_uri(string
|Standards.URI
uri
)
Normalizes uri
uri
A string or Standards.URI
.
Params
query_to_params(string
|Standards.URI
|mapping
q
)
Converts a query string, or a mapping, into a Params
object.
Request
request(string
|Standards.URI
uri
, Consumer
consumer
, Token
token
, void
|Params
params
, void
|string
http_method
)
Helper method to create a Request
object.
An error if consumer
is null.
http_method
Defaults to GET.
The purpose of this class is to streamline OAuth1 with OAuth2. This class will not do much on it's own, since its purpose is to be inherited by some other class implementing a specific authorization service.
constant
int
Web.Auth.OAuth.Authentication.ACCESS_TOKEN_URL
The endpoint to send request for an access token.
constant
int
Web.Auth.OAuth.Authentication.REQUEST_TOKEN_URL
The endpoint to send request for a request token.
constant
int
Web.Auth.OAuth.Authentication.USER_AUTH_URL
The enpoint to redirect to when authorize an application.
string
call(string
|Standards.URI
url
, void
|mapping
|.Params
args
, void
|string
method
)
Does the low level HTTP call to a service.
An error if HTTP status != 200
url
The full address to the service e.g: http://twitter.com/direct_messages.xml
args
Arguments to send with the request
mehod
The HTTP method to use
Web.Auth.OAuth.Authentication Web.Auth.OAuth.Authentication(
string
client_id
, string
client_secret
, void
|string
redir
, void
|string
|array
(string
)|multiset
(string
) scope
)
Creates an OAuth object.
client_id
The application ID.
client_secret
The application secret.
redirect_uri
Where the authorization page should redirect back to. This must be a
fully qualified domain name. This can be set/overridden in
get_request_token()
.
scope
Extended permissions to use for this authentication. This can be
set/overridden in get_auth_uri()
.
.Token
get_access_token(void
|string
oauth_verifier
)
Fetches an access token.
string
get_auth_uri(void
|mapping
args
)
.Token
get_request_token(void
|string
|Standards.URI
callback_uri
, void
|bool
force_login
)
Fetches a request token.
callback_uri
Overrides the callback uri in the application settings.
force_login
If 1 forces the user to provide its credentials at the Twitter login page.
inherit .Client : oauth
inherit Web.Auth.OAuth2.Client : oauth2
bool
is_authenticated()
Returns true if authenticated.
protected
string
low_get_access_token(void
|string
oauth_verifier
)
Fetches an access token.
protected
string
normalize_method(string
method
)
Normalizes and verifies the HTTP method to be used in a HTTP call.
mapping
parse_error_xml(string
xml
)
Parses an error xml tree.
A mapping:
|
|
string
request_access_token(string
code
)
Same as get_access_token
except this returns a string to comply
with the OAuth2 authentication process.
void
set_authentication(string
key
, void
|string
secret
)
Set authentication.
this_program
set_from_cookie(string
encoded_value
)
Populate this object with the result from
request_access_token()
.
The object being called.
OAuth client class.
This class is of no use by it self. It's intended to be inherited by classes that uses OAuth authorization.
protected
string
Web.Auth.OAuth.Client.access_token_url
The endpoint to send request for an access token.
protected
Consumer
Web.Auth.OAuth.Client.consumer
The consumer object.
Web.Auth.OAuth.Client Web.Auth.OAuth.Client(
Consumer
consumer
, Token
token
)
Create a new Client
.
This class must be inherited
string
get_access_token_url()
Returns the url for requesting an access token.
Consumer
get_consumer()
Returns the consumer
.
string
get_request_token_url()
Returns the url for requesting a request token.
Token
get_token()
Returns the token
.
string
get_user_auth_url()
Returns the url for authorizing an application.
protected
string
Web.Auth.OAuth.Client.request_token_url
The endpoint to send request for a request token.
void
set_token(Token
token
)
void
set_token(string
token_key
, string
token_secret
)
Set the Token.
key
Either a Token
object or a token key.
secret
The token secret if key
is a token key.
protected
Token
Web.Auth.OAuth.Client.token
The token object.
protected
string
Web.Auth.OAuth.Client.user_auth_url
The enpoint to redirect to when authorize an application.
An OAuth user
string
|Standards.URI
Web.Auth.OAuth.Consumer.callback
Callback url that the remote verifying page will return to.
Web.Auth.OAuth.Consumer Web.Auth.OAuth.Consumer(
string
key
, string
secret
, void
|string
|Standards.URI
callback
)
Creates a new Consumer
object.
callback
NOTE: Has no effect in this implementation.
string
Web.Auth.OAuth.Consumer.key
Consumer key
string
Web.Auth.OAuth.Consumer.secret
Consumer secret
Represents a query string parameter, i.e. key=value.
bool
res = Web.Auth.OAuth.Param()
== other
Comparer method. Checks if other
equals this object.
bool
res = Web.Auth.OAuth.Param()
> other
Checks if this object is greater than other
.
object
res = Web.Auth.OAuth.Param()
[ key
]
Index lookup.
Web.Auth.OAuth.Param Web.Auth.OAuth.Param(
string
name
, mixed
value
)
Creates a new Param
.
string
get_encoded_value()
Returns the value encoded.
string
get_name()
Getter for the name attribute.
string
get_signature()
Returns the name and value for usage in a signature string.
string
get_value()
Getter for the value attribute.
protected
string
Web.Auth.OAuth.Param.name
Param name
void
set_name(string
value
)
Setter for the value attribute.
void
set_value(mixed
_value
)
Setter for the value attribute.
protected
string
Web.Auth.OAuth.Param.value
Param value
Collection of Param
int(0..)
sizeof( Web.Auth.OAuth.Params arg )
Returns the size of the params
array.
mixed
values( Web.Auth.OAuth.Params arg )
Returns the params
.
this_program
res = Web.Auth.OAuth.Params()
+ p
Append p
to the internal array.
The object being called.
this_program
res = Web.Auth.OAuth.Params()
- p
Removes p
from the internal array.
The object being called.
mixed
res = Web.Auth.OAuth.Params()
[ key
]
Index lookup
If no Param
is found returns 0.
If multiple Param
s with name key
is found a new Params
object
with the found params will be retured.
If only one Param
is found that param will be returned.
this_program
add_mapping(mapping
args
)
Append mapping args
as Param
objects.
The object being called.
(
mapping
)Web.Auth.OAuth.Params()
Supports casting to mapping, which will map parameter names to their values.
Web.Auth.OAuth.Params Web.Auth.OAuth.Params(
Param
... params
)
Create a new Params
params
Arbitrary number of Param
objects.
string
get_auth_header()
Returns the params for usage in an authentication header.
mapping
get_encoded_variables()
Returns the parameters as a mapping with encoded values.
get_variables()
string
get_query_string()
Returns the parameters as a query string.
string
get_signature()
Returns the parameters for usage in a signature base string.
mapping
get_variables()
Returns the parameters as a mapping.
private
array
(Param
) Web.Auth.OAuth.Params.params
Storage for Param
s of this object.
Class for building a signed request and querying the remote service.
this_program
add_param(Param
|string
name
, void
|string
value
)
Add a param.
The object being called.
void
add_params(Params
params
)
Add a Params
object.
protected
string
Web.Auth.OAuth.Request.base_string
The signature basestring.
(
string
)Web.Auth.OAuth.Request()
It is possible to case the Request object to a string, which will be the request URL.
Web.Auth.OAuth.Request Web.Auth.OAuth.Request(
string
|Standards.URI
uri
, string
http_method
, void
|Params
params
)
Creates a new Request.
request()
uri
The uri to request.
http_method
The HTTP method to use. Either "GET"
or "POST"
.
Param
get_param(string
name
)
Get param with name name
.
Params
get_params()
Returns the Params
collection.
string
get_signature_base()
Generates a signature base.
protected
string
Web.Auth.OAuth.Request.method
String representation of the HTTP method.
protected
Params
Web.Auth.OAuth.Request.params
The parameters to send.
void
sign_request(int
signature_type
, Consumer
consumer
, Token
token
)
Signs the request.
signature_type
One of the types in Signature
.
Protocols.HTTP.Query
submit(void
|mapping
extra_headers
)
Send the request to the remote endpoint.
protected
Standards.URI
Web.Auth.OAuth.Request.uri
The remote endpoint.
Token class.
(
string
)Web.Auth.OAuth.Token()
Only supports casting to string wich will return a query string of the object.
Web.Auth.OAuth.Token Web.Auth.OAuth.Token(
string
key
, string
secret
)
string
Web.Auth.OAuth.Token.key
string
Web.Auth.OAuth.Token.secret
Module for creating OAuth signatures
constant
int
Web.Auth.OAuth.Signature.HMAC_SHA1
Signature type for hmac sha1 signing.
protected
constantint
Web.Auth.OAuth.Signature.NONE
Signature type for the Base class.
constant
int
Web.Auth.OAuth.Signature.PLAINTEXT
Signature type for plaintext signing.
constant
int
Web.Auth.OAuth.Signature.RSA_SHA1
Signature type for rsa sha1 signing.
constant
Web.Auth.OAuth.Signature.SIGTYPE
Signature types to signature key mapping.
Base
get_object(int
type
)
Returns a signature class for signing with type
.
An error if type
is unknown
type
Either PLAINTEXT
, HMAC_SHA1
or RSA_SHA1
.
Base signature class.
string
build_signature(Request
request
, Consumer
consumer
, Token
token
)
Builds the signature string.
string
get_method()
Returns the method
.
int
get_type()
Returns the type
.
protected
string
Web.Auth.OAuth.Signature.Base.method
String representation of signature type.
protected
int
Web.Auth.OAuth.Signature.Base.type
Signature type.
HMAC_SHA1 signature.
string
build_signature(Request
request
, Consumer
consumer
, Token
token
)
Builds the signature string.
inherit Base : Base
Plaintext signature.
string
build_signature(Request
request
, Consumer
consumer
, Token
token
)
Builds the signature string.
inherit Base : Base
RSA_SHA1 signature. Currently not implemented.
string
build_signature(Request
request
, Consumer
consumer
, Token
token
)
Builds the signature string.
inherit Base : Base
OAuth2 client
A base OAuth2 class can be instantiated either via `()
(Web.Auth.OAuth2(params...)) or via Web.Auth.OAuth2.Base()
.
protected
Base
`()(string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Instantiate a generic OAuth2 Base
class.
client_id
The application ID.
client_secret
The application secret.
redirect_uri
Where the authorization page should redirect back to. This must be a
fully qualified domain name. This can be set/overridden in
Base()->get_auth_uri()
and/or Base()->set_redirect_uri()
.
scope
Extended permissions to use for this authentication. This can be
set/overridden in Base()->get_auth_uri()
.
Generic OAuth2 client class.
protected
constantint
Web.Auth.OAuth2.Base.STATE
Some OAuth2 verifiers need the STATE parameter. If this is not 0 a random string will be generated and the state parameter will be added to the request.
protected
constantstring
Web.Auth.OAuth2.Base.USER_AGENT
User agent string.
protected
constantstring
Web.Auth.OAuth2.Base.VERSION
Version of this implementation.
protected
string
Web.Auth.OAuth2.Base._access_type
Access type of the request.
protected
string
Web.Auth.OAuth2.Base._client_id
The application ID.
protected
string
Web.Auth.OAuth2.Base._client_secret
The application secret.
protected
string
Web.Auth.OAuth2.Base._grant_type
GRANT_TYPE_AUTHORIZATION_CODE
for apps running on a web server
GRANT_TYPE_IMPLICIT
for browser-based or mobile apps
GRANT_TYPE_PASSWORD
for logging in with a username and password
GRANT_TYPE_CLIENT_CREDENTIALS
for application access
protected
string
Web.Auth.OAuth2.Base._redirect_uri
Where the authorization page should redirect to.
protected
string
Web.Auth.OAuth2.Base._response_type
RESPONSE_TYPE_CODE
for apps running on a webserver
RESPONSE_TYPE_TOKEN
for apps browser-based or mobile apps
protected
string
|array
(string
)|multiset
(string
) Web.Auth.OAuth2.Base._scope
The scope of the authorization. Limits the access.
string
Web.Auth.OAuth2.Base.access_token
Getting
Getter for access_token
.
Setting
Getter for access_token
.
(int)Web.Auth.OAuth2.Base()
(float)Web.Auth.OAuth2.Base()
(string)Web.Auth.OAuth2.Base()
(array)Web.Auth.OAuth2.Base()
(mapping)Web.Auth.OAuth2.Base()
(multiset)Web.Auth.OAuth2.Base()
If casted to string the access_token will be returned. If casted to int the expires timestamp will be returned.
Web.Auth.OAuth2.Base Web.Auth.OAuth2.Base(
string
client_id
, string
client_secret
, void
|string
redirect_uri
, void
|string
|array
(string
)|multiset
(string
) scope
)
Creates an OAuth2 object.
client_id
The application ID.
client_secret
The application secret.
redirect_uri
Where the authorization page should redirect back to. This must be a
fully qualified domain name. This can be set/overridden in
get_auth_uri()
and/or set_redirect_uri()
.
scope
Extended permissions to use for this authentication. This can be
set/overridden in get_auth_uri()
.
Calendar.Second
Web.Auth.OAuth2.Base.created
Getter for when the authentication was created
.
Read only
protected
bool
decode_access_token_response(string
r
)
Decode the response from an authentication call. If the response
was ok the internal mapping gettable
will be populated with
the members/variables in r
.
r
The response from do_query()
protected
string
do_query(string
oauth_token_uri
, Web.Auth.Params
p
, void
|function
(bool
, string
:void
) async_cb
)
Send a request to oauth_token_uri
with params p
async_cb
If given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true
or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value()
.
Calendar.Second
Web.Auth.OAuth2.Base.expires
Getter for when the authentication expires
.
Read only
string
get_access_type()
Getter for the access type, if any.
string
get_auth_uri(string
auth_uri
, void
|mapping
args
)
Returns an authorization URI.
auth_uri
The URI to the remote authorization page
args
Additional argument.
string
get_client_id()
Returns the application ID.
string
get_client_secret()
Returns the application secret.
protected
Web.Auth.Params
get_default_params(void
|string
grant_type
)
Returns a set of default parameters.
string
get_grant_type()
Returns the grant_type
of the object.
string
get_redirect_uri()
Returns the redirect uri.
mixed
get_scope()
Returns the scope/scopes set, if any.
string
get_token_from_jwt(string
jwt
, string
token_endpoint
, string
|void
sub
, void
|function
(bool
, string
:void
) async_cb
)
Get an access_token from a JWT. http://jwt.io/
jwt
JSON string.
token_endpoint
URI to the request access_token endpoint.
sub
Email/id of the requesting user.
async_callback
If given the request will be made asynchronously. The
signature is callback(bool, string). If successful the
second argument will be the result encoded with
predef::encode_value()
, which can be stored and later used
to populate an instance via set_from_cookie()
.
protected
string
get_valid_scopes(string
|array
(string
)|multiset
(string
) s
)
Returns a space separated list of all valid scopes in s
.
s
can be a comma or space separated string or an array or
multiset of strings. Each element in s
will be matched
against the valid scopes set in the module inheriting this
class.
bool
has_scope(string
scope
)
Check if scope
exists in this object.
int(1..)
Web.Auth.OAuth2.Base.http_request_timeout
Request timeout in seconds. Only affects async queries.
bool
is_authenticated()
Do we have a valid authentication.
bool
is_expired()
Checks if this authorization has expired.
bool
is_renewable()
Checks if the authorization is renewable. This is true if the
Web.Auth.OAuth2.Base()
object has been populated from
Web.Auth.OAuth2.Base()->set_from_cookie()
, i.e the user has been
authorized but the session has expired.
multiset
list_valid_scopes()
Returns the valid scopes.
string
refresh_access_token(string
oauth_token_uri
, void
|function
(bool
, string
:void
) async_cb
)
Refreshes the access token, if a refresh token exists in the object.
oauth_token_uri
Endpoint of the authentication service.
async_cb
If given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true
or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value()
.
string
Web.Auth.OAuth2.Base.refresh_token
Getter for refresh_token
.
Read only
string
request_access_token(string
oauth_token_uri
, string
code
, void
|function
(bool
, string
:void
) async_cb
)
Requests an access token.
An error if the access token request fails.
oauth_token_uri
An URI received from get_auth_url()
.
code
The code returned from the authorization page via get_auth_url()
.
async_cb
If given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true
or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value()
.
If OK
a Pike encoded mapping (i.e it's a string) is
returned which can be used to populate an Web.Auth.OAuth2
object at a later time.
The mapping looks like
|
|
|
|
|
Depending on the authorization service it might also contain more members.
protected
mapping
Web.Auth.OAuth2.Base.request_headers
Default request headers.
void
set_access_type(string
access_type
)
Set access_type explicilty.
access_type
Like: offline
this_program
set_from_cookie(string
encoded_value
)
Populate this object with the result from request_access_token()
.
An error if the decoding of encoded_value
fails.
encoded_value
The value from a previous call to request_access_token()
or
refresh_access_token()
.
The object being called.
void
set_grant_type(GrantType
type
)
Set the grant type to use.
void
set_redirect_uri(string
uri
)
Setter for the redirect uri.
void
set_scope(string
scope
)
Set scopes.
string
Web.Auth.OAuth2.Base.token_type
Getter for token_type
.
Read only
private
mixed
try_get_error(string
data
)
Try to get an error message from data
. Only successful if
data
is a JSON string and contains the key error.
mapping
Web.Auth.OAuth2.Base.user
Getter for the user
mapping which may or may not be set.
Read only
protected
multiset
(string
) Web.Auth.OAuth2.Base.valid_scopes
A mapping of valid scopes for the API.
Grant types.
constant
Web.Auth.OAuth2.Base.GRANT_TYPE_AUTHORIZATION_CODE
constant
Web.Auth.OAuth2.Base.GRANT_TYPE_CLIENT_CREDENTIALS
constant
Web.Auth.OAuth2.Base.GRANT_TYPE_IMPLICIT
constant
Web.Auth.OAuth2.Base.GRANT_TYPE_JWT
constant
Web.Auth.OAuth2.Base.GRANT_TYPE_PASSWORD
constant
Web.Auth.OAuth2.Base.GRANT_TYPE_REFRESH_TOKEN
Response types.
constant
Web.Auth.OAuth2.Base.RESPONSE_TYPE_CODE
constant
Web.Auth.OAuth2.Base.RESPONSE_TYPE_TOKEN
This class is intended to be extended by classes implementing different OAuth2 services.
protected
constantint
Web.Auth.OAuth2.Client.DEFAULT_SCOPE
Scope to set if none is set.
constant
int
Web.Auth.OAuth2.Client.OAUTH_AUTH_URI
Authorization URI.
constant
int
Web.Auth.OAuth2.Client.OAUTH_TOKEN_URI
Request access token URI.
string
get_auth_uri(void
|mapping
args
)
Returns an authorization URI.
args
Additional argument.
string
get_token_from_jwt(string
jwt
, void
|string
sub
, void
|function
(bool
, string
:void
) async_cb
)
Make an JWT (JSON Web Token) authentication.
inherit Base : Base
string
refresh_access_token(void
|function
(bool
, string
:void
) async_cb
)
Refreshes the access token, if a refresh token exists in the object.
async_cb
If given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true
or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value()
.
string
request_access_token(string
code
, void
|function
(bool
, string
:void
) async_cb
)
Requests an access token.
An error if the access token request fails.
code
The code returned from the authorization page via get_auth_url()
.
async_cb
If given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true
or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value()
.
If OK
a Pike encoded mapping (i.e it's a string) is
returned which can be used to populate an Base
object at a
later time.
The mapping looks like
|
|
|
|
|
Depending on the authorization service it might also contain more members.
Retrieves information about a CGI request from the environment and creates an object with the request information easily formatted.
array
(string
) Web.CGI.Request.client
multiset
(string
) Web.CGI.Request.config
If used with Roxen or Caudium webservers, this field will be populated with "config" information.
mapping
(string
:string
) Web.CGI.Request.cookies
Web.CGI.Request Web.CGI.Request()
creates the request object. To use, create a Request object while running in a CGI environment. Environment variables will be parsed and inserted in the appropriate fields of the resulting object.
string
Web.CGI.Request.data
string
Web.CGI.Request.method
mapping
(string
:int
|string
|array
(string
)) Web.CGI.Request.misc
multiset
(string
) Web.CGI.Request.pragma
multiset
(string
) Web.CGI.Request.prestate
If used with Roxen or Caudium webservers, this field will be populated with "prestate" information.
string
Web.CGI.Request.prot
string
Web.CGI.Request.query
string
Web.CGI.Request.rest_query
array
(string
) Web.CGI.Request.referer
string
Web.CGI.Request.remoteaddr
string
Web.CGI.Request.remotehost
multiset
(string
) Web.CGI.Request.supports
If used with Roxen or Caudium webservers, this field will be populated with "supports" information.
mapping
(string
:array
(string
)) Web.CGI.Request.variables
This module implements a generic web crawler.
Features:
Fully asynchronous operation (Several hundred simultaneous requests)
Supports the /robots.txt exclusion standard
Extensible
URI Queues
Allow/Deny rules
Configurable
Number of concurrent fetchers
Bits per second (bandwidth throttling)
Number of concurrent fetchers per host
Delay between fetches from the same host
Supports HTTP and HTTPS
Web.Crawler.ComplexQueue Web.Crawler.ComplexQueue(
Stats
stats
, Policy
policy
)
inherit Queue : Queue
Stats
Web.Crawler.ComplexQueue.stats
Policy
Web.Crawler.ComplexQueue.policy
Web.Crawler.Crawler Web.Crawler.Crawler(
Queue
_queue
, function
(:void
) _page_cb
, function
(:void
) _error_cb
, function
(:void
) _done_cb
, function
(:void
) _prepare_cb
, string
|array
(string
)|Standards.URI
|array
(Standards.URI
) start_uri
, mixed
... _args
)
_page_cb
function called when a page is retreived. Arguments are: Standards.URI uri, mixed data, mapping headers, mixed ... args. should return an array containing additional links found within data that will be analyzed for insertion into the crawler queue (assuming they are allowed by the allow/deny rulesets.
_error_cb
function called when an error is received from a server. Arguments are: Standards.URI real_uri, int status_code, mapping headers, mixed ... args. Returns void.
_done_cb
function called when crawl is complete. Accepts mixed ... args and returns void.
_prepare_cb
argument called before a uri is retrieved. may be used to alter the request. Argument is Standards.URI uri. Returns array with element 0 of Standards.URI uri, element 1 is a header mapping for the outgoing request.
start_uri
location to start the crawl from.
_args
optional arguments sent as the last argument to the callback functions.
A rule that uses glob expressions
pattern
a glob pattern that the rule will match against.
GlobRule("http://pike.lysator.liu.se/*.xml");
Web.Crawler.GlobRule Web.Crawler.GlobRule(
string
pattern
)
inherit Rule : Rule
string
Web.Crawler.GlobRule.pattern
Memory queue
Web.Crawler.MemoryQueue Web.Crawler.MemoryQueue(
Stats
_stats
, Policy
_policy
, RuleSet
_allow
, RuleSet
_deny
)
int
|Standards.URI
get()
Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling, outstanding requests and other limits. Returns 0 if there are no more URIs to index.
inherit Queue : Queue
void
put(string
|array
(string
)|Standards.URI
|array
(Standards.URI
) uri
)
Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.
Web.Crawler.MySQLQueue Web.Crawler.MySQLQueue(
Stats
_stats
, Policy
_policy
, string
_host
, string
_table
, void
|RuleSet
_allow
, void
|RuleSet
_deny
)
inherit Queue : Queue
The crawler policy object.
int
Web.Crawler.Policy.bandwidth_throttling_floating_window_width
Bandwidth throttling floating window width. Defaults to 30.
int
Web.Crawler.Policy.max_bits_per_second_per_host
Maximum number of bits per second, per host. Defaults to off (0).
int
Web.Crawler.Policy.max_bits_per_second_total
Maximum number of bits per second. Defaults to off (0).
int
Web.Crawler.Policy.max_concurrent_fetchers
Maximum number of fetchers. Defaults to 100.
int
Web.Crawler.Policy.max_concurrent_fetchers_per_host
Maximum concurrent fetchers per host. Defaults to 1.
int
Web.Crawler.Policy.min_delay_per_host
Minimum delay per host. Defaults to 0.
A crawler queue. Does not need to be reentrant safe. The Crawler always runs in just one thread.
int
|Standards.URI
get()
Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling and other limits. Returns 0 if there are no more URIs to index.
void
put(string
|array
(string
)|Standards.URI
|array
(Standards.URI
) uri
)
Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.
A rule that uses Regexp
expressions
Web.Crawler.RegexpRule Web.Crawler.RegexpRule(
string
re
)
re
a string describing the Regexp
expression
inherit Rule : Rule
Abstract rule class.
int
check(string
|Standards.URI
uri
)
A set of rules
void
add_rule(Rule
rule
)
add a rule to the ruleset
void
remove_rule(Rule
rule
)
remove a rule from the ruleset
Statistics.
void
bytes_read_callback(Standards.URI
uri
, int
num_bytes_read
)
This callback is called when data has arrived for a presently crawled URI, but no more often than once a second.
void
close_callback(Standards.URI
uri
)
This callback is called whenever the crawling of a URI is finished or fails.
Web.Crawler.Stats Web.Crawler.Stats(
int
window_width
, int
granularity
)
int
Web.Crawler.Stats.window_width
int
Web.Crawler.Stats.granularity
Represents a RSS (RDF Site Summary) file.
Index
parse_xml(string
|Parser.XML.Tree.Node
n
, void
|string
base
)
Returns an Index
object, populated with the rss information
given in the rss file n
.
Represents an RSS channel.
void
add_item(Item
i
)
Adds the Item
i
to the Channel
.
string
Web.RSS.Channel.title
string
Web.RSS.Channel.link
string
Web.RSS.Channel.description
string
|Standards.URI
Web.RSS.Channel.image
string
|Standards.URI
Web.RSS.Channel.textinput
array
(Item
) Web.RSS.Channel.items
inherit Thing : Thing
void
remove_item(Item
i
)
Removes the Item
i
from the Channel
.
Represents an RSS image resource.
inherit Thing : Thing
string
Web.RSS.Image.title
string
Web.RSS.Image.url
string
Web.RSS.Image.link
Represents the top level of an RSS index.
array
(Channel
) Web.RSS.Index.channels
The RSS channels.
Web.RSS.Index Web.RSS.Index(
.RDF
|void
_rdf
)
array
(Image
) Web.RSS.Index.images
The RSS images.
array
(Item
) Web.RSS.Index.items
The RSS items.
.RDF
Web.RSS.Index.rdf
The underlying RDF representation of the RSS index.
array
(Textinput
) Web.RSS.Index.textinputs
The RSS textinputs.
Represents an RSS item resource.
string
Web.RSS.Item.title
string
Web.RSS.Item.link
string
Web.RSS.Item.description
inherit Thing : Thing
Represents an RSS textinput resource.
string
Web.RSS.Textinput.title
string
Web.RSS.Textinput.description
string
Web.RSS.Textinput.name
string
Web.RSS.Textinput.link
inherit Thing : Thing
The base class for the RSS resources.
Web.RSS.Thing Web.RSS.Thing(
string
about
, mapping
attributes
)
Web.RSS.Thing Web.RSS.Thing(
.RDF.Resource
me
)
Creates an RSS resource.
.RDF.Resource
get_id()
Returns the RDF.Resource
that identifies this RSS resource.
constant
int
Web.Sass.HTTP_IMPORT_NONE
constant
int
Web.Sass.HTTP_IMPORT_GREEDY
constant
int
Web.Sass.HTTP_IMPORT_ANY
Description:
| Default value of |
| Allow imports over HTTP only if the returned content type is text/scss. |
| Anything goes. |
constant
string
Web.Sass.LIBSASS_VERSION
The libsass version, as a string, this module was compiled agains.
constant
int
Web.Sass.STYLE_NESTED
constant
int
Web.Sass.STYLE_EXPANDED
constant
int
Web.Sass.STYLE_COMPACT
constant
int
Web.Sass.STYLE_COMPRESSED
Styling of output. Use as argument to Compiler.set_output_style()
| The default setting. The output will look like:
|
| Fully expanded output:
|
| Somewhat minified output:
|
| Minified output
|
string
libsass_language_version()
Returns the language version of Sass this module was compiled against
string
libsass_version()
Returns the libsass version this module was compiled against
string(8bit)
sass2scss(string(8bit)
data
)
string(8bit)
sass2scss(string(8bit)
data
, int
options
)
Convert Sass syntax (i.e. indented syntax) to SCSS syntax.
data
Sass syntax text to convert to SCSS syntax.
options
This is a bitwise union of compression level (STYLE_NESTED
,
STYLE_EXPANDED
, STYLE_COMPACT
and $[STYLE_COMPRESSED]) and the
SASS2SCSS_* constants SASS2SCSS_KEEP_COMMENT
,
SASS2SCSS_STRIP_COMMENT
and SASS2SCSS_CONVERT_COMMENT
.
It defaults to STYLE_NESTED|SASS2SCSS_KEEP_COMMENT
.
data
converted to SCSS syntax.
string
sass2scss_version()
Returns the sass2scss version this module was compiled against
Low-level Sass/SCSS compiler.
You probably want to use Compiler
instead of this class.
Compiler
string(8bit)
compile_string(string(8bit)
source
)
Compiles the string source
and returns the generated CSS.
If the source
contain @import directives you have to
explicitly set the include path via include_path
.
source
The string to compile
string(8bit)
Web.Sass.Api.include_path
The base path of @imports. Note! This needs to be set when
compile_string()
is used.
bool
Web.Sass.Api.omit_source_map_url
Set whether writing the sourceMappingUrl=# or not.
int(2bit)
Web.Sass.Api.output_style
Determines the level of compression on the generated output.
STYLE_NESTED
, STYLE_EXPANDED
, STYLE_COMPACT
and
STYLE_COMPRESSED
.
int
Web.Sass.Api.precision
Set the precision of fractional numbers. Default is 5.
bool
Web.Sass.Api.sass_syntax
Set whether the code is Sass syntax, i.e. indented syntax or not. Only
necessary when using compile_string()
bool
Web.Sass.Api.source_comments
Emit comments in the generated CSS indicating the corresponding source line. Default is false.
bool
Web.Sass.Api.source_map_embed
Set whether embedding sourceMappingUrl=# as data uri or not.
string(8bit)
Web.Sass.Api.source_map_file
Set the path of the source map file.
string(8bit)
Web.Sass.Api.source_map_root
Set the root path of the source files, relative to where the source.map file is written.
This module is an interface to the Yellow Pages functions. Yp is also known as NIS (Network Information System) and is most commonly used to distribute passwords and similar information within a network.
string
default_domain()
Returns the default yp-domain.
inherit "___Yp" : "___Yp"
mapping
(string
:string
) all(string
map
)
Returns the whole map as a mapping.
map
is the YP-map to search in. This must be the full map name,
you have to use passwd.byname instead of just passwd.
Yp.Domain Yp.Domain(
string
|void
domain
)
void
bind(string
domain
)
If domain
is not specified , the default domain will be used.
(As returned by Yp.default_domain()
).
If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. This timeout is not configurable.
Yp.default_domain()
void
map(string
map
, function
(string
, string
:void
) fun
)
For each entry in map
, call the function specified by fun
.
fun
will get two arguments, the first being the key, and the
second the value.
map
is the YP-map to search in. This must be the full map name.
eg passwd.byname instead of just passwd.
string
match(string
map
, string
key
)
Search for the key key
in the Yp-map map
.
If there is no key
in the map, 0 (zero) will be returned,
otherwise the string matching the key will be returned.
key
must match exactly, no pattern matching of any kind is done.
int
order(string
map
)
Returns the 'order' number for the map map
.
This is usually the number of seconds since Jan 1 1970 (see time()
).
When the map is changed, this number will change as well.
map
is the YP-map to search in. This must be the full map name.
eg passwd.byname instead of just passwd.
string
server(string
map
)
Returns the hostname of the server serving the map map
. map
is the YP-map to search in. This must be the full map name.
eg passwd.byname instead of just passwd.
Network Information Service aka YP map.
array
(string
) indices( Yp.Map arg )
Return the keys of the map.
int
sizeof( Yp.Map arg )
Return the number of entries in this map.
array
(string
) values( Yp.Map arg )
Return the values of the map.
string
match(string
key
)
string
res = Yp.Map()
[ key
]
Search for the key key
. If there is no key
in the map, 0 (zero)
will be returned, otherwise the string matching the key will
be returned.
key
must match exactly, no pattern matching of any kind is done.
mapping
(string
:string
) all()
Returns the whole map as a mapping.
(
mapping
)Yp.Map()
Convert the map to a mapping
Yp.Map Yp.Map(
string
map
, string
|void
domain
)
Create a new YP-map object.
map
is the YP-map to bind to. This may be a nickname, such as
passwd instead of just passwd.byname.
If domain
is not specified, the default domain will be used.
If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. The timeout is not configurable.
void
map(function
(string
, string
:void
) fun
)
Call a function for each entry in the map.
For each entry in the map, call the function fun
.
The function will be called like
void fun(string key, string value)
.
int
order()
Return the order number for this map.
string
server()
Return the server that provides this map.
ZXID is a library that implements SAML 2.0, Liberty ID-WSF 2.0 and XACML 2.0.
This module implements a wrapper for ZXID. The interface is similar to the C one, but using generally accepted Pike syntax.
inherit "___ZXID" : ZXID
string(8bit)
mapping_to_query(mapping
(string(8bit)
:string(8bit)
) map
)
Convert a mapping of query variables to a query string.
int
version()
Return the numeric version of the zxid library.
A set of configuration parameters for a ZXID context.
This is typically overloaded with new definitions for the various callback functions.
ZXID.Configuration ZXID.Configuration(
string
|mapping
(string(8bit)
:string(8bit)
) conf
)
Create a new Configuration
.
conf
ZXID configuration parameters. Either as a configuration string (as per the ZXID book chapter 7 and 10), or as a mapping of parameter settings. These are the most common parameters:
| Path to the directory containing the |
| URL of the SP. |
| The Common Domain URL. |
mapping
(string(8bit)
:mapping
(string(8bit)
:string(8bit)
)) idp_list()
Return a list of known identity providers.
Returns a mapping from IdP EID to display name (if any).
inherit ZXID::Configuration : Configuration
Represents the current session state for a user.
mapping
(string
:mixed
) ZXID.Configuration.Session.auth_info
mixed
authenticate(string(8bit)
uri_path
, string(8bit)
|mapping
(string(8bit)
:string(8bit)
) query
)
Authenticate via SAML given the query-string query
.
| Returns a mapping when interaction with the browser is needed. |
| Returns a string to ask for some specific actions. |
| Returns |
Throws errors on most error conditions.
string(8bit)
authenticate(string(8bit)
uri_path
, string(8bit)
query
)
Authenticate via SAML given the query-string query
.
uri_path
Current URI path (before '?').
query
Query variables (after '?').
Returns JSON-encoded data on success, and various other strings otherwise.
ZXID.Configuration.Session ZXID.Configuration.Session(
string
|void
session_id
)
Create a new or look up an existing session.
mapping
(string
:mixed
) get_auth_info()
inherit Configuration::Session : Session
string(8bit)
ZXID.Configuration.Session.session_id
Session id (if any).
constant
_Ffmpeg.CODEC_ID_NONE
constant
_Ffmpeg.CODEC_ID_AC3
constant
_Ffmpeg.CODEC_ID_ADPCM_IMA_QT
constant
_Ffmpeg.CODEC_ID_ADPCM_IMA_WAV
constant
_Ffmpeg.CODEC_ID_ADPCM_MS
constant
_Ffmpeg.CODEC_ID_H263
constant
_Ffmpeg.CODEC_ID_H263I
constant
_Ffmpeg.CODEC_ID_H263P
constant
_Ffmpeg.CODEC_ID_MJPEG
constant
_Ffmpeg.CODEC_ID_MPEG1VIDEO
constant
_Ffmpeg.CODEC_ID_MPEG4
constant
_Ffmpeg.CODEC_ID_MP2
constant
_Ffmpeg.CODEC_ID_MP3LAME
constant
_Ffmpeg.CODEC_ID_MSMPEG4V1
constant
_Ffmpeg.CODEC_ID_MSMPEG4V2
constant
_Ffmpeg.CODEC_ID_MSMPEG4V3
constant
_Ffmpeg.CODEC_ID_PCM_ALAW
constant
_Ffmpeg.CODEC_ID_PCM_MULAW
constant
_Ffmpeg.CODEC_ID_PCM_S16BE
constant
_Ffmpeg.CODEC_ID_PCM_S16LE
constant
_Ffmpeg.CODEC_ID_PCM_S8
constant
_Ffmpeg.CODEC_ID_PCM_U16BE
constant
_Ffmpeg.CODEC_ID_PCM_U16LE
constant
_Ffmpeg.CODEC_ID_PCM_U8
constant
_Ffmpeg.CODEC_ID_RAWVIDEO
constant
_Ffmpeg.CODEC_ID_RV10
constant
_Ffmpeg.CODEC_ID_SVQ1
constant
_Ffmpeg.CODEC_ID_VORBIS
constant
_Ffmpeg.CODEC_ID_WMV1
constant
_Ffmpeg.CODEC_ID_WMV2
Various audio and video codecs.
The list of supported codecs depends on Ffmpeg library.
constant
_Ffmpeg.CODEC_TYPE_AUDIO
constant
_Ffmpeg.CODEC_TYPE_VIDEO
Type of codec.
Implements support of all codecs from a nice project Ffmpeg. You can find more info about it at http://ffmpeg.sf.net/.
_Ffmpeg.ffmpeg _Ffmpeg.ffmpeg(
int
codec_name
, int
encoder
)
Create decoder or encoder object.
codec_name
Internal number of codec, eg. CODEC_ID_MP2
.
encoder
If true, encoder object will be created, decoder object otherwise.
mapping
|int
decode(string
data
)
Returns a mapping with the new decoded frame and lenght of
data
which was used for decoding.
int
decode(string
data
, function
(:void
) shuffler
)
Decode all data
buffer and pass result to shuffler
.
Returns 1
on success, 0
otherwise.
Shuffler variant isn't implemented, yet.
Usable only in decoder.
create()
mapping
|int
get_codec_info()
Returns mapping with info of used codec.
list_codecs()
mapping
|int
get_codec_status()
Returns a mapping with the actual codec parameters.
set_codec_param()
array
(mapping
) list_codecs()
Gets all supported codecs.
Array of mapping with codec features.
int
set_codec_param(string
name
, mixed
value
)
Sets one codec parameter
name
The name of parameter. One of "sample_rate"
,
"bit_rate"
, "channels"
.
Returns 1 on success, 0 otherwise (parameter not known).
get_codec_params()
Sass is a scripting language that is interpreted into Cascading Style Sheets (CSS). This module is a glue for libsass.
protected
typedefstring(8bit)
_Sass.s8
Shorthand for string(8bit)
Sass/SCSS compiler.
Web.Sass.Compiler compiler = Web.Sass.Compiler(); // Allow for HTTP imports, disallowed by default. compiler->http_import = Web.Sass.HTTP_IMPORT_ANY; // Minify the output and create a source map file. compiler->set_options(([ "output_style" : Web.Sass.STYLE_COMPRESSED, "source_map_file" : "path/to/write/source.map" ])); if (mixed e = catch(compiler->compile_file("input.scss", "output.css"))) { werror("Failed compiling input.scss to output.css\n"); }
bool
_Sass.Compiler.check_file_access
Should file access be tested right away when paths are set or should that be left to Sass to handle? The default value is true.
mapping
(s8
:s8
) compile_file(s8
input_file
)
Compile the file input_file
and return the result
input_file
The SCSS file to compile
A mapping with the generated CSS and source mapping file if such is set to be generated
| The generated CSS |
| The generated source mapping data |
variant
void
compile_file(s8
input_file
, s8
output_file
)
Compile the file input_file
and write the result to output_file
.
If a source mapping file is set to be generated either via
set_options()
or source_map_file
it will be written as per
the value set in the option.
input_file
The SCSS file to compile
output_file
The name of the CSS file to save the result in.
protected
string
|array
(string(8bit)
) handle_sass_import(string(8bit)
path
, void
|string(8bit)
absolute_path
, void
|string(8bit)
relative_path
)
Resolve imports in sass/scss files.
In general this method doesn't need to overloaded. In principle it's only necessary if the Sass files reside in a non-standard filesystem.
If overloaded abs_path
and rel_path
is the absolute and relaive
paths of the file containing the import statement path
.
If the Sass/SCSS files are located in a normal filesystem this method
can return the contents of path
as a string and libsass will
resolve the paths to the imports by itself.
However, if the files are not located in a normal filesystem this
function should return an array of two indices, where the first index
should be the contents of path
and the second the calculated absolute
path of path
.
path
This is the value of `path` in @import 'path'.
absolute_path
This is the absolute path of the file containing the @import statement.
relative_path
The relative path of absolute_path
in relation to the prevoius
absolute_path
| If undefined is returned the import resolution is given back to libsass. |
| The contents of |
| if an array is returned it should contain two indices, where the first
if the contents of |
int(0..2)
_Sass.Compiler.http_import
If a Sass file is importing an external URI this flag determines if
thats allowed at all, or if the content type of the imported file has
to be in http_import_allow_ct
, or if anything goes.
Default is HTTP_IMPORT_NONE
.
HTTP_IMPORT_NONE
, HTTP_IMPORT_GREEDY
and
HTTP_IMPORT_ANY
.
multiset
(s8
) _Sass.Compiler.http_import_allow_ct
List of allowed content types if http_import
is set to
HTTP_IMPORT_GREEDY
. The default is to allow text/scss and
text/sass.
inherit Api : Api
void
set_options(mapping
(s8
:s8
|int
) opts
)
Set options to the SASS compiler.
opts
| Any of the |
| Path to root of incude files. See also |
| File to write source map file to.
See also |
| Turn on/off comments in the output containing info about the source
file - line numbers and such. Default of false. See also
|
| Turn on/off if a source map should be embedded in the output or not.
Default is false. See also |
| Set the root path of the source files, relative to where the
source.map file is written.
See also |
| Omit the #sourceMappingURL or not.
See also |
| Turn on/off Sass syntax, i.e. indented syntax. Only necessary when
using |
| Floating point precision. See also |
Base class for AE (Authenticated Encryption) algorithms.
AE algorithms behave like a combination of a Cipher
and
a HMAC.
Note that no actual AE algorithm is implemented in the base class. They are implemented in classes that inherit this class.
AEAD
State
res = __builtin.Nettle.AE()
()
Calling `() will return a State
object.
int(0..)
digest_size()
Returns the size of a hash digest.
inherit __builtin.Nettle.Cipher : Cipher
This is the context for a single incrementally updated AE cipher.
Most of the functions here are only prototypes, and need to be overrided via inherit.
string(8bit)
digest(int
|void
length
)
Generates a digest, and resets the hashing contents.
length
If the length argument is provided, the digest is truncated to the given length.
The digest.
int(0..)
digest_size()
Returns the size of a hash digest.
inherit Cipher::State : State
Base class for AEAD (Authenticated Encryption with Associated Data) algorithms.
AEAD algorithms behave like a combination of a Cipher
and
a HMAC.
Note that no actual AEAD algorithm is implemented in the base class. They are implemented in classes that inherit this class.
AE
State
res = __builtin.Nettle.AEAD()
()
Calling `() will return a State
object.
inherit __builtin.Nettle.AE : AE
inherit __builtin.Nettle.__Hash : __Hash
This is the context for a single incrementally updated AEAD cipher.
Most of the functions here are only prototypes, and need to be overrided via inherit.
inherit Cipher::State : State
inherit __Hash::State : State
Base class for block cipher algorithms.
Implements some common convenience functions, and prototypes.
It also implements operating modes other than ECB.
Note that no actual cipher algorithm is implemented in the base class. They are implemented in classes that inherit this class.
inherit .Cipher : Cipher
Implementation of Counter Mode (CTR). Works as a wrapper for the cipher algorithm in the parent module.
This cipher mode works like a stream cipher with a block size >= 1. This means that the same key and initialization vector (aka counter) should never be reused, since a simple xor would reveal information about the plain text. It also means that it should never be used without a suiteable Message Authentication Code (MAC).
CBC
, CCM
, GCM
, MAC
inherit .Cipher : Cipher
string(7bit)
name()
Returns the name of the base cipher extended with ".CTR"
.
The state for the embedded algorithm
inherit ::this_program : this_program
Base class for cipher algorithms.
Implements some common convenience functions, and prototypes.
Note that no actual cipher algorithm is implemented
in the base class. They are implemented in classes
that inherit (usually via predef::Nettle.Cipher
) this class.
predef::Nettle.Cipher
, Crypto.Cipher
State
res = __builtin.Nettle.Cipher()
()
Calling `() will return a State
object.
int(0..)
block_size()
The block size of the cipher (1
for stream ciphers).
string
decrypt(string(8bit)
key
, string(8bit)
data
)
Works as a shortcut for obj->set_decrypt_key(key)->crypt(data)
string
encrypt(string(8bit)
key
, string(8bit)
data
)
Works as a shortcut for obj->set_encrypt_key(key)->crypt(data)
int(0..)
key_size()
The recommended key size for the cipher.
string(7bit)
name()
Returns a human readable name for the algorithm.
This is the context for a single incrementally updated cipher.
Most of the functions here are only prototypes, and need to be overrided via inherit.
int(0..)
block_size()
The block size of the cipher (1
for stream ciphers).
Defaults to just returning global::block_size()
.
string(8bit)
crypt(string(8bit)
data
)
Encrypts or decrypts data, using the current key. Neither the
input nor output data is automatically memory scrubbed,
unless String.secure
has been called on them.
data
For block ciphers, data must be an integral number of blocks.
The encrypted or decrypted data.
int(0..)
key_size()
The actual key size for this cipher.
Defaults to just returning global::key_size()
.
string(8bit)
make_key()
Generate a key by calling Crypto.Random.random_string
and
initialize the object for encryption with that key.
The generated key.
set_encrypt_key
string(7bit)
name()
Returns a human readable name for the algorithm.
Defaults to just returning global::name()
.
this_program
set_decrypt_key(string(8bit)
key
, void
|int
force
)
Initializes the object for decryption.
set_encrypt_key
, crypt
this_program
set_encrypt_key(string(8bit)
key
, void
|int
force
)
Initializes the object for encryption.
set_decrypt_key
, crypt
Base class for Elliptic Curve Definitions.
Crypto.ECC.Curve
, Nettle.ECC_Curve
Base class for a point on an elliptic curve.
__builtin.Nettle.ECC_Curve.Point __builtin.Nettle.ECC_Curve.Point(
Gmp.mpz
|int
x
, Gmp.mpz
|int
y
)
__builtin.Nettle.ECC_Curve.Point __builtin.Nettle.ECC_Curve.Point(
Stdio.Buffer
|string(7bit)
data
)
Initialize to the selected point on the curve.
Throws errors if the point isn't on the curve.
string
encode()
Serialize the Point
.
The default implementation serializes according to ANSI x9.62 encoding #4 (uncompressed point format).
Base class for hash algorithms.
Implements common meta functions, such as key expansion algoritms and convenience functions.
Note that no actual hash algorithm is implemented in the base class. They are implemented in classes that inherit this class.
string(8bit)
P_hash(string(8bit)
password
, string(8bit)
salt
, int
rounds
, int
bytes
)
This is the Password-Based Key Derivation Function used in TLS.
password
The prf secret.
salt
The prf seed.
rounds
Ignored.
bytes
The number of bytes to generate.
State
res = __builtin.Nettle.Hash()
()
Calling `() will return a State
object.
string(7bit)
crypt_hash(string(8bit)
password
, string(8bit)
salt
, int
rounds
)
Password hashing function in crypt_md5()
-style.
Implements the algorithm described in http://www.akkadia.org/drepper/SHA-crypt.txt.
This is the algorithm used by crypt(2) in methods $5$ (SHA256) and $6$ (SHA512).
crypt_md5()
string(8bit)
hash(string(8bit)
data
)
string(8bit)
hash(Stdio.File
file
, void
|int
bytes
)
Shortcut for hashing some data.
data
String to hash.
file
Stdio.File
object to read some data to hash from.
bytes
The number of bytes of the file object file
that should be
hashed. Negative numbers are ignored and the whole file is
hashed.
Works as a (possibly faster) shortcut for
State(data)->digest()
, where State
is
the hash state class corresponding to this Hash
.
Stdio.File
, State()->update()
and State()->digest()
.
inherit .__Hash : __Hash
string(8bit)
openssl_pbkdf(string(8bit)
password
, string(8bit)
salt
, int
rounds
, int
bytes
)
Password Based Key Derivation Function from OpenSSL.
This when used with Crypto.MD5
and a single round
is the function used to derive the key to encrypt
Standards.PEM
body data.
Derived from OpenSSL. Is there any proper specification?
It seems to be related to PBKDF1 from RFC2898.
pbkdf1()
, pbkdf2()
, crypt_password()
string(8bit)
pbkdf1(string(8bit)
password
, string(8bit)
salt
, int
rounds
, int
bytes
)
Password Based Key Derivation Function #1 from RFC 2898. This method is compatible with the one from PKCS#5 v1.5.
password
salt
Password and salt for the keygenerator.
rounds
The number of iterations to rehash the input.
bytes
The number of bytes of output. Note that this has an upper limit of the size of a single digest.
Returns the derived key.
RFC 2898 does not recommend this function for anything else than compatibility with existing applications, due to the limits in the length of the generated keys.
pbkdf2()
, openssl_pbkdf()
, crypt_password()
string(8bit)
pbkdf2(string(8bit)
password
, string(8bit)
salt
, int
rounds
, int
bytes
)
Password Based Key Derivation Function #2 from RFC 2898, PKCS#5 v2.0.
password
salt
Password and salt for the keygenerator.
rounds
The number of iterations to rehash the input.
bytes
The number of bytes of output.
Returns the derived key.
pbkdf1()
, openssl_pbkdf()
, crypt_password()
string(8bit)
pkcs_digest(object
|string(8bit)
s
)
Make a PKCS-1 digest info block with the message s
.
Standards.PKCS.build_digestinfo()
SCRAM, defined by RFC 5802.
This implements both the client- and the serverside. You normally run either the server or the client, but if you would run both (use a separate client and a separate server object!), the sequence would be:
client_1
-> server_1
-> server_2
-> client_2
->
server_3
-> client_3
If you are a client, you must use the client_*
methods; if you are
a server, you must use the server_*
methods.
You cannot mix both client and server methods in a single object.
This implementation does not pretend to support the full protocol. Most notably optional extension arguments are not supported (yet).
client_1
, server_1
string(7bit)
client_1(void
|string
username
)
Client-side step 1 in the SCRAM handshake.
username
The username to feed to the server. Some servers already received the username through an alternate channel (usually during the hash-function selection handshake), in which case it should be omitted here.
The client-first request to send to the server.
client_2
string(7bit)
client_2(string(8bit)
line
, string
pass
)
Client-side step 2 in the SCRAM handshake.
line
The received server-first challenge from the server.
pass
The password to feed to the server.
The client-final response to send to the server. If the response is null, the server sent something unacceptable or unparseable.
client_3
bool
client_3(string(8bit)
line
)
Final client-side step in the SCRAM handshake. If we get this far, the server has already verified that we supplied the correct credentials. If this step fails, it means the server does not have our credentials at all and is an imposter.
line
The received server-final verification response.
True if the server is valid, false if the server is invalid.
string
server_1(string(8bit)
line
)
Server-side step 1 in the SCRAM handshake.
line
The received client-first request from the client.
The username specified by the client. Returns null if the response could not be parsed.
server_2
string(7bit)
server_2(string(8bit)
salt
, int
iters
)
Server-side step 2 in the SCRAM handshake.
salt
The salt corresponding to the username that has been specified earlier.
iters
The number of iterations the hashing algorithm should perform to compute the authentication hash.
The server-first challenge to send to the client.
server_3
string(7bit)
server_3(string(8bit)
line
, string(8bit)
salted_password
)
Final server-side step in the SCRAM handshake.
line
The received client-final challenge and response from the client.
salted_password
The salted (using the salt provided earlier) password belonging to the specified username.
The server-final response to send to the client. If the response is null, the client did not supply the correct credentials or the response was unparseable.
HMAC (Hashing for Message Authenticity Control) for the hash algorithm.
RFC 2104.
Crypto.HMAC
State
res = __builtin.Nettle.Hash()
()
Returns a new State
object initialized with a password
.
protected
constantstring
__builtin.Nettle.Hash.HMAC.hmac_jwa_id
JWS algorithm id (if any) for the HMAC sub-module. Overloaded by the actual implementations.
inherit .MAC : MAC
int(0..0)
iv_size()
HMAC has no modifiable iv.
string(7bit)
jwa()
JWS algorithm identifier (if any, otherwise 0
).
int(0..)
key_size()
Returns the block size of the encapsulated hash.
Other key sizes are allowed, and will be expanded/compressed to this size.
The HMAC hash state.
string(8bit)
res = __builtin.Nettle.Hash.HMAC.State()
()
Hashes the text
according to the HMAC algorithm and returns
the hash value.
This works as a combined update()
and digest()
.
__builtin.Nettle.Hash.HMAC.State __builtin.Nettle.Hash.HMAC.State(
string(8bit)
passwd
, void
|int
b
)
passwd
The secret password (K).
string(8bit)
digest_info(string(8bit)
text
)
Hashes the text
according to the HMAC algorithm and returns
the hash value as a PKCS-1 digestinfo block.
inherit ::this_program : this_program
mapping
(string(7bit)
:string(7bit)
) jwk(bool
|void
private_key
)
Generate a JWK-style mapping of the object.
private_key
Ignored.
Returns a JWK-style mapping on success, and 0
(zero)
on failure.
create()
, Web.encode_jwk()
, RFC 7517 section 4, RFC 7518 section 6.4
this_program
set_iv(string(8bit)
iv
)
HMAC does not have a modifiable iv.
Base class for Message Authentication Codes (MAC)s.
These are hashes that have been extended with a secret key.
inherit .__Hash : __Hash
int(0..)
iv_size()
Returns the size of the iv/nonce (if any).
Some MACs like eg Crypto.SHA1.HMAC
have fixed ivs,
in which case this function will return 0
.
string(7bit)
jwa()
JWS algorithm identifier (if any, otherwise 0
).
int(0..)
key_size()
Returns the recomended size of the key.
protected
constantstring
__builtin.Nettle.MAC.mac_jwa_id
JWS algorithm id (if any). Overloaded by the actual implementations.
Never access this value directly. Use jwa()
.
jwa()
The state for the MAC.
__builtin.Nettle.MAC.State __builtin.Nettle.MAC.State(
string
key
)
key
The secret key for the hash.
inherit ::this_program : this_program
int(0..)
iv_size()
Returns the size of the iv/nonce (if any).
Some MACs like eg Crypto.SHA1.HMAC
have fixed ivs,
in which case this function will return 0
.
array
(mapping
(string(7bit)
:string(7bit)
|int
)|string(8bit)
) jose_decode(string(7bit)
jws
)
Verify and decode a JOSE JWS MAC signed value.
jws
A JSON Web Signature as returned by jose_sign()
.
Returns 0
(zero) on failure, and an array
Array | |
| The JOSE header. |
| The signed message. |
on success.
jose_sign()
, RFC 7515 section 3.5
string(7bit)
jose_sign(string(8bit)
message
, mapping
(string(7bit)
:string(7bit)
|int
)|void
headers
)
Signs the message
with a JOSE JWS MAC signature.
message
Message to sign.
headers
JOSE headers to use. Typically a mapping with a single element
"typ"
.
Returns the signature on success, and 0
(zero)
on failure (typically that JOSE doesn't support this MAC).
jose_decode()
, RFC 7515
int(0..)
key_size()
Returns the recomended size of the key.
Base class for cryptographic signature algorithms.
Typical classes implementing this API are Crypto.RSA
, Crypto.DSA
and
Crypto.ECC.Curve.ECDSA
.
bool
equal(__builtin.Nettle.Sign from, mixed
x
)
Check whether two objects are equivalent.
This includes checking both the public and private keys.
public_key_equal()
array
(mapping
(string(7bit)
:string(7bit)
|int
)|string(8bit)
) jose_decode(string(7bit)
jws
)
Verify and decode a JOSE JWS signed value.
jws
A JSON Web Signature as returned by jose_sign()
.
Returns 0
(zero) on failure, and an array
Array | |
| The JOSE header. |
| The signed message. |
The default implementation returns 0
for all parameters,
and can thus serve as a fallback for signature algorithms that
don't support or aren't supported by JWS (eg Crypto.DSA
).
jose_sign()
, pkcs_verify()
, RFC 7515
string(7bit)
jose_sign(string(8bit)
message
, mapping
(string(7bit)
:string(7bit)
|int
)|void
headers
, .Hash
|void
h
)
Signs the message
with a JOSE JWS signature using hash
algorithm h
and JOSE headers headers
.
message
Message to sign.
headers
JOSE headers to use. Typically a mapping with a single element
"typ"
.
h
Hash algorithm to use. Valid hashes depend on the signature algorithm. The default value depends on the signature algorithm.
Returns the signature on success, and 0
(zero)
on failure (typically that either the hash algorithm
is invalid for this signature algorithm),
The default implementation returns 0
for all parameters,
and can thus serve as a fallback for signature algorithms that
don't support or aren't supported by JWS (eg Crypto.DSA
).
jose_decode()
, pkcs_sign()
, RFC 7515
mapping
(string(7bit)
:string(7bit)
) jwk(bool
|void
private_key
)
Generate a JOSE JWK mapping representation of the object.
private_key
If true, include private fields in the result.
Returns a mapping as per RFC 7517 section 4 on success,
and 0
(zero) on failure (typically that
the object isn't initialized properly, or that
it isn't supported by JWK).
Web.encode_jwk()
, Web.decode_jwk()
, RFC 7517 section 4
int(0..)
key_size()
Returns the number of bits in the private key.
string(7bit)
name()
Returns the printable name of the signing algorithm.
Sequence
pkcs_algorithm_identifier()
Returns the PKCS-1 AlgorithmIdentifier.
Sequence
pkcs_public_key()
Creates a SubjectPublicKeyInfo ASN.1 sequence for the object. See RFC 5280 section 4.1.2.7.
string(8bit)
pkcs_sign(string(8bit)
message
, .Hash
h
)
Signs the message
with a PKCS-1 signature using hash algorithm
h
.
Sequence
pkcs_signature_algorithm_id(.Hash
hash
)
Returns the PKCS-1 algorithm identifier for the signing algorithm with the provided hash algorithm.
bool
pkcs_verify(string(8bit)
message
, .Hash
h
, string(8bit)
sign
)
Verify PKCS-1 signature sign
of message message
using hash
algorithm h
.
bool
public_key_equal(this_program
other
)
Check whether the public key is the same in two objects.
This function differs from _equal()
in that only the
public key is regarded, and that it only needs to regard
objects implementing Crypto.Sign
.
_equal()
Base class for hash algorithms.
Note that no actual hash algorithm is implemented in the base class. They are implemented in classes that inherit this class.
int(1..)
block_size()
Returns the internal block size of the hash algorithm.
int(0..)
digest_size()
Returns the size of a hash digests.
string
name()
Returns a human readable name for the algorithm.
This is the context for a single incrementally updated hash.
Most of the functions here are only prototypes, and need to be overrided via inherit.
int(1..)
block_size()
Returns the internal block size of the hash algorithm.
__builtin.Nettle.__Hash.State __builtin.Nettle.__Hash.State(
string(8bit)
|void
data
)
Create the new context, and optionally add some initial data to hash.
The default implementation calls update()
with data
if any,
so there's usually no reason to override this function, since
overriding update()
should be sufficient.
string(8bit)
digest(int
|void
length
)
Generates a digests, and resets the hashing contents.
length
If the length argument is provided, the digest is truncated to the given length.
The digest.
int(0..)
digest_size()
Returns the size of a hash digests.
this_program
init(string(8bit)
|void
data
)
Reset the context, and optionally add some initial data to the hash.
string
name()
Returns a human readable name for the algorithm.
this_program
update(string(8bit)
data
)
Add some more data to hash.
array
(array
(string
|int
)) _dump_obj_table()
string
_low_program_name(program
prog
)
string
discdate(int
time
)
string
fd_info(int
fd
)
array
(mapping
(string
:int
)|int
) parse_accessed_database(string
database
)
string
parse_html(string
html
, mapping
(string
:function
(string
, mapping
(string
:string
), mixed
... :string
|array
)) tag_callbacks
, mapping
(string
:function
(string
, mapping
(string
:string
), string
, mixed
... :string
|array
)) container_callbacks
, mixed
... extras
)
string
parse_html_lines(string
html
, mapping
(string
:function
(string
, mapping
(string
:string
), int
, mixed
... :string
|array
)) tag_callbacks
, mapping
(string
:function
(string
, mapping
(string
:string
), string
, int
, mixed
... :string
|array
)) container_callbacks
, mixed
... extras
)
void
set_end_quote(int
quote
)
void
set_start_quote(int
quote
)
string
stardate(int
time
, int
precision
)