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