glib

package
v0.0.0-...-aefa52a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2024 License: MPL-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TypeInvalid   = coreglib.TypeInvalid
	TypeNone      = coreglib.TypeNone
	TypeInterface = coreglib.TypeInterface
	TypeChar      = coreglib.TypeChar
	TypeUchar     = coreglib.TypeUchar
	TypeBoolean   = coreglib.TypeBoolean
	TypeInt       = coreglib.TypeInt
	TypeUint      = coreglib.TypeUint
	TypeLong      = coreglib.TypeLong
	TypeUlong     = coreglib.TypeUlong
	TypeInt64     = coreglib.TypeInt64
	TypeUint64    = coreglib.TypeUint64
	TypeEnum      = coreglib.TypeEnum
	TypeFlags     = coreglib.TypeFlags
	TypeFloat     = coreglib.TypeFloat
	TypeDouble    = coreglib.TypeDouble
	TypeString    = coreglib.TypeString
	TypePointer   = coreglib.TypePointer
	TypeBoxed     = coreglib.TypeBoxed
	TypeParam     = coreglib.TypeParam
	TypeObject    = coreglib.TypeObject
	TypeVariant   = coreglib.TypeVariant

	PriorityHigh        = coreglib.PriorityHigh
	PriorityDefault     = coreglib.PriorityDefault
	PriorityHighIdle    = coreglib.PriorityHighIdle
	PriorityDefaultIdle = coreglib.PriorityDefaultIdle
	PriorityLow         = coreglib.PriorityLow
)

Constant aliases from pkg/core/glib.

View Source
const ANALYZER_ANALYZING = 1
View Source
const ASCII_DTOSTR_BUF_SIZE = 39

ASCII_DTOSTR_BUF_SIZE: good size for a buffer to be passed into g_ascii_dtostr(). It is guaranteed to be enough for all output of that function on systems with 64bit IEEE-compatible doubles.

The typical usage would be something like:

char buf[G_ASCII_DTOSTR_BUF_SIZE];

fprintf (out, "value=s\n", g_ascii_dtostr (buf, sizeof (buf), value));.
View Source
const BIG_ENDIAN = 4321

BIG_ENDIAN specifies one of the possible types of byte order. See BYTE_ORDER.

View Source
const CSET_A_2_Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

CSET_A_2_Z: set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters in Config.

View Source
const CSET_DIGITS = "0123456789"

CSET_DIGITS: set of ASCII digits. Used for specifying valid identifier characters in Config.

View Source
const CSET_a_2_z = "abcdefghijklmnopqrstuvwxyz"

CSET_a_2_z: set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters in Config.

View Source
const DATALIST_FLAGS_MASK = 3

DATALIST_FLAGS_MASK: bitmask that restricts the possible flags passed to g_datalist_set_flags(). Passing a flags value where flags & ~G_DATALIST_FLAGS_MASK != 0 is an error.

View Source
const DATE_BAD_DAY = 0

DATE_BAD_DAY represents an invalid Day.

View Source
const DATE_BAD_JULIAN = 0

DATE_BAD_JULIAN represents an invalid Julian day number.

View Source
const DATE_BAD_YEAR = 0

DATE_BAD_YEAR represents an invalid year.

View Source
const DIR_SEPARATOR = 47

DIR_SEPARATOR: directory separator character. This is '/' on UNIX machines and '\' under Windows.

View Source
const DIR_SEPARATOR_S = "/"

DIR_SEPARATOR_S: directory separator as a string. This is "/" on UNIX machines and "\" under Windows.

View Source
const E = 2.718282

E: base of natural logarithms.

View Source
const GINT16_FORMAT = "hi"

GINT16_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #gint16. It is a string literal, but doesn't include the percent-sign, such that you can add precision and length modifiers between percent-sign and conversion specifier.

gint16 in;
gint32 out;
sscanf ("42", "%" G_GINT16_FORMAT, &in)
out = in * 1000;
g_print ("%" G_GINT32_FORMAT, out);.
View Source
const GINT16_MODIFIER = "h"

GINT16_MODIFIER: platform dependent length modifier for conversion specifiers for scanning and printing values of type #gint16 or #guint16. It is a string literal, but doesn't include the percent-sign, such that you can add precision and length modifiers between percent-sign and conversion specifier and append a conversion specifier.

The following example prints "0x7b";

gint16 value = 123;
g_print ("%#" G_GINT16_MODIFIER "x", value);.
View Source
const GINT32_FORMAT = "i"

GINT32_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #gint32. See also GINT16_FORMAT.

View Source
const GINT32_MODIFIER = ""

GINT32_MODIFIER: platform dependent length modifier for conversion specifiers for scanning and printing values of type #gint32 or #guint32. It is a string literal. See also GINT16_MODIFIER.

View Source
const GINT64_FORMAT = "li"

GINT64_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #gint64. See also GINT16_FORMAT.

Some platforms do not support scanning and printing 64-bit integers, even though the types are supported. On such platforms G_GINT64_FORMAT is not defined. Note that scanf() may not support 64-bit integers, even if G_GINT64_FORMAT is defined. Due to its weak error handling, scanf() is not recommended for parsing anyway; consider using g_ascii_strtoull() instead.

View Source
const GINT64_MODIFIER = "l"

GINT64_MODIFIER: platform dependent length modifier for conversion specifiers for scanning and printing values of type #gint64 or #guint64. It is a string literal.

Some platforms do not support printing 64-bit integers, even though the types are supported. On such platforms G_GINT64_MODIFIER is not defined.

View Source
const GINTPTR_FORMAT = "li"

GINTPTR_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #gintptr.

View Source
const GINTPTR_MODIFIER = "l"

GINTPTR_MODIFIER: platform dependent length modifier for conversion specifiers for scanning and printing values of type #gintptr or #guintptr. It is a string literal.

View Source
const GNUC_FUNCTION = ""

GNUC_FUNCTION expands to "" on all modern compilers, and to __FUNCTION__ on gcc version 2.x. Don't use it.

Deprecated: Use G_STRFUNC() instead.

View Source
const GNUC_PRETTY_FUNCTION = ""

GNUC_PRETTY_FUNCTION expands to "" on all modern compilers, and to __PRETTY_FUNCTION__ on gcc version 2.x. Don't use it.

Deprecated: Use G_STRFUNC() instead.

View Source
const GSIZE_FORMAT = "lu"

GSIZE_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #gsize. See also GINT16_FORMAT.

View Source
const GSIZE_MODIFIER = "l"

GSIZE_MODIFIER: platform dependent length modifier for conversion specifiers for scanning and printing values of type #gsize. It is a string literal.

View Source
const GSSIZE_FORMAT = "li"

GSSIZE_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #gssize. See also GINT16_FORMAT.

View Source
const GSSIZE_MODIFIER = "l"

GSSIZE_MODIFIER: platform dependent length modifier for conversion specifiers for scanning and printing values of type #gssize. It is a string literal.

View Source
const GUINT16_FORMAT = "hu"

GUINT16_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #guint16. See also GINT16_FORMAT.

View Source
const GUINT32_FORMAT = "u"

GUINT32_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #guint32. See also GINT16_FORMAT.

View Source
const GUINT64_FORMAT = "lu"

GUINT64_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #guint64. See also GINT16_FORMAT.

Some platforms do not support scanning and printing 64-bit integers, even though the types are supported. On such platforms G_GUINT64_FORMAT is not defined. Note that scanf() may not support 64-bit integers, even if G_GINT64_FORMAT is defined. Due to its weak error handling, scanf() is not recommended for parsing anyway; consider using g_ascii_strtoull() instead.

View Source
const GUINTPTR_FORMAT = "lu"

GUINTPTR_FORMAT: this is the platform dependent conversion specifier for scanning and printing values of type #guintptr.

View Source
const HAVE_GINT64 = 1
View Source
const HAVE_GNUC_VARARGS = 1
View Source
const HAVE_GNUC_VISIBILITY = 1

HAVE_GNUC_VISIBILITY: defined to 1 if gcc-style visibility handling is supported.

View Source
const HAVE_GROWING_STACK = 0
View Source
const HAVE_ISO_VARARGS = 1
View Source
const HOOK_FLAG_USER_SHIFT = 4

HOOK_FLAG_USER_SHIFT: position of the first bit which is not reserved for internal use be the #GHook implementation, i.e. 1 << G_HOOK_FLAG_USER_SHIFT is the first bit which can be used for application-defined flags.

View Source
const IEEE754_DOUBLE_BIAS = 1023

IEEE754_DOUBLE_BIAS bias by which exponents in double-precision floats are offset.

View Source
const IEEE754_FLOAT_BIAS = 127

IEEE754_FLOAT_BIAS bias by which exponents in single-precision floats are offset.

View Source
const KEY_FILE_DESKTOP_GROUP = "Desktop Entry"

KEY_FILE_DESKTOP_GROUP: name of the main group of a desktop entry file, as defined in the Desktop Entry Specification (http://freedesktop.org/Standards/desktop-entry-spec). Consult the specification for more details about the meanings of the keys below.

View Source
const KEY_FILE_DESKTOP_KEY_ACTIONS = "Actions"

KEY_FILE_DESKTOP_KEY_ACTIONS: key under KEY_FILE_DESKTOP_GROUP, whose value is a string list giving the available application actions.

View Source
const KEY_FILE_DESKTOP_KEY_CATEGORIES = "Categories"

KEY_FILE_DESKTOP_KEY_CATEGORIES: key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the categories in which the desktop entry should be shown in a menu.

View Source
const KEY_FILE_DESKTOP_KEY_COMMENT = "Comment"

KEY_FILE_DESKTOP_KEY_COMMENT: key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the tooltip for the desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE = "DBusActivatable"

KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE: key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean set to true if the application is D-Bus activatable.

View Source
const KEY_FILE_DESKTOP_KEY_EXEC = "Exec"

KEY_FILE_DESKTOP_KEY_EXEC: key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the command line to execute. It is only valid for desktop entries with the Application type.

View Source
const KEY_FILE_DESKTOP_KEY_GENERIC_NAME = "GenericName"

KEY_FILE_DESKTOP_KEY_GENERIC_NAME: key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the generic name of the desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_HIDDEN = "Hidden"

KEY_FILE_DESKTOP_KEY_HIDDEN: key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry has been deleted by the user.

View Source
const KEY_FILE_DESKTOP_KEY_ICON = "Icon"

KEY_FILE_DESKTOP_KEY_ICON: key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the name of the icon to be displayed for the desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_MIME_TYPE = "MimeType"

KEY_FILE_DESKTOP_KEY_MIME_TYPE: key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the MIME types supported by this desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_NAME = "Name"

KEY_FILE_DESKTOP_KEY_NAME: key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the specific name of the desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN = "NotShowIn"

KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN: key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should not display the desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_NO_DISPLAY = "NoDisplay"

KEY_FILE_DESKTOP_KEY_NO_DISPLAY: key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry should be shown in menus.

View Source
const KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN = "OnlyShowIn"

KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN: key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should display the desktop entry.

View Source
const KEY_FILE_DESKTOP_KEY_PATH = "Path"

KEY_FILE_DESKTOP_KEY_PATH: key under KEY_FILE_DESKTOP_GROUP, whose value is a string containing the working directory to run the program in. It is only valid for desktop entries with the Application type.

View Source
const KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY = "StartupNotify"

KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY: key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification (http://www.freedesktop.org/Standards/startup-notification-spec).

View Source
const KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS = "StartupWMClass"

KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS: key under KEY_FILE_DESKTOP_GROUP, whose value is string identifying the WM class or name hint of a window that the application will create, which can be used to emulate Startup Notification with older applications.

View Source
const KEY_FILE_DESKTOP_KEY_TERMINAL = "Terminal"

KEY_FILE_DESKTOP_KEY_TERMINAL: key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the program should be run in a terminal window. It is only valid for desktop entries with the Application type.

View Source
const KEY_FILE_DESKTOP_KEY_TRY_EXEC = "TryExec"

KEY_FILE_DESKTOP_KEY_TRY_EXEC: key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the file name of a binary on disk used to determine if the program is actually installed. It is only valid for desktop entries with the Application type.

View Source
const KEY_FILE_DESKTOP_KEY_TYPE = "Type"

KEY_FILE_DESKTOP_KEY_TYPE: key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the type of the desktop entry. Usually KEY_FILE_DESKTOP_TYPE_APPLICATION, KEY_FILE_DESKTOP_TYPE_LINK, or KEY_FILE_DESKTOP_TYPE_DIRECTORY.

View Source
const KEY_FILE_DESKTOP_KEY_URL = "URL"

KEY_FILE_DESKTOP_KEY_URL: key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the URL to access. It is only valid for desktop entries with the Link type.

View Source
const KEY_FILE_DESKTOP_KEY_VERSION = "Version"

KEY_FILE_DESKTOP_KEY_VERSION: key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file.

View Source
const KEY_FILE_DESKTOP_TYPE_APPLICATION = "Application"

KEY_FILE_DESKTOP_TYPE_APPLICATION: value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing applications.

View Source
const KEY_FILE_DESKTOP_TYPE_DIRECTORY = "Directory"

KEY_FILE_DESKTOP_TYPE_DIRECTORY: value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing directories.

View Source
const KEY_FILE_DESKTOP_TYPE_LINK = "Link"

KEY_FILE_DESKTOP_TYPE_LINK: value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing links to documents.

View Source
const LITTLE_ENDIAN = 1234

LITTLE_ENDIAN specifies one of the possible types of byte order. See BYTE_ORDER.

View Source
const LN10 = 2.302585

LN10: natural logarithm of 10.

View Source
const LN2 = 0.693147

LN2: natural logarithm of 2.

View Source
const LOG_2_BASE_10 = 0.301030

LOG_2_BASE_10: multiplying the base 2 exponent by this number yields the base 10 exponent.

View Source
const LOG_DOMAIN = 0

LOG_DOMAIN defines the log domain. See Log Domains (#log-domains).

Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.

Log domains must be unique, and it is recommended that they are the application or library name, optionally followed by a hyphen and a sub-domain name. For example, bloatpad or bloatpad-io.

If undefined, it defaults to the default NULL (or "") log domain; this is not advisable, as it cannot be filtered against using the G_MESSAGES_DEBUG environment variable.

For example, GTK+ uses this in its Makefile.am:

AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"

Applications can choose to leave it as the default NULL (or "") domain. However, defining the domain offers the same advantages as above.

View Source
const LOG_FATAL_MASK = 5

LOG_FATAL_MASK: GLib log levels that are considered fatal by default.

This is not used if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

View Source
const LOG_LEVEL_USER_SHIFT = 8

LOG_LEVEL_USER_SHIFT: log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib. Higher bits can be used for user-defined log levels.

View Source
const MAJOR_VERSION = 2

MAJOR_VERSION: major version number of the GLib library.

Like #glib_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

View Source
const MAXINT16 = 32767

MAXINT16: maximum value which can be held in a #gint16.

View Source
const MAXINT32 = 2147483647

MAXINT32: maximum value which can be held in a #gint32.

View Source
const MAXINT64 = 9223372036854775807

MAXINT64: maximum value which can be held in a #gint64.

View Source
const MAXINT8 = 127

MAXINT8: maximum value which can be held in a #gint8.

View Source
const MAXUINT16 = 65535

MAXUINT16: maximum value which can be held in a #guint16.

View Source
const MAXUINT32 = 4294967295

MAXUINT32: maximum value which can be held in a #guint32.

View Source
const MAXUINT64 = 18446744073709551615

MAXUINT64: maximum value which can be held in a #guint64.

View Source
const MAXUINT8 = 255

MAXUINT8: maximum value which can be held in a #guint8.

View Source
const MICRO_VERSION = 2

MICRO_VERSION: micro version number of the GLib library.

Like #gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

View Source
const MININT16 = -32768

MININT16: minimum value which can be held in a #gint16.

View Source
const MININT32 = -2147483648

MININT32: minimum value which can be held in a #gint32.

View Source
const MININT64 = -9223372036854775808

MININT64: minimum value which can be held in a #gint64.

View Source
const MININT8 = -128

MININT8: minimum value which can be held in a #gint8.

View Source
const MINOR_VERSION = 68

MINOR_VERSION: minor version number of the GLib library.

Like #gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

View Source
const MODULE_SUFFIX = "so"
View Source
const OPTION_REMAINING = ""

OPTION_REMAINING: if a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in argv. The option must be of type G_OPTION_ARG_CALLBACK, G_OPTION_ARG_STRING_ARRAY or G_OPTION_ARG_FILENAME_ARRAY.

Using OPTION_REMAINING instead of simply scanning argv for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.
View Source
const PDP_ENDIAN = 3412

PDP_ENDIAN specifies one of the possible types of byte order (currently unused). See BYTE_ORDER.

View Source
const PI = 3.141593

PI: value of pi (ratio of circle's circumference to its diameter).

View Source
const PID_FORMAT = "i"

PID_FORMAT: format specifier that can be used in printf()-style format strings when printing a #GPid.

View Source
const PI_2 = 1.570796

PI_2: pi divided by 2.

View Source
const PI_4 = 0.785398

PI_4: pi divided by 4.

View Source
const POLLFD_FORMAT = "%d"

POLLFD_FORMAT: format specifier that can be used in printf()-style format strings when printing the fd member of a FD.

View Source
const PRIORITY_DEFAULT = 0

PRIORITY_DEFAULT: use this for default priority event sources.

In GLib this priority is used when adding timeout functions with g_timeout_add(). In GDK this priority is used for events from the X server.

View Source
const PRIORITY_DEFAULT_IDLE = 200

PRIORITY_DEFAULT_IDLE: use this for default priority idle functions.

In GLib this priority is used when adding idle functions with g_idle_add().

View Source
const PRIORITY_HIGH = -100

PRIORITY_HIGH: use this for high priority event sources.

It is not used within GLib or GTK+.

View Source
const PRIORITY_HIGH_IDLE = 100

PRIORITY_HIGH_IDLE: use this for high priority idle functions.

GTK+ uses PRIORITY_HIGH_IDLE + 10 for resizing operations, and PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is done to ensure that any pending resizes are processed before any pending redraws, so that widgets are not redrawn twice unnecessarily.).

View Source
const PRIORITY_LOW = 300

PRIORITY_LOW: use this for very low priority background tasks.

It is not used within GLib or GTK+.

View Source
const SEARCHPATH_SEPARATOR = 58

SEARCHPATH_SEPARATOR: search path separator character. This is ':' on UNIX machines and ';' under Windows.

View Source
const SEARCHPATH_SEPARATOR_S = ":"

SEARCHPATH_SEPARATOR_S: search path separator as a string. This is ":" on UNIX machines and ";" under Windows.

View Source
const SIZEOF_LONG = 8
View Source
const SIZEOF_SIZE_T = 8
View Source
const SIZEOF_SSIZE_T = 8
View Source
const SIZEOF_VOID_P = 8
View Source
const SOURCE_CONTINUE = true

SOURCE_CONTINUE: use this macro as the return value of a Func to leave the #GSource in the main loop.

View Source
const SOURCE_REMOVE = false

SOURCE_REMOVE: use this macro as the return value of a Func to remove the #GSource from the main loop.

View Source
const SQRT2 = 1.414214

SQRT2: square root of two.

View Source
const STR_DELIMITERS = "_-|> <."

STR_DELIMITERS: standard delimiters, used in g_strdelimit().

View Source
const SYSDEF_AF_INET = 2
View Source
const SYSDEF_AF_INET6 = 10
View Source
const SYSDEF_AF_UNIX = 1
View Source
const SYSDEF_MSG_DONTROUTE = 4
View Source
const SYSDEF_MSG_OOB = 1
View Source
const SYSDEF_MSG_PEEK = 2
View Source
const TEST_OPTION_ISOLATE_DIRS = "isolate_dirs"

TEST_OPTION_ISOLATE_DIRS creates a unique temporary directory for each unit test and uses g_set_user_dirs() to set XDG directories to point into subdirectories of it for the duration of the unit test. The directory tree is cleaned up after the test finishes successfully. Note that this doesn’t take effect until g_test_run() is called, so calls to (for example) g_get_user_home_dir() will return the system-wide value when made in a test program’s main() function.

The following functions will return subdirectories of the temporary directory when this option is used. The specific subdirectory paths in use are not guaranteed to be stable API — always use a getter function to retrieve them.

  • g_get_home_dir()
  • g_get_user_cache_dir()
  • g_get_system_config_dirs()
  • g_get_user_config_dir()
  • g_get_system_data_dirs()
  • g_get_user_data_dir()
  • g_get_user_runtime_dir()

The subdirectories may not be created by the test harness; as with normal calls to functions like g_get_user_cache_dir(), the caller must be prepared to create the directory if it doesn’t exist.

View Source
const TIME_SPAN_DAY = 86400000000

TIME_SPAN_DAY evaluates to a time span of one day.

View Source
const TIME_SPAN_HOUR = 3600000000

TIME_SPAN_HOUR evaluates to a time span of one hour.

View Source
const TIME_SPAN_MILLISECOND = 1000

TIME_SPAN_MILLISECOND evaluates to a time span of one millisecond.

View Source
const TIME_SPAN_MINUTE = 60000000

TIME_SPAN_MINUTE evaluates to a time span of one minute.

View Source
const TIME_SPAN_SECOND = 1000000

TIME_SPAN_SECOND evaluates to a time span of one second.

View Source
const UNICHAR_MAX_DECOMPOSITION_LENGTH = 18

UNICHAR_MAX_DECOMPOSITION_LENGTH: maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.

This is as defined by Unicode 6.1.

View Source
const URI_RESERVED_CHARS_GENERIC_DELIMITERS = ":/?#[]@"

URI_RESERVED_CHARS_GENERIC_DELIMITERS: generic delimiters characters as defined in RFC 3986 (https://tools.ietf.org/html/rfc3986). Includes :/?#[]@.

View Source
const URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS = "!$&'()*+,;="

URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS: subcomponent delimiter characters as defined in RFC 3986 (https://tools.ietf.org/html/rfc3986). Includes !$&'()*+,;=.

View Source
const USEC_PER_SEC = 1000000

USEC_PER_SEC: number of microseconds in one second (1 million). This macro is provided for code readability.

View Source
const VERSION_MIN_REQUIRED = 2

VERSION_MIN_REQUIRED: macro that should be defined by the user prior to including the glib.h header. The definition should be one of the predefined GLib version macros: GLIB_VERSION_2_26, GLIB_VERSION_2_28,...

This macro defines the earliest version of GLib that the package is required to be able to compile against.

If the compiler is configured to warn about the use of deprecated functions, then using functions that were deprecated in version GLIB_VERSION_MIN_REQUIRED or earlier will cause warnings (but using functions deprecated in later releases will not).

View Source
const WIN32_MSG_HANDLE = 19981206

Variables

View Source
var (
	GTypeIOCondition        = coreglib.Type(C.g_io_condition_get_type())
	GTypeChecksum           = coreglib.Type(C.g_checksum_get_type())
	GTypeDateTime           = coreglib.Type(C.g_date_time_get_type())
	GTypeHashTable          = coreglib.Type(C.g_hash_table_get_type())
	GTypeIOChannel          = coreglib.Type(C.g_io_channel_get_type())
	GTypeKeyFile            = coreglib.Type(C.g_key_file_get_type())
	GTypeMainContext        = coreglib.Type(C.g_main_context_get_type())
	GTypeMainLoop           = coreglib.Type(C.g_main_loop_get_type())
	GTypeMappedFile         = coreglib.Type(C.g_mapped_file_get_type())
	GTypeMarkupParseContext = coreglib.Type(C.g_markup_parse_context_get_type())
	GTypeMatchInfo          = coreglib.Type(C.g_match_info_get_type())
	GTypeOptionGroup        = coreglib.Type(C.g_option_group_get_type())
	GTypeRegex              = coreglib.Type(C.g_regex_get_type())
	GTypeSource             = coreglib.Type(C.g_source_get_type())
	GTypeTimeZone           = coreglib.Type(C.g_time_zone_get_type())
	GTypeTree               = coreglib.Type(C.g_tree_get_type())
	GTypeURI                = coreglib.Type(C.g_uri_get_type())
	GTypeVariantBuilder     = coreglib.Type(C.g_variant_builder_get_type())
	GTypeVariantDict        = coreglib.Type(C.g_variant_dict_get_type())
	GTypeVariantType        = coreglib.Type(C.g_variant_type_get_gtype())
	GTypeVariant            = coreglib.Type(coreglib.TypeVariant)
)

GType values.

Functions

func AssertWarning

func AssertWarning(logDomain, file string, line int, prettyFunction, expression string)

The function takes the following parameters:

  • logDomain
  • file
  • line
  • prettyFunction
  • expression

func Basename deprecated

func Basename(fileName string) string

Basename gets the name of the file without any leading directory components. It returns a pointer into the given file name string.

Deprecated: Use g_path_get_basename() instead, but notice that g_path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.

The function takes the following parameters:

  • fileName: name of the file.

The function returns the following values:

  • filename: name of the file without any leading directory components.

func BitNthLSF

func BitNthLSF(mask uint32, nthBit int) int

BitNthLSF: 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.

The function takes the following parameters:

  • mask containing flags.
  • nthBit: index of the bit to start the search from.

The function returns the following values:

  • gint: index of the first bit set which is higher than nth_bit, or -1 if no higher bits are set.

func BitNthMSF

func BitNthMSF(mask uint32, nthBit int) int

BitNthMSF: 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.

The function takes the following parameters:

  • mask containing flags.
  • nthBit: index of the bit to start the search from.

The function returns the following values:

  • gint: index of the first bit set which is lower than nth_bit, or -1 if no lower bits are set.

func BitStorage

func BitStorage(number uint32) uint

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

The function takes the following parameters:

  • number: #guint.

The function returns the following values:

  • guint: number of bits used to hold number.

func BuildFilenamev

func BuildFilenamev(args []string) string

BuildFilenamev 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.

The function takes the following parameters:

  • args: NULL-terminated array of strings containing the path elements.

The function returns the following values:

  • filename: newly-allocated string that must be freed with g_free().

func BuildPathv

func BuildPathv(separator string, args []string) string

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

The function takes the following parameters:

  • separator: string used to separator the elements of the path.
  • args: NULL-terminated array of strings containing the path elements.

The function returns the following values:

  • filename: newly-allocated string that must be freed with g_free().

func CanonicalizeFilename

func CanonicalizeFilename(filename, relativeTo string) string

CanonicalizeFilename 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 NULL. If relative_to is NULL, it'll fallback to g_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.

The function takes the following parameters:

  • filename: name of the file.
  • relativeTo (optional): relative directory, or NULL to use the current working directory.

The function returns the following values:

  • ret: newly allocated string with the canonical file path.

func CheckVersion

func CheckVersion(requiredMajor, requiredMinor, requiredMicro uint) string

CheckVersion checks that the GLib library in use is compatible with the given version. Generally you would pass in the constants IB_MAJOR_VERSION, IB_MINOR_VERSION, IB_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.).

The function takes the following parameters:

  • requiredMajor: required major version.
  • requiredMinor: required minor version.
  • requiredMicro: required micro version.

The function returns the following values:

  • utf8: NULL 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.

func ChecksumTypeGetLength

func ChecksumTypeGetLength(checksumType ChecksumType) int

ChecksumTypeGetLength gets the length in bytes of digests of type checksum_type.

The function takes the following parameters:

  • checksumType: Type.

The function returns the following values:

  • gssize: checksum length, or -1 if checksum_type is not supported.

func ComputeChecksumForBytes

func ComputeChecksumForBytes(checksumType ChecksumType, data *Bytes) string

ComputeChecksumForBytes computes the checksum for a binary data. This is a convenience wrapper for g_checksum_new(), g_checksum_get_string() and g_checksum_free().

The hexadecimal string returned will be in lower case.

The function takes the following parameters:

  • checksumType: Type.
  • data: binary blob to compute the digest of.

The function returns the following values:

  • utf8 (optional): digest of the binary data as a string in hexadecimal, or NULL if g_checksum_new() fails for checksum_type. The returned string should be freed with g_free() when done using it.

func ComputeChecksumForData

func ComputeChecksumForData(checksumType ChecksumType, data []byte) string

ComputeChecksumForData computes the checksum for a binary data of length. This is a convenience wrapper for g_checksum_new(), g_checksum_get_string() and g_checksum_free().

The hexadecimal string returned will be in lower case.

The function takes the following parameters:

  • checksumType: Type.
  • data: binary blob to compute the digest of.

The function returns the following values:

  • utf8 (optional): digest of the binary data as a string in hexadecimal, or NULL if g_checksum_new() fails for checksum_type. The returned string should be freed with g_free() when done using it.

func ComputeChecksumForString

func ComputeChecksumForString(checksumType ChecksumType, str string, length int) string

ComputeChecksumForString computes the checksum of a string.

The hexadecimal string returned will be in lower case.

The function takes the following parameters:

  • checksumType: Type.
  • str: string to compute the checksum of.
  • length of the string, or -1 if the string is null-terminated.

The function returns the following values:

  • utf8 (optional): checksum as a hexadecimal string, or NULL if g_checksum_new() fails for checksum_type. The returned string should be freed with g_free() when done using it.

func ComputeHMACForBytes

func ComputeHMACForBytes(digestType ChecksumType, key, data *Bytes) string

ComputeHMACForBytes computes the HMAC for a binary data. This is a convenience wrapper for g_hmac_new(), g_hmac_get_string() and g_hmac_unref().

The hexadecimal string returned will be in lower case.

The function takes the following parameters:

  • digestType to use for the HMAC.
  • key to use in the HMAC.
  • data: binary blob to compute the HMAC of.

The function returns the following values:

  • utf8: HMAC of the binary data as a string in hexadecimal. The returned string should be freed with g_free() when done using it.

func ComputeHMACForData

func ComputeHMACForData(digestType ChecksumType, key, data []byte) string

ComputeHMACForData computes the HMAC for a binary data of length. This is a convenience wrapper for g_hmac_new(), g_hmac_get_string() and g_hmac_unref().

The hexadecimal string returned will be in lower case.

The function takes the following parameters:

  • digestType to use for the HMAC.
  • key to use in the HMAC.
  • data: binary blob to compute the HMAC of.

The function returns the following values:

  • utf8: HMAC of the binary data as a string in hexadecimal. The returned string should be freed with g_free() when done using it.

func ComputeHMACForString

func ComputeHMACForString(digestType ChecksumType, key []byte, str string, length int) string

ComputeHMACForString computes the HMAC for a string.

The hexadecimal string returned will be in lower case.

The function takes the following parameters:

  • digestType to use for the HMAC.
  • key to use in the HMAC.
  • str: string to compute the HMAC for.
  • length of the string, or -1 if the string is nul-terminated.

The function returns the following values:

  • utf8: HMAC as a hexadecimal string. The returned string should be freed with g_free() when done using it.

func Convert

func Convert(str, toCodeset, fromCodeset string) (uint, []byte, error)

Convert 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 g_convert(), g_convert_with_iconv() or g_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 g_str_to_ascii() instead.

The function takes the following parameters:

  • str: the string to convert.
  • toCodeset: name of character set into which to convert str.
  • fromCodeset: character set of str.

The function returns the following values:

  • bytesRead (optional): location to store the number of bytes in the input string that were successfully converted, or NULL. 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 CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
  • guint8s: If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with g_free(). Otherwise NULL and error will be set.

func ConvertWithFallback

func ConvertWithFallback(str, toCodeset, fromCodeset, fallback string) (uint, []byte, error)

ConvertWithFallback 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 g_convert(), g_convert_with_iconv() or g_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.).

The function takes the following parameters:

  • str: the string to convert.
  • toCodeset: name of character set into which to convert str.
  • fromCodeset: character set of str.
  • fallback: 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 NULL, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.

The function returns the following values:

  • bytesRead (optional): location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input.
  • guint8s: If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with g_free(). Otherwise NULL and error will be set.

func Dcgettext

func Dcgettext(domain, msgid string, category int) string

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

The function takes the following parameters:

  • domain (optional): translation domain to use, or NULL to use the domain set with textdomain().
  • msgid: message to translate.
  • category: locale category.

The function returns the following values:

  • utf8: translated string for the given locale category.

func Dgettext

func Dgettext(domain, msgid string) string

Dgettext: 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 g_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 NULL

- 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.

The function takes the following parameters:

  • domain (optional): translation domain to use, or NULL to use the domain set with textdomain().
  • msgid: message to translate.

The function returns the following values:

  • utf8: translated string.

func DirectEqual

func DirectEqual(v1, v2 unsafe.Pointer) bool

DirectEqual compares two #gpointer arguments and returns TRUE 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 Table.

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

The function takes the following parameters:

  • v1 (optional): key.
  • v2 (optional): key to compare with v1.

The function returns the following values:

  • ok: TRUE if the two keys match.

func DirectHash

func DirectHash(v unsafe.Pointer) uint

DirectHash 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 Table.

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

The function takes the following parameters:

  • v (optional): #gpointer key.

The function returns the following values:

  • guint: hash value corresponding to the key.

func Dngettext

func Dngettext(domain, msgid, msgidPlural string, n uint32) string

Dngettext: 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 g_dgettext() for details of how this differs from dngettext() proper.

The function takes the following parameters:

  • domain (optional): translation domain to use, or NULL to use the domain set with textdomain().
  • msgid: message to translate.
  • msgidPlural: plural form of the message.
  • n: quantity for which translation is needed.

The function returns the following values:

  • utf8: translated string.

func DoubleEqual

func DoubleEqual(v1, v2 unsafe.Pointer) bool

DoubleEqual compares the two #gdouble values being pointed to and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-NULL pointers to doubles as keys in a Table.

The function takes the following parameters:

  • v1: pointer to a #gdouble key.
  • v2: pointer to a #gdouble key to compare with v1.

The function returns the following values:

  • ok: TRUE if the two keys match.

func DoubleHash

func DoubleHash(v unsafe.Pointer) uint

DoubleHash 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-NULL pointers to doubles as keys in a Table.

The function takes the following parameters:

  • v: pointer to a #gdouble key.

The function returns the following values:

  • guint: hash value corresponding to the key.

func Dpgettext

func Dpgettext(domain, msgctxtid string, msgidoffset uint) string

Dpgettext: this function is a variant of g_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 g_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.

The function takes the following parameters:

  • domain (optional): translation domain to use, or NULL to use the domain set with textdomain().
  • msgctxtid: combined message context and message id, separated by a \004 character.
  • msgidoffset: offset of the message id in msgctxid.

The function returns the following values:

  • utf8: translated string.

func Dpgettext2

func Dpgettext2(domain, context, msgid string) string

Dpgettext2: this function is a variant of g_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 g_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.

The function takes the following parameters:

  • domain (optional): translation domain to use, or NULL to use the domain set with textdomain().
  • context: message context.
  • msgid: message.

The function returns the following values:

  • utf8: translated string.

func EnvironGetenv

func EnvironGetenv(envp []string, variable string) string

EnvironGetenv returns the value of the environment variable variable in the provided list envp.

The function takes the following parameters:

  • envp (optional): an environment list (eg, as returned from g_get_environ()), or NULL for an empty environment list.
  • variable: environment variable to get.

The function returns the following values:

  • filename: value of the environment variable, or NULL 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.

func EnvironSetenv

func EnvironSetenv(envp []string, variable, value string, overwrite bool) []string

EnvironSetenv sets the environment variable variable in the provided list envp to value.

The function takes the following parameters:

  • envp (optional): an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), or NULL for an empty environment list.
  • variable: environment variable to set, must not contain '='.
  • value for to set the variable to.
  • overwrite: whether to change the variable if it already exists.

The function returns the following values:

  • filenames: the updated environment list. Free it using g_strfreev().

func EnvironUnsetenv

func EnvironUnsetenv(envp []string, variable string) []string

EnvironUnsetenv removes the environment variable variable from the provided environment envp.

The function takes the following parameters:

  • envp (optional): an environment list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), or NULL for an empty environment list.
  • variable: environment variable to remove, must not contain '='.

The function returns the following values:

  • filenames: the updated environment list. Free it using g_strfreev().

func FileGetContents

func FileGetContents(filename string) ([]byte, error)

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

If the call was successful, it returns TRUE 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 NULL for the length argument. If the call was not successful, it returns FALSE and sets error. The error domain is FILE_ERROR. Possible error codes are those in the Error enumeration. In the error case, contents is set to NULL and length is set to zero.

The function takes the following parameters:

  • filename: name of a file to read contents from, in the GLib file name encoding.

The function returns the following values:

  • contents: location to store an allocated string, use g_free() to free the returned string.

func FileOpenTmp

func FileOpenTmp(tmpl string) (string, int, error)

FileOpenTmp opens a file for writing in the preferred directory for temporary files (as returned by g_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 NULL, 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-NULL, the actual name used is returned in name_used. This string should be freed with g_free() when not needed any longer. The returned name is in the GLib file name encoding.

The function takes the following parameters:

  • tmpl (optional): template for file name, as in g_mkstemp(), basename only, or NULL for a default template.

The function returns the following values:

  • nameUsed: location to store actual name used, or NULL.
  • gint: 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.
func FileReadLink(filename string) (string, error)

FileReadLink reads the contents of the symbolic link filename like the POSIX readlink() function. The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to convert it to UTF-8.

The function takes the following parameters:

  • filename: symbolic link.

The function returns the following values:

  • ret: newly-allocated string with the contents of the symbolic link, or NULL if an error occurred.

func FileSetContents

func FileSetContents(filename, contents string) error

FileSetContents writes all of contents to a file named filename. This is a convenience wrapper around calling g_file_set_contents_full() with flags set to G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING and mode set to 0666.

The function takes the following parameters:

  • filename: name of a file to write contents to, in the GLib file name encoding.
  • contents: string to write to the file.

func FileSetContentsFull

func FileSetContentsFull(filename, contents string, flags FileSetContentsFlags, mode int) error

FileSetContentsFull 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 G_FILE_SET_CONTENTS_NONE then this function may call fsync().

If G_FILE_SET_CONTENTS_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 G_FILE_SET_CONTENTS_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 G_FILE_SET_CONTENTS_DURABLE and G_FILE_SET_CONTENTS_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 TRUE. If the call was not successful, it returns FALSE and sets error. The error domain is FILE_ERROR. Possible error codes are those in the Error 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 may be changed to mode depending on flags, or they may remain unchanged.

The function takes the following parameters:

  • filename: name of a file to write contents to, in the GLib file name encoding.
  • contents: string to write to the file.
  • flags controlling the safety vs speed of the operation.
  • mode: file mode, as passed to open(); typically this will be 0666.

func FilenameDisplayBasename

func FilenameDisplayBasename(filename string) string

FilenameDisplayBasename 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 g_filename_display_name() if you know the whole path, as it allows translation.

The function takes the following parameters:

  • filename: absolute pathname in the GLib file name encoding.

The function returns the following values:

  • utf8: newly allocated string containing a rendition of the basename of the filename in valid UTF-8.

func FilenameDisplayName

func FilenameDisplayName(filename string) string

FilenameDisplayName 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 g_filename_to_utf8(), the result is guaranteed to be non-NULL 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 g_filename_display_basename(), since that allows location-based translation of filenames.

The function takes the following parameters:

  • filename: pathname hopefully in the GLib file name encoding.

The function returns the following values:

  • utf8: newly allocated string containing a rendition of the filename in valid UTF-8.

func FilenameFromURI

func FilenameFromURI(uri string) (hostname, filename string, goerr error)

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

The function takes the following parameters:

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

The function returns the following values:

  • hostname (optional): location to store hostname for the URI. If there is no hostname in the URI, NULL will be stored in this location.
  • filename: newly-allocated string holding the resulting filename, or NULL on an error.

func FilenameFromUTF8

func FilenameFromUTF8(utf8String string, len int) (bytesRead, bytesWritten uint, filename string, goerr error)

FilenameFromUTF8 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][setlocale].

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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the error G_CONVERT_ERROR_EMBEDDED_NUL is set and the function returns NULL.

The function takes the following parameters:

  • utf8String: UTF-8 encoded string.
  • len: length of the string, or -1 if the string is nul-terminated.

The function returns the following values:

  • bytesRead (optional): location to store the number of bytes in the input string that were successfully converted, or NULL. 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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
  • bytesWritten (optional): number of bytes stored in the output buffer (not including the terminating nul).
  • filename: The converted string, or NULL on an error.

func FilenameToURI

func FilenameToURI(filename, hostname string) (string, error)

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

The function takes the following parameters:

  • filename: 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 (optional): UTF-8 encoded hostname, or NULL for none.

The function returns the following values:

  • utf8: newly-allocated string holding the resulting URI, or NULL on an error.

func FilenameToUTF8

func FilenameToUTF8(opsysstring string, len int) (bytesRead, bytesWritten uint, utf8 string, goerr error)

FilenameToUTF8 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][setlocale].

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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE. If the source encoding is not UTF-8 and the conversion output contains a nul character, the error G_CONVERT_ERROR_EMBEDDED_NUL is set and the function returns NULL. Use g_convert() to produce output that may contain embedded nul characters.

The function takes the following parameters:

  • opsysstring: string in the encoding for filenames.
  • len: 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).

The function returns the following values:

  • bytesRead (optional): location to store the number of bytes in the input string that were successfully converted, or NULL. 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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
  • bytesWritten (optional): number of bytes stored in the output buffer (not including the terminating nul).
  • utf8: converted string, or NULL on an error.

func FindProgramInPath

func FindProgramInPath(program string) string

FindProgramInPath 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 NULL 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 NULL 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.

The function takes the following parameters:

  • program name in the GLib file name encoding.

The function returns the following values:

  • filename (optional): newly-allocated string with the absolute path, or NULL.

func FormatSize

func FormatSize(size uint64) string

FormatSize 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 g_free() when not needed any longer.

See g_format_size_full() for more options about how the size might be formatted.

The function takes the following parameters:

  • size in bytes.

The function returns the following values:

  • utf8: newly-allocated formatted string containing a human readable file size.

func FormatSizeForDisplay deprecated

func FormatSizeForDisplay(size int64) string

FormatSizeForDisplay 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.1 MB".

The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).

This string should be freed with g_free() when not needed any longer.

Deprecated: This function is broken due to its use of SI suffixes to denote IEC units. Use g_format_size() instead.

The function takes the following parameters:

  • size in bytes.

The function returns the following values:

  • utf8: newly-allocated formatted string containing a human readable file size.

func FormatSizeFull

func FormatSizeFull(size uint64, flags FormatSizeFlags) string

FormatSizeFull formats a size.

This function is similar to g_format_size() but allows for flags that modify the output. See SizeFlags.

The function takes the following parameters:

  • size in bytes.
  • flags to modify the output.

The function returns the following values:

  • utf8: newly-allocated formatted string containing a human readable file size.

func GetApplicationName

func GetApplicationName() string

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

The function returns the following values:

  • utf8 (optional): human-readable application name. May return NULL.

func GetCharset

func GetCharset() (string, bool)

GetCharset obtains the character set for the [current locale][setlocale]; you might use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding. (Frequently g_locale_to_utf8() and g_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.

The return value is TRUE if the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().

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

The function returns the following values:

  • charset (optional): return location for character set name, or NULL.
  • ok: TRUE if the returned charset is UTF-8.

func GetCodeset

func GetCodeset() string

GetCodeset gets the character set for the current locale.

The function returns the following values:

  • utf8: newly allocated string containing the name of the character set. This string must be freed with g_free().

func GetConsoleCharset

func GetConsoleCharset() (string, bool)

GetConsoleCharset 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 g_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 TRUE if the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().

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

The function returns the following values:

  • charset (optional): return location for character set name, or NULL.
  • ok: TRUE if the returned charset is UTF-8.

func GetCurrentDir

func GetCurrentDir() string

GetCurrentDir 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.

The function returns the following values:

  • filename: current directory.

func GetCurrentTime deprecated

func GetCurrentTime(result *TimeVal)

GetCurrentTime: equivalent to the UNIX gettimeofday() function, but portable.

You may find g_get_real_time() to be more convenient.

Deprecated: Val is not year-2038-safe. Use g_get_real_time() instead.

The function takes the following parameters:

  • result structure in which to store current time.

func GetEnviron

func GetEnviron() []string

GetEnviron gets the list of environment variables for the current process.

The list is NULL 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 g_strfreev() when it is no longer needed.

The function returns the following values:

  • filenames: the list of environment variables.

func GetFilenameCharsets

func GetFilenameCharsets() ([]string, bool)

GetFilenameCharsets 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 g_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][setlocale]. 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.

The function returns the following values:

  • filenameCharsets: return location for the NULL-terminated list of encoding names.
  • ok: TRUE if the filename encoding is UTF-8.

func GetHomeDir

func GetHomeDir() string

GetHomeDir 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.

The function returns the following values:

  • filename: current user's home directory.

func GetHostName

func GetHostName() string

GetHostName: 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.

The function returns the following values:

  • utf8: host name of the machine.

func GetLanguageNames

func GetLanguageNames() []string

GetLanguageNames 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.

The function returns the following values:

  • utf8s: NULL-terminated array of strings owned by GLib that must not be modified or freed.

func GetLanguageNamesWithCategory

func GetLanguageNamesWithCategory(categoryName string) []string

GetLanguageNamesWithCategory 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.

g_get_language_names() returns g_get_language_names_with_category("LC_MESSAGES").

The function takes the following parameters:

  • categoryName: locale category name.

The function returns the following values:

  • utf8s: NULL-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.

func GetLocaleVariants

func GetLocaleVariants(locale string) []string

GetLocaleVariants 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) (man:setlocale) 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-8euro, then the returned list is en_GB.UTF-8euro, en_GB.UTF-8, en_GBeuro, en_GB, en.UTF-8euro, en.UTF-8, eneuro, en.

If you need the list of variants for the current locale, use g_get_language_names().

The function takes the following parameters:

  • locale identifier.

The function returns the following values:

  • utf8s: newly allocated array of newly allocated strings with the locale variants. Free with g_strfreev().

func GetMonotonicTime

func GetMonotonicTime() int64

GetMonotonicTime queries the system monotonic time.

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.

The function returns the following values:

  • gint64: monotonic time, in microseconds.

func GetOsInfo

func GetOsInfo(keyName string) string

GetOsInfo: 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 NULL.

The function takes the following parameters:

  • keyName: key for the OS info being requested, for example G_OS_INFO_KEY_NAME.

The function returns the following values:

  • utf8 (optional): associated value for the requested key or NULL if this information is not provided.

func GetPrgname

func GetPrgname() string

GetPrgname gets the name of the program. This name should not be localized, in contrast to g_get_application_name().

If you are using #GApplication the program name is set in g_application_run(). In case of GDK or GTK+ it is set in gdk_init(), which is called by gtk_init() and the Application::startup handler. The program name is found by taking the last component of argv[0].

The function returns the following values:

  • utf8 (optional): name of the program, or NULL if it has not been set yet. The returned string belongs to GLib and must not be modified or freed.

func GetRealName

func GetRealName() string

GetRealName 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.

The function returns the following values:

  • filename user's real name.

func GetRealTime

func GetRealTime() int64

GetRealTime queries the system wall-clock time.

This call is functionally equivalent to g_get_current_time() except that the return value is often more convenient than dealing with a Val.

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

The function returns the following values:

  • gint64: number of microseconds since January 1, 1970 UTC.

func GetSystemConfigDirs

func GetSystemConfigDirs() []string

GetSystemConfigDirs 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 (http://www.freedesktop.org/Standards/basedir-spec). 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 CSIDL_COMMON_APPDATA 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.

The function returns the following values:

  • filenames: a NULL-terminated array of strings owned by GLib that must not be modified or freed.

func GetSystemDataDirs

func GetSystemDataDirs() []string

GetSystemDataDirs 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 (http://www.freedesktop.org/Standards/basedir-spec) 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 CSIDL_COMMON_APPDATA and CSIDL_COMMON_DOCUMENTS.

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.

The function returns the following values:

  • filenames: a NULL-terminated array of strings owned by GLib that must not be modified or freed.

func GetTmpDir

func GetTmpDir() string

GetTmpDir 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 NULL or the empty string.

The function returns the following values:

  • filename: directory to use for temporary files.

func GetUserCacheDir

func GetUserCacheDir() string

GetUserCacheDir 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 (http://www.freedesktop.org/Standards/basedir-spec). 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 CSIDL_INTERNET_CACHE (https://msdn.microsoft.com/en-us/library/windows/desktop/bb76249428v=vs.8529.aspx#csidl_internet_cache).

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.

The function returns the following values:

  • filename: string owned by GLib that must not be modified or freed.

func GetUserConfigDir

func GetUserConfigDir() string

GetUserConfigDir 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 (http://www.freedesktop.org/Standards/basedir-spec). 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 CSIDL_LOCAL_APPDATA (https://msdn.microsoft.com/en-us/library/windows/desktop/bb76249428v=vs.8529.aspx#csidl_local_appdata). Note that in this case on Windows it will be the same as what g_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.

The function returns the following values:

  • filename: string owned by GLib that must not be modified or freed.

func GetUserDataDir

func GetUserDataDir() string

GetUserDataDir 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 (http://www.freedesktop.org/Standards/basedir-spec). 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 CSIDL_LOCAL_APPDATA (https://msdn.microsoft.com/en-us/library/windows/desktop/bb76249428v=vs.8529.aspx#csidl_local_appdata). Note that in this case on Windows it will be the same as what g_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.

The function returns the following values:

  • filename: string owned by GLib that must not be modified or freed.

func GetUserName

func GetUserName() string

GetUserName 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.

The function returns the following values:

  • filename: user name of the current user.

func GetUserRuntimeDir

func GetUserRuntimeDir() string

GetUserRuntimeDir 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 (http://www.freedesktop.org/Standards/basedir-spec). 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 g_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.

The function returns the following values:

  • filename: string owned by GLib that must not be modified or freed.

func GetUserSpecialDir

func GetUserSpecialDir(directory UserDirectory) string

GetUserSpecialDir 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, G_USER_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.

The function takes the following parameters:

  • directory: logical id of special directory.

The function returns the following values:

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

func Getenv

func Getenv(variable string) string

Getenv 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.

The function takes the following parameters:

  • variable: environment variable to get.

The function returns the following values:

  • filename: value of the environment variable, or NULL if the environment variable is not found. The returned string may be overwritten by the next call to g_getenv(), g_setenv() or g_unsetenv().

func HashTableAdd

func HashTableAdd(hashTable map[unsafe.Pointer]unsafe.Pointer, key unsafe.Pointer) bool

HashTableAdd: this is a convenience function for using a Table as a set. It is equivalent to calling g_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.

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to insert.

The function returns the following values:

  • ok: TRUE if the key did not exist yet.

func HashTableContains

func HashTableContains(hashTable map[unsafe.Pointer]unsafe.Pointer, key unsafe.Pointer) bool

HashTableContains checks if key is in hash_table.

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to check.

The function returns the following values:

  • ok: TRUE if key is in hash_table, FALSE otherwise.

func HashTableDestroy

func HashTableDestroy(hashTable map[unsafe.Pointer]unsafe.Pointer)

HashTableDestroy destroys all keys and values in the Table and decrements its reference count by 1. If keys and/or values are dynamically allocated, you should either free them first or create the Table 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.

The function takes the following parameters:

  • hashTable: Table.

func HashTableInsert

func HashTableInsert(hashTable map[unsafe.Pointer]unsafe.Pointer, key, value unsafe.Pointer) bool

HashTableInsert inserts a new key and value into a Table.

If the key already exists in the Table its current value is replaced with the new value. If you supplied a value_destroy_func when creating the Table, the old value is freed using that function. If you supplied a key_destroy_func when creating the Table, 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.

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to insert.
  • value (optional) to associate with the key.

The function returns the following values:

  • ok: TRUE if the key did not exist yet.

func HashTableLookup

func HashTableLookup(hashTable map[unsafe.Pointer]unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer

HashTableLookup looks up a key in a Table. Note that this function cannot distinguish between a key that is not present and one which is present and has the value NULL. If you need this distinction, use g_hash_table_lookup_extended().

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to look up.

The function returns the following values:

  • gpointer (optional): associated value, or NULL if the key is not found.

func HashTableLookupExtended

func HashTableLookupExtended(hashTable map[unsafe.Pointer]unsafe.Pointer, lookupKey unsafe.Pointer) (origKey, value unsafe.Pointer, ok bool)

HashTableLookupExtended looks up a key in the Table, returning the original key and the associated value and a #gboolean which is TRUE if the key was found. This is useful if you need to free the memory allocated for the original key, for example before calling g_hash_table_remove().

You can actually pass NULL for lookup_key to test whether the NULL key exists, provided the hash and equal functions of hash_table are NULL-safe.

The function takes the following parameters:

  • hashTable: Table.
  • lookupKey (optional): key to look up.

The function returns the following values:

  • origKey (optional): return location for the original key.
  • value (optional): return location for the value associated with the key.
  • ok: TRUE if the key was found in the Table.

func HashTableRemove

func HashTableRemove(hashTable map[unsafe.Pointer]unsafe.Pointer, key unsafe.Pointer) bool

HashTableRemove removes a key and its associated value from a Table.

If the Table 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.

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to remove.

The function returns the following values:

  • ok: TRUE if the key was found and removed from the Table.

func HashTableRemoveAll

func HashTableRemoveAll(hashTable map[unsafe.Pointer]unsafe.Pointer)

HashTableRemoveAll removes all keys and their associated values from a Table.

If the Table 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.

The function takes the following parameters:

  • hashTable: Table.

func HashTableReplace

func HashTableReplace(hashTable map[unsafe.Pointer]unsafe.Pointer, key, value unsafe.Pointer) bool

HashTableReplace inserts a new key and value into a Table similar to g_hash_table_insert(). The difference is that if the key already exists in the Table, it gets replaced by the new key. If you supplied a value_destroy_func when creating the Table, the old value is freed using that function. If you supplied a key_destroy_func when creating the Table, 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.

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to insert.
  • value (optional) to associate with the key.

The function returns the following values:

  • ok: TRUE if the key did not exist yet.

func HashTableSize

func HashTableSize(hashTable map[unsafe.Pointer]unsafe.Pointer) uint

HashTableSize returns the number of elements contained in the Table.

The function takes the following parameters:

  • hashTable: Table.

The function returns the following values:

  • guint: number of key/value pairs in the Table.

func HashTableSteal

func HashTableSteal(hashTable map[unsafe.Pointer]unsafe.Pointer, key unsafe.Pointer) bool

HashTableSteal removes a key and its associated value from a Table without calling the key and value destroy functions.

The function takes the following parameters:

  • hashTable: Table.
  • key (optional) to remove.

The function returns the following values:

  • ok: TRUE if the key was found and removed from the Table.

func HashTableStealAll

func HashTableStealAll(hashTable map[unsafe.Pointer]unsafe.Pointer)

HashTableStealAll removes all keys and their associated values from a Table without calling the key and value destroy functions.

The function takes the following parameters:

  • hashTable: Table.

func HashTableStealExtended

func HashTableStealExtended(hashTable map[unsafe.Pointer]unsafe.Pointer, lookupKey unsafe.Pointer) (stolenKey, stolenValue unsafe.Pointer, ok bool)

HashTableStealExtended looks up a key in the Table, stealing the original key and the associated value and returning TRUE if the key was found. If the key was not found, FALSE 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 g_hash_table_steal().

You can pass NULL for lookup_key, provided the hash and equal functions of hash_table are NULL-safe.

The function takes the following parameters:

  • hashTable: Table.
  • lookupKey (optional): key to look up.

The function returns the following values:

  • stolenKey (optional): return location for the original key.
  • stolenValue (optional): return location for the value associated with the key.
  • ok: TRUE if the key was found in the Table.

func HostnameIsASCIIEncoded

func HostnameIsASCIIEncoded(hostname string) bool

HostnameIsASCIIEncoded tests if hostname contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returns TRUE, you should decode the hostname with g_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 g_hostname_is_non_ascii() and g_hostname_is_ascii_encoded() to both return TRUE for a name.

The function takes the following parameters:

  • hostname: hostname.

The function returns the following values:

  • ok: TRUE if hostname contains any ASCII-encoded segments.

func HostnameIsIPAddress

func HostnameIsIPAddress(hostname string) bool

HostnameIsIPAddress 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).

The function takes the following parameters:

  • hostname (or IP address in string form).

The function returns the following values:

  • ok: TRUE if hostname is an IP address.

func HostnameIsNonASCII

func HostnameIsNonASCII(hostname string) bool

HostnameIsNonASCII tests if hostname contains Unicode characters. If this returns TRUE, you need to encode the hostname with g_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 g_hostname_is_non_ascii() and g_hostname_is_ascii_encoded() to both return TRUE for a name.

The function takes the following parameters:

  • hostname: hostname.

The function returns the following values:

  • ok: TRUE if hostname contains any non-ASCII characters.

func HostnameToASCII

func HostnameToASCII(hostname string) string

HostnameToASCII converts hostname to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.

The function takes the following parameters:

  • hostname: valid UTF-8 or ASCII hostname.

The function returns the following values:

  • utf8 (optional): ASCII hostname, which must be freed, or NULL if hostname is in some way invalid.

func HostnameToUnicode

func HostnameToUnicode(hostname string) string

HostnameToUnicode 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.

The function takes the following parameters:

  • hostname: valid UTF-8 or ASCII hostname.

The function returns the following values:

  • utf8 (optional): UTF-8 hostname, which must be freed, or NULL if hostname is in some way invalid.

func IdleRemoveByData

func IdleRemoveByData(data unsafe.Pointer) bool

IdleRemoveByData removes the idle function with the given data.

The function takes the following parameters:

  • data (optional) for the idle source's callback.

The function returns the following values:

  • ok: TRUE if an idle source was found and removed.

func Int64Equal

func Int64Equal(v1, v2 unsafe.Pointer) bool

Int64Equal compares the two #gint64 values being pointed to and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-NULL pointers to 64-bit integers as keys in a Table.

The function takes the following parameters:

  • v1: pointer to a #gint64 key.
  • v2: pointer to a #gint64 key to compare with v1.

The function returns the following values:

  • ok: TRUE if the two keys match.

func Int64Hash

func Int64Hash(v unsafe.Pointer) uint

Int64Hash 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-NULL pointers to 64-bit integer values as keys in a Table.

The function takes the following parameters:

  • v: pointer to a #gint64 key.

The function returns the following values:

  • guint: hash value corresponding to the key.

func IntEqual

func IntEqual(v1, v2 unsafe.Pointer) bool

IntEqual compares the two #gint values being pointed to and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-NULL pointers to integers as keys in a Table.

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 g_direct_equal() instead.

The function takes the following parameters:

  • v1: pointer to a #gint key.
  • v2: pointer to a #gint key to compare with v1.

The function returns the following values:

  • ok: TRUE if the two keys match.

func IntHash

func IntHash(v unsafe.Pointer) uint

IntHash 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-NULL pointers to integer values as keys in a Table.

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 g_direct_hash() instead.

The function takes the following parameters:

  • v: pointer to a #gint key.

The function returns the following values:

  • guint: hash value corresponding to the key.

func InternStaticString

func InternStaticString(str string) string

InternStaticString returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). g_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++.

The function takes the following parameters:

  • str (optional): static string.

The function returns the following values:

  • utf8: canonical representation for the string.

func InternString

func InternString(str string) string

InternString 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++.

The function takes the following parameters:

  • str (optional): string.

The function returns the following values:

  • utf8: canonical representation for the string.

func Listenv

func Listenv() []string

Listenv gets the names of all variables set in the environment.

Programs that want to be portable to Windows should typically use this function and g_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 g_getenv() provide.

The function returns the following values:

  • filenames: a NULL-terminated list of strings which must be freed with g_strfreev().

func LocaleFromUTF8

func LocaleFromUTF8(utf8String string, len int) (uint, []byte, error)

LocaleFromUTF8 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][setlocale]. 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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE. Use g_convert() to convert input that may contain embedded nul characters.

The function takes the following parameters:

  • utf8String: UTF-8 encoded string.
  • len: length of the string, or -1 if the string is nul-terminated.

The function returns the following values:

  • bytesRead (optional): location to store the number of bytes in the input string that were successfully converted, or NULL. 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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
  • guint8s: A newly-allocated buffer containing the converted string, or NULL on an error, and error will be set.

func LocaleToUTF8

func LocaleToUTF8(opsysstring string) (bytesRead, bytesWritten uint, utf8 string, goerr error)

LocaleToUTF8 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][setlocale] into a UTF-8 string.

If the source encoding is not UTF-8 and the conversion output contains a nul character, the error G_CONVERT_ERROR_EMBEDDED_NUL is set and the function returns NULL. If the source encoding is UTF-8, an embedded nul character is treated with the G_CONVERT_ERROR_ILLEGAL_SEQUENCE error for backward compatibility with earlier versions of this library. Use g_convert() to produce output that may contain embedded nul characters.

The function takes the following parameters:

  • opsysstring: string in the encoding of the current locale. On Windows this means the system codepage.

The function returns the following values:

  • bytesRead (optional): location to store the number of bytes in the input string that were successfully converted, or NULL. 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 G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
  • bytesWritten (optional): number of bytes stored in the output buffer (not including the terminating nul).
  • utf8: converted string, or NULL on an error.

func LogDefaultHandler

func LogDefaultHandler(logDomain string, logLevel LogLevelFlags, message string, unusedData unsafe.Pointer)

LogDefaultHandler: default log handler set up by GLib; g_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 G_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.

stderr is used for levels G_LOG_LEVEL_ERROR, G_LOG_LEVEL_CRITICAL, G_LOG_LEVEL_WARNING and G_LOG_LEVEL_MESSAGE. stdout is used for the rest, unless stderr was requested by g_log_writer_default_set_use_stderr().

This has no effect if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

The function takes the following parameters:

  • logDomain (optional): log domain of the message, or NULL for the default "" application domain.
  • logLevel: level of the message.
  • message (optional): message.
  • unusedData (optional): data passed from g_log() which is unused.

func LogRemoveHandler

func LogRemoveHandler(logDomain string, handlerId uint)

LogRemoveHandler removes the log handler.

This has no effect if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

The function takes the following parameters:

  • logDomain: log domain.
  • handlerId: id of the handler, which was returned in g_log_set_handler().

func LogStructuredArray

func LogStructuredArray(logLevel LogLevelFlags, fields []LogField)

LogStructuredArray: log a message with structured data. The message will be passed through to the log writer set by the application using g_log_set_writer_func(). If the message is fatal (i.e. its log level is G_LOG_LEVEL_ERROR), the program will be aborted at the end of this function.

See g_log_structured() for more documentation.

This assumes that log_level is already present in fields (typically as the PRIORITY field).

The function takes the following parameters:

  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • fields: key–value pairs of structured data to add to the log message.

func LogVariant

func LogVariant(logDomain string, logLevel LogLevelFlags, fields *Variant)

LogVariant: 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 String (VARIANT_TYPE_STRING). Array of bytes (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 g_variant_print() will be used to convert the value into a string.

For more details on its usage and about the parameters, see g_log_structured().

The function takes the following parameters:

  • logDomain (optional): log domain, usually G_LOG_DOMAIN.
  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • fields: dictionary (#GVariant of the type G_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.

func LogWriterDefaultSetUseStderr

func LogWriterDefaultSetUseStderr(useStderr bool)

LogWriterDefaultSetUseStderr: configure whether the built-in log functions (g_log_default_handler() for the old-style API, and both g_log_writer_default() and g_log_writer_standard_streams() for the structured API) will output all log messages to stderr.

By default, log messages of levels G_LOG_LEVEL_INFO and G_LOG_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.

The function takes the following parameters:

  • useStderr: if TRUE, use stderr for log messages that would normally have appeared on stdout.

func LogWriterDefaultWouldDrop

func LogWriterDefaultWouldDrop(logLevel LogLevelFlags, logDomain string) bool

LogWriterDefaultWouldDrop: check whether g_log_writer_default() and g_log_default_handler() would ignore a message with the given domain and level.

As with g_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.

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 (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
  {
    gchar *result = expensive_computation (my_object);

    g_debug ("my_object result: s", result);
    g_free (result);
  }.

The function takes the following parameters:

  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • logDomain (optional): log domain.

The function returns the following values:

  • ok: TRUE if the log message would be dropped by GLib's default log handlers.

func LogWriterFormatFields

func LogWriterFormatFields(logLevel LogLevelFlags, fields []LogField, useColor bool) string

LogWriterFormatFields: format a structured log message as a string suitable for outputting to the terminal (or elsewhere). This will include the values of all fields it knows how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the documentation for g_log_structured()). It does not include values from unknown fields.

The returned string does **not** have a trailing new-line character. It is encoded in the character set of the current locale, which is not necessarily UTF-8.

The function takes the following parameters:

  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • fields: key–value pairs of structured data forming the log message.
  • useColor: TRUE to use ANSI color escape sequences when formatting the message, FALSE to not.

The function returns the following values:

  • utf8: string containing the formatted log message, in the character set of the current locale.

func LogWriterIsJournald

func LogWriterIsJournald(outputFd int) bool

LogWriterIsJournald: 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));.

The function takes the following parameters:

  • outputFd: output file descriptor to check.

The function returns the following values:

  • ok: TRUE if output_fd points to the journal, FALSE otherwise.

func LogWriterSupportsColor

func LogWriterSupportsColor(outputFd int) bool

LogWriterSupportsColor: check whether the given output_fd file descriptor supports ANSI color escape sequences. If so, they can safely be used when formatting log messages.

The function takes the following parameters:

  • outputFd: output file descriptor to check.

The function returns the following values:

  • ok: TRUE if ANSI color escapes are supported, FALSE otherwise.

func MainDepth

func MainDepth() int

MainDepth returns the depth of the stack of calls to g_main_context_dispatch() on any Context in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback from g_main_context_iteration() (or g_main_loop_run(), etc.) it returns 1. When called from within a callback to a recursive call to g_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.

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 g_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 g_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 gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.

2. 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.

The function returns the following values:

  • gint: main loop recursion level in the current thread.

func MarkupEscapeText

func MarkupEscapeText(text string, length int) string

MarkupEscapeText 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.

The function takes the following parameters:

  • text: some valid UTF-8 text.
  • length of text in bytes, or -1 if the text is nul-terminated.

The function returns the following values:

  • utf8: newly allocated string with the escaped text.

func MkdirWithParents

func MkdirWithParents(pathname string, mode int) int

MkdirWithParents: create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.

The function takes the following parameters:

  • pathname in the GLib file name encoding.
  • mode permissions to use for newly created directories.

The function returns the following values:

  • gint: 0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.

func NewVariantValue

func NewVariantValue(variant *Variant) *coreglib.Value

NewVariantValue creates a new GValue from a GVariant. This function only exists as a workaround for coreglib's cyclical imports. It be removed in the future once coreglib is merged in.

func ObjectEq

func ObjectEq(obj1 Objector, obj2 Objector) bool

ObjectEq is an alias for pkg/core/glib.ObjectEq.

func ParseDebugString

func ParseDebugString(str string, keys []DebugKey) uint

ParseDebugString parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

If string is equal to "all", all flags are set. Any flags specified along with "all" in string are inverted; thus, "all,foo,bar" or "foo,bar,all" sets all flags except those corresponding to "foo" and "bar".

If string is equal to "help", all the available keys in keys are printed out to standard error.

The function takes the following parameters:

  • str (optional): list of debug options separated by colons, spaces, or commas, or NULL.
  • keys: pointer to an array of Key which associate strings with bit flags.

The function returns the following values:

  • guint: combined set of bit flags.

func PathGetBasename

func PathGetBasename(fileName string) string

PathGetBasename 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 ".".

The function takes the following parameters:

  • fileName: name of the file.

The function returns the following values:

  • filename: newly allocated string containing the last component of the filename.

func PathGetDirname

func PathGetDirname(fileName string) string

PathGetDirname 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.

The function takes the following parameters:

  • fileName: name of the file.

The function returns the following values:

  • filename: directory components of the file.

func PathIsAbsolute

func PathIsAbsolute(fileName string) bool

PathIsAbsolute returns TRUE 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 g_get_current_dir() either. Such paths should be avoided, or need to be handled using Windows-specific code.

The function takes the following parameters:

  • fileName: file name.

The function returns the following values:

  • ok: TRUE if file_name is absolute.

func PathSkipRoot

func PathSkipRoot(fileName string) string

PathSkipRoot 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 NULL.

The function takes the following parameters:

  • fileName: file name.

The function returns the following values:

  • filename (optional): pointer into file_name after the root component.

func PatternMatchSimple

func PatternMatchSimple(pattern, str string) bool

PatternMatchSimple 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 g_pattern_spec_new() and call g_pattern_match_string() repeatedly.

The function takes the following parameters:

  • pattern: UTF-8 encoded pattern.
  • str: UTF-8 encoded string to match.

The function returns the following values:

  • ok: TRUE if string matches pspec.

func QuarkToString

func QuarkToString(quark Quark) string

QuarkToString gets the string associated with the given #GQuark.

The function takes the following parameters:

  • quark: #GQuark.

The function returns the following values:

  • utf8: string associated with the #GQuark.

func RandomDouble

func RandomDouble() float64

RandomDouble returns a random #gdouble equally distributed over the range [0..1).

The function returns the following values:

  • gdouble: random number.

func RandomDoubleRange

func RandomDoubleRange(begin, end float64) float64

RandomDoubleRange returns a random #gdouble equally distributed over the range [begin..end).

The function takes the following parameters:

  • begin: lower closed bound of the interval.
  • end: upper open bound of the interval.

The function returns the following values:

  • gdouble: random number.

func RandomInt

func RandomInt() uint32

RandomInt: return a random #guint32 equally distributed over the range [0..2^32-1].

The function returns the following values:

  • guint32: random number.

func RandomIntRange

func RandomIntRange(begin, end int32) int32

RandomIntRange returns a random #gint32 equally distributed over the range [begin..end-1].

The function takes the following parameters:

  • begin: lower closed bound of the interval.
  • end: upper open bound of the interval.

The function returns the following values:

  • gint32: random number.

func RandomSetSeed

func RandomSetSeed(seed uint32)

RandomSetSeed sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

The function takes the following parameters:

  • seed: value to reinitialize the global random number generator.

func RegexCheckReplacement

func RegexCheckReplacement(replacement string) (bool, error)

RegexCheckReplacement checks whether replacement is a valid replacement string (see g_regex_replace()), i.e. that all escape sequences in it are valid.

If has_references is not NULL 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 Info object.

The function takes the following parameters:

  • replacement string.

The function returns the following values:

  • hasReferences (optional): location to store information about references in replacement or NULL.

func RegexEscapeNUL

func RegexEscapeNUL(str string, length int) string

RegexEscapeNUL 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.

The function takes the following parameters:

  • str: string to escape.
  • length of string.

The function returns the following values:

  • utf8: newly-allocated escaped string.

func RegexMatchSimple

func RegexMatchSimple(pattern, str string, compileOptions RegexCompileFlags, matchOptions RegexMatchFlags) bool

RegexMatchSimple scans for a match in string for pattern.

This function is equivalent to g_regex_match() but it does not require to compile the pattern with g_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 g_regex_new() and then use g_regex_match().

The function takes the following parameters:

  • pattern: regular expression.
  • str: string to scan for matches.
  • compileOptions: compile options for the regular expression, or 0.
  • matchOptions: match options, or 0.

The function returns the following values:

  • ok: TRUE if the string matched, FALSE otherwise.

func RegexSplitSimple

func RegexSplitSimple(pattern, str string, compileOptions RegexCompileFlags, matchOptions RegexMatchFlags) []string

RegexSplitSimple 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 g_regex_split() but it does not require to compile the pattern with g_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 g_regex_new() and then use g_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".

The function takes the following parameters:

  • pattern: regular expression.
  • str: string to scan for matches.
  • compileOptions: compile options for the regular expression, or 0.
  • matchOptions: match options, or 0.

The function returns the following values:

  • utf8s: NULL-terminated array of strings. Free it using g_strfreev().

func ReloadUserSpecialDirsCache

func ReloadUserSpecialDirsCache()

ReloadUserSpecialDirsCache resets the cache used for g_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 g_get_user_special_dir() that can't be freed. We ensure to only leak the data for the directories that actually changed value though.

func SetApplicationName

func SetApplicationName(applicationName string)

SetApplicationName 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 g_set_prgname(), which sets a non-localized name. g_set_prgname() will be called automatically by gtk_init(), but g_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.

The function takes the following parameters:

  • applicationName: localized name of the application.

func SetPrgname

func SetPrgname(prgname string)

SetPrgname sets the name of the program. This name should not be localized, in contrast to g_set_application_name().

If you are using #GApplication the program name is set in g_application_run(). In case of GDK or GTK+ it is set in gdk_init(), which is called by gtk_init() and the Application::startup handler. The program name is found by taking the last component of argv[0].

Note that for thread-safety reasons this function can only be called once.

The function takes the following parameters:

  • prgname: name of the program.

func Setenv

func Setenv(variable, value string, overwrite bool) bool

Setenv 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 g_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 g_get_environ() to get an environment array, modify that with g_environ_setenv() and g_environ_unsetenv(), and then pass that array directly to execvpe(), g_spawn_async(), or the like.

The function takes the following parameters:

  • variable: environment variable to set, must not contain '='.
  • value for to set the variable to.
  • overwrite: whether to change the variable if it already exists.

The function returns the following values:

  • ok: FALSE if the environment variable couldn't be set.

func ShellParseArgv

func ShellParseArgv(commandLine string) ([]string, error)

ShellParseArgv 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 SHELL_ERROR domain. Free the returned vector with g_strfreev().

The function takes the following parameters:

  • commandLine: command line to parse.

The function returns the following values:

  • argvp (optional): return location for array of args.

func ShellQuote

func ShellQuote(unquotedString string) string

ShellQuote 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 g_free(). The quoting style used is undefined (single or double quotes may be used).

The function takes the following parameters:

  • unquotedString: literal string.

The function returns the following values:

  • filename: quoted string.

func ShellUnquote

func ShellUnquote(quotedString string) (string, error)

ShellUnquote unquotes a string as the shell (/bin/sh) would. 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 g_shell_quote(). If it fails, it returns NULL and sets the error. The quoted_string need not actually contain quoted or escaped text; g_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 g_free(). Possible errors are in the 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.

The function takes the following parameters:

  • quotedString: shell-quoted string.

The function returns the following values:

  • filename: unquoted string.

func SourceRemove

func SourceRemove(src SourceHandle) bool

SourceRemove is an alias for pkg/core/glib.SourceRemove.

func SourceRemoveByFuncsUserData

func SourceRemoveByFuncsUserData(funcs *SourceFuncs, userData unsafe.Pointer) bool

SourceRemoveByFuncsUserData removes a source from the default main loop context given the source functions and user data. If multiple sources exist with the same source functions and user data, only one will be destroyed.

The function takes the following parameters:

  • funcs passed to g_source_new().
  • userData (optional): user data for the callback.

The function returns the following values:

  • ok: TRUE if a source was found and removed.

func SourceRemoveByUserData

func SourceRemoveByUserData(userData unsafe.Pointer) bool

SourceRemoveByUserData 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.

The function takes the following parameters:

  • userData (optional): user_data for the callback.

The function returns the following values:

  • ok: TRUE if a source was found and removed.

func SourceSetNameByID

func SourceSetNameByID(tag uint, name string)

SourceSetNameByID sets the name of a source using its ID.

This is a convenience utility to set source names from the return value of g_idle_add(), g_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 g_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.

The function takes the following parameters:

  • tag: #GSource ID.
  • name: debug name for the source.

func SpacedPrimesClosest

func SpacedPrimesClosest(num uint) uint

SpacedPrimesClosest 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 Table.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

The function takes the following parameters:

  • num: #guint.

The function returns the following values:

  • guint: smallest prime number from a built-in array of primes which is larger than num.

func SpawnCheckExitStatus

func SpawnCheckExitStatus(exitStatus int) error

SpawnCheckExitStatus: set error if exit_status indicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal).

The g_spawn_sync() and g_child_watch_add() family of APIs return an exit status for 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 exit_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 exit 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 exit_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, the domain will be G_SPAWN_ERROR, and the code will be G_SPAWN_ERROR_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 exit_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.

The function takes the following parameters:

  • exitStatus: exit code as returned from g_spawn_sync().

func SpawnCommandLineAsync

func SpawnCommandLineAsync(commandLine string) error

SpawnCommandLineAsync: simple version of g_spawn_async() that parses a command line with g_shell_parse_argv() and passes it to g_spawn_async(). Runs a command line in the background. Unlike g_spawn_async(), the G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note that G_SPAWN_SEARCH_PATH can have security implications, so consider using g_spawn_async() directly if appropriate. Possible errors are those from g_shell_parse_argv() and g_spawn_async().

The same concerns on Windows apply as for g_spawn_command_line_sync().

The function takes the following parameters:

  • commandLine: command line.

func SpawnCommandLineSync

func SpawnCommandLineSync(commandLine string) (standardOutput, standardError []byte, exitStatus int, goerr error)

SpawnCommandLineSync: simple version of g_spawn_sync() with little-used parameters removed, taking a command line instead of an argument vector. See g_spawn_sync() for full details. command_line will be parsed by g_shell_parse_argv(). Unlike g_spawn_sync(), the G_SPAWN_SEARCH_PATH flag is enabled. Note that G_SPAWN_SEARCH_PATH can have security implications, so consider using g_spawn_sync() directly if appropriate. Possible errors are those from g_spawn_sync() and those from g_shell_parse_argv().

If exit_status is non-NULL, the platform-specific exit status of the child is stored there; see the documentation of g_spawn_check_exit_status() for how to use and interpret this.

On Windows, please note the implications of g_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'".

The function takes the following parameters:

  • commandLine: command line.

The function returns the following values:

  • standardOutput (optional): return location for child output.
  • standardError (optional): return location for child errors.
  • exitStatus (optional): return location for child exit status, as returned by waitpid().

func SpawnSync

func SpawnSync(workingDirectory string, argv, envp []string, flags SpawnFlags, childSetup SpawnChildSetupFunc) (standardOutput, standardError []byte, exitStatus int, goerr error)

SpawnSync 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-NULL. Note that you must set the G_SPAWN_STDOUT_TO_DEV_NULL and G_SPAWN_STDERR_TO_DEV_NULL flags when passing NULL for standard_output and standard_error.

If exit_status is non-NULL, the platform-specific exit status of the child is stored there; see the documentation of g_spawn_check_exit_status() for how to use and interpret this. Note that it is invalid to pass G_SPAWN_DO_NOT_REAP_CHILD in flags, and on POSIX platforms, the same restrictions as for g_child_watch_source_new() apply.

If an error occurs, no data is returned in standard_output, standard_error, or exit_status.

This function calls g_spawn_async_with_pipes() internally; see that function for full details on the other parameters and details on how these functions work on Windows.

The function takes the following parameters:

  • workingDirectory (optional) child's current working directory, or NULL to inherit parent's.
  • argv: child's argument vector.
  • envp (optional): child's environment, or NULL to inherit parent's.
  • flags from Flags.
  • childSetup (optional): function to run in the child just before exec().

The function returns the following values:

  • standardOutput (optional): return location for child output, or NULL.
  • standardError (optional): return location for child error messages, or NULL.
  • exitStatus (optional): return location for child exit status, as returned by waitpid(), or NULL.

func StrEqual

func StrEqual(v1, v2 unsafe.Pointer) bool

StrEqual compares two strings for byte-by-byte equality and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-NULL strings as keys in a Table.

This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-NULL strings. For a NULL-safe string comparison function, see g_strcmp0().

The function takes the following parameters:

  • v1: key.
  • v2: key to compare with v1.

The function returns the following values:

  • ok: TRUE if the two keys match.

func StrHash

func StrHash(v unsafe.Pointer) uint

StrHash 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-NULL strings as keys in a Table.

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.

The function takes the following parameters:

  • v: string key.

The function returns the following values:

  • guint: hash value corresponding to the key.

func StripContext

func StripContext(msgid, msgval string) string

StripContext: auxiliary function for gettext() support (see Q_()).

The function takes the following parameters:

  • msgid: string.
  • msgval: another string.

The function returns the following values:

  • utf8: 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.

func StrvGetType

func StrvGetType() coreglib.Type

The function returns the following values:

func TestFile

func TestFile(filename string, test FileTest) bool

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

Apart from G_FILE_TEST_IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will return TRUE for both G_FILE_TEST_IS_SYMLINK and G_FILE_TEST_IS_REGULAR.

Note, that for a dangling symbolic link g_file_test() will return TRUE for G_FILE_TEST_IS_SYMLINK and FALSE for all other flags.

You should never use g_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. For example, you might think you could use G_FILE_TEST_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
  }

Another thing to note is that G_FILE_TEST_EXISTS and G_FILE_TEST_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 G_FILE_TEST_IS_SYMLINK will always return FALSE. Testing for G_FILE_TEST_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.

This type has been renamed from file_test.

The function takes the following parameters:

  • filename to test in the GLib file name encoding.
  • test: bitfield of Test flags.

The function returns the following values:

  • ok: whether a test was TRUE.

func UCS4ToUTF16

func UCS4ToUTF16(str *uint32, len int32) (itemsRead, itemsWritten int32, guint16 *uint16, goerr error)

UCS4ToUTF16: convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.

The function takes the following parameters:

  • str: UCS-4 encoded string.
  • len: maximum length (number of characters) of str to use. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsRead (optional): location to store number of bytes read, or NULL. If an error occurs then the index of the invalid input is stored here.
  • itemsWritten (optional): location to store number of #gunichar2 written, or NULL. The value stored here does not include the trailing 0.
  • guint16: pointer to a newly allocated UTF-16 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

func UCS4ToUTF8

func UCS4ToUTF8(str *uint32, len int32) (itemsRead, itemsWritten int32, utf8 string, goerr error)

UCS4ToUTF8: convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8. The result will be terminated with a 0 byte.

The function takes the following parameters:

  • str: UCS-4 encoded string.
  • len: maximum length (number of characters) of str to use. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsRead (optional): location to store number of characters read, or NULL.
  • itemsWritten (optional): location to store number of bytes written or NULL. The value here stored does not include the trailing 0 byte.
  • utf8: pointer to a newly allocated UTF-8 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set. In that case, items_read will be set to the position of the first invalid input character.

func URIEscapeBytes

func URIEscapeBytes(unescaped []byte, reservedCharsAllowed string) string

URIEscapeBytes 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.

The function takes the following parameters:

  • unescaped input data.
  • reservedCharsAllowed (optional): string of reserved characters that are allowed to be used, or NULL.

The function returns the following values:

  • utf8: escaped version of unescaped. The returned string should be freed when no longer needed.

func URIEscapeString

func URIEscapeString(unescaped, reservedCharsAllowed string, allowUtf8 bool) string

URIEscapeString 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.

The function takes the following parameters:

  • unescaped input string.
  • reservedCharsAllowed (optional): string of reserved characters that are allowed to be used, or NULL.
  • allowUtf8: TRUE if the result can include UTF-8 characters.

The function returns the following values:

  • utf8: escaped version of unescaped. The returned string should be freed when no longer needed.

func URIIsValid

func URIIsValid(uriString string, flags URIFlags) error

URIIsValid parses uri_string according to flags, to determine whether it is a valid [absolute URI][relative-absolute-uris], i.e. it does not need to be resolved relative to another URI using g_uri_parse_relative().

If it’s not a valid URI, an error is returned explaining how it’s invalid.

See g_uri_split(), and the definition of Flags, for more information on the effect of flags.

The function takes the following parameters:

  • uriString: string containing an absolute URI.
  • flags for parsing uri_string.

func URIJoin

func URIJoin(flags URIFlags, scheme, userinfo, host string, port int, path, query, fragment string) string

URIJoin joins the given components together according to flags to create an absolute URI string. path may not be NULL (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 RFC 3986, section 3 (https://tools.ietf.org/html/rfc3986#section-3).

See also g_uri_join_with_user(), which allows specifying the components of the ‘userinfo’ separately.

G_URI_FLAGS_HAS_PASSWORD and G_URI_FLAGS_HAS_AUTH_PARAMS are ignored if set in flags.

The function takes the following parameters:

  • flags describing how to build the URI string.
  • scheme (optional): URI scheme, or NULL.
  • userinfo (optional) component, or NULL.
  • host (optional) component, or NULL.
  • port: port, or -1.
  • path component.
  • query (optional) component, or NULL.
  • fragment (optional): fragment, or NULL.

The function returns the following values:

  • utf8: absolute URI string.

func URIJoinWithUser

func URIJoinWithUser(flags URIFlags, scheme, user, password, authParams, host string, port int, path, query, fragment string) string

URIJoinWithUser joins the given components together according to flags to create an absolute URI string. path may not be NULL (though it may be the empty string).

In contrast to g_uri_join(), this allows specifying the components of the ‘userinfo’ separately. It otherwise behaves the same.

G_URI_FLAGS_HAS_PASSWORD and G_URI_FLAGS_HAS_AUTH_PARAMS are ignored if set in flags.

The function takes the following parameters:

  • flags describing how to build the URI string.
  • scheme (optional): URI scheme, or NULL.
  • user (optional) component of the userinfo, or NULL.
  • password (optional) component of the userinfo, or NULL.
  • authParams (optional): auth params of the userinfo, or NULL.
  • host (optional) component, or NULL.
  • port: port, or -1.
  • path component.
  • query (optional) component, or NULL.
  • fragment (optional): fragment, or NULL.

The function returns the following values:

  • utf8: absolute URI string.

func URIListExtractURIs

func URIListExtractURIs(uriList string) []string

URIListExtractURIs 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.

The function takes the following parameters:

  • uriList: URI list.

The function returns the following values:

  • utf8s: newly allocated NULL-terminated list of strings holding the individual URIs. The array should be freed with g_strfreev().

func URIParseParams

func URIParseParams(params string, length int, separators string, flags URIParamsFlags) (map[string]string, error)

URIParseParams: 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 ParamsIter.

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 G_URI_FLAGS_PARSE_RELAXED rules for g_uri_parse(). (However, if params is the path or query string from a #GUri that was parsed without G_URI_FLAGS_PARSE_RELAXED and G_URI_FLAGS_ENCODED, then you already know that it does not contain any invalid encoding.)

G_URI_PARAMS_WWW_FORM is handled as documented for g_uri_params_iter_init().

If G_URI_PARAMS_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 NULL is returned.

The function takes the following parameters:

  • params: %-encoded string containing attribute=value parameters.
  • length of params, or -1 if it is nul-terminated.
  • separators: 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 to modify the way the parameters are handled.

The function returns the following values:

  • hashTable: A hash table of attribute/value pairs, with both names and values fully-decoded; or NULL on error.

func URIParseScheme

func URIParseScheme(uri string) string

URIParseScheme gets the scheme portion of a URI string. RFC 3986 (https://tools.ietf.org/html/rfc3986#section-3) decodes the scheme as:

URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

Common schemes include file, https, svn+ssh, etc.

The function takes the following parameters:

  • uri: valid URI.

The function returns the following values:

  • utf8 (optional): ‘scheme’ component of the URI, or NULL on error. The returned string should be freed when no longer needed.

func URIPeekScheme

func URIPeekScheme(uri string) string

URIPeekScheme gets the scheme portion of a URI string. RFC 3986 (https://tools.ietf.org/html/rfc3986#section-3) decodes the scheme as:

URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

Common schemes include file, https, svn+ssh, etc.

Unlike g_uri_parse_scheme(), the returned scheme is normalized to all-lowercase and does not need to be freed.

The function takes the following parameters:

  • uri: valid URI.

The function returns the following values:

  • utf8 (optional): ‘scheme’ component of the URI, or NULL on error. The returned string is normalized to all-lowercase, and interned via g_intern_string(), so it does not need to be freed.

func URIResolveRelative

func URIResolveRelative(baseUriString, uriRef string, flags URIFlags) (string, error)

URIResolveRelative parses uri_ref according to flags and, if it is a [relative URI][relative-absolute-uris], 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 NULL, this just returns uri_ref, or NULL if uri_ref is invalid or not absolute.).

The function takes the following parameters:

  • baseUriString (optional): string representing a base URI.
  • uriRef: string representing a relative or absolute URI.
  • flags describing how to parse uri_ref.

The function returns the following values:

  • utf8: resolved URI string, or NULL on error.

func URISplit

func URISplit(uriRef string, flags URIFlags) (scheme, userinfo, host string, port int, path, query, fragment string, goerr error)

URISplit parses uri_ref (which can be an [absolute or relative URI][relative-absolute-uris]) according to flags, and returns the pieces. Any component that doesn't appear in uri_ref will be returned as NULL (but note that all URIs always have a path component, though it may be the empty string).

If flags contains G_URI_FLAGS_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 G_URI_FLAGS_ENCODED if they are not.

Note that the G_URI_FLAGS_HAS_PASSWORD and G_URI_FLAGS_HAS_AUTH_PARAMS flags are ignored by g_uri_split(), since it always returns only the full userinfo; use g_uri_split_with_user() if you want it split up.

The function takes the following parameters:

  • uriRef: string containing a relative or absolute URI.
  • flags for parsing uri_ref.

The function returns the following values:

  • scheme (optional): on return, contains the scheme (converted to lowercase), or NULL.
  • userinfo (optional): on return, contains the userinfo, or NULL.
  • host (optional): on return, contains the host, or NULL.
  • port (optional): on return, contains the port, or -1.
  • path (optional): on return, contains the path.
  • query (optional): on return, contains the query, or NULL.
  • fragment (optional): on return, contains the fragment, or NULL.

func URISplitNetwork

func URISplitNetwork(uriString string, flags URIFlags) (scheme, host string, port int, goerr error)

URISplitNetwork parses uri_string (which must be an [absolute URI][relative-absolute-uris]) according to flags, and returns the pieces relevant to connecting to a host. See the documentation for g_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.

The function takes the following parameters:

  • uriString: string containing an absolute URI.
  • flags for parsing uri_string.

The function returns the following values:

  • scheme (optional): on return, contains the scheme (converted to lowercase), or NULL.
  • host (optional): on return, contains the host, or NULL.
  • port (optional): on return, contains the port, or -1.

func URISplitWithUser

func URISplitWithUser(uriRef string, flags URIFlags) (scheme, user, password, authParams, host string, port int, path, query, fragment string, goerr error)

URISplitWithUser parses uri_ref (which can be an [absolute or relative URI][relative-absolute-uris]) according to flags, and returns the pieces. Any component that doesn't appear in uri_ref will be returned as NULL (but note that all URIs always have a path component, though it may be the empty string).

See g_uri_split(), and the definition of Flags, for more information on the effect of flags. Note that password will only be parsed out if flags contains G_URI_FLAGS_HAS_PASSWORD, and auth_params will only be parsed out if flags contains G_URI_FLAGS_HAS_AUTH_PARAMS.

The function takes the following parameters:

  • uriRef: string containing a relative or absolute URI.
  • flags for parsing uri_ref.

The function returns the following values:

  • scheme (optional): on return, contains the scheme (converted to lowercase), or NULL.
  • user (optional): on return, contains the user, or NULL.
  • password (optional): on return, contains the password, or NULL.
  • authParams (optional): on return, contains the auth_params, or NULL.
  • host (optional): on return, contains the host, or NULL.
  • port (optional): on return, contains the port, or -1.
  • path (optional): on return, contains the path.
  • query (optional): on return, contains the query, or NULL.
  • fragment (optional): on return, contains the fragment, or NULL.

func URIUnescapeSegment

func URIUnescapeSegment(escapedString, escapedStringEnd, illegalCharacters string) string

URIUnescapeSegment 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 NULL 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 g_uri_unescape_bytes().

The function takes the following parameters:

  • escapedString (optional): string, may be NULL.
  • escapedStringEnd (optional): pointer to end of escaped_string, may be NULL.
  • illegalCharacters (optional): optional string of illegal characters not to be allowed, may be NULL.

The function returns the following values:

  • utf8 (optional): unescaped version of escaped_string, or NULL on error. The returned string should be freed when no longer needed. As a special case if NULL is given for escaped_string, this function will return NULL.

func URIUnescapeString

func URIUnescapeString(escapedString, illegalCharacters string) string

URIUnescapeString 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 NULL 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.

The function takes the following parameters:

  • escapedString: escaped string to be unescaped.
  • illegalCharacters (optional): string of illegal characters not to be allowed, or NULL.

The function returns the following values:

  • utf8 (optional): unescaped version of escaped_string. The returned string should be freed when no longer needed.

func UTF16ToUCS4

func UTF16ToUCS4(str *uint16, len int32) (itemsRead, itemsWritten int32, gunichar *uint32, goerr error)

UTF16ToUCS4: convert a string from UTF-16 to UCS-4. The result will be nul-terminated.

The function takes the following parameters:

  • str: UTF-16 encoded string.
  • len: maximum length (number of #gunichar2) of str to use. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsRead (optional): location to store number of words read, or NULL. If NULL, then G_CONVERT_ERROR_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.
  • itemsWritten (optional): location to store number of characters written, or NULL. The value stored here does not include the trailing 0 character.
  • gunichar: pointer to a newly allocated UCS-4 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

func UTF16ToUTF8

func UTF16ToUTF8(str *uint16, len int32) (itemsRead, itemsWritten int32, utf8 string, goerr error)

UTF16ToUTF8: convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.

Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. g_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 e.g. 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.

The function takes the following parameters:

  • str: UTF-16 encoded string.
  • len: maximum length (number of #gunichar2) of str to use. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsRead (optional): location to store number of words read, or NULL. If NULL, then G_CONVERT_ERROR_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.
  • itemsWritten (optional): location to store number of bytes written, or NULL. The value stored here does not include the trailing 0 byte.
  • utf8: pointer to a newly allocated UTF-8 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

func UTF8Casefold

func UTF8Casefold(str string, len int) string

UTF8Casefold 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 g_utf8_casefold() on other strings.

Note that calling g_utf8_casefold() followed by g_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.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: length of str, in bytes, or -1 if str is nul-terminated.

The function returns the following values:

  • utf8: newly allocated string, that is a case independent form of str.

func UTF8Collate

func UTF8Collate(str1, str2 string) int

UTF8Collate compares two strings for ordering using the linguistically correct rules for the [current locale][setlocale]. When sorting a large number of strings, it will be significantly faster to obtain collation keys with g_utf8_collate_key() and compare the keys with strcmp() when sorting instead of sorting the original strings.

The function takes the following parameters:

  • str1: UTF-8 encoded string.
  • str2: UTF-8 encoded string.

The function returns the following values:

  • gint: < 0 if str1 compares before str2, 0 if they compare equal, > 0 if str1 compares after str2.

func UTF8CollateKey

func UTF8CollateKey(str string, len int) string

UTF8CollateKey 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 g_utf8_collate().

Note that this function depends on the [current locale][setlocale].

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: length of str, in bytes, or -1 if str is nul-terminated.

The function returns the following values:

  • utf8: newly allocated string. This string should be freed with g_free() when you are done with it.

func UTF8CollateKeyForFilename

func UTF8CollateKeyForFilename(str string, len int) string

UTF8CollateKeyForFilename 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][setlocale].

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: length of str, in bytes, or -1 if str is nul-terminated.

The function returns the following values:

  • utf8: newly allocated string. This string should be freed with g_free() when you are done with it.

func UTF8FindNextChar

func UTF8FindNextChar(p, end string) string

UTF8FindNextChar 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.

The function takes the following parameters:

  • p: pointer to a position within a UTF-8 encoded string.
  • end (optional): pointer to the byte following the end of the string, or NULL to indicate that the string is nul-terminated.

The function returns the following values:

  • utf8 (optional): pointer to the found character or NULL if end is set and is reached.

func UTF8FindPrevChar

func UTF8FindPrevChar(str, p string) string

UTF8FindPrevChar: 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.

The function takes the following parameters:

  • str: pointer to the beginning of a UTF-8 encoded string.
  • p: pointer to some position within str.

The function returns the following values:

  • utf8 (optional): pointer to the found character or NULL.

func UTF8GetChar

func UTF8GetChar(p string) uint32

UTF8GetChar 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 g_utf8_get_char_validated() instead.

The function takes the following parameters:

  • p: pointer to Unicode character encoded as UTF-8.

The function returns the following values:

  • gunichar: resulting character.

func UTF8GetCharValidated

func UTF8GetCharValidated(p string, maxLen int) uint32

UTF8GetCharValidated: 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 g_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.

The function takes the following parameters:

  • p: pointer to Unicode character encoded as UTF-8.
  • maxLen: maximum number of bytes to read, or -1 if p is nul-terminated.

The function returns the following values:

  • gunichar: 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.

func UTF8MakeValid

func UTF8MakeValid(str string, len int) string

UTF8MakeValid: 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.

The function takes the following parameters:

  • str: string to coerce into UTF-8.
  • len: maximum length of str to use, in bytes. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • utf8: valid UTF-8 string whose content resembles str.

func UTF8Normalize

func UTF8Normalize(str string, len int, mode NormalizeMode) string

UTF8Normalize 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 NULL is returned. You should generally call g_utf8_normalize() before comparing two Unicode strings.

The normalization mode G_NORMALIZE_DEFAULT only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. G_NORMALIZE_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.

G_NORMALIZE_DEFAULT_COMPOSE and G_NORMALIZE_ALL_COMPOSE are like G_NORMALIZE_DEFAULT and G_NORMALIZE_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.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: length of str, in bytes, or -1 if str is nul-terminated.
  • mode: type of normalization to perform.

The function returns the following values:

  • utf8 (optional): newly allocated string, that is the normalized form of str, or NULL if str is not valid UTF-8.

func UTF8OffsetToPointer

func UTF8OffsetToPointer(str string, offset int32) string

UTF8OffsetToPointer 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 g_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.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • offset: character offset within str.

The function returns the following values:

  • utf8: resulting pointer.

func UTF8PointerToOffset

func UTF8PointerToOffset(str, pos string) int32

UTF8PointerToOffset 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.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • pos: pointer to a position within str.

The function returns the following values:

  • glong: resulting character offset.

func UTF8PrevChar

func UTF8PrevChar(p string) string

UTF8PrevChar 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 g_utf8_find_prev_char() instead.

The function takes the following parameters:

  • p: pointer to a position within a UTF-8 encoded string.

The function returns the following values:

  • utf8: pointer to the found character.

func UTF8Strchr

func UTF8Strchr(p string, len int, c uint32) string

UTF8Strchr 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.

The function takes the following parameters:

  • p: nul-terminated UTF-8 encoded string.
  • len: maximum length of p.
  • c: unicode character.

The function returns the following values:

  • utf8 (optional): 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.

func UTF8Strdown

func UTF8Strdown(str string, len int) string

UTF8Strdown 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.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: length of str, in bytes, or -1 if str is nul-terminated.

The function returns the following values:

  • utf8: newly allocated string, with all characters converted to lowercase.

func UTF8Strlen

func UTF8Strlen(p string, max int) int32

UTF8Strlen 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.

The function takes the following parameters:

  • p: pointer to the start of a UTF-8 encoded string.
  • max: 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.

The function returns the following values:

  • glong: length of the string in characters.

func UTF8Strncpy

func UTF8Strncpy(dest, src string, n uint) string

UTF8Strncpy: 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 g_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 to fit the largest possible UTF-8 characters.

The function takes the following parameters:

  • dest: buffer to fill with characters from src.
  • src: UTF-8 encoded string.
  • n: character count.

The function returns the following values:

  • utf8: dest.

func UTF8Strrchr

func UTF8Strrchr(p string, len int, c uint32) string

UTF8Strrchr: 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.

The function takes the following parameters:

  • p: nul-terminated UTF-8 encoded string.
  • len: maximum length of p.
  • c: unicode character.

The function returns the following values:

  • utf8 (optional): 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.

func UTF8Strreverse

func UTF8Strreverse(str string, len int) string

UTF8Strreverse reverses a UTF-8 string. str must be valid UTF-8 encoded text. (Use g_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 g_strreverse(), this function returns newly-allocated memory, which should be freed with g_free() when no longer needed.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: maximum length of str to use, in bytes. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • utf8: newly-allocated string which is the reverse of str.

func UTF8Strup

func UTF8Strup(str string, len int) string

UTF8Strup 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.).

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: length of str, in bytes, or -1 if str is nul-terminated.

The function returns the following values:

  • utf8: newly allocated string, with all characters converted to uppercase.

func UTF8Substring

func UTF8Substring(str string, startPos, endPos int32) string

UTF8Substring copies a substring out of a UTF-8 encoded string. The substring will contain end_pos - start_pos characters.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • startPos: character offset within str.
  • endPos: another character offset within str.

The function returns the following values:

  • utf8: newly allocated copy of the requested substring. Free with g_free() when no longer needed.

func UTF8ToUCS4

func UTF8ToUCS4(str string, len int32) (itemsRead, itemsWritten int32, gunichar *uint32, goerr error)

UTF8ToUCS4: convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 character will be added to the string after the converted text.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: maximum length of str to use, in bytes. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsRead (optional): location to store number of bytes read, or NULL. If NULL, then G_CONVERT_ERROR_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.
  • itemsWritten (optional): location to store number of characters written or NULL. The value here stored does not include the trailing 0 character.
  • gunichar: pointer to a newly allocated UCS-4 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

func UTF8ToUCS4Fast

func UTF8ToUCS4Fast(str string, len int32) (int32, *uint32)

UTF8ToUCS4Fast: 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 g_utf8_to_ucs4() but does no error checking on the input. A trailing 0 character will be added to the string after the converted text.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: maximum length of str to use, in bytes. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsWritten (optional): location to store the number of characters in the result, or NULL.
  • gunichar: pointer to a newly allocated UCS-4 string. This value must be freed with g_free().

func UTF8ToUTF16

func UTF8ToUTF16(str string, len int32) (itemsRead, itemsWritten int32, guint16 *uint16, goerr error)

UTF8ToUTF16: convert a string from UTF-8 to UTF-16. A 0 character will be added to the result after the converted text.

The function takes the following parameters:

  • str: UTF-8 encoded string.
  • len: maximum length (number of bytes) of str to use. If len < 0, then the string is nul-terminated.

The function returns the following values:

  • itemsRead (optional): location to store number of bytes read, or NULL. If NULL, then G_CONVERT_ERROR_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.
  • itemsWritten (optional): location to store number of #gunichar2 written, or NULL. The value stored here does not include the trailing 0.
  • guint16: pointer to a newly allocated UTF-16 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

func UTF8Validate

func UTF8Validate(str string) (string, bool)

UTF8Validate 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 (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).

Note that g_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 g_utf8_validate() before doing anything else with it.

The function takes the following parameters:

  • str: pointer to character data.

The function returns the following values:

  • end (optional): return location for end of valid data.
  • ok: TRUE if the text was valid UTF-8.

func UTF8ValidateLen

func UTF8ValidateLen(str string) (string, bool)

UTF8ValidateLen validates UTF-8 encoded text.

As with g_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.

The function takes the following parameters:

  • str: pointer to character data.

The function returns the following values:

  • end (optional): return location for end of valid data.
  • ok: TRUE if the text was valid UTF-8.

func UUIDStringIsValid

func UUIDStringIsValid(str string) bool

UUIDStringIsValid 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.

The function takes the following parameters:

  • str: string representing a UUID.

The function returns the following values:

  • ok: TRUE if str is a valid UUID, FALSE otherwise.

func UUIDStringRandom

func UUIDStringRandom() string

UUIDStringRandom 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.

The function returns the following values:

  • utf8: string that should be freed with g_free().

func UnicharCombiningClass

func UnicharCombiningClass(uc uint32) int

UnicharCombiningClass determines the canonical combining class of a Unicode character.

The function takes the following parameters:

  • uc: unicode character.

The function returns the following values:

  • gint: combining class of the character.

func UnicharCompose

func UnicharCompose(a, b uint32) (uint32, bool)

UnicharCompose 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 g_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 (http://unicode.org/reports/tr15/) for details.

The function takes the following parameters:

  • a: unicode character.
  • b: unicode character.

The function returns the following values:

  • ch: return location for the composed character.
  • ok: TRUE if the characters could be composed.

func UnicharDecompose

func UnicharDecompose(ch uint32) (a, b uint32, ok bool)

UnicharDecompose 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 g_unichar_fully_decompose().

See UAX#15 (http://unicode.org/reports/tr15/) for details.

The function takes the following parameters:

  • ch: unicode character.

The function returns the following values:

  • a: return location for the first component of ch.
  • b: return location for the second component of ch.
  • ok: TRUE if the character could be decomposed.

func UnicharDigitValue

func UnicharDigitValue(c uint32) int

UnicharDigitValue determines the numeric value of a character as a decimal digit.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • gint: if c is a decimal digit (according to g_unichar_isdigit()), its numeric value. Otherwise, -1.

func UnicharFullyDecompose

func UnicharFullyDecompose(ch uint32, compat bool, resultLen uint) (uint32, uint)

UnicharFullyDecompose computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, pass TRUE for compat; for canonical decomposition pass FALSE 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 (http://unicode.org/reports/tr15/) for details.

The function takes the following parameters:

  • ch: unicode character.
  • compat: whether perform canonical or compatibility decomposition.
  • resultLen: length of result.

The function returns the following values:

  • result (optional): location to store decomposed result, or NULL.
  • gsize: length of the full decomposition.

func UnicharGetMirrorChar

func UnicharGetMirrorChar(ch uint32, mirroredCh *uint32) bool

UnicharGetMirrorChar: 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.

The function takes the following parameters:

  • ch: unicode character.
  • mirroredCh: location to store the mirrored character.

The function returns the following values:

  • ok: TRUE if ch has a mirrored character, FALSE otherwise.

func UnicharIsalnum

func UnicharIsalnum(c uint32) bool

UnicharIsalnum determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is an alphanumeric character.

func UnicharIsalpha

func UnicharIsalpha(c uint32) bool

UnicharIsalpha determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is an alphabetic character.

func UnicharIscntrl

func UnicharIscntrl(c uint32) bool

UnicharIscntrl determines whether a character is a control character. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is a control character.

func UnicharIsdefined

func UnicharIsdefined(c uint32) bool

UnicharIsdefined determines if a given character is assigned in the Unicode standard.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if the character has an assigned value.

func UnicharIsdigit

func UnicharIsdigit(c uint32) bool

UnicharIsdigit 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 g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is a digit.

func UnicharIsgraph

func UnicharIsgraph(c uint32) bool

UnicharIsgraph determines whether a character is printable and not a space (returns FALSE for control characters, format characters, and spaces). g_unichar_isprint() is similar, but returns TRUE for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is printable unless it's a space.

func UnicharIslower

func UnicharIslower(c uint32) bool

UnicharIslower determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is a lowercase letter.

func UnicharIsmark

func UnicharIsmark(c uint32) bool

UnicharIsmark 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 g_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.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is a mark character.

func UnicharIsprint

func UnicharIsprint(c uint32) bool

UnicharIsprint determines whether a character is printable. Unlike g_unichar_isgraph(), returns TRUE for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is printable.

func UnicharIspunct

func UnicharIspunct(c uint32) bool

UnicharIspunct determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is a punctuation or symbol character.

func UnicharIsspace

func UnicharIsspace(c uint32) bool

UnicharIsspace 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 g_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.).

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is a space character.

func UnicharIstitle

func UnicharIstitle(c uint32) bool

UnicharIstitle 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.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if the character is titlecase.

func UnicharIsupper

func UnicharIsupper(c uint32) bool

UnicharIsupper determines if a character is uppercase.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if c is an uppercase character.

func UnicharIswide

func UnicharIswide(c uint32) bool

UnicharIswide determines if a character is typically rendered in a double-width cell.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if the character is wide.

func UnicharIswideCjk

func UnicharIswideCjk(c uint32) bool

UnicharIswideCjk determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to g_unichar_iswide(), then it is also reported wide with this function, but the converse is not necessarily true. See the Unicode Standard Annex #11 (http://www.unicode.org/reports/tr11/) for details.

If a character passes the g_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 g_unichar_iszerowidth().

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if the character is wide in legacy East Asian locales.

func UnicharIsxdigit

func UnicharIsxdigit(c uint32) bool

UnicharIsxdigit determines if a character is a hexadecimal digit.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if the character is a hexadecimal digit.

func UnicharIszerowidth

func UnicharIszerowidth(c uint32) bool

UnicharIszerowidth determines if a given character typically takes zero width when rendered. The return value is TRUE 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 g_unichar_iswide() or g_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.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • ok: TRUE if the character has zero width.

func UnicharToLower

func UnicharToLower(c uint32) uint32

UnicharToLower converts a character to lower case.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • gunichar: 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.

func UnicharToTitle

func UnicharToTitle(c uint32) uint32

UnicharToTitle converts a character to the titlecase.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • gunichar: result of converting c to titlecase. If c is not an uppercase or lowercase character, c is returned unchanged.

func UnicharToUpper

func UnicharToUpper(c uint32) uint32

UnicharToUpper converts a character to uppercase.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • gunichar: 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.

func UnicharValidate

func UnicharValidate(ch uint32) bool

UnicharValidate checks whether ch is a valid Unicode character. Some possible integer values of ch will not be valid. 0 is considered a valid character, though it's normally a string terminator.

The function takes the following parameters:

  • ch: unicode character.

The function returns the following values:

  • ok: TRUE if ch is a valid Unicode character.

func UnicharXDigitValue

func UnicharXDigitValue(c uint32) int

UnicharXDigitValue determines the numeric value of a character as a hexadecimal digit.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • gint: if c is a hex digit (according to g_unichar_isxdigit()), its numeric value. Otherwise, -1.

func UnicodeCanonicalDecomposition deprecated

func UnicodeCanonicalDecomposition(ch uint32, resultLen *uint) *uint32

UnicodeCanonicalDecomposition computes the canonical decomposition of a Unicode character.

Deprecated: Use the more flexible g_unichar_fully_decompose() instead.

The function takes the following parameters:

  • ch: unicode character.
  • resultLen: location to store the length of the return value.

The function returns the following values:

  • gunichar: newly allocated string of Unicode characters. result_len is set to the resulting length of the string.

func UnicodeCanonicalOrdering

func UnicodeCanonicalOrdering(str *uint32, len uint)

UnicodeCanonicalOrdering 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.

The function takes the following parameters:

  • str: UCS-4 encoded string.
  • len: maximum length of string to use.

func UnicodeScriptToISO15924

func UnicodeScriptToISO15924(script UnicodeScript) uint32

UnicodeScriptToISO15924 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 (http://unicode.org/iso15924/codelists.html) for details.

The function takes the following parameters:

  • script: unicode script.

The function returns the following values:

  • guint32: ISO 15924 code for script, encoded as an integer, of zero if script is G_UNICODE_SCRIPT_INVALID_CODE or ISO 15924 code 'Zzzz' (script code for UNKNOWN) if script is not understood.

func Unsetenv

func Unsetenv(variable string)

Unsetenv 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 g_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 g_get_environ() to get an environment array, modify that with g_environ_setenv() and g_environ_unsetenv(), and then pass that array directly to execvpe(), g_spawn_async(), or the like.

The function takes the following parameters:

  • variable: environment variable to remove, must not contain '='.

func Usleep

func Usleep(microseconds uint32)

Usleep pauses the current thread for the given number of microseconds.

There are 1 million microseconds per second (represented by the USEC_PER_SEC macro). g_usleep() may have limited precision, depending on hardware and operating system; don't rely on the exact length of the sleep.

The function takes the following parameters:

  • microseconds: number of microseconds to pause.

func VariantGetGType

func VariantGetGType() coreglib.Type

The function returns the following values:

func VariantIsObjectPath

func VariantIsObjectPath(str string) bool

VariantIsObjectPath 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 g_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.

The function takes the following parameters:

  • str: normal C nul-terminated string.

The function returns the following values:

  • ok: TRUE if string is a D-Bus object path.

func VariantIsSignature

func VariantIsSignature(str string) bool

VariantIsSignature 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 g_variant_new_signature().

D-Bus type signatures consist of zero or more definite Type strings in sequence.

The function takes the following parameters:

  • str: normal C nul-terminated string.

The function returns the following values:

  • ok: TRUE if string is a D-Bus type signature.

func VariantParseErrorPrintContext

func VariantParseErrorPrintContext(err error, sourceStr string) string

VariantParseErrorPrintContext 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 g_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 g_variant_parse() then you must add nul termination before using this function.

The function takes the following parameters:

  • err from the ParseError domain.
  • sourceStr: string that was given to the parser.

The function returns the following values:

  • utf8: printed message.

func VariantTypeStringGetDepth_

func VariantTypeStringGetDepth_(typeString string) uint

The function takes the following parameters:

The function returns the following values:

func VariantTypeStringIsValid

func VariantTypeStringIsValid(typeString string) bool

VariantTypeStringIsValid checks if type_string is a valid GVariant type string. This call is equivalent to calling g_variant_type_string_scan() and confirming that the following character is a nul terminator.

The function takes the following parameters:

  • typeString: pointer to any string.

The function returns the following values:

  • ok: TRUE if type_string is exactly one valid type string

    Since 2.24.

func VariantTypeStringScan

func VariantTypeStringScan(str, limit string) (string, bool)

VariantTypeStringScan: 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 TRUE is returned.

If there is no valid type string starting at string, or if the type string does not end before limit then FALSE is returned.

For the simple case of checking if a string is a valid type string, see g_variant_type_string_is_valid().

The function takes the following parameters:

  • str: pointer to any string.
  • limit (optional): end of string, or NULL.

The function returns the following values:

  • endptr (optional): location to store the end pointer, or NULL.
  • ok: TRUE if a valid type string was found.

Types

type Array

type Array struct {
	// contains filtered or unexported fields
}

Array contains the public fields of a GArray.

An instance of this type is always passed by reference.

func (*Array) Data

func (a *Array) Data() string

Data: pointer to the element data. The data may be moved as elements are added to the #GArray.

func (*Array) Len

func (a *Array) Len() uint

Len: number of elements in the #GArray not including the possible terminating zero element.

func (*Array) SetLen

func (a *Array) SetLen(len uint)

Len: number of elements in the #GArray not including the possible terminating zero element.

type BookmarkFileError

type BookmarkFileError C.gint

BookmarkFileError: error codes returned by bookmark file parsing.

const (
	// BookmarkFileErrorInvalidURI: URI was ill-formed.
	BookmarkFileErrorInvalidURI BookmarkFileError = iota
	// BookmarkFileErrorInvalidValue: requested field was not found.
	BookmarkFileErrorInvalidValue
	// BookmarkFileErrorAppNotRegistered: requested application did not register
	// a bookmark.
	BookmarkFileErrorAppNotRegistered
	// BookmarkFileErrorURINotFound: requested URI was not found.
	BookmarkFileErrorURINotFound
	// BookmarkFileErrorRead: document was ill formed.
	BookmarkFileErrorRead
	// BookmarkFileErrorUnknownEncoding: text being parsed was in an unknown
	// encoding.
	BookmarkFileErrorUnknownEncoding
	// BookmarkFileErrorWrite: error occurred while writing.
	BookmarkFileErrorWrite
	// BookmarkFileErrorFileNotFound: requested file was not found.
	BookmarkFileErrorFileNotFound
)

func (BookmarkFileError) String

func (b BookmarkFileError) String() string

String returns the name in string for BookmarkFileError.

type ByteArray

type ByteArray struct {
	// contains filtered or unexported fields
}

ByteArray contains the public fields of a GByteArray.

An instance of this type is always passed by reference.

func (*ByteArray) Data

func (b *ByteArray) Data() *byte

Data: pointer to the element data. The data may be moved as elements are added to the Array.

func (*ByteArray) Len

func (b *ByteArray) Len() uint

Len: number of elements in the Array.

func (*ByteArray) SetLen

func (b *ByteArray) SetLen(len uint)

Len: number of elements in the Array.

type Bytes

type Bytes struct {
	// contains filtered or unexported fields
}

Bytes: simple refcounted data type representing an immutable sequence of zero or more bytes from an unspecified origin.

The purpose of a #GBytes is to keep the memory region that it holds alive for as long as anyone holds a reference to the bytes. When the last reference count is dropped, the memory is released. Multiple unrelated callers can use byte data in the #GBytes without coordinating their activities, resting assured that the byte data will not change or move while they hold a reference.

A #GBytes can come from many different origins that may have different procedures for freeing the memory region. Examples are memory from g_malloc(), from memory slices, from a File or memory from other allocators.

#GBytes work well as keys in Table. Use g_bytes_equal() and g_bytes_hash() as parameters to g_hash_table_new() or g_hash_table_new_full(). #GBytes can also be used as keys in a #GTree by passing the g_bytes_compare() function to g_tree_new().

The data pointed to by this bytes must not be modified. For a mutable array of bytes see Array. Use g_bytes_unref_to_array() to create a mutable array for a #GBytes sequence. To create an immutable #GBytes from a mutable Array, use the g_byte_array_free_to_bytes() function.

An instance of this type is always passed by reference.

func NewBytes

func NewBytes(data []byte) *Bytes

NewBytes constructs a struct Bytes.

func NewBytesWithGo

func NewBytesWithGo(data []byte) *Bytes

NewBytesWithGo is similar to NewBytes, except the given Go byte slice is not copied, but will be kept alive for the lifetime of the GBytes. Note that the user must NOT modify data.

Refer to g_bytes_new_with_free_func() for more information.

func URIUnescapeBytes

func URIUnescapeBytes(escapedString string, length int, illegalCharacters string) (*Bytes, error)

URIUnescapeBytes unescapes a segment of an escaped string as binary data.

Note that in contrast to g_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 NULL 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.

The function takes the following parameters:

  • escapedString: URI-escaped string.
  • length (in bytes) of escaped_string to escape, or -1 if it is nul-terminated.
  • illegalCharacters (optional): string of illegal characters not to be allowed, or NULL.

The function returns the following values:

  • bytes: unescaped version of escaped_string or NULL on error (if decoding failed, using G_URI_ERROR_FAILED error code). The returned #GBytes should be unreffed when no longer needed.

func (*Bytes) Compare

func (bytes1 *Bytes) Compare(bytes2 *Bytes) int

Compare compares the two #GBytes values.

This function can be used to sort GBytes instances in lexicographical order.

If bytes1 and bytes2 have different length but the shorter one is a prefix of the longer one then the shorter one is considered to be less than the longer one. Otherwise the first byte where both differ is used for comparison. If bytes1 has a smaller value at that position it is considered less, otherwise greater than bytes2.

The function takes the following parameters:

  • bytes2: pointer to a #GBytes to compare with bytes1.

The function returns the following values:

  • gint: negative value if bytes1 is less than bytes2, a positive value if bytes1 is greater than bytes2, and zero if bytes1 is equal to bytes2.

func (*Bytes) Data

func (bytes *Bytes) Data() []byte

Data: get the byte data in the #GBytes. This data should not be modified.

This function will always return the same pointer for a given #GBytes.

NULL may be returned if size is 0. This is not guaranteed, as the #GBytes may represent an empty string with data non-NULL and size as 0. NULL will not be returned if size is non-zero.

The function returns the following values:

  • guint8s (optional): a pointer to the byte data, or NULL.

func (*Bytes) Equal

func (bytes1 *Bytes) Equal(bytes2 *Bytes) bool

Equal compares the two #GBytes values being pointed to and returns TRUE if they are equal.

This function can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-NULL #GBytes pointers as keys in a Table.

The function takes the following parameters:

  • bytes2: pointer to a #GBytes to compare with bytes1.

The function returns the following values:

  • ok: TRUE if the two keys match.

func (*Bytes) Hash

func (bytes *Bytes) Hash() uint

Hash creates an integer hash code for the byte data in the #GBytes.

This function can be passed to g_hash_table_new() as the key_hash_func parameter, when using non-NULL #GBytes pointers as keys in a Table.

The function returns the following values:

  • guint: hash value corresponding to the key.

func (*Bytes) NewFromBytes

func (bytes *Bytes) NewFromBytes(offset uint, length uint) *Bytes

NewFromBytes creates a #GBytes which is a subsection of another #GBytes. The offset + length may not be longer than the size of bytes.

A reference to bytes will be held by the newly created #GBytes until the byte data is no longer needed.

Since 2.56, if offset is 0 and length matches the size of bytes, then bytes will be returned with the reference count incremented by 1. If bytes is a slice of another #GBytes, then the resulting #GBytes will reference the same #GBytes instead of bytes. This allows consumers to simplify the usage of #GBytes when asynchronously writing to streams.

The function takes the following parameters:

  • offset which subsection starts at.
  • length of subsection.

The function returns the following values:

  • ret: new #GBytes.

func (*Bytes) Size

func (bytes *Bytes) Size() uint

Size: get the size of the byte data in the #GBytes.

This function will always return the same value for a given #GBytes.

The function returns the following values:

  • gsize: size.

func (*Bytes) Use

func (b *Bytes) Use(f func([]byte))

Use calls f with Bytes' internal byte slice without making a copy. f must NOT move the byte slice to outside of the closure, since the slice's internal array buffer may be freed after.

type Checksum

type Checksum struct {
	// contains filtered or unexported fields
}

Checksum: opaque structure representing a checksumming operation. To create a new GChecksum, use g_checksum_new(). To free a GChecksum, use g_checksum_free().

An instance of this type is always passed by reference.

func NewChecksum

func NewChecksum(checksumType ChecksumType) *Checksum

NewChecksum constructs a struct Checksum.

func (*Checksum) Copy

func (checksum *Checksum) Copy() *Checksum

Copy copies a #GChecksum. If checksum has been closed, by calling g_checksum_get_string() or g_checksum_get_digest(), the copied checksum will be closed as well.

The function returns the following values:

  • ret: copy of the passed #GChecksum. Use g_checksum_free() when finished using it.

func (*Checksum) Reset

func (checksum *Checksum) Reset()

Reset resets the state of the checksum back to its initial state.

func (*Checksum) String

func (checksum *Checksum) String() string

String gets the digest as a hexadecimal string.

Once this function has been called the #GChecksum can no longer be updated with g_checksum_update().

The hexadecimal characters will be lower case.

The function returns the following values:

  • utf8: hexadecimal representation of the checksum. The returned string is owned by the checksum and should not be modified or freed.

func (*Checksum) Update

func (checksum *Checksum) Update(data []byte)

Update feeds data into an existing #GChecksum. The checksum must still be open, that is g_checksum_get_string() or g_checksum_get_digest() must not have been called on checksum.

The function takes the following parameters:

  • data: buffer used to compute the checksum.

type ChecksumType

type ChecksumType C.gint

ChecksumType: hashing algorithm to be used by #GChecksum when performing the digest of some data.

Note that the Type enumeration may be extended at a later date to include new hashing algorithm types.

const (
	// ChecksumMD5: use the MD5 hashing algorithm.
	ChecksumMD5 ChecksumType = iota
	// ChecksumSHA1: use the SHA-1 hashing algorithm.
	ChecksumSHA1
	// ChecksumSHA256: use the SHA-256 hashing algorithm.
	ChecksumSHA256
	// ChecksumSHA512: use the SHA-512 hashing algorithm (Since: 2.36).
	ChecksumSHA512
	// ChecksumSHA384: use the SHA-384 hashing algorithm (Since: 2.51).
	ChecksumSHA384
)

func (ChecksumType) String

func (c ChecksumType) String() string

String returns the name in string for ChecksumType.

type CompareDataFunc

type CompareDataFunc func(a, b unsafe.Pointer) (gint int)

CompareDataFunc specifies the type of a comparison function used to compare two values. The function should return a negative integer if the first value comes before the second, 0 if they are equal, or a positive integer if the first value comes after the second.

func NewObjectComparer

func NewObjectComparer[T Objector](f func(a, b T) int) CompareDataFunc

NewObjectComparer returns a CompareDataFunc that uses the given function to compare two objects of type T. If the underlying objects are not of type T, then the function panics. If the underlying pointers aren't objects, then the behavior is undefined.

type ConvertError

type ConvertError C.gint

ConvertError: error codes returned by character set conversion routines.

const (
	// ConvertErrorNoConversion: conversion between the requested character sets
	// is not supported.
	ConvertErrorNoConversion ConvertError = iota
	// ConvertErrorIllegalSequence: invalid byte sequence in conversion input;
	// or the character sequence could not be represented in the target
	// character set.
	ConvertErrorIllegalSequence
	// ConvertErrorFailed: conversion failed for some reason.
	ConvertErrorFailed
	// ConvertErrorPartialInput: partial character sequence at end of input.
	ConvertErrorPartialInput
	// ConvertErrorBadURI: URI is invalid.
	ConvertErrorBadURI
	// ConvertErrorNotAbsolutePath: pathname is not an absolute path.
	ConvertErrorNotAbsolutePath
	// ConvertErrorNoMemory: no memory available. Since: 2.40.
	ConvertErrorNoMemory
	// ConvertErrorEmbeddedNUL: embedded NUL character is present in conversion
	// output where a NUL-terminated string is expected. Since: 2.56.
	ConvertErrorEmbeddedNUL
)

func (ConvertError) String

func (c ConvertError) String() string

String returns the name in string for ConvertError.

type DateTime

type DateTime struct {
	// contains filtered or unexported fields
}

DateTime: GDateTime is an opaque structure whose members cannot be accessed directly.

An instance of this type is always passed by reference.

func NewDateTime

func NewDateTime(tz *TimeZone, year int, month int, day int, hour int, minute int, seconds float64) *DateTime

NewDateTime constructs a struct DateTime.

func NewDateTimeFromGo

func NewDateTimeFromGo(t time.Time) *DateTime

NewDateTimeFromGo creates a new DateTime instance from Go's Time. The TimeZone of the DateTime will be implicitly converted from the Time.

func NewDateTimeFromISO8601

func NewDateTimeFromISO8601(text string, defaultTz *TimeZone) *DateTime

NewDateTimeFromISO8601 constructs a struct DateTime.

func NewDateTimeFromTimevalLocal

func NewDateTimeFromTimevalLocal(tv *TimeVal) *DateTime

NewDateTimeFromTimevalLocal constructs a struct DateTime.

func NewDateTimeFromTimevalUTC

func NewDateTimeFromTimevalUTC(tv *TimeVal) *DateTime

NewDateTimeFromTimevalUTC constructs a struct DateTime.

func NewDateTimeFromUnixLocal

func NewDateTimeFromUnixLocal(t int64) *DateTime

NewDateTimeFromUnixLocal constructs a struct DateTime.

func NewDateTimeFromUnixUTC

func NewDateTimeFromUnixUTC(t int64) *DateTime

NewDateTimeFromUnixUTC constructs a struct DateTime.

func NewDateTimeLocal

func NewDateTimeLocal(year int, month int, day int, hour int, minute int, seconds float64) *DateTime

NewDateTimeLocal constructs a struct DateTime.

func NewDateTimeNow

func NewDateTimeNow(tz *TimeZone) *DateTime

NewDateTimeNow constructs a struct DateTime.

func NewDateTimeNowLocal

func NewDateTimeNowLocal() *DateTime

NewDateTimeNowLocal constructs a struct DateTime.

func NewDateTimeNowUTC

func NewDateTimeNowUTC() *DateTime

NewDateTimeNowUTC constructs a struct DateTime.

func NewDateTimeUTC

func NewDateTimeUTC(year int, month int, day int, hour int, minute int, seconds float64) *DateTime

NewDateTimeUTC constructs a struct DateTime.

func (*DateTime) Add

func (datetime *DateTime) Add(timespan TimeSpan) *DateTime

Add creates a copy of datetime and adds the specified timespan to the copy.

The function takes the following parameters:

  • timespan: Span.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddDays

func (datetime *DateTime) AddDays(days int) *DateTime

AddDays creates a copy of datetime and adds the specified number of days to the copy. Add negative values to subtract days.

The function takes the following parameters:

  • days: number of days.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddFull

func (datetime *DateTime) AddFull(years int, months int, days int, hours int, minutes int, seconds float64) *DateTime

AddFull creates a new Time adding the specified values to the current date and time in datetime. Add negative values to subtract.

The function takes the following parameters:

  • years: number of years to add.
  • months: number of months to add.
  • days: number of days to add.
  • hours: number of hours to add.
  • minutes: number of minutes to add.
  • seconds: number of seconds to add.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddHours

func (datetime *DateTime) AddHours(hours int) *DateTime

AddHours creates a copy of datetime and adds the specified number of hours. Add negative values to subtract hours.

The function takes the following parameters:

  • hours: number of hours to add.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddMinutes

func (datetime *DateTime) AddMinutes(minutes int) *DateTime

AddMinutes creates a copy of datetime adding the specified number of minutes. Add negative values to subtract minutes.

The function takes the following parameters:

  • minutes: number of minutes to add.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddMonths

func (datetime *DateTime) AddMonths(months int) *DateTime

AddMonths creates a copy of datetime and adds the specified number of months to the copy. Add negative values to subtract months.

The day of the month of the resulting Time is clamped to the number of days in the updated calendar month. For example, if adding 1 month to 31st January 2018, the result would be 28th February 2018. In 2020 (a leap year), the result would be 29th February.

The function takes the following parameters:

  • months: number of months.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddSeconds

func (datetime *DateTime) AddSeconds(seconds float64) *DateTime

AddSeconds creates a copy of datetime and adds the specified number of seconds. Add negative values to subtract seconds.

The function takes the following parameters:

  • seconds: number of seconds to add.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddWeeks

func (datetime *DateTime) AddWeeks(weeks int) *DateTime

AddWeeks creates a copy of datetime and adds the specified number of weeks to the copy. Add negative values to subtract weeks.

The function takes the following parameters:

  • weeks: number of weeks.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) AddYears

func (datetime *DateTime) AddYears(years int) *DateTime

AddYears creates a copy of datetime and adds the specified number of years to the copy. Add negative values to subtract years.

As with g_date_time_add_months(), if the resulting date would be 29th February on a non-leap year, the day will be clamped to 28th February.

The function takes the following parameters:

  • years: number of years.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) Compare

func (dt1 *DateTime) Compare(dt2 *DateTime) int

Compare: comparison function for Times that is suitable as a Func. Both Times must be non-NULL.

The function takes the following parameters:

  • dt2: second Time to compare.

The function returns the following values:

  • gint: -1, 0 or 1 if dt1 is less than, equal to or greater than dt2.

func (*DateTime) DayOfMonth

func (datetime *DateTime) DayOfMonth() int

DayOfMonth retrieves the day of the month represented by datetime in the gregorian calendar.

The function returns the following values:

  • gint: day of the month.

func (*DateTime) DayOfWeek

func (datetime *DateTime) DayOfWeek() int

DayOfWeek retrieves the ISO 8601 day of the week on which datetime falls (1 is Monday, 2 is Tuesday... 7 is Sunday).

The function returns the following values:

  • gint: day of the week.

func (*DateTime) DayOfYear

func (datetime *DateTime) DayOfYear() int

DayOfYear retrieves the day of the year represented by datetime in the Gregorian calendar.

The function returns the following values:

  • gint: day of the year.

func (*DateTime) Difference

func (end *DateTime) Difference(begin *DateTime) TimeSpan

Difference calculates the difference in time between end and begin. The Span that is returned is effectively end - begin (ie: positive if the first parameter is larger).

The function takes the following parameters:

  • begin: Time.

The function returns the following values:

  • timeSpan: difference between the two Time, as a time span expressed in microseconds.

func (*DateTime) Equal

func (dt1 *DateTime) Equal(dt2 *DateTime) bool

Equal checks to see if dt1 and dt2 are equal.

Equal here means that they represent the same moment after converting them to the same time zone.

The function takes the following parameters:

  • dt2: Time.

The function returns the following values:

  • ok: TRUE if dt1 and dt2 are equal.

func (*DateTime) Format

func (datetime *DateTime) Format(format string) string

Format creates a newly allocated string representing the requested format.

The format strings understood by this function are a subset of the strftime() format language as specified by C99. The \D, \U and \W conversions are not supported, nor is the 'E' modifier. The GNU extensions \k, \l, \s and \P are supported, however, as are the '0', '_' and '-' modifiers. The Python extension \f is also supported.

In contrast to strftime(), this function always produces a UTF-8 string, regardless of the current locale. Note that the rendering of many formats is locale-dependent and may not match the strftime() output exactly.

The following format specifiers are supported:

- \a: the abbreviated weekday name according to the current locale

- \A: the full weekday name according to the current locale

- \b: the abbreviated month name according to the current locale

- \B: the full month name according to the current locale

- \c: the preferred date and time representation for the current locale

- \C: the century number (year/100) as a 2-digit integer (00-99)

- \d: the day of the month as a decimal number (range 01 to 31)

- \e: the day of the month as a decimal number (range 1 to 31)

- \F: equivalent to Y-m-d (the ISO 8601 date format)

- \g: the last two digits of the ISO 8601 week-based year as a decimal number (00-99). This works well with \V and \u.

- \G: the ISO 8601 week-based year as a decimal number. This works well with \V and \u.

- \h: equivalent to \b

- \H: the hour as a decimal number using a 24-hour clock (range 00 to 23)

- \I: the hour as a decimal number using a 12-hour clock (range 01 to 12)

- \j: the day of the year as a decimal number (range 001 to 366)

- \k: the hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank

- \l: the hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank

- \m: the month as a decimal number (range 01 to 12)

- \M: the minute as a decimal number (range 00 to 59)

- \f: the microsecond as a decimal number (range 000000 to 999999)

- \p: either "AM" or "PM" according to the given time value, or the corresponding strings for the current locale. Noon is treated as "PM" and midnight as "AM". Use of this format specifier is discouraged, as many locales have no concept of AM/PM formatting. Use \c or \X instead.

- \P: like \p but lowercase: "am" or "pm" or a corresponding string for the current locale. Use of this format specifier is discouraged, as many locales have no concept of AM/PM formatting. Use \c or \X instead.

- \r: the time in a.m. or p.m. notation. Use of this format specifier is discouraged, as many locales have no concept of AM/PM formatting. Use \c or \X instead.

- \R: the time in 24-hour notation (\H:\M)

- \s: the number of seconds since the Epoch, that is, since 1970-01-01 00:00:00 UTC

- \S: the second as a decimal number (range 00 to 60)

- \t: a tab character

- \T: the time in 24-hour notation with seconds (\H:\M:\S)

- \u: the ISO 8601 standard day of the week as a decimal, range 1 to 7, Monday being 1. This works well with \G and \V.

- \V: the ISO 8601 standard week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the new year. See g_date_time_get_week_of_year(). This works well with \G and \u.

- \w: the day of the week as a decimal, range 0 to 6, Sunday being 0. This is not the ISO 8601 standard format -- use \u instead.

- \x: the preferred date representation for the current locale without the time

- \X: the preferred time representation for the current locale without the date

- \y: the year as a decimal number without the century

- \Y: the year as a decimal number including the century

- \z: the time zone as an offset from UTC (+hhmm)

- \%:z: the time zone as an offset from UTC (+hh:mm). This is a gnulib strftime() extension. Since: 2.38

- \%::z: the time zone as an offset from UTC (+hh:mm:ss). This is a gnulib strftime() extension. Since: 2.38

- \%:::z: the time zone as an offset from UTC, with : to necessary precision (e.g., -04, +05:30). This is a gnulib strftime() extension. Since: 2.38

- \Z: the time zone or name or abbreviation

- \%\%: a literal \% character

Some conversion specifications can be modified by preceding the conversion specifier by one or more modifier characters. The following modifiers are supported for many of the numeric conversions:

- O: Use alternative numeric symbols, if the current locale supports those.

- _: Pad a numeric result with spaces. This overrides the default padding for the specifier.

- -: Do not pad a numeric result. This overrides the default padding for the specifier.

- 0: Pad a numeric result with zeros. This overrides the default padding for the specifier.

Additionally, when O is used with B, b, or h, it produces the alternative form of a month name. The alternative form should be used when the month name is used without a day number (e.g., standalone). It is required in some languages (Baltic, Slavic, Greek, and more) due to their grammatical rules. For other languages there is no difference. \OB is a GNU and BSD strftime() extension expected to be added to the future POSIX specification, \Ob and \Oh are GNU strftime() extensions. Since: 2.56.

The function takes the following parameters:

  • format: valid UTF-8 string, containing the format for the Time.

The function returns the following values:

  • utf8 (optional): newly allocated string formatted to the requested format or NULL in the case that there was an error (such as a format specifier not being supported in the current locale). The string should be freed with g_free().

func (*DateTime) FormatISO8601

func (datetime *DateTime) FormatISO8601() string

FormatISO8601: format datetime in ISO 8601 format (https://en.wikipedia.org/wiki/ISO_8601), including the date, time and time zone, and return that as a UTF-8 encoded string.

Since GLib 2.66, this will output to sub-second precision if needed.

The function returns the following values:

  • utf8 (optional): newly allocated string formatted in ISO 8601 format or NULL in the case that there was an error. The string should be freed with g_free().

func (*DateTime) Hash

func (datetime *DateTime) Hash() uint

Hash hashes datetime into a #guint, suitable for use within Table.

The function returns the following values:

  • guint containing the hash.

func (*DateTime) Hour

func (datetime *DateTime) Hour() int

Hour retrieves the hour of the day represented by datetime.

The function returns the following values:

  • gint: hour of the day.

func (*DateTime) IsDaylightSavings

func (datetime *DateTime) IsDaylightSavings() bool

IsDaylightSavings determines if daylight savings time is in effect at the time and in the time zone of datetime.

The function returns the following values:

  • ok: TRUE if daylight savings time is in effect.

func (*DateTime) Microsecond

func (datetime *DateTime) Microsecond() int

Microsecond retrieves the microsecond of the date represented by datetime.

The function returns the following values:

  • gint: microsecond of the second.

func (*DateTime) Minute

func (datetime *DateTime) Minute() int

Minute retrieves the minute of the hour represented by datetime.

The function returns the following values:

  • gint: minute of the hour.

func (*DateTime) Month

func (datetime *DateTime) Month() int

Month retrieves the month of the year represented by datetime in the Gregorian calendar.

The function returns the following values:

  • gint: month represented by datetime.

func (*DateTime) Second

func (datetime *DateTime) Second() int

Second retrieves the second of the minute represented by datetime.

The function returns the following values:

  • gint: second represented by datetime.

func (*DateTime) Seconds

func (datetime *DateTime) Seconds() float64

Seconds retrieves the number of seconds since the start of the last minute, including the fractional part.

The function returns the following values:

  • gdouble: number of seconds.

func (*DateTime) Timezone

func (datetime *DateTime) Timezone() *TimeZone

Timezone: get the time zone for this datetime.

The function returns the following values:

  • timeZone: time zone.

func (*DateTime) TimezoneAbbreviation

func (datetime *DateTime) TimezoneAbbreviation() string

TimezoneAbbreviation determines the time zone abbreviation to be used at the time and in the time zone of datetime.

For example, in Toronto this is currently "EST" during the winter months and "EDT" during the summer months when daylight savings time is in effect.

The function returns the following values:

  • utf8: time zone abbreviation. The returned string is owned by the Time and it should not be modified or freed.

func (*DateTime) ToLocal

func (datetime *DateTime) ToLocal() *DateTime

ToLocal creates a new Time corresponding to the same instant in time as datetime, but in the local time zone.

This call is equivalent to calling g_date_time_to_timezone() with the time zone returned by g_time_zone_new_local().

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) ToTimeval deprecated

func (datetime *DateTime) ToTimeval(tv *TimeVal) bool

ToTimeval stores the instant in time that datetime represents into tv.

The time contained in a Val is always stored in the form of seconds elapsed since 1970-01-01 00:00:00 UTC, regardless of the time zone associated with datetime.

On systems where 'long' is 32bit (ie: all 32bit systems and all Windows systems), a Val is incapable of storing the entire range of values that Time is capable of expressing. On those systems, this function returns FALSE to indicate that the time is out of range.

On systems where 'long' is 64bit, this function never fails.

Deprecated: Val is not year-2038-safe. Use g_date_time_to_unix() instead.

The function takes the following parameters:

  • tv to modify.

The function returns the following values:

  • ok: TRUE if successful, else FALSE.

func (*DateTime) ToTimezone

func (datetime *DateTime) ToTimezone(tz *TimeZone) *DateTime

ToTimezone: create a new Time corresponding to the same instant in time as datetime, but in the time zone tz.

This call can fail in the case that the time goes out of bounds. For example, converting 0001-01-01 00:00:00 UTC to a time zone west of Greenwich will fail (due to the year 0 being out of range).

The function takes the following parameters:

  • tz: new Zone.

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) ToUTC

func (datetime *DateTime) ToUTC() *DateTime

ToUTC creates a new Time corresponding to the same instant in time as datetime, but in UTC.

This call is equivalent to calling g_date_time_to_timezone() with the time zone returned by g_time_zone_new_utc().

The function returns the following values:

  • dateTime (optional): newly created Time which should be freed with g_date_time_unref(), or NULL.

func (*DateTime) ToUnix

func (datetime *DateTime) ToUnix() int64

ToUnix gives the Unix time corresponding to datetime, rounding down to the nearest second.

Unix time is the number of seconds that have elapsed since 1970-01-01 00:00:00 UTC, regardless of the time zone associated with datetime.

The function returns the following values:

  • gint64: unix time corresponding to datetime.

func (*DateTime) UTCOffset

func (datetime *DateTime) UTCOffset() TimeSpan

UTCOffset determines the offset to UTC in effect at the time and in the time zone of datetime.

The offset is the number of microseconds that you add to UTC time to arrive at local time for the time zone (ie: negative numbers for time zones west of GMT, positive numbers for east).

If datetime represents UTC time, then the offset is always zero.

The function returns the following values:

  • timeSpan: number of microseconds that should be added to UTC to get the local time.

func (*DateTime) WeekNumberingYear

func (datetime *DateTime) WeekNumberingYear() int

WeekNumberingYear returns the ISO 8601 week-numbering year in which the week containing datetime falls.

This function, taken together with g_date_time_get_week_of_year() and g_date_time_get_day_of_week() can be used to determine the full ISO week date on which datetime falls.

This is usually equal to the normal Gregorian year (as returned by g_date_time_get_year()), except as detailed below:

For Thursday, the week-numbering year is always equal to the usual calendar year. For other days, the number is such that every day within a complete week (Monday to Sunday) is contained within the same week-numbering year.

For Monday, Tuesday and Wednesday occurring near the end of the year, this may mean that the week-numbering year is one greater than the calendar year (so that these days have the same week-numbering year as the Thursday occurring early in the next year).

For Friday, Saturday and Sunday occurring near the start of the year, this may mean that the week-numbering year is one less than the calendar year (so that these days have the same week-numbering year as the Thursday occurring late in the previous year).

An equivalent description is that the week-numbering year is equal to the calendar year containing the majority of the days in the current week (Monday to Sunday).

Note that January 1 0001 in the proleptic Gregorian calendar is a Monday, so this function never returns 0.

The function returns the following values:

  • gint: ISO 8601 week-numbering year for datetime.

func (*DateTime) WeekOfYear

func (datetime *DateTime) WeekOfYear() int

WeekOfYear returns the ISO 8601 week number for the week containing datetime. The ISO 8601 week number is the same for every day of the week (from Moday through Sunday). That can produce some unusual results (described below).

The first week of the year is week 1. This is the week that contains the first Thursday of the year. Equivalently, this is the first week that has more than 4 of its days falling within the calendar year.

The value 0 is never returned by this function. Days contained within a year but occurring before the first ISO 8601 week of that year are considered as being contained in the last week of the previous year. Similarly, the final days of a calendar year may be considered as being part of the first ISO 8601 week of the next year if 4 or more days of that week are contained within the new year.

The function returns the following values:

  • gint: ISO 8601 week number for datetime.

func (*DateTime) Year

func (datetime *DateTime) Year() int

Year retrieves the year represented by datetime in the Gregorian calendar.

The function returns the following values:

  • gint: year represented by datetime.

func (*DateTime) Ymd

func (datetime *DateTime) Ymd() (year int, month int, day int)

Ymd retrieves the Gregorian day, month, and year of a given Time.

The function returns the following values:

  • year (optional): return location for the gregorian year, or NULL.
  • month (optional): return location for the month of the year, or NULL.
  • day (optional): return location for the day of the month, or NULL.

type DebugKey

type DebugKey struct {
	// contains filtered or unexported fields
}

DebugKey associates a string with a bit flag. Used in g_parse_debug_string().

An instance of this type is always passed by reference.

func (*DebugKey) Key

func (d *DebugKey) Key() string

Key: string.

func (*DebugKey) SetValue

func (d *DebugKey) SetValue(value uint)

Value: flag.

func (*DebugKey) Value

func (d *DebugKey) Value() uint

Value: flag.

type ErrorType

type ErrorType C.gint

ErrorType: possible errors, used in the v_error field of Value, when the token is a G_TOKEN_ERROR.

const (
	// ErrUnknown: unknown error.
	ErrUnknown ErrorType = iota
	// ErrUnexpEOF: unexpected end of file.
	ErrUnexpEOF
	// ErrUnexpEOFInString: unterminated string constant.
	ErrUnexpEOFInString
	// ErrUnexpEOFInComment: unterminated comment.
	ErrUnexpEOFInComment
	// ErrNonDigitInConst: non-digit character in a number.
	ErrNonDigitInConst
	// ErrDigitRadix: digit beyond radix in a number.
	ErrDigitRadix
	// ErrFloatRadix: non-decimal floating point number.
	ErrFloatRadix
	// ErrFloatMalformed: malformed floating point number.
	ErrFloatMalformed
)

func (ErrorType) String

func (e ErrorType) String() string

String returns the name in string for ErrorType.

type FileError

type FileError C.gint

FileError values corresponding to errno codes returned from file operations on UNIX. Unlike errno codes, GFileError values are available on all systems, even Windows. The exact meaning of each code depends on what sort of file operation you were performing; the UNIX documentation gives more details. The following error code descriptions come from the GNU C Library manual, and are under the copyright of that manual.

It's not very portable to make detailed assumptions about exactly which errors will be returned from a given operation. Some errors don't occur on some systems, etc., sometimes there are subtle differences in when a system will report a given error, etc.

const (
	// FileErrorExist: operation not permitted; only the owner of the file (or
	// other resource) or processes with special privileges can perform the
	// operation.
	FileErrorExist FileError = iota
	// FileErrorIsdir: file is a directory; you cannot open a directory for
	// writing, or create or remove hard links to it.
	FileErrorIsdir
	// FileErrorAcces: permission denied; the file permissions do not allow the
	// attempted operation.
	FileErrorAcces
	// FileErrorNametoolong: filename too long.
	FileErrorNametoolong
	// FileErrorNoent: no such file or directory. This is a "file doesn't exist"
	// error for ordinary files that are referenced in contexts where they are
	// expected to already exist.
	FileErrorNoent
	// FileErrorNotdir: file that isn't a directory was specified when a
	// directory is required.
	FileErrorNotdir
	// FileErrorNxio: no such device or address. The system tried to use the
	// device represented by a file you specified, and it couldn't find the
	// device. This can mean that the device file was installed incorrectly,
	// or that the physical device is missing or not correctly attached to the
	// computer.
	FileErrorNxio
	// FileErrorNodev: underlying file system of the specified file does not
	// support memory mapping.
	FileErrorNodev
	// FileErrorRofs: directory containing the new link can't be modified
	// because it's on a read-only file system.
	FileErrorRofs
	// FileErrorTxtbsy: text file busy.
	FileErrorTxtbsy
	// FileErrorFault: you passed in a pointer to bad memory. (GLib won't
	// reliably return this, don't pass in pointers to bad memory.).
	FileErrorFault
	// FileErrorLoop: too many levels of symbolic links were encountered in
	// looking up a file name. This often indicates a cycle of symbolic links.
	FileErrorLoop
	// FileErrorNospc: no space left on device; write operation on a file failed
	// because the disk is full.
	FileErrorNospc
	// FileErrorNOMEM: no memory available. The system cannot allocate more
	// virtual memory because its capacity is full.
	FileErrorNOMEM
	// FileErrorMfile: current process has too many files open and can't open
	// any more. Duplicate descriptors do count toward this limit.
	FileErrorMfile
	// FileErrorNfile: there are too many distinct file openings in the entire
	// system.
	FileErrorNfile
	// FileErrorBadf: bad file descriptor; for example, I/O on a descriptor that
	// has been closed or reading from a descriptor open only for writing (or
	// vice versa).
	FileErrorBadf
	// FileErrorInval: invalid argument. This is used to indicate various kinds
	// of problems with passing the wrong argument to a library function.
	FileErrorInval
	// FileErrorPipe: broken pipe; there is no process reading from the other
	// end of a pipe. Every library function that returns this error code also
	// generates a 'SIGPIPE' signal; this signal terminates the program if not
	// handled or blocked. Thus, your program will never actually see this code
	// unless it has handled or blocked 'SIGPIPE'.
	FileErrorPipe
	// FileErrorAgain: resource temporarily unavailable; the call might work if
	// you try again later.
	FileErrorAgain
	// FileErrorIntr: interrupted function call; an asynchronous signal occurred
	// and prevented completion of the call. When this happens, you should try
	// the call again.
	FileErrorIntr
	// FileErrorIO: input/output error; usually used for physical read or write
	// errors. i.e. the disk or other physical device hardware is returning
	// errors.
	FileErrorIO
	// FileErrorPerm: operation not permitted; only the owner of the file (or
	// other resource) or processes with special privileges can perform the
	// operation.
	FileErrorPerm
	// FileErrorNosys: function not implemented; this indicates that the system
	// is missing some functionality.
	FileErrorNosys
	// FileErrorFailed does not correspond to a UNIX error code; this is the
	// standard "failed for unspecified reason" error code present in all
	// #GError error code enumerations. Returned if no specific code applies.
	FileErrorFailed
)

func FileErrorFromErrno

func FileErrorFromErrno(errNo int) FileError

FileErrorFromErrno gets a Error constant based on the passed-in err_no. For example, if you pass in EEXIST this function returns FILE_ERROR_EXIST. Unlike errno values, you can portably assume that all Error values will exist.

Normally a Error value goes into a #GError returned from a function that manipulates files. So you would use g_file_error_from_errno() when constructing a #GError.

The function takes the following parameters:

  • errNo: "errno" value.

The function returns the following values:

  • fileError corresponding to the given errno.

func (FileError) String

func (f FileError) String() string

String returns the name in string for FileError.

type FileSetContentsFlags

type FileSetContentsFlags C.guint

FileSetContentsFlags flags to pass to g_file_set_contents_full() to affect its safety and performance.

const (
	// FileSetContentsNone: no guarantees about file consistency or durability.
	// The most dangerous setting, which is slightly faster than other settings.
	FileSetContentsNone FileSetContentsFlags = 0b0
	// FileSetContentsConsistent: guarantee file consistency: after a crash,
	// either the old version of the file or the new version of the file will be
	// available, but not a mixture. On Unix systems this equates to an fsync()
	// on the file and use of an atomic rename() of the new version of the file
	// over the old.
	FileSetContentsConsistent FileSetContentsFlags = 0b1
	// FileSetContentsDurable: guarantee file durability: after a crash, the
	// new version of the file will be available. On Unix systems this equates
	// to an fsync() on the file (if G_FILE_SET_CONTENTS_CONSISTENT is unset),
	// or the effects of G_FILE_SET_CONTENTS_CONSISTENT plus an fsync() on the
	// directory containing the file after calling rename().
	FileSetContentsDurable FileSetContentsFlags = 0b10
	// FileSetContentsOnlyExisting: only apply consistency and durability
	// guarantees if the file already exists. This may speed up file operations
	// if the file doesn’t currently exist, but may result in a corrupted
	// version of the new file if the system crashes while writing it.
	FileSetContentsOnlyExisting FileSetContentsFlags = 0b100
)

func (FileSetContentsFlags) Has

Has returns true if f contains other.

func (FileSetContentsFlags) String

func (f FileSetContentsFlags) String() string

String returns the names in string for FileSetContentsFlags.

type FileTest

type FileTest C.guint

FileTest: test to perform on a file using g_file_test().

const (
	// FileTestIsRegular: TRUE if the file is a regular file (not a directory).
	// Note that this test will also return TRUE if the tested file is a symlink
	// to a regular file.
	FileTestIsRegular FileTest = 0b1
	// FileTestIsSymlink: TRUE if the file is a symlink.
	FileTestIsSymlink FileTest = 0b10
	// FileTestIsDir: TRUE if the file is a directory.
	FileTestIsDir FileTest = 0b100
	// FileTestIsExecutable: TRUE if the file is executable.
	FileTestIsExecutable FileTest = 0b1000
	// FileTestExists: TRUE if the file exists. It may or may not be a regular
	// file.
	FileTestExists FileTest = 0b10000
)

func (FileTest) Has

func (f FileTest) Has(other FileTest) bool

Has returns true if f contains other.

func (FileTest) String

func (f FileTest) String() string

String returns the names in string for FileTest.

type FormatSizeFlags

type FormatSizeFlags C.guint

FormatSizeFlags flags to modify the format of the string returned by g_format_size_full().

const (
	// FormatSizeDefault: behave the same as g_format_size().
	FormatSizeDefault FormatSizeFlags = 0b0
	// FormatSizeLongFormat: include the exact number of bytes as part of the
	// returned string. For example, "45.6 kB (45,612 bytes)".
	FormatSizeLongFormat FormatSizeFlags = 0b1
	// FormatSizeIecUnits: use IEC (base 1024) units with "KiB"-style suffixes.
	// IEC units should only be used for reporting things with a strong "power
	// of 2" basis, like RAM sizes or RAID stripe sizes. Network and storage
	// sizes should be reported in the normal SI units.
	FormatSizeIecUnits FormatSizeFlags = 0b10
	// FormatSizeBits: set the size as a quantity in bits, rather than bytes,
	// and return units in bits. For example, ‘Mb’ rather than ‘MB’.
	FormatSizeBits FormatSizeFlags = 0b100
)

func (FormatSizeFlags) Has

func (f FormatSizeFlags) Has(other FormatSizeFlags) bool

Has returns true if f contains other.

func (FormatSizeFlags) String

func (f FormatSizeFlags) String() string

String returns the names in string for FormatSizeFlags.

type Func

type Func func(data unsafe.Pointer)

Func specifies the type of functions passed to g_list_foreach() and g_slist_foreach().

type HFunc

type HFunc func(key, value unsafe.Pointer)

HFunc specifies the type of the function passed to g_hash_table_foreach(). It is called with each key/value pair, together with the user_data parameter which is passed to g_hash_table_foreach().

type HRFunc

type HRFunc func(key, value unsafe.Pointer) (ok bool)

HRFunc specifies the type of the function passed to g_hash_table_foreach_remove(). It is called with each key/value pair, together with the user_data parameter passed to g_hash_table_foreach_remove(). It should return TRUE if the key/value pair should be removed from the Table.

type HashTable

type HashTable struct {
	// contains filtered or unexported fields
}

HashTable struct is an opaque data structure to represent a [Hash Table][glib-Hash-Tables]. It should only be accessed via the following functions.

An instance of this type is always passed by reference.

type HashTableIter

type HashTableIter struct {
	// contains filtered or unexported fields
}

HashTableIter structure represents an iterator that can be used to iterate over the elements of a Table. GHashTableIter structures are typically allocated on the stack and then initialized with g_hash_table_iter_init().

The iteration order of a TableIter over the keys/values in a hash table is not defined.

An instance of this type is always passed by reference.

func (*HashTableIter) Init

func (iter *HashTableIter) Init(hashTable map[unsafe.Pointer]unsafe.Pointer)

Init initializes a key/value pair iterator and associates it with hash_table. Modifying the hash table after calling this function invalidates the returned iterator.

The iteration order of a TableIter over the keys/values in a hash table is not defined.

GHashTableIter iter;
gpointer key, value;

g_hash_table_iter_init (&iter, hash_table);
while (g_hash_table_iter_next (&iter, &key, &value))
  {
    // do something with key and value
  }.

The function takes the following parameters:

  • hashTable: Table.

func (*HashTableIter) Next

func (iter *HashTableIter) Next() (key unsafe.Pointer, value unsafe.Pointer, ok bool)

Next advances iter and retrieves the key and/or value that are now pointed to as a result of this advancement. If FALSE is returned, key and value are not set, and the iterator becomes invalid.

The function returns the following values:

  • key (optional): location to store the key.
  • value (optional): location to store the value.
  • ok: FALSE if the end of the Table has been reached.

func (*HashTableIter) Remove

func (iter *HashTableIter) Remove()

Remove removes the key/value pair currently pointed to by the iterator from its associated Table. Can only be called after g_hash_table_iter_next() returned TRUE, and cannot be called more than once for the same key/value pair.

If the Table 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.

It is safe to continue iterating the Table afterward:

while (g_hash_table_iter_next (&iter, &key, &value))
  {
    if (condition)
      g_hash_table_iter_remove (&iter);
  }.

func (*HashTableIter) Replace

func (iter *HashTableIter) Replace(value unsafe.Pointer)

Replace replaces the value currently pointed to by the iterator from its associated Table. Can only be called after g_hash_table_iter_next() returned TRUE.

If you supplied a value_destroy_func when creating the Table, the old value is freed using that function.

The function takes the following parameters:

  • value (optional) to replace with.

func (*HashTableIter) Steal

func (iter *HashTableIter) Steal()

Steal removes the key/value pair currently pointed to by the iterator from its associated Table, without calling the key and value destroy functions. Can only be called after g_hash_table_iter_next() returned TRUE, and cannot be called more than once for the same key/value pair.

type IOChannel

type IOChannel struct {
	// contains filtered or unexported fields
}

IOChannel: data structure representing an IO Channel. The fields should be considered private and should only be accessed with the following functions.

An instance of this type is always passed by reference.

func NewIOChannelFile

func NewIOChannelFile(filename string, mode string) (*IOChannel, error)

NewIOChannelFile constructs a struct IOChannel.

func NewIOChannelUnix

func NewIOChannelUnix(fd int) *IOChannel

NewIOChannelUnix constructs a struct IOChannel.

func (*IOChannel) BufferCondition

func (channel *IOChannel) BufferCondition() IOCondition

BufferCondition: this function returns a OCondition depending on whether there is data to be read/space to write data in the internal buffers in the OChannel. Only the flags G_IO_IN and G_IO_OUT may be set.

The function returns the following values:

  • ioCondition: OCondition.

func (*IOChannel) BufferSize

func (channel *IOChannel) BufferSize() uint

BufferSize gets the buffer size.

The function returns the following values:

  • gsize: size of the buffer.

func (*IOChannel) Buffered

func (channel *IOChannel) Buffered() bool

Buffered returns whether channel is buffered.

The function returns the following values:

  • ok: TRUE if the channel is buffered.

func (*IOChannel) Close deprecated

func (channel *IOChannel) Close()

Close an IO channel. Any pending data to be written will be flushed, ignoring errors. The channel will not be freed until the last reference is dropped using g_io_channel_unref().

Deprecated: Use g_io_channel_shutdown() instead.

func (*IOChannel) Encoding

func (channel *IOChannel) Encoding() string

Encoding gets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The encoding NULL makes the channel safe for binary data.

The function returns the following values:

  • utf8: string containing the encoding, this string is owned by GLib and must not be freed.

func (*IOChannel) Flags

func (channel *IOChannel) Flags() IOFlags

Flags gets the current flags for a OChannel, including read-only flags such as G_IO_FLAG_IS_READABLE.

The values of the flags G_IO_FLAG_IS_READABLE and G_IO_FLAG_IS_WRITABLE are cached for internal use by the channel when it is created. If they should change at some later point (e.g. partial shutdown of a socket with the UNIX shutdown() function), the user should immediately call g_io_channel_get_flags() to update the internal values of these flags.

The function returns the following values:

  • ioFlags flags which are set on the channel.

func (*IOChannel) Flush

func (channel *IOChannel) Flush() (IOStatus, error)

Flush flushes the write buffer for the GIOChannel.

The function returns the following values:

  • ioStatus status of the operation: One of IO_STATUS_NORMAL, IO_STATUS_AGAIN, or IO_STATUS_ERROR.

func (*IOChannel) Init

func (channel *IOChannel) Init()

Init initializes a OChannel struct.

This is called by each of the above functions when creating a OChannel, and so is not often needed by the application programmer (unless you are creating a new type of OChannel).

func (*IOChannel) LineTerm

func (channel *IOChannel) LineTerm(length *int) string

LineTerm: this returns the string that OChannel uses to determine where in the file a line break occurs. A value of NULL indicates autodetection.

The function takes the following parameters:

  • length: location to return the length of the line terminator.

The function returns the following values:

  • utf8: line termination string. This value is owned by GLib and must not be freed.

func (*IOChannel) ReadChars

func (channel *IOChannel) ReadChars(buf []byte) (uint, IOStatus, error)

ReadChars: replacement for g_io_channel_read() with the new API.

The function takes the following parameters:

  • buf: a buffer to read data into.

The function returns the following values:

  • bytesRead (optional): number of bytes read. This may be zero even on success if count < 6 and the channel's encoding is non-NULL. This indicates that the next UTF-8 character is too wide for the buffer.
  • ioStatus status of the operation.

func (*IOChannel) ReadLine

func (channel *IOChannel) ReadLine() (strReturn string, length uint, terminatorPos uint, ioStatus IOStatus, goerr error)

ReadLine reads a line, including the terminating character(s), from a OChannel into a newly-allocated string. str_return will contain allocated memory if the return is G_IO_STATUS_NORMAL.

The function returns the following values:

  • strReturn: line read from the OChannel, including the line terminator. This data should be freed with g_free() when no longer needed. This is a nul-terminated string. If a length of zero is returned, this will be NULL instead.
  • length (optional): location to store length of the read data, or NULL.
  • terminatorPos (optional): location to store position of line terminator, or NULL.
  • ioStatus status of the operation.

func (*IOChannel) ReadToEnd

func (channel *IOChannel) ReadToEnd() ([]byte, IOStatus, error)

ReadToEnd reads all the remaining data from the file.

The function returns the following values:

  • strReturn: location to store a pointer to a string holding the remaining data in the OChannel. This data should be freed with g_free() when no longer needed. This data is terminated by an extra nul character, but there may be other nuls in the intervening data.
  • ioStatus: G_IO_STATUS_NORMAL on success. This function never returns G_IO_STATUS_EOF.

func (*IOChannel) ReadUnichar

func (channel *IOChannel) ReadUnichar() (uint32, IOStatus, error)

ReadUnichar reads a Unicode character from channel. This function cannot be called on a channel with NULL encoding.

The function returns the following values:

  • thechar: location to return a character.
  • ioStatus: OStatus.

func (*IOChannel) Seek deprecated

func (channel *IOChannel) Seek(offset int64, typ SeekType) IOError

Seek sets the current position in the OChannel, similar to the standard library function fseek().

Deprecated: Use g_io_channel_seek_position() instead.

The function takes the following parameters:

  • offset: offset, in bytes, which is added to the position specified by type.
  • typ: position in the file, which can be G_SEEK_CUR (the current position), G_SEEK_SET (the start of the file), or G_SEEK_END (the end of the file).

The function returns the following values:

  • ioError: G_IO_ERROR_NONE if the operation was successful.

func (*IOChannel) SeekPosition

func (channel *IOChannel) SeekPosition(offset int64, typ SeekType) (IOStatus, error)

SeekPosition: replacement for g_io_channel_seek() with the new API.

The function takes the following parameters:

  • offset in bytes from the position specified by type.
  • typ The type G_SEEK_CUR is only allowed in those cases where a call to g_io_channel_set_encoding () is allowed. See the documentation for g_io_channel_set_encoding () for details.

The function returns the following values:

  • ioStatus status of the operation.

func (*IOChannel) SetBufferSize

func (channel *IOChannel) SetBufferSize(size uint)

SetBufferSize sets the buffer size.

The function takes the following parameters:

  • size of the buffer, or 0 to let GLib pick a good size.

func (*IOChannel) SetBuffered

func (channel *IOChannel) SetBuffered(buffered bool)

SetBuffered: buffering state can only be set if the channel's encoding is NULL. For any other encoding, the channel must be buffered.

A buffered channel can only be set unbuffered if the channel's internal buffers have been flushed. Newly created channels or channels which have returned G_IO_STATUS_EOF not require such a flush. For write-only channels, a call to g_io_channel_flush () is sufficient. For all other channels, the buffers may be flushed by a call to g_io_channel_seek_position (). This includes the possibility of seeking with seek type G_SEEK_CUR and an offset of zero. Note that this means that socket-based channels cannot be set unbuffered once they have had data read from them.

On unbuffered channels, it is safe to mix read and write calls from the new and old APIs, if this is necessary for maintaining old code.

The default state of the channel is buffered.

The function takes the following parameters:

  • buffered: whether to set the channel buffered or unbuffered.

func (*IOChannel) SetEncoding

func (channel *IOChannel) SetEncoding(encoding string) (IOStatus, error)

SetEncoding sets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The default encoding for the external file is UTF-8.

The encoding NULL is safe to use with binary data.

The encoding can only be set if one of the following conditions is true:

- The channel was just created, and has not been written to or read from yet.

- The channel is write-only.

- The channel is a file, and the file pointer was just repositioned by a call to g_io_channel_seek_position(). (This flushes all the internal buffers.)

- The current encoding is NULL or UTF-8.

- One of the (new API) read functions has just returned G_IO_STATUS_EOF (or, in the case of g_io_channel_read_to_end(), G_IO_STATUS_NORMAL).

- One of the functions g_io_channel_read_chars() or g_io_channel_read_unichar() has returned G_IO_STATUS_AGAIN or G_IO_STATUS_ERROR. This may be useful in the case of G_CONVERT_ERROR_ILLEGAL_SEQUENCE. Returning one of these statuses from g_io_channel_read_line(), g_io_channel_read_line_string(), or g_io_channel_read_to_end() does not guarantee that the encoding can be changed.

Channels which do not meet one of the above conditions cannot call g_io_channel_seek_position() with an offset of G_SEEK_CUR, and, if they are "seekable", cannot call g_io_channel_write_chars() after calling one of the API "read" functions.

The function takes the following parameters:

  • encoding (optional) type.

The function returns the following values:

  • ioStatus: G_IO_STATUS_NORMAL if the encoding was successfully set.

func (*IOChannel) SetFlags

func (channel *IOChannel) SetFlags(flags IOFlags) (IOStatus, error)

SetFlags sets the (writeable) flags in channel to (flags & G_IO_FLAG_SET_MASK).

The function takes the following parameters:

  • flags to set on the IO channel.

The function returns the following values:

  • ioStatus status of the operation.

func (*IOChannel) SetLineTerm

func (channel *IOChannel) SetLineTerm(lineTerm string, length int)

SetLineTerm: this sets the string that OChannel uses to determine where in the file a line break occurs.

The function takes the following parameters:

  • lineTerm (optional): line termination string. Use NULL for autodetect. Autodetection breaks on "\n", "\r\n", "\r", "\0", and the Unicode paragraph separator. Autodetection should not be used for anything other than file-based channels.
  • length of the termination string. If -1 is passed, the string is assumed to be nul-terminated. This option allows termination strings with embedded nuls.

func (*IOChannel) Shutdown

func (channel *IOChannel) Shutdown(flush bool) (IOStatus, error)

Shutdown: close an IO channel. Any pending data to be written will be flushed if flush is TRUE. The channel will not be freed until the last reference is dropped using g_io_channel_unref().

The function takes the following parameters:

  • flush: if TRUE, flush pending.

The function returns the following values:

  • ioStatus status of the operation.

func (*IOChannel) UnixGetFd

func (channel *IOChannel) UnixGetFd() int

UnixGetFd returns the file descriptor of the OChannel.

On Windows this function returns the file descriptor or socket of the OChannel.

The function returns the following values:

  • gint: file descriptor of the OChannel.

func (*IOChannel) Write deprecated

func (channel *IOChannel) Write(buf string, count uint, bytesWritten *uint) IOError

Write writes data to a OChannel.

Deprecated: Use g_io_channel_write_chars() instead.

The function takes the following parameters:

  • buf: buffer containing the data to write.
  • count: number of bytes to write.
  • bytesWritten: number of bytes actually written.

The function returns the following values:

  • ioError: G_IO_ERROR_NONE if the operation was successful.

func (*IOChannel) WriteChars

func (channel *IOChannel) WriteChars(buf string, count int) (uint, IOStatus, error)

WriteChars: replacement for g_io_channel_write() with the new API.

On seekable channels with encodings other than NULL or UTF-8, generic mixing of reading and writing is not allowed. A call to g_io_channel_write_chars () may only be made on a channel from which data has been read in the cases described in the documentation for g_io_channel_set_encoding ().

The function takes the following parameters:

  • buf: buffer to write data from.
  • count: size of the buffer. If -1, the buffer is taken to be a nul-terminated string.

The function returns the following values:

  • bytesWritten: number of bytes written. This can be nonzero even if the return value is not G_IO_STATUS_NORMAL. If the return value is G_IO_STATUS_NORMAL and the channel is blocking, this will always be equal to count if count >= 0.
  • ioStatus status of the operation.

func (*IOChannel) WriteUnichar

func (channel *IOChannel) WriteUnichar(thechar uint32) (IOStatus, error)

WriteUnichar writes a Unicode character to channel. This function cannot be called on a channel with NULL encoding.

The function takes the following parameters:

  • thechar: character.

The function returns the following values:

  • ioStatus: OStatus.

type IOChannelError

type IOChannelError C.gint

IOChannelError: error codes returned by OChannel operations.

const (
	// IOChannelErrorFbig: file too large.
	IOChannelErrorFbig IOChannelError = iota
	// IOChannelErrorInval: invalid argument.
	IOChannelErrorInval
	// IOChannelErrorIO: IO error.
	IOChannelErrorIO
	// IOChannelErrorIsdir: file is a directory.
	IOChannelErrorIsdir
	// IOChannelErrorNospc: no space left on device.
	IOChannelErrorNospc
	// IOChannelErrorNxio: no such device or address.
	IOChannelErrorNxio
	// IOChannelErrorOverflow: value too large for defined datatype.
	IOChannelErrorOverflow
	// IOChannelErrorPipe: broken pipe.
	IOChannelErrorPipe
	// IOChannelErrorFailed: some other error.
	IOChannelErrorFailed
)

func IOChannelErrorFromErrno

func IOChannelErrorFromErrno(en int) IOChannelError

IOChannelErrorFromErrno converts an errno error number to a OChannelError.

The function takes the following parameters:

  • en: errno error number, e.g. EINVAL.

The function returns the following values:

  • ioChannelError error number, e.g. G_IO_CHANNEL_ERROR_INVAL.

func (IOChannelError) String

func (i IOChannelError) String() string

String returns the name in string for IOChannelError.

type IOCondition

type IOCondition C.guint

IOCondition: bitwise combination representing a condition to watch for on an event source.

const (
	// IOIn: there is data to read.
	IOIn IOCondition = 0b1
	// IOOut: data can be written (without blocking).
	IOOut IOCondition = 0b100
	// IOPri: there is urgent data to read.
	IOPri IOCondition = 0b10
	// IOErr: error condition.
	IOErr IOCondition = 0b1000
	// IOHup: hung up (the connection has been broken, usually for pipes and
	// sockets).
	IOHup IOCondition = 0b10000
	// IONval: invalid request. The file descriptor is not open.
	IONval IOCondition = 0b100000
)

func (IOCondition) Has

func (i IOCondition) Has(other IOCondition) bool

Has returns true if i contains other.

func (IOCondition) String

func (i IOCondition) String() string

String returns the names in string for IOCondition.

type IOError

type IOError C.gint

IOError is only used by the deprecated functions g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().

const (
	// IOErrorNone: no error.
	IOErrorNone IOError = iota
	// IOErrorAgain: EAGAIN error occurred.
	IOErrorAgain
	// IOErrorInval: EINVAL error occurred.
	IOErrorInval
	// IOErrorUnknown: another error occurred.
	IOErrorUnknown
)

func (IOError) String

func (i IOError) String() string

String returns the name in string for IOError.

type IOFlags

type IOFlags C.guint

IOFlags specifies properties of a OChannel. Some of the flags can only be read with g_io_channel_get_flags(), but not changed with g_io_channel_set_flags().

const (
	// IOFlagAppend turns on append mode, corresponds to O_APPEND (see the
	// documentation of the UNIX open() syscall).
	IOFlagAppend IOFlags = 0b1
	// IOFlagNonblock turns on nonblocking mode, corresponds to
	// O_NONBLOCK/O_NDELAY (see the documentation of the UNIX open() syscall).
	IOFlagNonblock IOFlags = 0b10
	// IOFlagIsReadable indicates that the io channel is readable. This flag
	// cannot be changed.
	IOFlagIsReadable IOFlags = 0b100
	// IOFlagIsWritable indicates that the io channel is writable. This flag
	// cannot be changed.
	IOFlagIsWritable IOFlags = 0b1000
	// IOFlagIsWriteable: misspelled version of G_IO_FLAG_IS_WRITABLE that
	// existed before the spelling was fixed in GLib 2.30. It is kept here for
	// compatibility reasons. Deprecated since 2.30.
	IOFlagIsWriteable IOFlags = 0b1000
	// IOFlagIsSeekable indicates that the io channel is seekable, i.e.
	// that g_io_channel_seek_position() can be used on it. This flag cannot be
	// changed.
	IOFlagIsSeekable IOFlags = 0b10000
	// IOFlagMask: mask that specifies all the valid flags.
	IOFlagMask IOFlags = 0b11111
	// IOFlagGetMask: mask of the flags that are returned from
	// g_io_channel_get_flags().
	IOFlagGetMask IOFlags = 0b11111
	// IOFlagSetMask: mask of the flags that the user can modify with
	// g_io_channel_set_flags().
	IOFlagSetMask IOFlags = 0b11
)

func (IOFlags) Has

func (i IOFlags) Has(other IOFlags) bool

Has returns true if i contains other.

func (IOFlags) String

func (i IOFlags) String() string

String returns the names in string for IOFlags.

type IOFuncs

type IOFuncs struct {
	// contains filtered or unexported fields
}

IOFuncs: table of functions used to handle different types of OChannel in a generic way.

An instance of this type is always passed by reference.

type IOStatus

type IOStatus C.gint

IOStatus statuses returned by most of the OFuncs functions.

const (
	// IOStatusError: error occurred.
	IOStatusError IOStatus = iota
	// IOStatusNormal: success.
	IOStatusNormal
	// IOStatusEOF: end of file.
	IOStatusEOF
	// IOStatusAgain: resource temporarily unavailable.
	IOStatusAgain
)

func (IOStatus) String

func (i IOStatus) String() string

String returns the name in string for IOStatus.

type KeyFile

type KeyFile struct {
	// contains filtered or unexported fields
}

KeyFile struct contains only private data and should not be accessed directly.

An instance of this type is always passed by reference.

func NewKeyFile

func NewKeyFile() *KeyFile

NewKeyFile constructs a struct KeyFile.

func (*KeyFile) Boolean

func (keyFile *KeyFile) Boolean(groupName string, key string) error

Boolean returns the value associated with key under group_name as a boolean.

If key cannot be found then FALSE is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as a boolean then FALSE is returned and error is set to KEY_FILE_ERROR_INVALID_VALUE.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

func (*KeyFile) BooleanList

func (keyFile *KeyFile) BooleanList(groupName string, key string) ([]bool, error)

BooleanList returns the values associated with key under group_name as booleans.

If key cannot be found then NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as booleans then NULL is returned and error is set to KEY_FILE_ERROR_INVALID_VALUE.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • oks: the values associated with the key as a list of booleans, or NULL if the key was not found or could not be parsed. The returned list of booleans should be freed with g_free() when no longer needed.

func (*KeyFile) Comment

func (keyFile *KeyFile) Comment(groupName string, key string) (string, error)

Comment retrieves a comment above key from group_name. If key is NULL then comment will be read from above group_name. If both key and group_name are NULL, then comment will be read from above the first group in the file.

Note that the returned string does not include the '#' comment markers, but does include any whitespace after them (on each line). It includes the line breaks between lines, but does not include the final line break.

The function takes the following parameters:

  • groupName (optional): group name, or NULL.
  • key (optional): key.

The function returns the following values:

  • utf8: comment that should be freed with g_free().

func (*KeyFile) Double

func (keyFile *KeyFile) Double(groupName string, key string) (float64, error)

Double returns the value associated with key under group_name as a double. If group_name is NULL, the start_group is used.

If key cannot be found then 0.0 is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as a double then 0.0 is returned and error is set to KEY_FILE_ERROR_INVALID_VALUE.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • gdouble: value associated with the key as a double, or 0.0 if the key was not found or could not be parsed.

func (*KeyFile) DoubleList

func (keyFile *KeyFile) DoubleList(groupName string, key string) ([]float64, error)

DoubleList returns the values associated with key under group_name as doubles.

If key cannot be found then NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as doubles then NULL is returned and error is set to KEY_FILE_ERROR_INVALID_VALUE.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • gdoubles: the values associated with the key as a list of doubles, or NULL if the key was not found or could not be parsed. The returned list of doubles should be freed with g_free() when no longer needed.

func (*KeyFile) Groups

func (keyFile *KeyFile) Groups() (uint, []string)

Groups returns all groups in the key file loaded with key_file. The array of returned groups will be NULL-terminated, so length may optionally be NULL.

The function returns the following values:

  • length (optional): return location for the number of returned groups, or NULL.
  • utf8s: newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

func (*KeyFile) HasGroup

func (keyFile *KeyFile) HasGroup(groupName string) bool

HasGroup looks whether the key file has the group group_name.

The function takes the following parameters:

  • groupName: group name.

The function returns the following values:

  • ok: TRUE if group_name is a part of key_file, FALSE otherwise.

func (*KeyFile) Int64

func (keyFile *KeyFile) Int64(groupName string, key string) (int64, error)

Int64 returns the value associated with key under group_name as a signed 64-bit integer. This is similar to g_key_file_get_integer() but can return 64-bit results without truncation.

The function takes the following parameters:

  • groupName: non-NULL group name.
  • key: non-NULL key.

The function returns the following values:

  • gint64: value associated with the key as a signed 64-bit integer, or 0 if the key was not found or could not be parsed.

func (*KeyFile) Integer

func (keyFile *KeyFile) Integer(groupName string, key string) (int, error)

Integer returns the value associated with key under group_name as an integer.

If key cannot be found then 0 is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as an integer, or is out of range for a #gint, then 0 is returned and error is set to KEY_FILE_ERROR_INVALID_VALUE.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • gint: value associated with the key as an integer, or 0 if the key was not found or could not be parsed.

func (*KeyFile) IntegerList

func (keyFile *KeyFile) IntegerList(groupName string, key string) ([]int, error)

IntegerList returns the values associated with key under group_name as integers.

If key cannot be found then NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as integers, or are out of range for #gint, then NULL is returned and error is set to KEY_FILE_ERROR_INVALID_VALUE.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • gints: the values associated with the key as a list of integers, or NULL if the key was not found or could not be parsed. The returned list of integers should be freed with g_free() when no longer needed.

func (*KeyFile) Keys

func (keyFile *KeyFile) Keys(groupName string) (uint, []string, error)

Keys returns all keys for the group name group_name. The array of returned keys will be NULL-terminated, so length may optionally be NULL. In the event that the group_name cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_GROUP_NOT_FOUND.

The function takes the following parameters:

  • groupName: group name.

The function returns the following values:

  • length (optional): return location for the number of keys returned, or NULL.
  • utf8s: newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

func (*KeyFile) LoadFromBytes

func (keyFile *KeyFile) LoadFromBytes(bytes *Bytes, flags KeyFileFlags) error

LoadFromBytes loads a key file from the data in bytes into an empty File structure. If the object cannot be created then error is set to a FileError.

The function takes the following parameters:

  • bytes: #GBytes.
  • flags from FileFlags.

func (*KeyFile) LoadFromData

func (keyFile *KeyFile) LoadFromData(data string, length uint, flags KeyFileFlags) error

LoadFromData loads a key file from memory into an empty File structure. If the object cannot be created then error is set to a FileError.

The function takes the following parameters:

  • data: key file loaded in memory.
  • length of data in bytes (or (gsize)-1 if data is nul-terminated).
  • flags from FileFlags.

func (*KeyFile) LoadFromDataDirs

func (keyFile *KeyFile) LoadFromDataDirs(file string, flags KeyFileFlags) (string, error)

LoadFromDataDirs: this function looks for a key file named file in the paths returned from g_get_user_data_dir() and g_get_system_data_dirs(), loads the file into key_file and returns the file's full path in full_path. If the file could not be loaded then an error is set to either a Error or FileError.

The function takes the following parameters:

  • file: relative path to a filename to open and parse.
  • flags from FileFlags.

The function returns the following values:

  • fullPath (optional): return location for a string containing the full path of the file, or NULL.

func (*KeyFile) LoadFromDirs

func (keyFile *KeyFile) LoadFromDirs(file string, searchDirs []string, flags KeyFileFlags) (string, error)

LoadFromDirs: this function looks for a key file named file in the paths specified in search_dirs, loads the file into key_file and returns the file's full path in full_path.

If the file could not be found in any of the search_dirs, G_KEY_FILE_ERROR_NOT_FOUND is returned. If the file is found but the OS returns an error when opening or reading the file, a G_FILE_ERROR is returned. If there is a problem parsing the file, a G_KEY_FILE_ERROR is returned.

The function takes the following parameters:

  • file: relative path to a filename to open and parse.
  • searchDirs: NULL-terminated array of directories to search.
  • flags from FileFlags.

The function returns the following values:

  • fullPath (optional): return location for a string containing the full path of the file, or NULL.

func (*KeyFile) LoadFromFile

func (keyFile *KeyFile) LoadFromFile(file string, flags KeyFileFlags) error

LoadFromFile loads a key file into an empty File structure.

If the OS returns an error when opening or reading the file, a G_FILE_ERROR is returned. If there is a problem parsing the file, a G_KEY_FILE_ERROR is returned.

This function will never return a G_KEY_FILE_ERROR_NOT_FOUND error. If the file is not found, G_FILE_ERROR_NOENT is returned.

The function takes the following parameters:

  • file: path of a filename to load, in the GLib filename encoding.
  • flags from FileFlags.

func (*KeyFile) LocaleForKey

func (keyFile *KeyFile) LocaleForKey(groupName string, key string, locale string) string

LocaleForKey returns the actual locale which the result of g_key_file_get_locale_string() or g_key_file_get_locale_string_list() came from.

If calling g_key_file_get_locale_string() or g_key_file_get_locale_string_list() with exactly the same key_file, group_name, key and locale, the result of those functions will have originally been tagged with the locale that is the result of this function.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • locale (optional) identifier or NULL.

The function returns the following values:

  • utf8 (optional): locale from the file, or NULL if the key was not found or the entry in the file was was untranslated.

func (*KeyFile) LocaleString

func (keyFile *KeyFile) LocaleString(groupName string, key string, locale string) (string, error)

LocaleString returns the value associated with key under group_name translated in the given locale if available. If locale is NULL then the current locale is assumed.

If locale is to be non-NULL, or if the current locale will change over the lifetime of the File, it must be loaded with G_KEY_FILE_KEEP_TRANSLATIONS in order to load strings for all locales.

If key cannot be found then NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. If the value associated with key cannot be interpreted or no suitable translation can be found then the untranslated value is returned.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • locale (optional) identifier or NULL.

The function returns the following values:

  • utf8: newly allocated string or NULL if the specified key cannot be found.

func (*KeyFile) LocaleStringList

func (keyFile *KeyFile) LocaleStringList(groupName string, key string, locale string) ([]string, error)

LocaleStringList returns the values associated with key under group_name translated in the given locale if available. If locale is NULL then the current locale is assumed.

If locale is to be non-NULL, or if the current locale will change over the lifetime of the File, it must be loaded with G_KEY_FILE_KEEP_TRANSLATIONS in order to load strings for all locales.

If key cannot be found then NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. If the values associated with key cannot be interpreted or no suitable translations can be found then the untranslated values are returned. The returned array is NULL-terminated, so length may optionally be NULL.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • locale (optional) identifier or NULL.

The function returns the following values:

  • utf8s: newly allocated NULL-terminated string array or NULL if the key isn't found. The string array should be freed with g_strfreev().

func (*KeyFile) RemoveComment

func (keyFile *KeyFile) RemoveComment(groupName string, key string) error

RemoveComment removes a comment above key from group_name. If key is NULL then comment will be removed above group_name. If both key and group_name are NULL, then comment will be removed above the first group in the file.

The function takes the following parameters:

  • groupName (optional): group name, or NULL.
  • key (optional): key.

func (*KeyFile) RemoveGroup

func (keyFile *KeyFile) RemoveGroup(groupName string) error

RemoveGroup removes the specified group, group_name, from the key file.

The function takes the following parameters:

  • groupName: group name.

func (*KeyFile) RemoveKey

func (keyFile *KeyFile) RemoveKey(groupName string, key string) error

RemoveKey removes key in group_name from the key file.

The function takes the following parameters:

  • groupName: group name.
  • key name to remove.

func (*KeyFile) SaveToFile

func (keyFile *KeyFile) SaveToFile(filename string) error

SaveToFile writes the contents of key_file to filename using g_file_set_contents(). If you need stricter guarantees about durability of the written file than are provided by g_file_set_contents(), use g_file_set_contents_full() with the return value of g_key_file_to_data().

This function can fail for any of the reasons that g_file_set_contents() may fail.

The function takes the following parameters:

  • filename: name of the file to write to.

func (*KeyFile) SetBoolean

func (keyFile *KeyFile) SetBoolean(groupName string, key string, value bool)

SetBoolean associates a new boolean value with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • value: TRUE or FALSE.

func (*KeyFile) SetBooleanList

func (keyFile *KeyFile) SetBooleanList(groupName string, key string, list []bool)

SetBooleanList associates a list of boolean values with key under group_name. If key cannot be found then it is created. If group_name is NULL, the start_group is used.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • list: array of boolean values.

func (*KeyFile) SetComment

func (keyFile *KeyFile) SetComment(groupName string, key string, comment string) error

SetComment places a comment above key from group_name.

If key is NULL then comment will be written above group_name. If both key and group_name are NULL, then comment will be written above the first group in the file.

Note that this function prepends a '#' comment marker to each line of comment.

The function takes the following parameters:

  • groupName (optional): group name, or NULL.
  • key (optional): key.
  • comment: comment.

func (*KeyFile) SetDouble

func (keyFile *KeyFile) SetDouble(groupName string, key string, value float64)

SetDouble associates a new double value with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • value: double value.

func (*KeyFile) SetDoubleList

func (keyFile *KeyFile) SetDoubleList(groupName string, key string, list []float64)

SetDoubleList associates a list of double values with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • list: array of double values.

func (*KeyFile) SetInt64

func (keyFile *KeyFile) SetInt64(groupName string, key string, value int64)

SetInt64 associates a new integer value with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • value: integer value.

func (*KeyFile) SetInteger

func (keyFile *KeyFile) SetInteger(groupName string, key string, value int)

SetInteger associates a new integer value with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • value: integer value.

func (*KeyFile) SetIntegerList

func (keyFile *KeyFile) SetIntegerList(groupName string, key string, list []int)

SetIntegerList associates a list of integer values with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • list: array of integer values.

func (*KeyFile) SetListSeparator

func (keyFile *KeyFile) SetListSeparator(separator byte)

SetListSeparator sets the character which is used to separate values in lists. Typically ';' or ',' are used as separators. The default list separator is ';'.

The function takes the following parameters:

  • separator: separator.

func (*KeyFile) SetLocaleString

func (keyFile *KeyFile) SetLocaleString(groupName string, key string, locale string, str string)

SetLocaleString associates a string value for key and locale under group_name. If the translation for key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • locale identifier.
  • str: string.

func (*KeyFile) SetLocaleStringList

func (keyFile *KeyFile) SetLocaleStringList(groupName string, key string, locale string, list []string)

SetLocaleStringList associates a list of string values for key and locale under group_name. If the translation for key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • locale identifier.
  • list: NULL-terminated array of locale string values.

func (*KeyFile) SetString

func (keyFile *KeyFile) SetString(groupName string, key string, str string)

SetString associates a new string value with key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created. Unlike g_key_file_set_value(), this function handles characters that need escaping, such as newlines.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • str: string.

func (*KeyFile) SetStringList

func (keyFile *KeyFile) SetStringList(groupName string, key string, list []string)

SetStringList associates a list of string values for key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • list: array of string values.

func (*KeyFile) SetUint64

func (keyFile *KeyFile) SetUint64(groupName string, key string, value uint64)

SetUint64 associates a new integer value with key under group_name. If key cannot be found then it is created.

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • value: integer value.

func (*KeyFile) SetValue

func (keyFile *KeyFile) SetValue(groupName string, key string, value string)

SetValue associates a new value with key under group_name.

If key cannot be found then it is created. If group_name cannot be found then it is created. To set an UTF-8 string which may contain characters that need escaping (such as newlines or spaces), use g_key_file_set_string().

The function takes the following parameters:

  • groupName: group name.
  • key: key.
  • value: string.

func (*KeyFile) StartGroup

func (keyFile *KeyFile) StartGroup() string

StartGroup returns the name of the start group of the file.

The function returns the following values:

  • utf8 (optional): start group of the key file.

func (*KeyFile) String

func (keyFile *KeyFile) String(groupName string, key string) (string, error)

String returns the string value associated with key under group_name. Unlike g_key_file_get_value(), this function handles escape sequences like \s.

In the event the key cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_GROUP_NOT_FOUND.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • utf8: newly allocated string or NULL if the specified key cannot be found.

func (*KeyFile) StringList

func (keyFile *KeyFile) StringList(groupName string, key string) ([]string, error)

StringList returns the values associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_GROUP_NOT_FOUND.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • utf8s: a NULL-terminated string array or NULL if the specified key cannot be found. The array should be freed with g_strfreev().

func (*KeyFile) ToData

func (keyFile *KeyFile) ToData() (uint, string, error)

ToData: this function outputs key_file as a string.

Note that this function never reports an error, so it is safe to pass NULL as error.

The function returns the following values:

  • length (optional): return location for the length of the returned string, or NULL.
  • utf8: newly allocated string holding the contents of the File.

func (*KeyFile) Uint64

func (keyFile *KeyFile) Uint64(groupName string, key string) (uint64, error)

Uint64 returns the value associated with key under group_name as an unsigned 64-bit integer. This is similar to g_key_file_get_integer() but can return large positive results without truncation.

The function takes the following parameters:

  • groupName: non-NULL group name.
  • key: non-NULL key.

The function returns the following values:

  • guint64: value associated with the key as an unsigned 64-bit integer, or 0 if the key was not found or could not be parsed.

func (*KeyFile) Value

func (keyFile *KeyFile) Value(groupName string, key string) (string, error)

Value returns the raw value associated with key under group_name. Use g_key_file_get_string() to retrieve an unescaped UTF-8 string.

In the event the key cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to KEY_FILE_ERROR_GROUP_NOT_FOUND.

The function takes the following parameters:

  • groupName: group name.
  • key: key.

The function returns the following values:

  • utf8: newly allocated string or NULL if the specified key cannot be found.

type KeyFileError

type KeyFileError C.gint

KeyFileError: error codes returned by key file parsing.

const (
	// KeyFileErrorUnknownEncoding: text being parsed was in an unknown
	// encoding.
	KeyFileErrorUnknownEncoding KeyFileError = iota
	// KeyFileErrorParse: document was ill-formed.
	KeyFileErrorParse
	// KeyFileErrorNotFound: file was not found.
	KeyFileErrorNotFound
	// KeyFileErrorKeyNotFound: requested key was not found.
	KeyFileErrorKeyNotFound
	// KeyFileErrorGroupNotFound: requested group was not found.
	KeyFileErrorGroupNotFound
	// KeyFileErrorInvalidValue: value could not be parsed.
	KeyFileErrorInvalidValue
)

func (KeyFileError) String

func (k KeyFileError) String() string

String returns the name in string for KeyFileError.

type KeyFileFlags

type KeyFileFlags C.guint

KeyFileFlags flags which influence the parsing.

const (
	// KeyFileNone: no flags, default behaviour.
	KeyFileNone KeyFileFlags = 0b0
	// KeyFileKeepComments: use this flag if you plan to write the (possibly
	// modified) contents of the key file back to a file; otherwise all comments
	// will be lost when the key file is written back.
	KeyFileKeepComments KeyFileFlags = 0b1
	// KeyFileKeepTranslations: use this flag if you plan to write the (possibly
	// modified) contents of the key file back to a file; otherwise only the
	// translations for the current language will be written back.
	KeyFileKeepTranslations KeyFileFlags = 0b10
)

func (KeyFileFlags) Has

func (k KeyFileFlags) Has(other KeyFileFlags) bool

Has returns true if k contains other.

func (KeyFileFlags) String

func (k KeyFileFlags) String() string

String returns the names in string for KeyFileFlags.

type LogField

type LogField struct {
	// contains filtered or unexported fields
}

LogField: structure representing a single field in a structured log entry. See g_log_structured() for details.

Log fields may contain arbitrary values, including binary with embedded nul bytes. If the field contains a string, the string must be UTF-8 encoded and have a trailing nul byte. Otherwise, length must be set to a non-negative value.

An instance of this type is always passed by reference.

func (*LogField) Key

func (l *LogField) Key() string

Key: field name (UTF-8 string).

func (*LogField) Value

func (l *LogField) Value() string

Value returns the field's value.

type LogFunc

type LogFunc func(logDomain string, logLevel LogLevelFlags, message string)

LogFunc specifies the prototype of log handler functions.

The default log handler, g_log_default_handler(), automatically appends a new-line character to message when printing it. It is advised that any custom log handler functions behave similarly, so that logging calls in user code do not need modifying to add a new-line character to the message if the log handler is changed.

This is not used if structured logging is enabled; see [Using Structured Logging][using-structured-logging].

type LogLevelFlags

type LogLevelFlags C.guint

LogLevelFlags flags specifying the level of log messages.

It is possible to change how GLib treats messages of the various levels using g_log_set_handler() and g_log_set_fatal_mask().

const (
	// LogFlagRecursion: internal flag.
	LogFlagRecursion LogLevelFlags = 0b1
	// LogFlagFatal: internal flag.
	LogFlagFatal LogLevelFlags = 0b10
	// LogLevelError: log level for errors, see g_error(). This level is also
	// used for messages produced by g_assert().
	LogLevelError LogLevelFlags = 0b100
	// LogLevelCritical: log level for critical warning messages,
	// see g_critical(). This level is also used for messages produced by
	// g_return_if_fail() and g_return_val_if_fail().
	LogLevelCritical LogLevelFlags = 0b1000
	// LogLevelWarning: log level for warnings, see g_warning().
	LogLevelWarning LogLevelFlags = 0b10000
	// LogLevelMessage: log level for messages, see g_message().
	LogLevelMessage LogLevelFlags = 0b100000
	// LogLevelInfo: log level for informational messages, see g_info().
	LogLevelInfo LogLevelFlags = 0b1000000
	// LogLevelDebug: log level for debug messages, see g_debug().
	LogLevelDebug LogLevelFlags = 0b10000000
)

func LogSetAlwaysFatal

func LogSetAlwaysFatal(fatalMask LogLevelFlags) LogLevelFlags

LogSetAlwaysFatal 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. G_LOG_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 (glib-running.html)).

Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

Structured log messages (using g_log_structured() and g_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][using-structured-logging].

The function takes the following parameters:

  • fatalMask: mask containing bits set for each level of error which is to be fatal.

The function returns the following values:

  • logLevelFlags: old fatal mask.

func LogSetFatalMask

func LogSetFatalMask(logDomain string, fatalMask LogLevelFlags) LogLevelFlags

LogSetFatalMask sets the log levels which are fatal in the given domain. G_LOG_LEVEL_ERROR is always fatal.

This has no effect on structured log messages (using g_log_structured() or g_log_structured_array()). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using g_log_set_writer_func(). See [Using Structured Logging][using-structured-logging].

This function is mostly intended to be used with G_LOG_LEVEL_CRITICAL. You should typically not set G_LOG_LEVEL_WARNING, G_LOG_LEVEL_MESSAGE, G_LOG_LEVEL_INFO or G_LOG_LEVEL_DEBUG as fatal except inside of test programs.

The function takes the following parameters:

  • logDomain: log domain.
  • fatalMask: new fatal mask.

The function returns the following values:

  • logLevelFlags: old fatal mask for the log domain.

func (LogLevelFlags) Has

func (l LogLevelFlags) Has(other LogLevelFlags) bool

Has returns true if l contains other.

func (LogLevelFlags) String

func (l LogLevelFlags) String() string

String returns the names in string for LogLevelFlags.

type LogWriterFunc

type LogWriterFunc func(logLevel LogLevelFlags, fields []LogField) (logWriterOutput LogWriterOutput)

LogWriterFunc: writer function for log entries. A log entry is a collection of one or more Fields, using the standard [field names from journal specification](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html). See g_log_structured() for more information.

Writer functions must ignore fields which they do not recognise, unless they can write arbitrary binary output, as field values may be arbitrary binary.

log_level is guaranteed to be included in fields as the PRIORITY field, but is provided separately for convenience of deciding whether or where to output the log entry.

Writer functions should return G_LOG_WRITER_HANDLED if they handled the log message successfully or if they deliberately ignored it. If there was an error handling the message (for example, if the writer function is meant to send messages to a remote logging server and there is a network error), it should return G_LOG_WRITER_UNHANDLED. This allows writer functions to be chained and fall back to simpler handlers in case of failure.

type LogWriterOutput

type LogWriterOutput C.gint

LogWriterOutput: return values from WriterFuncs to indicate whether the given log entry was successfully handled by the writer, or whether there was an error in handling it (and hence a fallback writer should be used).

If a WriterFunc ignores a log entry, it should return G_LOG_WRITER_HANDLED.

const (
	// LogWriterHandled: log writer has handled the log entry.
	LogWriterHandled LogWriterOutput = 1
	// LogWriterUnhandled: log writer could not handle the log entry.
	LogWriterUnhandled LogWriterOutput = 0
)

func LogWriterDefault

func LogWriterDefault(logLevel LogLevelFlags, fields []LogField, userData unsafe.Pointer) LogWriterOutput

LogWriterDefault: format a structured log message and output it to the default log destination for the platform. On Linux, this is typically the systemd journal, falling back to stdout or stderr if running from the terminal or if output is being redirected to a file.

Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.

This is suitable for use as a WriterFunc, and is the default writer used if no other is set using g_log_set_writer_func().

As with g_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.

g_log_writer_default() uses the mask set by g_log_set_always_fatal() to determine which messages are fatal. When using a custom writer func instead it is up to the writer function to determine which log messages are fatal.

The function takes the following parameters:

  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • fields: key–value pairs of structured data forming the log message.
  • userData (optional): user data passed to g_log_set_writer_func().

The function returns the following values:

  • logWriterOutput: G_LOG_WRITER_HANDLED on success, G_LOG_WRITER_UNHANDLED otherwise.

func LogWriterJournald

func LogWriterJournald(logLevel LogLevelFlags, fields []LogField, userData unsafe.Pointer) LogWriterOutput

LogWriterJournald: format a structured log message and send it to the systemd journal as a set of key–value pairs. All fields are sent to the journal, but if a field has length zero (indicating program-specific data) then only its key will be sent.

This is suitable for use as a WriterFunc.

If GLib has been compiled without systemd support, this function is still defined, but will always return G_LOG_WRITER_UNHANDLED.

The function takes the following parameters:

  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • fields: key–value pairs of structured data forming the log message.
  • userData (optional): user data passed to g_log_set_writer_func().

The function returns the following values:

  • logWriterOutput: G_LOG_WRITER_HANDLED on success, G_LOG_WRITER_UNHANDLED otherwise.

func LogWriterStandardStreams

func LogWriterStandardStreams(logLevel LogLevelFlags, fields []LogField, userData unsafe.Pointer) LogWriterOutput

LogWriterStandardStreams: format a structured log message and print it to either stdout or stderr, depending on its log level. G_LOG_LEVEL_INFO and G_LOG_LEVEL_DEBUG messages are sent to stdout, or to stderr if requested by g_log_writer_default_set_use_stderr(); all other log levels are sent to stderr. Only fields which are understood by this function are included in the formatted string which is printed.

If the output stream supports ANSI color escape sequences, they will be used in the output.

A trailing new-line character is added to the log message when it is printed.

This is suitable for use as a WriterFunc.

The function takes the following parameters:

  • logLevel: log level, either from LevelFlags, or a user-defined level.
  • fields: key–value pairs of structured data forming the log message.
  • userData (optional): user data passed to g_log_set_writer_func().

The function returns the following values:

  • logWriterOutput: G_LOG_WRITER_HANDLED on success, G_LOG_WRITER_UNHANDLED otherwise.

func (LogWriterOutput) String

func (l LogWriterOutput) String() string

String returns the name in string for LogWriterOutput.

type MainContext

type MainContext struct {
	// contains filtered or unexported fields
}

MainContext: GMainContext struct is an opaque data type representing a set of sources to be handled in a main loop.

An instance of this type is always passed by reference.

func MainContextDefault

func MainContextDefault() *MainContext

MainContextDefault 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 g_main_context_get_thread_default().

The function returns the following values:

  • mainContext: global default main context.

func MainContextGetThreadDefault

func MainContextGetThreadDefault() *MainContext

MainContextGetThreadDefault gets the thread-default 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 g_main_context_ref_thread_default() to get a Context to add their #GSources 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 g_main_context_ref_thread_default() instead.

The function returns the following values:

  • mainContext (optional): thread-default Context, or NULL if the thread-default context is the global default context.

func MainContextRefThreadDefault

func MainContextRefThreadDefault() *MainContext

MainContextRefThreadDefault gets the thread-default Context for this thread, as with g_main_context_get_thread_default(), but also adds a reference to it with g_main_context_ref(). In addition, unlike g_main_context_get_thread_default(), if the thread-default context is the global default context, this will return that Context (with a ref added to it) rather than returning NULL.

The function returns the following values:

  • mainContext: thread-default Context. Unref with g_main_context_unref() when you are done with it.

func NewMainContext

func NewMainContext() *MainContext

NewMainContext constructs a struct MainContext.

func (*MainContext) Acquire

func (context *MainContext) Acquire() bool

Acquire tries to become the owner of the specified context. If some other thread is the owner of the context, returns FALSE immediately. Ownership is properly recursive: the owner can require ownership again and will release ownership when g_main_context_release() is called as many times as g_main_context_acquire().

You must be the owner of a context before you can call g_main_context_prepare(), g_main_context_query(), g_main_context_check(), g_main_context_dispatch().

The function returns the following values:

  • ok: TRUE if the operation succeeded, and this thread is now the owner of context.

func (*MainContext) Dispatch

func (context *MainContext) Dispatch()

Dispatch dispatches all pending sources.

You must have successfully acquired the context with g_main_context_acquire() before you may call this function.

func (*MainContext) FindSourceByFuncsUserData

func (context *MainContext) FindSourceByFuncsUserData(funcs *SourceFuncs, userData unsafe.Pointer) *Source

FindSourceByFuncsUserData finds a source with the given source functions and user data. If multiple sources exist with the same source function and user data, the first one found will be returned.

The function takes the following parameters:

  • funcs passed to g_source_new().
  • userData (optional): user data from the callback.

The function returns the following values:

  • source: source, if one was found, otherwise NULL.

func (*MainContext) FindSourceByID

func (context *MainContext) FindSourceByID(sourceId uint) *Source

FindSourceByID finds a #GSource given a pair of context and ID.

It is a programmer error to attempt to look up 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 g_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.

The function takes the following parameters:

  • sourceId: source ID, as returned by g_source_get_id().

The function returns the following values:

  • source: #GSource.

func (*MainContext) FindSourceByUserData

func (context *MainContext) FindSourceByUserData(userData unsafe.Pointer) *Source

FindSourceByUserData finds a source with the given user data for the callback. If multiple sources exist with the same user data, the first one found will be returned.

The function takes the following parameters:

  • userData (optional): user_data for the callback.

The function returns the following values:

  • source: source, if one was found, otherwise NULL.

func (*MainContext) InvokeFull

func (context *MainContext) InvokeFull(priority int, function SourceFunc)

InvokeFull invokes a function in such a way that context is owned during the invocation of function.

This function is the same as g_main_context_invoke() except that it lets you specify the priority in case function ends up being scheduled as an idle and also lets you give a Notify for data.

notify should not assume that it is called from any particular thread or with any particular context acquired.

The function takes the following parameters:

  • priority at which to run function.
  • function to call.

func (*MainContext) IsOwner

func (context *MainContext) IsOwner() bool

IsOwner determines whether this thread holds the (recursive) ownership of this Context. This is useful to know before waiting on another thread that may be blocking to get ownership of context.

The function returns the following values:

  • ok: TRUE if current thread is owner of context.

func (*MainContext) Iteration

func (context *MainContext) Iteration(mayBlock bool) bool

Iteration runs a single iteration for the given main loop. This involves checking to see if any event sources are ready to be processed, then if no events sources are ready and may_block is TRUE, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Otherwise, if may_block is FALSE sources are not waited to become ready, only those highest priority events sources will be dispatched (if any), that are ready at this given moment without further waiting.

Note that even when may_block is TRUE, it is still possible for g_main_context_iteration() to return FALSE, since the wait may be interrupted for other reasons than an event source becoming ready.

The function takes the following parameters:

  • mayBlock: whether the call may block.

The function returns the following values:

  • ok: TRUE if events were dispatched.

func (*MainContext) Pending

func (context *MainContext) Pending() bool

Pending checks if any sources have pending events for the given context.

The function returns the following values:

  • ok: TRUE if events are pending.

func (*MainContext) PopThreadDefault

func (context *MainContext) PopThreadDefault()

PopThreadDefault pops context off the thread-default context stack (verifying that it was on the top of the stack).

func (*MainContext) Prepare

func (context *MainContext) Prepare() (int, bool)

Prepare prepares to poll sources within a main loop. The resulting information for polling is determined by calling g_main_context_query ().

You must have successfully acquired the context with g_main_context_acquire() before you may call this function.

The function returns the following values:

  • priority (optional): location to store priority of highest priority source already ready.
  • ok: TRUE if some source is ready to be dispatched prior to polling.

func (*MainContext) PushThreadDefault

func (context *MainContext) PushThreadDefault()

PushThreadDefault acquires context and sets it as the thread-default context for the current thread. This will cause certain asynchronous operations (such as most [gio][gio]-based I/O) which are started in this thread to run under context and deliver their results to its main loop, rather than running under the global default context in the main thread. Note that calling this function changes the context returned by g_main_context_get_thread_default(), not the one returned by g_main_context_default(), so it does not affect the context used by functions like g_idle_add().

Normally you would call this function shortly after creating a new thread, passing it a Context which will be run by a Loop in that thread, to set a new default context for all async operations in that thread. In this case you may not need to ever call g_main_context_pop_thread_default(), assuming you want the new Context to be the default for the whole lifecycle of the thread.

If you don't have control over how the new thread was created (e.g. in the new thread isn't newly created, or if the thread life cycle is managed by a Pool), it is always suggested to wrap the logic that needs to use the new Context inside a g_main_context_push_thread_default() / g_main_context_pop_thread_default() pair, otherwise threads that are re-used will end up never explicitly releasing the Context reference they hold.

In some cases you may want to schedule a single operation in a non-default context, or temporarily use a non-default context in the main thread. In that case, you can wrap the call to the asynchronous operation inside a g_main_context_push_thread_default() / g_main_context_pop_thread_default() pair, but it is up to you to ensure that no other asynchronous operations accidentally get started while the non-default context is active.

Beware that libraries that predate this function may not correctly handle being used from a thread with a thread-default context. Eg, see g_file_supports_thread_contexts().

func (*MainContext) Release

func (context *MainContext) Release()

Release releases ownership of a context previously acquired by this thread with g_main_context_acquire(). If the context was acquired multiple times, the ownership will be released only when g_main_context_release() is called as many times as it was acquired.

func (*MainContext) Wakeup

func (context *MainContext) Wakeup()

Wakeup: if context is currently blocking in g_main_context_iteration() waiting for a source to become ready, cause it to stop blocking and return. Otherwise, cause the next invocation of g_main_context_iteration() to return without blocking.

This API is useful for low-level control over Context; for example, integrating it with main loop implementations such as Loop.

Another related use for this function is when implementing a main loop with a termination condition, computed from multiple threads:

perform_work();

if (g_atomic_int_dec_and_test (&tasks_remaining))
  g_main_context_wakeup (NULL);.

type MainLoop

type MainLoop struct {
	// contains filtered or unexported fields
}

MainLoop: GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK+ application.

An instance of this type is always passed by reference.

func NewMainLoop

func NewMainLoop(context *MainContext, isRunning bool) *MainLoop

NewMainLoop constructs a struct MainLoop.

func (*MainLoop) Context

func (loop *MainLoop) Context() *MainContext

Context returns the Context of loop.

The function returns the following values:

  • mainContext of loop.

func (*MainLoop) IsRunning

func (loop *MainLoop) IsRunning() bool

IsRunning checks to see if the main loop is currently being run via g_main_loop_run().

The function returns the following values:

  • ok: TRUE if the mainloop is currently being run.

func (*MainLoop) Quit

func (loop *MainLoop) Quit()

Quit stops a Loop from running. Any calls to g_main_loop_run() for the loop will return.

Note that sources that have already been dispatched when g_main_loop_quit() is called will still be executed.

func (*MainLoop) Run

func (loop *MainLoop) Run()

Run runs a main loop until g_main_loop_quit() is called on the loop. If this is called for the thread of the loop's Context, it will process events from the loop, otherwise it will simply wait.

type MappedFile

type MappedFile struct {
	// contains filtered or unexported fields
}

MappedFile represents a file mapping created with g_mapped_file_new(). It has only private members and should not be accessed directly.

An instance of this type is always passed by reference.

func NewMappedFile

func NewMappedFile(filename string, writable bool) (*MappedFile, error)

NewMappedFile constructs a struct MappedFile.

func NewMappedFileFromFd

func NewMappedFileFromFd(fd int, writable bool) (*MappedFile, error)

NewMappedFileFromFd constructs a struct MappedFile.

func (*MappedFile) Bytes

func (file *MappedFile) Bytes() *Bytes

Bytes creates a new #GBytes which references the data mapped from file. The mapped contents of the file must not be modified after creating this bytes object, because a #GBytes should be immutable.

The function returns the following values:

  • bytes: newly allocated #GBytes referencing data from file.

func (*MappedFile) Contents

func (file *MappedFile) Contents() string

Contents returns the contents of a File.

Note that the contents may not be zero-terminated, even if the File is backed by a text file.

If the file is empty then NULL is returned.

The function returns the following values:

  • utf8 contents of file, or NULL.

func (*MappedFile) Length

func (file *MappedFile) Length() uint

Length returns the length of the contents of a File.

The function returns the following values:

  • gsize: length of the contents of file.

type MarkupCollectType

type MarkupCollectType C.guint

MarkupCollectType: mixed enumerated type and flags field. You must specify one type (string, strdup, boolean, tristate). Additionally, you may optionally bitwise OR the type with the flag G_MARKUP_COLLECT_OPTIONAL.

It is likely that this enum will be extended in the future to support other types.

const (
	// MarkupCollectInvalid: used to terminate the list of attributes to
	// collect.
	MarkupCollectInvalid MarkupCollectType = 0b0
	// MarkupCollectString: collect the string pointer directly from the
	// attribute_values[] array. Expects a parameter of type (const char **).
	// If G_MARKUP_COLLECT_OPTIONAL is specified and the attribute isn't present
	// then the pointer will be set to NULL.
	MarkupCollectString MarkupCollectType = 0b1
	// MarkupCollectStrdup as with G_MARKUP_COLLECT_STRING, but expects a
	// parameter of type (char **) and g_strdup()s the returned pointer.
	// The pointer must be freed with g_free().
	MarkupCollectStrdup MarkupCollectType = 0b10
	// MarkupCollectBoolean expects a parameter of type (gboolean *) and parses
	// the attribute value as a boolean. Sets FALSE if the attribute isn't
	// present. Valid boolean values consist of (case-insensitive) "false", "f",
	// "no", "n", "0" and "true", "t", "yes", "y", "1".
	MarkupCollectBoolean MarkupCollectType = 0b11
	// MarkupCollectTristate as with G_MARKUP_COLLECT_BOOLEAN, but in the case
	// of a missing attribute a value is set that compares equal to neither
	// FALSE nor TRUE G_MARKUP_COLLECT_OPTIONAL is implied.
	MarkupCollectTristate MarkupCollectType = 0b100
	// MarkupCollectOptional: can be bitwise ORed with the other fields.
	// If present, allows the attribute not to appear. A default value is set
	// depending on what value type is used.
	MarkupCollectOptional MarkupCollectType = 0b10000000000000000
)

func (MarkupCollectType) Has

Has returns true if m contains other.

func (MarkupCollectType) String

func (m MarkupCollectType) String() string

String returns the names in string for MarkupCollectType.

type MarkupError

type MarkupError C.gint

MarkupError: error codes returned by markup parsing.

const (
	// MarkupErrorBadUTF8: text being parsed was not valid UTF-8.
	MarkupErrorBadUTF8 MarkupError = iota
	// MarkupErrorEmpty: document contained nothing, or only whitespace.
	MarkupErrorEmpty
	// MarkupErrorParse: document was ill-formed.
	MarkupErrorParse
	// MarkupErrorUnknownElement: error should be set by Parser functions;
	// element wasn't known.
	MarkupErrorUnknownElement
	// MarkupErrorUnknownAttribute: error should be set by Parser functions;
	// attribute wasn't known.
	MarkupErrorUnknownAttribute
	// MarkupErrorInvalidContent: error should be set by Parser functions;
	// content was invalid.
	MarkupErrorInvalidContent
	// MarkupErrorMissingAttribute: error should be set by Parser functions;
	// a required attribute was missing.
	MarkupErrorMissingAttribute
)

func (MarkupError) String

func (m MarkupError) String() string

String returns the name in string for MarkupError.

type MarkupParseContext

type MarkupParseContext struct {
	// contains filtered or unexported fields
}

MarkupParseContext: parse context is used to parse a stream of bytes that you expect to contain marked-up text.

See g_markup_parse_context_new(), Parser, and so on for more details.

An instance of this type is always passed by reference.

func (*MarkupParseContext) Element

func (context *MarkupParseContext) Element() string

Element retrieves the name of the currently open element.

If called from the start_element or end_element handlers this will give the element_name as passed to those functions. For the parent elements, see g_markup_parse_context_get_element_stack().

The function returns the following values:

  • utf8: name of the currently open element, or NULL.

func (*MarkupParseContext) EndParse

func (context *MarkupParseContext) EndParse() error

EndParse signals to the ParseContext that all data has been fed into the parse context with g_markup_parse_context_parse().

This function reports an error if the document isn't complete, for example if elements are still open.

func (*MarkupParseContext) Parse

func (context *MarkupParseContext) Parse(text string, textLen int) error

Parse: feed some data to the ParseContext.

The data need not be valid UTF-8; an error will be signaled if it's invalid. The data need not be an entire document; you can feed a document into the parser incrementally, via multiple calls to this function. Typically, as you receive data from a network connection or file, you feed each received chunk of data into this function, aborting the process if an error occurs. Once an error is reported, no further data may be fed to the ParseContext; all errors are fatal.

The function takes the following parameters:

  • text: chunk of text to parse.
  • textLen: length of text in bytes.

func (*MarkupParseContext) Pop

func (context *MarkupParseContext) Pop() unsafe.Pointer

Pop completes the process of a temporary sub-parser redirection.

This function exists to collect the user_data allocated by a matching call to g_markup_parse_context_push(). It must be called in the end_element handler corresponding to the start_element handler during which g_markup_parse_context_push() was called. You must not call this function from the error callback -- the user_data is provided directly to the callback in that case.

This function is not intended to be directly called by users interested in invoking subparsers. Instead, it is intended to be used by the subparsers themselves to implement a higher-level interface.

The function returns the following values:

  • gpointer (optional): user data passed to g_markup_parse_context_push().

func (*MarkupParseContext) Position

func (context *MarkupParseContext) Position() (lineNumber int, charNumber int)

Position retrieves the current line number and the number of the character on that line. Intended for use in error messages; there are no strict semantics for what constitutes the "current" line number other than "the best number we could come up with for error messages.".

The function returns the following values:

  • lineNumber (optional): return location for a line number, or NULL.
  • charNumber (optional): return location for a char-on-line number, or NULL.

func (*MarkupParseContext) Push

func (context *MarkupParseContext) Push(parser *MarkupParser, userData unsafe.Pointer)

Push: temporarily redirects markup data to a sub-parser.

This function may only be called from the start_element handler of a Parser. It must be matched with a corresponding call to g_markup_parse_context_pop() in the matching end_element handler (except in the case that the parser aborts due to an error).

All tags, text and other data between the matching tags is redirected to the subparser given by parser. user_data is used as the user_data for that parser. user_data is also passed to the error callback in the event that an error occurs. This includes errors that occur in subparsers of the subparser.

The end tag matching the start tag for which this call was made is handled by the previous parser (which is given its own user_data) which is why g_markup_parse_context_pop() is provided to allow "one last access" to the user_data provided to this function. In the case of error, the user_data provided here is passed directly to the error callback of the subparser and g_markup_parse_context_pop() should not be called. In either case, if user_data was allocated then it ought to be freed from both of these locations.

This function is not intended to be directly called by users interested in invoking subparsers. Instead, it is intended to be used by the subparsers themselves to implement a higher-level interface.

As an example, see the following implementation of a simple parser that counts the number of tags encountered.

static void start_element (context, element_name, ...)
{
  if (strcmp (element_name, "count-these") == 0)
    start_counting (context);

  // else, handle other tags...
}

static void end_element (context, element_name, ...)
{
  if (strcmp (element_name, "count-these") == 0)
    g_print ("Counted d tags\n", end_counting (context));

  // else, handle other tags...
}.

The function takes the following parameters:

  • parser: Parser.
  • userData (optional): user data to pass to Parser functions.

func (*MarkupParseContext) UserData

func (context *MarkupParseContext) UserData() unsafe.Pointer

UserData returns the user_data associated with context.

This will either be the user_data that was provided to g_markup_parse_context_new() or to the most recent call of g_markup_parse_context_push().

The function returns the following values:

  • gpointer (optional): provided user_data. The returned data belongs to the markup context and will be freed when g_markup_parse_context_free() is called.

type MarkupParseFlags

type MarkupParseFlags C.guint

MarkupParseFlags flags that affect the behaviour of the parser.

const (
	// MarkupDoNotUseThisUnsupportedFlag: flag you should not use.
	MarkupDoNotUseThisUnsupportedFlag MarkupParseFlags = 0b1
	// MarkupTreatCdataAsText: when this flag is set, CDATA marked sections are
	// not passed literally to the passthrough function of the parser. Instead,
	// the content of the section (without the <![CDATA[ and ]]>) is passed to
	// the text function. This flag was added in GLib 2.12.
	MarkupTreatCdataAsText MarkupParseFlags = 0b10
	// MarkupPrefixErrorPosition: normally errors caught by GMarkup itself
	// have line/column information prefixed to them to let the caller know the
	// location of the error. When this flag is set the location information is
	// also prefixed to errors generated by the Parser implementation functions.
	MarkupPrefixErrorPosition MarkupParseFlags = 0b100
	// MarkupIgnoreQualified: ignore (don't report) qualified attributes and
	// tags, along with their contents. A qualified attribute or tag is one that
	// contains ':' in its name (ie: is in another namespace). Since: 2.40.
	MarkupIgnoreQualified MarkupParseFlags = 0b1000
)

func (MarkupParseFlags) Has

func (m MarkupParseFlags) Has(other MarkupParseFlags) bool

Has returns true if m contains other.

func (MarkupParseFlags) String

func (m MarkupParseFlags) String() string

String returns the names in string for MarkupParseFlags.

type MarkupParser

type MarkupParser struct {
	// contains filtered or unexported fields
}

MarkupParser: any of the fields in Parser can be NULL, in which case they will be ignored. Except for the error function, any of these callbacks can set an error; in particular the G_MARKUP_ERROR_UNKNOWN_ELEMENT, G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE, and G_MARKUP_ERROR_INVALID_CONTENT errors are intended to be set from these callbacks. If you set an error from a callback, g_markup_parse_context_parse() will report that error back to its caller.

An instance of this type is always passed by reference.

type MatchInfo

type MatchInfo struct {
	// contains filtered or unexported fields
}

MatchInfo is an opaque struct used to return information about matches.

An instance of this type is always passed by reference.

func (*MatchInfo) ExpandReferences

func (matchInfo *MatchInfo) ExpandReferences(stringToExpand string) (string, error)

ExpandReferences returns a new string containing the text in string_to_expand with references and escape sequences expanded. References refer to the last match done with string against regex and have the same syntax used by g_regex_replace().

The string_to_expand must be UTF-8 encoded even if REGEX_RAW was passed to g_regex_new().

The backreferences are extracted from the string passed to the match function, so you cannot call this function after freeing the string.

match_info may be NULL in which case string_to_expand must not contain references. For instance "foo\n" does not refer to an actual pattern and '\n' merely will be replaced with \n character, while to expand "\0" (whole match) one needs the result of a match. Use g_regex_check_replacement() to find out whether string_to_expand contains references.

The function takes the following parameters:

  • stringToExpand: string to expand.

The function returns the following values:

  • utf8 (optional): expanded string, or NULL if an error occurred.

func (*MatchInfo) Fetch

func (matchInfo *MatchInfo) Fetch(matchNum int) string

Fetch retrieves the text matching the match_num'th capturing parentheses. 0 is the full text of the match, 1 is the first paren set, 2 the second, and so on.

If match_num is a valid sub pattern but it didn't match anything (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty string is returned.

If the match was obtained using the DFA algorithm, that is using g_regex_match_all() or g_regex_match_all_full(), the retrieved string is not that of a set of parentheses but that of a matched substring. Substrings are matched in reverse order of length, so 0 is the longest match.

The string is fetched from the string passed to the match function, so you cannot call this function after freeing the string.

The function takes the following parameters:

  • matchNum: number of the sub expression.

The function returns the following values:

  • utf8 (optional): matched substring, or NULL if an error occurred. You have to free the string yourself.

func (*MatchInfo) FetchAll

func (matchInfo *MatchInfo) FetchAll() []string

FetchAll bundles up pointers to each of the matching substrings from a match and stores them in an array of gchar pointers. The first element in the returned array is the match number 0, i.e. the entire matched text.

If a sub pattern didn't match anything (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty string is inserted.

If the last match was obtained using the DFA algorithm, that is using g_regex_match_all() or g_regex_match_all_full(), the retrieved strings are not that matched by sets of parentheses but that of the matched substring. Substrings are matched in reverse order of length, so the first one is the longest match.

The strings are fetched from the string passed to the match function, so you cannot call this function after freeing the string.

The function returns the following values:

  • utf8s: NULL-terminated array of gchar * pointers. It must be freed using g_strfreev(). If the previous match failed NULL is returned.

func (*MatchInfo) FetchNamed

func (matchInfo *MatchInfo) FetchNamed(name string) string

FetchNamed retrieves the text matching the capturing parentheses named name.

If name is a valid sub pattern name but it didn't match anything (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b") then an empty string is returned.

The string is fetched from the string passed to the match function, so you cannot call this function after freeing the string.

The function takes the following parameters:

  • name of the subexpression.

The function returns the following values:

  • utf8 (optional): matched substring, or NULL if an error occurred. You have to free the string yourself.

func (*MatchInfo) FetchNamedPos

func (matchInfo *MatchInfo) FetchNamedPos(name string) (startPos int, endPos int, ok bool)

FetchNamedPos retrieves the position in bytes of the capturing parentheses named name.

If name is a valid sub pattern name but it didn't match anything (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b") then start_pos and end_pos are set to -1 and TRUE is returned.

The function takes the following parameters:

  • name of the subexpression.

The function returns the following values:

  • startPos (optional): pointer to location where to store the start position, or NULL.
  • endPos (optional): pointer to location where to store the end position, or NULL.
  • ok: TRUE if the position was fetched, FALSE otherwise. If the position cannot be fetched, start_pos and end_pos are left unchanged.

func (*MatchInfo) FetchPos

func (matchInfo *MatchInfo) FetchPos(matchNum int) (startPos int, endPos int, ok bool)

FetchPos retrieves the position in bytes of the match_num'th capturing parentheses. 0 is the full text of the match, 1 is the first paren set, 2 the second, and so on.

If match_num is a valid sub pattern but it didn't match anything (e.g. sub pattern 1, matching "b" against "(a)?b") then start_pos and end_pos are set to -1 and TRUE is returned.

If the match was obtained using the DFA algorithm, that is using g_regex_match_all() or g_regex_match_all_full(), the retrieved position is not that of a set of parentheses but that of a matched substring. Substrings are matched in reverse order of length, so 0 is the longest match.

The function takes the following parameters:

  • matchNum: number of the sub expression.

The function returns the following values:

  • startPos (optional): pointer to location where to store the start position, or NULL.
  • endPos (optional): pointer to location where to store the end position, or NULL.
  • ok: TRUE if the position was fetched, FALSE otherwise. If the position cannot be fetched, start_pos and end_pos are left unchanged.

func (*MatchInfo) IsPartialMatch

func (matchInfo *MatchInfo) IsPartialMatch() bool

IsPartialMatch: usually if the string passed to g_regex_match*() matches as far as it goes, but is too short to match the entire pattern, FALSE is returned. There are circumstances where it might be helpful to distinguish this case from other cases in which there is no match.

Consider, for example, an application where a human is required to type in data for a field with specific formatting requirements. An example might be a date in the form ddmmmyy, defined by the pattern "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$". If the application sees the user’s keystrokes one by one, and can check that what has been typed so far is potentially valid, it is able to raise an error as soon as a mistake is made.

GRegex supports the concept of partial matching by means of the REGEX_MATCH_PARTIAL_SOFT and REGEX_MATCH_PARTIAL_HARD flags. When they are used, the return code for g_regex_match() or g_regex_match_full() is, as usual, TRUE for a complete match, FALSE otherwise. But, when these functions return FALSE, you can check if the match was partial calling g_match_info_is_partial_match().

The difference between REGEX_MATCH_PARTIAL_SOFT and REGEX_MATCH_PARTIAL_HARD is that when a partial match is encountered with REGEX_MATCH_PARTIAL_SOFT, matching continues to search for a possible complete match, while with REGEX_MATCH_PARTIAL_HARD matching stops at the partial match. When both REGEX_MATCH_PARTIAL_SOFT and REGEX_MATCH_PARTIAL_HARD are set, the latter takes precedence.

There were formerly some restrictions on the pattern for partial matching. The restrictions no longer apply.

See pcrepartial(3) for more information on partial matching.

The function returns the following values:

  • ok: TRUE if the match was partial, FALSE otherwise.

func (*MatchInfo) MatchCount

func (matchInfo *MatchInfo) MatchCount() int

MatchCount retrieves the number of matched substrings (including substring 0, that is the whole matched text), so 1 is returned if the pattern has no substrings in it and 0 is returned if the match failed.

If the last match was obtained using the DFA algorithm, that is using g_regex_match_all() or g_regex_match_all_full(), the retrieved count is not that of the number of capturing parentheses but that of the number of matched substrings.

The function returns the following values:

  • gint: number of matched substrings, or -1 if an error occurred.

func (*MatchInfo) Matches

func (matchInfo *MatchInfo) Matches() bool

Matches returns whether the previous match operation succeeded.

The function returns the following values:

  • ok: TRUE if the previous match operation succeeded, FALSE otherwise.

func (*MatchInfo) Next

func (matchInfo *MatchInfo) Next() error

Next scans for the next match using the same parameters of the previous call to g_regex_match_full() or g_regex_match() that returned match_info.

The match is done on the string passed to the match function, so you cannot free it before calling this function.

func (*MatchInfo) Regex

func (matchInfo *MatchInfo) Regex() *Regex

Regex returns #GRegex object used in match_info. It belongs to Glib and must not be freed. Use g_regex_ref() if you need to keep it after you free match_info object.

The function returns the following values:

  • regex object used in match_info.

func (*MatchInfo) String

func (matchInfo *MatchInfo) String() string

String returns the string searched with match_info. This is the string passed to g_regex_match() or g_regex_replace() so you may not free it before calling this function.

The function returns the following values:

  • utf8: string searched with match_info.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node struct represents one node in a [n-ary tree][glib-N-ary-Trees].

An instance of this type is always passed by reference.

func (*Node) ChildIndex

func (node *Node) ChildIndex(data unsafe.Pointer) int

ChildIndex gets the position of the first child of a #GNode which contains the given data.

The function takes the following parameters:

  • data (optional) to find.

The function returns the following values:

  • gint: index of the child of node which contains data, or -1 if the data is not found.

func (*Node) ChildPosition

func (node *Node) ChildPosition(child *Node) int

ChildPosition gets the position of a #GNode with respect to its siblings. child must be a child of node. The first child is numbered 0, the second 1, and so on.

The function takes the following parameters:

  • child of node.

The function returns the following values:

  • gint: position of child with respect to its siblings.

func (*Node) Children

func (n *Node) Children() *Node

Children points to the first child of the #GNode. The other children are accessed by using the next pointer of each child.

func (*Node) Data

func (n *Node) Data() unsafe.Pointer

Data contains the actual data of the node.

func (*Node) Depth

func (node *Node) Depth() uint

Depth gets the depth of a #GNode.

If node is NULL the depth is 0. The root node has a depth of 1. For the children of the root node the depth is 2. And so on.

The function returns the following values:

  • guint: depth of the #GNode.

func (*Node) Destroy

func (root *Node) Destroy()

Destroy removes root and its children from the tree, freeing any memory allocated.

func (*Node) IsAncestor

func (node *Node) IsAncestor(descendant *Node) bool

IsAncestor returns TRUE if node is an ancestor of descendant. This is true if node is the parent of descendant, or if node is the grandparent of descendant etc.

The function takes the following parameters:

  • descendant: #GNode.

The function returns the following values:

  • ok: TRUE if node is an ancestor of descendant.

func (*Node) MaxHeight

func (root *Node) MaxHeight() uint

MaxHeight gets the maximum height of all branches beneath a #GNode. This is the maximum distance from the #GNode to all leaf nodes.

If root is NULL, 0 is returned. If root has no children, 1 is returned. If root has children, 2 is returned. And so on.

The function returns the following values:

  • guint: maximum height of the tree beneath root.

func (*Node) NChildren

func (node *Node) NChildren() uint

NChildren gets the number of children of a #GNode.

The function returns the following values:

  • guint: number of children of node.

func (*Node) NNodes

func (root *Node) NNodes(flags TraverseFlags) uint

NNodes gets the number of nodes in a tree.

The function takes the following parameters:

  • flags: which types of children are to be counted, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.

The function returns the following values:

  • guint: number of nodes in the tree.

func (*Node) Next

func (n *Node) Next() *Node

Next points to the node's next sibling (a sibling is another #GNode with the same parent).

func (*Node) Parent

func (n *Node) Parent() *Node

Parent points to the parent of the #GNode, or is NULL if the #GNode is the root of the tree.

func (*Node) Prev

func (n *Node) Prev() *Node

Prev points to the node's previous sibling.

func (*Node) ReverseChildren

func (node *Node) ReverseChildren()

ReverseChildren reverses the order of the children of a #GNode. (It doesn't change the order of the grandchildren.).

func (node *Node) Unlink()

Unlink unlinks a #GNode from a tree, resulting in two separate trees.

type NormalizeMode

type NormalizeMode C.gint

NormalizeMode defines how a Unicode string is transformed in a 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. Unicode strings should generally be normalized before comparing them.

const (
	// NormalizeDefault: standardize differences that do not affect the text
	// content, such as the above-mentioned accent representation.
	NormalizeDefault NormalizeMode = 0
	// NormalizeNFD: another name for G_NORMALIZE_DEFAULT.
	NormalizeNFD NormalizeMode = 0
	// NormalizeDefaultCompose: like G_NORMALIZE_DEFAULT, but with composed
	// forms rather than a maximally decomposed form.
	NormalizeDefaultCompose NormalizeMode = 1
	// NormalizeNFC: another name for G_NORMALIZE_DEFAULT_COMPOSE.
	NormalizeNFC NormalizeMode = 1
	// NormalizeAll: beyond G_NORMALIZE_DEFAULT also standardize 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.
	NormalizeAll NormalizeMode = 2
	// NormalizeNFKD: another name for G_NORMALIZE_ALL.
	NormalizeNFKD NormalizeMode = 2
	// NormalizeAllCompose: like G_NORMALIZE_ALL, but with composed forms rather
	// than a maximally decomposed form.
	NormalizeAllCompose NormalizeMode = 3
	// NormalizeNFKC: another name for G_NORMALIZE_ALL_COMPOSE.
	NormalizeNFKC NormalizeMode = 3
)

func (NormalizeMode) String

func (n NormalizeMode) String() string

String returns the name in string for NormalizeMode.

type Object

type Object = coreglib.Object

Object is an alias for pkg/core/glib.Object.

func BaseObject

func BaseObject(obj Objector) *Object

BaseObject is an alias for pkg/core/glib.BaseObject.

type Objector

type Objector = coreglib.Objector

Objector is an alias for pkg/core/glib.Objector.

type OptionArg

type OptionArg C.gint

OptionArg enum values determine which type of extra argument the options expect to find. If an option expects an extra argument, it can be specified in several ways; with a short option: -x arg, with a long option: --name arg or combined in a single argument: --name=arg.

const (
	// OptionArgNone: no extra argument. This is useful for simple flags.
	OptionArgNone OptionArg = iota
	// OptionArgString: option takes a UTF-8 string argument.
	OptionArgString
	// OptionArgInt: option takes an integer argument.
	OptionArgInt
	// OptionArgCallback: option provides a callback (of type ArgFunc) to parse
	// the extra argument.
	OptionArgCallback
	// OptionArgFilename: option takes a filename as argument, which will be in
	// the GLib filename encoding rather than UTF-8.
	OptionArgFilename
	// OptionArgStringArray: option takes a string argument, multiple uses of
	// the option are collected into an array of strings.
	OptionArgStringArray
	// OptionArgFilenameArray: option takes a filename as argument, multiple
	// uses of the option are collected into an array of strings.
	OptionArgFilenameArray
	// OptionArgDouble: option takes a double argument. The argument can be
	// formatted either for the user's locale or for the "C" locale. Since 2.12.
	OptionArgDouble
	// OptionArgInt64: option takes a 64-bit integer. Like G_OPTION_ARG_INT but
	// for larger numbers. The number can be in decimal base, or in hexadecimal
	// (when prefixed with 0x, for example, 0xffffffff). Since 2.12.
	OptionArgInt64
)

func (OptionArg) String

func (o OptionArg) String() string

String returns the name in string for OptionArg.

type OptionEntry

type OptionEntry struct {
	// contains filtered or unexported fields
}

OptionEntry struct defines a single option. To have an effect, they must be added to a Group with g_option_context_add_main_entries() or g_option_group_add_entries().

An instance of this type is always passed by reference.

func (*OptionEntry) Arg

func (o *OptionEntry) Arg() OptionArg

Arg: type of the option, as a Arg.

func (*OptionEntry) ArgData

func (o *OptionEntry) ArgData() unsafe.Pointer

ArgData: if the arg type is G_OPTION_ARG_CALLBACK, then arg_data must point to a ArgFunc callback function, which will be called to handle the extra argument. Otherwise, arg_data is a pointer to a location to store the value, the required type of the location depends on the arg type: - G_OPTION_ARG_NONE: gboolean - G_OPTION_ARG_STRING: gchar* - G_OPTION_ARG_INT: gint - G_OPTION_ARG_FILENAME: gchar* - G_OPTION_ARG_STRING_ARRAY: gchar** - G_OPTION_ARG_FILENAME_ARRAY: gchar** - G_OPTION_ARG_DOUBLE: gdouble If arg type is G_OPTION_ARG_STRING or G_OPTION_ARG_FILENAME, the location will contain a newly allocated string if the option was given. That string needs to be freed by the callee using g_free(). Likewise if arg type is G_OPTION_ARG_STRING_ARRAY or G_OPTION_ARG_FILENAME_ARRAY, the data should be freed using g_strfreev().

func (*OptionEntry) ArgDescription

func (o *OptionEntry) ArgDescription() string

ArgDescription: placeholder to use for the extra argument parsed by the option in --help output. The arg_description is translated using the translate_func of the group, see g_option_group_set_translation_domain().

func (*OptionEntry) Description

func (o *OptionEntry) Description() string

Description: description for the option in --help output. The description is translated using the translate_func of the group, see g_option_group_set_translation_domain().

func (*OptionEntry) Flags

func (o *OptionEntry) Flags() int

Flags from Flags.

func (*OptionEntry) LongName

func (o *OptionEntry) LongName() string

LongName: long name of an option can be used to specify it in a commandline as --long_name. Every option must have a long name. To resolve conflicts if multiple option groups contain the same long name, it is also possible to specify the option as --groupname-long_name.

func (*OptionEntry) SetFlags

func (o *OptionEntry) SetFlags(flags int)

Flags from Flags.

func (*OptionEntry) SetShortName

func (o *OptionEntry) SetShortName(shortName byte)

ShortName: if an option has a short name, it can be specified -short_name in a commandline. short_name must be a printable ASCII character different from '-', or zero if the option has no short name.

func (*OptionEntry) ShortName

func (o *OptionEntry) ShortName() byte

ShortName: if an option has a short name, it can be specified -short_name in a commandline. short_name must be a printable ASCII character different from '-', or zero if the option has no short name.

type OptionError

type OptionError C.gint

OptionError: error codes returned by option parsing.

const (
	// OptionErrorUnknownOption: option was not known to the parser. This error
	// will only be reported, if the parser hasn't been instructed to ignore
	// unknown options, see g_option_context_set_ignore_unknown_options().
	OptionErrorUnknownOption OptionError = iota
	// OptionErrorBadValue: value couldn't be parsed.
	OptionErrorBadValue
	// OptionErrorFailed callback failed.
	OptionErrorFailed
)

func (OptionError) String

func (o OptionError) String() string

String returns the name in string for OptionError.

type OptionFlags

type OptionFlags C.guint

OptionFlags flags which modify individual options.

const (
	// OptionFlagNone: no flags. Since: 2.42.
	OptionFlagNone OptionFlags = 0b0
	// OptionFlagHidden: option doesn't appear in --help output.
	OptionFlagHidden OptionFlags = 0b1
	// OptionFlagInMain: option appears in the main section of the --help
	// output, even if it is defined in a group.
	OptionFlagInMain OptionFlags = 0b10
	// OptionFlagReverse: for options of the G_OPTION_ARG_NONE kind, this flag
	// indicates that the sense of the option is reversed.
	OptionFlagReverse OptionFlags = 0b100
	// OptionFlagNoArg: for options of the G_OPTION_ARG_CALLBACK kind,
	// this flag indicates that the callback does not take any argument (like a
	// G_OPTION_ARG_NONE option). Since 2.8.
	OptionFlagNoArg OptionFlags = 0b1000
	// OptionFlagFilename: for options of the G_OPTION_ARG_CALLBACK kind,
	// this flag indicates that the argument should be passed to the callback in
	// the GLib filename encoding rather than UTF-8. Since 2.8.
	OptionFlagFilename OptionFlags = 0b10000
	// OptionFlagOptionalArg: for options of the G_OPTION_ARG_CALLBACK kind,
	// this flag indicates that the argument supply is optional. If no argument
	// is given then data of GOptionParseFunc will be set to NULL. Since 2.8.
	OptionFlagOptionalArg OptionFlags = 0b100000
	// OptionFlagNoalias: this flag turns off the automatic conflict resolution
	// which prefixes long option names with groupname- if there is a conflict.
	// This option should only be used in situations where aliasing is necessary
	// to model some legacy commandline interface. It is not safe to use
	// this option, unless all option groups are under your direct control.
	// Since 2.8.
	OptionFlagNoalias OptionFlags = 0b1000000
)

func (OptionFlags) Has

func (o OptionFlags) Has(other OptionFlags) bool

Has returns true if o contains other.

func (OptionFlags) String

func (o OptionFlags) String() string

String returns the names in string for OptionFlags.

type OptionGroup

type OptionGroup struct {
	// contains filtered or unexported fields
}

OptionGroup: GOptionGroup struct defines the options in a single group. The struct has only private fields and should not be directly accessed.

All options in a group share the same translation function. Libraries which need to parse commandline options are expected to provide a function for getting a GOptionGroup holding their options, which the application can then add to its Context.

An instance of this type is always passed by reference.

func (*OptionGroup) AddEntries

func (group *OptionGroup) AddEntries(entries []OptionEntry)

AddEntries adds the options specified in entries to group.

The function takes the following parameters:

  • entries: NULL-terminated array of Entrys.

func (*OptionGroup) SetTranslationDomain

func (group *OptionGroup) SetTranslationDomain(domain string)

SetTranslationDomain: convenience function to use gettext() for translating user-visible strings.

The function takes the following parameters:

  • domain to use.

type Priority

type Priority = coreglib.Priority

Priority is an alias for pkg/core/glib.Priority.

type PtrArray

type PtrArray struct {
	// contains filtered or unexported fields
}

PtrArray contains the public fields of a pointer array.

An instance of this type is always passed by reference.

func (*PtrArray) Len

func (p *PtrArray) Len() uint

Len: number of pointers in the array.

func (*PtrArray) Pdata

func (p *PtrArray) Pdata() *unsafe.Pointer

Pdata points to the array of pointers, which may be moved when the array grows.

func (*PtrArray) SetLen

func (p *PtrArray) SetLen(len uint)

Len: number of pointers in the array.

type Quark

type Quark = uint32

Quark is a non-zero integer which uniquely identifies a particular string. A GQuark value of zero is associated to NULL.

func ConvertErrorQuark

func ConvertErrorQuark() Quark

The function returns the following values:

func FileErrorQuark

func FileErrorQuark() Quark

The function returns the following values:

func IOChannelErrorQuark

func IOChannelErrorQuark() Quark

The function returns the following values:

func KeyFileErrorQuark

func KeyFileErrorQuark() Quark

The function returns the following values:

func MarkupErrorQuark

func MarkupErrorQuark() Quark

The function returns the following values:

func NumberParserErrorQuark

func NumberParserErrorQuark() Quark

The function returns the following values:

func OptionErrorQuark

func OptionErrorQuark() Quark

The function returns the following values:

func QuarkFromStaticString

func QuarkFromStaticString(str string) Quark

QuarkFromStaticString 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 g_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++.

The function takes the following parameters:

  • str (optional): string.

The function returns the following values:

  • quark identifying the string, or 0 if string is NULL.

func QuarkFromString

func QuarkFromString(str string) Quark

QuarkFromString 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++.

The function takes the following parameters:

  • str (optional): string.

The function returns the following values:

  • quark identifying the string, or 0 if string is NULL.

func QuarkTryString

func QuarkTryString(str string) Quark

QuarkTryString gets the #GQuark associated with the given string, or 0 if string is NULL or it has no associated #GQuark.

If you want the GQuark to be created if it doesn't already exist, use g_quark_from_string() or g_quark_from_static_string().

This function must not be used before library constructors have finished running.

The function takes the following parameters:

  • str (optional): string.

The function returns the following values:

  • quark associated with the string, or 0 if string is NULL or there is no #GQuark associated with it.

func RegexErrorQuark

func RegexErrorQuark() Quark

The function returns the following values:

func ShellErrorQuark

func ShellErrorQuark() Quark

The function returns the following values:

func SpawnErrorQuark

func SpawnErrorQuark() Quark

The function returns the following values:

func SpawnExitErrorQuark

func SpawnExitErrorQuark() Quark

The function returns the following values:

func URIErrorQuark

func URIErrorQuark() Quark

The function returns the following values:

func VariantParseErrorQuark

func VariantParseErrorQuark() Quark

The function returns the following values:

func VariantParserGetErrorQuark deprecated

func VariantParserGetErrorQuark() Quark

VariantParserGetErrorQuark: same as g_variant_error_quark().

Deprecated: Use g_variant_parse_error_quark() instead.

The function returns the following values:

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue contains the public fields of a Queue[glib-Double-ended-Queues].

An instance of this type is always passed by reference.

func (*Queue) Clear

func (queue *Queue) Clear()

Clear removes all the elements in queue. If queue elements contain dynamically-allocated memory, they should be freed first.

func (*Queue) Index

func (queue *Queue) Index(data unsafe.Pointer) int

Index returns the position of the first element in queue which contains data.

The function takes the following parameters:

  • data (optional) to find.

The function returns the following values:

  • gint: position of the first element in queue which contains data, or -1 if no element in queue contains data.

func (*Queue) Init

func (queue *Queue) Init()

Init: statically-allocated #GQueue must be initialized with this function before it can be used. Alternatively you can initialize it with QUEUE_INIT. It is not necessary to initialize queues created with g_queue_new().

func (*Queue) IsEmpty

func (queue *Queue) IsEmpty() bool

IsEmpty returns TRUE if the queue is empty.

The function returns the following values:

  • ok: TRUE if the queue is empty.

func (*Queue) Length

func (queue *Queue) Length() uint

Length returns the number of items in queue.

The function returns the following values:

  • guint: number of items in queue.

func (*Queue) PeekHead

func (queue *Queue) PeekHead() unsafe.Pointer

PeekHead returns the first element of the queue.

The function returns the following values:

  • gpointer (optional): data of the first element in the queue, or NULL if the queue is empty.

func (*Queue) PeekNth

func (queue *Queue) PeekNth(n uint) unsafe.Pointer

PeekNth returns the n'th element of queue.

The function takes the following parameters:

  • n of the element.

The function returns the following values:

  • gpointer (optional): data for the n'th element of queue, or NULL if n is off the end of queue.

func (*Queue) PeekTail

func (queue *Queue) PeekTail() unsafe.Pointer

PeekTail returns the last element of the queue.

The function returns the following values:

  • gpointer (optional): data of the last element in the queue, or NULL if the queue is empty.

func (*Queue) PopHead

func (queue *Queue) PopHead() unsafe.Pointer

PopHead removes the first element of the queue and returns its data.

The function returns the following values:

  • gpointer (optional): data of the first element in the queue, or NULL if the queue is empty.

func (*Queue) PopNth

func (queue *Queue) PopNth(n uint) unsafe.Pointer

PopNth removes the n'th element of queue and returns its data.

The function takes the following parameters:

  • n of the element.

The function returns the following values:

  • gpointer (optional) element's data, or NULL if n is off the end of queue.

func (*Queue) PopTail

func (queue *Queue) PopTail() unsafe.Pointer

PopTail removes the last element of the queue and returns its data.

The function returns the following values:

  • gpointer (optional): data of the last element in the queue, or NULL if the queue is empty.

func (*Queue) PushHead

func (queue *Queue) PushHead(data unsafe.Pointer)

PushHead adds a new element at the head of the queue.

The function takes the following parameters:

  • data (optional) for the new element.

func (*Queue) PushNth

func (queue *Queue) PushNth(data unsafe.Pointer, n int)

PushNth inserts a new element into queue at the given position.

The function takes the following parameters:

  • data (optional) for the new element.
  • n to insert the new element. If n is negative or larger than the number of elements in the queue, the element is added to the end of the queue.

func (*Queue) PushTail

func (queue *Queue) PushTail(data unsafe.Pointer)

PushTail adds a new element at the tail of the queue.

The function takes the following parameters:

  • data (optional) for the new element.

func (*Queue) Remove

func (queue *Queue) Remove(data unsafe.Pointer) bool

Remove removes the first element in queue that contains data.

The function takes the following parameters:

  • data (optional) to remove.

The function returns the following values:

  • ok: TRUE if data was found and removed from queue.

func (*Queue) RemoveAll

func (queue *Queue) RemoveAll(data unsafe.Pointer) uint

RemoveAll: remove all elements whose data equals data from queue.

The function takes the following parameters:

  • data (optional) to remove.

The function returns the following values:

  • guint: number of elements removed from queue.

func (*Queue) Reverse

func (queue *Queue) Reverse()

Reverse reverses the order of the items in queue.

type Regex

type Regex struct {
	// contains filtered or unexported fields
}

Regex: g_regex_*() functions implement regular expression pattern matching using syntax and semantics similar to Perl regular expression.

Some functions accept a start_position argument, setting it differs from just passing over a shortened string and setting REGEX_MATCH_NOTBOL in the case of a pattern that begins with any kind of lookbehind assertion. For example, consider the pattern "\Biss\B" which finds occurrences of "iss" in the middle of words. ("\B" matches only if the current position in the subject is not a word boundary.) When applied to the string "Mississipi" from the fourth byte, namely "issipi", it does not match, because "\B" is always false at the start of the subject, which is deemed to be a word boundary. However, if the entire string is passed , but with start_position set to 4, it finds the second occurrence of "iss" because it is able to look behind the starting point to discover that it is preceded by a letter.

Note that, unless you set the REGEX_RAW flag, all the strings passed to these functions must be encoded in UTF-8. The lengths and the positions inside the strings are in bytes and not in characters, so, for instance, "\xc3\xa0" (i.e. "à") is two bytes long but it is treated as a single character. If you set REGEX_RAW the strings can be non-valid UTF-8 strings and a byte is treated as a character, so "\xc3\xa0" is two bytes and two characters long.

When matching a pattern, "\n" matches only against a "\n" character in the string, and "\r" matches only a "\r" character. To match any newline sequence use "\R". This particular group matches either the two-character sequence CR + LF ("\r\n"), or one of the single characters LF (linefeed, U+000A, "\n"), VT vertical tab, U+000B, "\v"), FF (formfeed, U+000C, "\f"), CR (carriage return, U+000D, "\r"), NEL (next line, U+0085), LS (line separator, U+2028), or PS (paragraph separator, U+2029).

The behaviour of the dot, circumflex, and dollar metacharacters are affected by newline characters, the default is to recognize any newline character (the same characters recognized by "\R"). This can be changed with REGEX_NEWLINE_CR, REGEX_NEWLINE_LF and REGEX_NEWLINE_CRLF compile options, and with REGEX_MATCH_NEWLINE_ANY, REGEX_MATCH_NEWLINE_CR, REGEX_MATCH_NEWLINE_LF and REGEX_MATCH_NEWLINE_CRLF match options. These settings are also relevant when compiling a pattern if REGEX_EXTENDED is set, and an unescaped "#" outside a character class is encountered. This indicates a comment that lasts until after the next newline.

When setting the G_REGEX_JAVASCRIPT_COMPAT flag, pattern syntax and pattern matching is changed to be compatible with the way that regular expressions work in JavaScript. More precisely, a lonely ']' character in the pattern is a syntax error; the '\x' escape only allows 0 to 2 hexadecimal digits, and you must use the '\u' escape sequence with 4 hex digits to specify a unicode codepoint instead of '\x' or 'x{....}'. If '\x' or '\u' are not followed by the specified number of hex digits, they match 'x' and 'u' literally; also '\U' always matches 'U' instead of being an error in the pattern. Finally, pattern matching is modified so that back references to an unset subpattern group produces a match with the empty string instead of an error. See pcreapi(3) for more information.

Creating and manipulating the same #GRegex structure from different threads is not a problem as #GRegex does not modify its internal state between creation and destruction, on the other hand Info is not threadsafe.

The regular expressions low-level functionalities are obtained through the excellent PCRE (http://www.pcre.org/) library written by Philip Hazel.

An instance of this type is always passed by reference.

func NewRegex

func NewRegex(pattern string, compileOptions RegexCompileFlags, matchOptions RegexMatchFlags) (*Regex, error)

NewRegex constructs a struct Regex.

func (*Regex) CaptureCount

func (regex *Regex) CaptureCount() int

CaptureCount returns the number of capturing subpatterns in the pattern.

The function returns the following values:

  • gint: number of capturing subpatterns.

func (*Regex) CompileFlags

func (regex *Regex) CompileFlags() RegexCompileFlags

CompileFlags returns the compile options that regex was created with.

Depending on the version of PCRE that is used, this may or may not include flags set by option expressions such as (?i) found at the top-level within the compiled pattern.

The function returns the following values:

  • regexCompileFlags flags from CompileFlags.

func (*Regex) HasCrOrLf

func (regex *Regex) HasCrOrLf() bool

HasCrOrLf checks whether the pattern contains explicit CR or LF references.

The function returns the following values:

  • ok: TRUE if the pattern contains explicit CR or LF references.

func (*Regex) Match

func (regex *Regex) Match(str string, matchOptions RegexMatchFlags) (*MatchInfo, bool)

Match scans for a match in string for the pattern in regex. The match_options are combined with the match options specified when the regex structure was created, letting you have more flexibility in reusing #GRegex structures.

Unless G_REGEX_RAW is specified in the options, string must be valid UTF-8.

A Info structure, used to get information on the match, is stored in match_info if not NULL. Note that if match_info is not NULL then it is created even if the function returns FALSE, i.e. you must free it regardless if regular expression actually matched.

To retrieve all the non-overlapping matches of the pattern in string you can use g_match_info_next().

static void
print_uppercase_words (const gchar *string)
{
  // Print all uppercase-only words.
  GRegex *regex;
  GMatchInfo *match_info;

  regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
  g_regex_match (regex, string, 0, &match_info);
  while (g_match_info_matches (match_info))
    {
      gchar *word = g_match_info_fetch (match_info, 0);
      g_print ("Found: s\n", word);
      g_free (word);
      g_match_info_next (match_info, NULL);
    }
  g_match_info_free (match_info);
  g_regex_unref (regex);
}

string is not copied and is used in Info internally. If you use any Info method (except g_match_info_free()) after freeing or modifying string then the behaviour is undefined.

The function takes the following parameters:

  • str: string to scan for matches.
  • matchOptions: match options.

The function returns the following values:

  • matchInfo (optional): pointer to location where to store the Info, or NULL if you do not need it.
  • ok: TRUE is the string matched, FALSE otherwise.

func (*Regex) MatchAll

func (regex *Regex) MatchAll(str string, matchOptions RegexMatchFlags) (*MatchInfo, bool)

MatchAll: using the standard algorithm for regular expression matching only the longest match in the string is retrieved. This function uses a different algorithm so it can retrieve all the possible matches. For more documentation see g_regex_match_all_full().

A Info structure, used to get information on the match, is stored in match_info if not NULL. Note that if match_info is not NULL then it is created even if the function returns FALSE, i.e. you must free it regardless if regular expression actually matched.

string is not copied and is used in Info internally. If you use any Info method (except g_match_info_free()) after freeing or modifying string then the behaviour is undefined.

The function takes the following parameters:

  • str: string to scan for matches.
  • matchOptions: match options.

The function returns the following values:

  • matchInfo (optional): pointer to location where to store the Info, or NULL if you do not need it.
  • ok: TRUE is the string matched, FALSE otherwise.

func (*Regex) MatchFlags

func (regex *Regex) MatchFlags() RegexMatchFlags

MatchFlags returns the match options that regex was created with.

The function returns the following values:

  • regexMatchFlags flags from MatchFlags.

func (*Regex) MaxBackref

func (regex *Regex) MaxBackref() int

MaxBackref returns the number of the highest back reference in the pattern, or 0 if the pattern does not contain back references.

The function returns the following values:

  • gint: number of the highest back reference.

func (*Regex) MaxLookbehind

func (regex *Regex) MaxLookbehind() int

MaxLookbehind gets the number of characters in the longest lookbehind assertion in the pattern. This information is useful when doing multi-segment matching using the partial matching facilities.

The function returns the following values:

  • gint: number of characters in the longest lookbehind assertion.

func (*Regex) Pattern

func (regex *Regex) Pattern() string

Pattern gets the pattern string associated with regex, i.e. a copy of the string passed to g_regex_new().

The function returns the following values:

  • utf8: pattern of regex.

func (*Regex) Split

func (regex *Regex) Split(str string, matchOptions RegexMatchFlags) []string

Split 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.

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".

The function takes the following parameters:

  • str: string to split with the pattern.
  • matchOptions: match time option flags.

The function returns the following values:

  • utf8s: NULL-terminated gchar ** array. Free it using g_strfreev().

func (*Regex) StringNumber

func (regex *Regex) StringNumber(name string) int

StringNumber retrieves the number of the subexpression named name.

The function takes the following parameters:

  • name of the subexpression.

The function returns the following values:

  • gint: number of the subexpression or -1 if name does not exists.

type RegexCompileFlags

type RegexCompileFlags C.guint

RegexCompileFlags flags specifying compile-time options.

const (
	// RegexCaseless letters in the pattern match both upper- and lowercase
	// letters. This option can be changed within a pattern by a "(?i)" option
	// setting.
	RegexCaseless RegexCompileFlags = 0b1
	// RegexMultiline: by default, GRegex treats the strings as consisting of
	// a single line of characters (even if it actually contains newlines).
	// The "start of line" metacharacter ("^") matches only at the start of
	// the string, while the "end of line" metacharacter ("$") matches only
	// at the end of the string, or before a terminating newline (unless
	// REGEX_DOLLAR_ENDONLY is set). When REGEX_MULTILINE is set, the "start
	// of line" and "end of line" constructs match immediately following or
	// immediately before any newline in the string, respectively, as well as at
	// the very start and end. This can be changed within a pattern by a "(?m)"
	// option setting.
	RegexMultiline RegexCompileFlags = 0b10
	// RegexDotall: dot metacharacter (".") in the pattern matches all
	// characters, including newlines. Without it, newlines are excluded.
	// This option can be changed within a pattern by a ("?s") option setting.
	RegexDotall RegexCompileFlags = 0b100
	// RegexExtended: whitespace data characters in the pattern are totally
	// ignored except when escaped or inside a character class. Whitespace
	// does not include the VT character (code 11). In addition, characters
	// between an unescaped "#" outside a character class and the next newline
	// character, inclusive, are also ignored. This can be changed within a
	// pattern by a "(?x)" option setting.
	RegexExtended RegexCompileFlags = 0b1000
	// RegexAnchored: pattern is forced to be "anchored", that is, it is
	// constrained to match only at the first matching point in the string
	// that is being searched. This effect can also be achieved by appropriate
	// constructs in the pattern itself such as the "^" metacharacter.
	RegexAnchored RegexCompileFlags = 0b10000
	// RegexDollarEndonly: dollar metacharacter ("$") in the pattern matches
	// only at the end of the string. Without this option, a dollar also matches
	// immediately before the final character if it is a newline (but not before
	// any other newlines). This option is ignored if REGEX_MULTILINE is set.
	RegexDollarEndonly RegexCompileFlags = 0b100000
	// RegexUngreedy inverts the "greediness" of the quantifiers so that they
	// are not greedy by default, but become greedy if followed by "?". It can
	// also be set by a "(?U)" option setting within the pattern.
	RegexUngreedy RegexCompileFlags = 0b1000000000
	// RegexRaw: usually strings must be valid UTF-8 strings, using this flag
	// they are considered as a raw sequence of bytes.
	RegexRaw RegexCompileFlags = 0b100000000000
	// RegexNoAutoCapture disables the use of numbered capturing parentheses in
	// the pattern. Any opening parenthesis that is not followed by "?" behaves
	// as if it were followed by "?:" but named parentheses can still be used
	// for capturing (and they acquire numbers in the usual way).
	RegexNoAutoCapture RegexCompileFlags = 0b1000000000000
	// RegexOptimize: optimize the regular expression. If the pattern will
	// be used many times, then it may be worth the effort to optimize it to
	// improve the speed of matches.
	RegexOptimize RegexCompileFlags = 0b10000000000000
	// RegexFirstline limits an unanchored pattern to match before (or at) the
	// first newline. Since: 2.34.
	RegexFirstline RegexCompileFlags = 0b1000000000000000000
	// RegexDupnames names used to identify capturing subpatterns need not be
	// unique. This can be helpful for certain types of pattern when it is known
	// that only one instance of the named subpattern can ever be matched.
	RegexDupnames RegexCompileFlags = 0b10000000000000000000
	// RegexNewlineCr: usually any newline character or character sequence is
	// recognized. If this option is set, the only recognized newline character
	// is '\r'.
	RegexNewlineCr RegexCompileFlags = 0b100000000000000000000
	// RegexNewlineLf: usually any newline character or character sequence is
	// recognized. If this option is set, the only recognized newline character
	// is '\n'.
	RegexNewlineLf RegexCompileFlags = 0b1000000000000000000000
	// RegexNewlineCrlf: usually any newline character or character sequence is
	// recognized. If this option is set, the only recognized newline character
	// sequence is '\r\n'.
	RegexNewlineCrlf RegexCompileFlags = 0b1100000000000000000000
	// RegexNewlineAnycrlf: usually any newline character or character sequence
	// is recognized. If this option is set, the only recognized newline
	// character sequences are '\r', '\n', and '\r\n'. Since: 2.34.
	RegexNewlineAnycrlf RegexCompileFlags = 0b10100000000000000000000
	// RegexBsrAnycrlf: usually any newline character or character sequence is
	// recognised. If this option is set, then "\R" only recognizes the newline
	// characters '\r', '\n' and '\r\n'. Since: 2.34.
	RegexBsrAnycrlf RegexCompileFlags = 0b100000000000000000000000
	// RegexJavascriptCompat changes behaviour so that it is compatible with
	// JavaScript rather than PCRE. Since: 2.34.
	RegexJavascriptCompat RegexCompileFlags = 0b10000000000000000000000000
)

func (RegexCompileFlags) Has

Has returns true if r contains other.

func (RegexCompileFlags) String

func (r RegexCompileFlags) String() string

String returns the names in string for RegexCompileFlags.

type RegexError

type RegexError C.gint

RegexError: error codes returned by regular expressions functions.

const (
	// RegexErrorCompile: compilation of the regular expression failed.
	RegexErrorCompile RegexError = 0
	// RegexErrorOptimize: optimization of the regular expression failed.
	RegexErrorOptimize RegexError = 1
	// RegexErrorReplace: replacement failed due to an ill-formed replacement
	// string.
	RegexErrorReplace RegexError = 2
	// RegexErrorMatch: match process failed.
	RegexErrorMatch RegexError = 3
	// RegexErrorInternal: internal error of the regular expression engine.
	// Since 2.16.
	RegexErrorInternal RegexError = 4
	// RegexErrorStrayBackslash: "\\" at end of pattern. Since 2.16.
	RegexErrorStrayBackslash RegexError = 101
	// RegexErrorMissingControlChar: "\\c" at end of pattern. Since 2.16.
	RegexErrorMissingControlChar RegexError = 102
	// RegexErrorUnrecognizedEscape: unrecognized character follows "\\".
	// Since 2.16.
	RegexErrorUnrecognizedEscape RegexError = 103
	// RegexErrorQuantifiersOutOfOrder numbers out of order in "{}" quantifier.
	// Since 2.16.
	RegexErrorQuantifiersOutOfOrder RegexError = 104
	// RegexErrorQuantifierTooBig: number too big in "{}" quantifier. Since
	// 2.16.
	RegexErrorQuantifierTooBig RegexError = 105
	// RegexErrorUnterminatedCharacterClass: missing terminating "]" for
	// character class. Since 2.16.
	RegexErrorUnterminatedCharacterClass RegexError = 106
	// RegexErrorInvalidEscapeInCharacterClass: invalid escape sequence in
	// character class. Since 2.16.
	RegexErrorInvalidEscapeInCharacterClass RegexError = 107
	// RegexErrorRangeOutOfOrder: range out of order in character class.
	// Since 2.16.
	RegexErrorRangeOutOfOrder RegexError = 108
	// RegexErrorNothingToRepeat: nothing to repeat. Since 2.16.
	RegexErrorNothingToRepeat RegexError = 109
	// RegexErrorUnrecognizedCharacter: unrecognized character after "(?",
	// "(?<" or "(?P". Since 2.16.
	RegexErrorUnrecognizedCharacter RegexError = 112
	// RegexErrorPosixNamedClassOutsideClass: POSIX named classes are supported
	// only within a class. Since 2.16.
	RegexErrorPosixNamedClassOutsideClass RegexError = 113
	// RegexErrorUnmatchedParenthesis: missing terminating ")" or ")" without
	// opening "(". Since 2.16.
	RegexErrorUnmatchedParenthesis RegexError = 114
	// RegexErrorInexistentSubpatternReference: reference to non-existent
	// subpattern. Since 2.16.
	RegexErrorInexistentSubpatternReference RegexError = 115
	// RegexErrorUnterminatedComment: missing terminating ")" after comment.
	// Since 2.16.
	RegexErrorUnterminatedComment RegexError = 118
	// RegexErrorExpressionTooLarge: regular expression too large. Since 2.16.
	RegexErrorExpressionTooLarge RegexError = 120
	// RegexErrorMemoryError: failed to get memory. Since 2.16.
	RegexErrorMemoryError RegexError = 121
	// RegexErrorVariableLengthLookbehind: lookbehind assertion is not fixed
	// length. Since 2.16.
	RegexErrorVariableLengthLookbehind RegexError = 125
	// RegexErrorMalformedCondition: malformed number or name after "(?(".
	// Since 2.16.
	RegexErrorMalformedCondition RegexError = 126
	// RegexErrorTooManyConditionalBranches: conditional group contains more
	// than two branches. Since 2.16.
	RegexErrorTooManyConditionalBranches RegexError = 127
	// RegexErrorAssertionExpected: assertion expected after "(?(". Since 2.16.
	RegexErrorAssertionExpected RegexError = 128
	// RegexErrorUnknownPosixClassName: unknown POSIX class name. Since 2.16.
	RegexErrorUnknownPosixClassName RegexError = 130
	// RegexErrorPosixCollatingElementsNotSupported: POSIX collating elements
	// are not supported. Since 2.16.
	RegexErrorPosixCollatingElementsNotSupported RegexError = 131
	// RegexErrorHexCodeTooLarge: character value in "\\x{...}" sequence is too
	// large. Since 2.16.
	RegexErrorHexCodeTooLarge RegexError = 134
	// RegexErrorInvalidCondition: invalid condition "(?(0)". Since 2.16.
	RegexErrorInvalidCondition RegexError = 135
	// RegexErrorSingleByteMatchInLookbehind: \\C not allowed in lookbehind
	// assertion. Since 2.16.
	RegexErrorSingleByteMatchInLookbehind RegexError = 136
	// RegexErrorInfiniteLoop: recursive call could loop indefinitely. Since
	// 2.16.
	RegexErrorInfiniteLoop RegexError = 140
	// RegexErrorMissingSubpatternNameTerminator: missing terminator in
	// subpattern name. Since 2.16.
	RegexErrorMissingSubpatternNameTerminator RegexError = 142
	// RegexErrorDuplicateSubpatternName: two named subpatterns have the same
	// name. Since 2.16.
	RegexErrorDuplicateSubpatternName RegexError = 143
	// RegexErrorMalformedProperty: malformed "\\P" or "\\p" sequence. Since
	// 2.16.
	RegexErrorMalformedProperty RegexError = 146
	// RegexErrorUnknownProperty: unknown property name after "\\P" or "\\p".
	// Since 2.16.
	RegexErrorUnknownProperty RegexError = 147
	// RegexErrorSubpatternNameTooLong: subpattern name is too long (maximum 32
	// characters). Since 2.16.
	RegexErrorSubpatternNameTooLong RegexError = 148
	// RegexErrorTooManySubpatterns: too many named subpatterns (maximum
	// 10,000). Since 2.16.
	RegexErrorTooManySubpatterns RegexError = 149
	// RegexErrorInvalidOctalValue: octal value is greater than "\\377".
	// Since 2.16.
	RegexErrorInvalidOctalValue RegexError = 151
	// RegexErrorTooManyBranchesInDefine: "DEFINE" group contains more than one
	// branch. Since 2.16.
	RegexErrorTooManyBranchesInDefine RegexError = 154
	// RegexErrorDefineRepetion: repeating a "DEFINE" group is not allowed.
	// This error is never raised. Since: 2.16 Deprecated: 2.34.
	RegexErrorDefineRepetion RegexError = 155
	// RegexErrorInconsistentNewlineOptions: inconsistent newline options.
	// Since 2.16.
	RegexErrorInconsistentNewlineOptions RegexError = 156
	// RegexErrorMissingBackReference: "\\g" is not followed by a braced,
	// angle-bracketed, or quoted name or number, or by a plain number. Since:
	// 2.16.
	RegexErrorMissingBackReference RegexError = 157
	// RegexErrorInvalidRelativeReference: relative reference must not be zero.
	// Since: 2.34.
	RegexErrorInvalidRelativeReference RegexError = 158
	// RegexErrorBacktrackingControlVerbArgumentForbidden: backtracing control
	// verb used does not allow an argument. Since: 2.34.
	RegexErrorBacktrackingControlVerbArgumentForbidden RegexError = 159
	// RegexErrorUnknownBacktrackingControlVerb: unknown backtracing control
	// verb. Since: 2.34.
	RegexErrorUnknownBacktrackingControlVerb RegexError = 160
	// RegexErrorNumberTooBig: number is too big in escape sequence. Since:
	// 2.34.
	RegexErrorNumberTooBig RegexError = 161
	// RegexErrorMissingSubpatternName: missing subpattern name. Since: 2.34.
	RegexErrorMissingSubpatternName RegexError = 162
	// RegexErrorMissingDigit: missing digit. Since 2.34.
	RegexErrorMissingDigit RegexError = 163
	// RegexErrorInvalidDataCharacter: in JavaScript compatibility mode,
	// "[" is an invalid data character. Since: 2.34.
	RegexErrorInvalidDataCharacter RegexError = 164
	// RegexErrorExtraSubpatternName: different names for subpatterns of the
	// same number are not allowed. Since: 2.34.
	RegexErrorExtraSubpatternName RegexError = 165
	// RegexErrorBacktrackingControlVerbArgumentRequired: backtracing control
	// verb requires an argument. Since: 2.34.
	RegexErrorBacktrackingControlVerbArgumentRequired RegexError = 166
	// RegexErrorInvalidControlChar: "\\c" must be followed by an ASCII
	// character. Since: 2.34.
	RegexErrorInvalidControlChar RegexError = 168
	// RegexErrorMissingName: "\\k" is not followed by a braced,
	// angle-bracketed, or quoted name. Since: 2.34.
	RegexErrorMissingName RegexError = 169
	// RegexErrorNotSupportedInClass: "\\N" is not supported in a class. Since:
	// 2.34.
	RegexErrorNotSupportedInClass RegexError = 171
	// RegexErrorTooManyForwardReferences: too many forward references. Since:
	// 2.34.
	RegexErrorTooManyForwardReferences RegexError = 172
	// RegexErrorNameTooLong: name is too long in "(*MARK)", "(*PRUNE)",
	// "(*SKIP)", or "(*THEN)". Since: 2.34.
	RegexErrorNameTooLong RegexError = 175
	// RegexErrorCharacterValueTooLarge: character value in the \\u sequence is
	// too large. Since: 2.34.
	RegexErrorCharacterValueTooLarge RegexError = 176
)

func (RegexError) String

func (r RegexError) String() string

String returns the name in string for RegexError.

type RegexMatchFlags

type RegexMatchFlags C.guint

RegexMatchFlags flags specifying match-time options.

const (
	// RegexMatchAnchored: pattern is forced to be "anchored", that is,
	// it is constrained to match only at the first matching point in the string
	// that is being searched. This effect can also be achieved by appropriate
	// constructs in the pattern itself such as the "^" metacharacter.
	RegexMatchAnchored RegexMatchFlags = 0b10000
	// RegexMatchNotbol specifies that first character of the string is not the
	// beginning of a line, so the circumflex metacharacter should not match
	// before it. Setting this without REGEX_MULTILINE (at compile time) causes
	// circumflex never to match. This option affects only the behaviour of the
	// circumflex metacharacter, it does not affect "\A".
	RegexMatchNotbol RegexMatchFlags = 0b10000000
	// RegexMatchNoteol specifies that the end of the subject string is not
	// the end of a line, so the dollar metacharacter should not match it nor
	// (except in multiline mode) a newline immediately before it. Setting this
	// without REGEX_MULTILINE (at compile time) causes dollar never to match.
	// This option affects only the behaviour of the dollar metacharacter,
	// it does not affect "\Z" or "\z".
	RegexMatchNoteol RegexMatchFlags = 0b100000000
	// RegexMatchNotempty: empty string is not considered to be a valid match
	// if this option is set. If there are alternatives in the pattern,
	// they are tried. If all the alternatives match the empty string,
	// the entire match fails. For example, if the pattern "a?b?" is applied to
	// a string not beginning with "a" or "b", it matches the empty string at
	// the start of the string. With this flag set, this match is not valid,
	// so GRegex searches further into the string for occurrences of "a" or "b".
	RegexMatchNotempty RegexMatchFlags = 0b10000000000
	// RegexMatchPartial turns on the partial matching feature, for more
	// documentation on partial matching see g_match_info_is_partial_match().
	RegexMatchPartial RegexMatchFlags = 0b1000000000000000
	// RegexMatchNewlineCr overrides the newline definition set when creating a
	// new #GRegex, setting the '\r' character as line terminator.
	RegexMatchNewlineCr RegexMatchFlags = 0b100000000000000000000
	// RegexMatchNewlineLf overrides the newline definition set when creating a
	// new #GRegex, setting the '\n' character as line terminator.
	RegexMatchNewlineLf RegexMatchFlags = 0b1000000000000000000000
	// RegexMatchNewlineCrlf overrides the newline definition set when creating
	// a new #GRegex, setting the '\r\n' characters sequence as line terminator.
	RegexMatchNewlineCrlf RegexMatchFlags = 0b1100000000000000000000
	// RegexMatchNewlineAny overrides the newline definition set when creating
	// a new #GRegex, any Unicode newline sequence is recognised as a newline.
	// These are '\r', '\n' and '\rn', and the single characters U+000B LINE
	// TABULATION, U+000C FORM FEED (FF), U+0085 NEXT LINE (NEL), U+2028 LINE
	// SEPARATOR and U+2029 PARAGRAPH SEPARATOR.
	RegexMatchNewlineAny RegexMatchFlags = 0b10000000000000000000000
	// RegexMatchNewlineAnycrlf overrides the newline definition set when
	// creating a new #GRegex; any '\r', '\n', or '\r\n' character sequence is
	// recognized as a newline. Since: 2.34.
	RegexMatchNewlineAnycrlf RegexMatchFlags = 0b10100000000000000000000
	// RegexMatchBsrAnycrlf overrides the newline definition for "\R" set when
	// creating a new #GRegex; only '\r', '\n', or '\r\n' character sequences
	// are recognized as a newline by "\R". Since: 2.34.
	RegexMatchBsrAnycrlf RegexMatchFlags = 0b100000000000000000000000
	// RegexMatchBsrAny overrides the newline definition for "\R" set when
	// creating a new #GRegex; any Unicode newline character or character
	// sequence are recognized as a newline by "\R". These are '\r', '\n' and
	// '\rn', and the single characters U+000B LINE TABULATION, U+000C FORM FEED
	// (FF), U+0085 NEXT LINE (NEL), U+2028 LINE SEPARATOR and U+2029 PARAGRAPH
	// SEPARATOR. Since: 2.34.
	RegexMatchBsrAny RegexMatchFlags = 0b1000000000000000000000000
	// RegexMatchPartialSoft alias for REGEX_MATCH_PARTIAL. Since: 2.34.
	RegexMatchPartialSoft RegexMatchFlags = 0b1000000000000000
	// RegexMatchPartialHard turns on the partial matching feature. In contrast
	// to to REGEX_MATCH_PARTIAL_SOFT, this stops matching as soon as a partial
	// match is found, without continuing to search for a possible complete
	// match. See g_match_info_is_partial_match() for more information. Since:
	// 2.34.
	RegexMatchPartialHard RegexMatchFlags = 0b1000000000000000000000000000
	// RegexMatchNotemptyAtstart: like REGEX_MATCH_NOTEMPTY, but only applied
	// to the start of the matched string. For anchored patterns this can only
	// happen for pattern containing "\K". Since: 2.34.
	RegexMatchNotemptyAtstart RegexMatchFlags = 0b10000000000000000000000000000
)

func (RegexMatchFlags) Has

func (r RegexMatchFlags) Has(other RegexMatchFlags) bool

Has returns true if r contains other.

func (RegexMatchFlags) String

func (r RegexMatchFlags) String() string

String returns the names in string for RegexMatchFlags.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner: data structure representing a lexical scanner.

You should set input_name after creating the scanner, since it is used by the default message handler when displaying warnings and errors. If you are scanning a file, the filename would be a good choice.

The user_data and max_parse_errors fields are not used. If you need to associate extra data with the scanner you can place them here.

If you want to use your own message handler you can set the msg_handler field. The type of the message handler function is declared by MsgFunc.

An instance of this type is always passed by reference.

func (*Scanner) CurLine

func (scanner *Scanner) CurLine() uint

CurLine returns the current line in the input stream (counting from 1). This is the line of the last token parsed via g_scanner_get_next_token().

The function returns the following values:

  • guint: current line.

func (*Scanner) CurPosition

func (scanner *Scanner) CurPosition() uint

CurPosition returns the current position in the current line (counting from 0). This is the position of the last token parsed via g_scanner_get_next_token().

The function returns the following values:

  • guint: current position on the line.

func (*Scanner) CurToken

func (scanner *Scanner) CurToken() TokenType

CurToken gets the current token type. This is simply the token field in the #GScanner structure.

The function returns the following values:

  • tokenType: current token type.

func (*Scanner) Destroy

func (scanner *Scanner) Destroy()

Destroy frees all memory used by the #GScanner.

func (*Scanner) EOF

func (scanner *Scanner) EOF() bool

EOF returns TRUE if the scanner has reached the end of the file or text buffer.

The function returns the following values:

  • ok: TRUE if the scanner has reached the end of the file or text buffer.

func (*Scanner) InputFile

func (scanner *Scanner) InputFile(inputFd int)

InputFile prepares to scan a file.

The function takes the following parameters:

  • inputFd: file descriptor.

func (*Scanner) InputText

func (scanner *Scanner) InputText(text string, textLen uint)

InputText prepares to scan a text buffer.

The function takes the following parameters:

  • text buffer to scan.
  • textLen: length of the text buffer.

func (*Scanner) LookupSymbol

func (scanner *Scanner) LookupSymbol(symbol string) unsafe.Pointer

LookupSymbol looks up a symbol in the current scope and return its value. If the symbol is not bound in the current scope, NULL is returned.

The function takes the following parameters:

  • symbol to look up.

The function returns the following values:

  • gpointer (optional): value of symbol in the current scope, or NULL if symbol is not bound in the current scope.

func (*Scanner) NextToken

func (scanner *Scanner) NextToken() TokenType

NextToken parses the next token just like g_scanner_peek_next_token() and also removes it from the input stream. The token data is placed in the token, value, line, and position fields of the #GScanner structure.

The function returns the following values:

  • tokenType: type of the token.

func (*Scanner) PeekNextToken

func (scanner *Scanner) PeekNextToken() TokenType

PeekNextToken parses the next token, without removing it from the input stream. The token data is placed in the next_token, next_value, next_line, and next_position fields of the #GScanner structure.

Note that, while the token is not removed from the input stream (i.e. the next call to g_scanner_get_next_token() will return the same token), it will not be reevaluated. This can lead to surprising results when changing scope or the scanner configuration after peeking the next token. Getting the next token after switching the scope or configuration will return whatever was peeked before, regardless of any symbols that may have been added or removed in the new scope.

The function returns the following values:

  • tokenType: type of the token.

func (*Scanner) ScopeAddSymbol

func (scanner *Scanner) ScopeAddSymbol(scopeId uint, symbol string, value unsafe.Pointer)

ScopeAddSymbol adds a symbol to the given scope.

The function takes the following parameters:

  • scopeId: scope id.
  • symbol to add.
  • value (optional) of the symbol.

func (*Scanner) ScopeLookupSymbol

func (scanner *Scanner) ScopeLookupSymbol(scopeId uint, symbol string) unsafe.Pointer

ScopeLookupSymbol looks up a symbol in a scope and return its value. If the symbol is not bound in the scope, NULL is returned.

The function takes the following parameters:

  • scopeId: scope id.
  • symbol to look up.

The function returns the following values:

  • gpointer (optional): value of symbol in the given scope, or NULL if symbol is not bound in the given scope.

func (*Scanner) ScopeRemoveSymbol

func (scanner *Scanner) ScopeRemoveSymbol(scopeId uint, symbol string)

ScopeRemoveSymbol removes a symbol from a scope.

The function takes the following parameters:

  • scopeId: scope id.
  • symbol to remove.

func (*Scanner) SetScope

func (scanner *Scanner) SetScope(scopeId uint) uint

SetScope sets the current scope.

The function takes the following parameters:

  • scopeId: new scope id.

The function returns the following values:

  • guint: old scope id.

func (*Scanner) SyncFileOffset

func (scanner *Scanner) SyncFileOffset()

SyncFileOffset rewinds the filedescriptor to the current buffer position and blows the file read ahead buffer. This is useful for third party uses of the scanners filedescriptor, which hooks onto the current scanning position.

func (*Scanner) UnexpToken

func (scanner *Scanner) UnexpToken(expectedToken TokenType, identifierSpec string, symbolSpec string, symbolName string, message string, isError int)

UnexpToken outputs a message through the scanner's msg_handler, resulting from an unexpected token in the input stream. Note that you should not call g_scanner_peek_next_token() followed by g_scanner_unexp_token() without an intermediate call to g_scanner_get_next_token(), as g_scanner_unexp_token() evaluates the scanner's current token (not the peeked token) to construct part of the message.

The function takes the following parameters:

  • expectedToken: expected token.
  • identifierSpec: string describing how the scanner's user refers to identifiers (NULL defaults to "identifier"). This is used if expected_token is G_TOKEN_IDENTIFIER or G_TOKEN_IDENTIFIER_NULL.
  • symbolSpec: string describing how the scanner's user refers to symbols (NULL defaults to "symbol"). This is used if expected_token is G_TOKEN_SYMBOL or any token value greater than G_TOKEN_LAST.
  • symbolName: name of the symbol, if the scanner's current token is a symbol.
  • message string to output at the end of the warning/error, or NULL.
  • isError: if TRUE it is output as an error. If FALSE it is output as a warning.

type ScannerConfig

type ScannerConfig struct {
	// contains filtered or unexported fields
}

ScannerConfig specifies the #GScanner parser configuration. Most settings can be changed during the parsing phase and will affect the lexical parsing of the next unpeeked token.

An instance of this type is always passed by reference.

func (*ScannerConfig) CpairCommentSingle

func (s *ScannerConfig) CpairCommentSingle() string

CpairCommentSingle specifies the characters at the start and end of single-line comments. The default is "#\n" which means that single-line comments start with a '#' and continue until a '\n' (end of line).

func (*ScannerConfig) CsetIdentifierFirst

func (s *ScannerConfig) CsetIdentifierFirst() string

CsetIdentifierFirst specifies the characters which can start identifiers (the default is CSET_a_2_z, "_", and CSET_A_2_Z).

func (*ScannerConfig) CsetIdentifierNth

func (s *ScannerConfig) CsetIdentifierNth() string

CsetIdentifierNth specifies the characters which can be used in identifiers, after the first character (the default is CSET_a_2_z, "_0123456789", CSET_A_2_Z, CSET_LATINS, CSET_LATINC).

func (*ScannerConfig) CsetSkipCharacters

func (s *ScannerConfig) CsetSkipCharacters() string

CsetSkipCharacters specifies which characters should be skipped by the scanner (the default is the whitespace characters: space, tab, carriage-return and line-feed).

type SeekType

type SeekType C.gint

SeekType: enumeration specifying the base position for a g_io_channel_seek_position() operation.

const (
	// SeekCur: current position in the file.
	SeekCur SeekType = iota
	// SeekSet: start of the file.
	SeekSet
	// SeekEnd: end of the file.
	SeekEnd
)

func (SeekType) String

func (s SeekType) String() string

String returns the name in string for SeekType.

type ShellError

type ShellError C.gint

ShellError: error codes returned by shell functions.

const (
	// ShellErrorBadQuoting: mismatched or otherwise mangled quoting.
	ShellErrorBadQuoting ShellError = iota
	// ShellErrorEmptyString: string to be parsed was empty.
	ShellErrorEmptyString
	// ShellErrorFailed: some other error.
	ShellErrorFailed
)

func (ShellError) String

func (s ShellError) String() string

String returns the name in string for ShellError.

type SignalHandle

type SignalHandle = coreglib.SignalHandle

SignalHandle is an alias for pkg/core/glib.SignalHandle.

type Source

type Source struct {
	// contains filtered or unexported fields
}

Source: GSource struct is an opaque data type representing an event source.

An instance of this type is always passed by reference.

func IOCreateWatch

func IOCreateWatch(channel *IOChannel, condition IOCondition) *Source

IOCreateWatch creates a #GSource that's dispatched when condition is met for the given channel. For example, if condition is IO_IN, the source will be dispatched when there's data available for reading.

The callback function invoked by the #GSource should be added with g_source_set_callback(), but it has type OFunc (not Func).

g_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.

The function takes the following parameters:

  • channel to watch.
  • condition conditions to watch for.

The function returns the following values:

  • source: new #GSource.

func MainCurrentSource

func MainCurrentSource() *Source

MainCurrentSource returns the currently firing source for this thread.

The function returns the following values:

  • source (optional): currently firing source or NULL.

func NewIdleSource

func NewIdleSource() *Source

NewIdleSource creates a new idle source.

The source will not initially be associated with any Context and must be added to one with g_source_attach() before it will be executed. Note that the default priority for idle sources is G_PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of G_PRIORITY_DEFAULT.

The function returns the following values:

  • source: newly-created idle source.

func NewSource

func NewSource(sourceFuncs *SourceFuncs, structSize uint) *Source

NewSource constructs a struct Source.

func NewTimeoutSource

func NewTimeoutSource(interval uint) *Source

NewTimeoutSource creates a new timeout source.

The source will not initially be associated with any Context and must be added to one with g_source_attach() before it will be executed.

The interval given is in terms of monotonic time, not wall clock time. See g_get_monotonic_time().

The function takes the following parameters:

  • interval: timeout interval in milliseconds.

The function returns the following values:

  • source: newly-created timeout source.

func TimeoutSourceNewSeconds

func TimeoutSourceNewSeconds(interval uint) *Source

TimeoutSourceNewSeconds creates a new timeout source.

The source will not initially be associated with any Context and must be added to one with g_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 g_get_monotonic_time().

The function takes the following parameters:

  • interval: timeout interval in seconds.

The function returns the following values:

  • source: newly-created timeout source.

func (*Source) AddChildSource

func (source *Source) AddChildSource(childSource *Source)

AddChildSource adds child_source to source as a "polled" source; when source is added to a Context, child_source will be automatically added with the same priority, when child_source is triggered, it will cause source to dispatch (in addition to calling its own callback), and when source is destroyed, it will destroy child_source as well. (source will also still be dispatched if its own prepare/check functions indicate that it is ready.)

If you don't need child_source to do anything on its own when it triggers, you can call g_source_set_dummy_callback() on it to set a callback that does nothing (except return TRUE if appropriate).

source will hold a reference on child_source while child_source is attached to it.

This API is only intended to be used by implementations of #GSource. Do not call this API on a #GSource that you did not create.

The function takes the following parameters:

  • childSource: second #GSource that source should "poll".

func (*Source) Attach

func (source *Source) Attach(context *MainContext) uint

Attach adds a #GSource to a context so that it will be executed within that context. Remove it by calling g_source_destroy().

This function is safe to call from any thread, regardless of which thread the context is running in.

The function takes the following parameters:

  • context (optional) (if NULL, the default context will be used).

The function returns the following values:

  • guint: ID (greater than 0) for the source within the Context.

func (*Source) CanRecurse

func (source *Source) CanRecurse() bool

CanRecurse checks whether a source is allowed to be called recursively. see g_source_set_can_recurse().

The function returns the following values:

  • ok: whether recursion is allowed.

func (*Source) Context

func (source *Source) Context() *MainContext

Context gets the Context with which the source is associated.

You can call this on a source that has been destroyed, provided that the Context it was attached to still exists (in which case it will return that Context). In particular, you can always call this function on the source returned from g_main_current_source(). But calling this function on a source whose Context has been destroyed is an error.

The function returns the following values:

  • mainContext (optional) with which the source is associated, or NULL if the context has not yet been added to a source.

func (*Source) CurrentTime deprecated

func (source *Source) CurrentTime(timeval *TimeVal)

CurrentTime: this function ignores source and is otherwise the same as g_get_current_time().

Deprecated: use g_source_get_time() instead.

The function takes the following parameters:

  • timeval structure in which to store current time.

func (*Source) Destroy

func (source *Source) Destroy()

Destroy removes a source from its Context, if any, and mark it as destroyed. The source cannot be subsequently added to another context. It is safe to call this on sources which have already been removed from their context.

This does not unref the #GSource: if you still hold a reference, use g_source_unref() to drop it.

This function is safe to call from any thread, regardless of which thread the Context is running in.

func (*Source) ID

func (source *Source) ID() uint

ID returns the numeric ID for a particular source. The ID of a source is a positive integer which is unique within a particular main loop context. The reverse mapping from ID to source is done by g_main_context_find_source_by_id().

You can only call this function while the source is associated to a Context instance; calling this function before g_source_attach() or after g_source_destroy() yields undefined behavior. The ID returned is unique within the Context instance passed to g_source_attach().

The function returns the following values:

  • guint: ID (greater than 0) for the source.

func (*Source) IsDestroyed

func (source *Source) IsDestroyed() bool

IsDestroyed returns whether source has been destroyed.

This is important when you operate upon your objects from within idle handlers, but may have freed the object before the dispatch of your idle handler.

static gboolean
idle_callback (gpointer data)
{
  SomeWidget *self = data;

  g_mutex_lock (&self->idle_id_mutex);
  if (!g_source_is_destroyed (g_main_current_source ()))
    {
      // do stuff with self
    }
  g_mutex_unlock (&self->idle_id_mutex);

  return FALSE;
}

Calls to this function from a thread other than the one acquired by the Context the #GSource is attached to are typically redundant, as the source could be destroyed immediately after this function returns. However, once a source is destroyed it cannot be un-destroyed, so this function can be used for opportunistic checks from any thread.

The function returns the following values:

  • ok: TRUE if the source has been destroyed.

func (*Source) Name

func (source *Source) Name() string

Name gets a name for the source, used in debugging and profiling. The name may be LL if it has never been set with g_source_set_name().

The function returns the following values:

  • utf8 (optional): name of the source.

func (*Source) Priority

func (source *Source) Priority() int

Priority gets the priority of a source.

The function returns the following values:

  • gint: priority of the source.

func (*Source) ReadyTime

func (source *Source) ReadyTime() int64

ReadyTime gets the "ready time" of source, as set by g_source_set_ready_time().

Any time before the current monotonic time (including 0) is an indication that the source will fire immediately.

The function returns the following values:

  • gint64: monotonic ready time, -1 for "never".

func (*Source) RemoveChildSource

func (source *Source) RemoveChildSource(childSource *Source)

RemoveChildSource detaches child_source from source and destroys it.

This API is only intended to be used by implementations of #GSource. Do not call this API on a #GSource that you did not create.

The function takes the following parameters:

  • childSource previously passed to g_source_add_child_source().

func (*Source) SetCallback

func (source *Source) SetCallback(fn SourceFunc)

SetCallback sets the callback function for a source. The callback for a source is called from the source's dispatch function.

The exact type of func depends on the type of source; ie. you should not count on func being called with data as its first parameter. Cast func with G_SOURCE_FUNC() to avoid warnings about incompatible function types.

See [memory management of sources][mainloop-memory-management] for details on how to handle memory management of data.

Typically, you won't use this function. Instead use functions specific to the type of source you are using, such as g_idle_add() or g_timeout_add().

It is safe to call this function multiple times on a source which has already been attached to a context. The changes will take effect for the next time the source is dispatched after this call returns.

The function takes the following parameters:

  • fn: callback function.

func (*Source) SetCallbackIndirect

func (source *Source) SetCallbackIndirect(callbackData unsafe.Pointer, callbackFuncs *SourceCallbackFuncs)

SetCallbackIndirect sets the callback function storing the data as a refcounted callback "object". This is used internally. Note that calling g_source_set_callback_indirect() assumes an initial reference count on callback_data, and thus callback_funcs->unref will eventually be called once more than callback_funcs->ref.

It is safe to call this function multiple times on a source which has already been attached to a context. The changes will take effect for the next time the source is dispatched after this call returns.

The function takes the following parameters:

  • callbackData (optional): pointer to callback data "object".
  • callbackFuncs functions for reference counting callback_data and getting the callback and data.

func (*Source) SetCanRecurse

func (source *Source) SetCanRecurse(canRecurse bool)

SetCanRecurse sets whether a source can be called recursively. If can_recurse is TRUE, then while the source is being dispatched then this source will be processed normally. Otherwise, all processing of this source is blocked until the dispatch function returns.

The function takes the following parameters:

  • canRecurse: whether recursion is allowed for this source.

func (*Source) SetFuncs

func (source *Source) SetFuncs(funcs *SourceFuncs)

SetFuncs sets the source functions (can be used to override default implementations) of an unattached source.

The function takes the following parameters:

  • funcs: new Funcs.

func (*Source) SetName

func (source *Source) SetName(name string)

SetName sets a name for the source, used in debugging and profiling. The name defaults to LL.

The source name should describe in a human-readable way what the source does. For example, "X11 event queue" or "GTK+ repaint idle handler" or whatever it is.

It is permitted to call this function multiple times, but is not recommended due to the potential performance impact. For example, one could change the name in the "check" function of a Funcs to include details like the event type in the source name.

Use caution if changing the name while another thread may be accessing it with g_source_get_name(); that function does not copy the value, and changing the value will free it while the other thread may be attempting to use it.

The function takes the following parameters:

  • name: debug name for the source.

func (*Source) SetPriority

func (source *Source) SetPriority(priority int)

SetPriority sets the priority of a source. While the main loop is being run, a source will be dispatched if it is ready to be dispatched and no sources at a higher (numerically smaller) priority are ready to be dispatched.

A child source always has the same priority as its parent. It is not permitted to change the priority of a source once it has been added as a child of another source.

The function takes the following parameters:

  • priority: new priority.

func (*Source) SetReadyTime

func (source *Source) SetReadyTime(readyTime int64)

SetReadyTime sets a #GSource to be dispatched when the given monotonic time is reached (or passed). If the monotonic time is in the past (as it always will be if ready_time is 0) then the source will be dispatched immediately.

If ready_time is -1 then the source is never woken up on the basis of the passage of time.

Dispatching the source does not reset the ready time. You should do so yourself, from the source dispatch function.

Note that if you have a pair of sources where the ready time of one suggests that it will be delivered first but the priority for the other suggests that it would be delivered first, and the ready time for both sources is reached during the same main context iteration, then the order of dispatch is undefined.

It is a no-op to call this function on a #GSource which has already been destroyed with g_source_destroy().

This API is only intended to be used by implementations of #GSource. Do not call this API on a #GSource that you did not create.

The function takes the following parameters:

  • readyTime: monotonic time at which the source will be ready, 0 for "immediately", -1 for "never".

func (*Source) Time

func (source *Source) Time() int64

Time gets the time to be used when checking this source. The advantage of calling this function over calling g_get_monotonic_time() directly is that when checking multiple sources, GLib can cache a single value instead of having to repeatedly get the system monotonic time.

The time here is the system monotonic time, if available, or some other reasonable alternative otherwise. See g_get_monotonic_time().

The function returns the following values:

  • gint64: monotonic time in microseconds.

type SourceCallbackFuncs

type SourceCallbackFuncs struct {
	// contains filtered or unexported fields
}

SourceCallbackFuncs: GSourceCallbackFuncs struct contains functions for managing callback objects.

An instance of this type is always passed by reference.

type SourceFunc

type SourceFunc func() (ok bool)

SourceFunc specifies the type of function passed to g_timeout_add(), g_timeout_add_full(), g_idle_add(), and g_idle_add_full().

When calling g_source_set_callback(), you may need to cast a function of a different type to this type. Use G_SOURCE_FUNC() to avoid warnings about incompatible function types.

type SourceFuncs

type SourceFuncs struct {
	// contains filtered or unexported fields
}

SourceFuncs: GSourceFuncs struct contains a table of functions used to handle event sources in a generic manner.

For idle sources, the prepare and check functions always return TRUE to indicate that the source is always ready to be processed. The prepare function also returns a timeout value of 0 to ensure that the poll() call doesn't block (since that would be time wasted which could have been spent running the idle function).

For timeout sources, the prepare and check functions both return TRUE if the timeout interval has expired. The prepare function also returns a timeout value to ensure that the poll() call doesn't block too long and miss the next timeout.

For file descriptor sources, the prepare function typically returns FALSE, since it must wait until poll() has been called before it knows whether any events need to be processed. It sets the returned timeout to -1 to indicate that it doesn't mind how long the poll() call blocks. In the check function, it tests the results of the poll() call to see if the required condition has been met, and returns TRUE if so.

An instance of this type is always passed by reference.

type SourceHandle

type SourceHandle = coreglib.SourceHandle

SourceHandle is an alias for pkg/core/glib.SourceHandle.

func IdleAdd

func IdleAdd(f interface{}) SourceHandle

IdleAdd is an alias for pkg/core/glib.IdleAdd.

func IdleAddPriority

func IdleAddPriority(p Priority, f interface{}) SourceHandle

IdleAddPriority is an alias for pkg/core/glib.IdleAddPriority.

func TimeoutAdd

func TimeoutAdd(ms uint, f interface{}) SourceHandle

TimeoutAdd is an alias for pkg/core/glib.TimeoutAdd.

func TimeoutAddPriority

func TimeoutAddPriority(ms uint, p Priority, f interface{}) SourceHandle

TimeoutAddPriority is an alias for pkg/core/glib.TimeoutAddPriority.

func TimeoutSecondsAdd

func TimeoutSecondsAdd(s uint, f interface{}) SourceHandle

TimeoutSecondsAdd is an alias for pkg/core/glib.TimeoutSecondsAdd.

func TimeoutSecondsAddPriority

func TimeoutSecondsAddPriority(s uint, p Priority, f interface{}) SourceHandle

TimeoutSecondsAddPriority is an alias for pkg/core/glib.TimeoutSecondsAddPriority.

type SpawnChildSetupFunc

type SpawnChildSetupFunc func()

SpawnChildSetupFunc specifies the type of the setup function passed to g_spawn_async(), g_spawn_sync() and g_spawn_async_with_pipes(), which can, in very limited ways, be used to affect the child's execution.

On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform, but before calling exec(). Actions taken in this function will only affect the child, not the parent.

On Windows, the function is called in the parent. Its usefulness on Windows is thus questionable. In many cases executing the child setup function in the parent can have ill effects, and you should be very careful when porting software to Windows that uses child setup functions.

However, even on POSIX, you are extremely limited in what you can safely do from a ChildSetupFunc, because any mutexes that were held by other threads in the parent process at the time of the fork() will still be locked in the child process, and they will never be unlocked (since the threads that held them don't exist in the child). POSIX allows only async-signal-safe functions (see signal(7)) to be called in the child between fork() and exec(), which drastically limits the usefulness of child setup functions.

In particular, it is not safe to call any function which may call malloc(), which includes POSIX functions such as setenv(). If you need to set up the child environment differently from the parent, you should use g_get_environ(), g_environ_setenv(), and g_environ_unsetenv(), and then pass the complete environment list to the g_spawn... function.

type SpawnError

type SpawnError C.gint

SpawnError: error codes returned by spawning processes.

const (
	// SpawnErrorFork: fork failed due to lack of memory.
	SpawnErrorFork SpawnError = 0
	// SpawnErrorRead: read or select on pipes failed.
	SpawnErrorRead SpawnError = 1
	// SpawnErrorChdir: changing to working directory failed.
	SpawnErrorChdir SpawnError = 2
	// SpawnErrorAcces: execv() returned EACCES.
	SpawnErrorAcces SpawnError = 3
	// SpawnErrorPerm: execv() returned EPERM.
	SpawnErrorPerm SpawnError = 4
	// SpawnErrorTooBig: execv() returned E2BIG.
	SpawnErrorTooBig SpawnError = 5
	// SpawnError2Big: deprecated alias for G_SPAWN_ERROR_TOO_BIG (deprecated
	// since GLib 2.32).
	SpawnError2Big SpawnError = 5
	// SpawnErrorNoexec: execv() returned ENOEXEC.
	SpawnErrorNoexec SpawnError = 6
	// SpawnErrorNametoolong: execv() returned ENAMETOOLONG.
	SpawnErrorNametoolong SpawnError = 7
	// SpawnErrorNoent: execv() returned ENOENT.
	SpawnErrorNoent SpawnError = 8
	// SpawnErrorNOMEM: execv() returned ENOMEM.
	SpawnErrorNOMEM SpawnError = 9
	// SpawnErrorNotdir: execv() returned ENOTDIR.
	SpawnErrorNotdir SpawnError = 10
	// SpawnErrorLoop: execv() returned ELOOP.
	SpawnErrorLoop SpawnError = 11
	// SpawnErrorTxtbusy: execv() returned ETXTBUSY.
	SpawnErrorTxtbusy SpawnError = 12
	// SpawnErrorIO: execv() returned EIO.
	SpawnErrorIO SpawnError = 13
	// SpawnErrorNfile: execv() returned ENFILE.
	SpawnErrorNfile SpawnError = 14
	// SpawnErrorMfile: execv() returned EMFILE.
	SpawnErrorMfile SpawnError = 15
	// SpawnErrorInval: execv() returned EINVAL.
	SpawnErrorInval SpawnError = 16
	// SpawnErrorIsdir: execv() returned EISDIR.
	SpawnErrorIsdir SpawnError = 17
	// SpawnErrorLibbad: execv() returned ELIBBAD.
	SpawnErrorLibbad SpawnError = 18
	// SpawnErrorFailed: some other fatal failure, error->message should
	// explain.
	SpawnErrorFailed SpawnError = 19
)

func (SpawnError) String

func (s SpawnError) String() string

String returns the name in string for SpawnError.

type SpawnFlags

type SpawnFlags C.guint

SpawnFlags flags passed to g_spawn_sync(), g_spawn_async() and g_spawn_async_with_pipes().

const (
	// SpawnDefault: no flags, default behaviour.
	SpawnDefault SpawnFlags = 0b0
	// SpawnLeaveDescriptorsOpen parent's open file descriptors will be
	// inherited by the child; otherwise all descriptors except stdin, stdout
	// and stderr will be closed before calling exec() in the child.
	SpawnLeaveDescriptorsOpen SpawnFlags = 0b1
	// SpawnDoNotReapChild: child will not be automatically reaped; you must
	// use g_child_watch_add() yourself (or call waitpid() or handle SIGCHLD
	// yourself), or the child will become a zombie.
	SpawnDoNotReapChild SpawnFlags = 0b10
	// SpawnSearchPath: argv[0] need not be an absolute path, it will be looked
	// for in the user's PATH.
	SpawnSearchPath SpawnFlags = 0b100
	// SpawnStdoutToDevNull child's standard output will be discarded, instead
	// of going to the same location as the parent's standard output.
	SpawnStdoutToDevNull SpawnFlags = 0b1000
	// SpawnStderrToDevNull child's standard error will be discarded.
	SpawnStderrToDevNull SpawnFlags = 0b10000
	// SpawnChildInheritsStdin: child will inherit the parent's standard input
	// (by default, the child's standard input is attached to /dev/null).
	SpawnChildInheritsStdin SpawnFlags = 0b100000
	// SpawnFileAndArgvZero: first element of argv is the file to execute,
	// while the remaining elements are the actual argument vector to pass to
	// the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to
	// execute, and passes all of argv to the child.
	SpawnFileAndArgvZero SpawnFlags = 0b1000000
	// SpawnSearchPathFromEnvp: if argv[0] is not an absolute path, it will be
	// looked for in the PATH from the passed child environment. Since: 2.34.
	SpawnSearchPathFromEnvp SpawnFlags = 0b10000000
	// SpawnCloexecPipes: create all pipes with the O_CLOEXEC flag set. Since:
	// 2.40.
	SpawnCloexecPipes SpawnFlags = 0b100000000
)

func (SpawnFlags) Has

func (s SpawnFlags) Has(other SpawnFlags) bool

Has returns true if s contains other.

func (SpawnFlags) String

func (s SpawnFlags) String() string

String returns the names in string for SpawnFlags.

type TimeSpan

type TimeSpan = int64

TimeSpan: value representing an interval of time, in microseconds.

type TimeType

type TimeType C.gint

TimeType disambiguates a given time in two ways.

First, specifies if the given time is in universal or local time.

Second, if the time is in local time, specifies if it is local standard time or local daylight time. This is important for the case where the same local time occurs twice (during daylight savings time transitions, for example).

const (
	// TimeTypeStandard: time is in local standard time.
	TimeTypeStandard TimeType = iota
	// TimeTypeDaylight: time is in local daylight time.
	TimeTypeDaylight
	// TimeTypeUniversal: time is in UTC.
	TimeTypeUniversal
)

func (TimeType) String

func (t TimeType) String() string

String returns the name in string for TimeType.

type TimeVal deprecated

type TimeVal struct {
	// contains filtered or unexported fields
}

TimeVal represents a precise time, with seconds and microseconds. Similar to the struct timeval returned by the gettimeofday() UNIX system call.

GLib is attempting to unify around the use of 64-bit integers to represent microsecond-precision time. As such, this type will be removed from a future version of GLib. A consequence of using glong for tv_sec is that on 32-bit systems GTimeVal is subject to the year 2038 problem.

Deprecated: Use Time or #guint64 instead.

An instance of this type is always passed by reference.

func NewTimeVal

func NewTimeVal(tvSec, tvUsec int32) TimeVal

NewTimeVal creates a new TimeVal instance from the given fields. Beware that this function allocates on the Go heap; be careful when using it!

func TimeValFromISO8601 deprecated

func TimeValFromISO8601(isoDate string) (*TimeVal, bool)

TimeValFromISO8601 converts a string containing an ISO 8601 encoded date and time to a Val and puts it into time_.

iso_date must include year, month, day, hours, minutes, and seconds. It can optionally include fractions of a second and a time zone indicator. (In the absence of any time zone indication, the timestamp is assumed to be in local time.)

Any leading or trailing space in iso_date is ignored.

This function was deprecated, along with Val itself, in GLib 2.62. Equivalent functionality is available using code like:

GDateTime *dt = g_date_time_new_from_iso8601 (iso8601_string, NULL);
gint64 time_val = g_date_time_to_unix (dt);
g_date_time_unref (dt);

Deprecated: Val is not year-2038-safe. Use g_date_time_new_from_iso8601() instead.

The function takes the following parameters:

  • isoDate: ISO 8601 encoded date string.

The function returns the following values:

  • time_: Val.
  • ok: TRUE if the conversion was successful.

func (*TimeVal) Add deprecated

func (time_ *TimeVal) Add(microseconds int32)

Add adds the given number of microseconds to time_. microseconds can also be negative to decrease the value of time_.

Deprecated: Val is not year-2038-safe. Use guint64 for representing microseconds since the epoch, or use Time.

The function takes the following parameters:

  • microseconds: number of microseconds to add to time.

func (*TimeVal) SetTvSec

func (t *TimeVal) SetTvSec(tvSec int32)

TvSec: seconds.

func (*TimeVal) SetTvUsec

func (t *TimeVal) SetTvUsec(tvUsec int32)

TvUsec: microseconds.

func (*TimeVal) ToISO8601 deprecated

func (time_ *TimeVal) ToISO8601() string

ToISO8601 converts time_ into an RFC 3339 encoded string, relative to the Coordinated Universal Time (UTC). This is one of the many formats allowed by ISO 8601.

ISO 8601 allows a large number of date/time formats, with or without punctuation and optional elements. The format returned by this function is a complete date and time, with optional punctuation included, the UTC time zone represented as "Z", and the tv_usec part included if and only if it is nonzero, i.e. either "YYYY-MM-DDTHH:MM:SSZ" or "YYYY-MM-DDTHH:MM:SS.fffffZ".

This corresponds to the Internet date/time format defined by RFC 3339 (https://www.ietf.org/rfc/rfc3339.txt), and to either of the two most-precise formats defined by the W3C Note Date and Time Formats (http://www.w3.org/TR/NOTE-datetime-19980827). Both of these documents are profiles of ISO 8601.

Use g_date_time_format() or g_strdup_printf() if a different variation of ISO 8601 format is required.

If time_ represents a date which is too large to fit into a struct tm, NULL will be returned. This is platform dependent. Note also that since GTimeVal stores the number of seconds as a glong, on 32-bit systems it is subject to the year 2038 problem. Accordingly, since GLib 2.62, this function has been deprecated. Equivalent functionality is available using:

GDateTime *dt = g_date_time_new_from_unix_utc (time_val);
iso8601_string = g_date_time_format_iso8601 (dt);
g_date_time_unref (dt);

The return value of g_time_val_to_iso8601() has been nullable since GLib 2.54; before then, GLib would crash under the same conditions.

Deprecated: Val is not year-2038-safe. Use g_date_time_format_iso8601(dt) instead.

The function returns the following values:

  • utf8 (optional): newly allocated string containing an ISO 8601 date, or NULL if time_ was too large.

func (*TimeVal) TvSec

func (t *TimeVal) TvSec() int32

TvSec: seconds.

func (*TimeVal) TvUsec

func (t *TimeVal) TvUsec() int32

TvUsec: microseconds.

type TimeZone

type TimeZone struct {
	// contains filtered or unexported fields
}

TimeZone is an opaque structure whose members cannot be accessed directly.

An instance of this type is always passed by reference.

func NewTimeZone

func NewTimeZone(identifier string) *TimeZone

NewTimeZone constructs a struct TimeZone.

func NewTimeZoneFromGo

func NewTimeZoneFromGo(loc *time.Location) *TimeZone

NewTimeZoneFromGo creates a new TimeZone instance from Go's Location. The location's accuracy is down to the second.

func NewTimeZoneIdentifier

func NewTimeZoneIdentifier(identifier string) *TimeZone

NewTimeZoneIdentifier constructs a struct TimeZone.

func NewTimeZoneLocal

func NewTimeZoneLocal() *TimeZone

NewTimeZoneLocal constructs a struct TimeZone.

func NewTimeZoneOffset

func NewTimeZoneOffset(seconds int32) *TimeZone

NewTimeZoneOffset constructs a struct TimeZone.

func NewTimeZoneUTC

func NewTimeZoneUTC() *TimeZone

NewTimeZoneUTC constructs a struct TimeZone.

func (*TimeZone) Abbreviation

func (tz *TimeZone) Abbreviation(interval int) string

Abbreviation determines the time zone abbreviation to be used during a particular interval of time in the time zone tz.

For example, in Toronto this is currently "EST" during the winter months and "EDT" during the summer months when daylight savings time is in effect.

The function takes the following parameters:

  • interval within the timezone.

The function returns the following values:

  • utf8: time zone abbreviation, which belongs to tz.

func (*TimeZone) AdjustTime

func (tz *TimeZone) AdjustTime(typ TimeType, time_ *int64) int

AdjustTime finds an interval within tz that corresponds to the given time_, possibly adjusting time_ if required to fit into an interval. The meaning of time_ depends on type.

This function is similar to g_time_zone_find_interval(), with the difference that it always succeeds (by making the adjustments described below).

In any of the cases where g_time_zone_find_interval() succeeds then this function returns the same value, without modifying time_.

This function may, however, modify time_ in order to deal with non-existent times. If the non-existent local time_ of 02:30 were requested on March 14th 2010 in Toronto then this function would adjust time_ to be 03:00 and return the interval containing the adjusted time.

The function takes the following parameters:

  • typ of time_.
  • time_: pointer to a number of seconds since January 1, 1970.

The function returns the following values:

  • gint: interval containing time_, never -1.

func (*TimeZone) FindInterval

func (tz *TimeZone) FindInterval(typ TimeType, time_ int64) int

FindInterval finds an interval within tz that corresponds to the given time_. The meaning of time_ depends on type.

If type is G_TIME_TYPE_UNIVERSAL then this function will always succeed (since universal time is monotonic and continuous).

Otherwise time_ is treated as local time. The distinction between G_TIME_TYPE_STANDARD and G_TIME_TYPE_DAYLIGHT is ignored except in the case that the given time_ is ambiguous. In Toronto, for example, 01:30 on November 7th 2010 occurred twice (once inside of daylight savings time and the next, an hour later, outside of daylight savings time). In this case, the different value of type would result in a different interval being returned.

It is still possible for this function to fail. In Toronto, for example, 02:00 on March 14th 2010 does not exist (due to the leap forward to begin daylight savings time). -1 is returned in that case.

The function takes the following parameters:

  • typ of time_.
  • time_: number of seconds since January 1, 1970.

The function returns the following values:

  • gint: interval containing time_, or -1 in case of failure.

func (*TimeZone) Identifier

func (tz *TimeZone) Identifier() string

Identifier: get the identifier of this Zone, as passed to g_time_zone_new(). If the identifier passed at construction time was not recognised, UTC will be returned. If it was NULL, the identifier of the local timezone at construction time will be returned.

The identifier will be returned in the same format as provided at construction time: if provided as a time offset, that will be returned by this function.

The function returns the following values:

  • utf8: identifier for this timezone.

func (*TimeZone) IsDst

func (tz *TimeZone) IsDst(interval int) bool

IsDst determines if daylight savings time is in effect during a particular interval of time in the time zone tz.

The function takes the following parameters:

  • interval within the timezone.

The function returns the following values:

  • ok: TRUE if daylight savings time is in effect.

func (*TimeZone) Offset

func (tz *TimeZone) Offset(interval int) int32

Offset determines the offset to UTC in effect during a particular interval of time in the time zone tz.

The offset is the number of seconds that you add to UTC time to arrive at local time for tz (ie: negative numbers for time zones west of GMT, positive numbers for east).

The function takes the following parameters:

  • interval within the timezone.

The function returns the following values:

  • gint32: number of seconds that should be added to UTC to get the local time in tz.

type TokenType

type TokenType C.gint

TokenType: possible types of token returned from each g_scanner_get_next_token() call.

const (
	// TokenEOF: end of the file.
	TokenEOF TokenType = 0
	// TokenLeftParen: '(' character.
	TokenLeftParen TokenType = 40
	// TokenRightParen: ')' character.
	TokenRightParen TokenType = 41
	// TokenLeftCurly: '{' character.
	TokenLeftCurly TokenType = 123
	// TokenRightCurly: '}' character.
	TokenRightCurly TokenType = 125
	// TokenLeftBrace: '[' character.
	TokenLeftBrace TokenType = 91
	// TokenRightBrace: ']' character.
	TokenRightBrace TokenType = 93
	// TokenEqualSign: '=' character.
	TokenEqualSign TokenType = 61
	// TokenComma: ',' character.
	TokenComma TokenType = 44
	// TokenNone: not a token.
	TokenNone TokenType = 256
	// TokenError: error occurred.
	TokenError TokenType = 257
	// TokenChar: character.
	TokenChar TokenType = 258
	// TokenBinary: binary integer.
	TokenBinary TokenType = 259
	// TokenOctal: octal integer.
	TokenOctal TokenType = 260
	// TokenInt: integer.
	TokenInt TokenType = 261
	// TokenHex: hex integer.
	TokenHex TokenType = 262
	// TokenFloat: floating point number.
	TokenFloat TokenType = 263
	// TokenString: string.
	TokenString TokenType = 264
	// TokenSymbol: symbol.
	TokenSymbol TokenType = 265
	// TokenIdentifier: identifier.
	TokenIdentifier TokenType = 266
	// TokenIdentifierNull: null identifier.
	TokenIdentifierNull TokenType = 267
	// TokenCommentSingle: one line comment.
	TokenCommentSingle TokenType = 268
	// TokenCommentMulti: multi line comment.
	TokenCommentMulti TokenType = 269
)

func (TokenType) String

func (t TokenType) String() string

String returns the name in string for TokenType.

type TraverseFlags

type TraverseFlags C.guint

TraverseFlags specifies which nodes are visited during several of the tree functions, including g_node_traverse() and g_node_find().

const (
	// TraverseLeaves: only leaf nodes should be visited. This name has been
	// introduced in 2.6, for older version use G_TRAVERSE_LEAFS.
	TraverseLeaves TraverseFlags = 0b1
	// TraverseNonLeaves: only non-leaf nodes should be visited. This name has
	// been introduced in 2.6, for older version use G_TRAVERSE_NON_LEAFS.
	TraverseNonLeaves TraverseFlags = 0b10
	// TraverseAll: all nodes should be visited.
	TraverseAll TraverseFlags = 0b11
	// TraverseMask: mask of all traverse flags.
	TraverseMask TraverseFlags = 0b11
	// TraverseLeafs: identical to G_TRAVERSE_LEAVES.
	TraverseLeafs TraverseFlags = 0b1
	// TraverseNonLeafs: identical to G_TRAVERSE_NON_LEAVES.
	TraverseNonLeafs TraverseFlags = 0b10
)

func (TraverseFlags) Has

func (t TraverseFlags) Has(other TraverseFlags) bool

Has returns true if t contains other.

func (TraverseFlags) String

func (t TraverseFlags) String() string

String returns the names in string for TraverseFlags.

type TraverseType

type TraverseType C.gint

TraverseType specifies the type of traversal performed by g_tree_traverse(), g_node_traverse() and g_node_find(). The different orders are illustrated here:

- In order: A, B, C, D, E, F, G, H, I ! (Sorted_binary_tree_inorder.svg)

- Pre order: F, B, A, D, C, E, G, I, H ! (Sorted_binary_tree_preorder.svg)

- Post order: A, C, E, D, B, H, I, G, F ! (Sorted_binary_tree_postorder.svg)

- Level order: F, B, G, A, D, I, C, E, H ! (Sorted_binary_tree_breadth-first_traversal.svg).

const (
	// InOrder vists a node's left child first, then the node itself, then
	// its right child. This is the one to use if you want the output sorted
	// according to the compare function.
	InOrder TraverseType = iota
	// PreOrder visits a node, then its children.
	PreOrder
	// PostOrder visits the node's children, then the node itself.
	PostOrder
	// LevelOrder is not implemented for [balanced binary
	// trees][glib-Balanced-Binary-Trees]. For [n-ary trees][glib-N-ary-Trees],
	// it vists the root node first, then its children, then its grandchildren,
	// and so on. Note that this is less efficient than the other orders.
	LevelOrder
)

func (TraverseType) String

func (t TraverseType) String() string

String returns the name in string for TraverseType.

type Tree

type Tree struct {
	// contains filtered or unexported fields
}

Tree struct is an opaque data structure representing a [balanced binary tree][glib-Balanced-Binary-Trees]. It should be accessed only by using the following functions.

An instance of this type is always passed by reference.

func (*Tree) Destroy

func (tree *Tree) Destroy()

Destroy removes all keys and values from the #GTree and decreases its reference count by one. If keys and/or values are dynamically allocated, you should either free them first or create the #GTree using g_tree_new_full(). In the latter case the destroy functions you supplied will be called on all keys and values before destroying the #GTree.

func (*Tree) Height

func (tree *Tree) Height() int

Height gets the height of a #GTree.

If the #GTree contains no nodes, the height is 0. If the #GTree contains only one root node the height is 1. If the root node has children the height is 2, etc.

The function returns the following values:

  • gint: height of tree.

func (*Tree) Insert

func (tree *Tree) Insert(key unsafe.Pointer, value unsafe.Pointer)

Insert inserts a key/value pair into a #GTree.

Inserts a new key and value into a #GTree as g_tree_insert_node() does, only this function does not return the inserted or set node.

The function takes the following parameters:

  • key (optional) to insert.
  • value (optional) corresponding to the key.

func (*Tree) Lookup

func (tree *Tree) Lookup(key unsafe.Pointer) unsafe.Pointer

Lookup gets the value corresponding to the given key. Since a #GTree is automatically balanced as key/value pairs are added, key lookup is O(log n) (where n is the number of key/value pairs in the tree).

The function takes the following parameters:

  • key (optional) to look up.

The function returns the following values:

  • gpointer (optional): value corresponding to the key, or NULL if the key was not found.

func (*Tree) LookupExtended

func (tree *Tree) LookupExtended(lookupKey unsafe.Pointer) (origKey unsafe.Pointer, value unsafe.Pointer, ok bool)

LookupExtended looks up a key in the #GTree, returning the original key and the associated value. This is useful if you need to free the memory allocated for the original key, for example before calling g_tree_remove().

The function takes the following parameters:

  • lookupKey (optional): key to look up.

The function returns the following values:

  • origKey (optional) returns the original key.
  • value (optional) returns the value associated with the key.
  • ok: TRUE if the key was found in the #GTree.

func (*Tree) Nnodes

func (tree *Tree) Nnodes() int

Nnodes gets the number of nodes in a #GTree.

The function returns the following values:

  • gint: number of nodes in tree.

func (*Tree) Remove

func (tree *Tree) Remove(key unsafe.Pointer) bool

Remove removes a key/value pair from a #GTree.

If the #GTree was created using g_tree_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. If the key does not exist in the #GTree, the function does nothing.

The cost of maintaining a balanced tree while removing a key/value result in a O(n log(n)) operation where most of the other operations are O(log(n)).

The function takes the following parameters:

  • key (optional) to remove.

The function returns the following values:

  • ok: TRUE if the key was found (prior to 2.8, this function returned nothing).

func (*Tree) Replace

func (tree *Tree) Replace(key unsafe.Pointer, value unsafe.Pointer)

Replace inserts a new key and value into a #GTree as g_tree_replace_node() does, only this function does not return the inserted or set node.

The function takes the following parameters:

  • key (optional) to insert.
  • value (optional) corresponding to the key.

func (*Tree) Steal

func (tree *Tree) Steal(key unsafe.Pointer) bool

Steal removes a key and its associated value from a #GTree without calling the key and value destroy functions.

If the key does not exist in the #GTree, the function does nothing.

The function takes the following parameters:

  • key (optional) to remove.

The function returns the following values:

  • ok: TRUE if the key was found (prior to 2.8, this function returned nothing).

type Type

type Type = coreglib.Type

Type is an alias for pkg/core/glib.Type.

func TypeFromName

func TypeFromName(typeName string) Type

TypeFromName is an alias for pkg/core/glib.TypeFromName.

type URI

type URI struct {
	// contains filtered or unexported fields
}

URI type and related functions can be used to parse URIs into their components, and build valid URIs from individual components.

Note that #GUri scope is to help manipulate URIs in various applications, following RFC 3986 (https://tools.ietf.org/html/rfc3986). In particular, it doesn't intend to cover web browser needs, and doesn't implement the WHATWG URL (https://url.spec.whatwg.org/) standard. No APIs are provided to help prevent homograph attacks (https://en.wikipedia.org/wiki/IDN_homograph_attack), so #GUri is not suitable for formatting URIs for display to the user for making security-sensitive decisions.

Relative and absolute URIs

As defined in RFC 3986 (https://tools.ietf.org/html/rfc3986#section-4), the hierarchical nature of URIs means that they can either be ‘relative references’ (sometimes referred to as ‘relative URIs’) or ‘URIs’ (for clarity, ‘URIs’ are referred to in this documentation as ‘absolute URIs’ — although in constrast to RFC 3986 (https://tools.ietf.org/html/rfc3986#section-4.3), fragment identifiers are always allowed).

Relative references have one or more components of the URI missing. In particular, they have no scheme. Any other component, such as hostname, query, etc. may be missing, apart from a path, which has to be specified (but may be empty). The path may be relative, starting with ./ rather than /.

For example, a valid relative reference is ./path?query, /?query#fragment or //example.com.

Absolute URIs have a scheme specified. Any other components of the URI which are missing are specified as explicitly unset in the URI, rather than being resolved relative to a base URI using g_uri_parse_relative().

For example, a valid absolute URI is file:///home/bob or https://search.com?query=string.

A #GUri instance is always an absolute URI. A string may be an absolute URI or a relative reference; see the documentation for individual functions as to what forms they accept.

Parsing URIs

The most minimalist APIs for parsing URIs are g_uri_split() and g_uri_split_with_user(). These split a URI into its component parts, and return the parts; the difference between the two is that g_uri_split() treats the ‘userinfo’ component of the URI as a single element, while g_uri_split_with_user() can (depending on the Flags you pass) treat it as containing a username, password, and authentication parameters. Alternatively, g_uri_split_network() can be used when you are only interested in the components that are needed to initiate a network connection to the service (scheme, host, and port).

g_uri_parse() is similar to g_uri_split(), but instead of returning individual strings, it returns a #GUri structure (and it requires that the URI be an absolute URI).

g_uri_resolve_relative() and g_uri_parse_relative() allow you to resolve a relative URI relative to a base URI. g_uri_resolve_relative() takes two strings and returns a string, and g_uri_parse_relative() takes a #GUri and a string and returns a #GUri.

All of the parsing functions take a Flags argument describing exactly how to parse the URI; see the documentation for that type for more details on the specific flags that you can pass. If you need to choose different flags based on the type of URI, you can use g_uri_peek_scheme() on the URI string to check the scheme first, and use that to decide what flags to parse it with.

For example, you might want to use G_URI_PARAMS_WWW_FORM when parsing the params for a web URI, so compare the result of g_uri_peek_scheme() against http and https.

Building URIs

g_uri_join() and g_uri_join_with_user() can be used to construct valid URI strings from a set of component strings. They are the inverse of g_uri_split() and g_uri_split_with_user().

Similarly, g_uri_build() and g_uri_build_with_user() can be used to construct a #GUri from a set of component strings.

As with the parsing functions, the building functions take a Flags argument. In particular, it is important to keep in mind whether the URI components you are using are already %-encoded. If so, you must pass the G_URI_FLAGS_ENCODED flag.

file:// URIs

Note that Windows and Unix both define special rules for parsing file:// URIs (involving non-UTF-8 character sets on Unix, and the interpretation of path separators on Windows). #GUri does not implement these rules. Use g_filename_from_uri() and g_filename_to_uri() if you want to properly convert between file:// URIs and local filenames.

URI Equality

Note that there is no g_uri_equal () function, because comparing URIs usefully requires scheme-specific knowledge that #GUri does not have. #GUri can help with normalization if you use the various encoded Flags as well as G_URI_FLAGS_SCHEME_NORMALIZE however it is not comprehensive. For example, data:,foo and data:;base64,Zm9v resolve to the same thing according to the data: URI specification which GLib does not handle.

An instance of this type is always passed by reference.

func URIBuild

func URIBuild(flags URIFlags, scheme, userinfo, host string, port int, path, query, fragment string) *URI

URIBuild creates a new #GUri from the given components according to flags.

See also g_uri_build_with_user(), which allows specifying the components of the "userinfo" separately.

The function takes the following parameters:

  • flags describing how to build the #GUri.
  • scheme: URI scheme.
  • userinfo (optional) component, or NULL.
  • host (optional) component, or NULL.
  • port: port, or -1.
  • path component.
  • query (optional) component, or NULL.
  • fragment (optional): fragment, or NULL.

The function returns the following values:

  • uri: new #GUri.

func URIBuildWithUser

func URIBuildWithUser(flags URIFlags, scheme, user, password, authParams, host string, port int, path, query, fragment string) *URI

URIBuildWithUser creates a new #GUri from the given components according to flags (G_URI_FLAGS_HAS_PASSWORD is added unconditionally). The flags must be coherent with the passed values, in particular use %-encoded values with G_URI_FLAGS_ENCODED.

In contrast to g_uri_build(), this allows specifying the components of the ‘userinfo’ field separately. Note that user must be non-NULL if either password or auth_params is non-NULL.

The function takes the following parameters:

  • flags describing how to build the #GUri.
  • scheme: URI scheme.
  • user (optional) component of the userinfo, or NULL.
  • password (optional) component of the userinfo, or NULL.
  • authParams (optional): auth params of the userinfo, or NULL.
  • host (optional) component, or NULL.
  • port: port, or -1.
  • path component.
  • query (optional) component, or NULL.
  • fragment (optional): fragment, or NULL.

The function returns the following values:

  • uri: new #GUri.

func URIParse

func URIParse(uriString string, flags URIFlags) (*URI, error)

URIParse parses uri_string according to flags. If the result is not a valid [absolute URI][relative-absolute-uris], it will be discarded, and an error returned.

The function takes the following parameters:

  • uriString: string representing an absolute URI.
  • flags describing how to parse uri_string.

The function returns the following values:

  • uri: new #GUri, or NULL on error.

func (*URI) AuthParams

func (uri *URI) AuthParams() string

AuthParams gets uri's authentication parameters, which may contain %-encoding, depending on the flags with which uri was created. (If uri was not created with G_URI_FLAGS_HAS_AUTH_PARAMS then this will be NULL.)

Depending on the URI scheme, g_uri_parse_params() may be useful for further parsing this information.

The function returns the following values:

  • utf8 (optional) uri's authentication parameters.

func (*URI) Flags

func (uri *URI) Flags() URIFlags

Flags gets uri's flags set upon construction.

The function returns the following values:

  • uriFlags uri's flags.

func (*URI) Fragment

func (uri *URI) Fragment() string

Fragment gets uri's fragment, which may contain %-encoding, depending on the flags with which uri was created.

The function returns the following values:

  • utf8 (optional) uri's fragment.

func (*URI) Host

func (uri *URI) Host() string

Host gets uri's host. This will never have %-encoded characters, unless it is non-UTF-8 (which can only be the case if uri was created with G_URI_FLAGS_NON_DNS).

If uri contained an IPv6 address literal, this value will be just that address, without the brackets around it that are necessary in the string form of the URI. Note that in this case there may also be a scope ID attached to the address. Eg, fe80::1234em1 (or fe80::123425em1 if the string is still encoded).

The function returns the following values:

  • utf8 (optional) uri's host.

func (*URI) ParseRelative

func (baseUri *URI) ParseRelative(uriRef string, flags URIFlags) (*URI, error)

ParseRelative parses uri_ref according to flags and, if it is a [relative URI][relative-absolute-uris], resolves it relative to base_uri. If the result is not a valid absolute URI, it will be discarded, and an error returned.

The function takes the following parameters:

  • uriRef: string representing a relative or absolute URI.
  • flags describing how to parse uri_ref.

The function returns the following values:

  • uri: new #GUri, or NULL on error.

func (*URI) Password

func (uri *URI) Password() string

Password gets uri's password, which may contain %-encoding, depending on the flags with which uri was created. (If uri was not created with G_URI_FLAGS_HAS_PASSWORD then this will be NULL.).

The function returns the following values:

  • utf8 (optional) uri's password.

func (*URI) Path

func (uri *URI) Path() string

Path gets uri's path, which may contain %-encoding, depending on the flags with which uri was created.

The function returns the following values:

  • utf8 uri's path.

func (*URI) Port

func (uri *URI) Port() int

Port gets uri's port.

The function returns the following values:

  • gint uri's port, or -1 if no port was specified.

func (*URI) Query

func (uri *URI) Query() string

Query gets uri's query, which may contain %-encoding, depending on the flags with which uri was created.

For queries consisting of a series of name=value parameters, ParamsIter or g_uri_parse_params() may be useful.

The function returns the following values:

  • utf8 (optional) uri's query.

func (*URI) Scheme

func (uri *URI) Scheme() string

Scheme gets uri's scheme. Note that this will always be all-lowercase, regardless of the string or strings that uri was created from.

The function returns the following values:

  • utf8 uri's scheme.

func (*URI) String

func (uri *URI) String() string

String returns a string representing uri.

This is not guaranteed to return a string which is identical to the string that uri was parsed from. However, if the source URI was syntactically correct (according to RFC 3986), and it was parsed with G_URI_FLAGS_ENCODED, then g_uri_to_string() is guaranteed to return a string which is at least semantically equivalent to the source URI (according to RFC 3986).

If uri might contain sensitive details, such as authentication parameters, or private data in its query string, and the returned string is going to be logged, then consider using g_uri_to_string_partial() to redact parts.

The function returns the following values:

  • utf8: string representing uri, which the caller must free.

func (*URI) ToStringPartial

func (uri *URI) ToStringPartial(flags URIHideFlags) string

ToStringPartial returns a string representing uri, subject to the options in flags. See g_uri_to_string() and HideFlags for more details.

The function takes the following parameters:

  • flags describing what parts of uri to hide.

The function returns the following values:

  • utf8: string representing uri, which the caller must free.

func (*URI) User

func (uri *URI) User() string

User gets the ‘username’ component of uri's userinfo, which may contain %-encoding, depending on the flags with which uri was created. If uri was not created with G_URI_FLAGS_HAS_PASSWORD or G_URI_FLAGS_HAS_AUTH_PARAMS, this is the same as g_uri_get_userinfo().

The function returns the following values:

  • utf8 (optional) uri's user.

func (*URI) Userinfo

func (uri *URI) Userinfo() string

Userinfo gets uri's userinfo, which may contain %-encoding, depending on the flags with which uri was created.

The function returns the following values:

  • utf8 (optional) uri's userinfo.

type URIError

type URIError C.gint

URIError: error codes returned by #GUri methods.

const (
	// URIErrorFailed: generic error if no more specific error is available.
	// See the error message for details.
	URIErrorFailed URIError = iota
	// URIErrorBadScheme: scheme of a URI could not be parsed.
	URIErrorBadScheme
	// URIErrorBadUser: user/userinfo of a URI could not be parsed.
	URIErrorBadUser
	// URIErrorBadPassword: password of a URI could not be parsed.
	URIErrorBadPassword
	// URIErrorBadAuthParams: authentication parameters of a URI could not be
	// parsed.
	URIErrorBadAuthParams
	// URIErrorBadHost: host of a URI could not be parsed.
	URIErrorBadHost
	// URIErrorBadPort: port of a URI could not be parsed.
	URIErrorBadPort
	// URIErrorBadPath: path of a URI could not be parsed.
	URIErrorBadPath
	// URIErrorBadQuery: query of a URI could not be parsed.
	URIErrorBadQuery
	// URIErrorBadFragment: fragment of a URI could not be parsed.
	URIErrorBadFragment
)

func (URIError) String

func (u URIError) String() string

String returns the name in string for URIError.

type URIFlags

type URIFlags C.guint

URIFlags flags that describe a URI.

When parsing a URI, if you need to choose different flags based on the type of URI, you can use g_uri_peek_scheme() on the URI string to check the scheme first, and use that to decide what flags to parse it with.

const (
	// URIFlagsNone: no flags set.
	URIFlagsNone URIFlags = 0b0
	// URIFlagsParseRelaxed: parse the URI more relaxedly than the RFC 3986
	// (https://tools.ietf.org/html/rfc3986) grammar specifies, fixing up or
	// ignoring common mistakes in URIs coming from external sources. This is
	// also needed for some obscure URI schemes where ; separates the host from
	// the path. Don’t use this flag unless you need to.
	URIFlagsParseRelaxed URIFlags = 0b1
	// URIFlagsHasPassword: userinfo field may contain a password, which will be
	// separated from the username by :.
	URIFlagsHasPassword URIFlags = 0b10
	// URIFlagsHasAuthParams: userinfo may contain additional
	// authentication-related parameters, which will be separated from the
	// username and/or password by ;.
	URIFlagsHasAuthParams URIFlags = 0b100
	// URIFlagsEncoded: when parsing a URI, this indicates that %-encoded
	// characters in the userinfo, path, query, and fragment fields should not
	// be decoded. (And likewise the host field if G_URI_FLAGS_NON_DNS is also
	// set.) When building a URI, it indicates that you have already %-encoded
	// the components, and so #GUri should not do any encoding itself.
	URIFlagsEncoded URIFlags = 0b1000
	// URIFlagsNonDns: host component should not be assumed to be a DNS hostname
	// or IP address (for example, for smb URIs with NetBIOS hostnames).
	URIFlagsNonDns URIFlags = 0b10000
	// URIFlagsEncodedQuery: same as G_URI_FLAGS_ENCODED, for the query field
	// only.
	URIFlagsEncodedQuery URIFlags = 0b100000
	// URIFlagsEncodedPath: same as G_URI_FLAGS_ENCODED, for the path only.
	URIFlagsEncodedPath URIFlags = 0b1000000
	// URIFlagsEncodedFragment: same as G_URI_FLAGS_ENCODED, for the fragment
	// only.
	URIFlagsEncodedFragment URIFlags = 0b10000000
	// URIFlagsSchemeNormalize: scheme-based normalization will be applied.
	// For example, when parsing an HTTP URI changing omitted path to / and
	// omitted port to 80; and when building a URI, changing empty path to / and
	// default port 80). This only supports a subset of known schemes. (Since:
	// 2.68).
	URIFlagsSchemeNormalize URIFlags = 0b100000000
)

func (URIFlags) Has

func (u URIFlags) Has(other URIFlags) bool

Has returns true if u contains other.

func (URIFlags) String

func (u URIFlags) String() string

String returns the names in string for URIFlags.

type URIHideFlags

type URIHideFlags C.guint

URIHideFlags flags describing what parts of the URI to hide in g_uri_to_string_partial(). Note that G_URI_HIDE_PASSWORD and G_URI_HIDE_AUTH_PARAMS will only work if the #GUri was parsed with the corresponding flags.

const (
	// URIHideNone: no flags set.
	URIHideNone URIHideFlags = 0b0
	// URIHideUserinfo: hide the userinfo.
	URIHideUserinfo URIHideFlags = 0b1
	// URIHidePassword: hide the password.
	URIHidePassword URIHideFlags = 0b10
	// URIHideAuthParams: hide the auth_params.
	URIHideAuthParams URIHideFlags = 0b100
	// URIHideQuery: hide the query.
	URIHideQuery URIHideFlags = 0b1000
	// URIHideFragment: hide the fragment.
	URIHideFragment URIHideFlags = 0b10000
)

func (URIHideFlags) Has

func (u URIHideFlags) Has(other URIHideFlags) bool

Has returns true if u contains other.

func (URIHideFlags) String

func (u URIHideFlags) String() string

String returns the names in string for URIHideFlags.

type URIParamsFlags

type URIParamsFlags C.guint

URIParamsFlags flags modifying the way parameters are handled by g_uri_parse_params() and ParamsIter.

const (
	// URIParamsNone: no flags set.
	URIParamsNone URIParamsFlags = 0b0
	// URIParamsCaseInsensitive: parameter names are case insensitive.
	URIParamsCaseInsensitive URIParamsFlags = 0b1
	// URIParamsWwwForm: replace + with space character. Only useful for URLs on
	// the web, using the https or http schemas.
	URIParamsWwwForm URIParamsFlags = 0b10
	// URIParamsParseRelaxed: see G_URI_FLAGS_PARSE_RELAXED.
	URIParamsParseRelaxed URIParamsFlags = 0b100
)

func (URIParamsFlags) Has

func (u URIParamsFlags) Has(other URIParamsFlags) bool

Has returns true if u contains other.

func (URIParamsFlags) String

func (u URIParamsFlags) String() string

String returns the names in string for URIParamsFlags.

type URIParamsIter

type URIParamsIter struct {
	// contains filtered or unexported fields
}

URIParamsIter: many URI schemes include one or more attribute/value pairs as part of the URI value. For example scheme://server/path?query=string&is=there has two attributes – query=string and is=there – in its query part.

A ParamsIter structure represents an iterator that can be used to iterate over the attribute/value pairs of a URI query string. ParamsIter structures are typically allocated on the stack and then initialized with g_uri_params_iter_init(). See the documentation for g_uri_params_iter_init() for a usage example.

An instance of this type is always passed by reference.

func (*URIParamsIter) Init

func (iter *URIParamsIter) Init(params string, length int, separators string, flags URIParamsFlags)

Init initializes an attribute/value pair iterator.

The iterator keeps pointers to the params and separators arguments, those variables must thus outlive the iterator and not be modified during the iteration.

If G_URI_PARAMS_WWW_FORM is passed in flags, + characters in the param string will be replaced with spaces in the output. For example, foo=bar+baz will give attribute foo with value bar baz. This is commonly used on the web (the https and http schemes only), but is deprecated in favour of the equivalent of encoding spaces as 20.

Unlike with g_uri_parse_params(), G_URI_PARAMS_CASE_INSENSITIVE has no effect if passed to flags for g_uri_params_iter_init(). The caller is responsible for doing their own case-insensitive comparisons.

GUriParamsIter iter;
GError *error = NULL;
gchar *unowned_attr, *unowned_value;

g_uri_params_iter_init (&iter, "foo=bar&baz=bar&Foo=frob&baz=bar2", -1, "&", G_URI_PARAMS_NONE);
while (g_uri_params_iter_next (&iter, &unowned_attr, &unowned_value, &error))
  {
    g_autofree gchar *attr = g_steal_pointer (&unowned_attr);
    g_autofree gchar *value = g_steal_pointer (&unowned_value);
    // do something with attr and value; this code will be called 4 times
    // for the params string in this example: once with attr=foo and value=bar,
    // then with baz/bar, then Foo/frob, then baz/bar2.
  }
if (error)
  // handle parsing error.

The function takes the following parameters:

  • params: %-encoded string containing attribute=value parameters.
  • length of params, or -1 if it is nul-terminated.
  • separators: 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 to modify the way the parameters are handled.

func (*URIParamsIter) Next

func (iter *URIParamsIter) Next() (attribute string, value string, goerr error)

Next advances iter and retrieves the next attribute/value. FALSE is returned if an error has occurred (in which case error is set), or if the end of the iteration is reached (in which case attribute and value are set to NULL and the iterator becomes invalid). If TRUE is returned, g_uri_params_iter_next() may be called again to receive another attribute/value pair.

Note that the same attribute may be returned multiple times, since URIs allow repeated attributes.

The function returns the following values:

  • attribute (optional): on return, contains the attribute, or NULL.
  • value (optional): on return, contains the value, or NULL.

type UnicodeBreakType

type UnicodeBreakType C.gint

UnicodeBreakType: these are the possible line break classifications.

Since new unicode versions may add new types here, applications should be ready to handle unknown values. They may be regarded as G_UNICODE_BREAK_UNKNOWN.

See Unicode Line Breaking Algorithm (http://www.unicode.org/unicode/reports/tr14/).

const (
	// UnicodeBreakMandatory: mandatory Break (BK).
	UnicodeBreakMandatory UnicodeBreakType = iota
	// UnicodeBreakCarriageReturn: carriage Return (CR).
	UnicodeBreakCarriageReturn
	// UnicodeBreakLineFeed: line Feed (LF).
	UnicodeBreakLineFeed
	// UnicodeBreakCombiningMark: attached Characters and Combining Marks (CM).
	UnicodeBreakCombiningMark
	// UnicodeBreakSurrogate surrogates (SG).
	UnicodeBreakSurrogate
	// UnicodeBreakZeroWidthSpace: zero Width Space (ZW).
	UnicodeBreakZeroWidthSpace
	// UnicodeBreakInseparable: inseparable (IN).
	UnicodeBreakInseparable
	// UnicodeBreakNonBreakingGlue: non-breaking ("Glue") (GL).
	UnicodeBreakNonBreakingGlue
	// UnicodeBreakContingent: contingent Break Opportunity (CB).
	UnicodeBreakContingent
	// UnicodeBreakSpace: space (SP).
	UnicodeBreakSpace
	// UnicodeBreakAfter: break Opportunity After (BA).
	UnicodeBreakAfter
	// UnicodeBreakBefore: break Opportunity Before (BB).
	UnicodeBreakBefore
	// UnicodeBreakBeforeAndAfter: break Opportunity Before and After (B2).
	UnicodeBreakBeforeAndAfter
	// UnicodeBreakHyphen: hyphen (HY).
	UnicodeBreakHyphen
	// UnicodeBreakNonStarter: nonstarter (NS).
	UnicodeBreakNonStarter
	// UnicodeBreakOpenPunctuation: opening Punctuation (OP).
	UnicodeBreakOpenPunctuation
	// UnicodeBreakClosePunctuation: closing Punctuation (CL).
	UnicodeBreakClosePunctuation
	// UnicodeBreakQuotation ambiguous Quotation (QU).
	UnicodeBreakQuotation
	// UnicodeBreakExclamation: exclamation/Interrogation (EX).
	UnicodeBreakExclamation
	// UnicodeBreakIdeographic: ideographic (ID).
	UnicodeBreakIdeographic
	// UnicodeBreakNumeric: numeric (NU).
	UnicodeBreakNumeric
	// UnicodeBreakInfixSeparator: infix Separator (Numeric) (IS).
	UnicodeBreakInfixSeparator
	// UnicodeBreakSymbol symbols Allowing Break After (SY).
	UnicodeBreakSymbol
	// UnicodeBreakAlphabetic: ordinary Alphabetic and Symbol Characters (AL).
	UnicodeBreakAlphabetic
	// UnicodeBreakPrefix: prefix (Numeric) (PR).
	UnicodeBreakPrefix
	// UnicodeBreakPostfix: postfix (Numeric) (PO).
	UnicodeBreakPostfix
	// UnicodeBreakComplexContext: complex Content Dependent (South East Asian)
	// (SA).
	UnicodeBreakComplexContext
	// UnicodeBreakAmbiguous ambiguous (Alphabetic or Ideographic) (AI).
	UnicodeBreakAmbiguous
	// UnicodeBreakUnknown: unknown (XX).
	UnicodeBreakUnknown
	// UnicodeBreakNextLine: next Line (NL).
	UnicodeBreakNextLine
	// UnicodeBreakWordJoiner: word Joiner (WJ).
	UnicodeBreakWordJoiner
	// UnicodeBreakHangulLJamo: hangul L Jamo (JL).
	UnicodeBreakHangulLJamo
	// UnicodeBreakHangulVJamo: hangul V Jamo (JV).
	UnicodeBreakHangulVJamo
	// UnicodeBreakHangulTJamo: hangul T Jamo (JT).
	UnicodeBreakHangulTJamo
	// UnicodeBreakHangulLvSyllable: hangul LV Syllable (H2).
	UnicodeBreakHangulLvSyllable
	// UnicodeBreakHangulLvtSyllable: hangul LVT Syllable (H3).
	UnicodeBreakHangulLvtSyllable
	// UnicodeBreakCloseParanthesis: closing Parenthesis (CP). Since 2.28.
	UnicodeBreakCloseParanthesis
	// UnicodeBreakConditionalJapaneseStarter: conditional Japanese Starter
	// (CJ). Since: 2.32.
	UnicodeBreakConditionalJapaneseStarter
	// UnicodeBreakHebrewLetter: hebrew Letter (HL). Since: 2.32.
	UnicodeBreakHebrewLetter
	// UnicodeBreakRegionalIndicator: regional Indicator (RI). Since: 2.36.
	UnicodeBreakRegionalIndicator
	// UnicodeBreakEmojiBase: emoji Base (EB). Since: 2.50.
	UnicodeBreakEmojiBase
	// UnicodeBreakEmojiModifier: emoji Modifier (EM). Since: 2.50.
	UnicodeBreakEmojiModifier
	// UnicodeBreakZeroWidthJoiner: zero Width Joiner (ZWJ). Since: 2.50.
	UnicodeBreakZeroWidthJoiner
)

func UnicharBreakType

func UnicharBreakType(c uint32) UnicodeBreakType

UnicharBreakType determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use g_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.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • unicodeBreakType: break type of c.

func (UnicodeBreakType) String

func (u UnicodeBreakType) String() string

String returns the name in string for UnicodeBreakType.

type UnicodeScript

type UnicodeScript C.gint

UnicodeScript enumeration identifies different writing systems. The values correspond to the names as defined in the Unicode standard. The enumeration has been added in GLib 2.14, and is interchangeable with Script.

Note that new types may be added in the future. Applications should be ready to handle unknown values. See Unicode Standard Annex #24: Script names (http://www.unicode.org/reports/tr24/).

const (
	// UnicodeScriptInvalidCode: value never returned from
	// g_unichar_get_script().
	UnicodeScriptInvalidCode UnicodeScript = -1
	// UnicodeScriptCommon: character used by multiple different scripts.
	UnicodeScriptCommon UnicodeScript = 0
	// UnicodeScriptInherited: mark glyph that takes its script from the base
	// glyph to which it is attached.
	UnicodeScriptInherited UnicodeScript = 1
	// UnicodeScriptArabic: arabic.
	UnicodeScriptArabic UnicodeScript = 2
	// UnicodeScriptArmenian: armenian.
	UnicodeScriptArmenian UnicodeScript = 3
	// UnicodeScriptBengali: bengali.
	UnicodeScriptBengali UnicodeScript = 4
	// UnicodeScriptBopomofo: bopomofo.
	UnicodeScriptBopomofo UnicodeScript = 5
	// UnicodeScriptCherokee: cherokee.
	UnicodeScriptCherokee UnicodeScript = 6
	// UnicodeScriptCoptic: coptic.
	UnicodeScriptCoptic UnicodeScript = 7
	// UnicodeScriptCyrillic: cyrillic.
	UnicodeScriptCyrillic UnicodeScript = 8
	// UnicodeScriptDeseret: deseret.
	UnicodeScriptDeseret UnicodeScript = 9
	// UnicodeScriptDevanagari: devanagari.
	UnicodeScriptDevanagari UnicodeScript = 10
	// UnicodeScriptEthiopic: ethiopic.
	UnicodeScriptEthiopic UnicodeScript = 11
	// UnicodeScriptGeorgian: georgian.
	UnicodeScriptGeorgian UnicodeScript = 12
	// UnicodeScriptGothic: gothic.
	UnicodeScriptGothic UnicodeScript = 13
	// UnicodeScriptGreek: greek.
	UnicodeScriptGreek UnicodeScript = 14
	// UnicodeScriptGujarati: gujarati.
	UnicodeScriptGujarati UnicodeScript = 15
	// UnicodeScriptGurmukhi: gurmukhi.
	UnicodeScriptGurmukhi UnicodeScript = 16
	// UnicodeScriptHan: han.
	UnicodeScriptHan UnicodeScript = 17
	// UnicodeScriptHangul: hangul.
	UnicodeScriptHangul UnicodeScript = 18
	// UnicodeScriptHebrew: hebrew.
	UnicodeScriptHebrew UnicodeScript = 19
	// UnicodeScriptHiragana: hiragana.
	UnicodeScriptHiragana UnicodeScript = 20
	// UnicodeScriptKannada: kannada.
	UnicodeScriptKannada UnicodeScript = 21
	// UnicodeScriptKatakana: katakana.
	UnicodeScriptKatakana UnicodeScript = 22
	// UnicodeScriptKhmer: khmer.
	UnicodeScriptKhmer UnicodeScript = 23
	// UnicodeScriptLao: lao.
	UnicodeScriptLao UnicodeScript = 24
	// UnicodeScriptLatin: latin.
	UnicodeScriptLatin UnicodeScript = 25
	// UnicodeScriptMalayalam: malayalam.
	UnicodeScriptMalayalam UnicodeScript = 26
	// UnicodeScriptMongolian: mongolian.
	UnicodeScriptMongolian UnicodeScript = 27
	// UnicodeScriptMyanmar: myanmar.
	UnicodeScriptMyanmar UnicodeScript = 28
	// UnicodeScriptOgham: ogham.
	UnicodeScriptOgham UnicodeScript = 29
	// UnicodeScriptOldItalic: old Italic.
	UnicodeScriptOldItalic UnicodeScript = 30
	// UnicodeScriptOriya: oriya.
	UnicodeScriptOriya UnicodeScript = 31
	// UnicodeScriptRunic: runic.
	UnicodeScriptRunic UnicodeScript = 32
	// UnicodeScriptSinhala: sinhala.
	UnicodeScriptSinhala UnicodeScript = 33
	// UnicodeScriptSyriac: syriac.
	UnicodeScriptSyriac UnicodeScript = 34
	// UnicodeScriptTamil: tamil.
	UnicodeScriptTamil UnicodeScript = 35
	// UnicodeScriptTelugu: telugu.
	UnicodeScriptTelugu UnicodeScript = 36
	// UnicodeScriptThaana: thaana.
	UnicodeScriptThaana UnicodeScript = 37
	// UnicodeScriptThai: thai.
	UnicodeScriptThai UnicodeScript = 38
	// UnicodeScriptTibetan: tibetan.
	UnicodeScriptTibetan UnicodeScript = 39
	// UnicodeScriptCanadianAboriginal: canadian Aboriginal.
	UnicodeScriptCanadianAboriginal UnicodeScript = 40
	// UnicodeScriptYi: yi.
	UnicodeScriptYi UnicodeScript = 41
	// UnicodeScriptTagalog: tagalog.
	UnicodeScriptTagalog UnicodeScript = 42
	// UnicodeScriptHanunoo: hanunoo.
	UnicodeScriptHanunoo UnicodeScript = 43
	// UnicodeScriptBuhid: buhid.
	UnicodeScriptBuhid UnicodeScript = 44
	// UnicodeScriptTagbanwa: tagbanwa.
	UnicodeScriptTagbanwa UnicodeScript = 45
	// UnicodeScriptBraille: braille.
	UnicodeScriptBraille UnicodeScript = 46
	// UnicodeScriptCypriot: cypriot.
	UnicodeScriptCypriot UnicodeScript = 47
	// UnicodeScriptLimbu: limbu.
	UnicodeScriptLimbu UnicodeScript = 48
	// UnicodeScriptOsmanya: osmanya.
	UnicodeScriptOsmanya UnicodeScript = 49
	// UnicodeScriptShavian: shavian.
	UnicodeScriptShavian UnicodeScript = 50
	// UnicodeScriptLinearB: linear B.
	UnicodeScriptLinearB UnicodeScript = 51
	// UnicodeScriptTaiLe: tai Le.
	UnicodeScriptTaiLe UnicodeScript = 52
	// UnicodeScriptUgaritic: ugaritic.
	UnicodeScriptUgaritic UnicodeScript = 53
	// UnicodeScriptNewTaiLue: new Tai Lue.
	UnicodeScriptNewTaiLue UnicodeScript = 54
	// UnicodeScriptBuginese: buginese.
	UnicodeScriptBuginese UnicodeScript = 55
	// UnicodeScriptGlagolitic: glagolitic.
	UnicodeScriptGlagolitic UnicodeScript = 56
	// UnicodeScriptTifinagh: tifinagh.
	UnicodeScriptTifinagh UnicodeScript = 57
	// UnicodeScriptSylotiNagri: syloti Nagri.
	UnicodeScriptSylotiNagri UnicodeScript = 58
	// UnicodeScriptOldPersian: old Persian.
	UnicodeScriptOldPersian UnicodeScript = 59
	// UnicodeScriptKharoshthi: kharoshthi.
	UnicodeScriptKharoshthi UnicodeScript = 60
	// UnicodeScriptUnknown: unassigned code point.
	UnicodeScriptUnknown UnicodeScript = 61
	// UnicodeScriptBalinese: balinese.
	UnicodeScriptBalinese UnicodeScript = 62
	// UnicodeScriptCuneiform: cuneiform.
	UnicodeScriptCuneiform UnicodeScript = 63
	// UnicodeScriptPhoenician: phoenician.
	UnicodeScriptPhoenician UnicodeScript = 64
	// UnicodeScriptPhagsPa: phags-pa.
	UnicodeScriptPhagsPa UnicodeScript = 65
	// UnicodeScriptNko: n'Ko.
	UnicodeScriptNko UnicodeScript = 66
	// UnicodeScriptKayahLi: kayah Li. Since 2.16.3.
	UnicodeScriptKayahLi UnicodeScript = 67
	// UnicodeScriptLepcha: lepcha. Since 2.16.3.
	UnicodeScriptLepcha UnicodeScript = 68
	// UnicodeScriptRejang: rejang. Since 2.16.3.
	UnicodeScriptRejang UnicodeScript = 69
	// UnicodeScriptSundanese: sundanese. Since 2.16.3.
	UnicodeScriptSundanese UnicodeScript = 70
	// UnicodeScriptSaurashtra: saurashtra. Since 2.16.3.
	UnicodeScriptSaurashtra UnicodeScript = 71
	// UnicodeScriptCham: cham. Since 2.16.3.
	UnicodeScriptCham UnicodeScript = 72
	// UnicodeScriptOlChiki: ol Chiki. Since 2.16.3.
	UnicodeScriptOlChiki UnicodeScript = 73
	// UnicodeScriptVai: vai. Since 2.16.3.
	UnicodeScriptVai UnicodeScript = 74
	// UnicodeScriptCarian: carian. Since 2.16.3.
	UnicodeScriptCarian UnicodeScript = 75
	// UnicodeScriptLycian: lycian. Since 2.16.3.
	UnicodeScriptLycian UnicodeScript = 76
	// UnicodeScriptLydian: lydian. Since 2.16.3.
	UnicodeScriptLydian UnicodeScript = 77
	// UnicodeScriptAvestan: avestan. Since 2.26.
	UnicodeScriptAvestan UnicodeScript = 78
	// UnicodeScriptBamum: bamum. Since 2.26.
	UnicodeScriptBamum UnicodeScript = 79
	// UnicodeScriptEgyptianHieroglyphs: egyptian Hieroglpyhs. Since 2.26.
	UnicodeScriptEgyptianHieroglyphs UnicodeScript = 80
	// UnicodeScriptImperialAramaic: imperial Aramaic. Since 2.26.
	UnicodeScriptImperialAramaic UnicodeScript = 81
	// UnicodeScriptInscriptionalPahlavi: inscriptional Pahlavi. Since 2.26.
	UnicodeScriptInscriptionalPahlavi UnicodeScript = 82
	// UnicodeScriptInscriptionalParthian: inscriptional Parthian. Since 2.26.
	UnicodeScriptInscriptionalParthian UnicodeScript = 83
	// UnicodeScriptJavanese: javanese. Since 2.26.
	UnicodeScriptJavanese UnicodeScript = 84
	// UnicodeScriptKaithi: kaithi. Since 2.26.
	UnicodeScriptKaithi UnicodeScript = 85
	// UnicodeScriptLisu: lisu. Since 2.26.
	UnicodeScriptLisu UnicodeScript = 86
	// UnicodeScriptMeeteiMayek: meetei Mayek. Since 2.26.
	UnicodeScriptMeeteiMayek UnicodeScript = 87
	// UnicodeScriptOldSouthArabian: old South Arabian. Since 2.26.
	UnicodeScriptOldSouthArabian UnicodeScript = 88
	// UnicodeScriptOldTurkic: old Turkic. Since 2.28.
	UnicodeScriptOldTurkic UnicodeScript = 89
	// UnicodeScriptSamaritan: samaritan. Since 2.26.
	UnicodeScriptSamaritan UnicodeScript = 90
	// UnicodeScriptTaiTham: tai Tham. Since 2.26.
	UnicodeScriptTaiTham UnicodeScript = 91
	// UnicodeScriptTaiViet: tai Viet. Since 2.26.
	UnicodeScriptTaiViet UnicodeScript = 92
	// UnicodeScriptBatak: batak. Since 2.28.
	UnicodeScriptBatak UnicodeScript = 93
	// UnicodeScriptBrahmi: brahmi. Since 2.28.
	UnicodeScriptBrahmi UnicodeScript = 94
	// UnicodeScriptMandaic: mandaic. Since 2.28.
	UnicodeScriptMandaic UnicodeScript = 95
	// UnicodeScriptChakma: chakma. Since: 2.32.
	UnicodeScriptChakma UnicodeScript = 96
	// UnicodeScriptMeroiticCursive: meroitic Cursive. Since: 2.32.
	UnicodeScriptMeroiticCursive UnicodeScript = 97
	// UnicodeScriptMeroiticHieroglyphs: meroitic Hieroglyphs. Since: 2.32.
	UnicodeScriptMeroiticHieroglyphs UnicodeScript = 98
	// UnicodeScriptMiao: miao. Since: 2.32.
	UnicodeScriptMiao UnicodeScript = 99
	// UnicodeScriptSharada: sharada. Since: 2.32.
	UnicodeScriptSharada UnicodeScript = 100
	// UnicodeScriptSoraSompeng: sora Sompeng. Since: 2.32.
	UnicodeScriptSoraSompeng UnicodeScript = 101
	// UnicodeScriptTakri: takri. Since: 2.32.
	UnicodeScriptTakri UnicodeScript = 102
	// UnicodeScriptBassaVah: bassa. Since: 2.42.
	UnicodeScriptBassaVah UnicodeScript = 103
	// UnicodeScriptCaucasianAlbanian: caucasian Albanian. Since: 2.42.
	UnicodeScriptCaucasianAlbanian UnicodeScript = 104
	// UnicodeScriptDuployan: duployan. Since: 2.42.
	UnicodeScriptDuployan UnicodeScript = 105
	// UnicodeScriptElbasan: elbasan. Since: 2.42.
	UnicodeScriptElbasan UnicodeScript = 106
	// UnicodeScriptGrantha: grantha. Since: 2.42.
	UnicodeScriptGrantha UnicodeScript = 107
	// UnicodeScriptKhojki: kjohki. Since: 2.42.
	UnicodeScriptKhojki UnicodeScript = 108
	// UnicodeScriptKhudawadi: khudawadi, Sindhi. Since: 2.42.
	UnicodeScriptKhudawadi UnicodeScript = 109
	// UnicodeScriptLinearA: linear A. Since: 2.42.
	UnicodeScriptLinearA UnicodeScript = 110
	// UnicodeScriptMahajani: mahajani. Since: 2.42.
	UnicodeScriptMahajani UnicodeScript = 111
	// UnicodeScriptManichaean: manichaean. Since: 2.42.
	UnicodeScriptManichaean UnicodeScript = 112
	// UnicodeScriptMendeKikakui: mende Kikakui. Since: 2.42.
	UnicodeScriptMendeKikakui UnicodeScript = 113
	// UnicodeScriptModi: modi. Since: 2.42.
	UnicodeScriptModi UnicodeScript = 114
	// UnicodeScriptMro: mro. Since: 2.42.
	UnicodeScriptMro UnicodeScript = 115
	// UnicodeScriptNabataean: nabataean. Since: 2.42.
	UnicodeScriptNabataean UnicodeScript = 116
	// UnicodeScriptOldNorthArabian: old North Arabian. Since: 2.42.
	UnicodeScriptOldNorthArabian UnicodeScript = 117
	// UnicodeScriptOldPermic: old Permic. Since: 2.42.
	UnicodeScriptOldPermic UnicodeScript = 118
	// UnicodeScriptPahawhHmong: pahawh Hmong. Since: 2.42.
	UnicodeScriptPahawhHmong UnicodeScript = 119
	// UnicodeScriptPalmyrene: palmyrene. Since: 2.42.
	UnicodeScriptPalmyrene UnicodeScript = 120
	// UnicodeScriptPauCinHau: pau Cin Hau. Since: 2.42.
	UnicodeScriptPauCinHau UnicodeScript = 121
	// UnicodeScriptPsalterPahlavi: psalter Pahlavi. Since: 2.42.
	UnicodeScriptPsalterPahlavi UnicodeScript = 122
	// UnicodeScriptSiddham: siddham. Since: 2.42.
	UnicodeScriptSiddham UnicodeScript = 123
	// UnicodeScriptTirhuta: tirhuta. Since: 2.42.
	UnicodeScriptTirhuta UnicodeScript = 124
	// UnicodeScriptWarangCiti: warang Citi. Since: 2.42.
	UnicodeScriptWarangCiti UnicodeScript = 125
	// UnicodeScriptAhom: ahom. Since: 2.48.
	UnicodeScriptAhom UnicodeScript = 126
	// UnicodeScriptAnatolianHieroglyphs: anatolian Hieroglyphs. Since: 2.48.
	UnicodeScriptAnatolianHieroglyphs UnicodeScript = 127
	// UnicodeScriptHatran: hatran. Since: 2.48.
	UnicodeScriptHatran UnicodeScript = 128
	// UnicodeScriptMultani: multani. Since: 2.48.
	UnicodeScriptMultani UnicodeScript = 129
	// UnicodeScriptOldHungarian: old Hungarian. Since: 2.48.
	UnicodeScriptOldHungarian UnicodeScript = 130
	// UnicodeScriptSignwriting: signwriting. Since: 2.48.
	UnicodeScriptSignwriting UnicodeScript = 131
	// UnicodeScriptAdlam: adlam. Since: 2.50.
	UnicodeScriptAdlam UnicodeScript = 132
	// UnicodeScriptBhaiksuki: bhaiksuki. Since: 2.50.
	UnicodeScriptBhaiksuki UnicodeScript = 133
	// UnicodeScriptMarchen: marchen. Since: 2.50.
	UnicodeScriptMarchen UnicodeScript = 134
	// UnicodeScriptNewa: newa. Since: 2.50.
	UnicodeScriptNewa UnicodeScript = 135
	// UnicodeScriptOsage: osage. Since: 2.50.
	UnicodeScriptOsage UnicodeScript = 136
	// UnicodeScriptTangut: tangut. Since: 2.50.
	UnicodeScriptTangut UnicodeScript = 137
	// UnicodeScriptMasaramGondi: masaram Gondi. Since: 2.54.
	UnicodeScriptMasaramGondi UnicodeScript = 138
	// UnicodeScriptNushu: nushu. Since: 2.54.
	UnicodeScriptNushu UnicodeScript = 139
	// UnicodeScriptSoyombo: soyombo. Since: 2.54.
	UnicodeScriptSoyombo UnicodeScript = 140
	// UnicodeScriptZanabazarSquare: zanabazar Square. Since: 2.54.
	UnicodeScriptZanabazarSquare UnicodeScript = 141
	// UnicodeScriptDogra: dogra. Since: 2.58.
	UnicodeScriptDogra UnicodeScript = 142
	// UnicodeScriptGunjalaGondi: gunjala Gondi. Since: 2.58.
	UnicodeScriptGunjalaGondi UnicodeScript = 143
	// UnicodeScriptHanifiRohingya: hanifi Rohingya. Since: 2.58.
	UnicodeScriptHanifiRohingya UnicodeScript = 144
	// UnicodeScriptMakasar: makasar. Since: 2.58.
	UnicodeScriptMakasar UnicodeScript = 145
	// UnicodeScriptMedefaidrin: medefaidrin. Since: 2.58.
	UnicodeScriptMedefaidrin UnicodeScript = 146
	// UnicodeScriptOldSogdian: old Sogdian. Since: 2.58.
	UnicodeScriptOldSogdian UnicodeScript = 147
	// UnicodeScriptSogdian: sogdian. Since: 2.58.
	UnicodeScriptSogdian UnicodeScript = 148
	// UnicodeScriptElymaic: elym. Since: 2.62.
	UnicodeScriptElymaic UnicodeScript = 149
	// UnicodeScriptNandinagari: nand. Since: 2.62.
	UnicodeScriptNandinagari UnicodeScript = 150
	// UnicodeScriptNyiakengPuachueHmong: rohg. Since: 2.62.
	UnicodeScriptNyiakengPuachueHmong UnicodeScript = 151
	// UnicodeScriptWancho: wcho. Since: 2.62.
	UnicodeScriptWancho UnicodeScript = 152
	// UnicodeScriptChorasmian: chorasmian. Since: 2.66.
	UnicodeScriptChorasmian UnicodeScript = 153
	// UnicodeScriptDivesAkuru dives Akuru. Since: 2.66.
	UnicodeScriptDivesAkuru UnicodeScript = 154
	// UnicodeScriptKhitanSmallScript: khitan small script. Since: 2.66.
	UnicodeScriptKhitanSmallScript UnicodeScript = 155
	// UnicodeScriptYezidi: yezidi. Since: 2.66.
	UnicodeScriptYezidi UnicodeScript = 156
)

func UnicharGetScript

func UnicharGetScript(ch uint32) UnicodeScript

UnicharGetScript looks up the Script 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 pango_script_for_unichar() and the two are interchangeable.

The function takes the following parameters:

  • ch: unicode character.

The function returns the following values:

  • unicodeScript for the character.

func UnicodeScriptFromISO15924

func UnicodeScriptFromISO15924(iso15924 uint32) UnicodeScript

UnicodeScriptFromISO15924 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 (http://unicode.org/iso15924/codelists.html) for details.

The function takes the following parameters:

  • iso15924: unicode script.

The function returns the following values:

  • unicodeScript: unicode script for iso15924, or of G_UNICODE_SCRIPT_INVALID_CODE if iso15924 is zero and G_UNICODE_SCRIPT_UNKNOWN if iso15924 is unknown.

func (UnicodeScript) String

func (u UnicodeScript) String() string

String returns the name in string for UnicodeScript.

type UnicodeType

type UnicodeType C.gint

UnicodeType: these are the possible character classifications from the Unicode specification. See Unicode Character Database (http://www.unicode.org/reports/tr44/Category_Values).

const (
	// UnicodeControl: general category "Other, Control" (Cc).
	UnicodeControl UnicodeType = iota
	// UnicodeFormat: general category "Other, Format" (Cf).
	UnicodeFormat
	// UnicodeUnassigned: general category "Other, Not Assigned" (Cn).
	UnicodeUnassigned
	// UnicodePrivateUse: general category "Other, Private Use" (Co).
	UnicodePrivateUse
	// UnicodeSurrogate: general category "Other, Surrogate" (Cs).
	UnicodeSurrogate
	// UnicodeLowercaseLetter: general category "Letter, Lowercase" (Ll).
	UnicodeLowercaseLetter
	// UnicodeModifierLetter: general category "Letter, Modifier" (Lm).
	UnicodeModifierLetter
	// UnicodeOtherLetter: general category "Letter, Other" (Lo).
	UnicodeOtherLetter
	// UnicodeTitlecaseLetter: general category "Letter, Titlecase" (Lt).
	UnicodeTitlecaseLetter
	// UnicodeUppercaseLetter: general category "Letter, Uppercase" (Lu).
	UnicodeUppercaseLetter
	// UnicodeSpacingMark: general category "Mark, Spacing" (Mc).
	UnicodeSpacingMark
	// UnicodeEnclosingMark: general category "Mark, Enclosing" (Me).
	UnicodeEnclosingMark
	// UnicodeNonSpacingMark: general category "Mark, Nonspacing" (Mn).
	UnicodeNonSpacingMark
	// UnicodeDecimalNumber: general category "Number, Decimal Digit" (Nd).
	UnicodeDecimalNumber
	// UnicodeLetterNumber: general category "Number, Letter" (Nl).
	UnicodeLetterNumber
	// UnicodeOtherNumber: general category "Number, Other" (No).
	UnicodeOtherNumber
	// UnicodeConnectPunctuation: general category "Punctuation, Connector"
	// (Pc).
	UnicodeConnectPunctuation
	// UnicodeDashPunctuation: general category "Punctuation, Dash" (Pd).
	UnicodeDashPunctuation
	// UnicodeClosePunctuation: general category "Punctuation, Close" (Pe).
	UnicodeClosePunctuation
	// UnicodeFinalPunctuation: general category "Punctuation, Final quote"
	// (Pf).
	UnicodeFinalPunctuation
	// UnicodeInitialPunctuation: general category "Punctuation, Initial quote"
	// (Pi).
	UnicodeInitialPunctuation
	// UnicodeOtherPunctuation: general category "Punctuation, Other" (Po).
	UnicodeOtherPunctuation
	// UnicodeOpenPunctuation: general category "Punctuation, Open" (Ps).
	UnicodeOpenPunctuation
	// UnicodeCurrencySymbol: general category "Symbol, Currency" (Sc).
	UnicodeCurrencySymbol
	// UnicodeModifierSymbol: general category "Symbol, Modifier" (Sk).
	UnicodeModifierSymbol
	// UnicodeMathSymbol: general category "Symbol, Math" (Sm).
	UnicodeMathSymbol
	// UnicodeOtherSymbol: general category "Symbol, Other" (So).
	UnicodeOtherSymbol
	// UnicodeLineSeparator: general category "Separator, Line" (Zl).
	UnicodeLineSeparator
	// UnicodeParagraphSeparator: general category "Separator, Paragraph" (Zp).
	UnicodeParagraphSeparator
	// UnicodeSpaceSeparator: general category "Separator, Space" (Zs).
	UnicodeSpaceSeparator
)

func UnicharType

func UnicharType(c uint32) UnicodeType

UnicharType classifies a Unicode character by type.

The function takes the following parameters:

  • c: unicode character.

The function returns the following values:

  • unicodeType: type of the character.

func (UnicodeType) String

func (u UnicodeType) String() string

String returns the name in string for UnicodeType.

type UserDirectory

type UserDirectory C.gint

UserDirectory: these are logical ids for special directories which are defined depending on the platform used. You should use g_get_user_special_dir() to retrieve the full path associated to the logical id.

The Directory enumeration can be extended at later date. Not every platform has a directory for every logical id in this enumeration.

const (
	// UserDirectoryDesktop user's Desktop directory.
	UserDirectoryDesktop UserDirectory = iota
	// UserDirectoryDocuments user's Documents directory.
	UserDirectoryDocuments
	// UserDirectoryDownload user's Downloads directory.
	UserDirectoryDownload
	// UserDirectoryMusic user's Music directory.
	UserDirectoryMusic
	// UserDirectoryPictures user's Pictures directory.
	UserDirectoryPictures
	// UserDirectoryPublicShare user's shared directory.
	UserDirectoryPublicShare
	// UserDirectoryTemplates user's Templates directory.
	UserDirectoryTemplates
	// UserDirectoryVideos user's Movies directory.
	UserDirectoryVideos
	// UserNDirectories: number of enum values.
	UserNDirectories
)

func (UserDirectory) String

func (u UserDirectory) String() string

String returns the name in string for UserDirectory.

type Value

type Value = coreglib.Value

Value is an alias for pkg/core/glib.Value.

func NewValue

func NewValue(v interface{}) *Value

NewValue is an alias for pkg/core/glib.NewValue.

type Variant

type Variant struct {
	// contains filtered or unexported fields
}

Variant is a variant datatype; it can contain one or more values along with information about the type of the values.

A #GVariant may contain simple types, like an integer, or a boolean value; or complex types, like an array of two strings, or a dictionary of key value pairs. A #GVariant is also immutable: once it's been created neither its type nor its content can be modified further.

GVariant is useful whenever data needs to be serialized, for example when sending method parameters in D-Bus, or when saving settings using GSettings.

When creating a new #GVariant, you pass the data you want to store in it along with a string representing the type of data you wish to pass to it.

For instance, if you want to create a #GVariant holding an integer value you can use:

GVariant *v = g_variant_new ("u", 40);

The string "u" in the first argument tells #GVariant that the data passed to the constructor (40) is going to be an unsigned integer.

More advanced examples of #GVariant in use can be found in documentation for [GVariant format strings][gvariant-format-strings-pointers].

The range of possible values is determined by the type.

The type system used by #GVariant is Type.

#GVariant instances always have a type and a value (which are given at construction time). The type and value of a #GVariant instance can never change other than by the #GVariant itself being destroyed. A #GVariant cannot contain a pointer.

#GVariant is reference counted using g_variant_ref() and g_variant_unref(). #GVariant also has floating reference counts -- see g_variant_ref_sink().

#GVariant is completely threadsafe. A #GVariant instance can be concurrently accessed in any way from any number of threads without problems.

#GVariant is heavily optimised for dealing with data in serialised form. It works particularly well with data located in memory-mapped files. It can perform nearly all deserialisation operations in a small constant time, usually touching only a single memory page. Serialised #GVariant data can also be sent over the network.

#GVariant is largely compatible with D-Bus. Almost all types of #GVariant instances can be sent over D-Bus. See Type for exceptions. (However, #GVariant's serialisation format is not the same as the serialisation format of a D-Bus message body: use BusMessage, in the gio library, for those.)

For space-efficiency, the #GVariant serialisation format does not automatically include the variant's length, type or endianness, which must either be implied from context (such as knowledge that a particular file format always contains a little-endian G_VARIANT_TYPE_VARIANT which occupies the whole length of the file) or supplied out-of-band (for instance, a length, type and/or endianness indicator could be placed at the beginning of a file, network message or network stream).

A #GVariant's size is limited mainly by any lower level operating system constraints, such as the number of bits in #gsize. For example, it is reasonable to have a 2GB file mapped into memory with File, and call g_variant_new_from_data() on it.

For convenience to C programmers, #GVariant features powerful varargs-based value construction and destruction. This feature is designed to be embedded in other libraries.

There is a Python-inspired text language for describing #GVariant values. #GVariant includes a printer for this language and a parser with type inferencing.

Memory Use

#GVariant tries to be quite efficient with respect to memory use. This section gives a rough idea of how much memory is used by the current implementation. The information here is subject to change in the future.

The memory allocated by #GVariant can be grouped into 4 broad purposes: memory for serialised data, memory for the type information cache, buffer management memory and memory for the #GVariant structure itself.

Serialised Data Memory

This is the memory that is used for storing GVariant data in serialised form. This is what would be sent over the network or what would end up on disk, not counting any indicator of the endianness, or of the length or type of the top-level variant.

The amount of memory required to store a boolean is 1 byte. 16, 32 and 64 bit integers and double precision floating point numbers use their "natural" size. Strings (including object path and signature strings) are stored with a nul terminator, and as such use the length of the string plus 1 byte.

Maybe types use no space at all to represent the null value and use the same amount of space (sometimes plus one byte) as the equivalent non-maybe-typed value to represent the non-null case.

Arrays use the amount of space required to store each of their members, concatenated. Additionally, if the items stored in an array are not of a fixed-size (ie: strings, other arrays, etc) then an additional framing offset is stored for each item. The size of this offset is either 1, 2 or 4 bytes depending on the overall size of the container. Additionally, extra padding bytes are added as required for alignment of child values.

Tuples (including dictionary entries) use the amount of space required to store each of their members, concatenated, plus one framing offset (as per arrays) for each non-fixed-sized item in the tuple, except for the last one. Additionally, extra padding bytes are added as required for alignment of child values.

Variants use the same amount of space as the item inside of the variant, plus 1 byte, plus the length of the type string for the item inside the variant.

As an example, consider a dictionary mapping strings to variants. In the case that the dictionary is empty, 0 bytes are required for the serialisation.

If we add an item "width" that maps to the int32 value of 500 then we will use 4 byte to store the int32 (so 6 for the variant containing it) and 6 bytes for the string. The variant must be aligned to 8 after the 6 bytes of the string, so that's 2 extra bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used for the dictionary entry. An additional 1 byte is added to the array as a framing offset making a total of 15 bytes.

If we add another entry, "title" that maps to a nullable string that happens to have a value of null, then we use 0 bytes for the null value (and 3 bytes for the variant to contain it along with its type string) plus 6 bytes for the string. Again, we need 2 padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.

We now require extra padding between the two items in the array. After the 14 bytes of the first item, that's 2 bytes required. We now require 2 framing offsets for an extra two bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item dictionary.

Type Information Cache

For each GVariant type that currently exists in the program a type information structure is kept in the type information cache. The type information structure is required for rapid deserialisation.

Continuing with the above example, if a #GVariant exists with the type "a{sv}" then a type information struct will exist for "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type will share the same type information. Additionally, all single-digit types are stored in read-only static memory and do not contribute to the writable memory footprint of a program using #GVariant.

Aside from the type information structures stored in read-only memory, there are two forms of type information. One is used for container types where there is a single element type: arrays and maybe types. The other is used for container types where there are multiple element types: tuples and dictionary entries.

Array type info structures are 6 * sizeof (void *), plus the memory required to store the type string itself. This means that on 32-bit systems, the cache entry for "a{sv}" would require 30 bytes of memory (plus malloc overhead).

Tuple type info structures are 6 * sizeof (void *), plus 4 * sizeof (void *) for each item in the tuple, plus the memory required to store the type string itself. A 2-item tuple, for example, would have a type information structure that consumed writable memory in the size of 14 * sizeof (void *) (plus type string) This means that on 32-bit systems, the cache entry for "{sv}" would require 61 bytes of memory (plus malloc overhead).

This means that in total, for our "a{sv}" example, 91 bytes of type information would be allocated.

The type information cache, additionally, uses a Table to store and look up the cached items and stores a pointer to this hash table in static storage. The hash table is freed when there are zero items in the type cache.

Although these sizes may seem large it is important to remember that a program will probably only have a very small number of different types of values in it and that only one type information structure is required for many different values of the same type.

Buffer Management Memory

#GVariant uses an internal buffer management structure to deal with the various different possible sources of serialised data that it uses. The buffer is responsible for ensuring that the correct call is made when the data is no longer in use by #GVariant. This may involve a g_free() or a g_slice_free() or even g_mapped_file_unref().

One buffer management structure is used for each chunk of serialised data. The size of the buffer management structure is 4 * (void *). On 32-bit systems, that's 16 bytes.

GVariant structure

The size of a #GVariant structure is 6 * (void *). On 32-bit systems, that's 24 bytes.

#GVariant structures only exist if they are explicitly created with API calls. For example, if a #GVariant is constructed out of serialised data for the example given above (with the dictionary) then although there are 9 individual values that comprise the entire dictionary (two keys, two values, two variants containing the values, two dictionary entries, plus the dictionary itself), only 1 #GVariant instance exists -- the one referring to the dictionary.

If calls are made to start accessing the other values then #GVariant instances will exist for those values only for as long as they are in use (ie: until you call g_variant_unref()). The type information is shared. The serialised data and the buffer management structure for that serialised data is shared by the child.

Summary

To put the entire example together, for our dictionary mapping strings to variants (with two entries, as given above), we are using 91 bytes of memory for type information, 29 bytes of memory for the serialised data, 16 bytes for buffer management and 24 bytes for the #GVariant instance, or a total of 160 bytes, plus malloc overhead. If we were to use g_variant_get_child_value() to access the two dictionary entries, we would use an additional 48 bytes. If we were to have other dictionaries of the same type, we would use more memory for the serialised data and buffer management for those dictionaries, but the type information would be shared.

An instance of this type is always passed by reference.

func NewVariantArray

func NewVariantArray(childType *VariantType, children []*Variant) *Variant

NewVariantArray constructs a struct Variant.

func NewVariantBoolean

func NewVariantBoolean(value bool) *Variant

NewVariantBoolean constructs a struct Variant.

func NewVariantByte

func NewVariantByte(value byte) *Variant

NewVariantByte constructs a struct Variant.

func NewVariantBytestring

func NewVariantBytestring(str []byte) *Variant

NewVariantBytestring constructs a struct Variant.

func NewVariantBytestringArray

func NewVariantBytestringArray(strv []string) *Variant

NewVariantBytestringArray constructs a struct Variant.

func NewVariantDictEntry

func NewVariantDictEntry(key *Variant, value *Variant) *Variant

NewVariantDictEntry constructs a struct Variant.

func NewVariantDouble

func NewVariantDouble(value float64) *Variant

NewVariantDouble constructs a struct Variant.

func NewVariantFixedArray

func NewVariantFixedArray(elementType *VariantType, elements unsafe.Pointer, nElements uint, elementSize uint) *Variant

NewVariantFixedArray constructs a struct Variant.

func NewVariantFromBytes

func NewVariantFromBytes(typ *VariantType, bytes *Bytes, trusted bool) *Variant

NewVariantFromBytes constructs a struct Variant.

func NewVariantHandle

func NewVariantHandle(value int32) *Variant

NewVariantHandle constructs a struct Variant.

func NewVariantInt16

func NewVariantInt16(value int16) *Variant

NewVariantInt16 constructs a struct Variant.

func NewVariantInt32

func NewVariantInt32(value int32) *Variant

NewVariantInt32 constructs a struct Variant.

func NewVariantInt64

func NewVariantInt64(value int64) *Variant

NewVariantInt64 constructs a struct Variant.

func NewVariantMaybe

func NewVariantMaybe(childType *VariantType, child *Variant) *Variant

NewVariantMaybe constructs a struct Variant.

func NewVariantObjectPath

func NewVariantObjectPath(objectPath string) *Variant

NewVariantObjectPath constructs a struct Variant.

func NewVariantObjv

func NewVariantObjv(strv []string) *Variant

NewVariantObjv constructs a struct Variant.

func NewVariantSignature

func NewVariantSignature(signature string) *Variant

NewVariantSignature constructs a struct Variant.

func NewVariantString

func NewVariantString(str string) *Variant

NewVariantString constructs a struct Variant.

func NewVariantStrv

func NewVariantStrv(strv []string) *Variant

NewVariantStrv constructs a struct Variant.

func NewVariantTuple

func NewVariantTuple(children []*Variant) *Variant

NewVariantTuple constructs a struct Variant.

func NewVariantUint16

func NewVariantUint16(value uint16) *Variant

NewVariantUint16 constructs a struct Variant.

func NewVariantUint32

func NewVariantUint32(value uint32) *Variant

NewVariantUint32 constructs a struct Variant.

func NewVariantUint64

func NewVariantUint64(value uint64) *Variant

NewVariantUint64 constructs a struct Variant.

func NewVariantVariant

func NewVariantVariant(value *Variant) *Variant

NewVariantVariant constructs a struct Variant.

func (*Variant) Boolean

func (value *Variant) Boolean() bool

Boolean returns the boolean value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_BOOLEAN.

The function returns the following values:

  • ok: TRUE or FALSE.

func (*Variant) Byte

func (value *Variant) Byte() byte

Byte returns the byte value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_BYTE.

The function returns the following values:

  • guint8: #guint8.

func (*Variant) Bytestring

func (value *Variant) Bytestring() []byte

Bytestring returns the string value of a #GVariant instance with an array-of-bytes type. The string has no particular encoding.

If the array does not end with a nul terminator character, the empty string is returned. For this reason, you can always trust that a non-NULL nul-terminated string will be returned by this function.

If the array contains a nul terminator character somewhere other than the last byte then the returned string is the string, up to the first such nul character.

g_variant_get_fixed_array() should be used instead if the array contains arbitrary data that could not be nul-terminated or could contain nul bytes.

It is an error to call this function with a value that is not an array of bytes.

The return value remains valid as long as value exists.

The function returns the following values:

  • guint8s: the constant string.

func (*Variant) BytestringArray

func (value *Variant) BytestringArray() []string

BytestringArray gets the contents of an array of array of bytes #GVariant. This call makes a shallow copy; the return result should be released with g_free(), but the individual strings must not be modified.

If length is non-NULL then the number of elements in the result is stored there. In any case, the resulting array will be NULL-terminated.

For an empty array, length will be set to 0 and a pointer to a NULL pointer will be returned.

The function returns the following values:

  • utf8s: array of constant strings.

func (*Variant) Byteswap

func (value *Variant) Byteswap() *Variant

Byteswap performs a byteswapping operation on the contents of value. The result is that all multi-byte numeric data contained in value is byteswapped. That includes 16, 32, and 64bit signed and unsigned integers as well as file handles and double precision floating point values.

This function is an identity mapping on any value that does not contain multi-byte numeric data. That include strings, booleans, bytes and containers containing only these things (recursively).

The returned value is always in normal form and is marked as trusted.

The function returns the following values:

  • variant (optional): byteswapped form of value.

func (*Variant) CheckFormatString

func (value *Variant) CheckFormatString(formatString string, copyOnly bool) bool

CheckFormatString checks if calling g_variant_get() with format_string on value would be valid from a type-compatibility standpoint. format_string is assumed to be a valid format string (from a syntactic standpoint).

If copy_only is TRUE then this function additionally checks that it would be safe to call g_variant_unref() on value immediately after the call to g_variant_get() without invalidating the result. This is only possible if deep copies are made (ie: there are no pointers to the data inside of the soon-to-be-freed #GVariant instance). If this check fails then a g_critical() is printed and FALSE is returned.

This function is meant to be used by functions that wish to provide varargs accessors to #GVariant values of uncertain values (eg: g_variant_lookup() or g_menu_model_get_item_attribute()).

The function takes the following parameters:

  • formatString: valid #GVariant format string.
  • copyOnly: TRUE to ensure the format string makes deep copies.

The function returns the following values:

  • ok: TRUE if format_string is safe to use.

func (*Variant) ChildValue

func (value *Variant) ChildValue(index_ uint) *Variant

ChildValue reads a child item out of a container #GVariant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type of #GVariant.

It is an error if index_ is greater than the number of child items in the container. See g_variant_n_children().

The returned value is never floating. You should free it with g_variant_unref() when you're done with it.

Note that values borrowed from the returned child are not guaranteed to still be valid after the child is freed even if you still hold a reference to value, if value has not been serialised at the time this function is called. To avoid this, you can serialize value by calling g_variant_get_data() and optionally ignoring the return value.

There may be implementation specific restrictions on deeply nested values, which would result in the unit tuple being returned as the child value, instead of further nested children. #GVariant is guaranteed to handle nesting up to at least 64 levels.

This function is O(1).

The function takes the following parameters:

  • index_: index of the child to fetch.

The function returns the following values:

  • variant (optional): child at the specified index.

func (*Variant) Classify

func (value *Variant) Classify() VariantClass

Classify classifies value according to its top-level type.

The function returns the following values:

  • variantClass of value.

func (*Variant) Compare

func (one *Variant) Compare(two *Variant) int

Compare compares one and two.

The types of one and two are #gconstpointer only to allow use of this function with #GTree, Array, etc. They must each be a #GVariant.

Comparison is only defined for basic types (ie: booleans, numbers, strings). For booleans, FALSE is less than TRUE. Numbers are ordered in the usual way. Strings are in ASCII lexographical order.

It is a programmer error to attempt to compare container values or two values that have types that are not exactly equal. For example, you cannot compare a 32-bit signed integer with a 32-bit unsigned integer. Also note that this function is not particularly well-behaved when it comes to comparison of doubles; in particular, the handling of incomparable values (ie: NaN) is undefined.

If you only require an equality comparison, g_variant_equal() is more general.

The function takes the following parameters:

  • two instance of the same type.

The function returns the following values:

  • gint: negative value if a < b; zero if a = b; positive value if a > b.

func (*Variant) Data

func (value *Variant) Data() unsafe.Pointer

Data returns a pointer to the serialised form of a #GVariant instance. The returned data may not be in fully-normalised form if read from an untrusted source. The returned data must not be freed; it remains valid for as long as value exists.

If value is a fixed-sized value that was deserialised from a corrupted serialised container then NULL may be returned. In this case, the proper thing to do is typically to use the appropriate number of nul bytes in place of value. If value is not fixed-sized then NULL is never returned.

In the case that value is already in serialised form, this function is O(1). If the value is not already in serialised form, serialisation occurs implicitly and is approximately O(n) in the size of the result.

To deserialise the data returned by this function, in addition to the serialised data, you must know the type of the #GVariant, and (if the machine might be different) the endianness of the machine that stored it. As a result, file formats or network messages that incorporate serialised #GVariants must include this information either implicitly (for instance "the file always contains a G_VARIANT_TYPE_VARIANT and it is always in little-endian order") or explicitly (by storing the type and/or endianness in addition to the serialised data).

The function returns the following values:

  • gpointer (optional): serialised form of value, or NULL.

func (*Variant) DataAsBytes

func (value *Variant) DataAsBytes() *Bytes

DataAsBytes returns a pointer to the serialised form of a #GVariant instance. The semantics of this function are exactly the same as g_variant_get_data(), except that the returned #GBytes holds a reference to the variant data.

The function returns the following values:

  • bytes: new #GBytes representing the variant data.

func (*Variant) Double

func (value *Variant) Double() float64

Double returns the double precision floating point value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_DOUBLE.

The function returns the following values:

  • gdouble: #gdouble.

func (*Variant) DupBytestring

func (value *Variant) DupBytestring() []byte

DupBytestring: similar to g_variant_get_bytestring() except that instead of returning a constant string, the string is duplicated.

The return value must be freed using g_free().

The function returns the following values:

  • guint8s: a newly allocated string.

func (*Variant) DupBytestringArray

func (value *Variant) DupBytestringArray() []string

DupBytestringArray gets the contents of an array of array of bytes #GVariant. This call makes a deep copy; the return result should be released with g_strfreev().

If length is non-NULL then the number of elements in the result is stored there. In any case, the resulting array will be NULL-terminated.

For an empty array, length will be set to 0 and a pointer to a NULL pointer will be returned.

The function returns the following values:

  • utf8s: array of strings.

func (*Variant) DupObjv

func (value *Variant) DupObjv() []string

DupObjv gets the contents of an array of object paths #GVariant. This call makes a deep copy; the return result should be released with g_strfreev().

If length is non-NULL then the number of elements in the result is stored there. In any case, the resulting array will be NULL-terminated.

For an empty array, length will be set to 0 and a pointer to a NULL pointer will be returned.

The function returns the following values:

  • utf8s: array of strings.

func (*Variant) DupString

func (value *Variant) DupString() (uint, string)

DupString: similar to g_variant_get_string() except that instead of returning a constant string, the string is duplicated.

The string will always be UTF-8 encoded.

The return value must be freed using g_free().

The function returns the following values:

  • length: pointer to a #gsize, to store the length.
  • utf8: newly allocated string, UTF-8 encoded.

func (*Variant) DupStrv

func (value *Variant) DupStrv() []string

DupStrv gets the contents of an array of strings #GVariant. This call makes a deep copy; the return result should be released with g_strfreev().

If length is non-NULL then the number of elements in the result is stored there. In any case, the resulting array will be NULL-terminated.

For an empty array, length will be set to 0 and a pointer to a NULL pointer will be returned.

The function returns the following values:

  • utf8s: array of strings.

func (*Variant) Equal

func (one *Variant) Equal(two *Variant) bool

Equal checks if one and two have the same type and value.

The types of one and two are #gconstpointer only to allow use of this function with Table. They must each be a #GVariant.

The function takes the following parameters:

  • two: #GVariant instance.

The function returns the following values:

  • ok: TRUE if one and two are equal.

func (*Variant) ForEach

func (value *Variant) ForEach(f func(*Variant) (stop bool))

ForEach iterates over items in value. The iteration breaks out once f returns true. This method wraps around g_variant_iter_new.

func (*Variant) Handle

func (value *Variant) Handle() int32

Handle returns the 32-bit signed integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_HANDLE.

By convention, handles are indexes into an array of file descriptors that are sent alongside a D-Bus message. If you're not interacting with D-Bus, you probably don't need them.

The function returns the following values:

  • gint32: #gint32.

func (*Variant) Hash

func (value *Variant) Hash() uint

Hash generates a hash value for a #GVariant instance.

The output of this function is guaranteed to be the same for a given value only per-process. It may change between different processor architectures or even different versions of GLib. Do not use this function as a basis for building protocols or file formats.

The type of value is #gconstpointer only to allow use of this function with Table. value must be a #GVariant.

The function returns the following values:

  • guint: hash value corresponding to value.

func (*Variant) Int16

func (value *Variant) Int16() int16

Int16 returns the 16-bit signed integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_INT16.

The function returns the following values:

  • gint16: #gint16.

func (*Variant) Int32

func (value *Variant) Int32() int32

Int32 returns the 32-bit signed integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_INT32.

The function returns the following values:

  • gint32: #gint32.

func (*Variant) Int64

func (value *Variant) Int64() int64

Int64 returns the 64-bit signed integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_INT64.

The function returns the following values:

  • gint64: #gint64.

func (*Variant) IsContainer

func (value *Variant) IsContainer() bool

IsContainer checks if value is a container.

The function returns the following values:

  • ok: TRUE if value is a container.

func (*Variant) IsFloating

func (value *Variant) IsFloating() bool

IsFloating checks whether value has a floating reference count.

This function should only ever be used to assert that a given variant is or is not floating, or for debug purposes. To acquire a reference to a variant that might be floating, always use g_variant_ref_sink() or g_variant_take_ref().

See g_variant_ref_sink() for more information about floating reference counts.

The function returns the following values:

  • ok: whether value is floating.

func (*Variant) IsNormalForm

func (value *Variant) IsNormalForm() bool

IsNormalForm checks if value is in normal form.

The main reason to do this is to detect if a given chunk of serialised data is in normal form: load the data into a #GVariant using g_variant_new_from_data() and then use this function to check.

If value is found to be in normal form then it will be marked as being trusted. If the value was already marked as being trusted then this function will immediately return TRUE.

There may be implementation specific restrictions on deeply nested values. GVariant is guaranteed to handle nesting up to at least 64 levels.

The function returns the following values:

  • ok: TRUE if value is in normal form.

func (*Variant) IsOfType

func (value *Variant) IsOfType(typ *VariantType) bool

IsOfType checks if a value has a type matching the provided type.

The function takes the following parameters:

  • typ: Type.

The function returns the following values:

  • ok: TRUE if the type of value matches type.

func (*Variant) LookupValue

func (dictionary *Variant) LookupValue(key string, expectedType *VariantType) *Variant

LookupValue looks up a value in a dictionary #GVariant.

This function works with dictionaries of the type a{s*} (and equally well with type a{o*}, but we only further discuss the string case for sake of clarity).

In the event that dictionary has the type a{sv}, the expected_type string specifies what type of value is expected to be inside of the variant. If the value inside the variant has a different type then NULL is returned. In the event that dictionary has a value type other than v then expected_type must directly match the value type and it is used to unpack the value directly or an error occurs.

In either case, if key is not found in dictionary, NULL is returned.

If the key is found and the value has the correct type, it is returned. If expected_type was specified then any non-NULL return value will have this type.

This function is currently implemented with a linear scan. If you plan to do many lookups then Dict may be more efficient.

The function takes the following parameters:

  • key to look up in the dictionary.
  • expectedType (optional) or NULL.

The function returns the following values:

  • variant (optional): value of the dictionary key, or NULL.

func (*Variant) Maybe

func (value *Variant) Maybe() *Variant

Maybe: given a maybe-typed #GVariant instance, extract its value. If the value is Nothing, then this function returns NULL.

The function returns the following values:

  • variant (optional) contents of value, or NULL.

func (*Variant) NChildren

func (value *Variant) NChildren() uint

NChildren determines the number of children in a container #GVariant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type of #GVariant.

For variants, the return value is always 1. For values with maybe types, it is always zero or one. For arrays, it is the length of the array. For tuples it is the number of tuple items (which depends only on the type). For dictionary entries, it is always 2

This function is O(1).

The function returns the following values:

  • gsize: number of children in the container.

func (*Variant) NormalForm

func (value *Variant) NormalForm() *Variant

NormalForm gets a #GVariant instance that has the same value as value and is trusted to be in normal form.

If value is already trusted to be in normal form then a new reference to value is returned.

If value is not already trusted, then it is scanned to check if it is in normal form. If it is found to be in normal form then it is marked as trusted and a new reference to it is returned.

If value is found not to be in normal form then a new trusted #GVariant is created with the same value as value.

It makes sense to call this function if you've received #GVariant data from untrusted sources and you want to ensure your serialised output is definitely in normal form.

If value is already in normal form, a new reference will be returned (which will be floating if value is floating). If it is not in normal form, the newly created #GVariant will be returned with a single non-floating reference. Typically, g_variant_take_ref() should be called on the return value from this function to guarantee ownership of a single non-floating reference to it.

The function returns the following values:

  • variant (optional): trusted #GVariant.

func (*Variant) Objv

func (value *Variant) Objv() []string

Objv gets the contents of an array of object paths #GVariant. This call makes a shallow copy; the return result should be released with g_free(), but the individual strings must not be modified.

If length is non-NULL then the number of elements in the result is stored there. In any case, the resulting array will be NULL-terminated.

For an empty array, length will be set to 0 and a pointer to a NULL pointer will be returned.

The function returns the following values:

  • utf8s: array of constant strings.

func (*Variant) Print

func (value *Variant) Print(typeAnnotate bool) string

Print pretty-prints value in the format understood by g_variant_parse().

The format is described [here][gvariant-text].

If type_annotate is TRUE, then type information is included in the output.

The function takes the following parameters:

  • typeAnnotate: TRUE if type information should be included in the output.

The function returns the following values:

  • utf8: newly-allocated string holding the result.

func (*Variant) RefSink

func (value *Variant) RefSink() *Variant

RefSink uses a floating reference count system. All functions with names starting with g_variant_new_ return floating references.

Calling g_variant_ref_sink() on a #GVariant with a floating reference will convert the floating reference into a full reference. Calling g_variant_ref_sink() on a non-floating #GVariant results in an additional normal reference being added.

In other words, if the value is floating, then this call "assumes ownership" of the floating reference, converting it to a normal reference. If the value is not floating, then this call adds a new normal reference increasing the reference count by one.

All calls that result in a #GVariant instance being inserted into a container will call g_variant_ref_sink() on the instance. This means that if the value was just created (and has only its floating reference) then the container will assume sole ownership of the value at that point and the caller will not need to unreference it. This makes certain common styles of programming much easier while still maintaining normal refcounting semantics in situations where values are not floating.

The function returns the following values:

  • variant (optional): same value.

func (*Variant) Size

func (value *Variant) Size() uint

Size determines the number of bytes that would be required to store value with g_variant_store().

If value has a fixed-sized type then this function always returned that fixed size.

In the case that value is already in serialised form or the size has already been calculated (ie: this function has been called before) then this function is O(1). Otherwise, the size is calculated, an operation which is approximately O(n) in the number of values involved.

The function returns the following values:

  • gsize: serialised size of value.

func (*Variant) Store

func (value *Variant) Store(data unsafe.Pointer)

Store stores the serialised form of value at data. data should be large enough. See g_variant_get_size().

The stored data is in machine native byte order but may not be in fully-normalised form if read from an untrusted source. See g_variant_get_normal_form() for a solution.

As with g_variant_get_data(), to be able to deserialise the serialised variant successfully, its type and (if the destination machine might be different) its endianness must also be available.

This function is approximately O(n) in the size of data.

The function takes the following parameters:

  • data: location to store the serialised data at.

func (*Variant) String

func (value *Variant) String() string

String returns the string value of a #GVariant instance with a string type. This includes the types G_VARIANT_TYPE_STRING, G_VARIANT_TYPE_OBJECT_PATH and G_VARIANT_TYPE_SIGNATURE.

The string will always be UTF-8 encoded, will never be NULL, and will never contain nul bytes.

If length is non-NULL then the length of the string (in bytes) is returned there. For trusted values, this information is already known. Untrusted values will be validated and, if valid, a strlen() will be performed. If invalid, a default value will be returned — for G_VARIANT_TYPE_OBJECT_PATH, this is "/", and for other types it is the empty string.

It is an error to call this function with a value of any type other than those three.

The return value remains valid as long as value exists.

The function returns the following values:

  • utf8: constant string, UTF-8 encoded.

func (*Variant) Strv

func (value *Variant) Strv() []string

Strv gets the contents of an array of strings #GVariant. This call makes a shallow copy; the return result should be released with g_free(), but the individual strings must not be modified.

If length is non-NULL then the number of elements in the result is stored there. In any case, the resulting array will be NULL-terminated.

For an empty array, length will be set to 0 and a pointer to a NULL pointer will be returned.

The function returns the following values:

  • utf8s: array of constant strings.

func (*Variant) Type

func (value *Variant) Type() *VariantType

Type determines the type of value.

The return value is valid for the lifetime of value and must not be freed.

The function returns the following values:

  • variantType: Type.

func (*Variant) TypeString

func (value *Variant) TypeString() string

TypeString returns the type string of value. Unlike the result of calling g_variant_type_peek_string(), this string is nul-terminated. This string belongs to #GVariant and must not be freed.

The function returns the following values:

  • utf8: type string for the type of value.

func (*Variant) Uint16

func (value *Variant) Uint16() uint16

Uint16 returns the 16-bit unsigned integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_UINT16.

The function returns the following values:

  • guint16: #guint16.

func (*Variant) Uint32

func (value *Variant) Uint32() uint32

Uint32 returns the 32-bit unsigned integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_UINT32.

The function returns the following values:

  • guint32: #guint32.

func (*Variant) Uint64

func (value *Variant) Uint64() uint64

Uint64 returns the 64-bit unsigned integer value of value.

It is an error to call this function with a value of any type other than G_VARIANT_TYPE_UINT64.

The function returns the following values:

  • guint64: #guint64.

func (*Variant) Variant

func (value *Variant) Variant() *Variant

Variant unboxes value. The result is the #GVariant instance that was contained in value.

The function returns the following values:

  • variant (optional): item contained in the variant.

type VariantBuilder

type VariantBuilder struct {
	// contains filtered or unexported fields
}

VariantBuilder: utility type for constructing container-type #GVariant instances.

This is an opaque structure and may only be accessed using the following functions.

Builder is not threadsafe in any way. Do not attempt to access it from more than one thread.

An instance of this type is always passed by reference.

func NewVariantBuilder

func NewVariantBuilder(typ *VariantType) *VariantBuilder

NewVariantBuilder constructs a struct VariantBuilder.

func (*VariantBuilder) AddValue

func (builder *VariantBuilder) AddValue(value *Variant)

AddValue adds value to builder.

It is an error to call this function in any way that would create an inconsistent value to be constructed. Some examples of this are putting different types of items into an array, putting the wrong types or number of items in a tuple, putting more than one value into a variant, etc.

If value is a floating reference (see g_variant_ref_sink()), the builder instance takes ownership of value.

The function takes the following parameters:

  • value: #GVariant.

func (*VariantBuilder) Close

func (builder *VariantBuilder) Close()

Close closes the subcontainer inside the given builder that was opened by the most recent call to g_variant_builder_open().

It is an error to call this function in any way that would create an inconsistent value to be constructed (ie: too few values added to the subcontainer).

func (*VariantBuilder) End

func (builder *VariantBuilder) End() *Variant

End ends the builder process and returns the constructed value.

It is not permissible to use builder in any way after this call except for reference counting operations (in the case of a heap-allocated Builder) or by reinitialising it with g_variant_builder_init() (in the case of stack-allocated). This means that for the stack-allocated builders there is no need to call g_variant_builder_clear() after the call to g_variant_builder_end().

It is an error to call this function in any way that would create an inconsistent value to be constructed (ie: insufficient number of items added to a container with a specific number of children required). It is also an error to call this function if the builder was created with an indefinite array or maybe type and no children have been added; in this case it is impossible to infer the type of the empty array.

The function returns the following values:

  • variant: new, floating, #GVariant.

func (*VariantBuilder) Open

func (builder *VariantBuilder) Open(typ *VariantType)

Open opens a subcontainer inside the given builder. When done adding items to the subcontainer, g_variant_builder_close() must be called. type is the type of the container: so to build a tuple of several values, type must include the tuple itself.

It is an error to call this function in any way that would cause an inconsistent value to be constructed (ie: adding too many values or a value of an incorrect type).

Example of building a nested variant:

GVariantBuilder builder;
guint32 some_number = get_number ();
g_autoptr (GHashTable) some_dict = get_dict ();
GHashTableIter iter;
const gchar *key;
const GVariant *value;
g_autoptr (GVariant) output = NULL;

g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
g_variant_builder_add (&builder, "u", some_number);
g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));

g_hash_table_iter_init (&iter, some_dict);
while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
  {
    g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
    g_variant_builder_add (&builder, "s", key);
    g_variant_builder_add (&builder, "v", value);
    g_variant_builder_close (&builder);
  }

g_variant_builder_close (&builder);

output = g_variant_builder_end (&builder);.

The function takes the following parameters:

  • typ of the container.

type VariantClass

type VariantClass C.gint

VariantClass: range of possible top-level types of #GVariant instances.

const (
	// VariantClassBoolean is a boolean.
	VariantClassBoolean VariantClass = 98
	// VariantClassByte is a byte.
	VariantClassByte VariantClass = 121
	// VariantClassInt16 is a signed 16 bit integer.
	VariantClassInt16 VariantClass = 110
	// VariantClassUint16 is an unsigned 16 bit integer.
	VariantClassUint16 VariantClass = 113
	// VariantClassInt32 is a signed 32 bit integer.
	VariantClassInt32 VariantClass = 105
	// VariantClassUint32 is an unsigned 32 bit integer.
	VariantClassUint32 VariantClass = 117
	// VariantClassInt64 is a signed 64 bit integer.
	VariantClassInt64 VariantClass = 120
	// VariantClassUint64 is an unsigned 64 bit integer.
	VariantClassUint64 VariantClass = 116
	// VariantClassHandle is a file handle index.
	VariantClassHandle VariantClass = 104
	// VariantClassDouble is a double precision floating point value.
	VariantClassDouble VariantClass = 100
	// VariantClassString is a normal string.
	VariantClassString VariantClass = 115
	// VariantClassObjectPath is a D-Bus object path string.
	VariantClassObjectPath VariantClass = 111
	// VariantClassSignature is a D-Bus signature string.
	VariantClassSignature VariantClass = 103
	// VariantClassVariant is a variant.
	VariantClassVariant VariantClass = 118
	// VariantClassMaybe is a maybe-typed value.
	VariantClassMaybe VariantClass = 109
	// VariantClassArray is an array.
	VariantClassArray VariantClass = 97
	// VariantClassTuple is a tuple.
	VariantClassTuple VariantClass = 40
	// VariantClassDictEntry is a dictionary entry.
	VariantClassDictEntry VariantClass = 123
)

func (VariantClass) String

func (v VariantClass) String() string

String returns the name in string for VariantClass.

type VariantDict

type VariantDict struct {
	// contains filtered or unexported fields
}

VariantDict is a mutable interface to #GVariant dictionaries.

It can be used for doing a sequence of dictionary lookups in an efficient way on an existing #GVariant dictionary or it can be used to construct new dictionaries with a hashtable-like interface. It can also be used for taking existing dictionaries and modifying them in order to create new ones.

Dict can only be used with G_VARIANT_TYPE_VARDICT dictionaries.

It is possible to use Dict allocated on the stack or on the heap. When using a stack-allocated Dict, you begin with a call to g_variant_dict_init() and free the resources with a call to g_variant_dict_clear().

Heap-allocated Dict follows normal refcounting rules: you allocate it with g_variant_dict_new() and use g_variant_dict_ref() and g_variant_dict_unref().

g_variant_dict_end() is used to convert the Dict back into a dictionary-type #GVariant. When used with stack-allocated instances, this also implicitly frees all associated memory, but for heap-allocated instances, you must still call g_variant_dict_unref() afterwards.

You will typically want to use a heap-allocated Dict when you expose it as part of an API. For most other uses, the stack-allocated form will be more convenient.

Consider the following two examples that do the same thing in each style: take an existing dictionary and look up the "count" uint32 key, adding 1 to it if it is found, or returning an error if the key is not found. Each returns the new dictionary as a floating #GVariant.

Using a stack-allocated GVariantDict

GVariant *
add_to_count (GVariant  *orig,
              GError   **error)
{
  GVariantDict *dict;
  GVariant *result;
  guint32 count;

  dict = g_variant_dict_new (orig);

  if (g_variant_dict_lookup (dict, "count", "u", &count))
    {
      g_variant_dict_insert (dict, "count", "u", count + 1);
      result = g_variant_dict_end (dict);
    }
  else
    {
      g_set_error (...);
      result = NULL;
    }

  g_variant_dict_unref (dict);

  return result;
}

An instance of this type is always passed by reference.

func NewVariantDict

func NewVariantDict(fromAsv *Variant) *VariantDict

NewVariantDict constructs a struct VariantDict.

func (*VariantDict) Clear

func (dict *VariantDict) Clear()

Clear releases all memory associated with a Dict without freeing the Dict structure itself.

It typically only makes sense to do this on a stack-allocated Dict if you want to abort building the value part-way through. This function need not be called if you call g_variant_dict_end() and it also doesn't need to be called on dicts allocated with g_variant_dict_new (see g_variant_dict_unref() for that).

It is valid to call this function on either an initialised Dict or one that was previously cleared by an earlier call to g_variant_dict_clear() but it is not valid to call this function on uninitialised memory.

func (*VariantDict) Contains

func (dict *VariantDict) Contains(key string) bool

Contains checks if key exists in dict.

The function takes the following parameters:

  • key to look up in the dictionary.

The function returns the following values:

  • ok: TRUE if key is in dict.

func (*VariantDict) End

func (dict *VariantDict) End() *Variant

End returns the current value of dict as a #GVariant of type G_VARIANT_TYPE_VARDICT, clearing it in the process.

It is not permissible to use dict in any way after this call except for reference counting operations (in the case of a heap-allocated Dict) or by reinitialising it with g_variant_dict_init() (in the case of stack-allocated).

The function returns the following values:

  • variant: new, floating, #GVariant.

func (*VariantDict) InsertValue

func (dict *VariantDict) InsertValue(key string, value *Variant)

InsertValue inserts (or replaces) a key in a Dict.

value is consumed if it is floating.

The function takes the following parameters:

  • key to insert a value for.
  • value to insert.

func (*VariantDict) LookupValue

func (dict *VariantDict) LookupValue(key string, expectedType *VariantType) *Variant

LookupValue looks up a value in a Dict.

If key is not found in dictionary, NULL is returned.

The expected_type string specifies what type of value is expected. If the value associated with key has a different type then NULL is returned.

If the key is found and the value has the correct type, it is returned. If expected_type was specified then any non-NULL return value will have this type.

The function takes the following parameters:

  • key to look up in the dictionary.
  • expectedType (optional) or NULL.

The function returns the following values:

  • variant: value of the dictionary key, or NULL.

func (*VariantDict) Remove

func (dict *VariantDict) Remove(key string) bool

Remove removes a key and its associated value from a Dict.

The function takes the following parameters:

  • key to remove.

The function returns the following values:

  • ok: TRUE if the key was found and removed.

type VariantParseError

type VariantParseError C.gint

VariantParseError: error codes returned by parsing text-format GVariants.

const (
	// VariantParseErrorFailed: generic error (unused).
	VariantParseErrorFailed VariantParseError = iota
	// VariantParseErrorBasicTypeExpected: non-basic Type was given where a
	// basic type was expected.
	VariantParseErrorBasicTypeExpected
	// VariantParseErrorCannotInferType: cannot infer the Type.
	VariantParseErrorCannotInferType
	// VariantParseErrorDefiniteTypeExpected: indefinite Type was given where a
	// definite type was expected.
	VariantParseErrorDefiniteTypeExpected
	// VariantParseErrorInputNotAtEnd: extra data after parsing finished.
	VariantParseErrorInputNotAtEnd
	// VariantParseErrorInvalidCharacter: invalid character in number or unicode
	// escape.
	VariantParseErrorInvalidCharacter
	// VariantParseErrorInvalidFormatString: not a valid #GVariant format
	// string.
	VariantParseErrorInvalidFormatString
	// VariantParseErrorInvalidObjectPath: not a valid object path.
	VariantParseErrorInvalidObjectPath
	// VariantParseErrorInvalidSignature: not a valid type signature.
	VariantParseErrorInvalidSignature
	// VariantParseErrorInvalidTypeString: not a valid #GVariant type string.
	VariantParseErrorInvalidTypeString
	// VariantParseErrorNoCommonType: could not find a common type for array
	// entries.
	VariantParseErrorNoCommonType
	// VariantParseErrorNumberOutOfRange: numerical value is out of range of the
	// given type.
	VariantParseErrorNumberOutOfRange
	// VariantParseErrorNumberTooBig: numerical value is out of range for any
	// type.
	VariantParseErrorNumberTooBig
	// VariantParseErrorTypeError: cannot parse as variant of the specified
	// type.
	VariantParseErrorTypeError
	// VariantParseErrorUnexpectedToken: unexpected token was encountered.
	VariantParseErrorUnexpectedToken
	// VariantParseErrorUnknownKeyword: unknown keyword was encountered.
	VariantParseErrorUnknownKeyword
	// VariantParseErrorUnterminatedStringConstant: unterminated string
	// constant.
	VariantParseErrorUnterminatedStringConstant
	// VariantParseErrorValueExpected: no value given.
	VariantParseErrorValueExpected
	// VariantParseErrorRecursion: variant was too deeply nested; #GVariant is
	// only guaranteed to handle nesting up to 64 levels (Since: 2.64).
	VariantParseErrorRecursion
)

func (VariantParseError) String

func (v VariantParseError) String() string

String returns the name in string for VariantParseError.

type VariantType

type VariantType struct {
	// contains filtered or unexported fields
}

VariantType: this section introduces the GVariant type system. It is based, in large part, on the D-Bus type system, with two major changes and some minor lifting of restrictions. The D-Bus specification (http://dbus.freedesktop.org/doc/dbus-specification.html), therefore, provides a significant amount of information that is useful when working with GVariant.

The first major change with respect to the D-Bus type system is the introduction of maybe (or "nullable") types. Any type in GVariant can be converted to a maybe type, in which case, "nothing" (or "null") becomes a valid value. Maybe types have been added by introducing the character "m" to type strings.

The second major change is that the GVariant type system supports the concept of "indefinite types" -- types that are less specific than the normal types found in D-Bus. For example, it is possible to speak of "an array of any type" in GVariant, where the D-Bus type system would require you to speak of "an array of integers" or "an array of strings". Indefinite types have been added by introducing the characters "*", "?" and "r" to type strings.

Finally, all arbitrary restrictions relating to the complexity of types are lifted along with the restriction that dictionary entries may only appear nested inside of arrays.

Just as in D-Bus, GVariant types are described with strings ("type strings"). Subject to the differences mentioned above, these strings are of the same form as those found in D-Bus. Note, however: D-Bus always works in terms of messages and therefore individual type strings appear nowhere in its interface. Instead, "signatures" are a concatenation of the strings of the type of each argument in a message. GVariant deals with single values directly so GVariant type strings always describe the type of exactly one value. This means that a D-Bus signature string is generally not a valid GVariant type string -- except in the case that it is the signature of a message containing exactly one argument.

An indefinite type is similar in spirit to what may be called an abstract type in other type systems. No value can exist that has an indefinite type as its type, but values can exist that have types that are subtypes of indefinite types. That is to say, g_variant_get_type() will never return an indefinite type, but calling g_variant_is_of_type() with an indefinite type may return TRUE. For example, you cannot have a value that represents "an array of no particular type", but you can have an "array of integers" which certainly matches the type of "an array of no particular type", since "array of integers" is a subtype of "array of no particular type".

This is similar to how instances of abstract classes may not directly exist in other type systems, but instances of their non-abstract subtypes may. For example, in GTK, no object that has the type of Bin can exist (since Bin is an abstract class), but a Window can certainly be instantiated, and you would say that the Window is a Bin (since Window is a subclass of Bin).

GVariant Type Strings

A GVariant type string can be any of the following:

- any basic type string (listed below)

- "v", "r" or "*"

- one of the characters 'a' or 'm', followed by another type string

- the character '(', followed by a concatenation of zero or more other type strings, followed by the character ')'

- the character '{', followed by a basic type string (see below), followed by another type string, followed by the character '}'

A basic type string describes a basic type (as per g_variant_type_is_basic()) and is always a single character in length. The valid basic type strings are "b", "y", "n", "q", "i", "u", "x", "t", "h", "d", "s", "o", "g" and "?".

The above definition is recursive to arbitrary depth. "aaaaai" and "(ui(nq((y)))s)" are both valid type strings, as is "a(aa(ui)(qna{ya(yd)}))". In order to not hit memory limits, #GVariant imposes a limit on recursion depth of 65 nested containers. This is the limit in the D-Bus specification (64) plus one to allow a BusMessage to be nested in a top-level tuple.

The meaning of each of the characters is as follows:

- b: the type string of G_VARIANT_TYPE_BOOLEAN; a boolean value.

- y: the type string of G_VARIANT_TYPE_BYTE; a byte.

- n: the type string of G_VARIANT_TYPE_INT16; a signed 16 bit integer.

- q: the type string of G_VARIANT_TYPE_UINT16; an unsigned 16 bit integer.

- i: the type string of G_VARIANT_TYPE_INT32; a signed 32 bit integer.

- u: the type string of G_VARIANT_TYPE_UINT32; an unsigned 32 bit integer.

- x: the type string of G_VARIANT_TYPE_INT64; a signed 64 bit integer.

- t: the type string of G_VARIANT_TYPE_UINT64; an unsigned 64 bit integer.

- h: the type string of G_VARIANT_TYPE_HANDLE; a signed 32 bit value that, by convention, is used as an index into an array of file descriptors that are sent alongside a D-Bus message.

- d: the type string of G_VARIANT_TYPE_DOUBLE; a double precision floating point value.

- s: the type string of G_VARIANT_TYPE_STRING; a string.

- o: the type string of G_VARIANT_TYPE_OBJECT_PATH; a string in the form of a D-Bus object path.

- g: the type string of G_VARIANT_TYPE_SIGNATURE; a string in the form of a D-Bus type signature.

- ?: the type string of G_VARIANT_TYPE_BASIC; an indefinite type that is a supertype of any of the basic types.

- v: the type string of G_VARIANT_TYPE_VARIANT; a container type that contain any other type of value.

- a: used as a prefix on another type string to mean an array of that type; the type string "ai", for example, is the type of an array of signed 32-bit integers.

- m: used as a prefix on another type string to mean a "maybe", or "nullable", version of that type; the type string "ms", for example, is the type of a value that maybe contains a string, or maybe contains nothing.

- (): used to enclose zero or more other concatenated type strings to create a tuple type; the type string "(is)", for example, is the type of a pair of an integer and a string.

- r: the type string of G_VARIANT_TYPE_TUPLE; an indefinite type that is a supertype of any tuple type, regardless of the number of items.

- {}: used to enclose a basic type string concatenated with another type string to create a dictionary entry type, which usually appears inside of an array to form a dictionary; the type string "a{sd}", for example, is the type of a dictionary that maps strings to double precision floating point values.

The first type (the basic type) is the key type and the second type is
the value type. The reason that the first type is restricted to being a
basic type is so that it can easily be hashed.

- *: the type string of G_VARIANT_TYPE_ANY; the indefinite type that is a supertype of all types. Note that, as with all type strings, this character represents exactly one type. It cannot be used inside of tuples to mean "any number of items".

Any type string of a container that contains an indefinite type is, itself, an indefinite type. For example, the type string "a*" (corresponding to G_VARIANT_TYPE_ARRAY) is an indefinite type that is a supertype of every array type. "(*s)" is a supertype of all tuples that contain exactly two items where the second item is a string.

"a{?*}" is an indefinite type that is a supertype of all arrays containing dictionary entries where the key is any basic type and the value is any type at all. This is, by definition, a dictionary, so this type string corresponds to G_VARIANT_TYPE_DICTIONARY. Note that, due to the restriction that the key of a dictionary entry must be a basic type, "{**}" is not a valid type string.

An instance of this type is always passed by reference.

func NewVariantType

func NewVariantType(typeString string) *VariantType

NewVariantType constructs a struct VariantType.

func NewVariantTypeArray

func NewVariantTypeArray(element *VariantType) *VariantType

NewVariantTypeArray constructs a struct VariantType.

func NewVariantTypeDictEntry

func NewVariantTypeDictEntry(key *VariantType, value *VariantType) *VariantType

NewVariantTypeDictEntry constructs a struct VariantType.

func NewVariantTypeMaybe

func NewVariantTypeMaybe(element *VariantType) *VariantType

NewVariantTypeMaybe constructs a struct VariantType.

func NewVariantTypeTuple

func NewVariantTypeTuple(items []*VariantType) *VariantType

NewVariantTypeTuple constructs a struct VariantType.

func VariantTypeChecked_

func VariantTypeChecked_(arg0 string) *VariantType

The function takes the following parameters:

The function returns the following values:

func (*VariantType) Copy

func (typ *VariantType) Copy() *VariantType

Copy makes a copy of a Type. It is appropriate to call g_variant_type_free() on the return value. type may not be NULL.

The function returns the following values:

  • variantType: new Type

    Since 2.24.

func (*VariantType) DupString

func (typ *VariantType) DupString() string

DupString returns a newly-allocated copy of the type string corresponding to type. The returned string is nul-terminated. It is appropriate to call g_free() on the return value.

The function returns the following values:

  • utf8: corresponding type string

    Since 2.24.

func (*VariantType) Element

func (typ *VariantType) Element() *VariantType

Element determines the element type of an array or maybe type.

This function may only be used with array or maybe types.

The function returns the following values:

  • variantType: element type of type

    Since 2.24.

func (*VariantType) Equal

func (type1 *VariantType) Equal(type2 *VariantType) bool

Equal compares type1 and type2 for equality.

Only returns TRUE if the types are exactly equal. Even if one type is an indefinite type and the other is a subtype of it, FALSE will be returned if they are not exactly equal. If you want to check for subtypes, use g_variant_type_is_subtype_of().

The argument types of type1 and type2 are only #gconstpointer to allow use with Table without function pointer casting. For both arguments, a valid Type must be provided.

The function takes the following parameters:

  • type2: Type.

The function returns the following values:

  • ok: TRUE if type1 and type2 are exactly equal

    Since 2.24.

func (*VariantType) First

func (typ *VariantType) First() *VariantType

First determines the first item type of a tuple or dictionary entry type.

This function may only be used with tuple or dictionary entry types, but must not be used with the generic tuple type G_VARIANT_TYPE_TUPLE.

In the case of a dictionary entry type, this returns the type of the key.

NULL is returned in case of type being G_VARIANT_TYPE_UNIT.

This call, together with g_variant_type_next() provides an iterator interface over tuple and dictionary entry types.

The function returns the following values:

  • variantType: first item type of type, or NULL

    Since 2.24.

func (*VariantType) Hash

func (typ *VariantType) Hash() uint

Hash hashes type.

The argument type of type is only #gconstpointer to allow use with Table without function pointer casting. A valid Type must be provided.

The function returns the following values:

  • guint: hash value

    Since 2.24.

func (*VariantType) IsArray

func (typ *VariantType) IsArray() bool

IsArray determines if the given type is an array type. This is true if the type string for type starts with an 'a'.

This function returns TRUE for any indefinite type for which every definite subtype is an array type -- G_VARIANT_TYPE_ARRAY, for example.

The function returns the following values:

  • ok: TRUE if type is an array type

    Since 2.24.

func (*VariantType) IsBasic

func (typ *VariantType) IsBasic() bool

IsBasic determines if the given type is a basic type.

Basic types are booleans, bytes, integers, doubles, strings, object paths and signatures.

Only a basic type may be used as the key of a dictionary entry.

This function returns FALSE for all indefinite types except G_VARIANT_TYPE_BASIC.

The function returns the following values:

  • ok: TRUE if type is a basic type

    Since 2.24.

func (*VariantType) IsContainer

func (typ *VariantType) IsContainer() bool

IsContainer determines if the given type is a container type.

Container types are any array, maybe, tuple, or dictionary entry types plus the variant type.

This function returns TRUE for any indefinite type for which every definite subtype is a container -- G_VARIANT_TYPE_ARRAY, for example.

The function returns the following values:

  • ok: TRUE if type is a container type

    Since 2.24.

func (*VariantType) IsDefinite

func (typ *VariantType) IsDefinite() bool

IsDefinite determines if the given type is definite (ie: not indefinite).

A type is definite if its type string does not contain any indefinite type characters ('*', '?', or 'r').

A #GVariant instance may not have an indefinite type, so calling this function on the result of g_variant_get_type() will always result in TRUE being returned. Calling this function on an indefinite type like G_VARIANT_TYPE_ARRAY, however, will result in FALSE being returned.

The function returns the following values:

  • ok: TRUE if type is definite

    Since 2.24.

func (*VariantType) IsDictEntry

func (typ *VariantType) IsDictEntry() bool

IsDictEntry determines if the given type is a dictionary entry type. This is true if the type string for type starts with a '{'.

This function returns TRUE for any indefinite type for which every definite subtype is a dictionary entry type -- G_VARIANT_TYPE_DICT_ENTRY, for example.

The function returns the following values:

  • ok: TRUE if type is a dictionary entry type

    Since 2.24.

func (*VariantType) IsMaybe

func (typ *VariantType) IsMaybe() bool

IsMaybe determines if the given type is a maybe type. This is true if the type string for type starts with an 'm'.

This function returns TRUE for any indefinite type for which every definite subtype is a maybe type -- G_VARIANT_TYPE_MAYBE, for example.

The function returns the following values:

  • ok: TRUE if type is a maybe type

    Since 2.24.

func (*VariantType) IsSubtypeOf

func (typ *VariantType) IsSubtypeOf(supertype *VariantType) bool

IsSubtypeOf checks if type is a subtype of supertype.

This function returns TRUE if type is a subtype of supertype. All types are considered to be subtypes of themselves. Aside from that, only indefinite types can have subtypes.

The function takes the following parameters:

  • supertype: Type.

The function returns the following values:

  • ok: TRUE if type is a subtype of supertype

    Since 2.24.

func (*VariantType) IsTuple

func (typ *VariantType) IsTuple() bool

IsTuple determines if the given type is a tuple type. This is true if the type string for type starts with a '(' or if type is G_VARIANT_TYPE_TUPLE.

This function returns TRUE for any indefinite type for which every definite subtype is a tuple type -- G_VARIANT_TYPE_TUPLE, for example.

The function returns the following values:

  • ok: TRUE if type is a tuple type

    Since 2.24.

func (*VariantType) IsVariant

func (typ *VariantType) IsVariant() bool

IsVariant determines if the given type is the variant type.

The function returns the following values:

  • ok: TRUE if type is the variant type

    Since 2.24.

func (*VariantType) Key

func (typ *VariantType) Key() *VariantType

Key determines the key type of a dictionary entry type.

This function may only be used with a dictionary entry type. Other than the additional restriction, this call is equivalent to g_variant_type_first().

The function returns the following values:

  • variantType: key type of the dictionary entry

    Since 2.24.

func (*VariantType) NItems

func (typ *VariantType) NItems() uint

NItems determines the number of items contained in a tuple or dictionary entry type.

This function may only be used with tuple or dictionary entry types, but must not be used with the generic tuple type G_VARIANT_TYPE_TUPLE.

In the case of a dictionary entry type, this function will always return 2.

The function returns the following values:

  • gsize: number of items in type

    Since 2.24.

func (*VariantType) Next

func (typ *VariantType) Next() *VariantType

Next determines the next item type of a tuple or dictionary entry type.

type must be the result of a previous call to g_variant_type_first() or g_variant_type_next().

If called on the key type of a dictionary entry then this call returns the value type. If called on the value type of a dictionary entry then this call returns NULL.

For tuples, NULL is returned when type is the last item in a tuple.

The function returns the following values:

  • variantType: next Type after type, or NULL

    Since 2.24.

func (*VariantType) StringLength

func (typ *VariantType) StringLength() uint

StringLength returns the length of the type string corresponding to the given type. This function must be used to determine the valid extent of the memory region returned by g_variant_type_peek_string().

The function returns the following values:

  • gsize: length of the corresponding type string

    Since 2.24.

func (*VariantType) Value

func (typ *VariantType) Value() *VariantType

Value determines the value type of a dictionary entry type.

This function may only be used with a dictionary entry type.

The function returns the following values:

  • variantType: value type of the dictionary entry

    Since 2.24.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL