Add function to get the codeset name for the current locale.
[glib.git] / glib / glib.h
blobd585282b9ec3803d7b874d11b60b6ca2593d1e76
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-1999. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
27 #ifndef __G_LIB_H__
28 #define __G_LIB_H__
30 /* Here we provide G_GNUC_EXTENSION as an alias for __extension__,
31 * where this is valid. This allows for warningless compilation of
32 * "long long" types even in the presence of '-ansi -pedantic'. This
33 * of course should be with the other GCC-isms below, but then
34 * glibconfig.h wouldn't load cleanly and it is better to have that
35 * here, than in glibconfig.h.
37 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 8)
38 # define G_GNUC_EXTENSION __extension__
39 #else
40 # define G_GNUC_EXTENSION
41 #endif
43 /* system specific config file glibconfig.h provides definitions for
44 * the extrema of many of the standard types. These are:
46 * G_MINSHORT, G_MAXSHORT
47 * G_MININT, G_MAXINT
48 * G_MINLONG, G_MAXLONG
49 * G_MINFLOAT, G_MAXFLOAT
50 * G_MINDOUBLE, G_MAXDOUBLE
52 * It also provides the following typedefs:
54 * gint8, guint8
55 * gint16, guint16
56 * gint32, guint32
57 * gint64, guint64
59 * It defines the G_BYTE_ORDER symbol to one of G_*_ENDIAN (see later in
60 * this file).
62 * And it provides a way to store and retrieve a `gint' in/from a `gpointer'.
63 * This is useful to pass an integer instead of a pointer to a callback.
65 * GINT_TO_POINTER (i), GUINT_TO_POINTER (i)
66 * GPOINTER_TO_INT (p), GPOINTER_TO_UINT (p)
68 * Finally, it provides the following wrappers to STDC functions:
70 * void g_memmove (gpointer dest, gconstpointer void *src, gulong count);
71 * A wrapper for STDC memmove, or an implementation, if memmove doesn't
72 * exist. The prototype looks like the above, give or take a const,
73 * or size_t.
75 #include <glibconfig.h>
77 /* Define some mathematical constants that aren't available
78 * symbolically in some strict ISO C implementations.
80 #define G_E 2.7182818284590452354E0
81 #define G_LN2 6.9314718055994530942E-1
82 #define G_LN10 2.3025850929940456840E0
83 #define G_PI 3.14159265358979323846E0
84 #define G_PI_2 1.57079632679489661923E0
85 #define G_PI_4 0.78539816339744830962E0
86 #define G_SQRT2 1.4142135623730950488E0
88 /* include varargs functions for assertment macros
90 #include <stdarg.h>
92 /* optionally feature DMALLOC memory allocation debugger
94 #ifdef USE_DMALLOC
95 #include "dmalloc.h"
96 #endif
99 #ifdef G_OS_WIN32
101 /* On native Win32, directory separator is the backslash, and search path
102 * separator is the semicolon.
104 #define G_DIR_SEPARATOR '\\'
105 #define G_DIR_SEPARATOR_S "\\"
106 #define G_SEARCHPATH_SEPARATOR ';'
107 #define G_SEARCHPATH_SEPARATOR_S ";"
109 #else /* !G_OS_WIN32 */
111 /* Unix */
113 #define G_DIR_SEPARATOR '/'
114 #define G_DIR_SEPARATOR_S "/"
115 #define G_SEARCHPATH_SEPARATOR ':'
116 #define G_SEARCHPATH_SEPARATOR_S ":"
118 #endif /* !G_OS_WIN32 */
120 #ifdef __cplusplus
121 extern "C" {
122 #endif /* __cplusplus */
125 /* Provide definitions for some commonly used macros.
126 * Some of them are only provided if they haven't already
127 * been defined. It is assumed that if they are already
128 * defined then the current definition is correct.
130 #ifndef NULL
131 # ifdef __cplusplus
132 # define NULL (0L)
133 # else /* !__cplusplus */
134 # define NULL ((void*) 0)
135 # endif /* !__cplusplus */
136 #endif
138 #ifndef FALSE
139 #define FALSE (0)
140 #endif
142 #ifndef TRUE
143 #define TRUE (!FALSE)
144 #endif
146 #undef MAX
147 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
149 #undef MIN
150 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
152 #undef ABS
153 #define ABS(a) (((a) < 0) ? -(a) : (a))
155 #undef CLAMP
156 #define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
158 #define G_STRINGIFY(macro_or_string) G_STRINGIFY_ARG (macro_or_string)
159 #define G_STRINGIFY_ARG(contents) #contents
161 /* provide a string identifying the current code position */
162 #ifdef __GNUC__
163 # define G_STRLOC __FILE__ ":" G_STRINGIFY (__LINE__) ":" __PRETTY_FUNCTION__ "()"
164 #else
165 # define G_STRLOC __FILE__ ":" G_STRINGIFY (__LINE__)
166 #endif
169 /* Count the number of elements in an array. The array must be defined
170 * as such; using this with a dynamically allocated array will give
171 * incorrect results.
173 #define G_N_ELEMENTS(arr) (sizeof (arr) / sizeof ((arr)[0]))
175 /* Define G_VA_COPY() to do the right thing for copying va_list variables.
176 * glibconfig.h may have already defined G_VA_COPY as va_copy or __va_copy.
178 #if !defined (G_VA_COPY)
179 # if defined (__GNUC__) && defined (__PPC__) && (defined (_CALL_SYSV) || defined (_WIN32))
180 # define G_VA_COPY(ap1, ap2) (*(ap1) = *(ap2))
181 # elif defined (G_VA_COPY_AS_ARRAY)
182 # define G_VA_COPY(ap1, ap2) g_memmove ((ap1), (ap2), sizeof (va_list))
183 # else /* va_list is a pointer */
184 # define G_VA_COPY(ap1, ap2) ((ap1) = (ap2))
185 # endif /* va_list is a pointer */
186 #endif /* !G_VA_COPY */
189 /* Provide convenience macros for handling structure
190 * fields through their offsets.
192 #define G_STRUCT_OFFSET(struct_type, member) \
193 ((glong) ((guint8*) &((struct_type*) 0)->member))
194 #define G_STRUCT_MEMBER_P(struct_p, struct_offset) \
195 ((gpointer) ((guint8*) (struct_p) + (glong) (struct_offset)))
196 #define G_STRUCT_MEMBER(member_type, struct_p, struct_offset) \
197 (*(member_type*) G_STRUCT_MEMBER_P ((struct_p), (struct_offset)))
200 /* inlining hassle. for compilers that don't allow the `inline' keyword,
201 * mostly because of strict ANSI C compliance or dumbness, we try to fall
202 * back to either `__inline__' or `__inline'.
203 * we define G_CAN_INLINE, if the compiler seems to be actually
204 * *capable* to do function inlining, in which case inline function bodys
205 * do make sense. we also define G_INLINE_FUNC to properly export the
206 * function prototypes if no inlining can be performed.
207 * we special case most of the stuff, so inline functions can have a normal
208 * implementation by defining G_INLINE_FUNC to extern and G_CAN_INLINE to 1.
210 #ifndef G_INLINE_FUNC
211 # define G_CAN_INLINE 1
212 #endif
213 #ifdef G_HAVE_INLINE
214 # if defined (__GNUC__) && defined (__STRICT_ANSI__)
215 # undef inline
216 # define inline __inline__
217 # endif
218 #else /* !G_HAVE_INLINE */
219 # undef inline
220 # if defined (G_HAVE___INLINE__)
221 # define inline __inline__
222 # else /* !inline && !__inline__ */
223 # if defined (G_HAVE___INLINE)
224 # define inline __inline
225 # else /* !inline && !__inline__ && !__inline */
226 # define inline /* don't inline, then */
227 # ifndef G_INLINE_FUNC
228 # undef G_CAN_INLINE
229 # endif
230 # endif
231 # endif
232 #endif
233 #ifndef G_INLINE_FUNC
234 # ifdef __GNUC__
235 # ifdef __OPTIMIZE__
236 # define G_INLINE_FUNC extern inline
237 # else
238 # undef G_CAN_INLINE
239 # define G_INLINE_FUNC extern
240 # endif
241 # else /* !__GNUC__ */
242 # ifdef G_CAN_INLINE
243 # define G_INLINE_FUNC static inline
244 # else
245 # define G_INLINE_FUNC extern
246 # endif
247 # endif /* !__GNUC__ */
248 #endif /* !G_INLINE_FUNC */
251 /* Provide simple macro statement wrappers (adapted from Perl):
252 * G_STMT_START { statements; } G_STMT_END;
253 * can be used as a single statement, as in
254 * if (x) G_STMT_START { ... } G_STMT_END; else ...
256 * For gcc we will wrap the statements within `({' and `})' braces.
257 * For SunOS they will be wrapped within `if (1)' and `else (void) 0',
258 * and otherwise within `do' and `while (0)'.
260 #if !(defined (G_STMT_START) && defined (G_STMT_END))
261 # if defined (__GNUC__) && !defined (__STRICT_ANSI__) && !defined (__cplusplus)
262 # define G_STMT_START (void)(
263 # define G_STMT_END )
264 # else
265 # if (defined (sun) || defined (__sun__))
266 # define G_STMT_START if (1)
267 # define G_STMT_END else (void)0
268 # else
269 # define G_STMT_START do
270 # define G_STMT_END while (0)
271 # endif
272 # endif
273 #endif
276 /* Provide macros to feature the GCC function attribute.
278 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4)
279 #define G_GNUC_PRINTF( format_idx, arg_idx ) \
280 __attribute__((format (printf, format_idx, arg_idx)))
281 #define G_GNUC_SCANF( format_idx, arg_idx ) \
282 __attribute__((format (scanf, format_idx, arg_idx)))
283 #define G_GNUC_FORMAT( arg_idx ) \
284 __attribute__((format_arg (arg_idx)))
285 #define G_GNUC_NORETURN \
286 __attribute__((noreturn))
287 #define G_GNUC_CONST \
288 __attribute__((const))
289 #define G_GNUC_UNUSED \
290 __attribute__((unused))
291 #else /* !__GNUC__ */
292 #define G_GNUC_PRINTF( format_idx, arg_idx )
293 #define G_GNUC_SCANF( format_idx, arg_idx )
294 #define G_GNUC_FORMAT( arg_idx )
295 #define G_GNUC_NORETURN
296 #define G_GNUC_CONST
297 #define G_GNUC_UNUSED
298 #endif /* !__GNUC__ */
300 /* Wrap the gcc __PRETTY_FUNCTION__ and __FUNCTION__ variables with
301 * macros, so we can refer to them as strings unconditionally.
303 #ifdef __GNUC__
304 #define G_GNUC_FUNCTION __FUNCTION__
305 #define G_GNUC_PRETTY_FUNCTION __PRETTY_FUNCTION__
306 #else /* !__GNUC__ */
307 #define G_GNUC_FUNCTION ""
308 #define G_GNUC_PRETTY_FUNCTION ""
309 #endif /* !__GNUC__ */
311 /* we try to provide a usefull equivalent for ATEXIT if it is
312 * not defined, but use is actually abandoned. people should
313 * use g_atexit() instead.
315 #ifndef ATEXIT
316 # define ATEXIT(proc) g_ATEXIT(proc)
317 #else
318 # define G_NATIVE_ATEXIT
319 #endif /* ATEXIT */
321 /* Hacker macro to place breakpoints for elected machines.
322 * Actual use is strongly deprecated of course ;)
324 #if defined (__i386__) && defined (__GNUC__) && __GNUC__ >= 2
325 #define G_BREAKPOINT() G_STMT_START{ __asm__ __volatile__ ("int $03"); }G_STMT_END
326 #elif defined (__alpha__) && defined (__GNUC__) && __GNUC__ >= 2
327 #define G_BREAKPOINT() G_STMT_START{ __asm__ __volatile__ ("bpt"); }G_STMT_END
328 #else /* !__i386__ && !__alpha__ */
329 #define G_BREAKPOINT()
330 #endif /* __i386__ */
333 /* Provide macros for easily allocating memory. The macros
334 * will cast the allocated memory to the specified type
335 * in order to avoid compiler warnings. (Makes the code neater).
338 #ifdef __DMALLOC_H__
339 # define g_new(type, count) (ALLOC (type, count))
340 # define g_new0(type, count) (CALLOC (type, count))
341 # define g_renew(type, mem, count) (REALLOC (mem, type, count))
342 #else /* __DMALLOC_H__ */
343 # define g_new(type, count) \
344 ((type *) g_malloc ((unsigned) sizeof (type) * (count)))
345 # define g_new0(type, count) \
346 ((type *) g_malloc0 ((unsigned) sizeof (type) * (count)))
347 # define g_renew(type, mem, count) \
348 ((type *) g_realloc (mem, (unsigned) sizeof (type) * (count)))
349 #endif /* __DMALLOC_H__ */
351 #define g_mem_chunk_create(type, pre_alloc, alloc_type) ( \
352 g_mem_chunk_new (#type " mem chunks (" #pre_alloc ")", \
353 sizeof (type), \
354 sizeof (type) * (pre_alloc), \
355 (alloc_type)) \
357 #define g_chunk_new(type, chunk) ( \
358 (type *) g_mem_chunk_alloc (chunk) \
360 #define g_chunk_new0(type, chunk) ( \
361 (type *) g_mem_chunk_alloc0 (chunk) \
363 #define g_chunk_free(mem, mem_chunk) G_STMT_START { \
364 g_mem_chunk_free ((mem_chunk), (mem)); \
365 } G_STMT_END
368 /* Provide macros for error handling. The "assert" macros will
369 * exit on failure. The "return" macros will exit the current
370 * function. Two different definitions are given for the macros
371 * if G_DISABLE_ASSERT is not defined, in order to support gcc's
372 * __PRETTY_FUNCTION__ capability.
375 #ifdef G_DISABLE_ASSERT
377 #define g_assert(expr)
378 #define g_assert_not_reached()
380 #else /* !G_DISABLE_ASSERT */
382 #ifdef __GNUC__
384 #define g_assert(expr) G_STMT_START{ \
385 if (!(expr)) \
386 g_log (G_LOG_DOMAIN, \
387 G_LOG_LEVEL_ERROR, \
388 "file %s: line %d (%s): assertion failed: (%s)", \
389 __FILE__, \
390 __LINE__, \
391 __PRETTY_FUNCTION__, \
392 #expr); }G_STMT_END
394 #define g_assert_not_reached() G_STMT_START{ \
395 g_log (G_LOG_DOMAIN, \
396 G_LOG_LEVEL_ERROR, \
397 "file %s: line %d (%s): should not be reached", \
398 __FILE__, \
399 __LINE__, \
400 __PRETTY_FUNCTION__); }G_STMT_END
402 #else /* !__GNUC__ */
404 #define g_assert(expr) G_STMT_START{ \
405 if (!(expr)) \
406 g_log (G_LOG_DOMAIN, \
407 G_LOG_LEVEL_ERROR, \
408 "file %s: line %d: assertion failed: (%s)", \
409 __FILE__, \
410 __LINE__, \
411 #expr); }G_STMT_END
413 #define g_assert_not_reached() G_STMT_START{ \
414 g_log (G_LOG_DOMAIN, \
415 G_LOG_LEVEL_ERROR, \
416 "file %s: line %d: should not be reached", \
417 __FILE__, \
418 __LINE__); }G_STMT_END
420 #endif /* __GNUC__ */
422 #endif /* !G_DISABLE_ASSERT */
425 #ifdef G_DISABLE_CHECKS
427 #define g_return_if_fail(expr)
428 #define g_return_val_if_fail(expr,val)
430 #else /* !G_DISABLE_CHECKS */
432 #ifdef __GNUC__
434 #define g_return_if_fail(expr) G_STMT_START{ \
435 if (!(expr)) \
437 g_log (G_LOG_DOMAIN, \
438 G_LOG_LEVEL_CRITICAL, \
439 "file %s: line %d (%s): assertion `%s' failed.", \
440 __FILE__, \
441 __LINE__, \
442 __PRETTY_FUNCTION__, \
443 #expr); \
444 return; \
445 }; }G_STMT_END
447 #define g_return_val_if_fail(expr,val) G_STMT_START{ \
448 if (!(expr)) \
450 g_log (G_LOG_DOMAIN, \
451 G_LOG_LEVEL_CRITICAL, \
452 "file %s: line %d (%s): assertion `%s' failed.", \
453 __FILE__, \
454 __LINE__, \
455 __PRETTY_FUNCTION__, \
456 #expr); \
457 return val; \
458 }; }G_STMT_END
460 #else /* !__GNUC__ */
462 #define g_return_if_fail(expr) G_STMT_START{ \
463 if (!(expr)) \
465 g_log (G_LOG_DOMAIN, \
466 G_LOG_LEVEL_CRITICAL, \
467 "file %s: line %d: assertion `%s' failed.", \
468 __FILE__, \
469 __LINE__, \
470 #expr); \
471 return; \
472 }; }G_STMT_END
474 #define g_return_val_if_fail(expr, val) G_STMT_START{ \
475 if (!(expr)) \
477 g_log (G_LOG_DOMAIN, \
478 G_LOG_LEVEL_CRITICAL, \
479 "file %s: line %d: assertion `%s' failed.", \
480 __FILE__, \
481 __LINE__, \
482 #expr); \
483 return val; \
484 }; }G_STMT_END
486 #endif /* !__GNUC__ */
488 #endif /* !G_DISABLE_CHECKS */
491 /* Provide type definitions for commonly used types.
492 * These are useful because a "gint8" can be adjusted
493 * to be 1 byte (8 bits) on all platforms. Similarly and
494 * more importantly, "gint32" can be adjusted to be
495 * 4 bytes (32 bits) on all platforms.
498 typedef char gchar;
499 typedef short gshort;
500 typedef long glong;
501 typedef int gint;
502 typedef gint gboolean;
504 typedef unsigned char guchar;
505 typedef unsigned short gushort;
506 typedef unsigned long gulong;
507 typedef unsigned int guint;
509 #define G_GSHORT_FORMAT "hi"
510 #define G_GUSHORT_FORMAT "hu"
511 #define G_GINT_FORMAT "i"
512 #define G_GUINT_FORMAT "u"
513 #define G_GLONG_FORMAT "li"
514 #define G_GULONG_FORMAT "lu"
516 typedef float gfloat;
517 typedef double gdouble;
519 /* HAVE_LONG_DOUBLE doesn't work correctly on all platforms.
520 * Since gldouble isn't used anywhere, just disable it for now */
522 #if 0
523 #ifdef HAVE_LONG_DOUBLE
524 typedef long double gldouble;
525 #else /* HAVE_LONG_DOUBLE */
526 typedef double gldouble;
527 #endif /* HAVE_LONG_DOUBLE */
528 #endif /* 0 */
530 typedef void* gpointer;
531 typedef const void *gconstpointer;
534 typedef gint32 gssize;
535 typedef guint32 gsize;
536 typedef guint32 GQuark;
537 typedef gint32 GTime;
540 /* Portable endian checks and conversions
542 * glibconfig.h defines G_BYTE_ORDER which expands to one of
543 * the below macros.
545 #define G_LITTLE_ENDIAN 1234
546 #define G_BIG_ENDIAN 4321
547 #define G_PDP_ENDIAN 3412 /* unused, need specific PDP check */
550 /* Basic bit swapping functions
552 #define GUINT16_SWAP_LE_BE_CONSTANT(val) ((guint16) ( \
553 (((guint16) (val) & (guint16) 0x00ffU) << 8) | \
554 (((guint16) (val) & (guint16) 0xff00U) >> 8)))
555 #define GUINT32_SWAP_LE_BE_CONSTANT(val) ((guint32) ( \
556 (((guint32) (val) & (guint32) 0x000000ffU) << 24) | \
557 (((guint32) (val) & (guint32) 0x0000ff00U) << 8) | \
558 (((guint32) (val) & (guint32) 0x00ff0000U) >> 8) | \
559 (((guint32) (val) & (guint32) 0xff000000U) >> 24)))
561 /* Intel specific stuff for speed
563 #if defined (__i386__) && defined (__GNUC__) && __GNUC__ >= 2
564 # define GUINT16_SWAP_LE_BE_X86(val) \
565 (__extension__ \
566 ({ register guint16 __v; \
567 if (__builtin_constant_p (val)) \
568 __v = GUINT16_SWAP_LE_BE_CONSTANT (val); \
569 else \
570 __asm__ __const__ ("rorw $8, %w0" \
571 : "=r" (__v) \
572 : "0" ((guint16) (val))); \
573 __v; }))
574 # define GUINT16_SWAP_LE_BE(val) (GUINT16_SWAP_LE_BE_X86 (val))
575 # if !defined(__i486__) && !defined(__i586__) \
576 && !defined(__pentium__) && !defined(__i686__) && !defined(__pentiumpro__)
577 # define GUINT32_SWAP_LE_BE_X86(val) \
578 (__extension__ \
579 ({ register guint32 __v; \
580 if (__builtin_constant_p (val)) \
581 __v = GUINT32_SWAP_LE_BE_CONSTANT (val); \
582 else \
583 __asm__ __const__ ("rorw $8, %w0\n\t" \
584 "rorl $16, %0\n\t" \
585 "rorw $8, %w0" \
586 : "=r" (__v) \
587 : "0" ((guint32) (val))); \
588 __v; }))
589 # else /* 486 and higher has bswap */
590 # define GUINT32_SWAP_LE_BE_X86(val) \
591 (__extension__ \
592 ({ register guint32 __v; \
593 if (__builtin_constant_p (val)) \
594 __v = GUINT32_SWAP_LE_BE_CONSTANT (val); \
595 else \
596 __asm__ __const__ ("bswap %0" \
597 : "=r" (__v) \
598 : "0" ((guint32) (val))); \
599 __v; }))
600 # endif /* processor specific 32-bit stuff */
601 # define GUINT32_SWAP_LE_BE(val) (GUINT32_SWAP_LE_BE_X86 (val))
602 #else /* !__i386__ */
603 # define GUINT16_SWAP_LE_BE(val) (GUINT16_SWAP_LE_BE_CONSTANT (val))
604 # define GUINT32_SWAP_LE_BE(val) (GUINT32_SWAP_LE_BE_CONSTANT (val))
605 #endif /* __i386__ */
607 #ifdef G_HAVE_GINT64
608 # define GUINT64_SWAP_LE_BE_CONSTANT(val) ((guint64) ( \
609 (((guint64) (val) & \
610 (guint64) G_GINT64_CONSTANT(0x00000000000000ffU)) << 56) | \
611 (((guint64) (val) & \
612 (guint64) G_GINT64_CONSTANT(0x000000000000ff00U)) << 40) | \
613 (((guint64) (val) & \
614 (guint64) G_GINT64_CONSTANT(0x0000000000ff0000U)) << 24) | \
615 (((guint64) (val) & \
616 (guint64) G_GINT64_CONSTANT(0x00000000ff000000U)) << 8) | \
617 (((guint64) (val) & \
618 (guint64) G_GINT64_CONSTANT(0x000000ff00000000U)) >> 8) | \
619 (((guint64) (val) & \
620 (guint64) G_GINT64_CONSTANT(0x0000ff0000000000U)) >> 24) | \
621 (((guint64) (val) & \
622 (guint64) G_GINT64_CONSTANT(0x00ff000000000000U)) >> 40) | \
623 (((guint64) (val) & \
624 (guint64) G_GINT64_CONSTANT(0xff00000000000000U)) >> 56)))
625 # if defined (__i386__) && defined (__GNUC__) && __GNUC__ >= 2
626 # define GUINT64_SWAP_LE_BE_X86(val) \
627 (__extension__ \
628 ({ union { guint64 __ll; \
629 guint32 __l[2]; } __r; \
630 if (__builtin_constant_p (val)) \
631 __r.__ll = GUINT64_SWAP_LE_BE_CONSTANT (val); \
632 else \
634 union { guint64 __ll; \
635 guint32 __l[2]; } __w; \
636 __w.__ll = ((guint64) val); \
637 __r.__l[0] = GUINT32_SWAP_LE_BE (__w.__l[1]); \
638 __r.__l[1] = GUINT32_SWAP_LE_BE (__w.__l[0]); \
640 __r.__ll; }))
641 # define GUINT64_SWAP_LE_BE(val) (GUINT64_SWAP_LE_BE_X86 (val))
642 # else /* !__i386__ */
643 # define GUINT64_SWAP_LE_BE(val) (GUINT64_SWAP_LE_BE_CONSTANT(val))
644 # endif
645 #endif
647 #define GUINT16_SWAP_LE_PDP(val) ((guint16) (val))
648 #define GUINT16_SWAP_BE_PDP(val) (GUINT16_SWAP_LE_BE (val))
649 #define GUINT32_SWAP_LE_PDP(val) ((guint32) ( \
650 (((guint32) (val) & (guint32) 0x0000ffffU) << 16) | \
651 (((guint32) (val) & (guint32) 0xffff0000U) >> 16)))
652 #define GUINT32_SWAP_BE_PDP(val) ((guint32) ( \
653 (((guint32) (val) & (guint32) 0x00ff00ffU) << 8) | \
654 (((guint32) (val) & (guint32) 0xff00ff00U) >> 8)))
656 /* The G*_TO_?E() macros are defined in glibconfig.h.
657 * The transformation is symmetric, so the FROM just maps to the TO.
659 #define GINT16_FROM_LE(val) (GINT16_TO_LE (val))
660 #define GUINT16_FROM_LE(val) (GUINT16_TO_LE (val))
661 #define GINT16_FROM_BE(val) (GINT16_TO_BE (val))
662 #define GUINT16_FROM_BE(val) (GUINT16_TO_BE (val))
663 #define GINT32_FROM_LE(val) (GINT32_TO_LE (val))
664 #define GUINT32_FROM_LE(val) (GUINT32_TO_LE (val))
665 #define GINT32_FROM_BE(val) (GINT32_TO_BE (val))
666 #define GUINT32_FROM_BE(val) (GUINT32_TO_BE (val))
668 #ifdef G_HAVE_GINT64
669 #define GINT64_FROM_LE(val) (GINT64_TO_LE (val))
670 #define GUINT64_FROM_LE(val) (GUINT64_TO_LE (val))
671 #define GINT64_FROM_BE(val) (GINT64_TO_BE (val))
672 #define GUINT64_FROM_BE(val) (GUINT64_TO_BE (val))
673 #endif
675 #define GLONG_FROM_LE(val) (GLONG_TO_LE (val))
676 #define GULONG_FROM_LE(val) (GULONG_TO_LE (val))
677 #define GLONG_FROM_BE(val) (GLONG_TO_BE (val))
678 #define GULONG_FROM_BE(val) (GULONG_TO_BE (val))
680 #define GINT_FROM_LE(val) (GINT_TO_LE (val))
681 #define GUINT_FROM_LE(val) (GUINT_TO_LE (val))
682 #define GINT_FROM_BE(val) (GINT_TO_BE (val))
683 #define GUINT_FROM_BE(val) (GUINT_TO_BE (val))
686 /* Portable versions of host-network order stuff
688 #define g_ntohl(val) (GUINT32_FROM_BE (val))
689 #define g_ntohs(val) (GUINT16_FROM_BE (val))
690 #define g_htonl(val) (GUINT32_TO_BE (val))
691 #define g_htons(val) (GUINT16_TO_BE (val))
694 /* Glib version.
695 * we prefix variable declarations so they can
696 * properly get exported in windows dlls.
698 #ifdef G_OS_WIN32
699 # ifdef GLIB_COMPILATION
700 # define GUTILS_C_VAR __declspec(dllexport)
701 # else /* !GLIB_COMPILATION */
702 # define GUTILS_C_VAR extern __declspec(dllimport)
703 # endif /* !GLIB_COMPILATION */
704 #else /* !G_OS_WIN32 */
705 # define GUTILS_C_VAR extern
706 #endif /* !G_OS_WIN32 */
708 GUTILS_C_VAR const guint glib_major_version;
709 GUTILS_C_VAR const guint glib_minor_version;
710 GUTILS_C_VAR const guint glib_micro_version;
711 GUTILS_C_VAR const guint glib_interface_age;
712 GUTILS_C_VAR const guint glib_binary_age;
714 #define GLIB_CHECK_VERSION(major,minor,micro) \
715 (GLIB_MAJOR_VERSION > (major) || \
716 (GLIB_MAJOR_VERSION == (major) && GLIB_MINOR_VERSION > (minor)) || \
717 (GLIB_MAJOR_VERSION == (major) && GLIB_MINOR_VERSION == (minor) && \
718 GLIB_MICRO_VERSION >= (micro)))
720 /* Forward declarations of glib types.
722 typedef struct _GAllocator GAllocator;
723 typedef struct _GArray GArray;
724 typedef struct _GByteArray GByteArray;
725 typedef struct _GCache GCache;
726 typedef struct _GCompletion GCompletion;
727 typedef struct _GData GData;
728 typedef struct _GDebugKey GDebugKey;
729 typedef union _GDoubleIEEE754 GDoubleIEEE754;
730 typedef union _GFloatIEEE754 GFloatIEEE754;
731 typedef struct _GHashTable GHashTable;
732 typedef struct _GHook GHook;
733 typedef struct _GHookList GHookList;
734 typedef struct _GList GList;
735 typedef struct _GMemChunk GMemChunk;
736 typedef struct _GNode GNode;
737 typedef struct _GPtrArray GPtrArray;
738 typedef struct _GQueue GQueue;
739 typedef struct _GRand GRand;
740 typedef struct _GRelation GRelation;
741 typedef struct _GScanner GScanner;
742 typedef struct _GScannerConfig GScannerConfig;
743 typedef struct _GSList GSList;
744 typedef struct _GString GString;
745 typedef struct _GStringChunk GStringChunk;
746 typedef struct _GTimer GTimer;
747 typedef struct _GTrashStack GTrashStack;
748 typedef struct _GTree GTree;
749 typedef struct _GTuples GTuples;
750 typedef union _GTokenValue GTokenValue;
751 typedef struct _GIOChannel GIOChannel;
753 /* Tree traverse flags */
754 typedef enum
756 G_TRAVERSE_LEAFS = 1 << 0,
757 G_TRAVERSE_NON_LEAFS = 1 << 1,
758 G_TRAVERSE_ALL = G_TRAVERSE_LEAFS | G_TRAVERSE_NON_LEAFS,
759 G_TRAVERSE_MASK = 0x03
760 } GTraverseFlags;
762 /* Tree traverse orders */
763 typedef enum
765 G_IN_ORDER,
766 G_PRE_ORDER,
767 G_POST_ORDER,
768 G_LEVEL_ORDER
769 } GTraverseType;
771 /* Log level shift offset for user defined
772 * log levels (0-7 are used by GLib).
774 #define G_LOG_LEVEL_USER_SHIFT (8)
776 /* Glib log levels and flags.
778 typedef enum
780 /* log flags */
781 G_LOG_FLAG_RECURSION = 1 << 0,
782 G_LOG_FLAG_FATAL = 1 << 1,
784 /* GLib log levels */
785 G_LOG_LEVEL_ERROR = 1 << 2, /* always fatal */
786 G_LOG_LEVEL_CRITICAL = 1 << 3,
787 G_LOG_LEVEL_WARNING = 1 << 4,
788 G_LOG_LEVEL_MESSAGE = 1 << 5,
789 G_LOG_LEVEL_INFO = 1 << 6,
790 G_LOG_LEVEL_DEBUG = 1 << 7,
792 G_LOG_LEVEL_MASK = ~(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL)
793 } GLogLevelFlags;
795 /* GLib log levels that are considered fatal by default */
796 #define G_LOG_FATAL_MASK (G_LOG_FLAG_RECURSION | G_LOG_LEVEL_ERROR)
799 typedef gpointer (*GCacheNewFunc) (gpointer key);
800 typedef gpointer (*GCacheDupFunc) (gpointer value);
801 typedef void (*GCacheDestroyFunc) (gpointer value);
802 typedef gint (*GCompareFunc) (gconstpointer a,
803 gconstpointer b);
804 typedef gchar* (*GCompletionFunc) (gpointer);
805 typedef void (*GDestroyNotify) (gpointer data);
806 typedef void (*GDataForeachFunc) (GQuark key_id,
807 gpointer data,
808 gpointer user_data);
809 typedef void (*GFunc) (gpointer data,
810 gpointer user_data);
811 typedef guint (*GHashFunc) (gconstpointer key);
812 typedef void (*GFreeFunc) (gpointer data);
813 typedef void (*GHFunc) (gpointer key,
814 gpointer value,
815 gpointer user_data);
816 typedef gboolean (*GHRFunc) (gpointer key,
817 gpointer value,
818 gpointer user_data);
819 typedef gint (*GHookCompareFunc) (GHook *new_hook,
820 GHook *sibling);
821 typedef gboolean (*GHookFindFunc) (GHook *hook,
822 gpointer data);
823 typedef void (*GHookMarshaller) (GHook *hook,
824 gpointer data);
825 typedef gboolean (*GHookCheckMarshaller) (GHook *hook,
826 gpointer data);
827 typedef void (*GHookFunc) (gpointer data);
828 typedef gboolean (*GHookCheckFunc) (gpointer data);
829 typedef void (*GHookFreeFunc) (GHookList *hook_list,
830 GHook *hook);
831 typedef void (*GLogFunc) (const gchar *log_domain,
832 GLogLevelFlags log_level,
833 const gchar *message,
834 gpointer user_data);
835 typedef gboolean (*GNodeTraverseFunc) (GNode *node,
836 gpointer data);
837 typedef void (*GNodeForeachFunc) (GNode *node,
838 gpointer data);
839 typedef void (*GScannerMsgFunc) (GScanner *scanner,
840 gchar *message,
841 gint error);
842 typedef gint (*GTraverseFunc) (gpointer key,
843 gpointer value,
844 gpointer data);
845 typedef void (*GVoidFunc) (void);
848 struct _GArray
850 gchar *data;
851 guint len;
854 struct _GByteArray
856 guint8 *data;
857 guint len;
860 struct _GDebugKey
862 gchar *key;
863 guint value;
866 struct _GList
868 gpointer data;
869 GList *next;
870 GList *prev;
873 struct _GPtrArray
875 gpointer *pdata;
876 guint len;
879 struct _GQueue
881 GList *head;
882 GList *tail;
883 guint length;
886 struct _GSList
888 gpointer data;
889 GSList *next;
892 struct _GString
894 gchar *str;
895 gint len;
898 struct _GTrashStack
900 GTrashStack *next;
903 struct _GTuples
905 guint len;
909 /* IEEE Standard 754 Single Precision Storage Format (gfloat):
911 * 31 30 23 22 0
912 * +--------+---------------+---------------+
913 * | s 1bit | e[30:23] 8bit | f[22:0] 23bit |
914 * +--------+---------------+---------------+
915 * B0------------------->B1------->B2-->B3-->
917 * IEEE Standard 754 Double Precision Storage Format (gdouble):
919 * 63 62 52 51 32 31 0
920 * +--------+----------------+----------------+ +---------------+
921 * | s 1bit | e[62:52] 11bit | f[51:32] 20bit | | f[31:0] 32bit |
922 * +--------+----------------+----------------+ +---------------+
923 * B0--------------->B1---------->B2--->B3----> B4->B5->B6->B7->
925 /* subtract from biased_exponent to form base2 exponent (normal numbers) */
926 #define G_IEEE754_FLOAT_BIAS (127)
927 #define G_IEEE754_DOUBLE_BIAS (1023)
928 /* multiply with base2 exponent to get base10 exponent (nomal numbers) */
929 #define G_LOG_2_BASE_10 (0.30102999566398119521)
930 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
931 union _GFloatIEEE754
933 gfloat v_float;
934 struct {
935 guint mantissa : 23;
936 guint biased_exponent : 8;
937 guint sign : 1;
938 } mpn;
940 union _GDoubleIEEE754
942 gdouble v_double;
943 struct {
944 guint mantissa_low : 32;
945 guint mantissa_high : 20;
946 guint biased_exponent : 11;
947 guint sign : 1;
948 } mpn;
950 #elif G_BYTE_ORDER == G_BIG_ENDIAN
951 union _GFloatIEEE754
953 gfloat v_float;
954 struct {
955 guint sign : 1;
956 guint biased_exponent : 8;
957 guint mantissa : 23;
958 } mpn;
960 union _GDoubleIEEE754
962 gdouble v_double;
963 struct {
964 guint sign : 1;
965 guint biased_exponent : 11;
966 guint mantissa_high : 20;
967 guint mantissa_low : 32;
968 } mpn;
970 #else /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */
971 #error unknown ENDIAN type
972 #endif /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */
975 /* Doubly linked lists
977 void g_list_push_allocator (GAllocator *allocator);
978 void g_list_pop_allocator (void);
979 GList* g_list_alloc (void);
980 void g_list_free (GList *list);
981 void g_list_free_1 (GList *list);
982 GList* g_list_append (GList *list,
983 gpointer data);
984 GList* g_list_prepend (GList *list,
985 gpointer data);
986 GList* g_list_insert (GList *list,
987 gpointer data,
988 gint position);
989 GList* g_list_insert_sorted (GList *list,
990 gpointer data,
991 GCompareFunc func);
992 GList* g_list_concat (GList *list1,
993 GList *list2);
994 GList* g_list_remove (GList *list,
995 gconstpointer data);
996 GList* g_list_remove_link (GList *list,
997 GList *llink);
998 GList* g_list_delete_link (GList *list,
999 GList *link);
1000 GList* g_list_reverse (GList *list);
1001 GList* g_list_copy (GList *list);
1002 GList* g_list_nth (GList *list,
1003 guint n);
1004 GList* g_list_find (GList *list,
1005 gconstpointer data);
1006 GList* g_list_find_custom (GList *list,
1007 gconstpointer data,
1008 GCompareFunc func);
1009 gint g_list_position (GList *list,
1010 GList *llink);
1011 gint g_list_index (GList *list,
1012 gconstpointer data);
1013 GList* g_list_last (GList *list);
1014 GList* g_list_first (GList *list);
1015 guint g_list_length (GList *list);
1016 void g_list_foreach (GList *list,
1017 GFunc func,
1018 gpointer user_data);
1019 GList* g_list_sort (GList *list,
1020 GCompareFunc compare_func);
1021 gpointer g_list_nth_data (GList *list,
1022 guint n);
1023 #define g_list_previous(list) ((list) ? (((GList *)(list))->prev) : NULL)
1024 #define g_list_next(list) ((list) ? (((GList *)(list))->next) : NULL)
1027 /* Singly linked lists
1029 void g_slist_push_allocator (GAllocator *allocator);
1030 void g_slist_pop_allocator (void);
1031 GSList* g_slist_alloc (void);
1032 void g_slist_free (GSList *list);
1033 void g_slist_free_1 (GSList *list);
1034 GSList* g_slist_append (GSList *list,
1035 gpointer data);
1036 GSList* g_slist_prepend (GSList *list,
1037 gpointer data);
1038 GSList* g_slist_insert (GSList *list,
1039 gpointer data,
1040 gint position);
1041 GSList* g_slist_insert_sorted (GSList *list,
1042 gpointer data,
1043 GCompareFunc func);
1044 GSList* g_slist_insert_before (GSList *slist,
1045 GSList *sibling,
1046 gpointer data);
1047 GSList* g_slist_concat (GSList *list1,
1048 GSList *list2);
1049 GSList* g_slist_remove (GSList *list,
1050 gconstpointer data);
1051 GSList* g_slist_remove_link (GSList *list,
1052 GSList *link);
1053 GSList* g_slist_delete_link (GSList *list,
1054 GSList *link);
1055 GSList* g_slist_reverse (GSList *list);
1056 GSList* g_slist_copy (GSList *list);
1057 GSList* g_slist_nth (GSList *list,
1058 guint n);
1059 GSList* g_slist_find (GSList *list,
1060 gconstpointer data);
1061 GSList* g_slist_find_custom (GSList *list,
1062 gconstpointer data,
1063 GCompareFunc func);
1064 gint g_slist_position (GSList *list,
1065 GSList *llink);
1066 gint g_slist_index (GSList *list,
1067 gconstpointer data);
1068 GSList* g_slist_last (GSList *list);
1069 guint g_slist_length (GSList *list);
1070 void g_slist_foreach (GSList *list,
1071 GFunc func,
1072 gpointer user_data);
1073 GSList* g_slist_sort (GSList *list,
1074 GCompareFunc compare_func);
1075 gpointer g_slist_nth_data (GSList *list,
1076 guint n);
1077 #define g_slist_next(slist) ((slist) ? (((GSList *)(slist))->next) : NULL)
1080 /* Queues
1082 GQueue* g_queue_new (void);
1083 void g_queue_free (GQueue *queue);
1084 void g_queue_push_head (GQueue *queue,
1085 gpointer data);
1086 void g_queue_push_tail (GQueue *queue,
1087 gpointer data);
1088 gpointer g_queue_pop_head (GQueue *queue);
1089 gpointer g_queue_pop_tail (GQueue *queue);
1090 gboolean g_queue_is_empty (GQueue *queue);
1091 gpointer g_queue_peek_head (GQueue *queue);
1092 gpointer g_queue_peek_tail (GQueue *queue);
1093 void g_queue_push_head_link (GQueue *queue,
1094 GList *link);
1095 void g_queue_push_tail_link (GQueue *queue,
1096 GList *link);
1097 GList* g_queue_pop_head_link (GQueue *queue);
1098 GList* g_queue_pop_tail_link (GQueue *queue);
1100 /* Hash tables
1102 GHashTable* g_hash_table_new (GHashFunc hash_func,
1103 GCompareFunc key_compare_func);
1104 void g_hash_table_destroy (GHashTable *hash_table);
1105 void g_hash_table_insert (GHashTable *hash_table,
1106 gpointer key,
1107 gpointer value);
1108 void g_hash_table_remove (GHashTable *hash_table,
1109 gconstpointer key);
1110 gpointer g_hash_table_lookup (GHashTable *hash_table,
1111 gconstpointer key);
1112 gboolean g_hash_table_lookup_extended(GHashTable *hash_table,
1113 gconstpointer lookup_key,
1114 gpointer *orig_key,
1115 gpointer *value);
1116 void g_hash_table_freeze (GHashTable *hash_table);
1117 void g_hash_table_thaw (GHashTable *hash_table);
1118 void g_hash_table_foreach (GHashTable *hash_table,
1119 GHFunc func,
1120 gpointer user_data);
1121 guint g_hash_table_foreach_remove (GHashTable *hash_table,
1122 GHRFunc func,
1123 gpointer user_data);
1124 guint g_hash_table_size (GHashTable *hash_table);
1127 /* Caches
1129 GCache* g_cache_new (GCacheNewFunc value_new_func,
1130 GCacheDestroyFunc value_destroy_func,
1131 GCacheDupFunc key_dup_func,
1132 GCacheDestroyFunc key_destroy_func,
1133 GHashFunc hash_key_func,
1134 GHashFunc hash_value_func,
1135 GCompareFunc key_compare_func);
1136 void g_cache_destroy (GCache *cache);
1137 gpointer g_cache_insert (GCache *cache,
1138 gpointer key);
1139 void g_cache_remove (GCache *cache,
1140 gconstpointer value);
1141 void g_cache_key_foreach (GCache *cache,
1142 GHFunc func,
1143 gpointer user_data);
1144 void g_cache_value_foreach (GCache *cache,
1145 GHFunc func,
1146 gpointer user_data);
1149 /* Balanced binary trees
1151 GTree* g_tree_new (GCompareFunc key_compare_func);
1152 void g_tree_destroy (GTree *tree);
1153 void g_tree_insert (GTree *tree,
1154 gpointer key,
1155 gpointer value);
1156 void g_tree_remove (GTree *tree,
1157 gconstpointer key);
1158 gpointer g_tree_lookup (GTree *tree,
1159 gconstpointer key);
1160 void g_tree_traverse (GTree *tree,
1161 GTraverseFunc traverse_func,
1162 GTraverseType traverse_type,
1163 gpointer data);
1164 gpointer g_tree_search (GTree *tree,
1165 GCompareFunc search_func,
1166 gconstpointer data);
1167 gint g_tree_height (GTree *tree);
1168 gint g_tree_nnodes (GTree *tree);
1172 /* N-way tree implementation
1174 struct _GNode
1176 gpointer data;
1177 GNode *next;
1178 GNode *prev;
1179 GNode *parent;
1180 GNode *children;
1183 #define G_NODE_IS_ROOT(node) (((GNode*) (node))->parent == NULL && \
1184 ((GNode*) (node))->prev == NULL && \
1185 ((GNode*) (node))->next == NULL)
1186 #define G_NODE_IS_LEAF(node) (((GNode*) (node))->children == NULL)
1188 void g_node_push_allocator (GAllocator *allocator);
1189 void g_node_pop_allocator (void);
1190 GNode* g_node_new (gpointer data);
1191 void g_node_destroy (GNode *root);
1192 void g_node_unlink (GNode *node);
1193 GNode* g_node_copy (GNode *node);
1194 GNode* g_node_insert (GNode *parent,
1195 gint position,
1196 GNode *node);
1197 GNode* g_node_insert_before (GNode *parent,
1198 GNode *sibling,
1199 GNode *node);
1200 GNode* g_node_prepend (GNode *parent,
1201 GNode *node);
1202 guint g_node_n_nodes (GNode *root,
1203 GTraverseFlags flags);
1204 GNode* g_node_get_root (GNode *node);
1205 gboolean g_node_is_ancestor (GNode *node,
1206 GNode *descendant);
1207 guint g_node_depth (GNode *node);
1208 GNode* g_node_find (GNode *root,
1209 GTraverseType order,
1210 GTraverseFlags flags,
1211 gpointer data);
1213 /* convenience macros */
1214 #define g_node_append(parent, node) \
1215 g_node_insert_before ((parent), NULL, (node))
1216 #define g_node_insert_data(parent, position, data) \
1217 g_node_insert ((parent), (position), g_node_new (data))
1218 #define g_node_insert_data_before(parent, sibling, data) \
1219 g_node_insert_before ((parent), (sibling), g_node_new (data))
1220 #define g_node_prepend_data(parent, data) \
1221 g_node_prepend ((parent), g_node_new (data))
1222 #define g_node_append_data(parent, data) \
1223 g_node_insert_before ((parent), NULL, g_node_new (data))
1225 /* traversal function, assumes that `node' is root
1226 * (only traverses `node' and its subtree).
1227 * this function is just a high level interface to
1228 * low level traversal functions, optimized for speed.
1230 void g_node_traverse (GNode *root,
1231 GTraverseType order,
1232 GTraverseFlags flags,
1233 gint max_depth,
1234 GNodeTraverseFunc func,
1235 gpointer data);
1237 /* return the maximum tree height starting with `node', this is an expensive
1238 * operation, since we need to visit all nodes. this could be shortened by
1239 * adding `guint height' to struct _GNode, but then again, this is not very
1240 * often needed, and would make g_node_insert() more time consuming.
1242 guint g_node_max_height (GNode *root);
1244 void g_node_children_foreach (GNode *node,
1245 GTraverseFlags flags,
1246 GNodeForeachFunc func,
1247 gpointer data);
1248 void g_node_reverse_children (GNode *node);
1249 guint g_node_n_children (GNode *node);
1250 GNode* g_node_nth_child (GNode *node,
1251 guint n);
1252 GNode* g_node_last_child (GNode *node);
1253 GNode* g_node_find_child (GNode *node,
1254 GTraverseFlags flags,
1255 gpointer data);
1256 gint g_node_child_position (GNode *node,
1257 GNode *child);
1258 gint g_node_child_index (GNode *node,
1259 gpointer data);
1261 GNode* g_node_first_sibling (GNode *node);
1262 GNode* g_node_last_sibling (GNode *node);
1264 #define g_node_prev_sibling(node) ((node) ? \
1265 ((GNode*) (node))->prev : NULL)
1266 #define g_node_next_sibling(node) ((node) ? \
1267 ((GNode*) (node))->next : NULL)
1268 #define g_node_first_child(node) ((node) ? \
1269 ((GNode*) (node))->children : NULL)
1272 /* Callback maintenance functions
1274 #define G_HOOK_FLAG_USER_SHIFT (4)
1275 typedef enum
1277 G_HOOK_FLAG_ACTIVE = 1 << 0,
1278 G_HOOK_FLAG_IN_CALL = 1 << 1,
1279 G_HOOK_FLAG_MASK = 0x0f
1280 } GHookFlagMask;
1282 #define G_HOOK_DEFERRED_DESTROY ((GHookFreeFunc) 0x01)
1284 struct _GHookList
1286 guint seq_id;
1287 guint hook_size;
1288 guint is_setup : 1;
1289 GHook *hooks;
1290 GMemChunk *hook_memchunk;
1291 GHookFreeFunc hook_free; /* virtual function */
1292 GHookFreeFunc hook_destroy; /* virtual function */
1295 struct _GHook
1297 gpointer data;
1298 GHook *next;
1299 GHook *prev;
1300 guint ref_count;
1301 guint hook_id;
1302 guint flags;
1303 gpointer func;
1304 GDestroyNotify destroy;
1307 #define G_HOOK_ACTIVE(hook) ((((GHook*) hook)->flags & \
1308 G_HOOK_FLAG_ACTIVE) != 0)
1309 #define G_HOOK_IN_CALL(hook) ((((GHook*) hook)->flags & \
1310 G_HOOK_FLAG_IN_CALL) != 0)
1311 #define G_HOOK_IS_VALID(hook) (((GHook*) hook)->hook_id != 0 && \
1312 G_HOOK_ACTIVE (hook))
1313 #define G_HOOK_IS_UNLINKED(hook) (((GHook*) hook)->next == NULL && \
1314 ((GHook*) hook)->prev == NULL && \
1315 ((GHook*) hook)->hook_id == 0 && \
1316 ((GHook*) hook)->ref_count == 0)
1318 void g_hook_list_init (GHookList *hook_list,
1319 guint hook_size);
1320 void g_hook_list_clear (GHookList *hook_list);
1321 GHook* g_hook_alloc (GHookList *hook_list);
1322 void g_hook_free (GHookList *hook_list,
1323 GHook *hook);
1324 void g_hook_ref (GHookList *hook_list,
1325 GHook *hook);
1326 void g_hook_unref (GHookList *hook_list,
1327 GHook *hook);
1328 gboolean g_hook_destroy (GHookList *hook_list,
1329 guint hook_id);
1330 void g_hook_destroy_link (GHookList *hook_list,
1331 GHook *hook);
1332 void g_hook_prepend (GHookList *hook_list,
1333 GHook *hook);
1334 void g_hook_insert_before (GHookList *hook_list,
1335 GHook *sibling,
1336 GHook *hook);
1337 void g_hook_insert_sorted (GHookList *hook_list,
1338 GHook *hook,
1339 GHookCompareFunc func);
1340 GHook* g_hook_get (GHookList *hook_list,
1341 guint hook_id);
1342 GHook* g_hook_find (GHookList *hook_list,
1343 gboolean need_valids,
1344 GHookFindFunc func,
1345 gpointer data);
1346 GHook* g_hook_find_data (GHookList *hook_list,
1347 gboolean need_valids,
1348 gpointer data);
1349 GHook* g_hook_find_func (GHookList *hook_list,
1350 gboolean need_valids,
1351 gpointer func);
1352 GHook* g_hook_find_func_data (GHookList *hook_list,
1353 gboolean need_valids,
1354 gpointer func,
1355 gpointer data);
1356 /* return the first valid hook, and increment its reference count */
1357 GHook* g_hook_first_valid (GHookList *hook_list,
1358 gboolean may_be_in_call);
1359 /* return the next valid hook with incremented reference count, and
1360 * decrement the reference count of the original hook
1362 GHook* g_hook_next_valid (GHookList *hook_list,
1363 GHook *hook,
1364 gboolean may_be_in_call);
1366 /* GHookCompareFunc implementation to insert hooks sorted by their id */
1367 gint g_hook_compare_ids (GHook *new_hook,
1368 GHook *sibling);
1370 /* convenience macros */
1371 #define g_hook_append( hook_list, hook ) \
1372 g_hook_insert_before ((hook_list), NULL, (hook))
1374 /* invoke all valid hooks with the (*GHookFunc) signature.
1376 void g_hook_list_invoke (GHookList *hook_list,
1377 gboolean may_recurse);
1378 /* invoke all valid hooks with the (*GHookCheckFunc) signature,
1379 * and destroy the hook if FALSE is returned.
1381 void g_hook_list_invoke_check (GHookList *hook_list,
1382 gboolean may_recurse);
1383 /* invoke a marshaller on all valid hooks.
1385 void g_hook_list_marshal (GHookList *hook_list,
1386 gboolean may_recurse,
1387 GHookMarshaller marshaller,
1388 gpointer data);
1389 void g_hook_list_marshal_check (GHookList *hook_list,
1390 gboolean may_recurse,
1391 GHookCheckMarshaller marshaller,
1392 gpointer data);
1395 /* Fatal error handlers.
1396 * g_on_error_query() will prompt the user to either
1397 * [E]xit, [H]alt, [P]roceed or show [S]tack trace.
1398 * g_on_error_stack_trace() invokes gdb, which attaches to the current
1399 * process and shows a stack trace.
1400 * These function may cause different actions on non-unix platforms.
1401 * The prg_name arg is required by gdb to find the executable, if it is
1402 * passed as NULL, g_on_error_query() will try g_get_prgname().
1404 void g_on_error_query (const gchar *prg_name);
1405 void g_on_error_stack_trace (const gchar *prg_name);
1408 /* Logging mechanism
1410 extern const gchar *g_log_domain_glib;
1411 guint g_log_set_handler (const gchar *log_domain,
1412 GLogLevelFlags log_levels,
1413 GLogFunc log_func,
1414 gpointer user_data);
1415 void g_log_remove_handler (const gchar *log_domain,
1416 guint handler_id);
1417 void g_log_default_handler (const gchar *log_domain,
1418 GLogLevelFlags log_level,
1419 const gchar *message,
1420 gpointer unused_data);
1421 void g_log (const gchar *log_domain,
1422 GLogLevelFlags log_level,
1423 const gchar *format,
1424 ...) G_GNUC_PRINTF (3, 4);
1425 void g_logv (const gchar *log_domain,
1426 GLogLevelFlags log_level,
1427 const gchar *format,
1428 va_list args);
1429 GLogLevelFlags g_log_set_fatal_mask (const gchar *log_domain,
1430 GLogLevelFlags fatal_mask);
1431 GLogLevelFlags g_log_set_always_fatal (GLogLevelFlags fatal_mask);
1432 #ifndef G_LOG_DOMAIN
1433 #define G_LOG_DOMAIN ((gchar*) 0)
1434 #endif /* G_LOG_DOMAIN */
1435 #ifdef __GNUC__
1436 #define g_error(format, args...) g_log (G_LOG_DOMAIN, \
1437 G_LOG_LEVEL_ERROR, \
1438 format, ##args)
1439 #define g_message(format, args...) g_log (G_LOG_DOMAIN, \
1440 G_LOG_LEVEL_MESSAGE, \
1441 format, ##args)
1442 #define g_warning(format, args...) g_log (G_LOG_DOMAIN, \
1443 G_LOG_LEVEL_WARNING, \
1444 format, ##args)
1445 #else /* !__GNUC__ */
1446 static void
1447 g_error (const gchar *format,
1448 ...)
1450 va_list args;
1451 va_start (args, format);
1452 g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR, format, args);
1453 va_end (args);
1455 static void
1456 g_message (const gchar *format,
1457 ...)
1459 va_list args;
1460 va_start (args, format);
1461 g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, format, args);
1462 va_end (args);
1464 static void
1465 g_warning (const gchar *format,
1466 ...)
1468 va_list args;
1469 va_start (args, format);
1470 g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, format, args);
1471 va_end (args);
1473 #endif /* !__GNUC__ */
1475 typedef void (*GPrintFunc) (const gchar *string);
1476 void g_print (const gchar *format,
1477 ...) G_GNUC_PRINTF (1, 2);
1478 GPrintFunc g_set_print_handler (GPrintFunc func);
1479 void g_printerr (const gchar *format,
1480 ...) G_GNUC_PRINTF (1, 2);
1481 GPrintFunc g_set_printerr_handler (GPrintFunc func);
1483 /* deprecated compatibility functions, use g_log_set_handler() instead */
1484 typedef void (*GErrorFunc) (const gchar *str);
1485 typedef void (*GWarningFunc) (const gchar *str);
1486 GErrorFunc g_set_error_handler (GErrorFunc func);
1487 GWarningFunc g_set_warning_handler (GWarningFunc func);
1488 GPrintFunc g_set_message_handler (GPrintFunc func);
1491 /* Memory allocation and debugging
1493 #ifdef USE_DMALLOC
1495 #define g_malloc(size) ((gpointer) MALLOC (size))
1496 #define g_malloc0(size) ((gpointer) CALLOC (char, size))
1497 #define g_realloc(mem,size) ((gpointer) REALLOC (mem, char, size))
1498 #define g_free(mem) FREE (mem)
1500 #else /* !USE_DMALLOC */
1502 gpointer g_malloc (gulong size);
1503 gpointer g_malloc0 (gulong size);
1504 gpointer g_realloc (gpointer mem,
1505 gulong size);
1506 void g_free (gpointer mem);
1508 #endif /* !USE_DMALLOC */
1510 void g_mem_profile (void);
1511 void g_mem_check (gpointer mem);
1513 /* Generic allocators
1515 GAllocator* g_allocator_new (const gchar *name,
1516 guint n_preallocs);
1517 void g_allocator_free (GAllocator *allocator);
1519 #define G_ALLOCATOR_LIST (1)
1520 #define G_ALLOCATOR_SLIST (2)
1521 #define G_ALLOCATOR_NODE (3)
1524 /* "g_mem_chunk_new" creates a new memory chunk.
1525 * Memory chunks are used to allocate pieces of memory which are
1526 * always the same size. Lists are a good example of such a data type.
1527 * The memory chunk allocates and frees blocks of memory as needed.
1528 * Just be sure to call "g_mem_chunk_free" and not "g_free" on data
1529 * allocated in a mem chunk. ("g_free" will most likely cause a seg
1530 * fault...somewhere).
1532 * Oh yeah, GMemChunk is an opaque data type. (You don't really
1533 * want to know what's going on inside do you?)
1536 /* ALLOC_ONLY MemChunk's can only allocate memory. The free operation
1537 * is interpreted as a no op. ALLOC_ONLY MemChunk's save 4 bytes per
1538 * atom. (They are also useful for lists which use MemChunk to allocate
1539 * memory but are also part of the MemChunk implementation).
1540 * ALLOC_AND_FREE MemChunk's can allocate and free memory.
1543 #define G_ALLOC_ONLY 1
1544 #define G_ALLOC_AND_FREE 2
1546 GMemChunk* g_mem_chunk_new (gchar *name,
1547 gint atom_size,
1548 gulong area_size,
1549 gint type);
1550 void g_mem_chunk_destroy (GMemChunk *mem_chunk);
1551 gpointer g_mem_chunk_alloc (GMemChunk *mem_chunk);
1552 gpointer g_mem_chunk_alloc0 (GMemChunk *mem_chunk);
1553 void g_mem_chunk_free (GMemChunk *mem_chunk,
1554 gpointer mem);
1555 void g_mem_chunk_clean (GMemChunk *mem_chunk);
1556 void g_mem_chunk_reset (GMemChunk *mem_chunk);
1557 void g_mem_chunk_print (GMemChunk *mem_chunk);
1558 void g_mem_chunk_info (void);
1560 /* Ah yes...we have a "g_blow_chunks" function.
1561 * "g_blow_chunks" simply compresses all the chunks. This operation
1562 * consists of freeing every memory area that should be freed (but
1563 * which we haven't gotten around to doing yet). And, no,
1564 * "g_blow_chunks" doesn't follow the naming scheme, but it is a
1565 * much better name than "g_mem_chunk_clean_all" or something
1566 * similar.
1568 void g_blow_chunks (void);
1571 /* Timer
1574 #define G_MICROSEC 1000000
1576 GTimer* g_timer_new (void);
1577 void g_timer_destroy (GTimer *timer);
1578 void g_timer_start (GTimer *timer);
1579 void g_timer_stop (GTimer *timer);
1580 void g_timer_reset (GTimer *timer);
1581 gdouble g_timer_elapsed (GTimer *timer,
1582 gulong *microseconds);
1583 void g_usleep (gulong microseconds);
1585 /* String utility functions that modify a string argument or
1586 * return a constant string that must not be freed.
1588 #define G_STR_DELIMITERS "_-|> <."
1589 gchar* g_strdelimit (gchar *string,
1590 const gchar *delimiters,
1591 gchar new_delimiter);
1592 gchar* g_strcanon (gchar *string,
1593 const gchar *valid_chars,
1594 gchar subsitutor);
1595 gdouble g_strtod (const gchar *nptr,
1596 gchar **endptr);
1597 gchar* g_strerror (gint errnum);
1598 gchar* g_strsignal (gint signum);
1599 gint g_strcasecmp (const gchar *s1,
1600 const gchar *s2);
1601 gint g_strncasecmp (const gchar *s1,
1602 const gchar *s2,
1603 guint n);
1604 gchar* g_strdown (gchar *string);
1605 gchar* g_strup (gchar *string);
1606 gchar* g_strreverse (gchar *string);
1607 /* removes leading spaces */
1608 gchar* g_strchug (gchar *string);
1609 /* removes trailing spaces */
1610 gchar* g_strchomp (gchar *string);
1611 /* removes leading & trailing spaces */
1612 #define g_strstrip( string ) g_strchomp (g_strchug (string))
1614 /* String utility functions that return a newly allocated string which
1615 * ought to be freed with g_free from the caller at some point.
1617 gchar* g_strdup (const gchar *str);
1618 gchar* g_strdup_printf (const gchar *format,
1619 ...) G_GNUC_PRINTF (1, 2);
1620 gchar* g_strdup_vprintf (const gchar *format,
1621 va_list args);
1622 gchar* g_strndup (const gchar *str,
1623 guint n);
1624 gchar* g_strnfill (guint length,
1625 gchar fill_char);
1626 gchar* g_strconcat (const gchar *string1,
1627 ...); /* NULL terminated */
1628 gchar* g_strjoin (const gchar *separator,
1629 ...); /* NULL terminated */
1630 /* Make a copy of a string interpreting C string -style escape
1631 * sequences. Inverse of g_strescape. The recognized sequences are \b
1632 * \f \n \r \t \\ \" and the octal format.
1634 gchar* g_strcompress (const gchar *source);
1636 /* Convert between the operating system (or C runtime)
1637 * representation of file names and UTF-8.
1639 gchar* g_filename_to_utf8 (const gchar *opsysstring);
1640 gchar* g_filename_from_utf8 (const gchar *utf8string);
1642 /* Copy a string escaping nonprintable characters like in C strings.
1643 * Inverse of g_strcompress. The exceptions parameter, if non-NULL, points
1644 * to a string containing characters that are not to be escaped.
1646 * Deprecated API: gchar* g_strescape (const gchar *source);
1647 * Luckily this function wasn't used much, using NULL as second parameter
1648 * provides mostly identical semantics.
1650 gchar* g_strescape (const gchar *source,
1651 const gchar *exceptions);
1653 gpointer g_memdup (gconstpointer mem,
1654 guint byte_size);
1656 /* NULL terminated string arrays.
1657 * g_strsplit() splits up string into max_tokens tokens at delim and
1658 * returns a newly allocated string array.
1659 * g_strjoinv() concatenates all of str_array's strings, sliding in an
1660 * optional separator, the returned string is newly allocated.
1661 * g_strfreev() frees the array itself and all of its strings.
1663 gchar** g_strsplit (const gchar *string,
1664 const gchar *delimiter,
1665 gint max_tokens);
1666 gchar* g_strjoinv (const gchar *separator,
1667 gchar **str_array);
1668 void g_strfreev (gchar **str_array);
1672 /* calculate a string size, guarranteed to fit format + args.
1674 guint g_printf_string_upper_bound (const gchar* format,
1675 va_list args);
1678 /* Retrive static string info
1680 gchar* g_get_user_name (void);
1681 gchar* g_get_real_name (void);
1682 gchar* g_get_home_dir (void);
1683 gchar* g_get_tmp_dir (void);
1684 gchar* g_get_prgname (void);
1685 void g_set_prgname (const gchar *prgname);
1688 /* Miscellaneous utility functions
1690 guint g_parse_debug_string (const gchar *string,
1691 GDebugKey *keys,
1692 guint nkeys);
1693 gint g_snprintf (gchar *string,
1694 gulong n,
1695 gchar const *format,
1696 ...) G_GNUC_PRINTF (3, 4);
1697 gint g_vsnprintf (gchar *string,
1698 gulong n,
1699 gchar const *format,
1700 va_list args);
1701 gchar* g_basename (const gchar *file_name);
1702 /* Check if a file name is an absolute path */
1703 gboolean g_path_is_absolute (const gchar *file_name);
1704 /* In case of absolute paths, skip the root part */
1705 gchar* g_path_skip_root (gchar *file_name);
1707 /* strings are newly allocated with g_malloc() */
1708 gchar* g_dirname (const gchar *file_name);
1709 gchar* g_get_current_dir (void);
1711 /* return the environment string for the variable. The returned memory
1712 * must not be freed. */
1713 gchar* g_getenv (const gchar *variable);
1715 gchar * g_locale_get_codeset (void);
1717 /* we use a GLib function as a replacement for ATEXIT, so
1718 * the programmer is not required to check the return value
1719 * (if there is any in the implementation) and doesn't encounter
1720 * missing include files.
1722 void g_atexit (GVoidFunc func);
1725 /* Bit tests
1727 G_INLINE_FUNC gint g_bit_nth_lsf (guint32 mask,
1728 gint nth_bit);
1729 #ifdef G_CAN_INLINE
1730 G_INLINE_FUNC gint
1731 g_bit_nth_lsf (guint32 mask,
1732 gint nth_bit)
1736 nth_bit++;
1737 if (mask & (1 << (guint) nth_bit))
1738 return nth_bit;
1740 while (nth_bit < 32);
1741 return -1;
1743 #endif /* G_CAN_INLINE */
1745 G_INLINE_FUNC gint g_bit_nth_msf (guint32 mask,
1746 gint nth_bit);
1747 #ifdef G_CAN_INLINE
1748 G_INLINE_FUNC gint
1749 g_bit_nth_msf (guint32 mask,
1750 gint nth_bit)
1752 if (nth_bit < 0)
1753 nth_bit = 32;
1756 nth_bit--;
1757 if (mask & (1 << (guint) nth_bit))
1758 return nth_bit;
1760 while (nth_bit > 0);
1761 return -1;
1763 #endif /* G_CAN_INLINE */
1765 G_INLINE_FUNC guint g_bit_storage (guint number);
1766 #ifdef G_CAN_INLINE
1767 G_INLINE_FUNC guint
1768 g_bit_storage (guint number)
1770 register guint n_bits = 0;
1774 n_bits++;
1775 number >>= 1;
1777 while (number);
1778 return n_bits;
1780 #endif /* G_CAN_INLINE */
1783 /* Trash Stacks
1784 * elements need to be >= sizeof (gpointer)
1786 G_INLINE_FUNC void g_trash_stack_push (GTrashStack **stack_p,
1787 gpointer data_p);
1788 #ifdef G_CAN_INLINE
1789 G_INLINE_FUNC void
1790 g_trash_stack_push (GTrashStack **stack_p,
1791 gpointer data_p)
1793 GTrashStack *data = (GTrashStack *) data_p;
1795 data->next = *stack_p;
1796 *stack_p = data;
1798 #endif /* G_CAN_INLINE */
1800 G_INLINE_FUNC gpointer g_trash_stack_pop (GTrashStack **stack_p);
1801 #ifdef G_CAN_INLINE
1802 G_INLINE_FUNC gpointer
1803 g_trash_stack_pop (GTrashStack **stack_p)
1805 GTrashStack *data;
1807 data = *stack_p;
1808 if (data)
1810 *stack_p = data->next;
1811 /* NULLify private pointer here, most platforms store NULL as
1812 * subsequent 0 bytes
1814 data->next = NULL;
1817 return data;
1819 #endif /* G_CAN_INLINE */
1821 G_INLINE_FUNC gpointer g_trash_stack_peek (GTrashStack **stack_p);
1822 #ifdef G_CAN_INLINE
1823 G_INLINE_FUNC gpointer
1824 g_trash_stack_peek (GTrashStack **stack_p)
1826 GTrashStack *data;
1828 data = *stack_p;
1830 return data;
1832 #endif /* G_CAN_INLINE */
1834 G_INLINE_FUNC guint g_trash_stack_height (GTrashStack **stack_p);
1835 #ifdef G_CAN_INLINE
1836 G_INLINE_FUNC guint
1837 g_trash_stack_height (GTrashStack **stack_p)
1839 GTrashStack *data;
1840 guint i = 0;
1842 for (data = *stack_p; data; data = data->next)
1843 i++;
1845 return i;
1847 #endif /* G_CAN_INLINE */
1850 /* String Chunks
1852 GStringChunk* g_string_chunk_new (gint size);
1853 void g_string_chunk_free (GStringChunk *chunk);
1854 gchar* g_string_chunk_insert (GStringChunk *chunk,
1855 const gchar *string);
1856 gchar* g_string_chunk_insert_const (GStringChunk *chunk,
1857 const gchar *string);
1860 /* Strings
1862 GString* g_string_new (const gchar *init);
1863 GString* g_string_sized_new (guint dfl_size);
1864 void g_string_free (GString *string,
1865 gboolean free_segment);
1866 GString* g_string_assign (GString *string,
1867 const gchar *rval);
1868 GString* g_string_truncate (GString *string,
1869 guint len);
1870 GString* g_string_insert_len (GString *string,
1871 gint pos,
1872 const gchar *val,
1873 gint len);
1874 GString* g_string_append (GString *string,
1875 const gchar *val);
1876 GString* g_string_append_len (GString *string,
1877 const gchar *val,
1878 gint len);
1879 GString* g_string_append_c (GString *string,
1880 gchar c);
1881 GString* g_string_prepend (GString *string,
1882 const gchar *val);
1883 GString* g_string_prepend_c (GString *string,
1884 gchar c);
1885 GString* g_string_prepend_len (GString *string,
1886 const gchar *val,
1887 gint len);
1888 GString* g_string_insert (GString *string,
1889 gint pos,
1890 const gchar *val);
1891 GString* g_string_insert_c (GString *string,
1892 gint pos,
1893 gchar c);
1894 GString* g_string_erase (GString *string,
1895 gint pos,
1896 gint len);
1897 GString* g_string_down (GString *string);
1898 GString* g_string_up (GString *string);
1899 void g_string_sprintf (GString *string,
1900 const gchar *format,
1901 ...) G_GNUC_PRINTF (2, 3);
1902 void g_string_sprintfa (GString *string,
1903 const gchar *format,
1904 ...) G_GNUC_PRINTF (2, 3);
1907 /* Resizable arrays, remove fills any cleared spot and shortens the
1908 * array, while preserving the order. remove_fast will distort the
1909 * order by moving the last element to the position of the removed
1912 #define g_array_append_val(a,v) g_array_append_vals (a, &v, 1)
1913 #define g_array_prepend_val(a,v) g_array_prepend_vals (a, &v, 1)
1914 #define g_array_insert_val(a,i,v) g_array_insert_vals (a, i, &v, 1)
1915 #define g_array_index(a,t,i) (((t*) (a)->data) [(i)])
1917 GArray* g_array_new (gboolean zero_terminated,
1918 gboolean clear,
1919 guint element_size);
1920 GArray* g_array_sized_new (gboolean zero_terminated,
1921 gboolean clear,
1922 guint element_size,
1923 guint reserved_size);
1924 void g_array_free (GArray *array,
1925 gboolean free_segment);
1926 GArray* g_array_append_vals (GArray *array,
1927 gconstpointer data,
1928 guint len);
1929 GArray* g_array_prepend_vals (GArray *array,
1930 gconstpointer data,
1931 guint len);
1932 GArray* g_array_insert_vals (GArray *array,
1933 guint index,
1934 gconstpointer data,
1935 guint len);
1936 GArray* g_array_set_size (GArray *array,
1937 guint length);
1938 GArray* g_array_remove_index (GArray *array,
1939 guint index);
1940 GArray* g_array_remove_index_fast (GArray *array,
1941 guint index);
1943 /* Resizable pointer array. This interface is much less complicated
1944 * than the above. Add appends appends a pointer. Remove fills any
1945 * cleared spot and shortens the array. remove_fast will again distort
1946 * order.
1948 #define g_ptr_array_index(array,index) (array->pdata)[index]
1949 GPtrArray* g_ptr_array_new (void);
1950 GPtrArray* g_ptr_array_sized_new (guint reserved_size);
1951 void g_ptr_array_free (GPtrArray *array,
1952 gboolean free_seg);
1953 void g_ptr_array_set_size (GPtrArray *array,
1954 gint length);
1955 gpointer g_ptr_array_remove_index (GPtrArray *array,
1956 guint index);
1957 gpointer g_ptr_array_remove_index_fast (GPtrArray *array,
1958 guint index);
1959 gboolean g_ptr_array_remove (GPtrArray *array,
1960 gpointer data);
1961 gboolean g_ptr_array_remove_fast (GPtrArray *array,
1962 gpointer data);
1963 void g_ptr_array_add (GPtrArray *array,
1964 gpointer data);
1966 /* Byte arrays, an array of guint8. Implemented as a GArray,
1967 * but type-safe.
1970 GByteArray* g_byte_array_new (void);
1971 GByteArray* g_byte_array_sized_new (guint reserved_size);
1972 void g_byte_array_free (GByteArray *array,
1973 gboolean free_segment);
1974 GByteArray* g_byte_array_append (GByteArray *array,
1975 const guint8 *data,
1976 guint len);
1977 GByteArray* g_byte_array_prepend (GByteArray *array,
1978 const guint8 *data,
1979 guint len);
1980 GByteArray* g_byte_array_set_size (GByteArray *array,
1981 guint length);
1982 GByteArray* g_byte_array_remove_index (GByteArray *array,
1983 guint index);
1984 GByteArray* g_byte_array_remove_index_fast (GByteArray *array,
1985 guint index);
1988 /* Hash Functions
1990 gint g_str_equal (gconstpointer v,
1991 gconstpointer v2);
1992 guint g_str_hash (gconstpointer v);
1994 gint g_int_equal (gconstpointer v,
1995 gconstpointer v2);
1996 guint g_int_hash (gconstpointer v);
1998 /* This "hash" function will just return the key's adress as an
1999 * unsigned integer. Useful for hashing on plain adresses or
2000 * simple integer values.
2001 * passing NULL into g_hash_table_new() as GHashFunc has the
2002 * same effect as passing g_direct_hash().
2004 guint g_direct_hash (gconstpointer v);
2005 gint g_direct_equal (gconstpointer v,
2006 gconstpointer v2);
2009 /* Quarks (string<->id association)
2011 GQuark g_quark_try_string (const gchar *string);
2012 GQuark g_quark_from_static_string (const gchar *string);
2013 GQuark g_quark_from_string (const gchar *string);
2014 gchar* g_quark_to_string (GQuark quark);
2017 /* Keyed Data List
2019 void g_datalist_init (GData **datalist);
2020 void g_datalist_clear (GData **datalist);
2021 gpointer g_datalist_id_get_data (GData **datalist,
2022 GQuark key_id);
2023 void g_datalist_id_set_data_full (GData **datalist,
2024 GQuark key_id,
2025 gpointer data,
2026 GDestroyNotify destroy_func);
2027 gpointer g_datalist_id_remove_no_notify (GData **datalist,
2028 GQuark key_id);
2029 void g_datalist_foreach (GData **datalist,
2030 GDataForeachFunc func,
2031 gpointer user_data);
2032 #define g_datalist_id_set_data(dl, q, d) \
2033 g_datalist_id_set_data_full ((dl), (q), (d), NULL)
2034 #define g_datalist_id_remove_data(dl, q) \
2035 g_datalist_id_set_data ((dl), (q), NULL)
2036 #define g_datalist_get_data(dl, k) \
2037 (g_datalist_id_get_data ((dl), g_quark_try_string (k)))
2038 #define g_datalist_set_data_full(dl, k, d, f) \
2039 g_datalist_id_set_data_full ((dl), g_quark_from_string (k), (d), (f))
2040 #define g_datalist_remove_no_notify(dl, k) \
2041 g_datalist_id_remove_no_notify ((dl), g_quark_try_string (k))
2042 #define g_datalist_set_data(dl, k, d) \
2043 g_datalist_set_data_full ((dl), (k), (d), NULL)
2044 #define g_datalist_remove_data(dl, k) \
2045 g_datalist_id_set_data ((dl), g_quark_try_string (k), NULL)
2048 /* Location Associated Keyed Data
2050 void g_dataset_destroy (gconstpointer dataset_location);
2051 gpointer g_dataset_id_get_data (gconstpointer dataset_location,
2052 GQuark key_id);
2053 void g_dataset_id_set_data_full (gconstpointer dataset_location,
2054 GQuark key_id,
2055 gpointer data,
2056 GDestroyNotify destroy_func);
2057 gpointer g_dataset_id_remove_no_notify (gconstpointer dataset_location,
2058 GQuark key_id);
2059 void g_dataset_foreach (gconstpointer dataset_location,
2060 GDataForeachFunc func,
2061 gpointer user_data);
2062 #define g_dataset_id_set_data(l, k, d) \
2063 g_dataset_id_set_data_full ((l), (k), (d), NULL)
2064 #define g_dataset_id_remove_data(l, k) \
2065 g_dataset_id_set_data ((l), (k), NULL)
2066 #define g_dataset_get_data(l, k) \
2067 (g_dataset_id_get_data ((l), g_quark_try_string (k)))
2068 #define g_dataset_set_data_full(l, k, d, f) \
2069 g_dataset_id_set_data_full ((l), g_quark_from_string (k), (d), (f))
2070 #define g_dataset_remove_no_notify(l, k) \
2071 g_dataset_id_remove_no_notify ((l), g_quark_try_string (k))
2072 #define g_dataset_set_data(l, k, d) \
2073 g_dataset_set_data_full ((l), (k), (d), NULL)
2074 #define g_dataset_remove_data(l, k) \
2075 g_dataset_id_set_data ((l), g_quark_try_string (k), NULL)
2078 /* GScanner: Flexible lexical scanner for general purpose.
2081 /* Character sets */
2082 #define G_CSET_A_2_Z "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2083 #define G_CSET_a_2_z "abcdefghijklmnopqrstuvwxyz"
2084 #define G_CSET_DIGITS "0123456789"
2085 #define G_CSET_LATINC "\300\301\302\303\304\305\306"\
2086 "\307\310\311\312\313\314\315\316\317\320"\
2087 "\321\322\323\324\325\326"\
2088 "\330\331\332\333\334\335\336"
2089 #define G_CSET_LATINS "\337\340\341\342\343\344\345\346"\
2090 "\347\350\351\352\353\354\355\356\357\360"\
2091 "\361\362\363\364\365\366"\
2092 "\370\371\372\373\374\375\376\377"
2094 /* Error types */
2095 typedef enum
2097 G_ERR_UNKNOWN,
2098 G_ERR_UNEXP_EOF,
2099 G_ERR_UNEXP_EOF_IN_STRING,
2100 G_ERR_UNEXP_EOF_IN_COMMENT,
2101 G_ERR_NON_DIGIT_IN_CONST,
2102 G_ERR_DIGIT_RADIX,
2103 G_ERR_FLOAT_RADIX,
2104 G_ERR_FLOAT_MALFORMED
2105 } GErrorType;
2107 /* Token types */
2108 typedef enum
2110 G_TOKEN_EOF = 0,
2112 G_TOKEN_LEFT_PAREN = '(',
2113 G_TOKEN_RIGHT_PAREN = ')',
2114 G_TOKEN_LEFT_CURLY = '{',
2115 G_TOKEN_RIGHT_CURLY = '}',
2116 G_TOKEN_LEFT_BRACE = '[',
2117 G_TOKEN_RIGHT_BRACE = ']',
2118 G_TOKEN_EQUAL_SIGN = '=',
2119 G_TOKEN_COMMA = ',',
2121 G_TOKEN_NONE = 256,
2123 G_TOKEN_ERROR,
2125 G_TOKEN_CHAR,
2126 G_TOKEN_BINARY,
2127 G_TOKEN_OCTAL,
2128 G_TOKEN_INT,
2129 G_TOKEN_HEX,
2130 G_TOKEN_FLOAT,
2131 G_TOKEN_STRING,
2133 G_TOKEN_SYMBOL,
2134 G_TOKEN_IDENTIFIER,
2135 G_TOKEN_IDENTIFIER_NULL,
2137 G_TOKEN_COMMENT_SINGLE,
2138 G_TOKEN_COMMENT_MULTI,
2139 G_TOKEN_LAST
2140 } GTokenType;
2142 union _GTokenValue
2144 gpointer v_symbol;
2145 gchar *v_identifier;
2146 gulong v_binary;
2147 gulong v_octal;
2148 gulong v_int;
2149 gdouble v_float;
2150 gulong v_hex;
2151 gchar *v_string;
2152 gchar *v_comment;
2153 guchar v_char;
2154 guint v_error;
2157 struct _GScannerConfig
2159 /* Character sets
2161 gchar *cset_skip_characters; /* default: " \t\n" */
2162 gchar *cset_identifier_first;
2163 gchar *cset_identifier_nth;
2164 gchar *cpair_comment_single; /* default: "#\n" */
2166 /* Should symbol lookup work case sensitive?
2168 guint case_sensitive : 1;
2170 /* Boolean values to be adjusted "on the fly"
2171 * to configure scanning behaviour.
2173 guint skip_comment_multi : 1; /* C like comment */
2174 guint skip_comment_single : 1; /* single line comment */
2175 guint scan_comment_multi : 1; /* scan multi line comments? */
2176 guint scan_identifier : 1;
2177 guint scan_identifier_1char : 1;
2178 guint scan_identifier_NULL : 1;
2179 guint scan_symbols : 1;
2180 guint scan_binary : 1;
2181 guint scan_octal : 1;
2182 guint scan_float : 1;
2183 guint scan_hex : 1; /* `0x0ff0' */
2184 guint scan_hex_dollar : 1; /* `$0ff0' */
2185 guint scan_string_sq : 1; /* string: 'anything' */
2186 guint scan_string_dq : 1; /* string: "\\-escapes!\n" */
2187 guint numbers_2_int : 1; /* bin, octal, hex => int */
2188 guint int_2_float : 1; /* int => G_TOKEN_FLOAT? */
2189 guint identifier_2_string : 1;
2190 guint char_2_token : 1; /* return G_TOKEN_CHAR? */
2191 guint symbol_2_token : 1;
2192 guint scope_0_fallback : 1; /* try scope 0 on lookups? */
2195 struct _GScanner
2197 /* unused fields */
2198 gpointer user_data;
2199 guint max_parse_errors;
2201 /* g_scanner_error() increments this field */
2202 guint parse_errors;
2204 /* name of input stream, featured by the default message handler */
2205 const gchar *input_name;
2207 /* data pointer for derived structures */
2208 gpointer derived_data;
2210 /* link into the scanner configuration */
2211 GScannerConfig *config;
2213 /* fields filled in after g_scanner_get_next_token() */
2214 GTokenType token;
2215 GTokenValue value;
2216 guint line;
2217 guint position;
2219 /* fields filled in after g_scanner_peek_next_token() */
2220 GTokenType next_token;
2221 GTokenValue next_value;
2222 guint next_line;
2223 guint next_position;
2225 /* to be considered private */
2226 GHashTable *symbol_table;
2227 gint input_fd;
2228 const gchar *text;
2229 const gchar *text_end;
2230 gchar *buffer;
2231 guint scope_id;
2233 /* handler function for _warn and _error */
2234 GScannerMsgFunc msg_handler;
2237 GScanner* g_scanner_new (GScannerConfig *config_templ);
2238 void g_scanner_destroy (GScanner *scanner);
2239 void g_scanner_input_file (GScanner *scanner,
2240 gint input_fd);
2241 void g_scanner_sync_file_offset (GScanner *scanner);
2242 void g_scanner_input_text (GScanner *scanner,
2243 const gchar *text,
2244 guint text_len);
2245 GTokenType g_scanner_get_next_token (GScanner *scanner);
2246 GTokenType g_scanner_peek_next_token (GScanner *scanner);
2247 GTokenType g_scanner_cur_token (GScanner *scanner);
2248 GTokenValue g_scanner_cur_value (GScanner *scanner);
2249 guint g_scanner_cur_line (GScanner *scanner);
2250 guint g_scanner_cur_position (GScanner *scanner);
2251 gboolean g_scanner_eof (GScanner *scanner);
2252 guint g_scanner_set_scope (GScanner *scanner,
2253 guint scope_id);
2254 void g_scanner_scope_add_symbol (GScanner *scanner,
2255 guint scope_id,
2256 const gchar *symbol,
2257 gpointer value);
2258 void g_scanner_scope_remove_symbol (GScanner *scanner,
2259 guint scope_id,
2260 const gchar *symbol);
2261 gpointer g_scanner_scope_lookup_symbol (GScanner *scanner,
2262 guint scope_id,
2263 const gchar *symbol);
2264 void g_scanner_scope_foreach_symbol (GScanner *scanner,
2265 guint scope_id,
2266 GHFunc func,
2267 gpointer user_data);
2268 gpointer g_scanner_lookup_symbol (GScanner *scanner,
2269 const gchar *symbol);
2270 void g_scanner_freeze_symbol_table (GScanner *scanner);
2271 void g_scanner_thaw_symbol_table (GScanner *scanner);
2272 void g_scanner_unexp_token (GScanner *scanner,
2273 GTokenType expected_token,
2274 const gchar *identifier_spec,
2275 const gchar *symbol_spec,
2276 const gchar *symbol_name,
2277 const gchar *message,
2278 gint is_error);
2279 void g_scanner_error (GScanner *scanner,
2280 const gchar *format,
2281 ...) G_GNUC_PRINTF (2,3);
2282 void g_scanner_warn (GScanner *scanner,
2283 const gchar *format,
2284 ...) G_GNUC_PRINTF (2,3);
2285 gint g_scanner_stat_mode (const gchar *filename);
2286 /* keep downward source compatibility */
2287 #define g_scanner_add_symbol( scanner, symbol, value ) G_STMT_START { \
2288 g_scanner_scope_add_symbol ((scanner), 0, (symbol), (value)); \
2289 } G_STMT_END
2290 #define g_scanner_remove_symbol( scanner, symbol ) G_STMT_START { \
2291 g_scanner_scope_remove_symbol ((scanner), 0, (symbol)); \
2292 } G_STMT_END
2293 #define g_scanner_foreach_symbol( scanner, func, data ) G_STMT_START { \
2294 g_scanner_scope_foreach_symbol ((scanner), 0, (func), (data)); \
2295 } G_STMT_END
2298 /* GCompletion
2301 struct _GCompletion
2303 GList* items;
2304 GCompletionFunc func;
2306 gchar* prefix;
2307 GList* cache;
2310 GCompletion* g_completion_new (GCompletionFunc func);
2311 void g_completion_add_items (GCompletion* cmp,
2312 GList* items);
2313 void g_completion_remove_items (GCompletion* cmp,
2314 GList* items);
2315 void g_completion_clear_items (GCompletion* cmp);
2316 GList* g_completion_complete (GCompletion* cmp,
2317 gchar* prefix,
2318 gchar** new_prefix);
2319 void g_completion_free (GCompletion* cmp);
2322 /* GDate
2324 * Date calculations (not time for now, to be resolved). These are a
2325 * mutant combination of Steffen Beyer's DateCalc routines
2326 * (http://www.perl.com/CPAN/authors/id/STBEY/) and Jon Trowbridge's
2327 * date routines (written for in-house software). Written by Havoc
2328 * Pennington <hp@pobox.com>
2331 typedef guint16 GDateYear;
2332 typedef guint8 GDateDay; /* day of the month */
2333 typedef struct _GDate GDate;
2334 /* make struct tm known without having to include time.h */
2335 struct tm;
2337 /* enum used to specify order of appearance in parsed date strings */
2338 typedef enum
2340 G_DATE_DAY = 0,
2341 G_DATE_MONTH = 1,
2342 G_DATE_YEAR = 2
2343 } GDateDMY;
2345 /* actual week and month values */
2346 typedef enum
2348 G_DATE_BAD_WEEKDAY = 0,
2349 G_DATE_MONDAY = 1,
2350 G_DATE_TUESDAY = 2,
2351 G_DATE_WEDNESDAY = 3,
2352 G_DATE_THURSDAY = 4,
2353 G_DATE_FRIDAY = 5,
2354 G_DATE_SATURDAY = 6,
2355 G_DATE_SUNDAY = 7
2356 } GDateWeekday;
2357 typedef enum
2359 G_DATE_BAD_MONTH = 0,
2360 G_DATE_JANUARY = 1,
2361 G_DATE_FEBRUARY = 2,
2362 G_DATE_MARCH = 3,
2363 G_DATE_APRIL = 4,
2364 G_DATE_MAY = 5,
2365 G_DATE_JUNE = 6,
2366 G_DATE_JULY = 7,
2367 G_DATE_AUGUST = 8,
2368 G_DATE_SEPTEMBER = 9,
2369 G_DATE_OCTOBER = 10,
2370 G_DATE_NOVEMBER = 11,
2371 G_DATE_DECEMBER = 12
2372 } GDateMonth;
2374 #define G_DATE_BAD_JULIAN 0U
2375 #define G_DATE_BAD_DAY 0U
2376 #define G_DATE_BAD_YEAR 0U
2378 /* Note: directly manipulating structs is generally a bad idea, but
2379 * in this case it's an *incredibly* bad idea, because all or part
2380 * of this struct can be invalid at any given time. Use the functions,
2381 * or you will get hosed, I promise.
2383 struct _GDate
2385 guint julian_days : 32; /* julian days representation - we use a
2386 * bitfield hoping that 64 bit platforms
2387 * will pack this whole struct in one big
2388 * int
2391 guint julian : 1; /* julian is valid */
2392 guint dmy : 1; /* dmy is valid */
2394 /* DMY representation */
2395 guint day : 6;
2396 guint month : 4;
2397 guint year : 16;
2400 /* g_date_new() returns an invalid date, you then have to _set() stuff
2401 * to get a usable object. You can also allocate a GDate statically,
2402 * then call g_date_clear() to initialize.
2404 GDate* g_date_new (void);
2405 GDate* g_date_new_dmy (GDateDay day,
2406 GDateMonth month,
2407 GDateYear year);
2408 GDate* g_date_new_julian (guint32 julian_day);
2409 void g_date_free (GDate *date);
2411 /* check g_date_valid() after doing an operation that might fail, like
2412 * _parse. Almost all g_date operations are undefined on invalid
2413 * dates (the exceptions are the mutators, since you need those to
2414 * return to validity).
2416 gboolean g_date_valid (GDate *date);
2417 gboolean g_date_valid_day (GDateDay day);
2418 gboolean g_date_valid_month (GDateMonth month);
2419 gboolean g_date_valid_year (GDateYear year);
2420 gboolean g_date_valid_weekday (GDateWeekday weekday);
2421 gboolean g_date_valid_julian (guint32 julian_date);
2422 gboolean g_date_valid_dmy (GDateDay day,
2423 GDateMonth month,
2424 GDateYear year);
2426 GDateWeekday g_date_weekday (GDate *date);
2427 GDateMonth g_date_month (GDate *date);
2428 GDateYear g_date_year (GDate *date);
2429 GDateDay g_date_day (GDate *date);
2430 guint32 g_date_julian (GDate *date);
2431 guint g_date_day_of_year (GDate *date);
2433 /* First monday/sunday is the start of week 1; if we haven't reached
2434 * that day, return 0. These are not ISO weeks of the year; that
2435 * routine needs to be added.
2436 * these functions return the number of weeks, starting on the
2437 * corrsponding day
2439 guint g_date_monday_week_of_year (GDate *date);
2440 guint g_date_sunday_week_of_year (GDate *date);
2442 /* If you create a static date struct you need to clear it to get it
2443 * in a sane state before use. You can clear a whole array at
2444 * once with the ndates argument.
2446 void g_date_clear (GDate *date,
2447 guint n_dates);
2449 /* The parse routine is meant for dates typed in by a user, so it
2450 * permits many formats but tries to catch common typos. If your data
2451 * needs to be strictly validated, it is not an appropriate function.
2453 void g_date_set_parse (GDate *date,
2454 const gchar *str);
2455 void g_date_set_time (GDate *date,
2456 GTime time);
2457 void g_date_set_month (GDate *date,
2458 GDateMonth month);
2459 void g_date_set_day (GDate *date,
2460 GDateDay day);
2461 void g_date_set_year (GDate *date,
2462 GDateYear year);
2463 void g_date_set_dmy (GDate *date,
2464 GDateDay day,
2465 GDateMonth month,
2466 GDateYear y);
2467 void g_date_set_julian (GDate *date,
2468 guint32 julian_date);
2469 gboolean g_date_is_first_of_month (GDate *date);
2470 gboolean g_date_is_last_of_month (GDate *date);
2472 /* To go forward by some number of weeks just go forward weeks*7 days */
2473 void g_date_add_days (GDate *date,
2474 guint n_days);
2475 void g_date_subtract_days (GDate *date,
2476 guint n_days);
2478 /* If you add/sub months while day > 28, the day might change */
2479 void g_date_add_months (GDate *date,
2480 guint n_months);
2481 void g_date_subtract_months (GDate *date,
2482 guint n_months);
2484 /* If it's feb 29, changing years can move you to the 28th */
2485 void g_date_add_years (GDate *date,
2486 guint n_years);
2487 void g_date_subtract_years (GDate *date,
2488 guint n_years);
2489 gboolean g_date_is_leap_year (GDateYear year);
2490 guint8 g_date_days_in_month (GDateMonth month,
2491 GDateYear year);
2492 guint8 g_date_monday_weeks_in_year (GDateYear year);
2493 guint8 g_date_sunday_weeks_in_year (GDateYear year);
2495 /* qsort-friendly (with a cast...) */
2496 gint g_date_compare (GDate *lhs,
2497 GDate *rhs);
2498 void g_date_to_struct_tm (GDate *date,
2499 struct tm *tm);
2501 /* Just like strftime() except you can only use date-related formats.
2502 * Using a time format is undefined.
2504 gsize g_date_strftime (gchar *s,
2505 gsize slen,
2506 const gchar *format,
2507 GDate *date);
2510 /* GRelation
2512 * Indexed Relations. Imagine a really simple table in a
2513 * database. Relations are not ordered. This data type is meant for
2514 * maintaining a N-way mapping.
2516 * g_relation_new() creates a relation with FIELDS fields
2518 * g_relation_destroy() frees all resources
2519 * g_tuples_destroy() frees the result of g_relation_select()
2521 * g_relation_index() indexes relation FIELD with the provided
2522 * equality and hash functions. this must be done before any
2523 * calls to insert are made.
2525 * g_relation_insert() inserts a new tuple. you are expected to
2526 * provide the right number of fields.
2528 * g_relation_delete() deletes all relations with KEY in FIELD
2529 * g_relation_select() returns ...
2530 * g_relation_count() counts ...
2533 GRelation* g_relation_new (gint fields);
2534 void g_relation_destroy (GRelation *relation);
2535 void g_relation_index (GRelation *relation,
2536 gint field,
2537 GHashFunc hash_func,
2538 GCompareFunc key_compare_func);
2539 void g_relation_insert (GRelation *relation,
2540 ...);
2541 gint g_relation_delete (GRelation *relation,
2542 gconstpointer key,
2543 gint field);
2544 GTuples* g_relation_select (GRelation *relation,
2545 gconstpointer key,
2546 gint field);
2547 gint g_relation_count (GRelation *relation,
2548 gconstpointer key,
2549 gint field);
2550 gboolean g_relation_exists (GRelation *relation,
2551 ...);
2552 void g_relation_print (GRelation *relation);
2554 void g_tuples_destroy (GTuples *tuples);
2555 gpointer g_tuples_index (GTuples *tuples,
2556 gint index,
2557 gint field);
2560 /* GRand - a good and fast random number generator: Mersenne Twister
2561 * see http://www.math.keio.ac.jp/~matumoto/emt.html for more info.
2562 * The range functions return a value in the intervall [min,max).
2563 * int -> [0..2^32-1]
2564 * int_range -> [min..max-1]
2565 * double -> [0..1)
2566 * double_range -> [min..max)
2569 GRand* g_rand_new_with_seed (guint32 seed);
2570 GRand* g_rand_new (void);
2571 void g_rand_free (GRand *rand);
2573 void g_rand_set_seed (GRand *rand,
2574 guint32 seed);
2575 guint32 g_rand_int (GRand *rand);
2576 gint32 g_rand_int_range (GRand *rand,
2577 gint32 min,
2578 gint32 max);
2579 gdouble g_rand_double (GRand *rand);
2580 gdouble g_rand_double_range (GRand *rand,
2581 gdouble min,
2582 gdouble max);
2584 void g_random_set_seed (guint32 seed);
2585 guint32 g_random_int (void);
2586 gint32 g_random_int_range (gint32 min,
2587 gint32 max);
2588 gdouble g_random_double (void);
2589 gdouble g_random_double_range (gdouble min,
2590 gdouble max);
2593 /* Prime numbers.
2596 /* This function returns prime numbers spaced by approximately 1.5-2.0
2597 * and is for use in resizing data structures which prefer
2598 * prime-valued sizes. The closest spaced prime function returns the
2599 * next largest prime, or the highest it knows about which is about
2600 * MAXINT/4.
2602 guint g_spaced_primes_closest (guint num);
2605 /* GIOChannel
2608 typedef struct _GIOFuncs GIOFuncs;
2609 typedef enum
2611 G_IO_ERROR_NONE,
2612 G_IO_ERROR_AGAIN,
2613 G_IO_ERROR_INVAL,
2614 G_IO_ERROR_UNKNOWN
2615 } GIOError;
2616 typedef enum
2618 G_SEEK_CUR,
2619 G_SEEK_SET,
2620 G_SEEK_END
2621 } GSeekType;
2622 typedef enum
2624 G_IO_IN GLIB_SYSDEF_POLLIN,
2625 G_IO_OUT GLIB_SYSDEF_POLLOUT,
2626 G_IO_PRI GLIB_SYSDEF_POLLPRI,
2627 G_IO_ERR GLIB_SYSDEF_POLLERR,
2628 G_IO_HUP GLIB_SYSDEF_POLLHUP,
2629 G_IO_NVAL GLIB_SYSDEF_POLLNVAL
2630 } GIOCondition;
2632 struct _GIOChannel
2634 guint channel_flags;
2635 guint ref_count;
2636 GIOFuncs *funcs;
2639 typedef gboolean (*GIOFunc) (GIOChannel *source,
2640 GIOCondition condition,
2641 gpointer data);
2642 struct _GIOFuncs
2644 GIOError (*io_read) (GIOChannel *channel,
2645 gchar *buf,
2646 guint count,
2647 guint *bytes_read);
2648 GIOError (*io_write) (GIOChannel *channel,
2649 gchar *buf,
2650 guint count,
2651 guint *bytes_written);
2652 GIOError (*io_seek) (GIOChannel *channel,
2653 gint offset,
2654 GSeekType type);
2655 void (*io_close) (GIOChannel *channel);
2656 guint (*io_add_watch) (GIOChannel *channel,
2657 gint priority,
2658 GIOCondition condition,
2659 GIOFunc func,
2660 gpointer user_data,
2661 GDestroyNotify notify);
2662 void (*io_free) (GIOChannel *channel);
2665 void g_io_channel_init (GIOChannel *channel);
2666 void g_io_channel_ref (GIOChannel *channel);
2667 void g_io_channel_unref (GIOChannel *channel);
2668 GIOError g_io_channel_read (GIOChannel *channel,
2669 gchar *buf,
2670 guint count,
2671 guint *bytes_read);
2672 GIOError g_io_channel_write (GIOChannel *channel,
2673 gchar *buf,
2674 guint count,
2675 guint *bytes_written);
2676 GIOError g_io_channel_seek (GIOChannel *channel,
2677 gint offset,
2678 GSeekType type);
2679 void g_io_channel_close (GIOChannel *channel);
2680 guint g_io_add_watch_full (GIOChannel *channel,
2681 gint priority,
2682 GIOCondition condition,
2683 GIOFunc func,
2684 gpointer user_data,
2685 GDestroyNotify notify);
2686 guint g_io_add_watch (GIOChannel *channel,
2687 GIOCondition condition,
2688 GIOFunc func,
2689 gpointer user_data);
2692 /* Main loop
2694 typedef struct _GTimeVal GTimeVal;
2695 typedef struct _GSourceFuncs GSourceFuncs;
2696 typedef struct _GMainLoop GMainLoop; /* Opaque */
2698 struct _GTimeVal
2700 glong tv_sec;
2701 glong tv_usec;
2703 struct _GSourceFuncs
2705 gboolean (*prepare) (gpointer source_data,
2706 GTimeVal *current_time,
2707 gint *timeout,
2708 gpointer user_data);
2709 gboolean (*check) (gpointer source_data,
2710 GTimeVal *current_time,
2711 gpointer user_data);
2712 gboolean (*dispatch) (gpointer source_data,
2713 GTimeVal *dispatch_time,
2714 gpointer user_data);
2715 GDestroyNotify destroy;
2718 /* Standard priorities */
2720 #define G_PRIORITY_HIGH -100
2721 #define G_PRIORITY_DEFAULT 0
2722 #define G_PRIORITY_HIGH_IDLE 100
2723 #define G_PRIORITY_DEFAULT_IDLE 200
2724 #define G_PRIORITY_LOW 300
2726 typedef gboolean (*GSourceFunc) (gpointer data);
2728 /* Hooks for adding to the main loop */
2729 guint g_source_add (gint priority,
2730 gboolean can_recurse,
2731 GSourceFuncs *funcs,
2732 gpointer source_data,
2733 gpointer user_data,
2734 GDestroyNotify notify);
2735 gboolean g_source_remove (guint tag);
2736 gboolean g_source_remove_by_user_data (gpointer user_data);
2737 gboolean g_source_remove_by_source_data (gpointer source_data);
2738 gboolean g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2739 gpointer user_data);
2741 void g_get_current_time (GTimeVal *result);
2743 /* Running the main loop */
2744 GMainLoop* g_main_new (gboolean is_running);
2745 void g_main_run (GMainLoop *loop);
2746 void g_main_quit (GMainLoop *loop);
2747 void g_main_destroy (GMainLoop *loop);
2748 gboolean g_main_is_running (GMainLoop *loop);
2750 /* Run a single iteration of the mainloop. If block is FALSE,
2751 * will never block
2753 gboolean g_main_iteration (gboolean may_block);
2755 /* See if any events are pending */
2756 gboolean g_main_pending (void);
2758 /* Idles and timeouts */
2759 guint g_timeout_add_full (gint priority,
2760 guint interval,
2761 GSourceFunc function,
2762 gpointer data,
2763 GDestroyNotify notify);
2764 guint g_timeout_add (guint interval,
2765 GSourceFunc function,
2766 gpointer data);
2767 guint g_idle_add (GSourceFunc function,
2768 gpointer data);
2769 guint g_idle_add_full (gint priority,
2770 GSourceFunc function,
2771 gpointer data,
2772 GDestroyNotify destroy);
2773 gboolean g_idle_remove_by_data (gpointer data);
2775 /* GPollFD
2777 * System-specific IO and main loop calls
2779 * On Win32, the fd in a GPollFD should be Win32 HANDLE (*not* a file
2780 * descriptor as provided by the C runtime) that can be used by
2781 * MsgWaitForMultipleObjects. This does *not* include file handles
2782 * from CreateFile, SOCKETs, nor pipe handles. (But you can use
2783 * WSAEventSelect to signal events when a SOCKET is readable).
2785 * On Win32, fd can also be the special value G_WIN32_MSG_HANDLE to
2786 * indicate polling for messages. These message queue GPollFDs should
2787 * be added with the g_main_poll_win32_msg_add function.
2789 * But note that G_WIN32_MSG_HANDLE GPollFDs should not be used by GDK
2790 * (GTK) programs, as GDK itself wants to read messages and convert them
2791 * to GDK events.
2793 * So, unless you really know what you are doing, it's best not to try
2794 * to use the main loop polling stuff for your own needs on
2795 * Win32. It's really only written for the GIMP's needs so
2796 * far.
2799 typedef struct _GPollFD GPollFD;
2800 typedef gint (*GPollFunc) (GPollFD *ufds,
2801 guint nfsd,
2802 gint timeout);
2803 struct _GPollFD
2805 gint fd;
2806 gushort events;
2807 gushort revents;
2810 void g_main_add_poll (GPollFD *fd,
2811 gint priority);
2812 void g_main_remove_poll (GPollFD *fd);
2813 void g_main_set_poll_func (GPollFunc func);
2815 /* On Unix, IO channels created with this function for any file
2816 * descriptor or socket.
2818 * On Win32, use this only for plain files opened with the MSVCRT (the
2819 * Microsoft run-time C library) _open(), including file descriptors
2820 * 0, 1 and 2 (corresponding to stdin, stdout and stderr).
2821 * Actually, don't do even that, this code isn't done yet.
2823 * The term file descriptor as used in the context of Win32 refers to
2824 * the emulated Unix-like file descriptors MSVCRT provides.
2826 GIOChannel* g_io_channel_unix_new (int fd);
2827 gint g_io_channel_unix_get_fd (GIOChannel *channel);
2829 #ifdef G_OS_WIN32
2831 GUTILS_C_VAR guint g_pipe_readable_msg;
2833 #define G_WIN32_MSG_HANDLE 19981206
2835 /* This is used to add polling for Windows messages. GDK (GTk+) programs
2836 * should *not* use this. (In fact, I can't think of any program that
2837 * would want to use this, but it's here just for completeness's sake.
2839 void g_main_poll_win32_msg_add(gint priority,
2840 GPollFD *fd,
2841 guint hwnd);
2843 /* An IO channel for Windows messages for window handle hwnd. */
2844 GIOChannel *g_io_channel_win32_new_messages (guint hwnd);
2846 /* An IO channel for an anonymous pipe as returned from the MSVCRT
2847 * _pipe(), with no mechanism for the writer to tell the reader when
2848 * there is data in the pipe.
2850 * This is not really implemented yet.
2852 GIOChannel *g_io_channel_win32_new_pipe (int fd);
2854 /* An IO channel for a pipe as returned from the MSVCRT _pipe(), with
2855 * Windows user messages used to signal data in the pipe for the
2856 * reader.
2858 * fd is the file descriptor. For the write end, peer is the thread id
2859 * of the reader, and peer_fd is his file descriptor for the read end
2860 * of the pipe.
2862 * This is used by the GIMP, and works.
2864 GIOChannel *g_io_channel_win32_new_pipe_with_wakeups (int fd,
2865 guint peer,
2866 int peer_fd);
2868 void g_io_channel_win32_pipe_request_wakeups (GIOChannel *channel,
2869 guint peer,
2870 int peer_fd);
2872 void g_io_channel_win32_pipe_readable (int fd,
2873 guint offset);
2875 /* Get the C runtime file descriptor of a channel. */
2876 gint g_io_channel_win32_get_fd (GIOChannel *channel);
2878 /* An IO channel for a SOCK_STREAM winsock socket. The parameter is
2879 * actually a SOCKET.
2881 GIOChannel *g_io_channel_win32_new_stream_socket (int socket);
2883 #endif
2885 /* Windows emulation stubs for common Unix functions
2887 #ifdef G_OS_WIN32
2888 # define MAXPATHLEN 1024
2890 #ifdef _MSC_VER
2891 typedef int pid_t;
2892 #endif
2895 * To get prototypes for the following POSIXish functions, you have to
2896 * include the indicated non-POSIX headers. The functions are defined
2897 * in OLDNAMES.LIB (MSVC) or -lmoldname-msvc (mingw32).
2899 * getcwd: <direct.h> (MSVC), <io.h> (mingw32)
2900 * getpid: <process.h>
2901 * access: <io.h>
2902 * unlink: <stdio.h> or <io.h>
2903 * open, read, write, lseek, close: <io.h>
2904 * rmdir: <direct.h>
2905 * pipe: <direct.h>
2908 /* pipe is not in OLDNAMES.LIB or -lmoldname-msvc. */
2909 #define pipe(phandles) _pipe (phandles, 4096, _O_BINARY)
2911 /* For some POSIX functions that are not provided by the MS runtime,
2912 * we provide emulators in glib, which are prefixed with g_win32_.
2914 # define ftruncate(fd, size) g_win32_ftruncate (fd, size)
2916 /* -lmingw32 also has emulations for these, but we need our own
2917 * for MSVC anyhow, so we might aswell use them always.
2919 # define opendir g_win32_opendir
2920 # define readdir g_win32_readdir
2921 # define rewinddir g_win32_rewinddir
2922 # define closedir g_win32_closedir
2923 # define NAME_MAX 255
2925 struct DIR
2927 gchar *dir_name;
2928 gboolean just_opened;
2929 guint find_file_handle;
2930 gpointer find_file_data;
2932 typedef struct DIR DIR;
2933 struct dirent
2935 gchar d_name[NAME_MAX + 1];
2937 /* emulation functions */
2938 extern int g_win32_ftruncate (gint f,
2939 guint size);
2940 DIR* g_win32_opendir (const gchar *dirname);
2941 struct dirent* g_win32_readdir (DIR *dir);
2942 void g_win32_rewinddir (DIR *dir);
2943 gint g_win32_closedir (DIR *dir);
2945 /* The MS setlocale uses locale names of the form "English_United
2946 * States.1252" etc. We want the Unixish standard form "en", "zh_TW"
2947 * etc. This function gets the current thread locale from Windows and
2948 * returns it as a string of the above form for use in forming file
2949 * names etc. The returned string should be deallocated with g_free().
2951 gchar * g_win32_getlocale (void);
2953 /* Translate a Win32 error code (as returned by GetLastError()) into
2954 * the corresponding message. The returned string should be deallocated
2955 * with g_free().
2957 gchar * g_win32_error_message (gint error);
2959 #endif /* G_OS_WIN32 */
2962 /* GLib Thread support
2965 typedef void (*GThreadFunc) (gpointer value);
2967 typedef enum
2969 G_THREAD_PRIORITY_LOW,
2970 G_THREAD_PRIORITY_NORMAL,
2971 G_THREAD_PRIORITY_HIGH,
2972 G_THREAD_PRIORITY_URGENT
2973 } GThreadPriority;
2975 typedef struct _GThread GThread;
2976 struct _GThread
2978 GThreadPriority priority;
2979 gboolean bound;
2980 gboolean joinable;
2983 typedef struct _GMutex GMutex;
2984 typedef struct _GCond GCond;
2985 typedef struct _GPrivate GPrivate;
2986 typedef struct _GStaticPrivate GStaticPrivate;
2987 typedef struct _GAsyncQueue GAsyncQueue;
2988 typedef struct _GThreadPool GThreadPool;
2990 typedef struct _GThreadFunctions GThreadFunctions;
2991 struct _GThreadFunctions
2993 GMutex* (*mutex_new) (void);
2994 void (*mutex_lock) (GMutex *mutex);
2995 gboolean (*mutex_trylock) (GMutex *mutex);
2996 void (*mutex_unlock) (GMutex *mutex);
2997 void (*mutex_free) (GMutex *mutex);
2998 GCond* (*cond_new) (void);
2999 void (*cond_signal) (GCond *cond);
3000 void (*cond_broadcast) (GCond *cond);
3001 void (*cond_wait) (GCond *cond,
3002 GMutex *mutex);
3003 gboolean (*cond_timed_wait) (GCond *cond,
3004 GMutex *mutex,
3005 GTimeVal *end_time);
3006 void (*cond_free) (GCond *cond);
3007 GPrivate* (*private_new) (GDestroyNotify destructor);
3008 gpointer (*private_get) (GPrivate *private_key);
3009 void (*private_set) (GPrivate *private_key,
3010 gpointer data);
3011 void (*thread_create) (GThreadFunc thread_func,
3012 gpointer arg,
3013 gulong stack_size,
3014 gboolean joinable,
3015 gboolean bound,
3016 GThreadPriority priority,
3017 gpointer thread);
3018 void (*thread_yield) (void);
3019 void (*thread_join) (gpointer thread);
3020 void (*thread_exit) (void);
3021 void (*thread_set_priority)(gpointer thread,
3022 GThreadPriority priority);
3023 void (*thread_self) (gpointer thread);
3026 GUTILS_C_VAR GThreadFunctions g_thread_functions_for_glib_use;
3027 GUTILS_C_VAR gboolean g_thread_use_default_impl;
3028 GUTILS_C_VAR gboolean g_threads_got_initialized;
3030 /* initializes the mutex/cond/private implementation for glib, might
3031 * only be called once, and must not be called directly or indirectly
3032 * from another glib-function, e.g. as a callback.
3034 void g_thread_init (GThreadFunctions *vtable);
3036 /* internal function for fallback static mutex implementation */
3037 GMutex* g_static_mutex_get_mutex_impl (GMutex **mutex);
3039 /* shorthands for conditional and unconditional function calls */
3040 #define G_THREAD_UF(name, arglist) \
3041 (*g_thread_functions_for_glib_use . name) arglist
3042 #define G_THREAD_CF(name, fail, arg) \
3043 (g_thread_supported () ? G_THREAD_UF (name, arg) : (fail))
3044 /* keep in mind, all those mutexes and static mutexes are not
3045 * recursive in general, don't rely on that
3047 #define g_thread_supported() (g_threads_got_initialized)
3048 #define g_mutex_new() G_THREAD_UF (mutex_new, ())
3049 #define g_mutex_lock(mutex) G_THREAD_CF (mutex_lock, (void)0, (mutex))
3050 #define g_mutex_trylock(mutex) G_THREAD_CF (mutex_trylock, TRUE, (mutex))
3051 #define g_mutex_unlock(mutex) G_THREAD_CF (mutex_unlock, (void)0, (mutex))
3052 #define g_mutex_free(mutex) G_THREAD_CF (mutex_free, (void)0, (mutex))
3053 #define g_cond_new() G_THREAD_UF (cond_new, ())
3054 #define g_cond_signal(cond) G_THREAD_CF (cond_signal, (void)0, (cond))
3055 #define g_cond_broadcast(cond) G_THREAD_CF (cond_broadcast, (void)0, (cond))
3056 #define g_cond_wait(cond, mutex) G_THREAD_CF (cond_wait, (void)0, (cond, \
3057 mutex))
3058 #define g_cond_free(cond) G_THREAD_CF (cond_free, (void)0, (cond))
3059 #define g_cond_timed_wait(cond, mutex, abs_time) G_THREAD_CF (cond_timed_wait, \
3060 TRUE, \
3061 (cond, mutex, \
3062 abs_time))
3063 #define g_private_new(destructor) G_THREAD_UF (private_new, (destructor))
3064 #define g_private_get(private_key) G_THREAD_CF (private_get, \
3065 ((gpointer)private_key), \
3066 (private_key))
3067 #define g_private_set(private_key, value) G_THREAD_CF (private_set, \
3068 (void) (private_key = \
3069 (GPrivate*) (value)), \
3070 (private_key, value))
3071 #define g_thread_yield() G_THREAD_CF (thread_yield, (void)0, ())
3072 #define g_thread_exit() G_THREAD_CF (thread_exit, (void)0, ())
3074 GThread* g_thread_create (GThreadFunc thread_func,
3075 gpointer arg,
3076 gulong stack_size,
3077 gboolean joinable,
3078 gboolean bound,
3079 GThreadPriority priority);
3080 GThread* g_thread_self ();
3081 void g_thread_join (GThread* thread);
3082 void g_thread_set_priority (GThread* thread,
3083 GThreadPriority priority);
3085 /* GStaticMutexes can be statically initialized with the value
3086 * G_STATIC_MUTEX_INIT, and then they can directly be used, that is
3087 * much easier, than having to explicitly allocate the mutex before
3088 * use
3090 #define g_static_mutex_lock(mutex) \
3091 g_mutex_lock (g_static_mutex_get_mutex (mutex))
3092 #define g_static_mutex_trylock(mutex) \
3093 g_mutex_trylock (g_static_mutex_get_mutex (mutex))
3094 #define g_static_mutex_unlock(mutex) \
3095 g_mutex_unlock (g_static_mutex_get_mutex (mutex))
3097 struct _GStaticPrivate
3099 guint index;
3101 #define G_STATIC_PRIVATE_INIT { 0 }
3102 gpointer g_static_private_get (GStaticPrivate *private_key);
3103 void g_static_private_set (GStaticPrivate *private_key,
3104 gpointer data,
3105 GDestroyNotify notify);
3106 gpointer g_static_private_get_for_thread (GStaticPrivate *private_key,
3107 GThread *thread);
3108 void g_static_private_set_for_thread (GStaticPrivate *private_key,
3109 GThread *thread,
3110 gpointer data,
3111 GDestroyNotify notify);
3113 typedef struct _GStaticRecMutex GStaticRecMutex;
3114 struct _GStaticRecMutex
3116 GStaticMutex mutex;
3117 unsigned int depth;
3118 GSystemThread owner;
3121 #define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT }
3122 void g_static_rec_mutex_lock (GStaticRecMutex *mutex);
3123 gboolean g_static_rec_mutex_trylock (GStaticRecMutex *mutex);
3124 void g_static_rec_mutex_unlock (GStaticRecMutex *mutex);
3125 void g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
3126 guint depth);
3127 guint g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex);
3129 typedef struct _GStaticRWLock GStaticRWLock;
3130 struct _GStaticRWLock
3132 GStaticMutex mutex;
3133 GCond *read_cond;
3134 GCond *write_cond;
3135 guint read_counter;
3136 gboolean write;
3137 guint want_to_write;
3140 #define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, FALSE }
3142 void g_static_rw_lock_reader_lock (GStaticRWLock* lock);
3143 gboolean g_static_rw_lock_reader_trylock (GStaticRWLock* lock);
3144 void g_static_rw_lock_reader_unlock (GStaticRWLock* lock);
3145 void g_static_rw_lock_writer_lock (GStaticRWLock* lock);
3146 gboolean g_static_rw_lock_writer_trylock (GStaticRWLock* lock);
3147 void g_static_rw_lock_writer_unlock (GStaticRWLock* lock);
3148 void g_static_rw_lock_free (GStaticRWLock* lock);
3150 /* these are some convenience macros that expand to nothing if GLib
3151 * was configured with --disable-threads. for using StaticMutexes,
3152 * you define them with G_LOCK_DEFINE_STATIC (name) or G_LOCK_DEFINE (name)
3153 * if you need to export the mutex. With G_LOCK_EXTERN (name) you can
3154 * declare such an globally defined lock. name is a unique identifier
3155 * for the protected varibale or code portion. locking, testing and
3156 * unlocking of such mutexes can be done with G_LOCK(), G_UNLOCK() and
3157 * G_TRYLOCK() respectively.
3159 extern void glib_dummy_decl (void);
3160 #define G_LOCK_NAME(name) g__ ## name ## _lock
3161 #ifdef G_THREADS_ENABLED
3162 # define G_LOCK_DEFINE_STATIC(name) static G_LOCK_DEFINE (name)
3163 # define G_LOCK_DEFINE(name) \
3164 GStaticMutex G_LOCK_NAME (name) = G_STATIC_MUTEX_INIT
3165 # define G_LOCK_EXTERN(name) extern GStaticMutex G_LOCK_NAME (name)
3167 # ifdef G_DEBUG_LOCKS
3168 # define G_LOCK(name) G_STMT_START{ \
3169 g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, \
3170 "file %s: line %d (%s): locking: %s ", \
3171 __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION, \
3172 #name); \
3173 g_static_mutex_lock (&G_LOCK_NAME (name)); \
3174 }G_STMT_END
3175 # define G_UNLOCK(name) G_STMT_START{ \
3176 g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, \
3177 "file %s: line %d (%s): unlocking: %s ", \
3178 __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION, \
3179 #name); \
3180 g_static_mutex_unlock (&G_LOCK_NAME (name)); \
3181 }G_STMT_END
3182 # define G_TRYLOCK(name) \
3183 (g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, \
3184 "file %s: line %d (%s): try locking: %s ", \
3185 __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION, \
3186 #name), g_static_mutex_trylock (&G_LOCK_NAME (name)))
3187 # else /* !G_DEBUG_LOCKS */
3188 # define G_LOCK(name) g_static_mutex_lock (&G_LOCK_NAME (name))
3189 # define G_UNLOCK(name) g_static_mutex_unlock (&G_LOCK_NAME (name))
3190 # define G_TRYLOCK(name) g_static_mutex_trylock (&G_LOCK_NAME (name))
3191 # endif /* !G_DEBUG_LOCKS */
3192 #else /* !G_THREADS_ENABLED */
3193 # define G_LOCK_DEFINE_STATIC(name) extern void glib_dummy_decl (void)
3194 # define G_LOCK_DEFINE(name) extern void glib_dummy_decl (void)
3195 # define G_LOCK_EXTERN(name) extern void glib_dummy_decl (void)
3196 # define G_LOCK(name)
3197 # define G_UNLOCK(name)
3198 # define G_TRYLOCK(name) (TRUE)
3199 #endif /* !G_THREADS_ENABLED */
3201 /* Asyncronous Queues, can be used to communicate between threads
3204 /* Get a new GAsyncQueue with the ref_count 1 */
3205 GAsyncQueue* g_async_queue_new (void);
3207 /* Lock and unlock an GAsyncQueue, all functions lock the queue for
3208 * themselves, but in certain cirumstances you want to hold the lock longer,
3209 * thus you lock the queue, call the *_unlocked functions and unlock it again
3211 void g_async_queue_lock (GAsyncQueue *queue);
3212 void g_async_queue_unlock (GAsyncQueue *queue);
3214 /* Ref and unref the GAsyncQueue. g_async_queue_unref_unlocked makes
3215 * no sense, as after the unreffing the Queue might be gone and can't
3216 * be unlocked. So you have a function to call, if you don't hold the
3217 * lock (g_async_queue_unref) and one to call, when you already hold
3218 * the lock (g_async_queue_unref_and_unlock). After that however, you
3219 * don't hold the lock anymore and the Queue might in fact be
3220 * destroyed, if you unrefed to zero */
3221 void g_async_queue_ref (GAsyncQueue *queue);
3222 void g_async_queue_ref_unlocked (GAsyncQueue *queue);
3223 void g_async_queue_unref (GAsyncQueue *queue);
3224 void g_async_queue_unref_and_unlock (GAsyncQueue *queue);
3226 /* Push data into the async queue. Must not be NULL */
3227 void g_async_queue_push (GAsyncQueue *queue,
3228 gpointer data);
3229 void g_async_queue_push_unlocked (GAsyncQueue *queue,
3230 gpointer data);
3232 /* Pop data from the async queue, when no data is there, the thread is blocked
3233 * until data arrives */
3234 gpointer g_async_queue_pop (GAsyncQueue *queue);
3235 gpointer g_async_queue_pop_unlocked (GAsyncQueue *queue);
3237 /* Try to pop data, NULL is returned in case of empty queue */
3238 gpointer g_async_queue_try_pop (GAsyncQueue *queue);
3239 gpointer g_async_queue_try_pop_unlocked (GAsyncQueue *queue);
3241 /* Wait for data until at maximum until end_time is reached, NULL is returned
3242 * in case of empty queue*/
3243 gpointer g_async_queue_timed_pop (GAsyncQueue *queue,
3244 GTimeVal *end_time);
3245 gpointer g_async_queue_timed_pop_unlocked (GAsyncQueue *queue,
3246 GTimeVal *end_time);
3248 /* Return the length of the queue, negative values mean, that threads
3249 * are waiting, positve values mean, that there are entries in the
3250 * queue. Actually this function returns the length of the queue minus
3251 * the number of waiting threads, g_async_queue_length == 0 could also
3252 * mean 'n' entries in the queue and 'n' thread waiting, such can
3253 * happen due to locking of the queue or due to scheduling. */
3254 gint g_async_queue_length (GAsyncQueue *queue);
3255 gint g_async_queue_length_unlocked (GAsyncQueue *queue);
3257 /* Thread Pools
3260 /* The real GThreadPool is bigger, so you may only create a thread
3261 * pool with the constructor function */
3262 struct _GThreadPool
3264 GFunc thread_func;
3265 gulong stack_size;
3266 gboolean bound;
3267 GThreadPriority priority;
3268 gboolean exclusive;
3269 gpointer user_data;
3272 /* Get a thread pool with the function thread_func, at most max_threads may
3273 * run at a time (max_threads == -1 means no limit), stack_size, bound,
3274 * priority like in g_thread_create, exclusive == TRUE means, that the threads
3275 * shouldn't be shared and that they will be prestarted (otherwise they are
3276 * started, as needed) user_data is the 2nd argument to the thread_func */
3277 GThreadPool* g_thread_pool_new (GFunc thread_func,
3278 gint max_threads,
3279 gulong stack_size,
3280 gboolean bound,
3281 GThreadPriority priority,
3282 gboolean exclusive,
3283 gpointer user_data);
3285 /* Push new data into the thread pool. This task is assigned to a thread later
3286 * (when the maximal number of threads is reached for that pool) or now
3287 * (otherwise). If necessary a new thread will be started. The function
3288 * returns immediatly */
3289 void g_thread_pool_push (GThreadPool *pool,
3290 gpointer data);
3292 /* Set the number of threads, which can run concurrently for that pool, -1
3293 * means no limit. 0 means has the effect, that the pool won't process
3294 * requests until the limit is set higher again */
3295 void g_thread_pool_set_max_threads (GThreadPool *pool,
3296 gint max_threads);
3297 gint g_thread_pool_get_max_threads (GThreadPool *pool);
3299 /* Get the number of threads assigned to that pool. This number doesn't
3300 * necessarily represent the number of working threads in that pool */
3301 guint g_thread_pool_get_num_threads (GThreadPool *pool);
3303 /* Get the number of unprocessed items in the pool */
3304 guint g_thread_pool_unprocessed (GThreadPool *pool);
3306 /* Free the pool, immediate means, that all unprocessed items in the queue
3307 * wont be processed, wait means, that the function doesn't return immediatly,
3308 * but after all threads in the pool are ready processing items. immediate
3309 * does however not mean, that threads are killed. */
3310 void g_thread_pool_free (GThreadPool *pool,
3311 gboolean immediate,
3312 gboolean wait);
3314 /* Set the maximal number of unused threads before threads will be stopped by
3315 * GLib, -1 means no limit */
3316 void g_thread_pool_set_max_unused_threads (gint max_threads);
3317 gint g_thread_pool_get_max_unused_threads (void);
3318 guint g_thread_pool_get_num_unused_threads (void);
3320 /* Stop all currently unused threads, but leave the limit untouched */
3321 void g_thread_pool_stop_unused_threads (void);
3323 #ifdef __cplusplus
3325 #endif /* __cplusplus */
3328 #endif /* __G_LIB_H__ */