5 Functions

Procedure: access filename mode ⇒ %return

A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.

On Windows, the file protection mechanism is not at all POSIX-like, and the underlying function in the C library only checks the FAT-style READONLY attribute, and does not look at the ACL of a file at all. This function is this in practise almost useless on Windows. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.

See your C library manual for more details about access().

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode

Passed: a 32-bit integer.

as in access()

%return

Returned: a 32-bit integer.

zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.

Procedure: aligned-alloc n-blocks n-block-bytes alignment ⇒ %return

This function is similar to malloc, allocating (n-blocks * n-block-bytes) bytes, but care is taken to align the allocated memory to with the given alignment value. Additionally, it will detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Aligned memory allocations returned by this function can only be freed using aligned-free-sized or aligned-free.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

alignment

Passed: an unsigned 64-bit integer.

the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)

%return

Returned: a foreign pointer, or #f.

the allocated memory

Procedure: aligned-alloc0 n-blocks n-block-bytes alignment ⇒ %return

This function is similar to aligned-alloc, but it will also clear the allocated memory before returning it.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

alignment

Passed: an unsigned 64-bit integer.

the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)

%return

Returned: a foreign pointer, or #f.

the allocated, cleared memory

Procedure: aligned-free [mem]

Frees the memory allocated by aligned-alloc.

mem

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the memory to deallocate

Procedure: aligned-free-sized mem alignment size

Frees the memory pointed to by mem, assuming it is has the given size and alignment.

If mem is #f this is a no-op (and size is ignored).

It is an error if size doesn’t match the size, or alignment doesn’t match the alignment, passed when mem was allocated. size and alignment are passed to this function to allow optimizations in the allocator. If you don’t know either of them, use aligned-free instead.

mem

Passed: a foreign pointer, or a bytevector, or #f.

the memory to free

alignment

Passed: an unsigned 64-bit integer.

alignment of mem

size

Passed: an unsigned 64-bit integer.

size of mem, in bytes

Procedure: ascii-digit-value c ⇒ %return

Determines the numeric value of a character as a decimal digit. If the character is not a decimal digit according to GLib.ascii_isdigit, -1 is returned.

Differs from unichar-digit-value because it takes a char, so there’s no worry about sign extension if characters are signed.

c

Passed: an 8-bit integer, or a character.

an ASCII character

%return

Returned: a 32-bit integer.

the numerical value of c if it is a decimal digit, -1 otherwise

Procedure: ascii-dtostr buffer buf-len d ⇒ %return

Converts a gdouble to a string, using the ’.’ as decimal point.

This function generates enough precision that converting the string back using ascii-strtod gives the same machine-number (on machines with IEEE compatible 64bit doubles). It is guaranteed that the size of the resulting string will never be larger than GLib.ASCII_DTOSTR_BUF_SIZE bytes, including the terminating nul character, which is always added.

buffer

Passed: a string.

a buffer to place the resulting string in

buf-len

Passed: a 32-bit integer.

the length of the buffer

d

Passed: a real number.

the value to convert

%return

Returned: a string.

the pointer to the buffer with the converted string

Procedure: ascii-formatd buffer buf-len format d ⇒ %return

Converts a gdouble to a string, using the ’.’ as decimal point. To format the number you pass in a printf()-style format string. Allowed conversion specifiers are ’e’, ’E’, ’f’, ’F’, ’g’ and ’G’.

The format must just be a single format specifier starting with %, expecting a gdouble argument.

The returned buffer is guaranteed to be nul-terminated.

If you just want to want to serialize the value into a string, use ascii-dtostr.

buffer

Passed: a string.

a buffer to place the resulting string in

buf-len

Passed: a 32-bit integer.

the length of the buffer

format

Passed: a string.

the printf()-style format to use for the code to use for converting

d

Passed: a real number.

the value to convert

%return

Returned: a string.

the pointer to the buffer with the converted string

Procedure: ascii-strcasecmp s1 s2 ⇒ %return

Compare two strings, ignoring the case of ASCII characters.

Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII bytes as if they are not letters.

This function should be used only on strings that are known to be in encodings where the bytes corresponding to ASCII letters always represent themselves. This includes UTF-8 and the ISO-8859-* charsets, but not for instance double-byte encodings like the Windows Codepage 932, where the trailing bytes of double-byte characters include all ASCII letters. If you compare two CP932 strings using this function, you will get false matches.

Both s1 and s2 must be non-NULL.

s1

Passed: a string.

string to compare with s2

s2

Passed: a string.

string to compare with s1

%return

Returned: a 32-bit integer.

0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2

Procedure: ascii-strdown str len ⇒ %return

Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly match ascii-tolower.

str

Passed: a string.

a string

len

Passed: a 64-bit integer.

length of str in bytes, or -1 if str is nul-terminated

%return

Returned: a string.

a newly-allocated string, with all the upper case characters in str converted to lower case. (Note that this is unlike the old GLib.strdown, which modified the string in place.)

Procedure: ascii-string-to-signed str base min max ⇒ %return out-num

A convenience function for converting a string to a signed number.

This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in out-num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input.

base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with "0x" or "0X". Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

Parsing failures result in an error with the G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be GLib.NumberParserError.INVALID. If the parsed number is out of bounds - GLib.NumberParserError.OUT_OF_BOUNDS.

See ascii-strtoll if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

str

Passed: a string.

a string to convert

base

Passed: an unsigned 32-bit integer.

base of a parsed number

min

Passed: a 64-bit integer.

a lower bound (inclusive)

max

Passed: a 64-bit integer.

an upper bound (inclusive)

%return

Returned: a boolean.

true if str was a number, false otherwise

out-num

Returned: a 64-bit integer.

a return location for a number

Procedure: ascii-string-to-unsigned str base min max ⇒ %return out-num

A convenience function for converting a string to an unsigned number.

This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in out-num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input. A string with a leading sign (- or +) is not a valid input for the unsigned parser.

base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with "0x" or "0X". Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

Parsing failures result in an error with the G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be GLib.NumberParserError.INVALID. If the parsed number is out of bounds - GLib.NumberParserError.OUT_OF_BOUNDS.

See ascii-strtoull if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

str

Passed: a string.

a string

base

Passed: an unsigned 32-bit integer.

base of a parsed number

min

Passed: an unsigned 64-bit integer.

a lower bound (inclusive)

max

Passed: an unsigned 64-bit integer.

an upper bound (inclusive)

%return

Returned: a boolean.

true if str was a number, false otherwise

out-num

Returned: an unsigned 64-bit integer.

a return location for a number

Procedure: ascii-strncasecmp s1 s2 n ⇒ %return

Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string. If either string is less than n bytes long, comparison will stop at the first nul byte encountered.

Unlike the BSD strncasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII characters as if they are not letters.

The same warning as in ascii-strcasecmp applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

s1

Passed: a string.

string to compare with s2

s2

Passed: a string.

string to compare with s1

n

Passed: an unsigned 64-bit integer.

number of characters to compare

%return

Returned: a 32-bit integer.

0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2

Procedure: ascii-strtod nptr ⇒ %return endptr

Converts a string to a floating point value.

This function behaves like the standard strtod() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe. A limitation of the implementation is that this function will still accept localized versions of infinities and NANs.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtod() function.

To convert from a gdouble to a string in a locale-insensitive way, use ascii-dtostr.

If the correct value would cause overflow, plus or minus HUGE_VAL is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

This function resets errno before calling strtod() so that you can reliably detect overflow and underflow.

nptr

Passed: a string.

the string to convert to a numeric value

%return

Returned: a real number.

the converted value

endptr

Returned: a string.

if non-NULL, it returns the character after the last character used in the conversion

Procedure: ascii-strtoll nptr base ⇒ %return endptr

Converts a string to a gint64 value.

This function behaves like the standard strtoll() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoll() function.

If the correct value would cause overflow, GLib.MAXINT64 or GLib.MININT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

nptr

Passed: a string.

the string to convert to a numeric value

base

Passed: an unsigned 32-bit integer.

to be used for the conversion, 2..36 or 0

%return

Returned: a 64-bit integer.

the converted value, or zero on error

endptr

Returned: a string.

if non-NULL, it returns the character after the last character used in the conversion

Procedure: ascii-strtoull nptr base ⇒ %return endptr

Converts a string to a guint64 value.

This function behaves like the standard strtoull() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

Note that input with a leading minus sign (-) is accepted, and will return the negation of the parsed number, unless that would overflow a guint64. Critically, this means you cannot assume that a short fixed length input will result in a low return value, as the input could have a leading -.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoull() function.

If the correct value would cause overflow, GLib.MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

nptr

Passed: a string.

the string to convert to a numeric value

base

Passed: an unsigned 32-bit integer.

to be used for the conversion, 2..36 or 0

%return

Returned: an unsigned 64-bit integer.

the converted value, or zero on error

endptr

Returned: a string.

if non-NULL, it returns the character after the last character used in the conversion

Procedure: ascii-strup str len ⇒ %return

Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly match ascii-toupper.

str

Passed: a string.

a string

len

Passed: a 64-bit integer.

length of str in bytes, or -1 if str is nul-terminated

%return

Returned: a string.

a newly-allocated string, with all the lower case characters in str converted to upper case. (Note that this is unlike the old GLib.strup, which modified the string in place.)

Procedure: ascii-tolower c ⇒ %return

Convert a character to ASCII lower case. If the character is not an ASCII upper case letter, it is returned unchanged.

Unlike the standard C library tolower() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are lower case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don’t call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c

Passed: an 8-bit integer, or a character.

any character

%return

Returned: an 8-bit integer.

the result of the conversion

Procedure: ascii-toupper c ⇒ %return

Convert a character to ASCII upper case. If the character is not an ASCII lower case letter, it is returned unchanged.

Unlike the standard C library toupper() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are upper case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don’t call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c

Passed: an 8-bit integer, or a character.

any character

%return

Returned: an 8-bit integer.

the result of the conversion

Procedure: ascii-xdigit-value c ⇒ %return

Determines the numeric value of a character as a hexadecimal digit. If the character is not a hex digit according to GLib.ascii_isxdigit, -1 is returned.

Differs from unichar-xdigit-value because it takes a char, so there’s no worry about sign extension if characters are signed.

Differs from unichar-xdigit-value because it takes a char, so there’s no worry about sign extension if characters are signed.

c

Passed: an 8-bit integer, or a character.

an ASCII character

%return

Returned: a 32-bit integer.

the numerical value of c if it is a hex digit, -1 otherwise

Procedure: assert-warning log-domain file line pretty-function expression
log-domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

pretty-function

Passed: a string.

expression

Passed: a string.

Procedure: assertion-message domain file line func message
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

message

Passed: a string.

Procedure: assertion-message-cmpint domain file line func expr arg1 cmp arg2 numtype
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

expr

Passed: a string.

arg1

Passed: an unsigned 64-bit integer.

cmp

Passed: a string.

arg2

Passed: an unsigned 64-bit integer.

numtype

Passed: an 8-bit integer, or a character.

Procedure: assertion-message-cmpstr domain file line func expr arg1 cmp arg2
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

expr

Passed: a string.

arg1

Passed: a string.

cmp

Passed: a string.

arg2

Passed: a string.

Procedure: assertion-message-cmpstrv domain file line func expr arg1 arg2 first-wrong-idx
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

expr

Passed: a string.

arg1

Passed: a string.

arg2

Passed: a string.

first-wrong-idx

Passed: an unsigned 64-bit integer.

Procedure: assertion-message-error domain file line func expr error error-domain error-code
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

expr

Passed: a string.

error

Passed: a <GError>.

error-domain

Passed: an unsigned 32-bit integer.

error-code

Passed: a 32-bit integer.

Procedure: atomic-int-add atomic val ⇒ %return

Atomically adds val to the value of atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

Before version 2.30, this function did not return a value (but g_atomic_int_exchange_and_add() did, and had the same meaning).

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

val

Passed: a 32-bit integer.

the value to add

%return

Returned: a 32-bit integer.

the value of atomic before the add, signed

Procedure: atomic-int-and atomic val ⇒ %return

Performs an atomic bitwise ’and’ of the value of atomic and val, storing the result back in atomic.

This call acts as a full compiler and hardware memory barrier.

Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

val

Passed: an unsigned 32-bit integer.

the value to ’and’

%return

Returned: an unsigned 32-bit integer.

the value of atomic before the operation, unsigned

Procedure: atomic-int-compare-and-exchange-full atomic oldval newval ⇒ %return preval

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs. In any case the value of atomic before this operation is stored in preval.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

See also atomic-int-compare-and-exchange?

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

oldval

Passed: a 32-bit integer.

the value to compare with

newval

Passed: a 32-bit integer.

the value to conditionally replace with

%return

Returned: a boolean.

#t if the exchange took place

preval

Returned: a 32-bit integer.

the contents of atomic before this operation

Procedure: atomic-int-compare-and-exchange? atomic oldval newval ⇒ %return

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

oldval

Passed: a 32-bit integer.

the value to compare with

newval

Passed: a 32-bit integer.

the value to conditionally replace with

%return

Returned: a boolean.

#t if the exchange took place

Procedure: atomic-int-dec-and-test? [atomic] ⇒ %return

Decrements the value of atomic by 1.

Think of this operation as an atomic version of { *atomic -= 1; return (*atomic == 0); }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

%return

Returned: a boolean.

#t if the resultant value is zero

Procedure: atomic-int-exchange atomic newval ⇒ %return

Sets the atomic to newval and returns the old value from atomic.

This exchange is done atomically.

Think of this operation as an atomic version of { tmp = *atomic; *atomic = val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

newval

Passed: a 32-bit integer.

the value to replace with

%return

Returned: a 32-bit integer.

the value of atomic before the exchange, signed

Procedure: atomic-int-get [atomic] ⇒ %return

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

%return

Returned: a 32-bit integer.

the value of the integer

Procedure: atomic-int-inc [atomic]

Increments the value of atomic by 1.

Think of this operation as an atomic version of { *atomic += 1; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

Procedure: atomic-int-or atomic val ⇒ %return

Performs an atomic bitwise ’or’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

val

Passed: an unsigned 32-bit integer.

the value to ’or’

%return

Returned: an unsigned 32-bit integer.

the value of atomic before the operation, unsigned

Procedure: atomic-int-set atomic newval

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

newval

Passed: a 32-bit integer.

a new value to store

Procedure: atomic-int-xor atomic val ⇒ %return

Performs an atomic bitwise ’xor’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to a gint or guint

val

Passed: an unsigned 32-bit integer.

the value to ’xor’

%return

Returned: an unsigned 32-bit integer.

the value of atomic before the operation, unsigned

Procedure: atomic-pointer-add atomic val ⇒ %return

Atomically adds val to the value of atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from gssize to gintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

val

Passed: a 64-bit integer.

the value to add

%return

Returned: a 64-bit integer.

the value of atomic before the add, signed

Procedure: atomic-pointer-and atomic val ⇒ %return

Performs an atomic bitwise ’and’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from gsize to guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

val

Passed: an unsigned 64-bit integer.

the value to ’and’

%return

Returned: an unsigned 64-bit integer.

the value of atomic before the operation, unsigned

Procedure: atomic-pointer-compare-and-exchange-full atomic [oldval] [newval] ⇒ %return preval

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs. In any case the value of atomic before this operation is stored in preval.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

See also atomic-pointer-compare-and-exchange?

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

oldval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to compare with

newval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to conditionally replace with

%return

Returned: a boolean.

#t if the exchange took place

preval

Returned: a foreign pointer.

the contents of atomic before this operation

Procedure: atomic-pointer-compare-and-exchange? atomic [oldval] [newval] ⇒ %return

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

oldval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to compare with

newval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to conditionally replace with

%return

Returned: a boolean.

#t if the exchange took place

Procedure: atomic-pointer-exchange [atomic] [newval] ⇒ %return

Sets the atomic to newval and returns the old value from atomic.

This exchange is done atomically.

Think of this operation as an atomic version of { tmp = *atomic; *atomic = val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

atomic

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a pointer to a gpointer-sized value

newval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to replace with

%return

Returned: a foreign pointer, or #f.

the value of atomic before the exchange

Procedure: atomic-pointer-get atomic ⇒ %return

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

%return

Returned: a foreign pointer, or #f.

the value of the pointer

Procedure: atomic-pointer-or atomic val ⇒ %return

Performs an atomic bitwise ’or’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from gsize to guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

val

Passed: an unsigned 64-bit integer.

the value to ’or’

%return

Returned: an unsigned 64-bit integer.

the value of atomic before the operation, unsigned

Procedure: atomic-pointer-set atomic [newval]

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

newval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a new value to store

Procedure: atomic-pointer-xor atomic val ⇒ %return

Performs an atomic bitwise ’xor’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from gsize to guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

atomic

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

val

Passed: an unsigned 64-bit integer.

the value to ’xor’

%return

Returned: an unsigned 64-bit integer.

the value of atomic before the operation, unsigned

Procedure: atomic-rc-box-acquire mem-block ⇒ %return

Atomically acquires a reference on the data pointed by mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

%return

Returned: a foreign pointer.

a pointer to the data, with its reference count increased

Procedure: atomic-rc-box-alloc block-size ⇒ %return

Allocates block-size bytes of memory, and adds atomic reference counting semantics to it.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

block-size

Passed: an unsigned 64-bit integer.

the size of the allocation, must be greater than 0

%return

Returned: a foreign pointer.

a pointer to the allocated memory

Procedure: atomic-rc-box-alloc0 block-size ⇒ %return

Allocates block-size bytes of memory, and adds atomic reference counting semantics to it.

The contents of the returned data is set to zero.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

block-size

Passed: an unsigned 64-bit integer.

the size of the allocation, must be greater than 0

%return

Returned: a foreign pointer.

a pointer to the allocated memory

Procedure: atomic-rc-box-dup block-size mem-block ⇒ %return

Allocates a new block of data with atomic reference counting semantics, and copies block-size bytes of mem-block into it.

block-size

Passed: an unsigned 64-bit integer.

the number of bytes to copy, must be greater than 0

mem-block

Passed: a foreign pointer, or a bytevector.

the memory to copy

%return

Returned: a foreign pointer.

a pointer to the allocated memory

Procedure: atomic-rc-box-get-size mem-block ⇒ %return

Retrieves the size of the reference counted data pointed by mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

%return

Returned: an unsigned 64-bit integer.

the size of the data, in bytes

Procedure: atomic-rc-box-release mem-block

Atomically releases a reference on the data pointed by mem-block.

If the reference was the last one, it will free the resources allocated for mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

Procedure: atomic-rc-box-release-full mem-block clear-func

Atomically releases a reference on the data pointed by mem-block.

If the reference was the last one, it will call clear-func to clear the contents of mem-block, and then will free the resources allocated for mem-block.

Note that implementing weak references via clear-func is not thread-safe: clearing a pointer to the memory from the callback can race with another thread trying to access it as mem-block already has a reference count of 0 when the callback is called and will be freed.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

clear-func

Passed: a procedure.

a function to call when clearing the data

See GDestroyNotify for how it is called.

Procedure: atomic-ref-count-compare? arc val ⇒ %return

Atomically compares the current value of arc with val.

arc

Passed: a 32-bit integer.

the address of an atomic reference count variable

val

Passed: a 32-bit integer.

the value to compare

%return

Returned: a boolean.

#t if the reference count is the same as the given value

Procedure: atomic-ref-count-dec? arc ⇒ %return

Atomically decreases the reference count.

If #t is returned, the reference count reached 0. After this point, arc is an undefined state and must be reinitialized with atomic-ref-count-init to be used again.

arc

Passed: a 32-bit integer.

the address of an atomic reference count variable

%return

Returned: a boolean.

#t if the reference count reached 0, and #f otherwise

Procedure: atomic-ref-count-inc arc

Atomically increases the reference count.

arc

Passed: a 32-bit integer.

the address of an atomic reference count variable

Procedure: atomic-ref-count-init ⇒ arc

Initializes a reference count variable to 1.

arc

Returned: a 32-bit integer.

the address of an atomic reference count variable

Procedure: base64-decode text ⇒ %return

Decode a sequence of Base-64 encoded text into binary data. Note that the returned binary data is not necessarily zero-terminated, so it should not be used as a character string.

text

Passed: a string.

zero-terminated string with base64 text to decode

%return

Returned: a bytevector.

newly allocated buffer containing the binary data that text represents. The returned buffer must be freed with byte-array:free.

out-len

Not returned: it is the length of %return.

The length of the decoded data is written here

Procedure: base64-decode-inplace! text ⇒ %return text

Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.

text

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer. Returned: a bytevector.

zero-terminated string with base64 text to decode

%return

Returned: an unsigned 8-bit integer.

The binary data that text responds. This pointer is the same as the input text.

out-len

Not returned: it is the length of text.

The length of the decoded data is written here

Procedure: base64-encode data ⇒ %return

Encode a sequence of binary data into its Base-64 stringified representation.

data

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer, or #f.

the binary data to encode

%return

Returned: a string.

a newly allocated, zero-terminated Base-64 encoded string representing data. The returned string must be freed with byte-array:free.

len

Not passed: guile-gi gives the length of data.

the length of data

Procedure: base64-encode-close break-lines state save ⇒ %return out state save

Flush the status from a sequence of calls to base64-encode-step.

The output buffer must be large enough to fit all the data that will be written to it. It will need up to 4 bytes, or up to 5 bytes if line-breaking is enabled.

The out array will not be automatically nul-terminated.

break-lines

Passed: a boolean.

whether to break long lines

state

Passed, and returned: a 32-bit integer.

Saved state from base64-encode-step

save

Passed, and returned: a 32-bit integer.

Saved state from base64-encode-step

%return

Returned: an unsigned 64-bit integer.

The number of bytes of output that was written

out

Returned: a foreign pointer.

pointer to destination buffer

Procedure: base64-encode-step in break-lines state save ⇒ %return out state save

Incrementally encode a sequence of binary data into its Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.

When all of the data has been converted you must call base64-encode-close to flush the saved state.

The output buffer must be large enough to fit all the data that will be written to it. Due to the way base64 encodes you will need at least: (len / 3 + 1) * 4 + 4 bytes (+ 4 may be needed in case of non-zero state). If you enable line-breaking you will need at least: ((len / 3 + 1) * 4 + 4) / 76 + 1 bytes of extra space.

break-lines is typically used when putting base64-encoded data in emails. It breaks the lines at 76 columns instead of putting all of the text on the same line. This avoids problems with long lines in the email system. Note however that it breaks the lines with LF characters, not CR LF sequences, so the result cannot be passed directly to SMTP or certain other protocols.

in

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the binary data to encode

break-lines

Passed: a boolean.

whether to break long lines

state

Passed, and returned: a 32-bit integer.

Saved state between steps, initialize to 0

save

Passed, and returned: a 32-bit integer.

Saved state between steps, initialize to 0

%return

Returned: an unsigned 64-bit integer.

The number of bytes of output that was written

out

Returned: a foreign pointer.

pointer to destination buffer

len

Not passed: guile-gi gives the length of in.

the length of in

Procedure: bit-lock address lock-bit

Sets the indicated lock-bit in address. If the bit is already set, this call will block until bit-unlock unsets the corresponding bit.

Attempting to lock on two different bits within the same integer is not supported and will very probably cause deadlocks.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

address

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to an integer

lock-bit

Passed: a 32-bit integer.

a bit value between 0 and 31

Procedure: bit-lock-and-get address lock-bit ⇒ out-val

Sets the indicated lock-bit in address and atomically returns the new value.

This is like bit-lock, except it can atomically return the new value at address (right after obtaining the lock). Thus the value returned in out-val always has the lock-bit set.

address

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to an integer

lock-bit

Passed: an unsigned 32-bit integer.

a bit value between 0 and 31

out-val

Returned: a 32-bit integer.

return location for the new value of the integer

Procedure: bit-nth-lsf mask nth-bit ⇒ %return

Find the position of the first bit set in mask, searching from (but not including) nth-bit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth-bit to -1.

mask

Passed: an unsigned 64-bit integer.

a gulong containing flags

nth-bit

Passed: a 32-bit integer.

the index of the bit to start the search from

%return

Returned: a 32-bit integer.

the index of the first bit set which is higher than nth-bit, or -1 if no higher bits are set

Procedure: bit-nth-msf mask nth-bit ⇒ %return

Find the position of the first bit set in mask, searching from (but not including) nth-bit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth-bit to -1 or GLIB_SIZEOF_LONG * 8.

mask

Passed: an unsigned 64-bit integer.

a gulong containing flags

nth-bit

Passed: a 32-bit integer.

the index of the bit to start the search from

%return

Returned: a 32-bit integer.

the index of the first bit set which is lower than nth-bit, or -1 if no lower bits are set

Procedure: bit-storage number ⇒ %return

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

number

Passed: an unsigned 64-bit integer.

a guint

%return

Returned: an unsigned 32-bit integer.

the number of bits used to hold number

Procedure: bit-trylock? address lock-bit ⇒ %return

Sets the indicated lock-bit in address, returning #t if successful. If the bit is already set, returns #f immediately.

Attempting to lock on two different bits within the same integer is not supported.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

address

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to an integer

lock-bit

Passed: a 32-bit integer.

a bit value between 0 and 31

%return

Returned: a boolean.

#t if the lock was acquired

Procedure: bit-unlock address lock-bit

Clears the indicated lock-bit in address. If another thread is currently blocked in bit-lock on this same bit then it will be woken up.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

address

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to an integer

lock-bit

Passed: a 32-bit integer.

a bit value between 0 and 31

Procedure: bit-unlock-and-set address lock-bit new-val preserve-mask

This is like bit-unlock but also atomically sets address to val.

If preserve-mask is not zero, then the preserve-mask bits will be preserved in address and are not set to val.

Note that the lock-bit bit will always be unset regardless of val, preserve-mask and the currently set value in address.

address

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to an integer

lock-bit

Passed: an unsigned 32-bit integer.

a bit value between 0 and 31

new-val

Passed: a 32-bit integer.

the new value to set

preserve-mask

Passed: a 32-bit integer.

mask for bits from address to preserve

Procedure: bookmark-file-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: build-filenamev args ⇒ %return

Creates a filename from a vector of elements using the correct separator for the current platform.

This function behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

If you are building a path programmatically you may want to use GPathBuf instead.

args

Passed: a list or vector, each a file name, as a string.

#f-terminated array of strings containing the path elements.

%return

Returned: a file name, as a string.

the newly allocated path

Procedure: build-pathv separator args ⇒ %return

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of variadic arguments.

This function is mainly meant for language bindings.

separator

Passed: a string.

a string used to separate the elements of the path.

args

Passed: a list or vector, each a file name, as a string.

#f-terminated array of strings containing the path elements.

%return

Returned: a file name, as a string.

a newly-allocated string that must be freed with byte-array:free.

Procedure: byte-array-append array data ⇒ %return

Adds the given bytes to the end of the <GByteArray>. The array will grow in size automatically if necessary.

array

Passed: a bytevector.

a byte array

data

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the byte data to be added

%return

Returned: a bytevector.

The <GByteArray>

len

Not passed: guile-gi gives the length of data.

the number of bytes to add

Procedure: byte-array-free array free-segment ⇒ %return

Frees the memory allocated by the <GByteArray>. If free-segment is true it frees the actual byte data. If the reference count of array is greater than one, the <GByteArray> wrapper is preserved but the size of array will be set to zero.

array

Passed: a bytevector.

a byte array

free-segment

Passed: a boolean.

if true, the actual byte data is freed as well

%return

Returned: a foreign pointer, or #f.

The allocated element data if free-segment is false, otherwise NULL.

Procedure: byte-array-free-to-bytes array ⇒ %return

Transfers the data from the <GByteArray> into a new immutable <GBytes>.

The <GByteArray> is freed unless the reference count of array is greater than one, in which the <GByteArray> wrapper is preserved but the size of array will be set to zero.

This is identical to using bytes:new-take and byte-array:free together.

array

Passed: a bytevector.

a byte array

%return

Returned: a <GBytes>.

The new immutable <GBytes> representing same byte data that was in the array

Procedure: byte-array-new ⇒ %return

Creates a new <GByteArray> with a reference count of 1.

%return

Returned: a bytevector.

The new <GByteArray>

Procedure: byte-array-new-take data ⇒ %return

Creates a byte array containing the data. After this call, data belongs to the <GByteArray> and may no longer be modified by the caller. The memory of data has to be dynamically allocated and will eventually be freed with byte-array:free.

Do not use it if len is greater than ‘G_MAXUINT‘. <GByteArray> stores the length of its data in guint, which may be shorter than gsize.

data

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the byte data for the array

%return

Returned: a bytevector.

The new <GByteArray>

len

Not passed: guile-gi gives the length of data.

the length of data

Procedure: byte-array-prepend array data ⇒ %return

Adds the given data to the start of the <GByteArray>. The array will grow in size automatically if necessary.

array

Passed: a bytevector.

a byte array

data

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the byte data to be added

%return

Returned: a bytevector.

The <GByteArray>

len

Not passed: guile-gi gives the length of data.

the number of bytes to add

Procedure: byte-array-ref array ⇒ %return

Atomically increments the reference count of array by one. This function is thread-safe and may be called from any thread.

array

Passed: a bytevector.

a byte array

%return

Returned: a bytevector.

The passed in <GByteArray>

Procedure: byte-array-remove-index array index- ⇒ %return

Removes the byte at the given index from a <GByteArray>. The following bytes are moved down one place.

array

Passed: a bytevector.

a byte array

index-

Passed: an unsigned 32-bit integer.

the index of the byte to remove

%return

Returned: a bytevector.

The <GByteArray>

Procedure: byte-array-remove-index-fast array index- ⇒ %return

Removes the byte at the given index from a <GByteArray>. The last element in the array is used to fill in the space, so this function does not preserve the order of the <GByteArray>. But it is faster than byte-array:remove-index.

array

Passed: a bytevector.

a byte array

index-

Passed: an unsigned 32-bit integer.

the index of the byte to remove

%return

Returned: a bytevector.

The <GByteArray>

Procedure: byte-array-remove-range array index- length ⇒ %return

Removes the given number of bytes starting at the given index from a <GByteArray>. The following elements are moved to close the gap.

array

Passed: a bytevector.

a byte array

index-

Passed: an unsigned 32-bit integer.

the index of the first byte to remove

length

Passed: an unsigned 32-bit integer.

the number of bytes to remove

%return

Returned: a bytevector.

The <GByteArray>

Procedure: byte-array-set-size array length ⇒ %return

Sets the size of the <GByteArray>, expanding it if necessary.

array

Passed: a bytevector.

a byte array

length

Passed: an unsigned 32-bit integer.

the new size of the <GByteArray>

%return

Returned: a bytevector.

The <GByteArray>

Procedure: byte-array-sized-new reserved-size ⇒ %return

Creates a new <GByteArray> with reserved-size bytes preallocated. This avoids frequent reallocation, if you are going to add many bytes to the array. Note however that the size of the array is still 0.

reserved-size

Passed: an unsigned 32-bit integer.

the number of bytes preallocated

%return

Returned: a bytevector.

The new <GByteArray>

Procedure: byte-array-sort array compare-func

Sorts a byte array, using compare-func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater than zero if first arg is greater than second arg).

If two array elements compare equal, their order in the sorted array is undefined. If you want equal elements to keep their order (i.e. you want a stable sort) you can write a comparison function that, if two elements would otherwise compare equal, compares them by their addresses.

array

Passed: a bytevector.

a byte array

compare-func

Passed: a procedure.

the comparison function

See GCompareFunc for how it is called.

Procedure: byte-array-sort-with-data array compare-func

Like byte-array:sort, but the comparison function takes an extra user data argument.

array

Passed: a bytevector.

a byte array

compare-func

Passed: a procedure.

the comparison function

See GCompareDataFunc for how it is called.

user-data

Not passed: guile-gi supplies it.

the data to pass to compare-func

Procedure: byte-array-steal array ⇒ %return

Frees the data in the array and resets the size to zero, while the underlying array is preserved for use elsewhere and returned to the caller.

array

Passed: a bytevector.

a byte array

%return

Returned: a bytevector.

The allocated element data

len

Not returned: it is the length of %return.

the pointer to retrieve the number of elements of the original array

Procedure: byte-array-unref array

Atomically decrements the reference count of array by one. If the reference count drops to 0, all memory allocated by the array is released. This function is thread-safe and may be called from any thread.

array

Passed: a bytevector.

a byte array

Procedure: byte-array:free array free-segment ⇒ %return
array

Passed: a bytevector.

free-segment

Passed: a boolean.

%return

Returned: a foreign pointer, or #f.

mem

Passed, or left out: a foreign pointer, or a bytevector, or #f.

Procedure: canonicalize-filename filename [relative-to] ⇒ %return

Gets the canonical file name from filename. All triple slashes are turned into single slashes, and all .. and .s resolved against relative-to.

Symlinks are not followed, and the returned path is guaranteed to be absolute.

If filename is an absolute path, relative-to is ignored. Otherwise, relative-to will be prepended to filename to make it absolute. relative-to must be an absolute path, or #f. If relative-to is #f, it’ll fallback to get-current-dir.

This function never fails, and will canonicalize file paths even if they don’t exist.

No file system I/O is done.

filename

Passed: a file name, as a string.

the name of the file

relative-to

Passed, or left out: a file name, as a string, or #f.

the relative directory, or #f to use the current working directory

%return

Returned: a file name, as a string.

a newly allocated string with the canonical file path

Procedure: chdir path ⇒ %return

A wrapper for the POSIX chdir() function. The function changes the current directory of the process to path.

See your C library manual for more details about chdir().

path

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

%return

Returned: a 32-bit integer.

0 on success, -1 if an error occurred.

Procedure: check-version required-major required-minor required-micro ⇒ %return

Checks that the GLib library in use is compatible with the given version.

Generally you would pass in the constants GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION as the three arguments to this function; that produces a check that the library in use is compatible with the version of GLib the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version @required_major.required_minor.@required_micro. Second the running library must be binary compatible with the version @required_major.@required_minor.@required_micro (same major version.)

required-major

Passed: an unsigned 32-bit integer.

the required major version

required-minor

Passed: an unsigned 32-bit integer.

the required minor version

required-micro

Passed: an unsigned 32-bit integer.

the required micro version

%return

Returned: a string, or #f.

#f if the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.

Procedure: checksum-type-get-length checksum-type ⇒ %return

Gets the length in bytes of digests of type checksum-type

checksum-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType>

%return

Returned: a 64-bit integer.

the checksum length, or -1 if checksum-type is not supported.

Procedure: child-watch-add priority pid function ⇒ %return

Sets a function to be called when the child indicated by pid exits, at a default priority, GLib.PRIORITY_DEFAULT.

If you obtain pid from spawn-async or spawn-async-with-pipes you will need to pass GLib.SpawnFlags.DO_NOT_REAP_CHILD as a flag to the spawn function for the child watching to work.

Note that on platforms where GLib.Pid must be explicitly closed (see spawn-close-pid) pid must not be closed while the source is still active. Typically, you will want to call spawn-close-pid in the callback function for the source.

GLib supports only a single callback per process ID. On POSIX platforms, the same restrictions mentioned for child-watch-source-new apply to this function.

This internally creates a main loop source using child-watch-source-new and attaches it to the main loop context using source:attach. You can do these steps manually if you need greater control.

priority

Passed: a 32-bit integer.

pid

Passed: a 32-bit integer.

process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)

function

Passed: a procedure.

function to call

See GChildWatchFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the ID (greater than 0) of the event source

notify

Not passed: guile-gi supplies it.

data

Not passed: guile-gi supplies it.

data to pass to function

Procedure: child-watch-source-new pid ⇒ %return

Creates a new child watch source.

The source will not initially be associated with any <GMainContext> and must be added to one with source:attach before it will be executed.

Note that child watch sources can only be used in conjunction with g_spawn... when the GLib.SpawnFlags.DO_NOT_REAP_CHILD flag is used.

Note that on platforms where GLib.Pid must be explicitly closed (see spawn-close-pid) pid must not be closed while the source is still active. Typically, you will want to call spawn-close-pid in the callback function for the source.

On POSIX platforms, the following restrictions apply to this API due to limitations in POSIX process interfaces:

  • pid must be a child of this process.
  • pid must be positive.
  • The application must not call ‘waitpid()‘) with a non-positive first argument, for instance in another thread.
  • The application must not wait for pid to exit by any other mechanism, including waitpid(pid, ...) or a second child-watch source for the same pid.
  • The application must not ignore SIGCHLD.
  • Before 2.78, the application could not send a signal (‘kill()‘)) to the watched pid in a race free manner. Since 2.78, you can do that while the associated <GMainContext> is acquired.
  • Before 2.78, even after destroying the <GSource>, you could not be sure that pid wasn’t already reaped. Hence, it was also not safe to kill() or waitpid() on the process ID after the child watch source was gone. Destroying the source before it fired made it impossible to reliably reap the process.

If any of those conditions are not met, this and related APIs will not work correctly. This can often be diagnosed via a GLib warning stating that ECHILD was received by waitpid().

Calling ‘waitpid()‘) for specific processes other than pid remains a valid thing to do.

pid

Passed: a 32-bit integer.

process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)

%return

Returned: a <GSource>.

the newly-created child watch source

Procedure: chmod filename mode ⇒ %return

A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object.

On Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the FAT-style READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.

See your C library manual for more details about chmod().

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode

Passed: a 32-bit integer.

as in chmod()

%return

Returned: a 32-bit integer.

0 if the operation succeeded, -1 on error

Procedure: clear-error

If err or *err is #f, does nothing. Otherwise, calls error:free on *err and sets *err to #f.

Procedure: close? fd ⇒ %return

This wraps the close() call. In case of error, errno will be preserved, but the error will also be stored as a <GError> in error. In case of success, errno is undefined.

Besides using <GError>, there is another major reason to prefer this function over the call provided by the system; on Unix, it will attempt to correctly handle EINTR, which has platform-specific semantics.

It is a bug to call this function with an invalid file descriptor.

On POSIX platforms since GLib 2.76, this function is async-signal safe if (and only if) error is #f and fd is a valid open file descriptor. This makes it safe to call from a signal handler or a GSpawnChildSetupFunc under those conditions. See ‘signal(7)‘) and ‘signal-safety(7)‘) for more details.

fd

Passed: a 32-bit integer.

A file descriptor

%return

Returned: a boolean.

#t on success, #f if there was an error.

Procedure: compute-checksum-for-bytes checksum-type data ⇒ %return

Computes the checksum for a binary data. This is a convenience wrapper for checksum:new, checksum:get-string and checksum:free.

The hexadecimal string returned will be in lower case.

checksum-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType>

data

Passed: a <GBytes>.

binary blob to compute the digest of

%return

Returned: a string, or #f.

the digest of the binary data as a string in hexadecimal, or #f if checksum:new fails for checksum-type. The returned string should be freed with byte-array:free when done using it.

Procedure: compute-checksum-for-data checksum-type data ⇒ %return

Computes the checksum for a binary data of length. This is a convenience wrapper for checksum:new, checksum:get-string and checksum:free.

The hexadecimal string returned will be in lower case.

checksum-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType>

data

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

binary blob to compute the digest of

%return

Returned: a string, or #f.

the digest of the binary data as a string in hexadecimal, or #f if checksum:new fails for checksum-type. The returned string should be freed with byte-array:free when done using it.

length

Not passed: guile-gi gives the length of data.

length of data

Procedure: compute-checksum-for-string checksum-type str length ⇒ %return

Computes the checksum of a string.

The hexadecimal string returned will be in lower case.

checksum-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType>

str

Passed: a string.

the string to compute the checksum of

length

Passed: a 64-bit integer.

the length of the string, or -1 if the string is null-terminated.

%return

Returned: a string, or #f.

the checksum as a hexadecimal string, or #f if checksum:new fails for checksum-type. The returned string should be freed with byte-array:free when done using it.

Procedure: compute-hmac-for-bytes digest-type key data ⇒ %return

Computes the HMAC for a binary data. This is a convenience wrapper for hmac:new, hmac:get-string and hmac:unref.

The hexadecimal string returned will be in lower case.

digest-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType> to use for the HMAC

key

Passed: a <GBytes>.

the key to use in the HMAC

data

Passed: a <GBytes>.

binary blob to compute the HMAC of

%return

Returned: a string.

the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with byte-array:free when done using it.

Procedure: compute-hmac-for-data digest-type key data ⇒ %return

Computes the HMAC for a binary data of length. This is a convenience wrapper for hmac:new, hmac:get-string and hmac:unref.

The hexadecimal string returned will be in lower case.

digest-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType> to use for the HMAC

key

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the key to use in the HMAC

data

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

binary blob to compute the HMAC of

%return

Returned: a string.

the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with byte-array:free when done using it.

key-len

Not passed: guile-gi gives the length of key.

the length of the key

length

Not passed: guile-gi gives the length of data.

length of data

Procedure: compute-hmac-for-string digest-type key str length ⇒ %return

Computes the HMAC for a string.

The hexadecimal string returned will be in lower case.

digest-type

Passed: a <%GChecksumType>, or one of its symbols.

a <%GChecksumType> to use for the HMAC

key

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the key to use in the HMAC

str

Passed: a string.

the string to compute the HMAC for

length

Passed: a 64-bit integer.

the length of the string, or -1 if the string is nul-terminated

%return

Returned: a string.

the HMAC as a hexadecimal string. The returned string should be freed with byte-array:free when done using it.

key-len

Not passed: guile-gi gives the length of key.

the length of the key

Procedure: convert str to-codeset from-codeset ⇒ %return bytes-read

Converts a string from one character set to another.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytes-read can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls to convert, g_convert_with_iconv() or convert-with-fallback. (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

Using extensions such as "//TRANSLIT" may not work (or may not work well) on many platforms. Consider using str-to-ascii instead.

str

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the string to convert.

to-codeset

Passed: a string.

name of character set into which to convert str

from-codeset

Passed: a string.

character set of str.

%return

Returned: a bytevector.

If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with byte-array:free. Otherwise #f and error will be set.

bytes-read

Returned: an unsigned 64-bit integer.

location to store the number of bytes in the input string that were successfully converted, or #f. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error illegal-sequence occurs, the value stored will be the byte offset after the last valid input sequence.

len

Not passed: guile-gi gives the length of str.

the length of the string in bytes, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)

bytes-written

Not returned: it is the length of %return.

the number of bytes stored in the output buffer (not including the terminating nul).

Procedure: convert-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: convert-with-fallback str to-codeset from-codeset fallback ⇒ %return bytes-read

Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output. Note that it is not guaranteed that the specification for the fallback sequences in fallback will be honored. Some systems may do an approximate conversion from from-codeset to to-codeset in their iconv() functions, in which case GLib will simply return that approximate conversion.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytes-read can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls to convert, g_convert_with_iconv() or convert-with-fallback. (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

str

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the string to convert.

to-codeset

Passed: a string.

name of character set into which to convert str

from-codeset

Passed: a string.

character set of str.

fallback

Passed: a string.

UTF-8 string to use in place of characters not present in the target encoding. (The string must be representable in the target encoding). If #f, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.

%return

Returned: a bytevector.

If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with byte-array:free. Otherwise #f and error will be set.

bytes-read

Returned: an unsigned 64-bit integer.

location to store the number of bytes in the input string that were successfully converted, or #f. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input.

len

Not passed: guile-gi gives the length of str.

the length of the string in bytes, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)

bytes-written

Not returned: it is the length of %return.

the number of bytes stored in the output buffer (not including the terminating nul).

Procedure: creat filename mode ⇒ %return

A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessary.

On POSIX systems file descriptors are implemented by the operating system. On Windows, it’s the C library that implements creat() and file descriptors. The actual Windows API for opening files is different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

See your C library manual for more details about creat().

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode

Passed: a 32-bit integer.

as in creat()

%return

Returned: a 32-bit integer.

a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().

Procedure: dataset-destroy dataset-location

Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

dataset-location

Passed: a foreign pointer, or a bytevector.

the location identifying the dataset.

Procedure: dataset-foreach dataset-location func

Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unless dataset-location can be protected from any modifications during invocation of this function, it should not be called.

func can make changes to the dataset, but the iteration will not reflect changes made during the dataset-foreach call, other than skipping over elements that are removed.

dataset-location

Passed: a foreign pointer, or a bytevector.

the location identifying the dataset.

func

Passed: a procedure.

the function to call for each data element.

See GDataForeachFunc for how it is called.

user-data

Not passed: guile-gi supplies it.

user data to pass to the function.

Procedure: dataset-id-get-data dataset-location key-id ⇒ %return

Gets the data element corresponding to a GQuark.

dataset-location

Passed: a foreign pointer, or a bytevector.

the location identifying the dataset.

key-id

Passed: an unsigned 32-bit integer.

the GQuark id to identify the data element.

%return

Returned: a foreign pointer, or #f.

the data element corresponding to the GQuark, or #f if it is not found.

Procedure: date-get-days-in-month month year ⇒ %return

Returns the number of days in a month, taking leap years into account.

month

Passed: a <%GDateMonth>, or one of its symbols.

month

year

Passed: an unsigned 16-bit integer.

year

%return

Returned: an unsigned 8-bit integer.

number of days in month during the year

Procedure: date-get-monday-weeks-in-year year ⇒ %return

Returns the number of weeks in the year, where weeks are taken to start on Monday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it’s a leap year. This function is basically telling you how many Mondays are in the year, i.e. there are 53 Mondays if one of the extra days happens to be a Monday.)

year

Passed: an unsigned 16-bit integer.

a year

%return

Returned: an unsigned 8-bit integer.

number of Mondays in the year

Procedure: date-get-sunday-weeks-in-year year ⇒ %return

Returns the number of weeks in the year, where weeks are taken to start on Sunday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it’s a leap year. This function is basically telling you how many Sundays are in the year, i.e. there are 53 Sundays if one of the extra days happens to be a Sunday.)

year

Passed: an unsigned 16-bit integer.

year to count weeks in

%return

Returned: an unsigned 8-bit integer.

the number of weeks in year

Procedure: date-get-weeks-in-year year first-day-of-week ⇒ %return

Calculates the number of weeks in the year.

The result depends on which day is considered the first day of the week, which varies by locale. first_day_of_week must be valid.

The result will be either 52 or 53. Years always have 52 seven-day periods, plus one or two extra days depending on whether it’s a leap year. This function effectively calculates how many first-day-of-week days there are in the year.

year

Passed: an unsigned 16-bit integer.

year to count weeks in

first-day-of-week

Passed: a <%GDateWeekday>, or one of its symbols.

the day which is considered the first day of the week (for example, this would be GLib.DateWeekday.SUNDAY in US locales, GLib.DateWeekday.MONDAY in British locales, and GLib.DateWeekday.SATURDAY in Egyptian locales

%return

Returned: an unsigned 8-bit integer.

the number of weeks in year

Procedure: date-is-leap-year? year ⇒ %return

Returns #t if the year is a leap year.

For the purposes of this function, leap year is every year divisible by 4 unless that year is divisible by 100. If it is divisible by 100 it would be a leap year only if that year is also divisible by 400.

year

Passed: an unsigned 16-bit integer.

year to check

%return

Returned: a boolean.

#t if the year is a leap year

Procedure: date-strftime s slen format date ⇒ %return

Generates a printed representation of the date, in a locale-specific way. Works just like the platform’s C library strftime() function, but only accepts date-related formats; time-related formats give undefined results. Date must be valid. Unlike strftime() (which uses the locale encoding), works on a UTF-8 format string and stores a UTF-8 result.

This function does not provide any conversion specifiers in addition to those implemented by the platform’s C library. For example, don’t expect that using date-strftime would make the \%F provided by the C99 strftime() work on Windows where the C library only complies to C89.

s

Passed: a string.

destination buffer

slen

Passed: an unsigned 64-bit integer.

buffer size

format

Passed: a string.

format string

date

Passed: a <GDate>.

valid <GDate>

%return

Returned: an unsigned 64-bit integer.

number of characters written to the buffer, or 0 if the buffer was too small

Procedure: date-valid-day? day ⇒ %return

Returns #t if the day of the month is valid (a day is valid if it’s between 1 and 31 inclusive).

day

Passed: an unsigned 8-bit integer, or a character.

day to check

%return

Returned: a boolean.

#t if the day is valid

Procedure: date-valid-dmy? day month year ⇒ %return

Returns #t if the day-month-year triplet forms a valid, existing day in the range of days <GDate> understands (Year 1 or later, no more than a few thousand years in the future).

day

Passed: an unsigned 8-bit integer, or a character.

day

month

Passed: a <%GDateMonth>, or one of its symbols.

month

year

Passed: an unsigned 16-bit integer.

year

%return

Returned: a boolean.

#t if the date is a valid one

Procedure: date-valid-julian? julian-date ⇒ %return

Returns #t if the Julian day is valid. Anything greater than zero is basically a valid Julian, though there is a 32-bit limit.

julian-date

Passed: an unsigned 32-bit integer.

Julian day to check

%return

Returned: a boolean.

#t if the Julian day is valid

Procedure: date-valid-month? month ⇒ %return

Returns #t if the month value is valid. The 12 <%GDateMonth> enumeration values are the only valid months.

month

Passed: a <%GDateMonth>, or one of its symbols.

month

%return

Returned: a boolean.

#t if the month is valid

Procedure: date-valid-weekday? weekday ⇒ %return

Returns #t if the weekday is valid. The seven <%GDateWeekday> enumeration values are the only valid weekdays.

weekday

Passed: a <%GDateWeekday>, or one of its symbols.

weekday

%return

Returned: a boolean.

#t if the weekday is valid

Procedure: date-valid-year? year ⇒ %return

Returns #t if the year is valid. Any year greater than 0 is valid, though there is a 16-bit limit to what <GDate> will understand.

year

Passed: an unsigned 16-bit integer.

year

%return

Returned: a boolean.

#t if the year is valid

Procedure: dcgettext domain msgid category ⇒ %return

This is a variant of dgettext that allows specifying a locale category instead of always using LC_MESSAGES. See dgettext for more information about how this functions differs from calling dcgettext() directly.

domain

Passed: a string, or #f.

the translation domain to use, or #f to use the domain set with textdomain()

msgid

Passed: a string.

message to translate

category

Passed: a 32-bit integer.

a locale category

%return

Returned: a string.

the translated string for the given locale category

Procedure: dgettext domain msgid ⇒ %return

This function is a wrapper of dgettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

The advantage of using this function over dgettext() proper is that libraries using this function (like GTK) will not use translations if the application using the library does not have translations for the current locale. This results in a consistent English-only interface instead of one having partial translations. For this feature to work, the call to textdomain() and setlocale() should precede any dgettext invocations. For GTK, it means calling textdomain() before gtk_init or its variants.

This function disables translations if and only if upon its first call all the following conditions hold:

  • domain is not #f
  • textdomain() has been called to set a default text domain
  • there is no translations available for the default text domain and the current locale
  • current locale is not "C" or any English locales (those starting with "en_")

Note that this behavior may not be desired for example if an application has its untranslated messages in a language other than English. In those cases the application should call textdomain() after initializing GTK.

Applications should normally not use this function directly, but use the _() macro for translations.

domain

Passed: a string, or #f.

the translation domain to use, or #f to use the domain set with textdomain()

msgid

Passed: a string.

message to translate

%return

Returned: a string.

The translated string

Procedure: dir-make-tmp [tmpl] ⇒ %return

Creates a subdirectory in the preferred directory for temporary files (as returned by get-tmp-dir).

tmpl should be a string in the GLib file name encoding containing a sequence of six ’X’ characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is #f, a default template is used.

Note that in contrast to g_mkdtemp() (and mkdtemp()) tmpl is not modified, and might thus be a read-only literal string.

tmpl

Passed, or left out: a file name, as a string, or #f.

Template for directory name, as in g_mkdtemp(), basename only, or #f for a default template

%return

Returned: a file name, as a string.

The actual name used. This string should be freed with byte-array:free when not needed any longer and is is in the GLib file name encoding. In case of errors, #f is returned and error will be set.

Procedure: dir:open path flags ⇒ %return
path

Passed: a string.

flags

Passed: an unsigned 32-bit integer.

%return

Returned: a <GDir>.

filename

Passed: a file name, as a string.

mode

Passed: a 32-bit integer.

Procedure: direct-equal? [v1] [v2] ⇒ %return

Compares two gpointer arguments and returns #t if they are equal. It can be passed to g_hash_table_new() as the key-equal-func parameter, when using opaque pointers compared by pointer value as keys in a <GHashTable>.

This equality function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

v1

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a key

v2

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a key to compare with v1

%return

Returned: a boolean.

#t if the two keys match.

Procedure: direct-hash [v] ⇒ %return

Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as the hash-func parameter, when using opaque pointers compared by pointer value as keys in a <GHashTable>.

This hash function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

v

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a gpointer key

%return

Returned: an unsigned 32-bit integer.

a hash value corresponding to the key.

Procedure: dngettext domain msgid msgid-plural n ⇒ %return

This function is a wrapper of dngettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

See dgettext for details of how this differs from dngettext() proper.

domain

Passed: a string, or #f.

the translation domain to use, or #f to use the domain set with textdomain()

msgid

Passed: a string.

message to translate

msgid-plural

Passed: a string.

plural form of the message

n

Passed: an unsigned 64-bit integer.

the quantity for which translation is needed

%return

Returned: a string.

The translated string

Procedure: double-equal? v1 v2 ⇒ %return

Compares the two gdouble values being pointed to and returns #t if they are equal. It can be passed to g_hash_table_new() as the key-equal-func parameter, when using non-#f pointers to doubles as keys in a <GHashTable>.

v1

Passed: a foreign pointer, or a bytevector.

a pointer to a gdouble key

v2

Passed: a foreign pointer, or a bytevector.

a pointer to a gdouble key to compare with v1

%return

Returned: a boolean.

#t if the two keys match.

Procedure: double-hash v ⇒ %return

Converts a pointer to a gdouble to a hash value. It can be passed to g_hash_table_new() as the hash-func parameter, It can be passed to g_hash_table_new() as the hash-func parameter, when using non-#f pointers to doubles as keys in a <GHashTable>.

v

Passed: a foreign pointer, or a bytevector.

a pointer to a gdouble key

%return

Returned: an unsigned 32-bit integer.

a hash value corresponding to the key.

Procedure: dpgettext domain msgctxtid msgidoffset ⇒ %return

This function is a variant of dgettext which supports a disambiguating message context. GNU gettext uses the ’\004’ character to separate the message context and message id in msgctxtid. If 0 is passed as msgidoffset, this function will fall back to trying to use the deprecated convention of using "|" as a separation character.

This uses dgettext internally. See that functions for differences with dgettext() proper.

Applications should normally not use this function directly, but use the C_() macro for translations with context.

domain

Passed: a string, or #f.

the translation domain to use, or #f to use the domain set with textdomain()

msgctxtid

Passed: a string.

a combined message context and message id, separated by a \004 character

msgidoffset

Passed: an unsigned 64-bit integer.

the offset of the message id in msgctxid

%return

Returned: a string.

The translated string

Procedure: dpgettext2 domain context msgid ⇒ %return

This function is a variant of dgettext which supports a disambiguating message context. GNU gettext uses the ’\004’ character to separate the message context and message id in msgctxtid.

This uses dgettext internally. See that functions for differences with dgettext() proper.

This function differs from C_() in that it is not a macro and thus you may use non-string-literals as context and msgid arguments.

domain

Passed: a string, or #f.

the translation domain to use, or #f to use the domain set with textdomain()

context

Passed: a string.

the message context

msgid

Passed: a string.

the message

%return

Returned: a string.

The translated string

Procedure: environ-getenv envp variable ⇒ %return

Returns the value of the environment variable variable in the provided list envp.

envp

Passed: a list or vector, each a file name, as a string, or #f.

an environment list (eg, as returned from get-environ), or #f for an empty environment list

variable

Passed: a file name, as a string.

the environment variable to get

%return

Returned: a file name, as a string, or #f.

the value of the environment variable, or #f if the environment variable is not set in envp. The returned string is owned by envp, and will be freed if variable is set or unset again.

Procedure: environ-setenv envp variable value overwrite ⇒ %return

Sets the environment variable variable in the provided list envp to value.

envp

Passed: a list or vector, each a file name, as a string, or #f.

an environment list that can be freed using strfreev (e.g., as returned from get-environ), or #f for an empty environment list

variable

Passed: a file name, as a string.

the environment variable to set, must not contain ’=’

value

Passed: a file name, as a string.

the value for to set the variable to

overwrite

Passed: a boolean.

whether to change the variable if it already exists

%return

Returned: a vector, each a file name, as a string.

the updated environment list. Free it using strfreev.

Procedure: environ-unsetenv envp variable ⇒ %return

Removes the environment variable variable from the provided environment envp.

envp

Passed: a list or vector, each a file name, as a string, or #f.

an environment list that can be freed using strfreev (e.g., as returned from get-environ), or #f for an empty environment list

variable

Passed: a file name, as a string.

the environment variable to remove, must not contain ’=’

%return

Returned: a vector, each a file name, as a string.

the updated environment list. Free it using strfreev.

Procedure: error-domain-register error-type-name error-type-private-size error-type-init error-type-copy error-type-clear ⇒ %return

This function registers an extended <GError> domain. error-type-name will be duplicated. Otherwise does the same as error-domain-register-static.

error-type-name

Passed: a string.

string to create a GQuark from

error-type-private-size

Passed: an unsigned 64-bit integer.

size of the private error data in bytes

error-type-init

Passed: a procedure.

function initializing fields of the private error data

See GErrorInitFunc for how it is called.

error-type-copy

Passed: a procedure.

function copying fields of the private error data

See GErrorCopyFunc for how it is called.

error-type-clear

Passed: a procedure.

function freeing fields of the private error data

See GErrorClearFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

GQuark representing the error domain

Procedure: error-domain-register-static error-type-name error-type-private-size error-type-init error-type-copy error-type-clear ⇒ %return

This function registers an extended <GError> domain.

error-type-name should not be freed. error-type-private-size must be greater than 0.

error-type-init receives an initialized <GError> and should then initialize the private data.

error-type-copy is a function that receives both original and a copy <GError> and should copy the fields of the private error data. The standard <GError> fields are already handled.

error-type-clear receives the pointer to the error, and it should free the fields of the private error data. It should not free the struct itself though.

Normally, it is better to use G_DEFINE_EXTENDED_ERROR(), as it already takes care of passing valid information to this function.

error-type-name

Passed: a string.

static string to create a GQuark from

error-type-private-size

Passed: an unsigned 64-bit integer.

size of the private error data in bytes

error-type-init

Passed: a procedure.

function initializing fields of the private error data

See GErrorInitFunc for how it is called.

error-type-copy

Passed: a procedure.

function copying fields of the private error data

See GErrorCopyFunc for how it is called.

error-type-clear

Passed: a procedure.

function freeing fields of the private error data

See GErrorClearFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

GQuark representing the error domain

Procedure: file-error-from-errno err-no ⇒ %return

Gets a <%GFileError> constant based on the passed-in err-no.

For example, if you pass in EEXIST this function returns exist. Unlike errno values, you can portably assume that all <%GFileError> values will exist.

Normally a <%GFileError> value goes into a <GError> returned from a function that manipulates files. So you would use file-error-from-errno when constructing a <GError>.

err-no

Passed: a 32-bit integer.

an "errno" value

%return

Returned: a <%GFileError>.

<%GFileError> corresponding to the given err-no

Procedure: file-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: file-get-contents filename ⇒ %return contents

Reads an entire file into allocated memory, with good error checking.

If the call was successful, it returns #t and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be nul-terminated, so for text files you can pass #f for the length argument. If the call was not successful, it returns #f and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the <%GFileError> enumeration. In the error case, contents is set to #f and length is set to zero.

filename

Passed: a file name, as a string.

name of a file to read contents from, in the GLib file name encoding

%return

Returned: a boolean.

#t on success, #f if an error occurred

contents

Returned: a bytevector.

location to store an allocated string, use byte-array:free to free the returned string

length

Not returned: it is the length of contents.

location to store length in bytes of the contents, or #f

Procedure: file-open-tmp [tmpl] ⇒ %return name-used

Opens a file for writing in the preferred directory for temporary files (as returned by get-tmp-dir).

tmpl should be a string in the GLib file name encoding containing a sequence of six ’X’ characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is #f, a default template is used.

Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

Upon success, and if name-used is non-#f, the actual name used is returned in name-used. This string should be freed with byte-array:free when not needed any longer. The returned name is in the GLib file name encoding.

tmpl

Passed, or left out: a file name, as a string, or #f.

Template for file name, as in g_mkstemp(), basename only, or #f for a default template

%return

Returned: a 32-bit integer.

A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and error will be set.

name-used

Returned: a file name, as a string.

location to store actual name used, or #f

Reads the contents of the symbolic link filename like the POSIX readlink() function.

The returned string is in the encoding used for filenames. Use filename-to-utf8 to convert it to UTF-8.

The returned string may also be a relative path. Use g_build_filename() to convert it to an absolute path:


g_autoptr(GError) local_error = NULL;
g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);

if (local_error != NULL)
  g_error ("Error reading link: %s", local_error->message);

if (!g_path_is_absolute (link_target))
  {
    g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
    g_free (link_target);
    link_target = g_steal_pointer (&absolute_link_target);
  }
filename

Passed: a file name, as a string.

the symbolic link

%return

Returned: a file name, as a string.

A newly-allocated string with the contents of the symbolic link, or #f if an error occurred.

Procedure: file-set-contents-full? filename contents flags mode ⇒ %return

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

flags control the properties of the write operation: whether it’s atomic, and what the tradeoff is between returning quickly or being resilient to system crashes.

As this function performs file I/O, it is recommended to not call it anywhere where blocking would cause problems, such as in the main loop of a graphical application. In particular, if flags has any value other than none then this function may call fsync().

If consistent is set in flags, the operation is atomic in the sense that it is first written to a temporary file which is then renamed to the final name.

Notes:

  • On UNIX, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.
  • On UNIX, if filename already exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and if consistent is set in flags, the fsync() call (or equivalent) will be used to ensure atomic replacement: filename will contain either its old contents or contents, even in the face of system power loss, the disk being unsafely removed, etc.
  • On UNIX, if filename does not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leave filename empty or full of NUL bytes, depending on the underlying filesystem, unless durable and consistent are set in flags.
  • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.
  • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

If the call was successful, it returns #t. If the call was not successful, it returns #f and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the <%GFileError> enumeration.

Note that the name for the temporary file is constructed by appending up to 7 characters to filename.

If the file didn’t exist before and is created, it will be given the permissions from mode. Otherwise, the permissions of the existing file will remain unchanged.

filename

Passed: a file name, as a string.

name of a file to write contents to, in the GLib file name encoding

contents

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

string to write to the file

flags

Passed: a <%GFileSetContentsFlags>, or a list of its symbols, or one of them.

flags controlling the safety vs speed of the operation

mode

Passed: a 32-bit integer.

file mode, as passed to open(); typically this will be 0666

%return

Returned: a boolean.

#t on success, #f if an error occurred

length

Not passed: guile-gi gives the length of contents.

length of contents, or -1 if contents is a nul-terminated string

Procedure: file-set-contents? filename contents ⇒ %return

Writes all of contents to a file named filename. This is a convenience wrapper around calling file-set-contents-full? with flags set to G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING and mode set to 0666.

filename

Passed: a file name, as a string.

name of a file to write contents to, in the GLib file name encoding

contents

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

string to write to the file

%return

Returned: a boolean.

#t on success, #f if an error occurred

length

Not passed: guile-gi gives the length of contents.

length of contents, or -1 if contents is a nul-terminated string

Procedure: file-test? filename test ⇒ %return

Returns #t if any of the tests in the bitfield test are #t. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return #t if the file exists; the check whether it’s a directory doesn’t matter since the existence test is #t. With the current set of available tests, there’s no point passing in more than one test at a time.

Apart from is-symlink all tests follow symbolic links, so for a symbolic link to a regular file file-test? will return #t for both is-symlink and is-regular.

Note, that for a dangling symbolic link file-test? will return #t for is-symlink and #f for all other flags.

You should never use file-test? to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before you actually perform the operation, see TOCTOU.

For example, you might think you could use is-symlink to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn’t work!


 // DON'T DO THIS
 if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
   {
     fd = g_open (filename, O_WRONLY);
     // write to fd
   }

 // DO THIS INSTEAD
 fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
 if (fd == -1)
   {
     // check error
     if (errno == ELOOP)
       // file is a symlink and can be ignored
     else
       // handle errors as before
   }
 else
   {
     // write to fd
   }

Another thing to note is that exists and is-executable are implemented using the access() system call. This usually doesn’t matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

On Windows, there are no symlinks, so testing for is-symlink will always return #f. Testing for is-executable will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

filename

Passed: a file name, as a string.

a filename to test in the GLib file name encoding

test

Passed: a <%GFileTest>, or a list of its symbols, or one of them.

bitfield of <%GFileTest> flags

%return

Returned: a boolean.

whether a test was #t

Procedure: filename-display-basename filename ⇒ %return

Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display.

If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.

This function is preferred over filename-display-name if you know the whole path, as it allows translation.

filename

Passed: a file name, as a string.

an absolute pathname in the GLib file name encoding

%return

Returned: a string.

a newly allocated string containing a rendition of the basename of the filename in valid UTF-8

Procedure: filename-display-name filename ⇒ %return

Converts a filename into a valid UTF-8 string. The conversion is not necessarily reversible, so you should keep the original around and use the return value of this function only for display purposes. Unlike filename-to-utf8, the result is guaranteed to be non-#f even if the filename actually isn’t in the GLib file name encoding.

If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

If you know the whole pathname of the file you should use filename-display-basename, since that allows location-based translation of filenames.

filename

Passed: a file name, as a string.

a pathname hopefully in the GLib file name encoding

%return

Returned: a string.

a newly allocated string containing a rendition of the filename in valid UTF-8

Procedure: filename-from-uri uri ⇒ %return hostname

Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

Since GLib 2.78, the query string and fragment can be present in the URI, but are not part of the resulting filename. We take inspiration from https://url.spec.whatwg.org/file-state, but we don’t support the entire standard.

uri

Passed: a string.

a uri describing a filename (escaped, encoded in ASCII).

%return

Returned: a file name, as a string.

a newly-allocated string holding the resulting filename, or #f on an error.

hostname

Returned: a string, or #f.

Location to store hostname for the URI. If there is no hostname in the URI, #f will be stored in this location.

Procedure: filename-from-utf8 utf8string len ⇒ %return bytes-read bytes-written

Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error illegal-sequence. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the error embedded-nul is set and the function returns #f.

utf8string

Passed: a string.

a UTF-8 encoded string.

len

Passed: a 64-bit integer.

the length of the string, or -1 if the string is nul-terminated.

%return

Returned: a file name, as a string.

The converted string, or #f on an error.

bytes-read

Returned: an unsigned 64-bit integer.

location to store the number of bytes in the input string that were successfully converted, or #f. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error illegal-sequence occurs, the value stored will be the byte offset after the last valid input sequence.

bytes-written

Returned: an unsigned 64-bit integer.

the number of bytes stored in the output buffer (not including the terminating nul).

Procedure: filename-to-uri filename [hostname] ⇒ %return

Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.

filename

Passed: a file name, as a string.

an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windows

hostname

Passed, or left out: a string, or #f.

A UTF-8 encoded hostname, or #f for none.

%return

Returned: a string.

a newly-allocated string holding the resulting URI, or #f on an error.

Procedure: filename-to-utf8 opsysstring len ⇒ %return bytes-read bytes-written

Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error illegal-sequence. If the source encoding is not UTF-8 and the conversion output contains a nul character, the error embedded-nul is set and the function returns #f. Use convert to produce output that may contain embedded nul characters.

opsysstring

Passed: a file name, as a string.

a string in the encoding for filenames

len

Passed: a 64-bit integer.

the length of the string, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)

%return

Returned: a string.

The converted string, or #f on an error.

bytes-read

Returned: an unsigned 64-bit integer.

location to store the number of bytes in the input string that were successfully converted, or #f. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error illegal-sequence occurs, the value stored will be the byte offset after the last valid input sequence.

bytes-written

Returned: an unsigned 64-bit integer.

the number of bytes stored in the output buffer (not including the terminating nul).

Procedure: find-program-in-path program ⇒ %return

Locates the first executable named program in the user’s path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or #f if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and #f otherwise. On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

program

Passed: a file name, as a string.

a program name in the GLib file name encoding

%return

Returned: a file name, as a string, or #f.

a newly-allocated string with the absolute path, or #f

Procedure: fopen filename mode ⇒ %return

A wrapper for the stdio fopen() function. The fopen() function opens a file and associates a new stream with it.

Because file descriptors are specific to the C library on Windows, and a file descriptor is part of the FILE struct, the FILE* returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the FILE* returned by this function cannot be passed to C library functions like fprintf() or fread().

See your C library manual for more details about fopen().

As close() and fclose() are part of the C library, this implies that it is currently impossible to close a file if the application C library and the C library used by GLib are different. Convenience functions like file-set-contents-full? avoid this problem.

Since GLib 2.86, the e option is supported in mode on all platforms. On Unix platforms it will set O_CLOEXEC on the opened file descriptor. On Windows platforms it will be converted to the ‘N‘ modifier. It is recommended to set e unconditionally, unless you know the returned file should be shared between this process and a new fork.

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode

Passed: a string.

a string describing the mode in which the file should be opened

%return

Returned: a foreign pointer, or #f.

A FILE* if the file was successfully opened, or #f if an error occurred

Procedure: format-size size ⇒ %return

Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (kB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.2 MB". The returned string is UTF-8, and may use a non-breaking space to separate the number and units, to ensure they aren’t separated when line wrapped.

The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).

This string should be freed with byte-array:free when not needed any longer.

See format-size-full for more options about how the size might be formatted.

size

Passed: an unsigned 64-bit integer.

a size in bytes

%return

Returned: a string.

a newly-allocated formatted string containing a human readable file size

Procedure: format-size-full size flags ⇒ %return

Formats a size.

This function is similar to format-size but allows for flags that modify the output. See <%GFormatSizeFlags>.

size

Passed: an unsigned 64-bit integer.

a size in bytes

flags

Passed: a <%GFormatSizeFlags>, or a list of its symbols, or one of them.

<%GFormatSizeFlags> to modify the output

%return

Returned: a string.

a newly-allocated formatted string containing a human readable file size

Procedure: free-sized mem size

Frees the memory pointed to by mem, assuming it is has the given size.

If mem is #f this is a no-op (and size is ignored).

It is an error if size doesn’t match the size passed when mem was allocated. size is passed to this function to allow optimizations in the allocator. If you don’t know the allocation size, use byte-array:free instead.

In case a GCC compatible compiler is used, this function may be used automatically via byte-array:free if the allocated size is known at compile time, since GLib 2.78.

mem

Passed: a foreign pointer, or a bytevector, or #f.

the memory to free

size

Passed: an unsigned 64-bit integer.

size of mem, in bytes

Procedure: freopen filename mode [stream] ⇒ %return

A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.

See your C library manual for more details about freopen().

Since GLib 2.86, the e option is supported in mode on all platforms. See the documentation for fopen for more details.

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode

Passed: a string.

a string describing the mode in which the file should be opened

stream

Passed, or left out: a foreign pointer, or a bytevector, or #f.

an existing stream which will be reused, or #f

%return

Returned: a foreign pointer, or #f.

A FILE* if the file was successfully opened, or #f if an error occurred.

Procedure: fsync fd ⇒ %return

A wrapper for the POSIX fsync() function. On Windows, _commit() will be used. On macOS, fcntl(F_FULLFSYNC) will be used. The fsync() function is used to synchronize a file’s in-core state with that of the disk.

This wrapper will handle retrying on EINTR.

See the C library manual for more details about fsync().

fd

Passed: a 32-bit integer.

a file descriptor

%return

Returned: a 32-bit integer.

0 on success, or -1 if an error occurred. The return value can be used exactly like the return value from fsync().

Procedure: get-application-name ⇒ %return

Gets a human-readable name for the application, as set by set-application-name. This name should be localized if possible, and is intended for display to the user. Contrast with get-prgname, which gets a non-localized name. If set-application-name has not been called, returns the result of get-prgname (which may be #f if set-prgname has also not been called).

%return

Returned: a string, or #f.

human-readable application name. May return #f

Procedure: get-charset ⇒ %return charset

Obtains the character set for the current locale; you might use this character set as an argument to convert, to convert from the current locale’s encoding to some other encoding. (Frequently locale-to-utf8 and locale-from-utf8 are nice shortcuts, though.)

On Windows the character set returned by this function is the so-called system default ANSI code-page. That is the character set used by the "narrow" versions of C library and Win32 functions that handle file names. It might be different from the character set used by the C library’s current locale.

On Linux, the character set is found by consulting nl_langinfo() if available. If not, the environment variables LC_ALL, LC_CTYPE, LANG and CHARSET are queried in order. nl_langinfo() returns the C locale if no locale has been loaded by setlocale().

The return value is #t if the locale’s encoding is UTF-8, in that case you can perhaps avoid calling convert.

The string returned in charset is not allocated, and should not be freed.

%return

Returned: a boolean.

#t if the returned charset is UTF-8

charset

Returned: a string.

return location for character set name, or #f.

Procedure: get-codeset ⇒ %return

Gets the character set for the current locale.

%return

Returned: a string.

a newly allocated string containing the name of the character set. This string must be freed with byte-array:free.

Procedure: get-console-charset ⇒ %return charset

Obtains the character set used by the console attached to the process, which is suitable for printing output to the terminal.

Usually this matches the result returned by get-charset, but in environments where the locale’s character set does not match the encoding of the console this function tries to guess a more suitable value instead.

On Windows the character set returned by this function is the output code page used by the console associated with the calling process. If the codepage can’t be determined (for example because there is no console attached) UTF-8 is assumed.

The return value is #t if the locale’s encoding is UTF-8, in that case you can perhaps avoid calling convert.

The string returned in charset is not allocated, and should not be freed.

%return

Returned: a boolean.

#t if the returned charset is UTF-8

charset

Returned: a string.

return location for character set name, or #f.

Procedure: get-current-dir ⇒ %return

Gets the current directory.

The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

Since GLib 2.40, this function will return the value of the "PWD" environment variable if it is set and it happens to be the same as the current directory. This can make a difference in the case that the current directory is the target of a symbolic link.

%return

Returned: a file name, as a string.

the current directory

Procedure: get-environ ⇒ %return

Gets the list of environment variables for the current process.

The list is #f terminated and each item in the list is of the form ’NAME=VALUE’.

This is equivalent to direct access to the ’environ’ global variable, except portable.

The return value is freshly allocated and it should be freed with strfreev when it is no longer needed.

%return

Returned: a vector, each a file name, as a string.

the list of environment variables

Procedure: get-filename-charsets ⇒ %return filename-charsets

Determines the preferred character sets used for filenames. The first character set from the charsets is the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, see filename-display-name.

On Unix, the character sets are determined by consulting the environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES. On Windows, the character set used in the GLib API is always UTF-8 and said environment variables have no effect.

G_FILENAME_ENCODING may be set to a comma-separated list of character set names. The special token @locale is taken to mean the character set for the current locale. If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the character set of the current locale is taken as the filename encoding. If neither environment variable is set, UTF-8 is taken as the filename encoding, but the character set of the current locale is also put in the list of encodings.

The returned charsets belong to GLib and must not be freed.

Note that on Unix, regardless of the locale character set or G_FILENAME_ENCODING value, the actual file names present on a system might be in any random encoding or just gibberish.

%return

Returned: a boolean.

#t if the filename encoding is UTF-8.

filename-charsets

Returned: a vector, each a string.

return location for the #f-terminated list of encoding names

Procedure: get-home-dir ⇒ %return

Gets the current user’s home directory.

As with most UNIX tools, this function will return the value of the HOME environment variable if it is set to an existing absolute path name, falling back to the passwd file in the case that it is unset.

If the path given in HOME is non-absolute, does not exist, or is not a directory, the result is undefined.

Before version 2.36 this function would ignore the HOME environment variable, taking the value from the passwd database instead. This was changed to increase the compatibility of GLib with other programs (and the XDG basedir specification) and to increase testability of programs based on GLib (by making it easier to run them from test frameworks).

If your program has a strong requirement for either the new or the old behaviour (and if you don’t wish to increase your GLib dependency to ensure that the new behaviour is in effect) then you should either directly check the HOME environment variable yourself or unset it before calling any functions in GLib.

%return

Returned: a file name, as a string.

the current user’s home directory

Procedure: get-host-name ⇒ %return

Return a name for the machine.

The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

The encoding of the returned string is UTF-8.

%return

Returned: a string.

the host name of the machine.

Procedure: get-language-names ⇒ %return

Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

For example, if LANGUAGE=de:en_US, then the returned list is "de", "en_US", "en", "C".

This function consults the environment variables LANGUAGE, LC_ALL, LC_MESSAGES and LANG to find the list of locales specified by the user.

%return

Returned: a vector, each a string.

a #f-terminated array of strings owned by GLib that must not be modified or freed.

Procedure: get-language-names-with-category category-name ⇒ %return

Computes a list of applicable locale names with a locale category name, which can be used to construct the fallback locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

This function consults the environment variables LANGUAGE, LC_ALL, category-name, and LANG to find the list of locales specified by the user.

get-language-names returns g_get_language_names_with_category("LC_MESSAGES").

category-name

Passed: a string.

a locale category name

%return

Returned: a vector, each a string.

a #f-terminated array of strings owned by the thread g_get_language_names_with_category was called from. It must not be modified or freed. It must be copied if planned to be used in another thread.

Procedure: get-locale-variants locale ⇒ %return

Returns a list of derived variants of locale, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable. This function handles territory, charset and extra locale modifiers. See ‘setlocale(3)‘ for information about locales and their format.

locale itself is guaranteed to be returned in the output.

For example, if locale is fr_BE, then the returned list is fr_BE, fr. If locale is en_GB.UTF-8@euro, then the returned list is en_GB.UTF-8@euro, en_GB.UTF-8, en_GB@euro, en_GB, en.UTF-8@euro, en.UTF-8, en@euro, en.

If you need the list of variants for the current locale, use get-language-names.

locale

Passed: a string.

a locale identifier

%return

Returned: a vector, each a string.

a newly allocated array of newly allocated strings with the locale variants. Free with strfreev.

Procedure: get-monotonic-time ⇒ %return

Queries the system monotonic time in microseconds.

The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.

We try to use the clock that corresponds as closely as possible to the passage of time as measured by system calls such as ‘poll()‘) but it may not always be possible to do this.

A more accurate version of this function exists. get-monotonic-time-ns returns the time in nanoseconds.

%return

Returned: a 64-bit integer.

the monotonic time, in microseconds

Procedure: get-monotonic-time-ns ⇒ %return

Queries the system monotonic time in nanoseconds.

The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.

We try to use the clock that corresponds as closely as possible to the passage of time as measured by system calls such as ‘poll()‘) but it may not always be possible to do this.

Another version of this function exists. get-monotonic-time returns the time in microseconds. If you want to support older GLib versions, it is an alternative.

%return

Returned: an unsigned 64-bit integer.

the monotonic time, in nanoseconds

Procedure: get-num-processors ⇒ %return

Determine the approximate number of threads that the system will schedule simultaneously for this process. This is intended to be used as a parameter to g_thread_pool_new() for CPU bound tasks and similar cases.

%return

Returned: an unsigned 32-bit integer.

Number of schedulable threads, always greater than 0

Procedure: get-os-info key-name ⇒ %return

Get information about the operating system.

On Linux this comes from the /etc/os-release file. On other systems, it may come from a variety of sources. You can either use the standard key names like G_OS_INFO_KEY_NAME or pass any UTF-8 string key name. For example, /etc/os-release provides a number of other less commonly used values that may be useful. No key is guaranteed to be provided, so the caller should always check if the result is #f.

key-name

Passed: a string.

a key for the OS info being requested, for example G_OS_INFO_KEY_NAME.

%return

Returned: a string, or #f.

The associated value for the requested key or #f if this information is not provided.

Procedure: get-prgname ⇒ %return

Gets the name of the program. This name should not be localized, in contrast to get-application-name.

If you are using <GApplication> the program name is set in application:run. In case of GDK or GTK it is set in gdk_init(), which is called by init and the "startup" handler. The program name is found by taking the last component of argv[0].

%return

Returned: a string, or #f.

the name of the program, or #f if it has not been set yet. The returned string belongs to GLib and must not be modified or freed.

Procedure: get-real-name ⇒ %return

Gets the real name of the user. This usually comes from the user’s entry in the passwd file. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string "Unknown" is returned.

%return

Returned: a file name, as a string.

the user’s real name.

Procedure: get-real-time ⇒ %return

Queries the system wall-clock time.

This is equivalent to the UNIX ‘gettimeofday()‘) function, but portable.

You should only use this call if you are actually interested in the real wall-clock time. get-monotonic-time is probably more useful for measuring intervals.

%return

Returned: a 64-bit integer.

the number of microseconds since 1970 UTC

Procedure: get-system-config-dirs ⇒ %return

Returns an ordered list of base directories in which to access system-wide configuration information.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the list of directories retrieved will be XDG_CONFIG_DIRS.

On Windows it follows XDG Base Directory Specification if XDG_CONFIG_DIRS is defined. If XDG_CONFIG_DIRS is undefined, the directory that contains application data for all users is used instead. A typical path is C:\Documents and Settings\All Users\Application Data. This folder is used for application data that is not user specific. For example, an application can store a spell-check dictionary, a database of clip art, or a log file in the FOLDERID_ProgramData folder. This information will not roam and is available to anyone using the computer.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a vector, each a file name, as a string.

a #f-terminated array of strings owned by GLib that must not be modified or freed.

Procedure: get-system-data-dirs ⇒ %return

Returns an ordered list of base directories in which to access system-wide application data.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification In this case the list of directories retrieved will be XDG_DATA_DIRS.

On Windows it follows XDG Base Directory Specification if XDG_DATA_DIRS is defined. If XDG_DATA_DIRS is undefined, the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for FOLDERID_ProgramData and FOLDERID_PublicDocuments.

Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application’s .exe file belongs to.

The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder’s name is "bin", its parent is used, otherwise the folder itself.

Note that on Windows the returned list can vary depending on where this function is called.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a vector, each a file name, as a string.

a #f-terminated array of strings owned by GLib that must not be modified or freed.

Procedure: get-tmp-dir ⇒ %return

Gets the directory to use for temporary files.

On UNIX, this is taken from the TMPDIR environment variable. If the variable is not set, P_tmpdir is used, as defined by the system C library. Failing that, a hard-coded default of "/tmp" is returned.

On Windows, the TEMP environment variable is used, with the root directory of the Windows installation (eg: "C:\") used as a default.

The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never #f or the empty string.

%return

Returned: a file name, as a string.

the directory to use for temporary files.

Procedure: get-user-cache-dir ⇒ %return

Returns a base directory in which to store non-essential, cached data specific to particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_CACHE_HOME.

On Windows it follows XDG Base Directory Specification if XDG_CACHE_HOME is defined. If XDG_CACHE_HOME is undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path is C:\Documents and Settings\username\Local Settings\Temporary Internet Files. See the documentation for ‘FOLDERID_InternetCache‘.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a file name, as a string.

a string owned by GLib that must not be modified or freed.

Procedure: get-user-config-dir ⇒ %return

Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_CONFIG_HOME.

On Windows it follows XDG Base Directory Specification if XDG_CONFIG_HOME is defined. If XDG_CONFIG_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for ‘FOLDERID_LocalAppData‘. Note that in this case on Windows it will be the same as what get-user-data-dir returns.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a file name, as a string.

a string owned by GLib that must not be modified or freed.

Procedure: get-user-data-dir ⇒ %return

Returns a base directory in which to access application data such as icons that is customized for a particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_DATA_HOME.

On Windows it follows XDG Base Directory Specification if XDG_DATA_HOME is defined. If XDG_DATA_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for ‘FOLDERID_LocalAppData‘. Note that in this case on Windows it will be the same as what get-user-config-dir returns.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a file name, as a string.

a string owned by GLib that must not be modified or freed.

Procedure: get-user-name ⇒ %return

Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.

%return

Returned: a file name, as a string.

the user name of the current user.

Procedure: get-user-runtime-dir ⇒ %return

Returns a directory that is unique to the current user on the local system.

This is determined using the mechanisms described in the XDG Base Directory Specification. This is the directory specified in the XDG_RUNTIME_DIR environment variable. In the case that this variable is not set, we return the value of get-user-cache-dir, after verifying that it exists.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a file name, as a string.

a string owned by GLib that must not be modified or freed.

Procedure: get-user-special-dir directory ⇒ %return

Returns the full path of a special directory using its logical id.

On UNIX this is done using the XDG special user directories. For compatibility with existing practise, directory-desktop falls back to $HOME/Desktop when XDG special user directories have not been set up.

Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

directory

Passed: a <%GUserDirectory>, or one of its symbols.

the logical id of special directory

%return

Returned: a file name, as a string, or #f.

the path to the specified special directory, or #f if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.

Procedure: get-user-state-dir ⇒ %return

Returns a base directory in which to store state files specific to particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_STATE_HOME.

On Windows it follows XDG Base Directory Specification if XDG_STATE_HOME is defined. If XDG_STATE_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for ‘FOLDERID_LocalAppData‘. Note that in this case on Windows it will be the same as what get-user-data-dir returns.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

%return

Returned: a file name, as a string.

a string owned by GLib that must not be modified or freed.

Procedure: getenv variable ⇒ %return

Returns the value of an environment variable.

On UNIX, the name and value are byte strings which might or might not be in some consistent character set and encoding. On Windows, they are in UTF-8. On Windows, in case the environment variable’s value contains references to other environment variables, they are expanded.

variable

Passed: a file name, as a string.

the environment variable to get

%return

Returned: a file name, as a string, or #f.

the value of the environment variable, or #f if the environment variable is not found. The returned string may be overwritten by the next call to getenv, setenv? or unsetenv.

Procedure: hash-table-add? hash-table [key] ⇒ %return

This is a convenience function for using a <GHashTable> as a set. It is equivalent to calling hash-table-replace? with key as both the key and the value.

In particular, this means that if key already exists in the hash table, then the old copy of key in the hash table is freed and key replaces it in the table.

When a hash table only ever contains keys that have themselves as the corresponding value it is able to be stored more efficiently. See the discussion in the section description.

Starting from GLib 2.40, this function returns a boolean value to indicate whether the newly added value was already in the hash table or not.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a key to insert

%return

Returned: a boolean.

#t if the key did not exist yet

Procedure: hash-table-contains? hash-table [key] ⇒ %return

Checks if key is in hash-table.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a key to check

%return

Returned: a boolean.

#t if key is in hash-table, #f otherwise.

Procedure: hash-table-destroy hash-table

Destroys all keys and values in the <GHashTable> and decrements its reference count by 1. If keys and/or values are dynamically allocated, you should either free them first or create the <GHashTable> with destroy notifiers using g_hash_table_new_full(). In the latter case the destroy functions you supplied will be called on all keys and values during the destruction phase.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

Procedure: hash-table-find hash-table predicate ⇒ %return

Calls the given function for key/value pairs in the <GHashTable> until predicate returns #t. The function is passed the key and value of each pair, and the given user-data parameter. The hash table may not be modified while iterating over it (you can’t add/remove items).

Note, that hash tables are really only optimized for forward lookups, i.e. hash-table-lookup. So code that frequently issues hash-table-find or hash-table-foreach (e.g. in the order of once per every entry in a hash table) should probably be reworked to use additional or different data structures for reverse lookups (keep in mind that an O(n) find/foreach operation issued for all n values in a hash table ends up needing O(n*n) operations).

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

predicate

Passed: a procedure.

function to test the key/value pairs for a certain property

See GHRFunc for how it is called.

%return

Returned: a foreign pointer, or #f.

The value of the first key/value pair is returned, for which predicate evaluates to #t. If no pair with the requested property is found, #f is returned.

user-data

Not passed: guile-gi supplies it.

user data to pass to the function

Procedure: hash-table-foreach hash-table func

Calls the given function for each of the key/value pairs in the <GHashTable>. The function is passed the key and value of each pair, and the given user-data parameter. The hash table may not be modified while iterating over it (you can’t add/remove items). To remove all items matching a predicate, use hash-table-foreach-remove.

The order in which hash-table-foreach iterates over the keys/values in the hash table is not defined.

See hash-table-find for performance caveats for linear order searches in contrast to hash-table-lookup.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

func

Passed: a procedure.

the function to call for each key/value pair

See GHFunc for how it is called.

user-data

Not passed: guile-gi supplies it.

user data to pass to the function

Procedure: hash-table-foreach-remove hash-table func ⇒ %return

Calls the given function for each key/value pair in the <GHashTable>. If the function returns #t, then the key/value pair is removed from the <GHashTable>. If you supplied key or value destroy functions when creating the <GHashTable>, they are used to free the memory allocated for the removed keys and values.

See GHashTableIter for an alternative way to loop over the key/value pairs in the hash table.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

func

Passed: a procedure.

the function to call for each key/value pair

See GHRFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the number of key/value pairs removed

user-data

Not passed: guile-gi supplies it.

user data to pass to the function

Procedure: hash-table-foreach-steal hash-table func ⇒ %return

Calls the given function for each key/value pair in the <GHashTable>. If the function returns #t, then the key/value pair is removed from the <GHashTable>, but no key or value destroy functions are called.

See GHashTableIter for an alternative way to loop over the key/value pairs in the hash table.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

func

Passed: a procedure.

the function to call for each key/value pair

See GHRFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the number of key/value pairs removed.

user-data

Not passed: guile-gi supplies it.

user data to pass to the function

Procedure: hash-table-insert? hash-table [key] [value] ⇒ %return

Inserts a new key and value into a <GHashTable>.

If the key already exists in the <GHashTable> its current value is replaced with the new value. If you supplied a value-destroy-func when creating the <GHashTable>, the old value is freed using that function. If you supplied a key-destroy-func when creating the <GHashTable>, the passed key is freed using that function.

Starting from GLib 2.40, this function returns a boolean value to indicate whether the newly added value was already in the hash table or not.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a key to insert

value

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to associate with the key

%return

Returned: a boolean.

#t if the key did not exist yet

Procedure: hash-table-lookup hash-table [key] ⇒ %return

Looks up a key in a <GHashTable>. Note that this function cannot distinguish between a key that is not present and one which is present and has the value #f. If you need this distinction, use hash-table-lookup-extended.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the key to look up

%return

Returned: a foreign pointer, or #f.

the associated value, or #f if the key is not found

Procedure: hash-table-lookup-extended hash-table [lookup-key] ⇒ %return orig-key value

Looks up a key in the <GHashTable>, returning the original key and the associated value and a gboolean which is #t if the key was found. This is useful if you need to free the memory allocated for the original key, for example before calling hash-table-remove?.

You can actually pass #f for lookup-key to test whether the #f key exists, provided the hash and equal functions of hash-table are #f-safe.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

lookup-key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the key to look up

%return

Returned: a boolean.

#t if the key was found in the <GHashTable>

orig-key

Returned: a foreign pointer, or #f.

return location for the original key

value

Returned: a foreign pointer, or #f.

return location for the value associated with the key

Procedure: hash-table-new-similar other-hash-table ⇒ %return

Creates a new <GHashTable> like g_hash_table_new_full() with a reference count of 1.

It inherits the hash function, the key equal function, the key destroy function, as well as the value destroy function, from other-hash-table.

The returned hash table will be empty; it will not contain the keys or values from other-hash-table.

other-hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

Another <GHashTable>

%return

Returned: a hash table, each key a foreign pointer and each value a foreign pointer.

a new <GHashTable>

Procedure: hash-table-ref hash-table ⇒ %return

Atomically increments the reference count of hash-table by one. This function is MT-safe and may be called from any thread.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a valid <GHashTable>

%return

Returned: a hash table, each key a foreign pointer and each value a foreign pointer.

the passed in <GHashTable>

Procedure: hash-table-remove-all hash-table

Removes all keys and their associated values from a <GHashTable>.

If the <GHashTable> was created using g_hash_table_new_full(), the keys and values are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

Procedure: hash-table-remove? hash-table [key] ⇒ %return

Removes a key and its associated value from a <GHashTable>.

If the <GHashTable> was created using g_hash_table_new_full(), the key and value are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the key to remove

%return

Returned: a boolean.

#t if the key was found and removed from the <GHashTable>

Procedure: hash-table-replace? hash-table [key] [value] ⇒ %return

Inserts a new key and value into a <GHashTable> similar to hash-table-insert?. The difference is that if the key already exists in the <GHashTable>, it gets replaced by the new key. If you supplied a value-destroy-func when creating the <GHashTable>, the old value is freed using that function. If you supplied a key-destroy-func when creating the <GHashTable>, the old key is freed using that function.

Starting from GLib 2.40, this function returns a boolean value to indicate whether the newly added value was already in the hash table or not.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a key to insert

value

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the value to associate with the key

%return

Returned: a boolean.

#t if the key did not exist yet

Procedure: hash-table-size hash-table ⇒ %return

Returns the number of elements contained in the <GHashTable>.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

%return

Returned: an unsigned 32-bit integer.

the number of key/value pairs in the <GHashTable>.

Procedure: hash-table-steal-all hash-table

Removes all keys and their associated values from a <GHashTable> without calling the key and value destroy functions.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

Procedure: hash-table-steal-extended hash-table [lookup-key] ⇒ %return stolen-key stolen-value

Looks up a key in the <GHashTable>, stealing the original key and the associated value and returning #t if the key was found. If the key was not found, #f is returned.

If found, the stolen key and value are removed from the hash table without calling the key and value destroy functions, and ownership is transferred to the caller of this method, as with hash-table-steal?. That is the case regardless whether stolen-key or stolen-value output parameters are requested.

You can pass #f for lookup-key, provided the hash and equal functions of hash-table are #f-safe.

The dictionary implementation optimizes for having all values identical to their keys, for example by using hash-table-add?. Before 2.82, when stealing both the key and the value from such a dictionary, the value was #f. Since 2.82, the returned value and key will be the same.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

lookup-key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the key to look up

%return

Returned: a boolean.

#t if the key was found in the <GHashTable>

stolen-key

Returned: a foreign pointer, or #f.

return location for the original key

stolen-value

Returned: a foreign pointer, or #f.

return location for the value associated with the key

Procedure: hash-table-steal? hash-table [key] ⇒ %return

Removes a key and its associated value from a <GHashTable> without calling the key and value destroy functions.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a <GHashTable>

key

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the key to remove

%return

Returned: a boolean.

#t if the key was found and removed from the <GHashTable>

Procedure: hash-table-unref hash-table

Atomically decrements the reference count of hash-table by one. If the reference count drops to 0, all keys and values will be destroyed, and all memory allocated by the hash table is released. This function is MT-safe and may be called from any thread.

hash-table

Passed: a hash table, each key a foreign pointer and each value a foreign pointer.

a valid <GHashTable>

Procedure: hostname-is-ascii-encoded? hostname ⇒ %return

Tests if hostname contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returns #t, you should decode the hostname with hostname-to-unicode before displaying it to the user.

Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for hostname-is-non-ascii? and hostname-is-ascii-encoded? to both return #t for a name.

hostname

Passed: a string.

a hostname

%return

Returned: a boolean.

#t if hostname contains any ASCII-encoded segments.

Procedure: hostname-is-ip-address? hostname ⇒ %return

Tests if hostname is the string form of an IPv4 or IPv6 address. (Eg, "192.168.0.1".)

Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).

hostname

Passed: a string.

a hostname (or IP address in string form)

%return

Returned: a boolean.

#t if hostname is an IP address

Procedure: hostname-is-non-ascii? hostname ⇒ %return

Tests if hostname contains Unicode characters. If this returns #t, you need to encode the hostname with hostname-to-ascii before using it in non-IDN-aware contexts.

Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for hostname-is-non-ascii? and hostname-is-ascii-encoded? to both return #t for a name.

hostname

Passed: a string.

a hostname

%return

Returned: a boolean.

#t if hostname contains any non-ASCII characters

Procedure: hostname-to-ascii hostname ⇒ %return

Converts hostname to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.

hostname

Passed: a string.

a valid UTF-8 or ASCII hostname

%return

Returned: a string, or #f.

an ASCII hostname, which must be freed, or #f if hostname is in some way invalid.

Procedure: hostname-to-unicode hostname ⇒ %return

Converts hostname to its canonical presentation form; a UTF-8 string in Unicode normalization form C, containing no uppercase letters, no forbidden characters, and no ASCII-encoded segments, and not ending with a trailing dot.

Of course if hostname is not an internationalized hostname, then the canonical presentation form will be entirely ASCII.

hostname

Passed: a string.

a valid UTF-8 or ASCII hostname

%return

Returned: a string, or #f.

a UTF-8 hostname, which must be freed, or #f if hostname is in some way invalid.

Procedure: idle-add priority function ⇒ %return

Adds a function to be called whenever there are no higher priority events pending to the default main loop.

The function is given the default idle priority, GLib.PRIORITY_DEFAULT_IDLE. If the function returns GLib.SOURCE_REMOVE it is automatically removed from the list of event sources and will not be called again.

See main loop memory management for details on how to handle the return value and memory management of data.

This internally creates a main loop source using idle-source-new and attaches it to the global <GMainContext> using source:attach, so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

priority

Passed: a 32-bit integer.

function

Passed: a procedure.

function to call

See GSourceFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the ID (greater than 0) of the event source

notify

Not passed: guile-gi supplies it.

data

Not passed: guile-gi supplies it.

data to pass to function

Procedure: idle-remove-by-data? [data] ⇒ %return

Removes the idle function with the given data.

data

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the data for the idle source’s callback.

%return

Returned: a boolean.

true if an idle source was found and removed, false otherwise

Procedure: idle-source-new ⇒ %return

Creates a new idle source.

The source will not initially be associated with any <GMainContext> and must be added to one with source:attach before it will be executed. Note that the default priority for idle sources is GLib.PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of GLib.PRIORITY_DEFAULT.

%return

Returned: a <GSource>.

the newly-created idle source

Procedure: int-equal? v1 v2 ⇒ %return

Compares the two gint values being pointed to and returns #t if they are equal. It can be passed to g_hash_table_new() as the key-equal-func parameter, when using non-#f pointers to integers as keys in a <GHashTable>.

Note that this function acts on pointers to gint, not on gint directly: if your hash table’s keys are of the form GINT_TO_POINTER (n), use direct-equal? instead.

v1

Passed: a foreign pointer, or a bytevector.

a pointer to a gint key

v2

Passed: a foreign pointer, or a bytevector.

a pointer to a gint key to compare with v1

%return

Returned: a boolean.

#t if the two keys match.

Procedure: int-hash v ⇒ %return

Converts a pointer to a gint to a hash value. It can be passed to g_hash_table_new() as the hash-func parameter, when using non-#f pointers to integer values as keys in a <GHashTable>.

Note that this function acts on pointers to gint, not on gint directly: if your hash table’s keys are of the form GINT_TO_POINTER (n), use direct-hash instead.

v

Passed: a foreign pointer, or a bytevector.

a pointer to a gint key

%return

Returned: an unsigned 32-bit integer.

a hash value corresponding to the key.

Procedure: int64-equal? v1 v2 ⇒ %return

Compares the two gint64 values being pointed to and returns #t if they are equal. It can be passed to g_hash_table_new() as the key-equal-func parameter, when using non-#f pointers to 64-bit integers as keys in a <GHashTable>.

v1

Passed: a foreign pointer, or a bytevector.

a pointer to a gint64 key

v2

Passed: a foreign pointer, or a bytevector.

a pointer to a gint64 key to compare with v1

%return

Returned: a boolean.

#t if the two keys match.

Procedure: int64-hash v ⇒ %return

Converts a pointer to a gint64 to a hash value.

It can be passed to g_hash_table_new() as the hash-func parameter, when using non-#f pointers to 64-bit integer values as keys in a <GHashTable>.

v

Passed: a foreign pointer, or a bytevector.

a pointer to a gint64 key

%return

Returned: an unsigned 32-bit integer.

a hash value corresponding to the key.

Procedure: intern-static-string [string] ⇒ %return

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). intern-static-string does not copy the string, therefore string must not be freed or modified.

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

string

Passed, or left out: a string, or #f.

a static string

%return

Returned: a string.

a canonical representation for the string

Procedure: intern-string [string] ⇒ %return

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

string

Passed, or left out: a string, or #f.

a string

%return

Returned: a string.

a canonical representation for the string

Procedure: io-add-watch channel priority condition func ⇒ %return

Adds the <GIOChannel> into the default main loop context with the default priority.

channel

Passed: a <GIOChannel>.

a <GIOChannel>

priority

Passed: a 32-bit integer.

condition

Passed: a <GIOCondition>, or a list of its symbols, or one of them.

the condition to watch for

func

Passed: a procedure.

the function to call when the condition is satisfied

See GIOFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the event source id

notify

Not passed: guile-gi supplies it.

user-data

Not passed: guile-gi supplies it.

user data to pass to func

Procedure: io-channel-error-from-errno en ⇒ %return

Converts an errno error number to a <%GIOChannelError>.

en

Passed: a 32-bit integer.

an errno error number, e.g. EINVAL

%return

Returned: a <%GIOChannelError>.

a <%GIOChannelError> error number, e.g. inval.

Procedure: io-channel-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: io-create-watch channel condition ⇒ %return

Creates a <GSource> that’s dispatched when condition is met for the given channel. For example, if condition is in, the source will be dispatched when there’s data available for reading.

The callback function invoked by the <GSource> should be added with source:set-callback, but it has type GIOFunc (not GSourceFunc).

io-add-watch is a simpler interface to this same functionality, for the case where you want to add the source to the default main loop context at the default priority.

On Windows, polling a <GSource> created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

channel

Passed: a <GIOChannel>.

a <GIOChannel> to watch

condition

Passed: a <GIOCondition>, or a list of its symbols, or one of them.

conditions to watch for

%return

Returned: a <GSource>.

a new <GSource>

Procedure: key-file-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: listenv ⇒ %return

Gets the names of all variables set in the environment.

Programs that want to be portable to Windows should typically use this function and getenv instead of using the environ array from the C library directly. On Windows, the strings in the environ array are in system codepage encoding, while in most of the typical use cases for environment variables in GLib-using programs you want the UTF-8 encoding that this function and getenv provide.

%return

Returned: a vector, each a file name, as a string.

a #f-terminated list of strings which must be freed with strfreev.

Procedure: locale-from-utf8 utf8string len ⇒ %return bytes-read

Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale. On Windows this means the system codepage.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error illegal-sequence. Use convert to convert input that may contain embedded nul characters.

utf8string

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

the length of the string, or -1 if the string is nul-terminated.

%return

Returned: a bytevector.

A newly-allocated buffer containing the converted string, or #f on an error, and error will be set.

bytes-read

Returned: an unsigned 64-bit integer.

location to store the number of bytes in the input string that were successfully converted, or #f. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error illegal-sequence occurs, the value stored will be the byte offset after the last valid input sequence.

bytes-written

Not returned: it is the length of %return.

the number of bytes stored in the output buffer (not including the terminating nul).

Procedure: locale-to-utf8 opsysstring ⇒ %return bytes-read bytes-written

Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.

If the source encoding is not UTF-8 and the conversion output contains a nul character, the error embedded-nul is set and the function returns #f. If the source encoding is UTF-8, an embedded nul character is treated with the illegal-sequence error for backward compatibility with earlier versions of this library. Use convert to produce output that may contain embedded nul characters.

opsysstring

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

a string in the encoding of the current locale. On Windows this means the system codepage.

%return

Returned: a string.

The converted string, or #f on an error.

bytes-read

Returned: an unsigned 64-bit integer.

location to store the number of bytes in the input string that were successfully converted, or #f. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error illegal-sequence occurs, the value stored will be the byte offset after the last valid input sequence.

bytes-written

Returned: an unsigned 64-bit integer.

the number of bytes stored in the output buffer (not including the terminating nul).

len

Not passed: guile-gi gives the length of opsysstring.

the length of the string, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)

Procedure: log-default-handler log-domain log-level [message] [unused-data]

The default log handler set up by GLib; GLib.log_set_default_handler allows to install an alternate default log handler.

This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls GLib.BREAKPOINT. It automatically prints a new-line character after the message, so one does not need to be manually included in message.

The behavior of this log handler can be influenced by a number of environment variables:

  • G_MESSAGES_PREFIXED: A :-separated list of log levels for which messages should be prefixed by the program name and PID of the application.
  • G_MESSAGES_DEBUG: A space-separated list of log domains for which debug and informational messages are printed. By default these messages are not printed. If you need to set the allowed domains at runtime, use log-writer-default-set-debug-domains.
  • DEBUG_INVOCATION: If set to 1, this is equivalent to G_MESSAGES_DEBUG=all. DEBUG_INVOCATION is a standard environment variable set by systemd to prompt debug output. (Since: 2.84)

stderr is used for levels GLib.LogLevelFlags.LEVEL_ERROR, GLib.LogLevelFlags.LEVEL_CRITICAL, GLib.LogLevelFlags.LEVEL_WARNING and GLib.LogLevelFlags.LEVEL_MESSAGE. stdout is used for the rest, unless stderr was requested by log-writer-default-set-use-stderr.

This has no effect if structured logging is enabled; see Using Structured Logging.

log-domain

Passed: a string, or #f.

the log domain of the message, or NULL for the default "" application domain

log-level

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

the level of the message

message

Passed, or left out: a string, or #f.

the message

unused-data

Passed, or left out: a foreign pointer, or a bytevector, or #f.

data passed from GLib.log which is unused

Procedure: log-get-always-fatal ⇒ %return

Gets the current fatal mask.

This is mostly used by custom log writers to make fatal messages (fatal-warnings, fatal-criticals) work as expected, when using the G_DEBUG environment variable (see Running GLib Applications).

An example usage is shown below:

static GLogWriterOutput
my_custom_log_writer_fn (GLogLevelFlags log_level,
                         const GLogField *fields,
                         gsize n_fields,
                         gpointer user_data)
{

   // abort if the message was fatal
   if (log_level & g_log_get_always_fatal ())
     g_abort ();

   // custom log handling code
   ...
   ...

   // success
   return G_LOG_WRITER_HANDLED;
}
%return

Returned: a <%GLogLevelFlags>.

the current fatal mask

Procedure: log-get-debug-enabled? ⇒ %return

Return whether debug output from the GLib logging system is enabled.

Note that this should not be used to conditionalise calls to GLib.debug or other logging functions; it should only be used from <GLogWriterFunc> implementations.

Note also that the value of this does not depend on G_MESSAGES_DEBUG, nor DEBUG_INVOCATION, nor log-writer-default-set-debug-domains; see the docs for log-set-debug-enabled.

%return

Returned: a boolean.

TRUE if debug output is enabled, FALSE otherwise

Procedure: log-remove-handler log-domain handler-id

Removes the log handler.

This has no effect if structured logging is enabled; see Using Structured Logging.

log-domain

Passed: a string.

the log domain

handler-id

Passed: an unsigned 32-bit integer.

the ID of the handler, which was returned in log-set-handler

Procedure: log-set-always-fatal fatal-mask ⇒ %return

Sets the message levels which are always fatal, in any log domain.

When a message with any of these levels is logged the program terminates. You can only set the levels defined by GLib to be fatal. GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

Structured log messages (using GLib.log_structured and GLib.log_structured_array) are fatal only if the default log writer is used; otherwise it is up to the writer function to determine which log messages are fatal. See Using Structured Logging.

fatal-mask

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

the mask containing bits set for each level of error which is to be fatal

%return

Returned: a <%GLogLevelFlags>.

the old fatal mask

Procedure: log-set-debug-enabled enabled

Enable or disable debug output from the GLib logging system for all domains.

This value interacts disjunctively with G_MESSAGES_DEBUG, DEBUG_INVOCATION and log-writer-default-set-debug-domains — if any of them would allow a debug message to be outputted, it will be.

Note that this should not be used from within library code to enable debug output — it is intended for external use.

enabled

Passed: a boolean.

TRUE to enable debug output, FALSE otherwise

Procedure: log-set-fatal-mask log-domain fatal-mask ⇒ %return

Sets the log levels which are fatal in the given domain.

GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

This has no effect on structured log messages (using GLib.log_structured or GLib.log_structured_array). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using GLib.log_set_writer_func. See Using Structured Logging.

This function is mostly intended to be used with GLib.LogLevelFlags.LEVEL_CRITICAL. You should typically not set GLib.LogLevelFlags.LEVEL_WARNING, GLib.LogLevelFlags.LEVEL_MESSAGE, GLib.LogLevelFlags.LEVEL_INFO or GLib.LogLevelFlags.LEVEL_DEBUG as fatal except inside of test programs.

log-domain

Passed: a string.

the log domain

fatal-mask

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

the new fatal mask

%return

Returned: a <%GLogLevelFlags>.

the old fatal mask for the log domain

Procedure: log-set-handler log-domain log-levels log-func ⇒ %return

Sets the log handler for a domain and a set of log levels.

To handle fatal and recursive messages the log-levels parameter must be combined with the GLib.LogLevelFlags.FLAG_FATAL and GLib.LogLevelFlags.FLAG_RECURSION bit flags.

Note that since the GLib.LogLevelFlags.LEVEL_ERROR log level is always fatal, if you want to set a handler for this log level you must combine it with GLib.LogLevelFlags.FLAG_FATAL.

This has no effect if structured logging is enabled; see Using Structured Logging.

The log_domain parameter can be set to NULL or an empty string to use the default application domain.

Here is an example for adding a log handler for all warning messages in the default domain:

g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
                   | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

This example adds a log handler for all critical messages from GTK:

g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
                   | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

This example adds a log handler for all messages from GLib:

g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
                   | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
log-domain

Passed: a string, or #f.

the log domain application domain

log-levels

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the GLib.LogLevelFlags.FLAG_FATAL and GLib.LogLevelFlags.FLAG_RECURSION bit flags.

log-func

Passed: a procedure.

the log handler function

See GLogFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the id of the new handler

destroy

Not passed: guile-gi supplies it.

user-data

Not passed: guile-gi supplies it.

data passed to the log handler

Procedure: log-variant log-domain log-level fields

Log a message with structured data, accepting the data within a <GVariant>.

This version is especially useful for use in other languages, via introspection.

The only mandatory item in the fields dictionary is the "MESSAGE" which must contain the text shown to the user.

The values in the fields dictionary are likely to be of type G_VARIANT_TYPE_STRING. Array of bytes (G_VARIANT_TYPE_BYTESTRING) is also supported. In this case the message is handled as binary and will be forwarded to the log writer as such. The size of the array should not be higher than G_MAXSSIZE. Otherwise it will be truncated to this size. For other types variant:print will be used to convert the value into a string.

For more details on its usage and about the parameters, see GLib.log_structured.

log-domain

Passed: a string, or #f.

log domain, usually G_LOG_DOMAIN

log-level

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

log level, either from <%GLogLevelFlags>, or a user-defined level

fields

Passed: a <GVariant>.

a dictionary (<GVariant> of the type G_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.

Procedure: log-writer-default-set-debug-domains [domains]

Reset the list of domains to be logged, that might be initially set by the G_MESSAGES_DEBUG or DEBUG_INVOCATION environment variables.

This function is thread-safe.

domains

Passed, or left out: a string, or #f.

NULL-terminated array with domains to be printed. NULL or an array with no values means none. Array with a single value "all" means all.

Procedure: log-writer-default-set-use-stderr use-stderr

Configure whether the built-in log functions will output all log messages to stderr.

The built-in log functions are log-default-handler for the old-style API, and both GLib.log_writer_default and GLib.log_writer_standard_streams for the structured API.

By default, log messages of levels GLib.LogLevelFlags.LEVEL_INFO and GLib.LogLevelFlags.LEVEL_DEBUG are sent to stdout, and other log messages are sent to stderr. This is problematic for applications that intend to reserve stdout for structured output such as JSON or XML.

This function sets global state. It is not thread-aware, and should be called at the very start of a program, before creating any other threads or creating objects that could create worker threads of their own.

use-stderr

Passed: a boolean.

If TRUE, use stderr for log messages that would normally have appeared on stdout

Procedure: log-writer-default-would-drop? log-level [log-domain] ⇒ %return

Check whether GLib.log_writer_default and log-default-handler would ignore a message with the given domain and level.

As with log-default-handler, this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or by log-writer-default-set-debug-domains.

This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:

if (g_log_writer_default_would_drop (log_level, log_domain))
  return G_LOG_WRITER_HANDLED;
]|

or to skip an expensive computation if it is only needed for a debugging
message, and `G_MESSAGES_DEBUG` and `DEBUG_INVOCATION` are not set:

c if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN)) { g_autofree gchar *result = expensive_computation (my_object);

g_debug ("my_object result: s", result); } “‘

log-level

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

log level, either from <%GLogLevelFlags>, or a user-defined level

log-domain

Passed, or left out: a string, or #f.

log domain

%return

Returned: a boolean.

TRUE if the log message would be dropped by GLib’s default log handlers

Procedure: log-writer-is-journald? output-fd ⇒ %return

Check whether the given output-fd file descriptor is a connection to the systemd journal, or something else (like a log file or stdout or stderr).

Invalid file descriptors are accepted and return FALSE, which allows for the following construct without needing any additional error handling:

is_journald = g_log_writer_is_journald (fileno (stderr));
output-fd

Passed: a 32-bit integer.

output file descriptor to check

%return

Returned: a boolean.

TRUE if output-fd points to the journal, FALSE otherwise

Procedure: log-writer-supports-color? output-fd ⇒ %return

Check whether the given output-fd file descriptor supports ANSI color escape sequences.

If so, they can safely be used when formatting log messages.

output-fd

Passed: a 32-bit integer.

output file descriptor to check

%return

Returned: a boolean.

TRUE if ANSI color escapes are supported, FALSE otherwise

Procedure: main-context-default ⇒ %return

Returns the global-default main context.

This is the main context used for main loop functions when a main loop is not explicitly specified, and corresponds to the ‘main’ main loop. See also main-context:get-thread-default.

%return

Returned: a <GMainContext>.

the global-default main context.

Procedure: main-context-get-thread-default ⇒ %return

Gets the thread-default main context for this thread.

Asynchronous operations that want to be able to be run in contexts other than the default one should call this method or main-context:ref-thread-default to get a <GMainContext> to add their <GSource>s to. (Note that even in single-threaded programs applications may sometimes want to temporarily push a non-default context, so it is not safe to assume that this will always return NULL if you are running in the default thread.)

If you need to hold a reference on the context, use main-context:ref-thread-default instead.

%return

Returned: a <GMainContext>, or #f.

the thread-default main context, or NULL if the thread-default context is the global-default main context

Procedure: main-context-ref-thread-default ⇒ %return

Gets a reference to the thread-default <GMainContext> for this thread

This is the same as main-context:get-thread-default, but it also adds a reference to the returned main context with main-context:ref. In addition, unlike main-context:get-thread-default, if the thread-default context is the global-default context, this will return that <GMainContext> (with a ref added to it) rather than returning NULL.

%return

Returned: a <GMainContext>.

the thread-default main context

Procedure: main-current-source ⇒ %return

Returns the currently firing source for this thread.

%return

Returned: a <GSource>, or #f.

the currently firing source, or NULL if none is firing

Procedure: main-depth ⇒ %return

Returns the depth of the stack of calls to main-context:dispatch on any <GMainContext> in the current thread.

That is, when called from the top level, it gives 0. When called from within a callback from main-context:iteration? (or main-loop:run, etc.) it returns 1. When called from within a callback to a recursive call to main-context:iteration?, it returns 2. And so forth.

This function is useful in a situation like the following: Imagine an extremely simple ‘garbage collected’ system.

static GList *free_list;

gpointer
allocate_memory (gsize size)
{
  gpointer result = g_malloc (size);
  free_list = g_list_prepend (free_list, result);
  return result;
}

void
free_allocated_memory (void)
{
  GList *l;
  for (l = free_list; l; l = l->next);
    g_free (l->data);
  g_list_free (free_list);
  free_list = NULL;
 }

[...]

while (TRUE);
 {
   g_main_context_iteration (NULL, TRUE);
   free_allocated_memory();
  }

This works from an application, however, if you want to do the same thing from a library, it gets more difficult, since you no longer control the main loop. You might think you can simply use an idle function to make the call to free_allocated_memory(), but that doesn’t work, since the idle function could be called from a recursive callback. This can be fixed by using main-depth

gpointer
allocate_memory (gsize size)
{
  FreeListBlock *block = g_new (FreeListBlock, 1);
  block->mem = g_malloc (size);
  block->depth = g_main_depth ();
  free_list = g_list_prepend (free_list, block);
  return block->mem;
}

void
free_allocated_memory (void)
{
  GList *l;
  
  int depth = g_main_depth ();
  for (l = free_list; l; );
    {
      GList *next = l->next;
      FreeListBlock *block = l->data;
      if (block->depth > depth)
        {
          g_free (block->mem);
          g_free (block);
          free_list = g_list_delete_link (free_list, l);
        }
              
      l = next;
    }
  }

There is a temptation to use main-depth to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item’s callback return immediately and do nothing if main-depth returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you’ll find yourself adding these checks all over your code, since there are doubtless many, many things that the user could do. Instead, you can use the following techniques:

  1. Use widget:set-sensitive or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.
  1. Avoid main loop recursion in situations where you can’t handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.
%return

Returned: a 32-bit integer.

the main loop recursion level in the current thread

Procedure: malloc n-bytes ⇒ %return

Allocates n-bytes bytes of memory. If n-bytes is 0 it returns #f.

If the allocation fails (because the system is out of memory), the program is terminated.

n-bytes

Passed: an unsigned 64-bit integer.

the number of bytes to allocate

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated memory

Procedure: malloc-n n-blocks n-block-bytes ⇒ %return

This function is similar to malloc, allocating (n-blocks * n-block-bytes) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated memory

Procedure: malloc0 n-bytes ⇒ %return

Allocates n-bytes bytes of memory, initialized to 0’s. If n-bytes is 0 it returns #f.

If the allocation fails (because the system is out of memory), the program is terminated.

n-bytes

Passed: an unsigned 64-bit integer.

the number of bytes to allocate

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated memory

Procedure: malloc0-n n-blocks n-block-bytes ⇒ %return

This function is similar to malloc0, allocating (n-blocks * n-block-bytes) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated memory

Procedure: markup-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: markup-escape-text text length ⇒ %return

Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.

Note that this function doesn’t protect whitespace and line endings from being processed according to the XML rules for normalization of line endings and attribute values.

Note also that this function will produce character references in the range of &#x1; ... &#x1f; for all control sequences except for tabstop, newline and carriage return. The character references in this range are not valid XML 1.0, but they are valid XML 1.1 and will be accepted by the GMarkup parser.

text

Passed: a string.

some valid UTF-8 text

length

Passed: a 64-bit integer.

length of text in bytes, or -1 if the text is nul-terminated

%return

Returned: a string.

a newly allocated string with the escaped text

Procedure: memdup2 mem byte-size ⇒ %return

Allocates byte-size bytes of memory, and copies byte-size bytes into it from mem. If mem is NULL it returns NULL.

This replaces GLib.memdup, which was prone to integer overflows when converting the argument from a gsize to a guint.

mem

Passed: a foreign pointer, or a bytevector, or #f.

the memory to copy

byte-size

Passed: an unsigned 64-bit integer.

the number of bytes to copy

%return

Returned: a foreign pointer, or #f.

a pointer to the newly-allocated copy of the memory

Procedure: mkdir filename mode ⇒ %return

A wrapper for the POSIX mkdir() function. The mkdir() function attempts to create a directory with the given name and permissions. The mode argument is ignored on Windows.

See your C library manual for more details about mkdir().

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode

Passed: a 32-bit integer.

permissions to use for the newly created directory

%return

Returned: a 32-bit integer.

0 if the directory was successfully created, -1 if an error occurred

Procedure: mkdir-with-parents pathname mode ⇒ %return

Create a directory if it doesn’t already exist. Create intermediate parent directories as needed, too.

pathname

Passed: a file name, as a string.

a pathname in the GLib file name encoding

mode

Passed: a 32-bit integer.

permissions to use for newly created directories

%return

Returned: a 32-bit integer.

0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.

Procedure: nullify-pointer nullify-location

Set the pointer at the specified location to #f.

nullify-location

Passed: a foreign pointer, or a bytevector.

the memory address of the pointer.

Procedure: number-parser-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: on-error-query prg-name

Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.


#include <glib.h>

static void
log_handler (const gchar   *log_domain,
             GLogLevelFlags log_level,
             const gchar   *message,
             gpointer       user_data)
{
  g_log_default_handler (log_domain, log_level, message, user_data);

  g_on_error_query (MY_PROGRAM_NAME);
}

int
main (int argc, char *argv[])
{
  g_log_set_handler (MY_LOG_DOMAIN,
                     G_LOG_LEVEL_WARNING |
                     G_LOG_LEVEL_ERROR |
                     G_LOG_LEVEL_CRITICAL,
                     log_handler,
                     NULL);
  ...

If "[E]xit" is selected, the application terminates with a call to _exit(0).

If "[S]tack" trace is selected, on-error-stack-trace is called. This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

If "[P]roceed" is selected, the function returns.

This function may cause different actions on non-UNIX platforms.

On Windows consider using the G_DEBUGGER environment variable (see Running GLib Applications) and calling on-error-stack-trace instead.

prg-name

Passed: a string.

the program name, needed by gdb for the "[S]tack trace" option. If prg-name is #f, get-prgname is called to get the program name (which will work correctly if gdk_init() or init has been called)

Procedure: on-error-stack-trace [prg-name]

Invokes gdb, which attaches to the current process and shows a stack trace. Called by on-error-query when the "[S]tack trace" option is selected. You can get the current process’s program name with get-prgname, assuming that you have called init or gdk_init().

This function may cause different actions on non-UNIX platforms.

When running on Windows, this function is not called by on-error-query. If called directly, it will raise an exception, which will crash the program. If the G_DEBUGGER environment variable is set, a debugger will be invoked to attach and handle that exception (see Running GLib Applications).

prg-name

Passed, or left out: a string, or #f.

the program name, needed by gdb for the "[S]tack trace" option, or NULL to use a default string

Procedure: once-init-enter! location ⇒ %return location

Function to be called when starting a critical initialization section. The argument location must point to a static 0-initialized variable that will be set to a value other than 0 at the end of the initialization section. In combination with once-init-leave! and the unique address value-location, it can be ensured that an initialization section will be executed only once during a program’s life time, and that concurrent threads are blocked until initialization completed. To be used in constructs like this:


  static gsize initialization_value = 0;

  if (g_once_init_enter (&initialization_value))
    {
      gsize setup_value = 42; // initialization code here

      g_once_init_leave (&initialization_value, setup_value);
    }

  // use initialization_value here

While location has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

location

Passed: a foreign pointer, or a bytevector. Returned: a foreign pointer.

location of a static initializable variable containing 0

%return

Returned: a boolean.

#t if the initialization section should be entered, #f and blocks otherwise

Procedure: once-init-enter-impl? location ⇒ %return
location

Passed: an unsigned 64-bit integer.

%return

Returned: a boolean.

Procedure: once-init-enter-pointer? location ⇒ %return

This functions behaves in the same way as once-init-enter!, but can can be used to initialize pointers (or guintptr) instead of gsize.


  static MyStruct *interesting_struct = NULL;

  if (g_once_init_enter_pointer (&interesting_struct))
    {
      MyStruct *setup_value = allocate_my_struct (); // initialization code here

      g_once_init_leave_pointer (&interesting_struct, g_steal_pointer (&setup_value));
    }

  // use interesting_struct here
location

Passed: a foreign pointer, or a bytevector.

location of a static initializable variable containing NULL

%return

Returned: a boolean.

#t if the initialization section should be entered, #f and blocks otherwise

Procedure: once-init-leave! location result ⇒ location

Counterpart to once-init-enter!. Expects a location of a static 0-initialized initialization variable, and an initialization value other than 0. Sets the variable to the initialization value, and releases concurrent threads blocking in once-init-enter! on this initialization variable.

While location has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

location

Passed: a foreign pointer, or a bytevector. Returned: a foreign pointer.

location of a static initializable variable containing 0

result

Passed: an unsigned 64-bit integer.

new non-0 value for *value_location

Procedure: once-init-leave-pointer location [result]

Counterpart to once-init-enter-pointer?. Expects a location of a static NULL-initialized initialization variable, and an initialization value other than NULL. Sets the variable to the initialization value, and releases concurrent threads blocking in once-init-enter-pointer? on this initialization variable.

This functions behaves in the same way as once-init-leave!, but can be used to initialize pointers (or guintptr) instead of gsize.

location

Passed: a foreign pointer, or a bytevector.

location of a static initializable variable containing NULL

result

Passed, or left out: a foreign pointer, or a bytevector, or #f.

new non-NULL value for *location

Procedure: option-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: path-buf-equal? v1 v2 ⇒ %return

Compares two path buffers for equality and returns TRUE if they are equal.

The paths inside the path buffers are not going to be normalized, so X/Y/Z/A/.., X/./Y/Z and X/Y/Z are not going to be considered equal.

This function can be passed to g_hash_table_new() as the key_equal_func parameter.

v1

Passed: a foreign pointer, or a bytevector.

a path buffer to compare

v2

Passed: a foreign pointer, or a bytevector.

a path buffer to compare

%return

Returned: a boolean.

TRUE if the two path buffers are equal, and FALSE otherwise

Procedure: path-get-basename file-name ⇒ %return

Gets the last component of the filename.

If file-name ends with a directory separator it gets the component before the last slash. If file-name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file-name is empty, it gets ".".

file-name

Passed: a file name, as a string.

the name of the file

%return

Returned: a file name, as a string.

a newly allocated string containing the last component of the filename

Procedure: path-get-dirname file-name ⇒ %return

Gets the directory components of a file name. For example, the directory component of /usr/bin/test is /usr/bin. The directory component of / is /.

If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

file-name

Passed: a file name, as a string.

the name of the file

%return

Returned: a file name, as a string.

the directory components of the file

Procedure: path-is-absolute? file-name ⇒ %return

Returns #t if the given file-name is an absolute file name. Note that this is a somewhat vague concept on Windows.

On POSIX systems, an absolute file name is well-defined. It always starts from the single root directory. For example "/usr/local".

On Windows, the concepts of current drive and drive-specific current directory introduce vagueness. This function interprets as an absolute file name one that either begins with a directory separator such as "\Users\tml" or begins with the root on a drive, for example "C:\Windows". The first case also includes UNC paths such as "\\\\myserver\docs\foo". In all cases, either slashes or backslashes are accepted.

Note that a file name relative to the current drive root does not truly specify a file uniquely over time and across processes, as the current drive is a per-process value and can be changed.

File names relative the current directory on some specific drive, such as "D:foo/bar", are not interpreted as absolute by this function, but they obviously are not relative to the normal current directory as returned by getcwd() or get-current-dir either. Such paths should be avoided, or need to be handled using Windows-specific code.

file-name

Passed: a file name, as a string.

a file name

%return

Returned: a boolean.

#t if file-name is absolute

Procedure: path-skip-root file-name ⇒ %return

Returns a pointer into file-name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file-name is not an absolute path it returns #f.

file-name

Passed: a file name, as a string.

a file name

%return

Returned: a file name, as a string, or #f.

a pointer into file-name after the root component

Procedure: pattern-match-simple? pattern string ⇒ %return

Matches a string against a pattern given as a string.

If this function is to be called in a loop, it’s more efficient to compile the pattern once with pattern-spec:new and call pattern-spec:match-string? repeatedly.

pattern

Passed: a string.

the UTF-8 encoded pattern

string

Passed: a string.

the UTF-8 encoded string to match

%return

Returned: a boolean.

#t if string matches pspec

Procedure: pointer-bit-lock address lock-bit

This is equivalent to g_bit_lock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

address

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

lock-bit

Passed: a 32-bit integer.

a bit value between 0 and 31

Procedure: pointer-bit-lock-and-get address lock-bit ⇒ out-ptr

This is equivalent to g_bit_lock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

address

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

lock-bit

Passed: an unsigned 32-bit integer.

a bit value between 0 and 31

out-ptr

Returned: an unsigned 64-bit integer.

returns the set pointer atomically. This is the value after setting the lock, it thus always has the lock bit set, while previously address had the lockbit unset. You may also use pointer-bit-lock-mask-ptr to clear the lock bit.

Procedure: pointer-bit-lock-mask-ptr ptr lock-bit set preserve-mask [preserve-ptr] ⇒ %return

This mangles ptr as pointer-bit-lock and pointer-bit-unlock do.

ptr

Passed: a foreign pointer, or a bytevector, or #f.

the pointer to mask

lock-bit

Passed: an unsigned 32-bit integer.

the bit to set/clear. If set to G_MAXUINT, the lockbit is taken from preserve-ptr or ptr (depending on preserve-mask).

set

Passed: a boolean.

whether to set (lock) the bit or unset (unlock). This has no effect, if lock-bit is set to G_MAXUINT.

preserve-mask

Passed: an unsigned 64-bit integer.

if non-zero, a bit-mask for preserve-ptr. The preserve-mask bits from preserve-ptr are set in the result. Note that the lock-bit bit will be always set according to set, regardless of preserve-mask and preserve-ptr (unless lock-bit is G_MAXUINT).

preserve-ptr

Passed, or left out: a foreign pointer, or a bytevector, or #f.

if preserve-mask is non-zero, the bits from this pointer are set in the result.

%return

Returned: a foreign pointer, or #f.

the mangled pointer.

Procedure: pointer-bit-trylock? address lock-bit ⇒ %return

This is equivalent to bit-trylock?, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

address

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

lock-bit

Passed: a 32-bit integer.

a bit value between 0 and 31

%return

Returned: a boolean.

#t if the lock was acquired

Procedure: pointer-bit-unlock address lock-bit

This is equivalent to g_bit_unlock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

address

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

lock-bit

Passed: a 32-bit integer.

a bit value between 0 and 31

Procedure: pointer-bit-unlock-and-set address lock-bit ptr preserve-mask

This is equivalent to pointer-bit-unlock and atomically setting the pointer value.

Note that the lock bit will be cleared from the pointer. If the unlocked pointer that was set is not identical to ptr, an assertion fails. In other words, ptr must have lock-bit unset. This also means, you usually can only use this on the lowest bits.

address

Passed: a foreign pointer, or a bytevector.

a pointer to a gpointer-sized value

lock-bit

Passed: an unsigned 32-bit integer.

a bit value between 0 and 31

ptr

Passed: a foreign pointer, or a bytevector, or #f.

the new pointer value to set

preserve-mask

Passed: an unsigned 64-bit integer.

if non-zero, those bits of the current pointer in address are preserved. Note that the lock-bit bit will be always unset regardless of ptr, preserve-mask and the currently set value in address.

Procedure: poll fds nfds timeout ⇒ %return

Polls fds, as with the poll() system call, but portably. (On systems that don’t have poll(), it is emulated using select().) This is used internally by <GMainContext>, but it can be called directly if you need to block until a file descriptor is ready, but don’t want to run the full main loop.

Each element of fds is a <GPollFD> describing a single file descriptor to poll. The fd field indicates the file descriptor, and the events field indicates the events to poll for. On return, the revents fields will be filled with the events that actually occurred.

On POSIX systems, the file descriptors in fds can be any sort of file descriptor, but the situation is much more complicated on Windows. If you need to use poll in code that has to run on Windows, the easiest solution is to construct all of your GPollFDs with g_io_channel_win32_make_pollfd().

fds

Passed: a <GPollFD>.

file descriptors to poll

nfds

Passed: an unsigned 32-bit integer.

the number of file descriptors in fds

timeout

Passed: a 32-bit integer.

amount of time to wait, in milliseconds, or -1 to wait forever

%return

Returned: a 32-bit integer.

the number of entries in fds whose revents fields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.

Procedure: prefix-error-literal! err prefix ⇒ err

Prefixes prefix to an existing error message. If err or *err is #f (i.e.: no error variable) then do nothing.

err

Passed, and returned: a <GError>, or #f.

a return location for a <GError>, or #f

prefix

Passed: a string.

string to prefix err with

Procedure: propagate-error src ⇒ dest

If dest is #f, free src; otherwise, moves src into *dest. The error variable dest points to must be #f.

src must be non-#f.

Note that src is no longer valid after this call. If you want to keep using the same GError*, you need to set it to #f after calling this function on it.

src

Passed: a <GError>.

error to move into the return location

dest

Returned: a <GError>, or #f.

error return location

Procedure: quark-from-static-string [string] ⇒ %return

Gets the GQuark identifying the given (static) string. If the string does not currently have an associated GQuark, a new GQuark is created, linked to the given string.

Note that this function is identical to quark-from-string except that if a new GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will continue to exist until the program terminates. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK theme engines).

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

string

Passed, or left out: a string, or #f.

a string

%return

Returned: an unsigned 32-bit integer.

the GQuark identifying the string, or 0 if string is #f

Procedure: quark-from-string [string] ⇒ %return

Gets the GQuark identifying the given string. If the string does not currently have an associated GQuark, a new GQuark is created, using a copy of the string.

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

string

Passed, or left out: a string, or #f.

a string

%return

Returned: an unsigned 32-bit integer.

the GQuark identifying the string, or 0 if string is #f

Procedure: quark-to-string quark ⇒ %return

Gets the string associated with the given GQuark.

quark

Passed: an unsigned 32-bit integer.

a GQuark.

%return

Returned: a string.

the string associated with the GQuark

Procedure: quark-try-string [string] ⇒ %return

Gets the GQuark associated with the given string, or 0 if string is #f or it has no associated GQuark.

If you want the GQuark to be created if it doesn’t already exist, use quark-from-string or quark-from-static-string.

This function must not be used before library constructors have finished running.

string

Passed, or left out: a string, or #f.

a string

%return

Returned: an unsigned 32-bit integer.

the GQuark associated with the string, or 0 if string is #f or there is no GQuark associated with it

Procedure: random-double ⇒ %return

Returns a random gdouble equally distributed over the range [0..1).

%return

Returned: a real number.

a random number

Procedure: random-double-range begin end ⇒ %return

Returns a random gdouble equally distributed over the range [begin..end).

begin

Passed: a real number.

lower closed bound of the interval

end

Passed: a real number.

upper open bound of the interval

%return

Returned: a real number.

a random number

Procedure: random-int ⇒ %return

Return a random guint32 equally distributed over the range [0..2^32-1].

%return

Returned: an unsigned 32-bit integer.

a random number

Procedure: random-int-range begin end ⇒ %return

Returns a random gint32 equally distributed over the range [begin..end-1].

begin

Passed: a 32-bit integer.

lower closed bound of the interval

end

Passed: a 32-bit integer.

upper open bound of the interval

%return

Returned: a 32-bit integer.

a random number

Procedure: random-set-seed seed

Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

seed

Passed: an unsigned 32-bit integer.

a value to reinitialize the global random number generator

Procedure: rc-box-acquire mem-block ⇒ %return

Acquires a reference on the data pointed by mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

%return

Returned: a foreign pointer.

a pointer to the data, with its reference count increased

Procedure: rc-box-alloc block-size ⇒ %return

Allocates block-size bytes of memory, and adds reference counting semantics to it.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

block-size

Passed: an unsigned 64-bit integer.

the size of the allocation, must be greater than 0

%return

Returned: a foreign pointer.

a pointer to the allocated memory

Procedure: rc-box-alloc0 block-size ⇒ %return

Allocates block-size bytes of memory, and adds reference counting semantics to it.

The contents of the returned data is set to zero.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

block-size

Passed: an unsigned 64-bit integer.

the size of the allocation, must be greater than 0

%return

Returned: a foreign pointer.

a pointer to the allocated memory

Procedure: rc-box-dup block-size mem-block ⇒ %return

Allocates a new block of data with reference counting semantics, and copies block-size bytes of mem-block into it.

block-size

Passed: an unsigned 64-bit integer.

the number of bytes to copy, must be greater than 0

mem-block

Passed: a foreign pointer, or a bytevector.

the memory to copy

%return

Returned: a foreign pointer.

a pointer to the allocated memory

Procedure: rc-box-get-size mem-block ⇒ %return

Retrieves the size of the reference counted data pointed by mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

%return

Returned: an unsigned 64-bit integer.

the size of the data, in bytes

Procedure: rc-box-release mem-block

Releases a reference on the data pointed by mem-block.

If the reference was the last one, it will free the resources allocated for mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

Procedure: rc-box-release-full mem-block clear-func

Releases a reference on the data pointed by mem-block.

If the reference was the last one, it will call clear-func to clear the contents of mem-block, and then will free the resources allocated for mem-block.

mem-block

Passed: a foreign pointer, or a bytevector.

a pointer to reference counted data

clear-func

Passed: a procedure.

a function to call when clearing the data

See GDestroyNotify for how it is called.

Procedure: realloc mem n-bytes ⇒ %return

Reallocates the memory pointed to by mem, so that it now has space for n-bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be #f, in which case it’s considered to have zero-length. n-bytes may be 0, in which case #f will be returned and mem will be freed unless it is #f.

If the allocation fails (because the system is out of memory), the program is terminated.

mem

Passed: a foreign pointer, or a bytevector, or #f.

the memory to reallocate

n-bytes

Passed: an unsigned 64-bit integer.

new size of the memory in bytes

%return

Returned: a foreign pointer, or #f.

the new address of the allocated memory

Procedure: realloc-n mem n-blocks n-block-bytes ⇒ %return

This function is similar to realloc, allocating (n-blocks * n-block-bytes) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

mem

Passed: a foreign pointer, or a bytevector, or #f.

the memory to reallocate

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

%return

Returned: a foreign pointer, or #f.

the new address of the allocated memory

Procedure: ref-count-compare? rc val ⇒ %return

Compares the current value of rc with val.

rc

Passed: a 32-bit integer.

the address of a reference count variable

val

Passed: a 32-bit integer.

the value to compare

%return

Returned: a boolean.

#t if the reference count is the same as the given value

Procedure: ref-count-dec rc ⇒ %return rc

Decreases the reference count.

If #t is returned, the reference count reached 0. After this point, rc is an undefined state and must be reinitialized with ref-count-init to be used again.

rc

Passed, and returned: a 32-bit integer.

the address of a reference count variable

%return

Returned: a boolean.

#t if the reference count reached 0, and #f otherwise

Procedure: ref-count-inc rc ⇒ rc

Increases the reference count.

rc

Passed, and returned: a 32-bit integer.

the address of a reference count variable

Procedure: ref-count-init ⇒ rc

Initializes a reference count variable to 1.

rc

Returned: a 32-bit integer.

the address of a reference count variable

Procedure: ref-string-acquire str ⇒ %return

Acquires a reference on a string.

str

Passed: a string.

a reference counted string

%return

Returned: a string.

the given string, with its reference count increased

Procedure: ref-string-equal? str1 str2 ⇒ %return

Compares two ref-counted strings for byte-by-byte equality.

It can be passed to GLib.HashTable.new as the key equality function, and behaves exactly the same as str-equal? (or strcmp()), but can return slightly faster as it can check the string lengths before checking all the bytes.

str1

Passed: a string.

a reference counted string

str2

Passed: a string.

a reference counted string

%return

Returned: a boolean.

TRUE if the strings are equal, otherwise FALSE

Procedure: ref-string-length str ⇒ %return

Retrieves the length of str.

str

Passed: a string.

a reference counted string

%return

Returned: an unsigned 64-bit integer.

the length of the given string, in bytes

Procedure: ref-string-new str ⇒ %return

Creates a new reference counted string and copies the contents of str into it.

str

Passed: a string.

a NUL-terminated string

%return

Returned: a string.

the newly created reference counted string

Procedure: ref-string-new-intern str ⇒ %return

Creates a new reference counted string and copies the content of str into it.

If you call this function multiple times with the same str, or with the same contents of str, it will return a new reference, instead of creating a new string.

str

Passed: a string.

a NUL-terminated string

%return

Returned: a string.

the newly created reference counted string, or a new reference to an existing string

Procedure: ref-string-new-len str len ⇒ %return

Creates a new reference counted string and copies the contents of str into it, up to len bytes.

Since this function does not stop at nul bytes, it is the caller’s responsibility to ensure that str has at least len addressable bytes.

str

Passed: a string.

a string

len

Passed: a 64-bit integer.

length of str to use, or -1 if str is nul-terminated

%return

Returned: a string.

the newly created reference counted string

Procedure: ref-string-release str

Releases a reference on a string; if it was the last reference, the resources allocated by the string are freed as well.

str

Passed: a string.

a reference counted string

Procedure: regex-check-replacement replacement ⇒ %return has-references

Checks whether replacement is a valid replacement string (see regex:replace), i.e. that all escape sequences in it are valid.

If has-references is not #f then replacement is checked for pattern references. For instance, replacement text ’foo\n’ does not contain references and may be evaluated without information about actual match, but ’\0\1’ (whole match followed by first subpattern) requires valid <GMatchInfo> object.

replacement

Passed: a string.

the replacement string

%return

Returned: a boolean.

whether replacement is a valid replacement string

has-references

Returned: a boolean.

location to store information about references in replacement or #f

Procedure: regex-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: regex-escape-nul string length ⇒ %return

Escapes the nul characters in string to "\x00". It can be used to compile a regex with embedded nul characters.

For completeness, length can be -1 for a nul-terminated string. In this case the output string will be of course equal to string.

string

Passed: a string.

the string to escape

length

Passed: a 32-bit integer.

the length of string

%return

Returned: a string.

a newly-allocated escaped string

Procedure: regex-escape-string string length ⇒ %return

Escapes the special characters used for regular expressions in string, for instance "a.b*c" becomes "a\.b\*c". This function is useful to dynamically generate regular expressions.

string can contain nul characters that are replaced with "\0", in this case remember to specify the correct length of string in length.

string

Passed: a string.

the string to escape

length

Passed: a 32-bit integer.

the length of string, in bytes, or -1 if string is nul-terminated

%return

Returned: a string.

a newly-allocated escaped string

Procedure: regex-match-simple? pattern string compile-options match-options ⇒ %return

Scans for a match in string for pattern.

This function is equivalent to regex:match but it does not require to compile the pattern with regex:new, avoiding some lines of code when you need just to do a match without extracting substrings, capture counts, and so on.

If this function is to be called on the same pattern more than once, it’s more efficient to compile the pattern once with regex:new and then use regex:match.

pattern

Passed: a string.

the regular expression

string

Passed: a string.

the string to scan for matches

compile-options

Passed: a <%GRegexCompileFlags>, or a list of its symbols, or one of them.

compile options for the regular expression, or 0

match-options

Passed: a <%GRegexMatchFlags>, or a list of its symbols, or one of them.

match options, or 0

%return

Returned: a boolean.

#t if the string matched, #f otherwise

Procedure: regex-split-simple pattern string compile-options match-options ⇒ %return

Breaks the string on the pattern, and returns an array of the tokens. If the pattern contains capturing parentheses, then the text for each of the substrings will also be returned. If the pattern does not match anywhere in the string, then the whole string is returned as the first token.

This function is equivalent to regex:split but it does not require to compile the pattern with regex:new, avoiding some lines of code when you need just to do a split without extracting substrings, capture counts, and so on.

If this function is to be called on the same pattern more than once, it’s more efficient to compile the pattern once with regex:new and then use regex:split.

As a special case, the result of splitting the empty string "" is an empty vector, not a vector containing a single string. The reason for this special case is that being able to represent an empty vector is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you’ll need to check for the empty string before calling this function.

A pattern that can match empty strings splits string into separate characters wherever it matches the empty string between characters. For example splitting "ab c" using as a separator "\s*", you will get "a", "b" and "c".

pattern

Passed: a string.

the regular expression

string

Passed: a string.

the string to scan for matches

compile-options

Passed: a <%GRegexCompileFlags>, or a list of its symbols, or one of them.

compile options for the regular expression, or 0

match-options

Passed: a <%GRegexMatchFlags>, or a list of its symbols, or one of them.

match options, or 0

%return

Returned: a vector, each a string.

a #f-terminated array of strings. Free it using strfreev

Procedure: reload-user-special-dirs-cache

Resets the cache used for get-user-special-dir, so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.

Due to thread safety issues this may cause leaking of strings that were previously returned from get-user-special-dir that can’t be freed. We ensure to only leak the data for the directories that actually changed value though.

Procedure: rename oldfilename newfilename ⇒ %return

A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.

See your C library manual for more details about how rename() works on your system. It is not possible in general on Windows to rename a file that is open to some process.

oldfilename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

newfilename

Passed: a file name, as a string.

a pathname in the GLib file name encoding

%return

Returned: a 32-bit integer.

0 if the renaming succeeded, -1 if an error occurred

Procedure: rmdir filename ⇒ %return

A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.

See your C library manual for more details about how rmdir() works on your system.

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

%return

Returned: a 32-bit integer.

0 if the directory was successfully removed, -1 if an error occurred

Procedure: set-application-name application-name

Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user. Contrast with set-prgname, which sets a non-localized name. set-prgname will be called automatically by init, but set-application-name will not.

Note that for thread safety reasons, this function can only be called once.

The application name will be used in contexts such as error messages, or when displaying an application’s name in the task list.

application-name

Passed: a string.

localized name of the application

Procedure: set-error-literal domain code message ⇒ err

Does nothing if err is #f; if err is non-#f, then *err must be #f. A new <GError> is created and assigned to *err. Unlike g_set_error(), message is not a printf()-style format string. Use this function if message contains text you don’t have control over, that could include printf() escape sequences.

domain

Passed: an unsigned 32-bit integer.

error domain

code

Passed: a 32-bit integer.

error code

message

Passed: a string.

error message

err

Returned: a <GError>.

a return location for a <GError>

Procedure: set-prgname prgname

Sets the name of the program. This name should not be localized, in contrast to set-application-name.

If you are using <GApplication> the program name is set in application:run. In case of GDK or GTK it is set in gdk_init(), which is called by init and the "startup" handler. By default, the program name is found by taking the last component of argv[0].

Since GLib 2.72, this function can be called multiple times and is fully thread safe. Prior to GLib 2.72, this function could only be called once per process.

See the GTK documentation for requirements on integrating set-prgname with GTK applications.

prgname

Passed: a string.

the name of the program.

Procedure: setenv? variable value overwrite ⇒ %return

Sets an environment variable. On UNIX, both the variable’s name and value can be arbitrary byte strings, except that the variable’s name cannot contain ’=’. On Windows, they should be in UTF-8.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn’t reclaimed.

You should be mindful of the fact that environment variable handling in UNIX is not thread-safe, and your program may crash if one thread calls setenv? while another thread is calling getenv(). (And note that many functions, such as gettext(), call getenv() internally.) This function is only safe to use at the very start of your program, before creating any other threads (or creating objects that create worker threads of their own).

If you need to set up the environment for a child process, you can use get-environ to get an environment array, modify that with environ-setenv and environ-unsetenv, and then pass that array directly to execvpe(), spawn-async, or the like.

variable

Passed: a file name, as a string.

the environment variable to set, must not contain ’=’.

value

Passed: a file name, as a string.

the value for to set the variable to.

overwrite

Passed: a boolean.

whether to change the variable if it already exists.

%return

Returned: a boolean.

#f if the environment variable couldn’t be set.

Procedure: shell-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: shell-parse-argv command-line ⇒ %return argvp

Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported).

The results are defined to be the same as those you would get from a UNIX98 /bin/sh, as long as the input contains none of the unsupported shell expansions. If the input does contain such expansions, they are passed through literally.

Possible errors are those from the G_SHELL_ERROR domain.

In particular, if command-line is an empty string (or a string containing only whitespace), empty-string will be returned. It’s guaranteed that argvp will be a non-empty array if this function returns successfully.

Free the returned vector with strfreev.

command-line

Passed: a file name, as a string.

command line to parse

%return

Returned: a boolean.

#t on success, #f if error set

argvp

Returned: a vector, each a file name, as a string.

return location for array of args

argcp

Not returned: it is the length of argvp.

return location for number of args

Procedure: shell-quote unquoted-string ⇒ %return

Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquoted-string.

If you pass a filename to the shell, for example, you should first quote it with this function.

The return value must be freed with byte-array:free.

The quoting style used is undefined (single or double quotes may be used).

unquoted-string

Passed: a file name, as a string.

a literal string

%return

Returned: a file name, as a string.

quoted string

Procedure: shell-unquote quoted-string ⇒ %return

Unquotes a string as the shell (/bin/sh) would.

This function only handles quotes; if a string contains file globs, arithmetic operators, variables, backticks, redirections, or other special-to-the-shell features, the result will be different from the result a real shell would produce (the variables, backticks, etc. will be passed through literally instead of being expanded).

This function is guaranteed to succeed if applied to the result of shell-quote. If it fails, it returns #f and sets the error.

The quoted-string need not actually contain quoted or escaped text; shell-unquote simply goes through the string and unquotes/unescapes anything that the shell would. Both single and double quotes are handled, as are escapes including escaped newlines.

The return value must be freed with byte-array:free.

Possible errors are in the G_SHELL_ERROR domain.

Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even \' - if you want a ' in the quoted text, you have to do something like 'foo'\''bar'. Double quotes allow $, “‘, ", \, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.

quoted-string

Passed: a file name, as a string.

shell-quoted string

%return

Returned: a file name, as a string.

an unquoted string

Procedure: slice-alloc block-size ⇒ %return

Allocates a block of memory from the libc allocator.

The block address handed out can be expected to be aligned to at least 1 * sizeof (void*).

Since GLib 2.76 this always uses the system malloc() implementation internally.

block-size

Passed: an unsigned 64-bit integer.

the number of bytes to allocate

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated memory block, which will be #f if and only if mem-size is 0

Procedure: slice-alloc0 block-size ⇒ %return

Allocates a block of memory via slice-alloc and initializes the returned memory to 0.

Since GLib 2.76 this always uses the system malloc() implementation internally.

block-size

Passed: an unsigned 64-bit integer.

the number of bytes to allocate

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated block, which will be #f if and only if mem-size is 0

Procedure: slice-copy block-size [mem-block] ⇒ %return

Allocates a block of memory from the slice allocator and copies block-size bytes into it from mem-block.

mem-block must be non-#f if block-size is non-zero.

Since GLib 2.76 this always uses the system malloc() implementation internally.

block-size

Passed: an unsigned 64-bit integer.

the number of bytes to allocate

mem-block

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the memory to copy

%return

Returned: a foreign pointer, or #f.

a pointer to the allocated memory block, which will be #f if and only if mem-size is 0

Procedure: slice-free-chain-with-offset block-size mem-chain next-offset

Frees a linked list of memory blocks of structure type type.

The memory blocks must be equal-sized, allocated via slice-alloc or slice-alloc0 and linked together by a next pointer (similar to GSList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the ‘G_DEBUG=gc-friendly‘ environment variable.

If mem-chain is #f, this function does nothing.

Since GLib 2.76 this always uses the system free_sized() implementation internally.

block-size

Passed: an unsigned 64-bit integer.

the size of the blocks

mem-chain

Passed: a foreign pointer, or a bytevector, or #f.

a pointer to the first block of the chain

next-offset

Passed: an unsigned 64-bit integer.

the offset of the next field in the blocks

Procedure: slice-free1 block-size [mem-block]

Frees a block of memory.

The memory must have been allocated via slice-alloc or slice-alloc0 and the block-size has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the ‘G_DEBUG=gc-friendly‘ environment variable.

If mem-block is #f, this function does nothing.

Since GLib 2.76 this always uses the system free_sized() implementation internally.

block-size

Passed: an unsigned 64-bit integer.

the size of the block

mem-block

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a pointer to the block to free

Procedure: slice-get-config ckey ⇒ %return
ckey

Passed: a <%GSliceConfig>, or one of its symbols.

%return

Returned: a 64-bit integer.

Procedure: slice-get-config-state ckey address n-values ⇒ %return
ckey

Passed: a <%GSliceConfig>, or one of its symbols.

address

Passed: a 64-bit integer.

n-values

Passed: an unsigned 32-bit integer.

%return

Returned: a 64-bit integer.

Procedure: slice-set-config ckey value
ckey

Passed: a <%GSliceConfig>, or one of its symbols.

value

Passed: a 64-bit integer.

Procedure: source-remove-by-user-data? [user-data] ⇒ %return

Removes a source from the default main loop context given the user data for the callback.

If multiple sources exist with the same user data, only one will be destroyed.

user-data

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the user_data for the callback

%return

Returned: a boolean.

true if a source was found and removed, false otherwise

Procedure: source-remove? tag ⇒ %return

Removes the source with the given ID from the default main context.

You must use source:destroy for sources added to a non-default main context.

The ID of a <GSource> is given by source:get-id, or will be returned by the functions source:attach, idle-add, GLib.idle_add_full, timeout-add, GLib.timeout_add_full, child-watch-add, GLib.child_watch_add_full, io-add-watch, and GLib.io_add_watch_full.

It is a programmer error to attempt to remove a non-existent source.

More specifically: source IDs can be reissued after a source has been destroyed and therefore it is never valid to use this function with a source ID which may have already been removed. An example is when scheduling an idle to run in another thread with idle-add: the idle may already have run and been removed by the time this function is called on its (now invalid) source ID. This source ID may have been reissued, leading to the operation being performed against the wrong source.

tag

Passed: an unsigned 32-bit integer.

the ID of the source to remove.

%return

Returned: a boolean.

true if the source was found and removed, false otherwise

Procedure: source-set-name-by-id tag name

Sets the name of a source using its ID.

This is a convenience utility to set source names from the return value of idle-add, timeout-add, etc.

It is a programmer error to attempt to set the name of a non-existent source.

More specifically: source IDs can be reissued after a source has been destroyed and therefore it is never valid to use this function with a source ID which may have already been removed. An example is when scheduling an idle to run in another thread with idle-add: the idle may already have run and been removed by the time this function is called on its (now invalid) source ID. This source ID may have been reissued, leading to the operation being performed against the wrong source.

tag

Passed: an unsigned 32-bit integer.

a source ID

name

Passed: a string.

debug name for the source

Procedure: source:remove? tag ⇒ %return
tag

Passed: an unsigned 32-bit integer.

%return

Returned: a boolean.

filename

Passed: a file name, as a string.

Procedure: source:remove? tag ⇒ %return

Removes the source with the given ID from the default main context.

You must use source:destroy for sources added to a non-default main context.

The ID of a <GSource> is given by source:get-id, or will be returned by the functions source:attach, idle-add, GLib.idle_add_full, timeout-add, GLib.timeout_add_full, child-watch-add, GLib.child_watch_add_full, io-add-watch, and GLib.io_add_watch_full.

It is a programmer error to attempt to remove a non-existent source.

More specifically: source IDs can be reissued after a source has been destroyed and therefore it is never valid to use this function with a source ID which may have already been removed. An example is when scheduling an idle to run in another thread with idle-add: the idle may already have run and been removed by the time this function is called on its (now invalid) source ID. This source ID may have been reissued, leading to the operation being performed against the wrong source.A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.

See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.

If this function fails on Windows you can’t infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().

tag

Passed: an unsigned 32-bit integer.

the ID of the source to remove.

%return

Returned: a boolean.

true if the source was found and removed, false otherwise0 if the file was successfully removed, -1 if an error occurred

filename

a pathname in the GLib file name encoding (UTF-8 on Windows)

Procedure: spaced-primes-closest num ⇒ %return

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a <GHashTable>.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

num

Passed: an unsigned 32-bit integer.

a guint

%return

Returned: an unsigned 32-bit integer.

the smallest prime number from a built-in array of primes which is larger than num

Procedure: spawn-async working-directory argv envp flags [child-setup] ⇒ %return child-pid

Executes a child program asynchronously.

See spawn-async-with-pipes-and-fds for a full description; this function simply calls the spawn-async-with-pipes without any pipes, which in turn calls spawn-async-with-pipes-and-fds.

You should call spawn-close-pid on the returned child process reference when you don’t need it any more.

If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use <GdkAppLaunchContext>, <GAppLaunchContext>, or set the DISPLAY environment variable.

Note that the returned child-pid on Windows is a handle to the child process and not its identifier. Process handles and process identifiers are different concepts on Windows.

working-directory

Passed: a file name, as a string, or #f.

child’s current working directory, or #f to inherit parent’s

argv

Passed: a list or vector, each a file name, as a string.

child’s argument vector

envp

Passed: a list or vector, each a file name, as a string, or #f.

child’s environment, or #f to inherit parent’s

flags

Passed: a <%GSpawnFlags>, or a list of its symbols, or one of them.

flags from <%GSpawnFlags>

child-setup

Passed, or left out: a procedure, or #f.

function to run in the child just before exec()

See GSpawnChildSetupFunc for how it is called.

%return

Returned: a boolean.

#t on success, #f if error is set

child-pid

Returned: a 32-bit integer.

return location for child process reference, or #f

user-data

Not passed: guile-gi supplies it.

user data for child-setup

Procedure: spawn-async-with-fds working-directory argv envp flags child-setup stdin-fd stdout-fd stderr-fd ⇒ %return child-pid

Executes a child program asynchronously.

Identical to spawn-async-with-pipes-and-fds but with n_fds set to zero, so no FD assignments are used.

working-directory

Passed: a file name, as a string, or #f.

child’s current working directory, or #f to inherit parent’s, in the GLib file name encoding

argv

Passed: a list or vector, each a string.

child’s argument vector, in the GLib file name encoding; it must be non-empty and #f-terminated

envp

Passed: a list or vector, each a string, or #f.

child’s environment, or #f to inherit parent’s, in the GLib file name encoding

flags

Passed: a <%GSpawnFlags>, or a list of its symbols, or one of them.

flags from <%GSpawnFlags>

child-setup

Passed: a procedure, or #f.

function to run in the child just before exec()

See GSpawnChildSetupFunc for how it is called.

stdin-fd

Passed: a 32-bit integer.

file descriptor to use for child’s stdin, or -1

stdout-fd

Passed: a 32-bit integer.

file descriptor to use for child’s stdout, or -1

stderr-fd

Passed: a 32-bit integer.

file descriptor to use for child’s stderr, or -1

%return

Returned: a boolean.

#t on success, #f if an error was set

child-pid

Returned: a 32-bit integer.

return location for child process ID, or #f

user-data

Not passed: guile-gi supplies it.

user data for child-setup

Procedure: spawn-async-with-pipes working-directory argv envp flags [child-setup] ⇒ %return child-pid standard-input standard-output standard-error

Identical to spawn-async-with-pipes-and-fds but with n_fds set to zero, so no FD assignments are used.

working-directory

Passed: a file name, as a string, or #f.

child’s current working directory, or #f to inherit parent’s, in the GLib file name encoding

argv

Passed: a list or vector, each a file name, as a string.

child’s argument vector, in the GLib file name encoding; it must be non-empty and #f-terminated

envp

Passed: a list or vector, each a file name, as a string, or #f.

child’s environment, or #f to inherit parent’s, in the GLib file name encoding

flags

Passed: a <%GSpawnFlags>, or a list of its symbols, or one of them.

flags from <%GSpawnFlags>

child-setup

Passed, or left out: a procedure, or #f.

function to run in the child just before exec()

See GSpawnChildSetupFunc for how it is called.

%return

Returned: a boolean.

#t on success, #f if an error was set

child-pid

Returned: a 32-bit integer.

return location for child process ID, or #f

standard-input

Returned: a 32-bit integer.

return location for file descriptor to write to child’s stdin, or #f

standard-output

Returned: a 32-bit integer.

return location for file descriptor to read child’s stdout, or #f

standard-error

Returned: a 32-bit integer.

return location for file descriptor to read child’s stderr, or #f

user-data

Not passed: guile-gi supplies it.

user data for child-setup

Procedure: spawn-async-with-pipes-and-fds working-directory argv envp flags child-setup stdin-fd stdout-fd stderr-fd source-fds target-fds ⇒ %return child-pid-out stdin-pipe-out stdout-pipe-out stderr-pipe-out

Executes a child program asynchronously (your program will not block waiting for the child to exit).

The child program is specified by the only argument that must be provided, argv. argv should be a #f-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path. If flags contains the search-path flag, the PATH environment variable is used to search for the executable. If flags contains the search-path-from-envp flag, the PATH variable from envp is used to search for the executable. If both the search-path and search-path-from-envp flags are set, the PATH variable from envp takes precedence over the environment variable.

If the program name is not a full path and search-path flag is not used, then the program will be run from the current directory (or working-directory, if specified); this might be unexpected or even dangerous in some cases when the current directory is world-writable.

On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in these arguments will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft’s tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

At least currently, mingw doesn’t support wmain(), so if you use mingw to develop the spawned program, it should call g_win32_get_command_line() to get arguments in UTF-8.

On Windows the low-level child process creation API CreateProcess() doesn’t use argument vectors, but a command line. The C runtime library’s spawn*() family of functions (which spawn-async-with-pipes eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when you have argument vector elements that contain spaces or double quotes. The spawn*() functions don’t do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, spawn-async-with-pipes will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

The returned child-pid on Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.

envp is a #f-terminated array of strings, where each string has the form KEY=VALUE. This will become the child’s environment. If envp is #f, the child inherits its parent’s environment.

flags should be the bitwise OR of any flags you want to affect the function’s behaviour. The do-not-reap-child means that the child will not automatically be reaped; you must use a child watch (child-watch-add) to be notified about the death of the child process, otherwise it will stay around as a zombie process until this process exits. Eventually you must call spawn-close-pid on the child-pid, in order to free resources which may be associated with the child process. (On Unix, using a child watch is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling spawn-close-pid is equivalent to calling CloseHandle() on the process handle returned in child-pid). See child-watch-add.

Open UNIX file descriptors marked as FD_CLOEXEC will be automatically closed in the child process. leave-descriptors-open means that other open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. search-path means that argv[0] need not be an absolute path, it will be looked for in the PATH environment variable. search-path-from-envp means need not be an absolute path, it will be looked for in the PATH variable from envp. If both search-path and search-path-from-envp are used, the value from envp takes precedence over the environment.

child-inherits-stdin means that the child will inherit the parent’s standard input (by default, the child’s standard input is attached to /dev/null). stdin-from-dev-null explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdin-pipe-out argument is ignored.

stdout-to-dev-null means that the child’s standard output will be discarded (by default, it goes to the same location as the parent’s standard output). child-inherits-stdout explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdout-pipe-out argument is ignored.

stderr-to-dev-null means that the child’s standard error will be discarded (by default, it goes to the same location as the parent’s standard error). child-inherits-stderr explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stderr-pipe-out argument is ignored.

It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both stdout-fd and stderr-fd, and include it in source-fds too).

source-fds and target-fds allow zero or more FDs from this process to be remapped to different FDs in the spawned process. If n-fds is greater than zero, source-fds and target-fds must both be non-#f and the same length. Each FD in source-fds is remapped to the FD number at the same index in target-fds. The source and target FD may be equal to simply propagate an FD to the spawned process. FD remappings are processed after standard FDs, so any target FDs which equal stdin-fd, stdout-fd or stderr-fd will overwrite them in the spawned process.

source-fds is supported on Windows since 2.72.

file-and-argv-zero means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally spawn-async-with-pipes uses argv[0] as the file to execute, and passes all of argv to the child.

child-setup and user-data are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, child-setup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent.

On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). There is no sensible thing child-setup could be used for on Windows so it is ignored and not called.

If non-#f, child-pid will on Unix be filled with the child’s process ID. You can use the process ID to send signals to the child, or to use child-watch-add (or waitpid()) if you specified the do-not-reap-child flag. On Windows, child-pid will be filled with a handle to the child process only if you specified the do-not-reap-child flag. You can then access the child process using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). You should close the handle with CloseHandle() or spawn-close-pid when you no longer need it.

If non-#f, the stdin-pipe-out, stdout-pipe-out, stderr-pipe-out locations will be filled with file descriptors for writing to the child’s standard input or reading from its standard output or standard error. The caller of spawn-async-with-pipes must close these file descriptors when they are no longer in use. If these parameters are #f, the corresponding pipe won’t be created.

If stdin-pipe-out is #f, the child’s standard input is attached to /dev/null unless child-inherits-stdin is set.

If stderr-pipe-out is NULL, the child’s standard error goes to the same location as the parent’s standard error unless stderr-to-dev-null is set.

If stdout-pipe-out is NULL, the child’s standard output goes to the same location as the parent’s standard output unless stdout-to-dev-null is set.

error can be #f to ignore errors, or non-#f to report errors. If an error is set, the function returns #f. Errors are reported even if they occur in the child (for example if the executable in @argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

If an error occurs, child-pid, stdin-pipe-out, stdout-pipe-out, and stderr-pipe-out will not be filled with valid values.

If child-pid is not #f and an error does not occur then the returned process reference must be closed using spawn-close-pid.

On modern UNIX platforms, GLib can use an efficient process launching codepath driven internally by posix_spawn(). This has the advantage of avoiding the fork-time performance costs of cloning the parent process address space, and avoiding associated memory overcommit checks that are not relevant in the context of immediately executing a distinct process. This optimized codepath will be used provided that the following conditions are met:

  1. do-not-reap-child is set
  2. leave-descriptors-open is set
  3. search-path-from-envp is not set
  4. working-directory is #f
  5. child-setup is #f
  6. The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.

If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use <GdkAppLaunchContext>, <GAppLaunchContext>, or set the DISPLAY environment variable.

working-directory

Passed: a file name, as a string, or #f.

child’s current working directory, or #f to inherit parent’s, in the GLib file name encoding

argv

Passed: a list or vector, each a file name, as a string.

child’s argument vector, in the GLib file name encoding; it must be non-empty and #f-terminated

envp

Passed: a list or vector, each a file name, as a string, or #f.

child’s environment, or #f to inherit parent’s, in the GLib file name encoding

flags

Passed: a <%GSpawnFlags>, or a list of its symbols, or one of them.

flags from <%GSpawnFlags>

child-setup

Passed: a procedure, or #f.

function to run in the child just before exec()

See GSpawnChildSetupFunc for how it is called.

stdin-fd

Passed: a 32-bit integer.

file descriptor to use for child’s stdin, or -1

stdout-fd

Passed: a 32-bit integer.

file descriptor to use for child’s stdout, or -1

stderr-fd

Passed: a 32-bit integer.

file descriptor to use for child’s stderr, or -1

source-fds

Passed: a s32vector, or a list or vector, each a 32-bit integer, or #f.

array of FDs from the parent process to make available in the child process

target-fds

Passed: a s32vector, or a list or vector, each a 32-bit integer, or #f.

array of FDs to remap source-fds to in the child process

%return

Returned: a boolean.

#t on success, #f if an error was set

child-pid-out

Returned: a 32-bit integer.

return location for child process ID, or #f

stdin-pipe-out

Returned: a 32-bit integer.

return location for file descriptor to write to child’s stdin, or #f

stdout-pipe-out

Returned: a 32-bit integer.

return location for file descriptor to read child’s stdout, or #f

stderr-pipe-out

Returned: a 32-bit integer.

return location for file descriptor to read child’s stderr, or #f

user-data

Not passed: guile-gi supplies it.

user data for child-setup

n-fds

Not passed: guile-gi gives the length of target-fds.

number of FDs in source-fds and target-fds

Procedure: spawn-check-wait-status? wait-status ⇒ %return

Set error if wait-status indicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal).

The spawn-sync and child-watch-add family of APIs return the status of subprocesses encoded in a platform-specific way. On Unix, this is guaranteed to be in the same format waitpid() returns, and on Windows it is guaranteed to be the result of GetExitCodeProcess().

Prior to the introduction of this function in GLib 2.34, interpreting wait-status required use of platform-specific APIs, which is problematic for software using GLib as a cross-platform layer.

Additionally, many programs simply want to determine whether or not the child exited successfully, and either propagate a <GError> or print a message to standard error. In that common case, this function can be used. Note that the error message in error will contain human-readable information about the wait status.

The domain and code of error have special semantics in the case where the process has an "exit code", as opposed to being killed by a signal. On Unix, this happens if WIFEXITED() would be true of wait-status. On Windows, it is always the case.

The special semantics are that the actual exit code will be the code set in error, and the domain will be G_SPAWN_EXIT_ERROR. This allows you to differentiate between different exit codes.

If the process was terminated by some means other than an exit status (for example if it was killed by a signal), the domain will be G_SPAWN_ERROR and the code will be failed.

This function just offers convenience; you can of course also check the available platform via a macro such as G_OS_UNIX, and use WIFEXITED() and WEXITSTATUS() on wait-status directly. Do not attempt to scan or parse the error message string; it may be translated and/or change in future versions of GLib.

Prior to version 2.70, g_spawn_check_exit_status() provides the same functionality, although under a misleading name.

wait-status

Passed: a 32-bit integer.

A platform-specific wait status as returned from spawn-sync

%return

Returned: a boolean.

#t if child exited successfully, #f otherwise (and error will be set)

Procedure: spawn-close-pid pid

On some platforms, notably Windows, the GPid type represents a resource which must be closed to prevent resource leaking. spawn-close-pid is provided for this purpose. It should be used on all platforms, even though it doesn’t do anything under UNIX.

pid

Passed: a 32-bit integer.

The process reference to close

Procedure: spawn-command-line-async? command-line ⇒ %return

A simple version of spawn-async that parses a command line with shell-parse-argv and passes it to spawn-async.

Runs a command line in the background. Unlike spawn-async, the search-path flag is enabled, other flags are not. Note that search-path can have security implications, so consider using spawn-async directly if appropriate. Possible errors are those from shell-parse-argv and spawn-async.

The same concerns on Windows apply as for spawn-command-line-sync.

command-line

Passed: a file name, as a string.

a command line

%return

Returned: a boolean.

#t on success, #f if error is set

Procedure: spawn-command-line-sync command-line ⇒ %return standard-output standard-error wait-status

A simple version of spawn-sync with little-used parameters removed, taking a command line instead of an argument vector.

See spawn-sync for full details.

The command-line argument will be parsed by shell-parse-argv.

Unlike spawn-sync, the search-path flag is enabled. Note that search-path can have security implications, so consider using spawn-sync directly if appropriate.

Possible errors are those from spawn-sync and those from shell-parse-argv.

If wait-status is non-#f, the platform-specific status of the child is stored there; see the documentation of spawn-check-wait-status? for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

On Windows, please note the implications of shell-parse-argv parsing command-line. Parsing is done according to Unix shell rules, not Windows command interpreter rules. Space is a separator, and backslashes are special. Thus you cannot simply pass a command-line containing canonical Windows paths, like "c:\\program files\\app\\app.exe", as the backslashes will be eaten, and the space will act as a separator. You need to enclose such paths with single quotes, like "’c:\\program files\\app\\app.exe’ ’e:\\folder\\argument.txt’".

command-line

Passed: a file name, as a string.

a command line

%return

Returned: a boolean.

#t on success, #f if an error was set

standard-output

Returned: a bytevector.

return location for child output

standard-error

Returned: a bytevector.

return location for child errors

wait-status

Returned: a 32-bit integer.

return location for child wait status, as returned by waitpid()

Procedure: spawn-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: spawn-exit-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: spawn-sync working-directory argv envp flags [child-setup] ⇒ %return standard-output standard-error wait-status

Executes a child synchronously (waits for the child to exit before returning).

All output from the child is stored in standard-output and standard-error, if those parameters are non-#f. Note that you must set the stdout-to-dev-null and stderr-to-dev-null flags when passing #f for standard-output and standard-error.

If wait-status is non-#f, the platform-specific status of the child is stored there; see the documentation of spawn-check-wait-status? for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

Note that it is invalid to pass do-not-reap-child in flags, and on POSIX platforms, the same restrictions as for child-watch-source-new apply.

If an error occurs, no data is returned in standard-output, standard-error, or wait-status.

This function calls spawn-async-with-pipes internally; see that function for full details on the other parameters and details on how these functions work on Windows.

working-directory

Passed: a file name, as a string, or #f.

child’s current working directory, or #f to inherit parent’s

argv

Passed: a list or vector, each a file name, as a string.

child’s argument vector, which must be non-empty and #f-terminated

envp

Passed: a list or vector, each a file name, as a string, or #f.

child’s environment, or #f to inherit parent’s

flags

Passed: a <%GSpawnFlags>, or a list of its symbols, or one of them.

flags from <%GSpawnFlags>

child-setup

Passed, or left out: a procedure, or #f.

function to run in the child just before exec()

See GSpawnChildSetupFunc for how it is called.

%return

Returned: a boolean.

#t on success, #f if an error was set

standard-output

Returned: a bytevector.

return location for child output, or #f

standard-error

Returned: a bytevector.

return location for child error messages, or #f

wait-status

Returned: a 32-bit integer.

return location for child wait status, as returned by waitpid(), or #f

user-data

Not passed: guile-gi supplies it.

user data for child-setup

Procedure: stpcpy dest src ⇒ %return

Copies a nul-terminated string into the destination buffer, including the trailing nul byte, and returns a pointer to the trailing nul byte in dest. The return value is useful for concatenating multiple strings without having to repeatedly scan for the end.

dest

Passed: a string.

destination buffer

src

Passed: a string.

source string

%return

Returned: a string.

a pointer to the trailing nul byte in dest

Procedure: str-equal? v1 v2 ⇒ %return

Compares two strings for byte-by-byte equality and returns #t if they are equal. It can be passed to g_hash_table_new() as the key-equal-func parameter, when using non-#f strings as keys in a <GHashTable>.

This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-#f strings. For a #f-safe string comparison function, see strcmp0.

v1

Passed: a foreign pointer, or a bytevector.

a key

v2

Passed: a foreign pointer, or a bytevector.

a key to compare with v1

%return

Returned: a boolean.

#t if the two keys match

Procedure: str-has-prefix? str prefix ⇒ %return

Looks whether the string str begins with prefix.

str

Passed: a string.

a string to look in

prefix

Passed: a string.

the prefix to look for

%return

Returned: a boolean.

true if str begins with prefix, false otherwise

Procedure: str-has-suffix? str suffix ⇒ %return

Looks whether a string ends with suffix.

str

Passed: a string.

a string to look in

suffix

Passed: a string.

the suffix to look for

%return

Returned: a boolean.

true if str ends with suffix, false otherwise

Procedure: str-hash v ⇒ %return

Converts a string to a hash value.

This function implements the widely used "djb" hash apparently posted by Daniel Bernstein to comp.lang.c some time ago. The 32 bit unsigned hash value starts at 5381 and for each byte ’c’ in the string, is updated: hash = hash * 33 + c. This function uses the signed value of each byte.

It can be passed to g_hash_table_new() as the hash-func parameter, when using non-#f strings as keys in a <GHashTable>.

Note that this function may not be a perfect fit for all use cases. For example, it produces some hash collisions with strings as short as 2.

v

Passed: a foreign pointer, or a bytevector.

a string key

%return

Returned: an unsigned 32-bit integer.

a hash value corresponding to the key

Procedure: str-is-ascii? str ⇒ %return

Determines if a string is pure ASCII. A string is pure ASCII if it contains no bytes with the high bit set.

str

Passed: a string.

a string

%return

Returned: a boolean.

true if str is ASCII

Procedure: str-match-string? search-term potential-hit accept-alternates ⇒ %return

Checks if a search conducted for search-term should match potential-hit.

This function calls str-tokenize-and-fold on both search-term and potential-hit. ASCII alternates are never taken for search-term but will be taken for potential-hit according to the value of accept-alternates.

A hit occurs when each folded token in search-term is a prefix of a folded token from potential-hit.

Depending on how you’re performing the search, it will typically be faster to call str-tokenize-and-fold on each string in your corpus and build an index on the returned folded tokens, then call str-tokenize-and-fold on the search term and perform lookups into that index.

As some examples, searching for ‘fred’ would match the potential hit ‘Smith, Fred’ and also ‘Frédéric’. Searching for ‘Fréd’ would match ‘Frédéric’ but not ‘Frederic’ (due to the one-directional nature of accent matching). Searching ‘fo’ would match ‘Foo’ and ‘Bar Foo Baz’, but not ‘SFO’ (because no word has ‘fo’ as a prefix).

search-term

Passed: a string.

the search term from the user

potential-hit

Passed: a string.

the text that may be a hit

accept-alternates

Passed: a boolean.

if true, ASCII alternates are accepted

%return

Returned: a boolean.

true if potential-hit is a hit

Procedure: str-to-ascii str [from-locale] ⇒ %return

Transliterate str to plain ASCII.

For best results, str should be in composed normalised form.

This function performs a reasonably good set of character replacements. The particular set of replacements that is done may change by version or even by runtime environment.

If the source language of str is known, it can used to improve the accuracy of the translation by passing it as from-locale. It should be a valid POSIX locale string (of the form language[_territory][.codeset][@modifier]).

If from-locale is #f then the current locale is used.

If you want to do translation for no specific locale, and you want it to be done independently of the currently locale, specify "C" for from-locale.

str

Passed: a string.

a string, in UTF-8

from-locale

Passed, or left out: a string, or #f.

the source locale, if known

%return

Returned: a string.

a string in plain ASCII

Procedure: str-tokenize-and-fold string [translit-locale] ⇒ %return ascii-alternates

Tokenizes string and performs folding on each token.

A token is a non-empty sequence of alphanumeric characters in the source string, separated by non-alphanumeric characters. An "alphanumeric" character for this purpose is one that matches unichar-isalnum? or unichar-ismark?.

Each token is then (Unicode) normalised and case-folded. If ascii-alternates is non-NULL and some of the returned tokens contain non-ASCII characters, ASCII alternatives will be generated.

The number of ASCII alternatives that are generated and the method for doing so is unspecified, but translit-locale (if specified) may improve the transliteration if the language of the source string is known.

string

Passed: a string.

a string to tokenize

translit-locale

Passed, or left out: a string, or #f.

the language code (like ’de’ or ’en_GB’) from which string originates

%return

Returned: a vector, each a string.

the folded tokens

ascii-alternates

Returned: a vector, each a string.

a return location for ASCII alternates

Procedure: strcanon string valid-chars substitutor ⇒ %return

For each character in string, if the character is not in valid-chars, replaces the character with substitutor.

Modifies string in place, and return string itself, not a copy. The return value is to allow nesting such as:

g_ascii_strup (g_strcanon (str, "abc", '?'))

In order to modify a copy, you may use strdup:

reformatted = g_strcanon (g_strdup (const_str), "abc", '?');
…
g_free (reformatted);
string

Passed: a string.

a nul-terminated array of bytes

valid-chars

Passed: a string.

bytes permitted in string

substitutor

Passed: an 8-bit integer, or a character.

replacement character for disallowed bytes

%return

Returned: a string.

the modified string

Procedure: strchomp string ⇒ %return

Removes trailing whitespace from a string.

This function doesn’t allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

The pointer to string is returned to allow the nesting of functions.

Also see strchug and GLib.strstrip.

string

Passed: a string.

a string to remove the trailing whitespace from

%return

Returned: a string.

the modified string

Procedure: strchug string ⇒ %return

Removes leading whitespace from a string, by moving the rest of the characters forward.

This function doesn’t allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

The pointer to string is returned to allow the nesting of functions.

Also see strchomp and GLib.strstrip.

string

Passed: a string.

a string to remove the leading whitespace from

%return

Returned: a string.

the modified string

Procedure: strcmp0 [str1] [str2] ⇒ %return

Compares str1 and str2 like strcmp().

Handles NULL gracefully by sorting it before non-NULL strings. Comparing two NULL pointers returns 0.

str1

Passed, or left out: a string, or #f.

a string

str2

Passed, or left out: a string, or #f.

another string

%return

Returned: a 32-bit integer.

an integer less than, equal to, or greater than zero, if str1 is <, == or > than str2

Procedure: strcompress source ⇒ %return

Makes a copy of a string replacing C string-style escape sequences with their one byte equivalent:

strescape does the reverse conversion.

source

Passed: a string.

a string to compress

%return

Returned: a string.

a newly-allocated copy of source with all escaped character compressed

Procedure: strdelimit string delimiters new-delimiter ⇒ %return

Converts any delimiter characters in string to new-delimiter.

Any characters in string which are found in delimiters are changed to the new-delimiter character. Modifies string in place, and returns string itself, not a copy.

The return value is to allow nesting such as:

g_ascii_strup (g_strdelimit (str, "abc", '?'))

In order to modify a copy, you may use strdup:

reformatted = g_strdelimit (g_strdup (const_str), "abc", '?');
…
g_free (reformatted);
string

Passed: a string.

the string to convert

delimiters

Passed: a string, or #f.

a string containing the current delimiters, or NULL to use the standard delimiters defined in GLib.STR_DELIMITERS

new-delimiter

Passed: an 8-bit integer, or a character.

the new delimiter character

%return

Returned: a string.

the modified string

Procedure: strdup [str] ⇒ %return

Duplicates a string. If str is NULL it returns NULL.

str

Passed, or left out: a string, or #f.

the string to duplicate

%return

Returned: a string.

a newly-allocated copy of str

Procedure: strdupv [str-array] ⇒ %return

Copies an array of strings. The copy is a deep copy; each string is also copied.

If called on a NULL value, strdupv simply returns NULL.

str-array

Passed, or left out: a list or vector, each a string, or #f.

an array of strings to copy

%return

Returned: a vector, each a string, or #f.

a newly-allocated array of strings. Use strfreev to free it.

Procedure: strerror errnum ⇒ %return

Returns a string corresponding to the given error code, e.g. "no such process".

Unlike strerror(), this always returns a string in UTF-8 encoding, and the pointer is guaranteed to remain valid for the lifetime of the process. If the error code is unknown, it returns a string like “Unknown error <code\>”.

Note that the string may be translated according to the current locale.

The value of errno will not be changed by this function. However, it may be changed by intermediate function calls, so you should save its value as soon as the call returns:

int saved_errno;

ret = read (blah);
saved_errno = errno;

g_strerror (saved_errno);
errnum

Passed: a 32-bit integer.

the system error number. See the standard C errno documentation

%return

Returned: a string.

the string describing the error code

Procedure: strescape source [exceptions] ⇒ %return

It replaces the following special characters in the string source with their corresponding C escape sequence:

| Symbol | Escape | |—————————————————————————–|——–| | U+0008 Backspace | \b | | U+000C Form Feed | \f | | U+000A Line Feed | \n | | U+000D Carriage Return | \r | | U+0009 Horizontal Tabulation | \t | | U+000B Vertical Tabulation | \v |

It also inserts a backslash (\) before any backslash or a double quote ("). Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a backslash followed by their octal representation. Characters supplied in exceptions are not escaped.

strcompress does the reverse conversion.

source

Passed: a string.

a string to escape

exceptions

Passed, or left out: a string, or #f.

a string of characters not to escape in source

%return

Returned: a string.

a newly-allocated copy of source with special characters escaped

Procedure: strfreev [str-array]

Frees an array of strings, as well as each string it contains.

If str-array is NULL, this function simply returns.

str-array

Passed, or left out: a list or vector, each a string, or #f.

an array of strings to free

Procedure: strip-context msgid msgval ⇒ %return

An auxiliary function for gettext() support (see Q_()).

msgid

Passed: a string.

a string

msgval

Passed: a string.

another string

%return

Returned: a string.

msgval, unless msgval is identical to msgid and contains a ’|’ character, in which case a pointer to the substring of msgid after the first ’|’ character is returned.

Procedure: strjoinv separator str-array ⇒ %return

Joins an array of strings together to form one long string, with the optional separator inserted between each of them.

If str-array has no items, the return value will be an empty string. If str-array contains a single item, separator will not appear in the resulting string.

separator

Passed: a string, or #f.

a string to insert between each of the strings

str-array

Passed: a list or vector, each a string.

an array of strings to join

%return

Returned: a string.

a newly-allocated string containing all of the strings joined together, with separator between them

Procedure: strlcat dest src dest-size ⇒ %return

Portability wrapper that calls strlcat() on systems which have it, and emulates it otherwise. Appends nul-terminated src string to dest, guaranteeing nul-termination for dest. The total size of dest won’t exceed dest-size.

At most dest-size - 1 characters will be copied. Unlike strncat(), dest-size is the full size of dest, not the space left over. This function does not allocate memory. It always nul-terminates (unless dest-size == 0 or there were no nul characters in the dest-size characters of dest to start with).

Caveat: this is supposedly a more secure alternative to strcat() or strncat(), but for real security GLib.strconcat is harder to mess up.

dest

Passed: a string.

destination buffer, already containing one nul-terminated string

src

Passed: a string.

source buffer

dest-size

Passed: an unsigned 64-bit integer.

length of dest buffer in bytes (not length of existing string inside dest)

%return

Returned: an unsigned 64-bit integer.

size of attempted result, which is MIN (dest_size, strlen (original dest)) + strlen (src), so if retval >= dest-size, truncation occurred

Procedure: strlcpy dest src dest-size ⇒ %return

Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise. Copies src to dest; dest is guaranteed to be nul-terminated; src must be nul-terminated; dest-size is the buffer size, not the number of bytes to copy.

At most dest-size - 1 characters will be copied. Always nul-terminates (unless dest-size is 0). This function does not allocate memory. Unlike strncpy(), this function doesn’t pad dest (so it’s often faster). It returns the size of the attempted result, strlen (src), so if retval >= dest-size, truncation occurred.

Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(), but if you really want to avoid screwups, strdup is an even better idea.

dest

Passed: a string.

destination buffer

src

Passed: a string.

source buffer

dest-size

Passed: an unsigned 64-bit integer.

length of dest in bytes

%return

Returned: an unsigned 64-bit integer.

length of src

Procedure: strndup str n ⇒ %return

Duplicates the first n bytes of a string, returning a newly-allocated buffer n + 1 bytes long which will always be nul-terminated. If str is less than n bytes long the buffer is padded with nuls. If str is NULL it returns NULL.

To copy a number of characters from a UTF-8 encoded string, use utf8-strncpy instead.

str

Passed: a string, or #f.

the string to duplicate

n

Passed: an unsigned 64-bit integer.

the maximum number of bytes to copy from str

%return

Returned: a string, or #f.

a newly-allocated buffer containing the first n bytes of str

Procedure: strnfill length fill-char ⇒ %return

Creates a new string length bytes long filled with fill-char.

length

Passed: an unsigned 64-bit integer.

the length of the new string

fill-char

Passed: an 8-bit integer, or a character.

the byte to fill the string with

%return

Returned: a string.

a newly-allocated string filled with fill-char

Procedure: strreverse string ⇒ %return

Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".

Note that strreverse doesn’t work on UTF-8 strings containing multibyte characters. For that purpose, use utf8-strreverse.

string

Passed: a string.

the string to reverse

%return

Returned: a string.

the string, reversed in place

Procedure: strrstr haystack needle ⇒ %return

Searches the string haystack for the last occurrence of the string needle.

The fact that this function returns gchar * rather than const gchar * is a historical artifact.

haystack

Passed: a string.

a string to search in

needle

Passed: a string.

the string to search for

%return

Returned: a string, or #f.

a pointer to the found occurrence, or NULL if not found

Procedure: strrstr-len haystack haystack-len needle ⇒ %return

Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystack-len.

The fact that this function returns gchar * rather than const gchar * is a historical artifact.

haystack

Passed: a string.

a string to search in

haystack-len

Passed: a 64-bit integer.

the maximum length of haystack in bytes. A length of -1 can be used to mean "search the entire string", like strrstr

needle

Passed: a string.

the string to search for

%return

Returned: a string, or #f.

a pointer to the found occurrence, or NULL if not found

Procedure: strsignal signum ⇒ %return

Returns a string describing the given signal, e.g. "Segmentation fault". If the signal is unknown, it returns “unknown signal (<signum\>)”.

You should use this function in preference to strsignal(), because it returns a string in UTF-8 encoding, and since not all platforms support the strsignal() function.

signum

Passed: a 32-bit integer.

the signal number. See the signal documentation

%return

Returned: a string.

the string describing the signal

Procedure: strsplit string delimiter max-tokens ⇒ %return

Splits a string into a maximum of max-tokens pieces, using the given delimiter. If max-tokens is reached, the remainder of string is appended to the last token.

As an example, the result of g_strsplit (":a:bc::d:", ":", -1) is an array containing the six strings "", "a", "bc", "", "d" and "".

As a special case, the result of splitting the empty string "" is an empty array, not an array containing a single string. The reason for this special case is that being able to represent an empty array is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you’ll need to check for the empty string before calling strsplit.

string

Passed: a string.

a string to split

delimiter

Passed: a string.

a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unless max-tokens is reached.

max-tokens

Passed: a 32-bit integer.

the maximum number of pieces to split string into If this is less than 1, the string is split completely

%return

Returned: a vector, each a string.

a newly-allocated array of strings, freed with strfreev

Procedure: strsplit-set string delimiters max-tokens ⇒ %return

Splits string into a number of tokens not containing any of the bytes in delimiters.

A token is the (possibly empty) longest string that does not contain any of the bytes in delimiters. Note that separators will only be single bytes from delimiters. If max-tokens is reached, the remainder is appended to the last token.

For example, the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is an array containing the three strings "abc", "def", and "ghi".

The result of g_strsplit_set (":def/ghi:/x", ":/", -1) is an array containing the five strings "", "def", "ghi", "", "x".

As a special case, the result of splitting the empty string "" is an empty array, not an array containing a single string. The reason for this special case is that being able to represent an empty array is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you’ll need to check for the empty string before calling strsplit-set.

Note that this function works on bytes not characters, so it can’t be used to delimit UTF-8 strings for anything but ASCII characters.

string

Passed: a string.

a string to split

delimiters

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

a nul-terminated byte array containing bytes that are used to split the string; can be empty (just a nul byte), which will result in no string splitting

max-tokens

Passed: a 32-bit integer.

the maximum number of tokens to split string into. If this is less than 1, the string is split completely

%return

Returned: a vector, each a string.

a newly-allocated array of strings. Use strfreev to free it.

Procedure: strstr-len haystack haystack-len needle ⇒ %return

Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystack-len or a nul terminator byte (whichever is reached first).

A length of -1 can be used to mean “search the entire string”, like strstr().

The fact that this function returns gchar * rather than const gchar * is a historical artifact.

haystack

Passed: a string.

a string to search in

haystack-len

Passed: a 64-bit integer.

the maximum length of haystack in bytes, or -1 to search it entirely

needle

Passed: a string.

the string to search for

%return

Returned: a string, or #f.

a pointer to the found occurrence, or NULL if not found

Procedure: strtod nptr ⇒ %return endptr

Converts a string to a floating point value.

It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with ascii-strtod, and returns the best match.

This function should seldom be used. The normal situation when reading numbers not for human consumption is to use ascii-strtod. Only when you know that you must expect both locale formatted and C formatted numbers should you use this. Make sure that you don’t pass strings such as comma separated lists of values, since the commas may be interpreted as a decimal point in some locales, causing unexpected results.

nptr

Passed: a string.

the string to convert to a numeric value

%return

Returned: a real number.

the converted value

endptr

Returned: a string.

if non-NULL, it returns the character after the last character used in the conversion

Procedure: strv-contains? strv str ⇒ %return

Checks if an array of strings contains the string str according to str-equal?. strv must not be NULL.

strv

Passed: a list or vector, each a string.

an array of strings to search in

str

Passed: a string.

the string to search for

%return

Returned: a boolean.

true if str is an element of strv

Procedure: strv-equal? strv1 strv2 ⇒ %return

Checks if two arrays of strings contain exactly the same elements in exactly the same order.

Elements are compared using str-equal?. To match independently of order, sort the arrays first (using GLib.qsort_with_data or similar).

Two empty arrays are considered equal. Neither strv1 nor strv2 may be NULL.

strv1

Passed: a list or vector, each a string.

an array of strings to compare to strv2

strv2

Passed: a list or vector, each a string.

an array of strings to compare to strv1

%return

Returned: a boolean.

true if strv1 and strv2 are equal

Procedure: strv-get-type ⇒ %return
%return

Returned: a class, or a GType number.

Procedure: strv-length str-array ⇒ %return

Returns the length of an array of strings. str-array must not be NULL.

str-array

Passed: a list or vector, each a string.

an array of strings

%return

Returned: an unsigned 32-bit integer.

length of str-array

Procedure: test-add-data-func testpath test-data test-func

Creates a new test case.

This function is similar to GLib.test_create_case. However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions of testpath. The test-data argument will be passed as first argument to test-func.

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or test-trap-subprocess.

No component of testpath may start with a dot (.) if the GLib.TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

testpath

Passed: a string.

a /-separated name for the test

test-data

Passed: a foreign pointer, or a bytevector, or #f.

data for the test-func

test-func

Passed: a procedure.

the test function to invoke for this test

See GTestDataFunc for how it is called.

Procedure: test-add-data-func-full testpath test-data test-func

Creates a new test case.

In contrast to test-add-data-func, this function is freeing test-data after the test run is complete.

testpath

Passed: a string.

a /-separated name for the test

test-data

Passed: a foreign pointer, or a bytevector, or #f.

data for test-func

test-func

Passed: a procedure.

the test function to invoke for this test

See GTestDataFunc for how it is called.

data-free-func

Not passed: guile-gi supplies it.

GDestroyNotify for test-data

See GDestroyNotify for how it is called.

Procedure: test-add-func testpath test-func

Creates a new test case.

This function is similar to GLib.test_create_case. However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions of testpath.

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or test-trap-subprocess.

No component of testpath may start with a dot (.) if the GLib.TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

testpath

Passed: a string.

a /-separated name for the test

test-func

Passed: a procedure.

the test function to invoke for this test

See GTestFunc for how it is called.

Procedure: test-assert-expected-messages-internal domain file line func
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

Procedure: test-bug bug-uri-snippet

Adds a message to test reports that associates a bug URI with a test case.

Bug URIs are constructed from a base URI set with test-bug-base and bug-uri-snippet. If test-bug-base has not been called, it is assumed to be the empty string, so a full URI can be provided to test-bug instead.

See also test-summary.

Since GLib 2.70, the base URI is not prepended to bug-uri-snippet if it is already a valid URI.

bug-uri-snippet

Passed: a string.

Bug specific bug tracker URI or URI portion.

Procedure: test-bug-base uri-pattern

Specifies the base URI for bug reports.

The base URI is used to construct bug report messages for GLib.test_message when test-bug is called. Calling this function outside of a test case sets the default base URI for all test cases. Calling it from within a test case changes the base URI for the scope of the test case only. Bug URIs are constructed by appending a bug specific URI portion to uri-pattern, or by replacing the special string %s within uri-pattern if that is present.

If test-bug-base is not called, bug URIs are formed solely from the value provided by test-bug.

uri-pattern

Passed: a string.

the base pattern for bug URIs

Procedure: test-disable-crash-reporting

Attempts to disable system crash reporting infrastructure.

This function should be called before exercising code paths that are expected or intended to crash, to avoid wasting resources in system-wide crash collection infrastructure such as systemd-coredump or abrt.

Procedure: test-expect-message log-domain log-level pattern

Indicates that a message with the given log-domain and log-level, with text matching pattern, is expected to be logged.

When this message is logged, it will not be printed, and the test case will not abort.

This API may only be used with the old logging API (GLib.log without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See Testing for Messages.

Use GLib.test_assert_expected_messages to assert that all previously-expected messages have been seen and suppressed.

You can call this multiple times in a row, if multiple messages are expected as a result of a single call. (The messages must appear in the same order as the calls to test-expect-message.)

For example:

// g_main_context_push_thread_default() should fail if the
// context is already owned by another thread.
g_test_expect_message (G_LOG_DOMAIN,
                       G_LOG_LEVEL_CRITICAL,
                       "assertion*acquired_context*failed");
g_main_context_push_thread_default (bad_context);
g_test_assert_expected_messages ();

Note that you cannot use this to test GLib.error messages, since GLib.error intentionally never returns even if the program doesn’t abort; use test-trap-subprocess in this case.

If messages at GLib.LogLevelFlags.LEVEL_DEBUG are emitted, but not explicitly expected via test-expect-message then they will be ignored.

log-domain

Passed: a string, or #f.

the log domain of the message

log-level

Passed: a <%GLogLevelFlags>, or a list of its symbols, or one of them.

the log level of the message

pattern

Passed: a string.

a glob-style pattern (see <GPatternSpec>)

Procedure: test-fail

Indicates that a test failed.

This function can be called multiple times from the same test. You can use this function if your test failed in a recoverable way.

Do not use this function if the failure of a test could cause other tests to malfunction.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Note that unlike test-skip and test-incomplete, this function does not log a message alongside the test failure. If details of the test failure are available, either log them with GLib.test_message before test-fail, or use GLib.test_fail_printf instead.

Procedure: test-failed? ⇒ %return

Returns whether a test has already failed.

This will be the case when test-fail, test-incomplete or test-skip have been called, but also if an assertion has failed.

This can be useful to return early from a test if continuing after a failed assertion might be harmful.

The return value of this function is only meaningful if it is called from inside a test function.

%return

Returned: a boolean.

true if the test has failed

Procedure: test-get-dir file-type ⇒ %return

Gets the pathname of the directory containing test files of the type specified by file-type.

This is approximately the same as calling g_test_build_filename("."), but you don’t need to free the return value.

file-type

Passed: a <%GTestFileType>, or one of its symbols.

the type of file (built vs. distributed)

%return

Returned: a file name, as a string.

the path of the directory, owned by GLib

Procedure: test-get-path ⇒ %return

Gets the test path for the test currently being run.

In essence, it will be the same string passed as the first argument to e.g. GLib.test_add when the test was added.

This function returns a valid string only within a test function.

Note that this is a test path, not a file system path.

%return

Returned: a string.

the test path for the test currently being run

Procedure: test-incomplete [msg]

Indicates that a test failed because of some incomplete functionality.

This function can be called multiple times from the same test.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

msg

Passed, or left out: a string, or #f.

explanation

Procedure: test-log-type-name log-type ⇒ %return
log-type

Passed: a <%GTestLogType>, or one of its symbols.

%return

Returned: a string.

Procedure: test-queue-destroy destroy-func [destroy-data]

Enqueues a callback destroy-func to be executed during the next test case teardown phase.

This is most useful to auto destroy allocated test resources at the end of a test run. Resources are released in reverse queue order, that means enqueueing callback A before callback B will cause B() to be called before A() during teardown.

destroy-func

Passed: a procedure.

destroy callback for teardown phase

See GDestroyNotify for how it is called.

destroy-data

Passed, or left out: a foreign pointer, or a bytevector, or #f.

destroy callback data

Procedure: test-queue-free [gfree-pointer]

Enqueues a pointer to be released with byte-array:free during the next teardown phase.

This is equivalent to calling test-queue-destroy with a destroy callback of byte-array:free.

gfree-pointer

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the pointer to be stored

Procedure: test-rand-double ⇒ %return

Gets a reproducible random floating point number.

See test-rand-int for details on test case random numbers.

%return

Returned: a real number.

a random number from the seeded random number generator

Procedure: test-rand-double-range range-start range-end ⇒ %return

Gets a reproducible random floating point number out of a specified range.

See test-rand-int for details on test case random numbers.

range-start

Passed: a real number.

the minimum value returned by this function

range-end

Passed: a real number.

the minimum value not returned by this function

%return

Returned: a real number.

a number with range-start <= number < range-end

Procedure: test-rand-int ⇒ %return

Gets a reproducible random integer number.

The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the –seed option is given when starting test programs.

For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make –seed effective for all test cases.

%return

Returned: a 32-bit integer.

a random number from the seeded random number generator

Procedure: test-rand-int-range begin end ⇒ %return

Gets a reproducible random integer number out of a specified range.

See test-rand-int for details on test case random numbers.

begin

Passed: a 32-bit integer.

the minimum value returned by this function

end

Passed: a 32-bit integer.

the smallest value not to be returned by this function

%return

Returned: a 32-bit integer.

a number with begin <= number < end

Procedure: test-run ⇒ %return

Runs all tests under the toplevel suite.

The toplevel suite can be retrieved with GLib.test_get_root.

Similar to GLib.test_run_suite, the test cases to be run are filtered according to test path arguments (-p testpath and -s testpath) as parsed by GLib.test_init. GLib.test_run_suite or test-run may only be called once in a program.

In general, the tests and sub-suites within each suite are run in the order in which they are defined. However, note that prior to GLib 2.36, there was a bug in the g_test_add_* functions which caused them to create multiple suites with the same name, meaning that if you created tests "/foo/simple", "/bar/simple", and "/foo/using-bar" in that order, they would get run in that order (since test-run would run the first "/foo" suite, then the "/bar" suite, then the second "/foo" suite). As of 2.36, this bug is fixed, and adding the tests in that order would result in a running order of "/foo/simple", "/foo/using-bar", "/bar/simple". If this new ordering is sub-optimal (because it puts more-complicated tests before simpler ones, making it harder to figure out exactly what has failed), you can fix it by changing the test paths to group tests by suite in a way that will result in the desired running order. Eg, "/simple/foo", "/simple/bar", "/complex/foo-using-bar".

However, you should never make the actual result of a test depend on the order that tests are run in. If you need to ensure that some particular code runs before or after a given test case, use GLib.test_add, which lets you specify setup and teardown functions.

If all tests are skipped or marked as incomplete (expected failures), this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.

%return

Returned: a 32-bit integer.

0 on success, 1 on failure (assuming it returns at all), 0 or 77 if all tests were skipped or marked as incomplete

Procedure: test-set-nonfatal-assertions

Changes the behaviour of the various assertion macros.

The g_assert_*() macros, g_test_assert_expected_messages() and the various g_test_trap_assert_*() macros are changed to not abort to program.

Instead, they will call test-fail and continue. (This also changes the behavior of test-fail so that it will not cause the test program to abort after completing the failed test.)

Note that the GLib.assert_not_reached and GLib.assert macros are not affected by this.

This function can only be called after GLib.test_init.

Procedure: test-skip [msg]

Indicates that a test was skipped.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

msg

Passed, or left out: a string, or #f.

explanation

Procedure: test-subprocess? ⇒ %return

Returns true if the test program is running under test-trap-subprocess.

%return

Returned: a boolean.

true if the test program is running under test-trap-subprocess

Procedure: test-summary summary

Sets the summary for a test.

This may be included in test report output, and is useful documentation for anyone reading the source code or modifying a test in future. It must be a single line, and it should summarise what the test checks, and how.

This should be called at the top of a test function.

For example:

static void
test_array_sort (void)
{
  g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
                  "including testing zero length and one-element arrays.");

  // ...
}

See also test-bug.

summary

Passed: a string.

summary of the test purpose

Procedure: test-timer-elapsed ⇒ %return

Gets the number of seconds since the last start of the timer with test-timer-start.

%return

Returned: a real number.

the time since the last start of the timer in seconds

Procedure: test-timer-last ⇒ %return

Reports the last result of test-timer-elapsed.

%return

Returned: a real number.

the last result of test-timer-elapsed

Procedure: test-timer-start

Starts a timing test.

Call test-timer-elapsed when the task is supposed to be done. Call this function again to restart the timer.

Procedure: test-trap-assertions domain file line func assertion-flags pattern
domain

Passed: a string.

file

Passed: a string.

line

Passed: a 32-bit integer.

func

Passed: a string.

assertion-flags

Passed: an unsigned 64-bit integer.

pattern

Passed: a string.

Procedure: test-trap-has-passed? ⇒ %return

Checks the result of the last test-trap-subprocess call.

%return

Returned: a boolean.

true if the last test subprocess terminated successfully

Procedure: test-trap-has-skipped? ⇒ %return

Checks the result of the last test-trap-subprocess call.

%return

Returned: a boolean.

true if the last test subprocess was skipped

Procedure: test-trap-reached-timeout? ⇒ %return

Checks the result of the last test-trap-subprocess call.

%return

Returned: a boolean.

true if the last test subprocess got killed due to a timeout

Procedure: test-trap-subprocess test-path usec-timeout test-flags

Respawns the test program to run only test-path in a subprocess.

This is equivalent to calling test-trap-subprocess-with-envp with envp set to NULL. See the documentation for that function for full details.

test-path

Passed: a string, or #f.

test to run in a subprocess

usec-timeout

Passed: an unsigned 64-bit integer.

timeout for the subprocess test in microseconds.

test-flags

Passed: a <%GTestSubprocessFlags>, or a list of its symbols, or one of them.

flags to modify subprocess behaviour

Procedure: test-trap-subprocess-with-envp test-path envp usec-timeout test-flags

Respawns the test program to run only test-path in a subprocess with a given environment.

This can be used for a test case that might not return, or that might abort.

If test-path is NULL then the same test is re-run in a subprocess. You can use test-subprocess? to determine whether the test is in a subprocess or not.

test-path can also be the name of the parent test, followed by "‘/subprocess/" and then a name for the specific subtest (or just ending with "/subprocess‘" if the test only has one child test); tests with names of this form will automatically be skipped in the parent process.

If envp is NULL, the parent process’ environment will be inherited.

If usec-timeout is non-0, the test subprocess is aborted and considered failing if its run time exceeds it.

The subprocess behavior can be configured with <%GTestSubprocessFlags> flags.

You can use methods such as GLib.test_trap_assert_passed, GLib.test_trap_assert_failed, and GLib.test_trap_assert_stderr to check the results of the subprocess. (But note that GLib.test_trap_assert_stdout and GLib.test_trap_assert_stderr cannot be used if test-flags specifies that the child should inherit the parent stdout/stderr.)

If your main () needs to behave differently in the subprocess, you can call test-subprocess? (after calling GLib.test_init) to see whether you are in a subprocess.

Internally, this function tracks the child process using child-watch-source-new, so your process must not ignore SIGCHLD, and must not attempt to watch or wait for the child process via another mechanism.

The following example tests that calling my_object_new(1000000) will abort with an error message.

  static void
  test_create_large_object (void)
  {
    if (g_test_subprocess ())
      {
        my_object_new (1000000);
        return;
      }

    // Reruns this same test in a subprocess
    g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
    g_test_trap_assert_failed ();
    g_test_trap_assert_stderr ("*ERROR*too large*");
  }

  static void
  test_different_username (void)
  {
    if (g_test_subprocess ())
      {
        // Code under test goes here
        g_message ("Username is now simulated as %s", g_getenv ("USER"));
        return;
      }

    // Reruns this same test in a subprocess
    g_auto(GStrv) envp = g_get_environ ();
    envp = g_environ_setenv (g_steal_pointer (&envp), "USER", "charlie", TRUE);
    g_test_trap_subprocess_with_envp (NULL, envp, 0, G_TEST_SUBPROCESS_DEFAULT);
    g_test_trap_assert_passed ();
    g_test_trap_assert_stdout ("Username is now simulated as charlie");
  }

  int
  main (int argc, char **argv)
  {
    g_test_init (&argc, &argv, NULL);

    g_test_add_func ("/myobject/create-large-object",
                     test_create_large_object);
    g_test_add_func ("/myobject/different-username",
                     test_different_username);
    return g_test_run ();
  }
test-path

Passed: a string, or #f.

test to run in a subprocess

envp

Passed: a list or vector, each a file name, as a string, or #f.

environment to run the test in

usec-timeout

Passed: an unsigned 64-bit integer.

timeout for the subprocess test in microseconds

test-flags

Passed: a <%GTestSubprocessFlags>, or a list of its symbols, or one of them.

flags to modify subprocess behaviour

Procedure: thread-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: thread-exit [retval]

Terminates the current thread.

If another thread is waiting for us using thread:join then the waiting thread will be woken up and get retval as the return value of thread:join.

Calling thread-exit with a parameter retval is equivalent to returning retval from the function func, as given to thread:new.

You must only call thread-exit from a thread that you created yourself with thread:new or related APIs. You must not call this function from a thread created with another threading library or or from within a GThreadPool.

retval

Passed, or left out: a foreign pointer, or a bytevector, or #f.

the return value of this thread

Procedure: thread-pool-get-max-idle-time ⇒ %return

This function will return the maximum interval that a thread will wait in the thread pool for new tasks before being stopped.

If this function returns 0, threads waiting in the thread pool for new work are not stopped.

%return

Returned: an unsigned 32-bit integer.

the maximum interval (milliseconds) to wait for new tasks in the thread pool before stopping the thread

Procedure: thread-pool-get-max-unused-threads ⇒ %return

Returns the maximal allowed number of unused threads.

%return

Returned: a 32-bit integer.

the maximal number of unused threads

Procedure: thread-pool-get-num-unused-threads ⇒ %return

Returns the number of currently unused threads.

%return

Returned: an unsigned 32-bit integer.

the number of currently unused threads

Procedure: thread-pool-set-max-idle-time interval

This function will set the maximum interval that a thread waiting in the pool for new tasks can be idle for before being stopped. This function is similar to calling thread-pool-stop-unused-threads on a regular timeout, except this is done on a per thread basis.

By setting interval to 0, idle threads will not be stopped.

The default value is 15000 (15 seconds).

interval

Passed: an unsigned 32-bit integer.

the maximum interval (in milliseconds) a thread can be idle

Procedure: thread-pool-set-max-unused-threads max-threads

Sets the maximal number of unused threads to max-threads. If max-threads is -1, no limit is imposed on the number of unused threads.

The default value is 8 since GLib 2.84. Previously the default value was 2.

max-threads

Passed: a 32-bit integer.

maximal number of unused threads

Procedure: thread-pool-stop-unused-threads

Stops all currently unused threads. This does not change the maximal number of unused threads. This function can be used to regularly stop all unused threads e.g. from timeout-add.

Procedure: thread-self ⇒ %return

This function returns the <GThread> corresponding to the current thread. Note that this function does not increase the reference count of the returned struct.

This function will return a <GThread> even for threads that were not created by GLib (i.e. those created by other threading APIs). This may be useful for thread identification purposes (i.e. comparisons) but you must not use GLib functions (such as thread:join) on these threads.

%return

Returned: a <GThread>.

the <GThread> representing the current thread

Procedure: thread-yield

Causes the calling thread to voluntarily relinquish the CPU, so that other threads can run.

This function is often used as a method to make busy wait less evil.

Procedure: timeout-add priority interval function ⇒ %return

Sets a function to be called at regular intervals, with the default priority, GLib.PRIORITY_DEFAULT.

The given function is called repeatedly until it returns GLib.SOURCE_REMOVE, at which point the timeout is automatically destroyed and the function will not be called again. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to ‘catch up’ time lost in delays).

See main loop memory management for details on how to handle the return value and memory management of data.

If you want to have a timer in the ‘seconds’ range and do not care about the exact time of the first call of the timer, use the timeout-add-seconds function; this function allows for more optimizations and more efficient system power usage.

This internally creates a main loop source using timeout-source-new and attaches it to the global <GMainContext> using source:attach, so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

It is safe to call this function from any thread.

The interval given is in terms of monotonic time, not wall clock time. See get-monotonic-time.

priority

Passed: a 32-bit integer.

interval

Passed: an unsigned 32-bit integer.

the time between calls to the function, in milliseconds

function

Passed: a procedure.

function to call

See GSourceFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the ID (greater than 0) of the event source

notify

Not passed: guile-gi supplies it.

data

Not passed: guile-gi supplies it.

data to pass to function

Procedure: timeout-add-seconds priority interval function ⇒ %return

Sets a function to be called at regular intervals with the default priority, GLib.PRIORITY_DEFAULT.

The function is called repeatedly until it returns GLib.SOURCE_REMOVE, at which point the timeout is automatically destroyed and the function will not be called again.

This internally creates a main loop source using timeout-source-new-seconds and attaches it to the main loop context using source:attach. You can do these steps manually if you need greater control. Also see GLib.timeout_add_seconds_full.

It is safe to call this function from any thread.

Note that the first call of the timer may not be precise for timeouts of one second. If you need finer precision and have such a timeout, you may want to use timeout-add instead.

See main loop memory management for details on how to handle the return value and memory management of data.

The interval given is in terms of monotonic time, not wall clock time. See get-monotonic-time.

priority

Passed: a 32-bit integer.

interval

Passed: an unsigned 32-bit integer.

the time between calls to the function, in seconds

function

Passed: a procedure.

function to call

See GSourceFunc for how it is called.

%return

Returned: an unsigned 32-bit integer.

the ID (greater than 0) of the event source

notify

Not passed: guile-gi supplies it.

data

Not passed: guile-gi supplies it.

data to pass to function

Procedure: timeout-source-new interval ⇒ %return

Creates a new timeout source.

The source will not initially be associated with any <GMainContext> and must be added to one with source:attach before it will be executed.

The interval given is in terms of monotonic time, not wall clock time. See get-monotonic-time.

interval

Passed: an unsigned 32-bit integer.

the timeout interval in milliseconds

%return

Returned: a <GSource>.

the newly-created timeout source

Procedure: timeout-source-new-seconds interval ⇒ %return

Creates a new timeout source.

The source will not initially be associated with any <GMainContext> and must be added to one with source:attach before it will be executed.

The scheduling granularity/accuracy of this timeout source will be in seconds.

The interval given is in terms of monotonic time, not wall clock time. See get-monotonic-time.

interval

Passed: an unsigned 32-bit integer.

the timeout interval in seconds

%return

Returned: a <GSource>.

the newly-created timeout source

Procedure: try-malloc n-bytes ⇒ %return

Attempts to allocate n-bytes, and returns #f on failure. Contrast with malloc, which aborts the program on failure.

n-bytes

Passed: an unsigned 64-bit integer.

number of bytes to allocate.

%return

Returned: a foreign pointer, or #f.

the allocated memory, or #f.

Procedure: try-malloc-n n-blocks n-block-bytes ⇒ %return

This function is similar to try-malloc, allocating (n-blocks * n-block-bytes) bytes, but care is taken to detect possible overflow during multiplication.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

%return

Returned: a foreign pointer, or #f.

the allocated memory, or #f.

Procedure: try-malloc0 n-bytes ⇒ %return

Attempts to allocate n-bytes, initialized to 0’s, and returns #f on failure. Contrast with malloc0, which aborts the program on failure.

n-bytes

Passed: an unsigned 64-bit integer.

number of bytes to allocate

%return

Returned: a foreign pointer, or #f.

the allocated memory, or #f

Procedure: try-malloc0-n n-blocks n-block-bytes ⇒ %return

This function is similar to try-malloc0, allocating (n-blocks * n-block-bytes) bytes, but care is taken to detect possible overflow during multiplication.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

%return

Returned: a foreign pointer, or #f.

the allocated memory, or #f

Procedure: try-realloc mem n-bytes ⇒ %return

Attempts to realloc mem to a new size, n-bytes, and returns #f on failure. Contrast with realloc, which aborts the program on failure.

If mem is #f, behaves the same as try-malloc.

mem

Passed: a foreign pointer, or a bytevector, or #f.

previously-allocated memory, or #f.

n-bytes

Passed: an unsigned 64-bit integer.

number of bytes to allocate.

%return

Returned: a foreign pointer, or #f.

the allocated memory, or #f.

Procedure: try-realloc-n mem n-blocks n-block-bytes ⇒ %return

This function is similar to try-realloc, allocating (n-blocks * n-block-bytes) bytes, but care is taken to detect possible overflow during multiplication.

mem

Passed: a foreign pointer, or a bytevector, or #f.

previously-allocated memory, or #f.

n-blocks

Passed: an unsigned 64-bit integer.

the number of blocks to allocate

n-block-bytes

Passed: an unsigned 64-bit integer.

the size of each block in bytes

%return

Returned: a foreign pointer, or #f.

the allocated memory, or #f.

Procedure: ucs4-to-utf16 str ⇒ %return items-read items-written

Convert a string from UCS-4 to UTF-16.

A nul character (U+0000) will be added to the result after the converted text.

str

Passed: a string.

a UCS-4 encoded string

%return

Returned: an unsigned 16-bit integer.

a pointer to a newly allocated UTF-16 string. This value must be freed with byte-array:free.

items-read

Returned: a 64-bit integer.

location to store number of bytes read, or NULL to ignore. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.

items-written

Returned: a 64-bit integer.

location to store number of gunichar2 written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.

len

Not passed: guile-gi gives the length of str.

the maximum length (number of characters) of str to use. If len is negative, then the string is nul-terminated.

Procedure: ucs4-to-utf8 str ⇒ %return items-read items-written

Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8.

The result will be terminated with a nul byte.

str

Passed: a string.

a UCS-4 encoded string

%return

Returned: a string.

a pointer to a newly allocated UTF-8 string. This value must be freed with byte-array:free.

items-read

Returned: a 64-bit integer.

location to store number of characters read, or NULL to ignore. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.

items-written

Returned: a 64-bit integer.

location to store number of bytes written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.

len

Not passed: guile-gi gives the length of str.

the maximum length (number of characters) of str to use. If len is negative, then the string is nul-terminated.

Procedure: unichar-break-type c ⇒ %return

Determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use utf8-get-char). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally you would use a function such as pango_break() instead of caring about break types yourself.

c

Passed: a character.

a Unicode character

%return

Returned: a <GUnicodeBreakType>.

the break type of c

Procedure: unichar-combining-class uc ⇒ %return

Determines the canonical combining class of a Unicode character.

uc

Passed: a character.

a Unicode character

%return

Returned: a 32-bit integer.

the combining class of the character

Procedure: unichar-compose a b ⇒ %return ch

Performs a single composition step of the Unicode canonical composition algorithm.

This function includes algorithmic Hangul Jamo composition, but it is not exactly the inverse of unichar-decompose. No composition can have either of a or b equal to zero. To be precise, this function composes if and only if there exists a Primary Composite P which is canonically equivalent to the sequence <a,b>. See the Unicode Standard for the definition of Primary Composite.

If a and b do not compose a new character, ch is set to zero.

See UAX#15 for details.

a

Passed: a character.

a Unicode character

b

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the characters could be composed

ch

Returned: a character.

return location for the composed character

Procedure: unichar-decompose ch ⇒ %return a b

Performs a single decomposition step of the Unicode canonical decomposition algorithm.

This function does not include compatibility decompositions. It does, however, include algorithmic Hangul Jamo decomposition, as well as ’singleton’ decompositions which replace a character by a single other character. In the case of singletons *b will be set to zero.

If ch is not decomposable, *a is set to ch and *b is set to zero.

Note that the way Unicode decomposition pairs are defined, it is guaranteed that b would not decompose further, but a may itself decompose. To get the full canonical decomposition for ch, one would need to recursively call this function on a. Or use unichar-fully-decompose.

See UAX#15 for details.

ch

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the character could be decomposed

a

Returned: a character.

return location for the first component of ch

b

Returned: a character.

return location for the second component of ch

Procedure: unichar-digit-value c ⇒ %return

Determines the numeric value of a character as a decimal digit.

c

Passed: a character.

a Unicode character

%return

Returned: a 32-bit integer.

If c is a decimal digit (according to unichar-isdigit?), its numeric value. Otherwise, -1.

Procedure: unichar-fully-decompose ch compat result result-len ⇒ %return result

Computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, pass #t for compat; for canonical decomposition pass #f for compat.

The decomposed sequence is placed in result. Only up to result-len characters are written into result. The length of the full decomposition (irrespective of result-len) is returned by the function. For canonical decomposition, currently all decompositions are of length at most 4, but this may change in the future (very unlikely though). At any rate, Unicode does guarantee that a buffer of length 18 is always enough for both compatibility and canonical decompositions, so that is the size recommended. This is provided as G_UNICHAR_MAX_DECOMPOSITION_LENGTH.

See UAX#15 for details.

ch

Passed: a character.

a Unicode character.

compat

Passed: a boolean.

whether perform canonical or compatibility decomposition

result

Passed, filled in, and returned: a character.

location to store decomposed result, or #f

result-len

Passed: an unsigned 64-bit integer.

length of result

%return

Returned: an unsigned 64-bit integer.

the length of the full decomposition.

Procedure: unichar-get-mirror-char ch ⇒ %return mirrored-ch

In Unicode, some characters are "mirrored". This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.

If ch has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of ch’s glyph and mirrored-ch is set, it puts that character in the address pointed to by mirrored-ch. Otherwise the original character is put.

ch

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if ch has a mirrored character, #f otherwise

mirrored-ch

Returned: a character.

location to store the mirrored character

Procedure: unichar-get-script ch ⇒ %return

Looks up the <GUnicodeScript> for a particular character (as defined by Unicode Standard Annex \#24). No check is made for ch being a valid Unicode character; if you pass in invalid character, the result is undefined.

This function is equivalent to script:for-unichar and the two are interchangeable.

ch

Passed: a character.

a Unicode character

%return

Returned: a <GUnicodeScript>.

the <GUnicodeScript> for the character.

Procedure: unichar-isalnum? c ⇒ %return

Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is an alphanumeric character

Procedure: unichar-isalpha? c ⇒ %return

Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is an alphabetic character

Procedure: unichar-iscntrl? c ⇒ %return

Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is a control character

Procedure: unichar-isdefined? c ⇒ %return

Determines if a given character is assigned in the Unicode standard.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the character has an assigned value

Procedure: unichar-isdigit? c ⇒ %return

Determines whether a character is numeric (i.e. a digit). This covers ASCII 0-9 and also digits in other languages/scripts. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is a digit

Procedure: unichar-isgraph? c ⇒ %return

Determines whether a character is printable and not a space (returns #f for control characters, format characters, and spaces). unichar-isprint? is similar, but returns #t for spaces. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is printable unless it’s a space

Procedure: unichar-islower? c ⇒ %return

Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is a lowercase letter

Procedure: unichar-ismark? c ⇒ %return

Determines whether a character is a mark (non-spacing mark, combining mark, or enclosing mark in Unicode speak). Given some UTF-8 text, obtain a character value with utf8-get-char.

Note: in most cases where isalpha characters are allowed, ismark characters should be allowed to as they are essential for writing most European languages as well as many non-Latin scripts.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is a mark character

Procedure: unichar-isprint? c ⇒ %return

Determines whether a character is printable. Unlike unichar-isgraph?, returns #t for spaces. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is printable

Procedure: unichar-ispunct? c ⇒ %return

Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with utf8-get-char.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is a punctuation or symbol character

Procedure: unichar-isspace? c ⇒ %return

Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.). Given some UTF-8 text, obtain a character value with utf8-get-char.

(Note: don’t use this to do word breaking; you have to use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is a space character

Procedure: unichar-istitle? c ⇒ %return

Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the character is titlecase

Procedure: unichar-isupper? c ⇒ %return

Determines if a character is uppercase.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if c is an uppercase character

Procedure: unichar-iswide-cjk? c ⇒ %return

Determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to unichar-iswide?, then it is also reported wide with this function, but the converse is not necessarily true. See the Unicode Standard Annex #11 for details.

If a character passes the unichar-iswide? test then it will also pass this test, but not the other way around. Note that some characters may pass both this test and unichar-iszerowidth?.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the character is wide in legacy East Asian locales

Procedure: unichar-iswide? c ⇒ %return

Determines if a character is typically rendered in a double-width cell.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the character is wide

Procedure: unichar-isxdigit? c ⇒ %return

Determines if a character is a hexadecimal digit.

c

Passed: a character.

a Unicode character.

%return

Returned: a boolean.

#t if the character is a hexadecimal digit

Procedure: unichar-iszerowidth? c ⇒ %return

Determines if a given character typically takes zero width when rendered. The return value is #t for all non-spacing and enclosing marks (e.g., combining accents), format characters, zero-width space, but not U+00AD SOFT HYPHEN.

A typical use of this function is with one of unichar-iswide? or unichar-iswide-cjk? to determine the number of cells a string occupies when displayed on a grid display (terminals). However, note that not all terminals support zero-width rendering of zero-width marks.

c

Passed: a character.

a Unicode character

%return

Returned: a boolean.

#t if the character has zero width

Procedure: unichar-to-utf8! c outbuf ⇒ %return outbuf

Converts a single character to UTF-8.

c

Passed: a character.

a Unicode character code

outbuf

Passed, filled in, and returned: a string.

output buffer, must have at least 6 bytes of space. If NULL, the length will be computed and returned and nothing will be written to outbuf.

%return

Returned: a 32-bit integer.

number of bytes written, guaranteed to be in the range [1, 6]

Procedure: unichar-tolower c ⇒ %return

Converts a character to lower case.

c

Passed: a character.

a Unicode character.

%return

Returned: a character.

the result of converting c to lower case. If c is not an upperlower or titlecase character, or has no lowercase equivalent c is returned unchanged.

Procedure: unichar-totitle c ⇒ %return

Converts a character to the titlecase.

c

Passed: a character.

a Unicode character

%return

Returned: a character.

the result of converting c to titlecase. If c is not an uppercase or lowercase character, c is returned unchanged.

Procedure: unichar-toupper c ⇒ %return

Converts a character to uppercase.

c

Passed: a character.

a Unicode character

%return

Returned: a character.

the result of converting c to uppercase. If c is not a lowercase or titlecase character, or has no upper case equivalent c is returned unchanged.

Procedure: unichar-type c ⇒ %return

Classifies a Unicode character by type.

c

Passed: a character.

a Unicode character

%return

Returned: a <GUnicodeType>.

the type of the character.

Procedure: unichar-validate? ch ⇒ %return

Checks whether ch is a valid Unicode character.

Some possible integer values of ch will not be valid. U+0000 is considered a valid character, though it’s normally a string terminator.

ch

Passed: a character.

a Unicode character

%return

Returned: a boolean.

TRUE if ch is a valid Unicode character

Procedure: unichar-xdigit-value c ⇒ %return

Determines the numeric value of a character as a hexadecimal digit.

c

Passed: a character.

a Unicode character

%return

Returned: a 32-bit integer.

If c is a hex digit (according to unichar-isxdigit?), its numeric value. Otherwise, -1.

Procedure: unicode-canonical-ordering string

Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.

string

Passed: a string.

a UCS-4 encoded string.

len

Not passed: guile-gi gives the length of string.

the maximum length of string to use.

Procedure: unicode-script-from-iso15924 iso15924 ⇒ %return

Looks up the Unicode script for iso15924. ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is ’Arab’. This function accepts four letter codes encoded as a guint32 in a big-endian fashion. That is, the code expected for Arabic is 0x41726162 (0x41 is ASCII code for ’A’, 0x72 is ASCII code for ’r’, etc).

See Codes for the representation of names of scripts for details.

iso15924

Passed: an unsigned 32-bit integer.

a Unicode script

%return

Returned: a <GUnicodeScript>.

the Unicode script for iso15924, or of invalid-code if iso15924 is zero and unknown if iso15924 is unknown.

Procedure: unicode-script-to-iso15924 script ⇒ %return

Looks up the ISO 15924 code for script. ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is ’Arab’. The four letter codes are encoded as a guint32 by this function in a big-endian fashion. That is, the code returned for Arabic is 0x41726162 (0x41 is ASCII code for ’A’, 0x72 is ASCII code for ’r’, etc).

See Codes for the representation of names of scripts for details.

script

Passed: a <GUnicodeScript>, or one of its symbols.

a Unicode script

%return

Returned: an unsigned 32-bit integer.

the ISO 15924 code for script, encoded as an integer, of zero if script is invalid-code or ISO 15924 code ’Zzzz’ (script code for UNKNOWN) if script is not understood.

A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.

See your C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

%return

Returned: a 32-bit integer.

0 if the name was successfully deleted, -1 if an error occurred

Procedure: unsetenv variable

Removes an environment variable from the environment.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn’t reclaimed.

You should be mindful of the fact that environment variable handling in UNIX is not thread-safe, and your program may crash if one thread calls unsetenv while another thread is calling getenv(). (And note that many functions, such as gettext(), call getenv() internally.) This function is only safe to use at the very start of your program, before creating any other threads (or creating objects that create worker threads of their own).

If you need to set up the environment for a child process, you can use get-environ to get an environment array, modify that with environ-setenv and environ-unsetenv, and then pass that array directly to execvpe(), spawn-async, or the like.

variable

Passed: a file name, as a string.

the environment variable to remove, must not contain ’=’

Procedure: uri-build flags scheme userinfo host port path [query] [fragment] ⇒ %return

Creates a new <GUri> from the given components according to flags.

See also uri-build-with-user, which allows specifying the components of the "userinfo" separately.

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags describing how to build the <GUri>

scheme

Passed: a string.

the URI scheme

userinfo

Passed: a string, or #f.

the userinfo component, or #f

host

Passed: a string, or #f.

the host component, or #f

port

Passed: a 32-bit integer.

the port, or -1

path

Passed: a string.

the path component

query

Passed, or left out: a string, or #f.

the query component, or #f

fragment

Passed, or left out: a string, or #f.

the fragment, or #f

%return

Returned: a <GUri>.

a new <GUri>

Procedure: uri-build-with-user flags scheme user password auth-params host port path [query] [fragment] ⇒ %return

Creates a new <GUri> from the given components according to flags (has-password is added unconditionally). The flags must be coherent with the passed values, in particular use %-encoded values with encoded.

In contrast to uri-build, this allows specifying the components of the ‘userinfo’ field separately. Note that user must be non-#f if either password or auth-params is non-#f.

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags describing how to build the <GUri>

scheme

Passed: a string.

the URI scheme

user

Passed: a string, or #f.

the user component of the userinfo, or #f

password

Passed: a string, or #f.

the password component of the userinfo, or #f

auth-params

Passed: a string, or #f.

the auth params of the userinfo, or #f

host

Passed: a string, or #f.

the host component, or #f

port

Passed: a 32-bit integer.

the port, or -1

path

Passed: a string.

the path component

query

Passed, or left out: a string, or #f.

the query component, or #f

fragment

Passed, or left out: a string, or #f.

the fragment, or #f

%return

Returned: a <GUri>.

a new <GUri>

Procedure: uri-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: uri-escape-bytes unescaped [reserved-chars-allowed] ⇒ %return

Escapes arbitrary data for use in a URI.

Normally all characters that are not ‘unreserved’ (i.e. ASCII alphanumerical characters plus dash, dot, underscore and tilde) are escaped. But if you specify characters in reserved-chars-allowed they are not escaped. This is useful for the ‘reserved’ characters in the URI specification, since those are allowed unescaped in some portions of a URI.

Though technically incorrect, this will also allow escaping nul bytes as %00.

unescaped

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

the unescaped input data.

reserved-chars-allowed

Passed, or left out: a string, or #f.

a string of reserved characters that are allowed to be used, or #f.

%return

Returned: a string.

an escaped version of unescaped. The returned string should be freed when no longer needed.

length

Not passed: guile-gi gives the length of unescaped.

the length of unescaped

Procedure: uri-escape-string unescaped reserved-chars-allowed allow-utf8 ⇒ %return

Escapes a string for use in a URI.

Normally all characters that are not "unreserved" (i.e. ASCII alphanumerical characters plus dash, dot, underscore and tilde) are escaped. But if you specify characters in reserved-chars-allowed they are not escaped. This is useful for the "reserved" characters in the URI specification, since those are allowed unescaped in some portions of a URI.

unescaped

Passed: a string.

the unescaped input string.

reserved-chars-allowed

Passed: a string, or #f.

a string of reserved characters that are allowed to be used, or #f.

allow-utf8

Passed: a boolean.

#t if the result can include UTF-8 characters.

%return

Returned: a string.

an escaped version of unescaped. The returned string should be freed when no longer needed.

Procedure: uri-is-valid? uri-string flags ⇒ %return

Parses uri-string according to flags, to determine whether it is a valid absolute URI, i.e. it does not need to be resolved relative to another URI using uri:parse-relative.

If it’s not a valid URI, an error is returned explaining how it’s invalid.

See uri-split, and the definition of <%GUriFlags>, for more information on the effect of flags.

uri-string

Passed: a string.

a string containing an absolute URI

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags for parsing uri-string

%return

Returned: a boolean.

#t if uri-string is a valid absolute URI, #f on error.

Procedure: uri-join flags scheme userinfo host port path [query] [fragment] ⇒ %return

Joins the given components together according to flags to create an absolute URI string. path may not be #f (though it may be the empty string).

When host is present, path must either be empty or begin with a slash (/) character. When host is not present, path cannot begin with two slash characters (//). See section 3.

See also uri-join-with-user, which allows specifying the components of the ‘userinfo’ separately.

has-password and has-auth-params are ignored if set in flags.

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags describing how to build the URI string

scheme

Passed: a string, or #f.

the URI scheme, or #f

userinfo

Passed: a string, or #f.

the userinfo component, or #f

host

Passed: a string, or #f.

the host component, or #f

port

Passed: a 32-bit integer.

the port, or -1

path

Passed: a string.

the path component

query

Passed, or left out: a string, or #f.

the query component, or #f

fragment

Passed, or left out: a string, or #f.

the fragment, or #f

%return

Returned: a string.

an absolute URI string

Procedure: uri-join-with-user flags scheme user password auth-params host port path [query] [fragment] ⇒ %return

Joins the given components together according to flags to create an absolute URI string. path may not be #f (though it may be the empty string).

In contrast to uri-join, this allows specifying the components of the ‘userinfo’ separately. It otherwise behaves the same.

has-password and has-auth-params are ignored if set in flags.

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags describing how to build the URI string

scheme

Passed: a string, or #f.

the URI scheme, or #f

user

Passed: a string, or #f.

the user component of the userinfo, or #f

password

Passed: a string, or #f.

the password component of the userinfo, or #f

auth-params

Passed: a string, or #f.

the auth params of the userinfo, or #f

host

Passed: a string, or #f.

the host component, or #f

port

Passed: a 32-bit integer.

the port, or -1

path

Passed: a string.

the path component

query

Passed, or left out: a string, or #f.

the query component, or #f

fragment

Passed, or left out: a string, or #f.

the fragment, or #f

%return

Returned: a string.

an absolute URI string

Procedure: uri-list-extract-uris uri-list ⇒ %return

Splits an URI list conforming to the text/uri-list mime type defined in RFC 2483 into individual URIs, discarding any comments. The URIs are not validated.

uri-list

Passed: a string.

an URI list

%return

Returned: a vector, each a string.

a newly allocated #f-terminated list of strings holding the individual URIs. The array should be freed with strfreev.

Procedure: uri-parse uri-string flags ⇒ %return

Parses uri-string according to flags. If the result is not a valid absolute URI, it will be discarded, and an error returned.

uri-string

Passed: a string.

a string representing an absolute URI

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags describing how to parse uri-string

%return

Returned: a <GUri>.

a new <GUri>, or NULL on error.

Procedure: uri-parse-params params length separators flags ⇒ %return

Many URI schemes include one or more attribute/value pairs as part of the URI value. This method can be used to parse them into a hash table. When an attribute has multiple occurrences, the last value is the final returned value. If you need to handle repeated attributes differently, use GUriParamsIter.

The params string is assumed to still be %-encoded, but the returned values will be fully decoded. (Thus it is possible that the returned values may contain = or separators, if the value was encoded in the input.) Invalid %-encoding is treated as with the parse-relaxed rules for uri-parse. (However, if params is the path or query string from a <GUri> that was parsed without parse-relaxed and encoded, then you already know that it does not contain any invalid encoding.)

www-form is handled as documented for g_uri_params_iter_init().

If case-insensitive is passed to flags, attributes will be compared case-insensitively, so a params string attr=123&Attr=456 will only return a single attribute–value pair, Attr=456. Case will be preserved in the returned attributes.

If params cannot be parsed (for example, it contains two separators characters in a row), then error is set and #f is returned.

params

Passed: a string.

a %-encoded string containing attribute=value parameters

length

Passed: a 64-bit integer.

the length of params, or -1 if it is nul-terminated

separators

Passed: a string.

the separator byte character set between parameters. (usually &, but sometimes ; or both &;). Note that this function works on bytes not characters, so it can’t be used to delimit UTF-8 strings for anything but ASCII characters. You may pass an empty set, in which case no splitting will occur.

flags

Passed: a <%GUriParamsFlags>, or a list of its symbols, or one of them.

flags to modify the way the parameters are handled.

%return

Returned: a hash table, each key a string and each value a string.

A hash table of attribute/value pairs, with both names and values fully-decoded; or #f on error.

Procedure: uri-parse-scheme uri ⇒ %return

Gets the scheme portion of a URI string. RFC 3986 decodes the scheme as:


URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

Common schemes include file, https, svn+ssh, etc.

uri

Passed: a string.

a valid URI.

%return

Returned: a string, or #f.

The ‘scheme’ component of the URI, or #f on error. The returned string should be freed when no longer needed.

Procedure: uri-peek-scheme uri ⇒ %return

Gets the scheme portion of a URI string. RFC 3986 decodes the scheme as:


URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

Common schemes include file, https, svn+ssh, etc.

Unlike uri-parse-scheme, the returned scheme is normalized to all-lowercase and does not need to be freed.

uri

Passed: a string.

a valid URI.

%return

Returned: a string, or #f.

The ‘scheme’ component of the URI, or #f on error. The returned string is normalized to all-lowercase, and interned via intern-string, so it does not need to be freed.

Procedure: uri-resolve-relative base-uri-string uri-ref flags ⇒ %return

Parses uri-ref according to flags and, if it is a relative URI, resolves it relative to base-uri-string. If the result is not a valid absolute URI, it will be discarded, and an error returned.

(If base-uri-string is #f, this just returns uri-ref, or #f if uri-ref is invalid or not absolute.)

base-uri-string

Passed: a string, or #f.

a string representing a base URI

uri-ref

Passed: a string.

a string representing a relative or absolute URI

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags describing how to parse uri-ref

%return

Returned: a string.

the resolved URI string, or NULL on error.

Procedure: uri-split uri-ref flags ⇒ scheme userinfo host port path query fragment

Parses uri-ref (which can be an absolute or relative URI) according to flags, and returns the pieces. Any component that doesn’t appear in uri-ref will be returned as #f (but note that all URIs always have a path component, though it may be the empty string).

If flags contains encoded, then %-encoded characters in uri-ref will remain encoded in the output strings. (If not, then all such characters will be decoded.) Note that decoding will only work if the URI components are ASCII or UTF-8, so you will need to use encoded if they are not.

Note that the has-password and has-auth-params flags are ignored by uri-split, since it always returns only the full userinfo; use uri-split-with-user if you want it split up.

uri-ref

Passed: a string.

a string containing a relative or absolute URI

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags for parsing uri-ref

scheme

Returned: a string, or #f.

on return, contains the scheme (converted to lowercase), or #f

userinfo

Returned: a string, or #f.

on return, contains the userinfo, or #f

host

Returned: a string, or #f.

on return, contains the host, or #f

port

Returned: a 32-bit integer.

on return, contains the port, or -1

path

Returned: a string.

on return, contains the path

query

Returned: a string, or #f.

on return, contains the query, or #f

fragment

Returned: a string, or #f.

on return, contains the fragment, or #f

Procedure: uri-split-network uri-string flags ⇒ scheme host port

Parses uri-string (which must be an absolute URI) according to flags, and returns the pieces relevant to connecting to a host. See the documentation for uri-split for more details; this is mostly a wrapper around that function with simpler arguments. However, it will return an error if uri-string is a relative URI, or does not contain a hostname component.

uri-string

Passed: a string.

a string containing an absolute URI

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags for parsing uri-string

scheme

Returned: a string, or #f.

on return, contains the scheme (converted to lowercase), or #f

host

Returned: a string, or #f.

on return, contains the host, or #f

port

Returned: a 32-bit integer.

on return, contains the port, or -1

Procedure: uri-split-with-user uri-ref flags ⇒ scheme user password auth-params host port path query fragment

Parses uri-ref (which can be an absolute or relative URI) according to flags, and returns the pieces. Any component that doesn’t appear in uri-ref will be returned as #f (but note that all URIs always have a path component, though it may be the empty string).

See uri-split, and the definition of <%GUriFlags>, for more information on the effect of flags. Note that password will only be parsed out if flags contains has-password, and auth-params will only be parsed out if flags contains has-auth-params.

uri-ref

Passed: a string.

a string containing a relative or absolute URI

flags

Passed: a <%GUriFlags>, or a list of its symbols, or one of them.

flags for parsing uri-ref

scheme

Returned: a string, or #f.

on return, contains the scheme (converted to lowercase), or #f

user

Returned: a string, or #f.

on return, contains the user, or #f

password

Returned: a string, or #f.

on return, contains the password, or #f

auth-params

Returned: a string, or #f.

on return, contains the auth_params, or #f

host

Returned: a string, or #f.

on return, contains the host, or #f

port

Returned: a 32-bit integer.

on return, contains the port, or -1

path

Returned: a string.

on return, contains the path

query

Returned: a string, or #f.

on return, contains the query, or #f

fragment

Returned: a string, or #f.

on return, contains the fragment, or #f

Procedure: uri-unescape-bytes escaped-string length [illegal-characters] ⇒ %return

Unescapes a segment of an escaped string as binary data.

Note that in contrast to uri-unescape-string, this does allow nul bytes to appear in the output.

If any of the characters in illegal-characters appears as an escaped character in escaped-string, then that is an error and #f will be returned. This is useful if you want to avoid for instance having a slash being expanded in an escaped path element, which might confuse pathname handling.

escaped-string

Passed: a string.

A URI-escaped string

length

Passed: a 64-bit integer.

the length (in bytes) of escaped-string to escape, or -1 if it is nul-terminated.

illegal-characters

Passed, or left out: a string, or #f.

a string of illegal characters not to be allowed, or #f.

%return

Returned: a <GBytes>.

an unescaped version of escaped-string or #f on error (if decoding failed, using failed error code). The returned <GBytes> should be unreffed when no longer needed.

Procedure: uri-unescape-segment [escaped-string] [escaped-string-end] [illegal-characters] ⇒ %return

Unescapes a segment of an escaped string.

If any of the characters in illegal-characters or the NUL character appears as an escaped character in escaped-string, then that is an error and #f will be returned. This is useful if you want to avoid for instance having a slash being expanded in an escaped path element, which might confuse pathname handling.

Note: NUL byte is not accepted in the output, in contrast to uri-unescape-bytes.

escaped-string

Passed, or left out: a string, or #f.

A string, may be #f

escaped-string-end

Passed, or left out: a string, or #f.

Pointer to end of escaped-string, may be #f

illegal-characters

Passed, or left out: a string, or #f.

An optional string of illegal characters not to be allowed, may be #f

%return

Returned: a string, or #f.

an unescaped version of escaped-string, or #f on error. The returned string should be freed when no longer needed. As a special case if #f is given for escaped-string, this function will return #f.

Procedure: uri-unescape-string escaped-string [illegal-characters] ⇒ %return

Unescapes a whole escaped string.

If any of the characters in illegal-characters or the NUL character appears as an escaped character in escaped-string, then that is an error and #f will be returned. This is useful if you want to avoid for instance having a slash being expanded in an escaped path element, which might confuse pathname handling.

escaped-string

Passed: a string.

an escaped string to be unescaped.

illegal-characters

Passed, or left out: a string, or #f.

a string of illegal characters not to be allowed, or #f.

%return

Returned: a string, or #f.

an unescaped version of escaped-string. The returned string should be freed when no longer needed.

Procedure: usleep microseconds

Pauses the current thread for the given number of microseconds.

There are 1 million microseconds per second (represented by the G_USEC_PER_SEC macro). usleep may have limited precision, depending on hardware and operating system; don’t rely on the exact length of the sleep.

microseconds

Passed: an unsigned 64-bit integer.

number of microseconds to pause

Procedure: utf16-to-ucs4 str ⇒ %return items-read items-written

Convert a string from UTF-16 to UCS-4.

The result will be nul-terminated.

str

Passed: an u16vector, or a list or vector, each an unsigned 16-bit integer.

a UTF-16 encoded string

%return

Returned: a character.

a pointer to a newly allocated UCS-4 string. This value must be freed with byte-array:free.

items-read

Returned: a 64-bit integer.

location to store number of gunichar2 read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.

items-written

Returned: a 64-bit integer.

location to store number of characters written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.

len

Not passed: guile-gi gives the length of str.

the maximum length (number of gunichar2) of str to use. If len is negative, then the string is nul-terminated.

Procedure: utf16-to-utf8 str ⇒ %return items-read items-written

Convert a string from UTF-16 to UTF-8.

The result will be terminated with a nul byte.

Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. convert can be used to convert a byte buffer of UTF-16 data of ambiguous endianness.

Further note that this function does not validate the result string; it may (for example) include embedded nul characters. The only validation done by this function is to ensure that the input can be correctly interpreted as UTF-16, i.e. it doesn’t contain unpaired surrogates or partial character sequences.

str

Passed: an u16vector, or a list or vector, each an unsigned 16-bit integer.

a UTF-16 encoded string

%return

Returned: a string.

a pointer to a newly allocated UTF-8 string. This value must be freed with byte-array:free.

items-read

Returned: a 64-bit integer.

location to store number of gunichar2 read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.

items-written

Returned: a 64-bit integer.

location to store number of bytes written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.

len

Not passed: guile-gi gives the length of str.

the maximum length (number of gunichar2) of str to use. If len is negative, then the string is nul-terminated.

Procedure: utf8-casefold str len ⇒ %return

Converts a string into a form that is independent of case. The result will not correspond to any particular case, but can be compared for equality or ordered with the results of calling utf8-casefold on other strings.

Note that calling utf8-casefold followed by utf8-collate is only an approximation to the correct linguistic case insensitive ordering, though it is a fairly good one. Getting this exactly right would require a more sophisticated collation function that takes case sensitivity into account. GLib does not currently provide such a function.

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

length of str, in bytes, or -1 if str is nul-terminated.

%return

Returned: a string.

a newly allocated string, that is a case independent form of str.

Procedure: utf8-collate str1 str2 ⇒ %return

Compares two strings for ordering using the linguistically correct rules for the current locale. When sorting a large number of strings, it will be significantly faster to obtain collation keys with utf8-collate-key and compare the keys with strcmp() when sorting instead of sorting the original strings.

If the two strings are not comparable due to being in different collation sequences, the result is undefined. This can happen if the strings are in different language scripts, for example.

str1

Passed: a string.

a UTF-8 encoded string

str2

Passed: a string.

a UTF-8 encoded string

%return

Returned: a 32-bit integer.

< 0 if str1 compares before str2, 0 if they compare equal, > 0 if str1 compares after str2.

Procedure: utf8-collate-key str len ⇒ %return

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

The results of comparing the collation keys of two strings with strcmp() will always be the same as comparing the two original keys with utf8-collate.

Note that this function depends on the current locale.

Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.

str

Passed: a string.

a UTF-8 encoded string.

len

Passed: a 64-bit integer.

length of str, in bytes, or -1 if str is nul-terminated.

%return

Returned: a file name, as a string.

a newly allocated string. The contents of the string are only meant to be used when sorting. This string should be freed with byte-array:free when you are done with it.

Procedure: utf8-collate-key-for-filename str len ⇒ %return

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

In order to sort filenames correctly, this function treats the dot ’.’ as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".

Note that this function depends on the current locale.

Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.

str

Passed: a string.

a UTF-8 encoded string.

len

Passed: a 64-bit integer.

length of str, in bytes, or -1 if str is nul-terminated.

%return

Returned: a file name, as a string.

a newly allocated string. The contents of the string are only meant to be used when sorting. This string should be freed with byte-array:free when you are done with it.

Procedure: utf8-find-next-char p [end] ⇒ %return

Finds the start of the next UTF-8 character in the string after p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

If end is NULL, the return value will never be NULL: if the end of the string is reached, a pointer to the terminating nul byte is returned. If end is non-NULL, the return value will be NULL if the end of the string is reached.

p

Passed: a string.

a pointer to a position within a UTF-8 encoded string

end

Passed, or left out: a string, or #f.

a pointer to the byte following the end of the string, or NULL to indicate that the string is nul-terminated

%return

Returned: a string, or #f.

a pointer to the found character or NULL if end is set and is reached

Procedure: utf8-find-prev-char str p ⇒ %return

Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns NULL if no UTF-8 characters are present in str before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

str

Passed: a string.

pointer to the beginning of a UTF-8 encoded string

p

Passed: a string.

pointer to some position within str

%return

Returned: a string, or #f.

a pointer to the found character

Procedure: utf8-get-char p ⇒ %return

Converts a sequence of bytes encoded as UTF-8 to a Unicode character.

If p does not point to a valid UTF-8 encoded character, results are undefined. If you are not sure that the bytes are complete valid Unicode characters, you should use utf8-get-char-validated instead.

p

Passed: a string.

a pointer to Unicode character encoded as UTF-8

%return

Returned: a character.

the resulting character

Procedure: utf8-get-char-validated p max-len ⇒ %return

Convert a sequence of bytes encoded as UTF-8 to a Unicode character.

This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.

Note that utf8-get-char-validated returns (gunichar)-2 if max-len is positive and any of the bytes in the first UTF-8 character sequence are nul.

p

Passed: a string.

a pointer to Unicode character encoded as UTF-8

max-len

Passed: a 64-bit integer.

the maximum number of bytes to read, or -1 if p is nul-terminated

%return

Returned: a character.

the resulting character. If p points to a partial sequence at the end of a string that could begin a valid character (or if max-len is zero), returns (gunichar)-2; otherwise, if p does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.

Procedure: utf8-make-valid str len ⇒ %return

If the provided string is valid UTF-8, return a copy of it. If not, return a copy in which bytes that could not be interpreted as valid Unicode are replaced with the Unicode replacement character (U+FFFD).

For example, this is an appropriate function to use if you have received a string that was incorrectly declared to be UTF-8, and you need a valid UTF-8 version of it that can be logged or displayed to the user, with the assumption that it is close enough to ASCII or UTF-8 to be mostly readable as-is.

str

Passed: a string.

string to coerce into UTF-8

len

Passed: a 64-bit integer.

the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

%return

Returned: a string.

a valid UTF-8 string whose content resembles str

Procedure: utf8-normalize str len mode ⇒ %return

Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. The string has to be valid UTF-8, otherwise #f is returned. You should generally call utf8-normalize before comparing two Unicode strings.

The normalization mode default only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. all also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.

default-compose and all-compose are like default and all, but returned a result with composed forms rather than a maximally decomposed form. This is often useful if you intend to convert the string to a legacy encoding or pass it to a system with less capable Unicode handling.

str

Passed: a string.

a UTF-8 encoded string.

len

Passed: a 64-bit integer.

length of str, in bytes, or -1 if str is nul-terminated.

mode

Passed: a <GNormalizeMode>, or one of its symbols.

the type of normalization to perform.

%return

Returned: a string, or #f.

a newly allocated string, that is the normalized form of str, or #f if str is not valid UTF-8.

Procedure: utf8-offset-to-pointer str offset ⇒ %return

Converts from an integer character offset to a pointer to a position within the string.

Since 2.10, this function allows to pass a negative offset to step backwards. It is usually worth stepping backwards from the end instead of forwards if offset is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.

Note that this function doesn’t abort when reaching the end of str. Therefore you should be sure that offset is within string boundaries before calling that function. Call utf8-strlen when unsure. This limitation exists as this function is called frequently during text rendering and therefore has to be as fast as possible.

str

Passed: a string.

a UTF-8 encoded string

offset

Passed: a 64-bit integer.

a character offset within str

%return

Returned: a string.

the resulting pointer

Procedure: utf8-pointer-to-offset str pos ⇒ %return

Converts from a pointer to position within a string to an integer character offset.

Since 2.10, this function allows pos to be before str, and returns a negative offset in this case.

str

Passed: a string.

a UTF-8 encoded string

pos

Passed: a string.

a pointer to a position within str

%return

Returned: a 64-bit integer.

the resulting character offset

Procedure: utf8-prev-char p ⇒ %return

Finds the previous UTF-8 character in the string before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If p might be the first character of the string, you must use utf8-find-prev-char instead.

p

Passed: a string.

a pointer to a position within a UTF-8 encoded string

%return

Returned: a string.

a pointer to the found character

Procedure: utf8-strchr p len c ⇒ %return

Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes.

If len is -1, allow unbounded search.

p

Passed: a string.

a nul-terminated UTF-8 encoded string

len

Passed: a 64-bit integer.

the maximum length of p

c

Passed: a character.

a Unicode character

%return

Returned: a string, or #f.

NULL if the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.

Procedure: utf8-strdown str len ⇒ %return

Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

length of str, in bytes, or -1 if str is nul-terminated.

%return

Returned: a string.

a newly allocated string, with all characters converted to lowercase.

Procedure: utf8-strlen p max ⇒ %return

Computes the length of the string in characters, not including the terminating nul character. If the max’th byte falls in the middle of a character, the last (partial) character is not counted.

p

Passed: a string.

pointer to the start of a UTF-8 encoded string

max

Passed: a 64-bit integer.

the maximum number of bytes to examine. If max is less than 0, then the string is assumed to be nul-terminated. If max is 0, p will not be examined and may be NULL. If max is greater than 0, up to max bytes are examined

%return

Returned: a 64-bit integer.

the length of the string in characters

Procedure: utf8-strncpy dest src n ⇒ %return

Like the standard C ‘strncpy()‘ function, but copies a given number of characters instead of a given number of bytes.

The src string must be valid UTF-8 encoded text. (Use utf8-validate on all text before trying to use UTF-8 utility functions with it.)

Note you must ensure dest is at least 4 * n + 1 to fit the largest possible UTF-8 characters

dest

Passed: a string.

buffer to fill with characters from src

src

Passed: a string.

UTF-8 encoded string

n

Passed: an unsigned 64-bit integer.

character count

%return

Returned: a string.

dest

Procedure: utf8-strrchr p len c ⇒ %return

Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes.

If len is -1, allow unbounded search.

p

Passed: a string.

a nul-terminated UTF-8 encoded string

len

Passed: a 64-bit integer.

the maximum length of p

c

Passed: a character.

a Unicode character

%return

Returned: a string, or #f.

NULL if the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.

Procedure: utf8-strreverse str len ⇒ %return

Reverses a UTF-8 string.

str must be valid UTF-8 encoded text. (Use utf8-validate on all text before trying to use UTF-8 utility functions with it.)

This function is intended for programmatic uses of reversed strings. It pays no attention to decomposed characters, combining marks, byte order marks, directional indicators (LRM, LRO, etc) and similar characters which might need special handling when reversing a string for display purposes.

Note that unlike strreverse, this function returns newly-allocated memory, which should be freed with byte-array:free when no longer needed.

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

%return

Returned: a string.

a newly-allocated string which is the reverse of str

Procedure: utf8-strup str len ⇒ %return

Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

length of str, in bytes, or -1 if str is nul-terminated.

%return

Returned: a string.

a newly allocated string, with all characters converted to uppercase.

Procedure: utf8-substring str start-pos end-pos ⇒ %return

Copies a substring out of a UTF-8 encoded string. The substring will contain end-pos - start-pos characters.

Since GLib 2.72, -1 can be passed to end-pos to indicate the end of the string.

str

Passed: a string.

a UTF-8 encoded string

start-pos

Passed: a 64-bit integer.

a character offset within str

end-pos

Passed: a 64-bit integer.

another character offset within str, or -1 to indicate the end of the string

%return

Returned: a string.

a newly allocated copy of the requested substring. Free with byte-array:free when no longer needed.

Procedure: utf8-to-ucs4 str len ⇒ %return items-read items-written

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4.

A trailing nul character (U+0000) will be added to the string after the converted text.

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

%return

Returned: a character.

a pointer to a newly allocated UCS-4 string. This value must be freed with byte-array:free.

items-read

Returned: a 64-bit integer.

location to store number of bytes read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.

items-written

Returned: a 64-bit integer.

location to store number of characters written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.

Procedure: utf8-to-ucs4-fast str len ⇒ %return items-written

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input.

This function is roughly twice as fast as utf8-to-ucs4 but does no error checking on the input. A trailing nul character (U+0000) will be added to the string after the converted text.

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

%return

Returned: a character.

a pointer to a newly allocated UCS-4 string. This value must be freed with byte-array:free.

items-written

Returned: a 64-bit integer.

location to store the number of characters in the result, or NULL.

Procedure: utf8-to-utf16 str len ⇒ %return items-read items-written

Convert a string from UTF-8 to UTF-16.

A nul character (U+0000) will be added to the result after the converted text.

str

Passed: a string.

a UTF-8 encoded string

len

Passed: a 64-bit integer.

the maximum length (number of bytes) of str to use. If len is negative, then the string is nul-terminated.

%return

Returned: an unsigned 16-bit integer.

a pointer to a newly allocated UTF-16 string. This value must be freed with byte-array:free.

items-read

Returned: a 64-bit integer.

location to store number of bytes read, or NULL to ignore. If NULL, then GLib.ConvertError.PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. The value stored here will never be negative.

items-written

Returned: a 64-bit integer.

location to store number of gunichar2 written, or NULL to ignore. The value stored here does not include the trailing nul, and will never be negative.

Procedure: utf8-truncate-middle string truncate-length ⇒ %return

Cuts off the middle of the string, preserving half of truncate-length characters at the beginning and half at the end.

If string is already short enough, this returns a copy of string. If truncate-length is 0, an empty string is returned.

string

Passed: a string.

a nul-terminated UTF-8 encoded string

truncate-length

Passed: an unsigned 64-bit integer.

the new size of string, in characters, including the ellipsis character

%return

Returned: a string.

a newly-allocated copy of string ellipsized in the middle

Procedure: utf8-validate str ⇒ %return end

Validates UTF-8 encoded text.

str is the text to validate; if str is nul-terminated, then max-len can be -1, otherwise max-len should be the number of bytes to validate.

If end is non-NULL, then the end of the valid range will be stored there. This is the first byte of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise — either the trailing nul byte, or the first byte beyond max-len (if it’s positive).

Note that utf8-validate returns FALSE if max-len is positive and any of the max-len bytes are nul.

Returns TRUE if all of str was valid. Many GLib and GTK routines require valid UTF-8 as input; so data read from a file or the network should be checked with utf8-validate before doing anything else with it.

str

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

a pointer to character data

%return

Returned: a boolean.

TRUE if the text was valid UTF-8

end

Returned: a bytevector.

return location for end of valid data

max-len

Not passed: guile-gi gives the length of str.

max bytes to validate, or -1 to go until nul

Procedure: utf8-validate-len str ⇒ %return end

Validates UTF-8 encoded text.

As with utf8-validate, but max-len must be set, and hence this function will always return FALSE if any of the bytes of str are nul.

str

Passed: a bytevector, or a list or vector, each an unsigned 8-bit integer.

a pointer to character data

%return

Returned: a boolean.

TRUE if the text was valid UTF-8

end

Returned: a bytevector.

return location for end of valid data

max-len

Not passed: guile-gi gives the length of str.

max bytes to validate

Procedure: utime filename [utb] ⇒ %return

A wrapper for the POSIX utime() function. The utime() function sets the access and modification timestamps of a file.

See your C library manual for more details about how utime() works on your system.

filename

Passed: a file name, as a string.

a pathname in the GLib file name encoding (UTF-8 on Windows)

utb

Passed, or left out: a foreign pointer, or a bytevector, or #f.

a pointer to a struct utimbuf.

%return

Returned: a 32-bit integer.

0 if the operation was successful, -1 if an error occurred

Procedure: uuid-string-is-valid? str ⇒ %return

Parses the string str and verify if it is a UUID.

The function accepts the following syntax:

  • simple forms (e.g. f81d4fae-7dec-11d0-a765-00a0c91e6bf6)

Note that hyphens are required within the UUID string itself, as per the aforementioned RFC.

str

Passed: a string.

a string representing a UUID

%return

Returned: a boolean.

#t if str is a valid UUID, #f otherwise.

Procedure: uuid-string-random ⇒ %return

Generates a random UUID (RFC 4122 version 4) as a string. It has the same randomness guarantees as <GRand>, so must not be used for cryptographic purposes such as key generation, nonces, salts or one-time pads.

%return

Returned: a string.

A string that should be freed with byte-array:free.

Procedure: variant-get-gtype ⇒ %return
%return

Returned: a class, or a GType number.

Procedure: variant-is-object-path? string ⇒ %return

Determines if a given string is a valid D-Bus object path. You should ensure that a string is a valid D-Bus object path before passing it to variant:new-object-path.

A valid object path starts with / followed by zero or more sequences of characters separated by / characters. Each sequence must contain only the characters [A-Z][a-z][0-9]_. No sequence (including the one following the final / character) may be empty.

string

Passed: a string.

a normal C nul-terminated string

%return

Returned: a boolean.

#t if string is a D-Bus object path

Procedure: variant-is-signature? string ⇒ %return

Determines if a given string is a valid D-Bus type signature. You should ensure that a string is a valid D-Bus type signature before passing it to variant:new-signature.

D-Bus type signatures consist of zero or more definite <GVariantType> strings in sequence.

string

Passed: a string.

a normal C nul-terminated string

%return

Returned: a boolean.

#t if string is a D-Bus type signature

Procedure: variant-parse type text [limit] [endptr] ⇒ %return

Parses a <GVariant> from a text representation.

A single <GVariant> is parsed from the content of text.

The format is described here.

The memory at limit will never be accessed and the parser behaves as if the character at limit is the nul terminator. This has the effect of bounding text.

If endptr is non-#f then text is permitted to contain data following the value that this function parses and endptr will be updated to point to the first character past the end of the text parsed by this function. If endptr is #f and there is extra data then an error is returned.

If type is non-#f then the value will be parsed to have that type. This may result in additional parse errors (in the case that the parsed value doesn’t fit the type) but may also result in fewer errors (in the case that the type would have been ambiguous, such as with empty arrays).

In the event that the parsing is successful, the resulting <GVariant> is returned. It is never floating, and must be freed with variant:unref.

In case of any error, #f will be returned. If error is non-#f then it will be set to reflect the error that occurred.

Officially, the language understood by the parser is “any string produced by variant:print”. This explicitly includes variant:print’s annotated types like int64 -1000.

There may be implementation specific restrictions on deeply nested values, which would result in a recursion error. <GVariant> is guaranteed to handle nesting up to at least 64 levels.

type

Passed: a <GVariantType>, or #f.

a <GVariantType>, or #f

text

Passed: a string.

a string containing a GVariant in text form

limit

Passed, or left out: a string, or #f.

a pointer to the end of text, or #f

endptr

Passed, or left out: a string, or #f.

a location to store the end pointer, or #f

%return

Returned: a <GVariant>.

a non-floating reference to a <GVariant>, or #f

Procedure: variant-parse-error-print-context error source-str ⇒ %return

Pretty-prints a message showing the context of a <GVariant> parse error within the string for which parsing was attempted.

The resulting string is suitable for output to the console or other monospace media where newlines are treated in the usual way.

The message will typically look something like one of the following:


unterminated string constant:
  (1, 2, 3, 'abc
            ^^^^

or


unable to find a common type:
  [1, 2, 3, 'str']
   ^        ^^^^^

The format of the message may change in a future version.

error must have come from a failed attempt to variant-parse and source-str must be exactly the same string that caused the error. If source-str was not nul-terminated when you passed it to variant-parse then you must add nul termination before using this function.

error

Passed: a <GError>.

a <GError> from the <%GVariantParseError> domain

source-str

Passed: a string.

the string that was given to the parser

%return

Returned: a string.

the printed message

Procedure: variant-parse-error-quark ⇒ %return
%return

Returned: an unsigned 32-bit integer.

Procedure: variant-type-checked- type-string ⇒ %return
type-string

Passed: a string.

%return

Returned: a <GVariantType>.

Procedure: variant-type-string-get-depth- type-string ⇒ %return
type-string

Passed: a string.

%return

Returned: an unsigned 64-bit integer.

Procedure: variant-type-string-is-valid? type-string ⇒ %return

Checks if type-string is a valid GVariant type string.

This call is equivalent to calling variant-type:string-scan and confirming that the following character is a nul terminator.

type-string

Passed: a string.

a pointer to any string

%return

Returned: a boolean.

true if type-string is exactly one valid type string Since 2.24

Procedure: variant-type-string-scan string [limit] ⇒ %return endptr

Scan for a single complete and valid GVariant type string in string.

The memory pointed to by limit (or bytes beyond it) is never accessed.

If a valid type string is found, endptr is updated to point to the first character past the end of the string that was found and #t is returned.

If there is no valid type string starting at string, or if the type string does not end before limit then #f is returned.

For the simple case of checking if a string is a valid type string, see variant-type:string-is-valid?.

string

Passed: a string.

a pointer to any string

limit

Passed, or left out: a string, or #f.

the end of string

%return

Returned: a boolean.

true if a valid type string was found

endptr

Returned: a string.

location to store the end pointer