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