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