New File implementing an asynchronous queue to be used for asynchronous
[platform/upstream/glib.git] / glib / 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 void            (*GScannerMsgFunc)      (GScanner      *scanner,
821                                                  gchar         *message,
822                                                  gint           error);
823 typedef gint            (*GTraverseFunc)        (gpointer       key,
824                                                  gpointer       value,
825                                                  gpointer       data);
826 typedef void            (*GVoidFunc)            (void);
827
828
829 struct _GArray
830 {
831   gchar *data;
832   guint len;
833 };
834
835 struct _GByteArray
836 {
837   guint8 *data;
838   guint   len;
839 };
840
841 struct _GDebugKey
842 {
843   gchar *key;
844   guint  value;
845 };
846
847 struct _GList
848 {
849   gpointer data;
850   GList *next;
851   GList *prev;
852 };
853
854 struct _GPtrArray
855 {
856   gpointer *pdata;
857   guint     len;
858 };
859
860 struct _GQueue
861 {
862   GList *head;
863   GList *tail;
864   guint  length;
865 };
866
867 struct _GSList
868 {
869   gpointer data;
870   GSList *next;
871 };
872
873 struct _GString
874 {
875   gchar *str;
876   gint len;
877 };
878
879 struct _GTrashStack
880 {
881   GTrashStack *next;
882 };
883
884 struct _GTuples
885 {
886   guint len;
887 };
888
889
890 /* IEEE Standard 754 Single Precision Storage Format (gfloat):
891  *
892  *        31 30           23 22            0
893  * +--------+---------------+---------------+
894  * | s 1bit | e[30:23] 8bit | f[22:0] 23bit |
895  * +--------+---------------+---------------+
896  * B0------------------->B1------->B2-->B3-->
897  *
898  * IEEE Standard 754 Double Precision Storage Format (gdouble):
899  *
900  *        63 62            52 51            32   31            0
901  * +--------+----------------+----------------+ +---------------+
902  * | s 1bit | e[62:52] 11bit | f[51:32] 20bit | | f[31:0] 32bit |
903  * +--------+----------------+----------------+ +---------------+
904  * B0--------------->B1---------->B2--->B3---->  B4->B5->B6->B7->
905  */
906 /* subtract from biased_exponent to form base2 exponent (normal numbers) */
907 #define G_IEEE754_FLOAT_BIAS    (127)
908 #define G_IEEE754_DOUBLE_BIAS   (1023)
909 /* multiply with base2 exponent to get base10 exponent (nomal numbers) */
910 #define G_LOG_2_BASE_10         (0.30102999566398119521)
911 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
912 union _GFloatIEEE754
913 {
914   gfloat v_float;
915   struct {
916     guint mantissa : 23;
917     guint biased_exponent : 8;
918     guint sign : 1;
919   } mpn;
920 };
921 union _GDoubleIEEE754
922 {
923   gdouble v_double;
924   struct {
925     guint mantissa_low : 32;
926     guint mantissa_high : 20;
927     guint biased_exponent : 11;
928     guint sign : 1;
929   } mpn;
930 };
931 #elif G_BYTE_ORDER == G_BIG_ENDIAN
932 union _GFloatIEEE754
933 {
934   gfloat v_float;
935   struct {
936     guint sign : 1;
937     guint biased_exponent : 8;
938     guint mantissa : 23;
939   } mpn;
940 };
941 union _GDoubleIEEE754
942 {
943   gdouble v_double;
944   struct {
945     guint sign : 1;
946     guint biased_exponent : 11;
947     guint mantissa_high : 20;
948     guint mantissa_low : 32;
949   } mpn;
950 };
951 #else /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */
952 #error unknown ENDIAN type
953 #endif /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */
954
955
956 /* Doubly linked lists
957  */
958 void   g_list_push_allocator    (GAllocator     *allocator);
959 void   g_list_pop_allocator     (void);
960 GList* g_list_alloc             (void);
961 void   g_list_free              (GList          *list);
962 void   g_list_free_1            (GList          *list);
963 GList* g_list_append            (GList          *list,
964                                  gpointer        data);
965 GList* g_list_prepend           (GList          *list,
966                                  gpointer        data);
967 GList* g_list_insert            (GList          *list,
968                                  gpointer        data,
969                                  gint            position);
970 GList* g_list_insert_sorted     (GList          *list,
971                                  gpointer        data,
972                                  GCompareFunc    func);
973 GList* g_list_concat            (GList          *list1,
974                                  GList          *list2);
975 GList* g_list_remove            (GList          *list,
976                                  gconstpointer   data);
977 GList* g_list_remove_link       (GList          *list,
978                                  GList          *llink);
979 GList* g_list_delete_link       (GList          *list,
980                                  GList          *link);
981 GList* g_list_reverse           (GList          *list);
982 GList* g_list_copy              (GList          *list);
983 GList* g_list_nth               (GList          *list,
984                                  guint           n);
985 GList* g_list_find              (GList          *list,
986                                  gconstpointer   data);
987 GList* g_list_find_custom       (GList          *list,
988                                  gconstpointer   data,
989                                  GCompareFunc    func);
990 gint   g_list_position          (GList          *list,
991                                  GList          *llink);
992 gint   g_list_index             (GList          *list,
993                                  gconstpointer   data);
994 GList* g_list_last              (GList          *list);
995 GList* g_list_first             (GList          *list);
996 guint  g_list_length            (GList          *list);
997 void   g_list_foreach           (GList          *list,
998                                  GFunc           func,
999                                  gpointer        user_data);
1000 GList* g_list_sort              (GList          *list,
1001                                  GCompareFunc    compare_func);
1002 gpointer g_list_nth_data        (GList          *list,
1003                                  guint           n);
1004 #define g_list_previous(list)   ((list) ? (((GList *)(list))->prev) : NULL)
1005 #define g_list_next(list)       ((list) ? (((GList *)(list))->next) : NULL)
1006
1007
1008 /* Singly linked lists
1009  */
1010 void    g_slist_push_allocator  (GAllocator     *allocator);
1011 void    g_slist_pop_allocator   (void);
1012 GSList* g_slist_alloc           (void);
1013 void    g_slist_free            (GSList         *list);
1014 void    g_slist_free_1          (GSList         *list);
1015 GSList* g_slist_append          (GSList         *list,
1016                                  gpointer        data);
1017 GSList* g_slist_prepend         (GSList         *list,
1018                                  gpointer        data);
1019 GSList* g_slist_insert          (GSList         *list,
1020                                  gpointer        data,
1021                                  gint            position);
1022 GSList* g_slist_insert_sorted   (GSList         *list,
1023                                  gpointer        data,
1024                                  GCompareFunc    func);
1025 GSList* g_slist_concat          (GSList         *list1,
1026                                  GSList         *list2);
1027 GSList* g_slist_remove          (GSList         *list,
1028                                  gconstpointer   data);
1029 GSList* g_slist_remove_link     (GSList         *list,
1030                                  GSList         *link);
1031 GSList* g_slist_delete_link     (GSList         *list,
1032                                  GSList         *link);
1033 GSList* g_slist_reverse         (GSList         *list);
1034 GSList* g_slist_copy            (GSList         *list);
1035 GSList* g_slist_nth             (GSList         *list,
1036                                  guint           n);
1037 GSList* g_slist_find            (GSList         *list,
1038                                  gconstpointer   data);
1039 GSList* g_slist_find_custom     (GSList         *list,
1040                                  gconstpointer   data,
1041                                  GCompareFunc    func);
1042 gint    g_slist_position        (GSList         *list,
1043                                  GSList         *llink);
1044 gint    g_slist_index           (GSList         *list,
1045                                  gconstpointer   data);
1046 GSList* g_slist_last            (GSList         *list);
1047 guint   g_slist_length          (GSList         *list);
1048 void    g_slist_foreach         (GSList         *list,
1049                                  GFunc           func,
1050                                  gpointer        user_data);
1051 GSList*  g_slist_sort           (GSList          *list,
1052                                  GCompareFunc    compare_func);
1053 gpointer g_slist_nth_data       (GSList         *list,
1054                                  guint           n);
1055 #define  g_slist_next(slist)    ((slist) ? (((GSList *)(slist))->next) : NULL)
1056
1057
1058 /* Queues
1059  */
1060 GQueue*  g_queue_new            (void);
1061 void     g_queue_free           (GQueue  *queue);
1062 void     g_queue_push_head      (GQueue  *queue,
1063                                  gpointer data);
1064 void     g_queue_push_tail      (GQueue  *queue,
1065                                  gpointer data);
1066 gpointer g_queue_pop_head       (GQueue  *queue);
1067 gpointer g_queue_pop_tail       (GQueue  *queue);
1068 gboolean g_queue_is_empty       (GQueue  *queue);
1069 gpointer g_queue_peek_head      (GQueue  *queue);
1070 gpointer g_queue_peek_tail      (GQueue  *queue);
1071 void     g_queue_push_head_link (GQueue  *queue,
1072                                  GList   *link);
1073 void     g_queue_push_tail_link (GQueue  *queue,
1074                                  GList   *link);
1075 GList*   g_queue_pop_head_link  (GQueue  *queue);
1076 GList*   g_queue_pop_tail_link  (GQueue  *queue);
1077
1078 /* Hash tables
1079  */
1080 GHashTable* g_hash_table_new            (GHashFunc       hash_func,
1081                                          GCompareFunc    key_compare_func);
1082 void        g_hash_table_destroy        (GHashTable     *hash_table);
1083 void        g_hash_table_insert         (GHashTable     *hash_table,
1084                                          gpointer        key,
1085                                          gpointer        value);
1086 void        g_hash_table_remove         (GHashTable     *hash_table,
1087                                          gconstpointer   key);
1088 gpointer    g_hash_table_lookup         (GHashTable     *hash_table,
1089                                          gconstpointer   key);
1090 gboolean    g_hash_table_lookup_extended(GHashTable     *hash_table,
1091                                          gconstpointer   lookup_key,
1092                                          gpointer       *orig_key,
1093                                          gpointer       *value);
1094 void        g_hash_table_freeze         (GHashTable     *hash_table);
1095 void        g_hash_table_thaw           (GHashTable     *hash_table);
1096 void        g_hash_table_foreach        (GHashTable     *hash_table,
1097                                          GHFunc          func,
1098                                          gpointer        user_data);
1099 guint       g_hash_table_foreach_remove (GHashTable     *hash_table,
1100                                          GHRFunc         func,
1101                                          gpointer        user_data);
1102 guint       g_hash_table_size           (GHashTable     *hash_table);
1103
1104
1105 /* Caches
1106  */
1107 GCache*  g_cache_new           (GCacheNewFunc      value_new_func,
1108                                 GCacheDestroyFunc  value_destroy_func,
1109                                 GCacheDupFunc      key_dup_func,
1110                                 GCacheDestroyFunc  key_destroy_func,
1111                                 GHashFunc          hash_key_func,
1112                                 GHashFunc          hash_value_func,
1113                                 GCompareFunc       key_compare_func);
1114 void     g_cache_destroy       (GCache            *cache);
1115 gpointer g_cache_insert        (GCache            *cache,
1116                                 gpointer           key);
1117 void     g_cache_remove        (GCache            *cache,
1118                                 gconstpointer      value);
1119 void     g_cache_key_foreach   (GCache            *cache,
1120                                 GHFunc             func,
1121                                 gpointer           user_data);
1122 void     g_cache_value_foreach (GCache            *cache,
1123                                 GHFunc             func,
1124                                 gpointer           user_data);
1125
1126
1127 /* Balanced binary trees
1128  */
1129 GTree*   g_tree_new      (GCompareFunc   key_compare_func);
1130 void     g_tree_destroy  (GTree         *tree);
1131 void     g_tree_insert   (GTree         *tree,
1132                           gpointer       key,
1133                           gpointer       value);
1134 void     g_tree_remove   (GTree         *tree,
1135                           gconstpointer  key);
1136 gpointer g_tree_lookup   (GTree         *tree,
1137                           gconstpointer  key);
1138 void     g_tree_traverse (GTree         *tree,
1139                           GTraverseFunc  traverse_func,
1140                           GTraverseType  traverse_type,
1141                           gpointer       data);
1142 gpointer g_tree_search   (GTree         *tree,
1143                           GCompareFunc   search_func,
1144                           gconstpointer  data);
1145 gint     g_tree_height   (GTree         *tree);
1146 gint     g_tree_nnodes   (GTree         *tree);
1147
1148
1149
1150 /* N-way tree implementation
1151  */
1152 struct _GNode
1153 {
1154   gpointer data;
1155   GNode   *next;
1156   GNode   *prev;
1157   GNode   *parent;
1158   GNode   *children;
1159 };
1160
1161 #define  G_NODE_IS_ROOT(node)   (((GNode*) (node))->parent == NULL && \
1162                                  ((GNode*) (node))->prev == NULL && \
1163                                  ((GNode*) (node))->next == NULL)
1164 #define  G_NODE_IS_LEAF(node)   (((GNode*) (node))->children == NULL)
1165
1166 void     g_node_push_allocator  (GAllocator       *allocator);
1167 void     g_node_pop_allocator   (void);
1168 GNode*   g_node_new             (gpointer          data);
1169 void     g_node_destroy         (GNode            *root);
1170 void     g_node_unlink          (GNode            *node);
1171 GNode*   g_node_copy            (GNode            *node);
1172 GNode*   g_node_insert          (GNode            *parent,
1173                                  gint              position,
1174                                  GNode            *node);
1175 GNode*   g_node_insert_before   (GNode            *parent,
1176                                  GNode            *sibling,
1177                                  GNode            *node);
1178 GNode*   g_node_prepend         (GNode            *parent,
1179                                  GNode            *node);
1180 guint    g_node_n_nodes         (GNode            *root,
1181                                  GTraverseFlags    flags);
1182 GNode*   g_node_get_root        (GNode            *node);
1183 gboolean g_node_is_ancestor     (GNode            *node,
1184                                  GNode            *descendant);
1185 guint    g_node_depth           (GNode            *node);
1186 GNode*   g_node_find            (GNode            *root,
1187                                  GTraverseType     order,
1188                                  GTraverseFlags    flags,
1189                                  gpointer          data);
1190
1191 /* convenience macros */
1192 #define g_node_append(parent, node)                             \
1193      g_node_insert_before ((parent), NULL, (node))
1194 #define g_node_insert_data(parent, position, data)              \
1195      g_node_insert ((parent), (position), g_node_new (data))
1196 #define g_node_insert_data_before(parent, sibling, data)        \
1197      g_node_insert_before ((parent), (sibling), g_node_new (data))
1198 #define g_node_prepend_data(parent, data)                       \
1199      g_node_prepend ((parent), g_node_new (data))
1200 #define g_node_append_data(parent, data)                        \
1201      g_node_insert_before ((parent), NULL, g_node_new (data))
1202
1203 /* traversal function, assumes that `node' is root
1204  * (only traverses `node' and its subtree).
1205  * this function is just a high level interface to
1206  * low level traversal functions, optimized for speed.
1207  */
1208 void     g_node_traverse        (GNode            *root,
1209                                  GTraverseType     order,
1210                                  GTraverseFlags    flags,
1211                                  gint              max_depth,
1212                                  GNodeTraverseFunc func,
1213                                  gpointer          data);
1214
1215 /* return the maximum tree height starting with `node', this is an expensive
1216  * operation, since we need to visit all nodes. this could be shortened by
1217  * adding `guint height' to struct _GNode, but then again, this is not very
1218  * often needed, and would make g_node_insert() more time consuming.
1219  */
1220 guint    g_node_max_height       (GNode *root);
1221
1222 void     g_node_children_foreach (GNode           *node,
1223                                   GTraverseFlags   flags,
1224                                   GNodeForeachFunc func,
1225                                   gpointer         data);
1226 void     g_node_reverse_children (GNode           *node);
1227 guint    g_node_n_children       (GNode           *node);
1228 GNode*   g_node_nth_child        (GNode           *node,
1229                                   guint            n);
1230 GNode*   g_node_last_child       (GNode           *node);
1231 GNode*   g_node_find_child       (GNode           *node,
1232                                   GTraverseFlags   flags,
1233                                   gpointer         data);
1234 gint     g_node_child_position   (GNode           *node,
1235                                   GNode           *child);
1236 gint     g_node_child_index      (GNode           *node,
1237                                   gpointer         data);
1238
1239 GNode*   g_node_first_sibling    (GNode           *node);
1240 GNode*   g_node_last_sibling     (GNode           *node);
1241
1242 #define  g_node_prev_sibling(node)      ((node) ? \
1243                                          ((GNode*) (node))->prev : NULL)
1244 #define  g_node_next_sibling(node)      ((node) ? \
1245                                          ((GNode*) (node))->next : NULL)
1246 #define  g_node_first_child(node)       ((node) ? \
1247                                          ((GNode*) (node))->children : NULL)
1248
1249
1250 /* Callback maintenance functions
1251  */
1252 #define G_HOOK_FLAG_USER_SHIFT  (4)
1253 typedef enum
1254 {
1255   G_HOOK_FLAG_ACTIVE    = 1 << 0,
1256   G_HOOK_FLAG_IN_CALL   = 1 << 1,
1257   G_HOOK_FLAG_MASK      = 0x0f
1258 } GHookFlagMask;
1259
1260 #define G_HOOK_DEFERRED_DESTROY ((GHookFreeFunc) 0x01)
1261
1262 struct _GHookList
1263 {
1264   guint          seq_id;
1265   guint          hook_size;
1266   guint          is_setup : 1;
1267   GHook         *hooks;
1268   GMemChunk     *hook_memchunk;
1269   GHookFreeFunc  hook_free; /* virtual function */
1270   GHookFreeFunc  hook_destroy; /* virtual function */
1271 };
1272
1273 struct _GHook
1274 {
1275   gpointer       data;
1276   GHook         *next;
1277   GHook         *prev;
1278   guint          ref_count;
1279   guint          hook_id;
1280   guint          flags;
1281   gpointer       func;
1282   GDestroyNotify destroy;
1283 };
1284
1285 #define G_HOOK_ACTIVE(hook)             ((((GHook*) hook)->flags & \
1286                                           G_HOOK_FLAG_ACTIVE) != 0)
1287 #define G_HOOK_IN_CALL(hook)            ((((GHook*) hook)->flags & \
1288                                           G_HOOK_FLAG_IN_CALL) != 0)
1289 #define G_HOOK_IS_VALID(hook)           (((GHook*) hook)->hook_id != 0 && \
1290                                          G_HOOK_ACTIVE (hook))
1291 #define G_HOOK_IS_UNLINKED(hook)        (((GHook*) hook)->next == NULL && \
1292                                          ((GHook*) hook)->prev == NULL && \
1293                                          ((GHook*) hook)->hook_id == 0 && \
1294                                          ((GHook*) hook)->ref_count == 0)
1295
1296 void     g_hook_list_init               (GHookList              *hook_list,
1297                                          guint                   hook_size);
1298 void     g_hook_list_clear              (GHookList              *hook_list);
1299 GHook*   g_hook_alloc                   (GHookList              *hook_list);
1300 void     g_hook_free                    (GHookList              *hook_list,
1301                                          GHook                  *hook);
1302 void     g_hook_ref                     (GHookList              *hook_list,
1303                                          GHook                  *hook);
1304 void     g_hook_unref                   (GHookList              *hook_list,
1305                                          GHook                  *hook);
1306 gboolean g_hook_destroy                 (GHookList              *hook_list,
1307                                          guint                   hook_id);
1308 void     g_hook_destroy_link            (GHookList              *hook_list,
1309                                          GHook                  *hook);
1310 void     g_hook_prepend                 (GHookList              *hook_list,
1311                                          GHook                  *hook);
1312 void     g_hook_insert_before           (GHookList              *hook_list,
1313                                          GHook                  *sibling,
1314                                          GHook                  *hook);
1315 void     g_hook_insert_sorted           (GHookList              *hook_list,
1316                                          GHook                  *hook,
1317                                          GHookCompareFunc        func);
1318 GHook*   g_hook_get                     (GHookList              *hook_list,
1319                                          guint                   hook_id);
1320 GHook*   g_hook_find                    (GHookList              *hook_list,
1321                                          gboolean                need_valids,
1322                                          GHookFindFunc           func,
1323                                          gpointer                data);
1324 GHook*   g_hook_find_data               (GHookList              *hook_list,
1325                                          gboolean                need_valids,
1326                                          gpointer                data);
1327 GHook*   g_hook_find_func               (GHookList              *hook_list,
1328                                          gboolean                need_valids,
1329                                          gpointer                func);
1330 GHook*   g_hook_find_func_data          (GHookList              *hook_list,
1331                                          gboolean                need_valids,
1332                                          gpointer                func,
1333                                          gpointer                data);
1334 /* return the first valid hook, and increment its reference count */
1335 GHook*   g_hook_first_valid             (GHookList              *hook_list,
1336                                          gboolean                may_be_in_call);
1337 /* return the next valid hook with incremented reference count, and
1338  * decrement the reference count of the original hook
1339  */
1340 GHook*   g_hook_next_valid              (GHookList              *hook_list,
1341                                          GHook                  *hook,
1342                                          gboolean                may_be_in_call);
1343
1344 /* GHookCompareFunc implementation to insert hooks sorted by their id */
1345 gint     g_hook_compare_ids             (GHook                  *new_hook,
1346                                          GHook                  *sibling);
1347
1348 /* convenience macros */
1349 #define  g_hook_append( hook_list, hook )  \
1350      g_hook_insert_before ((hook_list), NULL, (hook))
1351
1352 /* invoke all valid hooks with the (*GHookFunc) signature.
1353  */
1354 void     g_hook_list_invoke             (GHookList              *hook_list,
1355                                          gboolean                may_recurse);
1356 /* invoke all valid hooks with the (*GHookCheckFunc) signature,
1357  * and destroy the hook if FALSE is returned.
1358  */
1359 void     g_hook_list_invoke_check       (GHookList              *hook_list,
1360                                          gboolean                may_recurse);
1361 /* invoke a marshaller on all valid hooks.
1362  */
1363 void     g_hook_list_marshal            (GHookList              *hook_list,
1364                                          gboolean                may_recurse,
1365                                          GHookMarshaller         marshaller,
1366                                          gpointer                data);
1367 void     g_hook_list_marshal_check      (GHookList              *hook_list,
1368                                          gboolean                may_recurse,
1369                                          GHookCheckMarshaller    marshaller,
1370                                          gpointer                data);
1371
1372
1373 /* Fatal error handlers.
1374  * g_on_error_query() will prompt the user to either
1375  * [E]xit, [H]alt, [P]roceed or show [S]tack trace.
1376  * g_on_error_stack_trace() invokes gdb, which attaches to the current
1377  * process and shows a stack trace.
1378  * These function may cause different actions on non-unix platforms.
1379  * The prg_name arg is required by gdb to find the executable, if it is
1380  * passed as NULL, g_on_error_query() will try g_get_prgname().
1381  */
1382 void g_on_error_query (const gchar *prg_name);
1383 void g_on_error_stack_trace (const gchar *prg_name);
1384
1385
1386 /* Logging mechanism
1387  */
1388 extern          const gchar             *g_log_domain_glib;
1389 guint           g_log_set_handler       (const gchar    *log_domain,
1390                                          GLogLevelFlags  log_levels,
1391                                          GLogFunc        log_func,
1392                                          gpointer        user_data);
1393 void            g_log_remove_handler    (const gchar    *log_domain,
1394                                          guint           handler_id);
1395 void            g_log_default_handler   (const gchar    *log_domain,
1396                                          GLogLevelFlags  log_level,
1397                                          const gchar    *message,
1398                                          gpointer        unused_data);
1399 void            g_log                   (const gchar    *log_domain,
1400                                          GLogLevelFlags  log_level,
1401                                          const gchar    *format,
1402                                          ...) G_GNUC_PRINTF (3, 4);
1403 void            g_logv                  (const gchar    *log_domain,
1404                                          GLogLevelFlags  log_level,
1405                                          const gchar    *format,
1406                                          va_list         args);
1407 GLogLevelFlags  g_log_set_fatal_mask    (const gchar    *log_domain,
1408                                          GLogLevelFlags  fatal_mask);
1409 GLogLevelFlags  g_log_set_always_fatal  (GLogLevelFlags  fatal_mask);
1410 #ifndef G_LOG_DOMAIN
1411 #define G_LOG_DOMAIN    ((gchar*) 0)
1412 #endif  /* G_LOG_DOMAIN */
1413 #ifdef  __GNUC__
1414 #define g_error(format, args...)        g_log (G_LOG_DOMAIN, \
1415                                                G_LOG_LEVEL_ERROR, \
1416                                                format, ##args)
1417 #define g_message(format, args...)      g_log (G_LOG_DOMAIN, \
1418                                                G_LOG_LEVEL_MESSAGE, \
1419                                                format, ##args)
1420 #define g_warning(format, args...)      g_log (G_LOG_DOMAIN, \
1421                                                G_LOG_LEVEL_WARNING, \
1422                                                format, ##args)
1423 #else   /* !__GNUC__ */
1424 static void
1425 g_error (const gchar *format,
1426          ...)
1427 {
1428   va_list args;
1429   va_start (args, format);
1430   g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR, format, args);
1431   va_end (args);
1432 }
1433 static void
1434 g_message (const gchar *format,
1435            ...)
1436 {
1437   va_list args;
1438   va_start (args, format);
1439   g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, format, args);
1440   va_end (args);
1441 }
1442 static void
1443 g_warning (const gchar *format,
1444            ...)
1445 {
1446   va_list args;
1447   va_start (args, format);
1448   g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, format, args);
1449   va_end (args);
1450 }
1451 #endif  /* !__GNUC__ */
1452
1453 typedef void    (*GPrintFunc)           (const gchar    *string);
1454 void            g_print                 (const gchar    *format,
1455                                          ...) G_GNUC_PRINTF (1, 2);
1456 GPrintFunc      g_set_print_handler     (GPrintFunc      func);
1457 void            g_printerr              (const gchar    *format,
1458                                          ...) G_GNUC_PRINTF (1, 2);
1459 GPrintFunc      g_set_printerr_handler  (GPrintFunc      func);
1460
1461 /* deprecated compatibility functions, use g_log_set_handler() instead */
1462 typedef void            (*GErrorFunc)           (const gchar *str);
1463 typedef void            (*GWarningFunc)         (const gchar *str);
1464 GErrorFunc   g_set_error_handler   (GErrorFunc   func);
1465 GWarningFunc g_set_warning_handler (GWarningFunc func);
1466 GPrintFunc   g_set_message_handler (GPrintFunc func);
1467
1468
1469 /* Memory allocation and debugging
1470  */
1471 #ifdef USE_DMALLOC
1472
1473 #define g_malloc(size)       ((gpointer) MALLOC (size))
1474 #define g_malloc0(size)      ((gpointer) CALLOC (char, size))
1475 #define g_realloc(mem,size)  ((gpointer) REALLOC (mem, char, size))
1476 #define g_free(mem)          FREE (mem)
1477
1478 #else /* !USE_DMALLOC */
1479
1480 gpointer g_malloc      (gulong    size);
1481 gpointer g_malloc0     (gulong    size);
1482 gpointer g_realloc     (gpointer  mem,
1483                         gulong    size);
1484 void     g_free        (gpointer  mem);
1485
1486 #endif /* !USE_DMALLOC */
1487
1488 void     g_mem_profile (void);
1489 void     g_mem_check   (gpointer  mem);
1490
1491 /* Generic allocators
1492  */
1493 GAllocator* g_allocator_new   (const gchar  *name,
1494                                guint         n_preallocs);
1495 void        g_allocator_free  (GAllocator   *allocator);
1496
1497 #define G_ALLOCATOR_LIST        (1)
1498 #define G_ALLOCATOR_SLIST       (2)
1499 #define G_ALLOCATOR_NODE        (3)
1500
1501
1502 /* "g_mem_chunk_new" creates a new memory chunk.
1503  * Memory chunks are used to allocate pieces of memory which are
1504  *  always the same size. Lists are a good example of such a data type.
1505  * The memory chunk allocates and frees blocks of memory as needed.
1506  *  Just be sure to call "g_mem_chunk_free" and not "g_free" on data
1507  *  allocated in a mem chunk. ("g_free" will most likely cause a seg
1508  *  fault...somewhere).
1509  *
1510  * Oh yeah, GMemChunk is an opaque data type. (You don't really
1511  *  want to know what's going on inside do you?)
1512  */
1513
1514 /* ALLOC_ONLY MemChunk's can only allocate memory. The free operation
1515  *  is interpreted as a no op. ALLOC_ONLY MemChunk's save 4 bytes per
1516  *  atom. (They are also useful for lists which use MemChunk to allocate
1517  *  memory but are also part of the MemChunk implementation).
1518  * ALLOC_AND_FREE MemChunk's can allocate and free memory.
1519  */
1520
1521 #define G_ALLOC_ONLY      1
1522 #define G_ALLOC_AND_FREE  2
1523
1524 GMemChunk* g_mem_chunk_new     (gchar     *name,
1525                                 gint       atom_size,
1526                                 gulong     area_size,
1527                                 gint       type);
1528 void       g_mem_chunk_destroy (GMemChunk *mem_chunk);
1529 gpointer   g_mem_chunk_alloc   (GMemChunk *mem_chunk);
1530 gpointer   g_mem_chunk_alloc0  (GMemChunk *mem_chunk);
1531 void       g_mem_chunk_free    (GMemChunk *mem_chunk,
1532                                 gpointer   mem);
1533 void       g_mem_chunk_clean   (GMemChunk *mem_chunk);
1534 void       g_mem_chunk_reset   (GMemChunk *mem_chunk);
1535 void       g_mem_chunk_print   (GMemChunk *mem_chunk);
1536 void       g_mem_chunk_info    (void);
1537
1538 /* Ah yes...we have a "g_blow_chunks" function.
1539  * "g_blow_chunks" simply compresses all the chunks. This operation
1540  *  consists of freeing every memory area that should be freed (but
1541  *  which we haven't gotten around to doing yet). And, no,
1542  *  "g_blow_chunks" doesn't follow the naming scheme, but it is a
1543  *  much better name than "g_mem_chunk_clean_all" or something
1544  *  similar.
1545  */
1546 void g_blow_chunks (void);
1547
1548
1549 /* Timer
1550  */
1551
1552 #define G_MICROSEC 1000000
1553
1554 GTimer* g_timer_new     (void);
1555 void    g_timer_destroy (GTimer  *timer);
1556 void    g_timer_start   (GTimer  *timer);
1557 void    g_timer_stop    (GTimer  *timer);
1558 void    g_timer_reset   (GTimer  *timer);
1559 gdouble g_timer_elapsed (GTimer  *timer,
1560                          gulong  *microseconds);
1561 void    g_usleep        (gulong microseconds);
1562
1563 /* String utility functions that modify a string argument or
1564  * return a constant string that must not be freed.
1565  */
1566 #define  G_STR_DELIMITERS       "_-|> <."
1567 gchar*   g_strdelimit           (gchar       *string,
1568                                  const gchar *delimiters,
1569                                  gchar        new_delimiter);
1570 gdouble  g_strtod               (const gchar *nptr,
1571                                  gchar      **endptr);
1572 gchar*   g_strerror             (gint         errnum);
1573 gchar*   g_strsignal            (gint         signum);
1574 gint     g_strcasecmp           (const gchar *s1,
1575                                  const gchar *s2);
1576 gint     g_strncasecmp          (const gchar *s1,
1577                                  const gchar *s2,
1578                                  guint        n);
1579 void     g_strdown              (gchar       *string);
1580 void     g_strup                (gchar       *string);
1581 void     g_strreverse           (gchar       *string);
1582 /* removes leading spaces */
1583 gchar*   g_strchug              (gchar        *string);
1584 /* removes trailing spaces */
1585 gchar*  g_strchomp              (gchar        *string);
1586 /* removes leading & trailing spaces */
1587 #define g_strstrip( string )    g_strchomp (g_strchug (string))
1588
1589 /* String utility functions that return a newly allocated string which
1590  * ought to be freed with g_free from the caller at some point.
1591  */
1592 gchar*   g_strdup               (const gchar *str);
1593 gchar*   g_strdup_printf        (const gchar *format,
1594                                  ...) G_GNUC_PRINTF (1, 2);
1595 gchar*   g_strdup_vprintf       (const gchar *format,
1596                                  va_list      args);
1597 gchar*   g_strndup              (const gchar *str,
1598                                  guint        n);
1599 gchar*   g_strnfill             (guint        length,
1600                                  gchar        fill_char);
1601 gchar*   g_strconcat            (const gchar *string1,
1602                                  ...); /* NULL terminated */
1603 gchar*   g_strjoin              (const gchar  *separator,
1604                                  ...); /* NULL terminated */
1605 /* Make a copy of a string interpreting C string -style escape
1606  * sequences. Inverse of g_strescape. The recognized sequences are \b
1607  * \f \n \r \t \\ \" and the octal format.
1608  */
1609 gchar*   g_strcompress          (const gchar *source);
1610
1611 /* Convert between the operating system (or C runtime)
1612  * representation of file names and UTF-8.
1613  */
1614 gchar*   g_filename_to_utf8 (const gchar *opsysstring);
1615 gchar*   g_filename_from_utf8 (const gchar *utf8string);
1616
1617 /* Copy a string escaping nonprintable characters like in C strings.
1618  * Inverse of g_strcompress. The exceptions parameter, if non-NULL, points
1619  * to a string containing characters that are not to be escaped.
1620  *
1621  * Deprecated API: gchar* g_strescape (const gchar *source);
1622  * Luckily this function wasn't used much, using NULL as second parameter
1623  * provides mostly identical semantics.
1624  */
1625 gchar*   g_strescape            (const gchar *source,
1626                                  const gchar *exceptions);
1627
1628 gpointer g_memdup               (gconstpointer mem,
1629                                  guint         byte_size);
1630
1631 /* NULL terminated string arrays.
1632  * g_strsplit() splits up string into max_tokens tokens at delim and
1633  * returns a newly allocated string array.
1634  * g_strjoinv() concatenates all of str_array's strings, sliding in an
1635  * optional separator, the returned string is newly allocated.
1636  * g_strfreev() frees the array itself and all of its strings.
1637  */
1638 gchar**  g_strsplit             (const gchar  *string,
1639                                  const gchar  *delimiter,
1640                                  gint          max_tokens);
1641 gchar*   g_strjoinv             (const gchar  *separator,
1642                                  gchar       **str_array);
1643 void     g_strfreev             (gchar       **str_array);
1644
1645
1646
1647 /* calculate a string size, guarranteed to fit format + args.
1648  */
1649 guint   g_printf_string_upper_bound (const gchar* format,
1650                                      va_list      args);
1651
1652
1653 /* Retrive static string info
1654  */
1655 gchar*  g_get_user_name         (void);
1656 gchar*  g_get_real_name         (void);
1657 gchar*  g_get_home_dir          (void);
1658 gchar*  g_get_tmp_dir           (void);
1659 gchar*  g_get_prgname           (void);
1660 void    g_set_prgname           (const gchar *prgname);
1661
1662
1663 /* Miscellaneous utility functions
1664  */
1665 guint   g_parse_debug_string    (const gchar *string,
1666                                  GDebugKey   *keys,
1667                                  guint        nkeys);
1668 gint    g_snprintf              (gchar       *string,
1669                                  gulong       n,
1670                                  gchar const *format,
1671                                  ...) G_GNUC_PRINTF (3, 4);
1672 gint    g_vsnprintf             (gchar       *string,
1673                                  gulong       n,
1674                                  gchar const *format,
1675                                  va_list      args);
1676 gchar*  g_basename              (const gchar *file_name);
1677 /* Check if a file name is an absolute path */
1678 gboolean g_path_is_absolute     (const gchar *file_name);
1679 /* In case of absolute paths, skip the root part */
1680 gchar*  g_path_skip_root        (gchar       *file_name);
1681
1682 /* strings are newly allocated with g_malloc() */
1683 gchar*  g_dirname               (const gchar *file_name);
1684 gchar*  g_get_current_dir       (void);
1685
1686 /* return the environment string for the variable. The returned memory
1687  * must not be freed. */
1688 gchar*  g_getenv                (const gchar *variable);
1689
1690 /* we use a GLib function as a replacement for ATEXIT, so
1691  * the programmer is not required to check the return value
1692  * (if there is any in the implementation) and doesn't encounter
1693  * missing include files.
1694  */
1695 void    g_atexit                (GVoidFunc    func);
1696
1697
1698 /* Bit tests
1699  */
1700 G_INLINE_FUNC gint      g_bit_nth_lsf (guint32 mask,
1701                                        gint    nth_bit);
1702 #ifdef  G_CAN_INLINE
1703 G_INLINE_FUNC gint
1704 g_bit_nth_lsf (guint32 mask,
1705                gint    nth_bit)
1706 {
1707   do
1708     {
1709       nth_bit++;
1710       if (mask & (1 << (guint) nth_bit))
1711         return nth_bit;
1712     }
1713   while (nth_bit < 32);
1714   return -1;
1715 }
1716 #endif  /* G_CAN_INLINE */
1717
1718 G_INLINE_FUNC gint      g_bit_nth_msf (guint32 mask,
1719                                        gint    nth_bit);
1720 #ifdef G_CAN_INLINE
1721 G_INLINE_FUNC gint
1722 g_bit_nth_msf (guint32 mask,
1723                gint    nth_bit)
1724 {
1725   if (nth_bit < 0)
1726     nth_bit = 32;
1727   do
1728     {
1729       nth_bit--;
1730       if (mask & (1 << (guint) nth_bit))
1731         return nth_bit;
1732     }
1733   while (nth_bit > 0);
1734   return -1;
1735 }
1736 #endif  /* G_CAN_INLINE */
1737
1738 G_INLINE_FUNC guint     g_bit_storage (guint number);
1739 #ifdef G_CAN_INLINE
1740 G_INLINE_FUNC guint
1741 g_bit_storage (guint number)
1742 {
1743   register guint n_bits = 0;
1744   
1745   do
1746     {
1747       n_bits++;
1748       number >>= 1;
1749     }
1750   while (number);
1751   return n_bits;
1752 }
1753 #endif  /* G_CAN_INLINE */
1754
1755
1756 /* Trash Stacks
1757  * elements need to be >= sizeof (gpointer)
1758  */
1759 G_INLINE_FUNC void      g_trash_stack_push      (GTrashStack **stack_p,
1760                                                  gpointer      data_p);
1761 #ifdef G_CAN_INLINE
1762 G_INLINE_FUNC void
1763 g_trash_stack_push (GTrashStack **stack_p,
1764                     gpointer      data_p)
1765 {
1766   GTrashStack *data = (GTrashStack *) data_p;
1767
1768   data->next = *stack_p;
1769   *stack_p = data;
1770 }
1771 #endif  /* G_CAN_INLINE */
1772
1773 G_INLINE_FUNC gpointer  g_trash_stack_pop       (GTrashStack **stack_p);
1774 #ifdef G_CAN_INLINE
1775 G_INLINE_FUNC gpointer
1776 g_trash_stack_pop (GTrashStack **stack_p)
1777 {
1778   GTrashStack *data;
1779
1780   data = *stack_p;
1781   if (data)
1782     {
1783       *stack_p = data->next;
1784       /* NULLify private pointer here, most platforms store NULL as
1785        * subsequent 0 bytes
1786        */
1787       data->next = NULL;
1788     }
1789
1790   return data;
1791 }
1792 #endif  /* G_CAN_INLINE */
1793
1794 G_INLINE_FUNC gpointer  g_trash_stack_peek      (GTrashStack **stack_p);
1795 #ifdef G_CAN_INLINE
1796 G_INLINE_FUNC gpointer
1797 g_trash_stack_peek (GTrashStack **stack_p)
1798 {
1799   GTrashStack *data;
1800
1801   data = *stack_p;
1802
1803   return data;
1804 }
1805 #endif  /* G_CAN_INLINE */
1806
1807 G_INLINE_FUNC guint     g_trash_stack_height    (GTrashStack **stack_p);
1808 #ifdef G_CAN_INLINE
1809 G_INLINE_FUNC guint
1810 g_trash_stack_height (GTrashStack **stack_p)
1811 {
1812   GTrashStack *data;
1813   guint i = 0;
1814
1815   for (data = *stack_p; data; data = data->next)
1816     i++;
1817
1818   return i;
1819 }
1820 #endif  /* G_CAN_INLINE */
1821
1822
1823 /* String Chunks
1824  */
1825 GStringChunk* g_string_chunk_new           (gint size);
1826 void          g_string_chunk_free          (GStringChunk *chunk);
1827 gchar*        g_string_chunk_insert        (GStringChunk *chunk,
1828                                             const gchar  *string);
1829 gchar*        g_string_chunk_insert_const  (GStringChunk *chunk,
1830                                             const gchar  *string);
1831
1832
1833 /* Strings
1834  */
1835 GString*     g_string_new               (const gchar     *init);
1836 GString*     g_string_sized_new         (guint            dfl_size);
1837 void         g_string_free              (GString         *string,
1838                                          gboolean         free_segment);
1839 GString*     g_string_assign            (GString         *string,
1840                                          const gchar     *rval);
1841 GString*     g_string_truncate          (GString         *string,
1842                                          gint             len);
1843 GString*     g_string_insert_len        (GString         *string,
1844                                          gint             pos,
1845                                          const gchar     *val,
1846                                          gint             len);
1847 GString*     g_string_append            (GString         *string,
1848                                          const gchar     *val);
1849 GString*     g_string_append_len        (GString         *string,
1850                                          const gchar     *val,
1851                                          gint             len);
1852 GString*     g_string_append_c          (GString         *string,
1853                                          gchar            c);
1854 GString*     g_string_prepend           (GString         *string,
1855                                          const gchar     *val);
1856 GString*     g_string_prepend_c         (GString         *string,
1857                                          gchar            c);
1858 GString*     g_string_prepend_len       (GString         *string,
1859                                          const gchar     *val,
1860                                          gint             len);
1861 GString*     g_string_insert            (GString         *string,
1862                                          gint             pos,
1863                                          const gchar     *val);
1864 GString*     g_string_insert_c          (GString         *string,
1865                                          gint             pos,
1866                                          gchar            c);
1867 GString*     g_string_erase             (GString         *string,
1868                                          gint             pos,
1869                                          gint             len);
1870 GString*     g_string_down              (GString         *string);
1871 GString*     g_string_up                (GString         *string);
1872 void         g_string_sprintf           (GString         *string,
1873                                          const gchar     *format,
1874                                          ...) G_GNUC_PRINTF (2, 3);
1875 void         g_string_sprintfa          (GString         *string,
1876                                          const gchar     *format,
1877                                          ...) G_GNUC_PRINTF (2, 3);
1878
1879
1880 /* Resizable arrays, remove fills any cleared spot and shortens the
1881  * array, while preserving the order. remove_fast will distort the
1882  * order by moving the last element to the position of the removed 
1883  */
1884
1885 #define g_array_append_val(a,v)   g_array_append_vals (a, &v, 1)
1886 #define g_array_prepend_val(a,v)  g_array_prepend_vals (a, &v, 1)
1887 #define g_array_insert_val(a,i,v) g_array_insert_vals (a, i, &v, 1)
1888 #define g_array_index(a,t,i)      (((t*) (a)->data) [(i)])
1889
1890 GArray* g_array_new               (gboolean         zero_terminated,
1891                                    gboolean         clear,
1892                                    guint            element_size);
1893 GArray* g_array_sized_new         (gboolean         zero_terminated,
1894                                    gboolean         clear,
1895                                    guint            element_size,
1896                                    guint            reserved_size);
1897 void    g_array_free              (GArray          *array,
1898                                    gboolean         free_segment);
1899 GArray* g_array_append_vals       (GArray          *array,
1900                                    gconstpointer    data,
1901                                    guint            len);
1902 GArray* g_array_prepend_vals      (GArray          *array,
1903                                    gconstpointer    data,
1904                                    guint            len);
1905 GArray* g_array_insert_vals       (GArray          *array,
1906                                    guint            index,
1907                                    gconstpointer    data,
1908                                    guint            len);
1909 GArray* g_array_set_size          (GArray          *array,
1910                                    guint            length);
1911 GArray* g_array_remove_index      (GArray          *array,
1912                                    guint            index);
1913 GArray* g_array_remove_index_fast (GArray          *array,
1914                                    guint            index);
1915
1916 /* Resizable pointer array.  This interface is much less complicated
1917  * than the above.  Add appends appends a pointer.  Remove fills any
1918  * cleared spot and shortens the array. remove_fast will again distort
1919  * order.  
1920  */
1921 #define     g_ptr_array_index(array,index) (array->pdata)[index]
1922 GPtrArray*  g_ptr_array_new                (void);
1923 GPtrArray*  g_ptr_array_sized_new          (guint        reserved_size);
1924 void        g_ptr_array_free               (GPtrArray   *array,
1925                                             gboolean     free_seg);
1926 void        g_ptr_array_set_size           (GPtrArray   *array,
1927                                             gint         length);
1928 gpointer    g_ptr_array_remove_index       (GPtrArray   *array,
1929                                             guint        index);
1930 gpointer    g_ptr_array_remove_index_fast  (GPtrArray   *array,
1931                                             guint        index);
1932 gboolean    g_ptr_array_remove             (GPtrArray   *array,
1933                                             gpointer     data);
1934 gboolean    g_ptr_array_remove_fast        (GPtrArray   *array,
1935                                             gpointer     data);
1936 void        g_ptr_array_add                (GPtrArray   *array,
1937                                             gpointer     data);
1938
1939 /* Byte arrays, an array of guint8.  Implemented as a GArray,
1940  * but type-safe.
1941  */
1942
1943 GByteArray* g_byte_array_new               (void);
1944 GByteArray* g_byte_array_sized_new         (guint        reserved_size);
1945 void        g_byte_array_free              (GByteArray   *array,
1946                                             gboolean      free_segment);
1947 GByteArray* g_byte_array_append            (GByteArray   *array,
1948                                             const guint8 *data,
1949                                             guint         len);
1950 GByteArray* g_byte_array_prepend           (GByteArray   *array,
1951                                             const guint8 *data,
1952                                             guint         len);
1953 GByteArray* g_byte_array_set_size          (GByteArray   *array,
1954                                             guint         length);
1955 GByteArray* g_byte_array_remove_index      (GByteArray   *array,
1956                                             guint         index);
1957 GByteArray* g_byte_array_remove_index_fast (GByteArray   *array,
1958                                             guint         index);
1959
1960
1961 /* Hash Functions
1962  */
1963 gint  g_str_equal (gconstpointer   v,
1964                    gconstpointer   v2);
1965 guint g_str_hash  (gconstpointer   v);
1966
1967 gint  g_int_equal (gconstpointer   v,
1968                    gconstpointer   v2);
1969 guint g_int_hash  (gconstpointer   v);
1970
1971 /* This "hash" function will just return the key's adress as an
1972  * unsigned integer. Useful for hashing on plain adresses or
1973  * simple integer values.
1974  * passing NULL into g_hash_table_new() as GHashFunc has the
1975  * same effect as passing g_direct_hash().
1976  */
1977 guint g_direct_hash  (gconstpointer v);
1978 gint  g_direct_equal (gconstpointer v,
1979                       gconstpointer v2);
1980
1981
1982 /* Quarks (string<->id association)
1983  */
1984 GQuark    g_quark_try_string            (const gchar    *string);
1985 GQuark    g_quark_from_static_string    (const gchar    *string);
1986 GQuark    g_quark_from_string           (const gchar    *string);
1987 gchar*    g_quark_to_string             (GQuark          quark);
1988
1989
1990 /* Keyed Data List
1991  */
1992 void      g_datalist_init                (GData          **datalist);
1993 void      g_datalist_clear               (GData          **datalist);
1994 gpointer  g_datalist_id_get_data         (GData          **datalist,
1995                                           GQuark           key_id);
1996 void      g_datalist_id_set_data_full    (GData          **datalist,
1997                                           GQuark           key_id,
1998                                           gpointer         data,
1999                                           GDestroyNotify   destroy_func);
2000 gpointer  g_datalist_id_remove_no_notify (GData          **datalist,
2001                                           GQuark           key_id);
2002 void      g_datalist_foreach             (GData          **datalist,
2003                                           GDataForeachFunc func,
2004                                           gpointer         user_data);
2005 #define   g_datalist_id_set_data(dl, q, d)      \
2006      g_datalist_id_set_data_full ((dl), (q), (d), NULL)
2007 #define   g_datalist_id_remove_data(dl, q)      \
2008      g_datalist_id_set_data ((dl), (q), NULL)
2009 #define   g_datalist_get_data(dl, k)            \
2010      (g_datalist_id_get_data ((dl), g_quark_try_string (k)))
2011 #define   g_datalist_set_data_full(dl, k, d, f) \
2012      g_datalist_id_set_data_full ((dl), g_quark_from_string (k), (d), (f))
2013 #define   g_datalist_remove_no_notify(dl, k)    \
2014      g_datalist_id_remove_no_notify ((dl), g_quark_try_string (k))
2015 #define   g_datalist_set_data(dl, k, d)         \
2016      g_datalist_set_data_full ((dl), (k), (d), NULL)
2017 #define   g_datalist_remove_data(dl, k)         \
2018      g_datalist_id_set_data ((dl), g_quark_try_string (k), NULL)
2019
2020
2021 /* Location Associated Keyed Data
2022  */
2023 void      g_dataset_destroy             (gconstpointer    dataset_location);
2024 gpointer  g_dataset_id_get_data         (gconstpointer    dataset_location,
2025                                          GQuark           key_id);
2026 void      g_dataset_id_set_data_full    (gconstpointer    dataset_location,
2027                                          GQuark           key_id,
2028                                          gpointer         data,
2029                                          GDestroyNotify   destroy_func);
2030 gpointer  g_dataset_id_remove_no_notify (gconstpointer    dataset_location,
2031                                          GQuark           key_id);
2032 void      g_dataset_foreach             (gconstpointer    dataset_location,
2033                                          GDataForeachFunc func,
2034                                          gpointer         user_data);
2035 #define   g_dataset_id_set_data(l, k, d)        \
2036      g_dataset_id_set_data_full ((l), (k), (d), NULL)
2037 #define   g_dataset_id_remove_data(l, k)        \
2038      g_dataset_id_set_data ((l), (k), NULL)
2039 #define   g_dataset_get_data(l, k)              \
2040      (g_dataset_id_get_data ((l), g_quark_try_string (k)))
2041 #define   g_dataset_set_data_full(l, k, d, f)   \
2042      g_dataset_id_set_data_full ((l), g_quark_from_string (k), (d), (f))
2043 #define   g_dataset_remove_no_notify(l, k)      \
2044      g_dataset_id_remove_no_notify ((l), g_quark_try_string (k))
2045 #define   g_dataset_set_data(l, k, d)           \
2046      g_dataset_set_data_full ((l), (k), (d), NULL)
2047 #define   g_dataset_remove_data(l, k)           \
2048      g_dataset_id_set_data ((l), g_quark_try_string (k), NULL)
2049
2050
2051 /* GScanner: Flexible lexical scanner for general purpose.
2052  */
2053
2054 /* Character sets */
2055 #define G_CSET_A_2_Z    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2056 #define G_CSET_a_2_z    "abcdefghijklmnopqrstuvwxyz"
2057 #define G_CSET_LATINC   "\300\301\302\303\304\305\306"\
2058                         "\307\310\311\312\313\314\315\316\317\320"\
2059                         "\321\322\323\324\325\326"\
2060                         "\330\331\332\333\334\335\336"
2061 #define G_CSET_LATINS   "\337\340\341\342\343\344\345\346"\
2062                         "\347\350\351\352\353\354\355\356\357\360"\
2063                         "\361\362\363\364\365\366"\
2064                         "\370\371\372\373\374\375\376\377"
2065
2066 /* Error types */
2067 typedef enum
2068 {
2069   G_ERR_UNKNOWN,
2070   G_ERR_UNEXP_EOF,
2071   G_ERR_UNEXP_EOF_IN_STRING,
2072   G_ERR_UNEXP_EOF_IN_COMMENT,
2073   G_ERR_NON_DIGIT_IN_CONST,
2074   G_ERR_DIGIT_RADIX,
2075   G_ERR_FLOAT_RADIX,
2076   G_ERR_FLOAT_MALFORMED
2077 } GErrorType;
2078
2079 /* Token types */
2080 typedef enum
2081 {
2082   G_TOKEN_EOF                   =   0,
2083   
2084   G_TOKEN_LEFT_PAREN            = '(',
2085   G_TOKEN_RIGHT_PAREN           = ')',
2086   G_TOKEN_LEFT_CURLY            = '{',
2087   G_TOKEN_RIGHT_CURLY           = '}',
2088   G_TOKEN_LEFT_BRACE            = '[',
2089   G_TOKEN_RIGHT_BRACE           = ']',
2090   G_TOKEN_EQUAL_SIGN            = '=',
2091   G_TOKEN_COMMA                 = ',',
2092   
2093   G_TOKEN_NONE                  = 256,
2094   
2095   G_TOKEN_ERROR,
2096   
2097   G_TOKEN_CHAR,
2098   G_TOKEN_BINARY,
2099   G_TOKEN_OCTAL,
2100   G_TOKEN_INT,
2101   G_TOKEN_HEX,
2102   G_TOKEN_FLOAT,
2103   G_TOKEN_STRING,
2104   
2105   G_TOKEN_SYMBOL,
2106   G_TOKEN_IDENTIFIER,
2107   G_TOKEN_IDENTIFIER_NULL,
2108   
2109   G_TOKEN_COMMENT_SINGLE,
2110   G_TOKEN_COMMENT_MULTI,
2111   G_TOKEN_LAST
2112 } GTokenType;
2113
2114 union   _GTokenValue
2115 {
2116   gpointer      v_symbol;
2117   gchar         *v_identifier;
2118   gulong        v_binary;
2119   gulong        v_octal;
2120   gulong        v_int;
2121   gdouble       v_float;
2122   gulong        v_hex;
2123   gchar         *v_string;
2124   gchar         *v_comment;
2125   guchar        v_char;
2126   guint         v_error;
2127 };
2128
2129 struct  _GScannerConfig
2130 {
2131   /* Character sets
2132    */
2133   gchar         *cset_skip_characters;          /* default: " \t\n" */
2134   gchar         *cset_identifier_first;
2135   gchar         *cset_identifier_nth;
2136   gchar         *cpair_comment_single;          /* default: "#\n" */
2137   
2138   /* Should symbol lookup work case sensitive?
2139    */
2140   guint         case_sensitive : 1;
2141   
2142   /* Boolean values to be adjusted "on the fly"
2143    * to configure scanning behaviour.
2144    */
2145   guint         skip_comment_multi : 1;         /* C like comment */
2146   guint         skip_comment_single : 1;        /* single line comment */
2147   guint         scan_comment_multi : 1;         /* scan multi line comments? */
2148   guint         scan_identifier : 1;
2149   guint         scan_identifier_1char : 1;
2150   guint         scan_identifier_NULL : 1;
2151   guint         scan_symbols : 1;
2152   guint         scan_binary : 1;
2153   guint         scan_octal : 1;
2154   guint         scan_float : 1;
2155   guint         scan_hex : 1;                   /* `0x0ff0' */
2156   guint         scan_hex_dollar : 1;            /* `$0ff0' */
2157   guint         scan_string_sq : 1;             /* string: 'anything' */
2158   guint         scan_string_dq : 1;             /* string: "\\-escapes!\n" */
2159   guint         numbers_2_int : 1;              /* bin, octal, hex => int */
2160   guint         int_2_float : 1;                /* int => G_TOKEN_FLOAT? */
2161   guint         identifier_2_string : 1;
2162   guint         char_2_token : 1;               /* return G_TOKEN_CHAR? */
2163   guint         symbol_2_token : 1;
2164   guint         scope_0_fallback : 1;           /* try scope 0 on lookups? */
2165 };
2166
2167 struct  _GScanner
2168 {
2169   /* unused fields */
2170   gpointer              user_data;
2171   guint                 max_parse_errors;
2172   
2173   /* g_scanner_error() increments this field */
2174   guint                 parse_errors;
2175   
2176   /* name of input stream, featured by the default message handler */
2177   const gchar           *input_name;
2178   
2179   /* data pointer for derived structures */
2180   gpointer              derived_data;
2181   
2182   /* link into the scanner configuration */
2183   GScannerConfig        *config;
2184   
2185   /* fields filled in after g_scanner_get_next_token() */
2186   GTokenType            token;
2187   GTokenValue           value;
2188   guint                 line;
2189   guint                 position;
2190   
2191   /* fields filled in after g_scanner_peek_next_token() */
2192   GTokenType            next_token;
2193   GTokenValue           next_value;
2194   guint                 next_line;
2195   guint                 next_position;
2196   
2197   /* to be considered private */
2198   GHashTable            *symbol_table;
2199   gint                  input_fd;
2200   const gchar           *text;
2201   const gchar           *text_end;
2202   gchar                 *buffer;
2203   guint                 scope_id;
2204   
2205   /* handler function for _warn and _error */
2206   GScannerMsgFunc       msg_handler;
2207 };
2208
2209 GScanner*       g_scanner_new                   (GScannerConfig *config_templ);
2210 void            g_scanner_destroy               (GScanner       *scanner);
2211 void            g_scanner_input_file            (GScanner       *scanner,
2212                                                  gint           input_fd);
2213 void            g_scanner_sync_file_offset      (GScanner       *scanner);
2214 void            g_scanner_input_text            (GScanner       *scanner,
2215                                                  const  gchar   *text,
2216                                                  guint          text_len);
2217 GTokenType      g_scanner_get_next_token        (GScanner       *scanner);
2218 GTokenType      g_scanner_peek_next_token       (GScanner       *scanner);
2219 GTokenType      g_scanner_cur_token             (GScanner       *scanner);
2220 GTokenValue     g_scanner_cur_value             (GScanner       *scanner);
2221 guint           g_scanner_cur_line              (GScanner       *scanner);
2222 guint           g_scanner_cur_position          (GScanner       *scanner);
2223 gboolean        g_scanner_eof                   (GScanner       *scanner);
2224 guint           g_scanner_set_scope             (GScanner       *scanner,
2225                                                  guint           scope_id);
2226 void            g_scanner_scope_add_symbol      (GScanner       *scanner,
2227                                                  guint           scope_id,
2228                                                  const gchar    *symbol,
2229                                                  gpointer       value);
2230 void            g_scanner_scope_remove_symbol   (GScanner       *scanner,
2231                                                  guint           scope_id,
2232                                                  const gchar    *symbol);
2233 gpointer        g_scanner_scope_lookup_symbol   (GScanner       *scanner,
2234                                                  guint           scope_id,
2235                                                  const gchar    *symbol);
2236 void            g_scanner_scope_foreach_symbol  (GScanner       *scanner,
2237                                                  guint           scope_id,
2238                                                  GHFunc          func,
2239                                                  gpointer        user_data);
2240 gpointer        g_scanner_lookup_symbol         (GScanner       *scanner,
2241                                                  const gchar    *symbol);
2242 void            g_scanner_freeze_symbol_table   (GScanner       *scanner);
2243 void            g_scanner_thaw_symbol_table     (GScanner       *scanner);
2244 void            g_scanner_unexp_token           (GScanner       *scanner,
2245                                                  GTokenType     expected_token,
2246                                                  const gchar    *identifier_spec,
2247                                                  const gchar    *symbol_spec,
2248                                                  const gchar    *symbol_name,
2249                                                  const gchar    *message,
2250                                                  gint            is_error);
2251 void            g_scanner_error                 (GScanner       *scanner,
2252                                                  const gchar    *format,
2253                                                  ...) G_GNUC_PRINTF (2,3);
2254 void            g_scanner_warn                  (GScanner       *scanner,
2255                                                  const gchar    *format,
2256                                                  ...) G_GNUC_PRINTF (2,3);
2257 gint            g_scanner_stat_mode             (const gchar    *filename);
2258 /* keep downward source compatibility */
2259 #define         g_scanner_add_symbol( scanner, symbol, value )  G_STMT_START { \
2260   g_scanner_scope_add_symbol ((scanner), 0, (symbol), (value)); \
2261 } G_STMT_END
2262 #define         g_scanner_remove_symbol( scanner, symbol )      G_STMT_START { \
2263   g_scanner_scope_remove_symbol ((scanner), 0, (symbol)); \
2264 } G_STMT_END
2265 #define         g_scanner_foreach_symbol( scanner, func, data ) G_STMT_START { \
2266   g_scanner_scope_foreach_symbol ((scanner), 0, (func), (data)); \
2267 } G_STMT_END
2268
2269
2270 /* GCompletion
2271  */
2272
2273 struct _GCompletion
2274 {
2275   GList* items;
2276   GCompletionFunc func;
2277   
2278   gchar* prefix;
2279   GList* cache;
2280 };
2281
2282 GCompletion* g_completion_new          (GCompletionFunc func);
2283 void         g_completion_add_items    (GCompletion*    cmp,
2284                                         GList*          items);
2285 void         g_completion_remove_items (GCompletion*    cmp,
2286                                         GList*          items);
2287 void         g_completion_clear_items  (GCompletion*    cmp);
2288 GList*       g_completion_complete     (GCompletion*    cmp,
2289                                         gchar*          prefix,
2290                                         gchar**         new_prefix);
2291 void         g_completion_free         (GCompletion*    cmp);
2292
2293
2294 /* GDate
2295  *
2296  * Date calculations (not time for now, to be resolved). These are a
2297  * mutant combination of Steffen Beyer's DateCalc routines
2298  * (http://www.perl.com/CPAN/authors/id/STBEY/) and Jon Trowbridge's
2299  * date routines (written for in-house software).  Written by Havoc
2300  * Pennington <hp@pobox.com> 
2301  */
2302
2303 typedef guint16 GDateYear;
2304 typedef guint8  GDateDay;   /* day of the month */
2305 typedef struct _GDate GDate;
2306 /* make struct tm known without having to include time.h */
2307 struct tm;
2308
2309 /* enum used to specify order of appearance in parsed date strings */
2310 typedef enum
2311 {
2312   G_DATE_DAY   = 0,
2313   G_DATE_MONTH = 1,
2314   G_DATE_YEAR  = 2
2315 } GDateDMY;
2316
2317 /* actual week and month values */
2318 typedef enum
2319 {
2320   G_DATE_BAD_WEEKDAY  = 0,
2321   G_DATE_MONDAY       = 1,
2322   G_DATE_TUESDAY      = 2,
2323   G_DATE_WEDNESDAY    = 3,
2324   G_DATE_THURSDAY     = 4,
2325   G_DATE_FRIDAY       = 5,
2326   G_DATE_SATURDAY     = 6,
2327   G_DATE_SUNDAY       = 7
2328 } GDateWeekday;
2329 typedef enum
2330 {
2331   G_DATE_BAD_MONTH = 0,
2332   G_DATE_JANUARY   = 1,
2333   G_DATE_FEBRUARY  = 2,
2334   G_DATE_MARCH     = 3,
2335   G_DATE_APRIL     = 4,
2336   G_DATE_MAY       = 5,
2337   G_DATE_JUNE      = 6,
2338   G_DATE_JULY      = 7,
2339   G_DATE_AUGUST    = 8,
2340   G_DATE_SEPTEMBER = 9,
2341   G_DATE_OCTOBER   = 10,
2342   G_DATE_NOVEMBER  = 11,
2343   G_DATE_DECEMBER  = 12
2344 } GDateMonth;
2345
2346 #define G_DATE_BAD_JULIAN 0U
2347 #define G_DATE_BAD_DAY    0U
2348 #define G_DATE_BAD_YEAR   0U
2349
2350 /* Note: directly manipulating structs is generally a bad idea, but
2351  * in this case it's an *incredibly* bad idea, because all or part
2352  * of this struct can be invalid at any given time. Use the functions,
2353  * or you will get hosed, I promise.
2354  */
2355 struct _GDate
2356
2357   guint julian_days : 32; /* julian days representation - we use a
2358                            *  bitfield hoping that 64 bit platforms
2359                            *  will pack this whole struct in one big
2360                            *  int 
2361                            */
2362
2363   guint julian : 1;    /* julian is valid */
2364   guint dmy    : 1;    /* dmy is valid */
2365
2366   /* DMY representation */
2367   guint day    : 6;  
2368   guint month  : 4; 
2369   guint year   : 16; 
2370 };
2371
2372 /* g_date_new() returns an invalid date, you then have to _set() stuff 
2373  * to get a usable object. You can also allocate a GDate statically,
2374  * then call g_date_clear() to initialize.
2375  */
2376 GDate*       g_date_new                   (void);
2377 GDate*       g_date_new_dmy               (GDateDay     day, 
2378                                            GDateMonth   month, 
2379                                            GDateYear    year);
2380 GDate*       g_date_new_julian            (guint32      julian_day);
2381 void         g_date_free                  (GDate       *date);
2382
2383 /* check g_date_valid() after doing an operation that might fail, like
2384  * _parse.  Almost all g_date operations are undefined on invalid
2385  * dates (the exceptions are the mutators, since you need those to
2386  * return to validity).  
2387  */
2388 gboolean     g_date_valid                 (GDate       *date);
2389 gboolean     g_date_valid_day             (GDateDay     day);
2390 gboolean     g_date_valid_month           (GDateMonth   month);
2391 gboolean     g_date_valid_year            (GDateYear    year);
2392 gboolean     g_date_valid_weekday         (GDateWeekday weekday);
2393 gboolean     g_date_valid_julian          (guint32      julian_date);
2394 gboolean     g_date_valid_dmy             (GDateDay     day,
2395                                            GDateMonth   month,
2396                                            GDateYear    year);
2397
2398 GDateWeekday g_date_weekday               (GDate       *date);
2399 GDateMonth   g_date_month                 (GDate       *date);
2400 GDateYear    g_date_year                  (GDate       *date);
2401 GDateDay     g_date_day                   (GDate       *date);
2402 guint32      g_date_julian                (GDate       *date);
2403 guint        g_date_day_of_year           (GDate       *date);
2404
2405 /* First monday/sunday is the start of week 1; if we haven't reached
2406  * that day, return 0. These are not ISO weeks of the year; that
2407  * routine needs to be added.
2408  * these functions return the number of weeks, starting on the
2409  * corrsponding day
2410  */
2411 guint        g_date_monday_week_of_year   (GDate      *date);
2412 guint        g_date_sunday_week_of_year   (GDate      *date);
2413
2414 /* If you create a static date struct you need to clear it to get it
2415  * in a sane state before use. You can clear a whole array at
2416  * once with the ndates argument.
2417  */
2418 void         g_date_clear                 (GDate       *date, 
2419                                            guint        n_dates);
2420
2421 /* The parse routine is meant for dates typed in by a user, so it
2422  * permits many formats but tries to catch common typos. If your data
2423  * needs to be strictly validated, it is not an appropriate function.
2424  */
2425 void         g_date_set_parse             (GDate       *date,
2426                                            const gchar *str);
2427 void         g_date_set_time              (GDate       *date, 
2428                                            GTime        time);
2429 void         g_date_set_month             (GDate       *date, 
2430                                            GDateMonth   month);
2431 void         g_date_set_day               (GDate       *date, 
2432                                            GDateDay     day);
2433 void         g_date_set_year              (GDate       *date,
2434                                            GDateYear    year);
2435 void         g_date_set_dmy               (GDate       *date,
2436                                            GDateDay     day,
2437                                            GDateMonth   month,
2438                                            GDateYear    y);
2439 void         g_date_set_julian            (GDate       *date,
2440                                            guint32      julian_date);
2441 gboolean     g_date_is_first_of_month     (GDate       *date);
2442 gboolean     g_date_is_last_of_month      (GDate       *date);
2443
2444 /* To go forward by some number of weeks just go forward weeks*7 days */
2445 void         g_date_add_days              (GDate       *date, 
2446                                            guint        n_days);
2447 void         g_date_subtract_days         (GDate       *date, 
2448                                            guint        n_days);
2449
2450 /* If you add/sub months while day > 28, the day might change */
2451 void         g_date_add_months            (GDate       *date,
2452                                            guint        n_months);
2453 void         g_date_subtract_months       (GDate       *date,
2454                                            guint        n_months);
2455
2456 /* If it's feb 29, changing years can move you to the 28th */
2457 void         g_date_add_years             (GDate       *date,
2458                                            guint        n_years);
2459 void         g_date_subtract_years        (GDate       *date,
2460                                            guint        n_years);
2461 gboolean     g_date_is_leap_year          (GDateYear    year);
2462 guint8       g_date_days_in_month         (GDateMonth   month, 
2463                                            GDateYear    year);
2464 guint8       g_date_monday_weeks_in_year  (GDateYear    year);
2465 guint8       g_date_sunday_weeks_in_year  (GDateYear    year);
2466
2467 /* qsort-friendly (with a cast...) */
2468 gint         g_date_compare               (GDate       *lhs,
2469                                            GDate       *rhs);
2470 void         g_date_to_struct_tm          (GDate       *date,
2471                                            struct tm   *tm);
2472
2473 /* Just like strftime() except you can only use date-related formats.
2474  *   Using a time format is undefined.
2475  */
2476 gsize        g_date_strftime              (gchar       *s,
2477                                            gsize        slen,
2478                                            const gchar *format,
2479                                            GDate       *date);
2480
2481
2482 /* GRelation
2483  *
2484  * Indexed Relations.  Imagine a really simple table in a
2485  * database.  Relations are not ordered.  This data type is meant for
2486  * maintaining a N-way mapping.
2487  *
2488  * g_relation_new() creates a relation with FIELDS fields
2489  *
2490  * g_relation_destroy() frees all resources
2491  * g_tuples_destroy() frees the result of g_relation_select()
2492  *
2493  * g_relation_index() indexes relation FIELD with the provided
2494  *   equality and hash functions.  this must be done before any
2495  *   calls to insert are made.
2496  *
2497  * g_relation_insert() inserts a new tuple.  you are expected to
2498  *   provide the right number of fields.
2499  *
2500  * g_relation_delete() deletes all relations with KEY in FIELD
2501  * g_relation_select() returns ...
2502  * g_relation_count() counts ...
2503  */
2504
2505 GRelation* g_relation_new     (gint         fields);
2506 void       g_relation_destroy (GRelation   *relation);
2507 void       g_relation_index   (GRelation   *relation,
2508                                gint         field,
2509                                GHashFunc    hash_func,
2510                                GCompareFunc key_compare_func);
2511 void       g_relation_insert  (GRelation   *relation,
2512                                ...);
2513 gint       g_relation_delete  (GRelation   *relation,
2514                                gconstpointer  key,
2515                                gint         field);
2516 GTuples*   g_relation_select  (GRelation   *relation,
2517                                gconstpointer  key,
2518                                gint         field);
2519 gint       g_relation_count   (GRelation   *relation,
2520                                gconstpointer  key,
2521                                gint         field);
2522 gboolean   g_relation_exists  (GRelation   *relation,
2523                                ...);
2524 void       g_relation_print   (GRelation   *relation);
2525
2526 void       g_tuples_destroy   (GTuples     *tuples);
2527 gpointer   g_tuples_index     (GTuples     *tuples,
2528                                gint         index,
2529                                gint         field);
2530
2531
2532 /* GRand - a good and fast random number generator: Mersenne Twister 
2533  * see http://www.math.keio.ac.jp/~matumoto/emt.html for more info.
2534  * The range functions return a value in the intervall [min,max).
2535  * int          -> [0..2^32-1]
2536  * int_range    -> [min..max-1]
2537  * double       -> [0..1)
2538  * double_range -> [min..max)
2539  */
2540
2541 GRand*  g_rand_new_with_seed   (guint32     seed);
2542 GRand*  g_rand_new             (void);
2543 void    g_rand_free            (GRand      *rand);
2544
2545 void    g_rand_set_seed        (GRand      *rand, 
2546                                 guint32     seed);
2547 guint32 g_rand_int             (GRand      *rand);
2548 gint32  g_rand_int_range       (GRand      *rand, 
2549                                 gint32      min, 
2550                                 gint32      max);
2551 gdouble g_rand_double          (GRand      *rand);
2552 gdouble g_rand_double_range    (GRand      *rand, 
2553                                 gdouble     min, 
2554                                 gdouble     max);
2555
2556 void    g_random_set_seed      (guint32     seed);
2557 guint32 g_random_int           (void);
2558 gint32  g_random_int_range     (gint32      min, 
2559                                 gint32      max);
2560 gdouble g_random_double        (void);
2561 gdouble g_random_double_range  (gdouble     min, 
2562                                 gdouble     max);
2563  
2564
2565 /* Prime numbers.
2566  */
2567
2568 /* This function returns prime numbers spaced by approximately 1.5-2.0
2569  * and is for use in resizing data structures which prefer
2570  * prime-valued sizes.  The closest spaced prime function returns the
2571  * next largest prime, or the highest it knows about which is about
2572  * MAXINT/4.
2573  */
2574 guint      g_spaced_primes_closest (guint num);
2575
2576
2577 /* GIOChannel
2578  */
2579
2580 typedef struct _GIOFuncs GIOFuncs;
2581 typedef enum
2582 {
2583   G_IO_ERROR_NONE,
2584   G_IO_ERROR_AGAIN,
2585   G_IO_ERROR_INVAL,
2586   G_IO_ERROR_UNKNOWN
2587 } GIOError;
2588 typedef enum
2589 {
2590   G_SEEK_CUR,
2591   G_SEEK_SET,
2592   G_SEEK_END
2593 } GSeekType;
2594 typedef enum
2595 {
2596   G_IO_IN       GLIB_SYSDEF_POLLIN,
2597   G_IO_OUT      GLIB_SYSDEF_POLLOUT,
2598   G_IO_PRI      GLIB_SYSDEF_POLLPRI,
2599   G_IO_ERR      GLIB_SYSDEF_POLLERR,
2600   G_IO_HUP      GLIB_SYSDEF_POLLHUP,
2601   G_IO_NVAL     GLIB_SYSDEF_POLLNVAL
2602 } GIOCondition;
2603
2604 struct _GIOChannel
2605 {
2606   guint channel_flags;
2607   guint ref_count;
2608   GIOFuncs *funcs;
2609 };
2610
2611 typedef gboolean (*GIOFunc) (GIOChannel   *source,
2612                              GIOCondition  condition,
2613                              gpointer      data);
2614 struct _GIOFuncs
2615 {
2616   GIOError (*io_read)   (GIOChannel     *channel, 
2617                          gchar          *buf, 
2618                          guint           count,
2619                          guint          *bytes_read);
2620   GIOError (*io_write)  (GIOChannel     *channel, 
2621                          gchar          *buf, 
2622                          guint           count,
2623                          guint          *bytes_written);
2624   GIOError (*io_seek)   (GIOChannel     *channel, 
2625                          gint            offset, 
2626                          GSeekType       type);
2627   void (*io_close)      (GIOChannel     *channel);
2628   guint (*io_add_watch) (GIOChannel     *channel,
2629                          gint            priority,
2630                          GIOCondition    condition,
2631                          GIOFunc         func,
2632                          gpointer        user_data,
2633                          GDestroyNotify  notify);
2634   void (*io_free)       (GIOChannel     *channel);
2635 };
2636
2637 void        g_io_channel_init   (GIOChannel    *channel);
2638 void        g_io_channel_ref    (GIOChannel    *channel);
2639 void        g_io_channel_unref  (GIOChannel    *channel);
2640 GIOError    g_io_channel_read   (GIOChannel    *channel, 
2641                                  gchar         *buf, 
2642                                  guint          count,
2643                                  guint         *bytes_read);
2644 GIOError  g_io_channel_write    (GIOChannel    *channel, 
2645                                  gchar         *buf, 
2646                                  guint          count,
2647                                  guint         *bytes_written);
2648 GIOError  g_io_channel_seek     (GIOChannel    *channel,
2649                                  gint           offset, 
2650                                  GSeekType      type);
2651 void      g_io_channel_close    (GIOChannel    *channel);
2652 guint     g_io_add_watch_full   (GIOChannel    *channel,
2653                                  gint           priority,
2654                                  GIOCondition   condition,
2655                                  GIOFunc        func,
2656                                  gpointer       user_data,
2657                                  GDestroyNotify notify);
2658 guint    g_io_add_watch         (GIOChannel    *channel,
2659                                  GIOCondition   condition,
2660                                  GIOFunc        func,
2661                                  gpointer       user_data);
2662
2663
2664 /* Main loop
2665  */
2666 typedef struct _GTimeVal        GTimeVal;
2667 typedef struct _GSourceFuncs    GSourceFuncs;
2668 typedef struct _GMainLoop       GMainLoop;      /* Opaque */
2669
2670 struct _GTimeVal
2671 {
2672   glong tv_sec;
2673   glong tv_usec;
2674 };
2675 struct _GSourceFuncs
2676 {
2677   gboolean (*prepare)  (gpointer  source_data, 
2678                         GTimeVal *current_time,
2679                         gint     *timeout,
2680                         gpointer  user_data);
2681   gboolean (*check)    (gpointer  source_data,
2682                         GTimeVal *current_time,
2683                         gpointer  user_data);
2684   gboolean (*dispatch) (gpointer  source_data, 
2685                         GTimeVal *dispatch_time,
2686                         gpointer  user_data);
2687   GDestroyNotify destroy;
2688 };
2689
2690 /* Standard priorities */
2691
2692 #define G_PRIORITY_HIGH            -100
2693 #define G_PRIORITY_DEFAULT          0
2694 #define G_PRIORITY_HIGH_IDLE        100
2695 #define G_PRIORITY_DEFAULT_IDLE     200
2696 #define G_PRIORITY_LOW              300
2697
2698 typedef gboolean (*GSourceFunc) (gpointer data);
2699
2700 /* Hooks for adding to the main loop */
2701 guint    g_source_add                        (gint           priority, 
2702                                               gboolean       can_recurse,
2703                                               GSourceFuncs  *funcs,
2704                                               gpointer       source_data, 
2705                                               gpointer       user_data,
2706                                               GDestroyNotify notify);
2707 gboolean g_source_remove                     (guint          tag);
2708 gboolean g_source_remove_by_user_data        (gpointer       user_data);
2709 gboolean g_source_remove_by_source_data      (gpointer       source_data);
2710 gboolean g_source_remove_by_funcs_user_data  (GSourceFuncs  *funcs,
2711                                               gpointer       user_data);
2712
2713 void g_get_current_time                 (GTimeVal       *result);
2714
2715 /* Running the main loop */
2716 GMainLoop*      g_main_new              (gboolean        is_running);
2717 void            g_main_run              (GMainLoop      *loop);
2718 void            g_main_quit             (GMainLoop      *loop);
2719 void            g_main_destroy          (GMainLoop      *loop);
2720 gboolean        g_main_is_running       (GMainLoop      *loop);
2721
2722 /* Run a single iteration of the mainloop. If block is FALSE,
2723  * will never block
2724  */
2725 gboolean        g_main_iteration        (gboolean       may_block);
2726
2727 /* See if any events are pending */
2728 gboolean        g_main_pending          (void);
2729
2730 /* Idles and timeouts */
2731 guint           g_timeout_add_full      (gint           priority,
2732                                          guint          interval, 
2733                                          GSourceFunc    function,
2734                                          gpointer       data,
2735                                          GDestroyNotify notify);
2736 guint           g_timeout_add           (guint          interval,
2737                                          GSourceFunc    function,
2738                                          gpointer       data);
2739 guint           g_idle_add              (GSourceFunc    function,
2740                                          gpointer       data);
2741 guint           g_idle_add_full         (gint           priority,
2742                                          GSourceFunc    function,
2743                                          gpointer       data,
2744                                          GDestroyNotify destroy);
2745 gboolean        g_idle_remove_by_data   (gpointer       data);
2746
2747 /* GPollFD
2748  *
2749  * System-specific IO and main loop calls
2750  *
2751  * On Win32, the fd in a GPollFD should be Win32 HANDLE (*not* a file
2752  * descriptor as provided by the C runtime) that can be used by
2753  * MsgWaitForMultipleObjects. This does *not* include file handles
2754  * from CreateFile, SOCKETs, nor pipe handles. (But you can use
2755  * WSAEventSelect to signal events when a SOCKET is readable).
2756  *
2757  * On Win32, fd can also be the special value G_WIN32_MSG_HANDLE to
2758  * indicate polling for messages. These message queue GPollFDs should
2759  * be added with the g_main_poll_win32_msg_add function.
2760  *
2761  * But note that G_WIN32_MSG_HANDLE GPollFDs should not be used by GDK
2762  * (GTK) programs, as GDK itself wants to read messages and convert them
2763  * to GDK events.
2764  *
2765  * So, unless you really know what you are doing, it's best not to try
2766  * to use the main loop polling stuff for your own needs on
2767  * Win32. It's really only written for the GIMP's needs so
2768  * far.
2769  */
2770
2771 typedef struct _GPollFD GPollFD;
2772 typedef gint    (*GPollFunc)    (GPollFD *ufds,
2773                                  guint    nfsd,
2774                                  gint     timeout);
2775 struct _GPollFD
2776 {
2777   gint          fd;
2778   gushort       events;
2779   gushort       revents;
2780 };
2781
2782 void        g_main_add_poll          (GPollFD    *fd,
2783                                       gint        priority);
2784 void        g_main_remove_poll       (GPollFD    *fd);
2785 void        g_main_set_poll_func     (GPollFunc   func);
2786
2787 /* On Unix, IO channels created with this function for any file
2788  * descriptor or socket.
2789  *
2790  * On Win32, use this only for plain files opened with the MSVCRT (the
2791  * Microsoft run-time C library) _open(), including file descriptors
2792  * 0, 1 and 2 (corresponding to stdin, stdout and stderr).
2793  * Actually, don't do even that, this code isn't done yet.
2794  *
2795  * The term file descriptor as used in the context of Win32 refers to
2796  * the emulated Unix-like file descriptors MSVCRT provides.
2797  */
2798 GIOChannel* g_io_channel_unix_new    (int         fd);
2799 gint        g_io_channel_unix_get_fd (GIOChannel *channel);
2800
2801 #ifdef G_OS_WIN32
2802
2803 GUTILS_C_VAR guint g_pipe_readable_msg;
2804
2805 #define G_WIN32_MSG_HANDLE 19981206
2806
2807 /* This is used to add polling for Windows messages. GDK (GTk+) programs
2808  * should *not* use this. (In fact, I can't think of any program that
2809  * would want to use this, but it's here just for completeness's sake.
2810  */
2811 void        g_main_poll_win32_msg_add(gint        priority,
2812                                       GPollFD    *fd,
2813                                       guint       hwnd);
2814
2815 /* An IO channel for Windows messages for window handle hwnd. */
2816 GIOChannel *g_io_channel_win32_new_messages (guint hwnd);
2817
2818 /* An IO channel for an anonymous pipe as returned from the MSVCRT
2819  * _pipe(), with no mechanism for the writer to tell the reader when
2820  * there is data in the pipe.
2821  *
2822  * This is not really implemented yet.
2823  */
2824 GIOChannel *g_io_channel_win32_new_pipe (int fd);
2825
2826 /* An IO channel for a pipe as returned from the MSVCRT _pipe(), with
2827  * Windows user messages used to signal data in the pipe for the
2828  * reader.
2829  *
2830  * fd is the file descriptor. For the write end, peer is the thread id
2831  * of the reader, and peer_fd is his file descriptor for the read end
2832  * of the pipe.
2833  *
2834  * This is used by the GIMP, and works.
2835  */
2836 GIOChannel *g_io_channel_win32_new_pipe_with_wakeups (int   fd,
2837                                                       guint peer,
2838                                                       int   peer_fd);
2839
2840 void        g_io_channel_win32_pipe_request_wakeups (GIOChannel *channel,
2841                                                      guint       peer,
2842                                                      int         peer_fd);
2843
2844 void        g_io_channel_win32_pipe_readable (int   fd,
2845                                               guint offset);
2846
2847 /* Get the C runtime file descriptor of a channel. */
2848 gint        g_io_channel_win32_get_fd (GIOChannel *channel);
2849
2850 /* An IO channel for a SOCK_STREAM winsock socket. The parameter is
2851  * actually a SOCKET.
2852  */
2853 GIOChannel *g_io_channel_win32_new_stream_socket (int socket);
2854
2855 #endif
2856
2857 /* Windows emulation stubs for common Unix functions
2858  */
2859 #ifdef G_OS_WIN32
2860 #  define MAXPATHLEN 1024
2861
2862 #ifdef _MSC_VER
2863 typedef int pid_t;
2864 #endif
2865
2866 /*
2867  * To get prototypes for the following POSIXish functions, you have to
2868  * include the indicated non-POSIX headers. The functions are defined
2869  * in OLDNAMES.LIB (MSVC) or -lmoldname-msvc (mingw32).
2870  *
2871  * getcwd: <direct.h> (MSVC), <io.h> (mingw32)
2872  * getpid: <process.h>
2873  * access: <io.h>
2874  * unlink: <stdio.h> or <io.h>
2875  * open, read, write, lseek, close: <io.h>
2876  * rmdir: <direct.h>
2877  * pipe: <direct.h>
2878  */
2879
2880 /* pipe is not in OLDNAMES.LIB or -lmoldname-msvc. */
2881 #define pipe(phandles)  _pipe (phandles, 4096, _O_BINARY)
2882
2883 /* For some POSIX functions that are not provided by the MS runtime,
2884  * we provide emulators in glib, which are prefixed with g_win32_.
2885  */
2886 #    define ftruncate(fd, size) g_win32_ftruncate (fd, size)
2887
2888 /* -lmingw32 also has emulations for these, but we need our own
2889  * for MSVC anyhow, so we might aswell use them always.
2890  */
2891 #    define opendir             g_win32_opendir
2892 #    define readdir             g_win32_readdir
2893 #    define rewinddir           g_win32_rewinddir
2894 #    define closedir            g_win32_closedir
2895 #    define NAME_MAX 255
2896
2897 struct DIR
2898 {
2899   gchar    *dir_name;
2900   gboolean  just_opened;
2901   guint     find_file_handle;
2902   gpointer  find_file_data;
2903 };
2904 typedef struct DIR DIR;
2905 struct dirent
2906 {
2907   gchar  d_name[NAME_MAX + 1];
2908 };
2909 /* emulation functions */
2910 extern int      g_win32_ftruncate       (gint            f,
2911                                          guint           size);
2912 DIR*            g_win32_opendir         (const gchar    *dirname);
2913 struct dirent*  g_win32_readdir         (DIR            *dir);
2914 void            g_win32_rewinddir       (DIR            *dir);
2915 gint            g_win32_closedir        (DIR            *dir);
2916
2917 /* The MS setlocale uses locale names of the form "English_United
2918  * States.1252" etc. We want the Unixish standard form "en", "zh_TW"
2919  * etc. This function gets the current thread locale from Windows and
2920  * returns it as a string of the above form for use in forming file
2921  * names etc. The returned string should be deallocated with g_free().
2922  */
2923 gchar *         g_win32_getlocale  (void);
2924
2925 /* Translate a Win32 error code (as returned by GetLastError()) into
2926  * the corresponding message. The returned string should be deallocated
2927  * with g_free().
2928  */
2929 gchar *         g_win32_error_message (gint error);
2930
2931 #endif   /* G_OS_WIN32 */
2932
2933
2934 /* GLib Thread support
2935  */
2936
2937 typedef void            (*GThreadFunc)          (gpointer       value);
2938
2939 typedef enum
2940 {
2941     G_THREAD_PRIORITY_LOW,
2942     G_THREAD_PRIORITY_NORMAL,
2943     G_THREAD_PRIORITY_HIGH,
2944     G_THREAD_PRIORITY_URGENT
2945 } GThreadPriority;
2946
2947 typedef struct _GThread         GThread;
2948 struct  _GThread
2949 {
2950   GThreadPriority priority;
2951   gboolean bound;
2952   gboolean joinable;
2953 };
2954
2955 typedef struct _GMutex          GMutex;
2956 typedef struct _GCond           GCond;
2957 typedef struct _GPrivate        GPrivate;
2958 typedef struct _GStaticPrivate  GStaticPrivate;
2959 typedef struct _GAsyncQueue     GAsyncQueue;
2960 typedef struct _GThreadPool     GThreadPool;
2961
2962 typedef struct _GThreadFunctions GThreadFunctions;
2963 struct _GThreadFunctions
2964 {
2965   GMutex*  (*mutex_new)           (void);
2966   void     (*mutex_lock)          (GMutex               *mutex);
2967   gboolean (*mutex_trylock)       (GMutex               *mutex);
2968   void     (*mutex_unlock)        (GMutex               *mutex);
2969   void     (*mutex_free)          (GMutex               *mutex);
2970   GCond*   (*cond_new)            (void);
2971   void     (*cond_signal)         (GCond                *cond);
2972   void     (*cond_broadcast)      (GCond                *cond);
2973   void     (*cond_wait)           (GCond                *cond,
2974                                    GMutex               *mutex);
2975   gboolean (*cond_timed_wait)     (GCond                *cond,
2976                                    GMutex               *mutex, 
2977                                    GTimeVal             *end_time);
2978   void      (*cond_free)          (GCond                *cond);
2979   GPrivate* (*private_new)        (GDestroyNotify        destructor);
2980   gpointer  (*private_get)        (GPrivate             *private_key);
2981   void      (*private_set)        (GPrivate             *private_key,
2982                                    gpointer              data);
2983   void      (*thread_create)      (GThreadFunc           thread_func,
2984                                    gpointer              arg,
2985                                    gulong                stack_size,
2986                                    gboolean              joinable,
2987                                    gboolean              bound,
2988                                    GThreadPriority       priority,
2989                                    gpointer              thread);
2990   void      (*thread_yield)       (void);
2991   void      (*thread_join)        (gpointer              thread);
2992   void      (*thread_exit)        (void);
2993   void      (*thread_set_priority)(gpointer              thread, 
2994                                    GThreadPriority       priority);
2995   void      (*thread_self)        (gpointer              thread);
2996 };
2997
2998 GUTILS_C_VAR GThreadFunctions   g_thread_functions_for_glib_use;
2999 GUTILS_C_VAR gboolean           g_thread_use_default_impl;
3000 GUTILS_C_VAR gboolean           g_threads_got_initialized;
3001
3002 /* initializes the mutex/cond/private implementation for glib, might
3003  * only be called once, and must not be called directly or indirectly
3004  * from another glib-function, e.g. as a callback.
3005  */
3006 void    g_thread_init   (GThreadFunctions       *vtable);
3007
3008 /* internal function for fallback static mutex implementation */
3009 GMutex* g_static_mutex_get_mutex_impl   (GMutex **mutex);
3010
3011 /* shorthands for conditional and unconditional function calls */
3012 #define G_THREAD_UF(name, arglist) \
3013     (*g_thread_functions_for_glib_use . name) arglist
3014 #define G_THREAD_CF(name, fail, arg) \
3015     (g_thread_supported () ? G_THREAD_UF (name, arg) : (fail))
3016 /* keep in mind, all those mutexes and static mutexes are not 
3017  * recursive in general, don't rely on that
3018  */
3019 #define g_thread_supported()    (g_threads_got_initialized)
3020 #define g_mutex_new()            G_THREAD_UF (mutex_new,      ())
3021 #define g_mutex_lock(mutex)      G_THREAD_CF (mutex_lock,     (void)0, (mutex))
3022 #define g_mutex_trylock(mutex)   G_THREAD_CF (mutex_trylock,  TRUE,    (mutex))
3023 #define g_mutex_unlock(mutex)    G_THREAD_CF (mutex_unlock,   (void)0, (mutex))
3024 #define g_mutex_free(mutex)      G_THREAD_CF (mutex_free,     (void)0, (mutex))
3025 #define g_cond_new()             G_THREAD_UF (cond_new,       ())
3026 #define g_cond_signal(cond)      G_THREAD_CF (cond_signal,    (void)0, (cond))
3027 #define g_cond_broadcast(cond)   G_THREAD_CF (cond_broadcast, (void)0, (cond))
3028 #define g_cond_wait(cond, mutex) G_THREAD_CF (cond_wait,      (void)0, (cond, \
3029                                                                         mutex))
3030 #define g_cond_free(cond)        G_THREAD_CF (cond_free,      (void)0, (cond))
3031 #define g_cond_timed_wait(cond, mutex, abs_time) G_THREAD_CF (cond_timed_wait, \
3032                                                               TRUE, \
3033                                                               (cond, mutex, \
3034                                                                abs_time))
3035 #define g_private_new(destructor)         G_THREAD_UF (private_new, (destructor))
3036 #define g_private_get(private_key)        G_THREAD_CF (private_get, \
3037                                                        ((gpointer)private_key), \
3038                                                        (private_key))
3039 #define g_private_set(private_key, value) G_THREAD_CF (private_set, \
3040                                                        (void) (private_key = \
3041                                                         (GPrivate*) (value)), \
3042                                                        (private_key, value))
3043 #define g_thread_yield()              G_THREAD_CF (thread_yield, (void)0, ())
3044 #define g_thread_exit()               G_THREAD_CF (thread_exit, (void)0, ())
3045
3046 GThread* g_thread_create (GThreadFunc            thread_func,
3047                           gpointer               arg,
3048                           gulong                 stack_size,
3049                           gboolean               joinable,
3050                           gboolean               bound,
3051                           GThreadPriority        priority);
3052 GThread* g_thread_self ();
3053 void g_thread_join (GThread* thread);
3054 void g_thread_set_priority (GThread* thread, 
3055                             GThreadPriority priority);
3056
3057 /* GStaticMutexes can be statically initialized with the value
3058  * G_STATIC_MUTEX_INIT, and then they can directly be used, that is
3059  * much easier, than having to explicitly allocate the mutex before
3060  * use
3061  */
3062 #define g_static_mutex_lock(mutex) \
3063     g_mutex_lock (g_static_mutex_get_mutex (mutex))
3064 #define g_static_mutex_trylock(mutex) \
3065     g_mutex_trylock (g_static_mutex_get_mutex (mutex))
3066 #define g_static_mutex_unlock(mutex) \
3067     g_mutex_unlock (g_static_mutex_get_mutex (mutex)) 
3068
3069 struct _GStaticPrivate
3070 {
3071   guint index;
3072 };
3073 #define G_STATIC_PRIVATE_INIT { 0 }
3074 gpointer g_static_private_get (GStaticPrivate   *private_key);
3075 void     g_static_private_set (GStaticPrivate   *private_key, 
3076                                gpointer          data,
3077                                GDestroyNotify    notify);
3078 gpointer g_static_private_get_for_thread (GStaticPrivate *private_key,
3079                                           GThread        *thread);
3080 void g_static_private_set_for_thread (GStaticPrivate *private_key, 
3081                                       GThread        *thread,
3082                                       gpointer        data,
3083                                       GDestroyNotify  notify);
3084
3085 typedef struct _GStaticRecMutex GStaticRecMutex;
3086 struct _GStaticRecMutex
3087 {
3088   GStaticMutex mutex;
3089   unsigned int depth;
3090   GSystemThread owner;
3091 };
3092
3093 #define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT }
3094 void     g_static_rec_mutex_lock        (GStaticRecMutex *mutex);
3095 gboolean g_static_rec_mutex_trylock     (GStaticRecMutex *mutex);
3096 void     g_static_rec_mutex_unlock      (GStaticRecMutex *mutex);
3097 void     g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
3098                                          guint            depth);
3099 guint    g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex);
3100
3101 typedef struct _GStaticRWLock GStaticRWLock;
3102 struct _GStaticRWLock
3103 {
3104   GStaticMutex mutex; 
3105   GCond *read_cond;
3106   GCond *write_cond;
3107   guint read_counter;
3108   gboolean write;
3109   guint want_to_write;
3110 };
3111
3112 #define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, FALSE }
3113
3114 void      g_static_rw_lock_reader_lock    (GStaticRWLock* lock);
3115 gboolean  g_static_rw_lock_reader_trylock (GStaticRWLock* lock);
3116 void      g_static_rw_lock_reader_unlock  (GStaticRWLock* lock);
3117 void      g_static_rw_lock_writer_lock    (GStaticRWLock* lock);
3118 gboolean  g_static_rw_lock_writer_trylock (GStaticRWLock* lock);
3119 void      g_static_rw_lock_writer_unlock  (GStaticRWLock* lock);
3120 void      g_static_rw_lock_free (GStaticRWLock* lock);
3121
3122 /* these are some convenience macros that expand to nothing if GLib
3123  * was configured with --disable-threads. for using StaticMutexes,
3124  * you define them with G_LOCK_DEFINE_STATIC (name) or G_LOCK_DEFINE (name)
3125  * if you need to export the mutex. With G_LOCK_EXTERN (name) you can
3126  * declare such an globally defined lock. name is a unique identifier
3127  * for the protected varibale or code portion. locking, testing and
3128  * unlocking of such mutexes can be done with G_LOCK(), G_UNLOCK() and
3129  * G_TRYLOCK() respectively.  
3130  */
3131 extern void glib_dummy_decl (void);
3132 #define G_LOCK_NAME(name)               g__ ## name ## _lock
3133 #ifdef  G_THREADS_ENABLED
3134 #  define G_LOCK_DEFINE_STATIC(name)    static G_LOCK_DEFINE (name)
3135 #  define G_LOCK_DEFINE(name)           \
3136     GStaticMutex G_LOCK_NAME (name) = G_STATIC_MUTEX_INIT 
3137 #  define G_LOCK_EXTERN(name)           extern GStaticMutex G_LOCK_NAME (name)
3138
3139 #  ifdef G_DEBUG_LOCKS
3140 #    define G_LOCK(name)                G_STMT_START{             \
3141         g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,                   \
3142                "file %s: line %d (%s): locking: %s ",             \
3143                __FILE__,        __LINE__, G_GNUC_PRETTY_FUNCTION, \
3144                #name);                                            \
3145         g_static_mutex_lock (&G_LOCK_NAME (name));                \
3146      }G_STMT_END
3147 #    define G_UNLOCK(name)              G_STMT_START{             \
3148         g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,                   \
3149                "file %s: line %d (%s): unlocking: %s ",           \
3150                __FILE__,        __LINE__, G_GNUC_PRETTY_FUNCTION, \
3151                #name);                                            \
3152        g_static_mutex_unlock (&G_LOCK_NAME (name));               \
3153      }G_STMT_END
3154 #    define G_TRYLOCK(name)                                       \
3155         (g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,                  \
3156                "file %s: line %d (%s): try locking: %s ",         \
3157                __FILE__,        __LINE__, G_GNUC_PRETTY_FUNCTION, \
3158                #name), g_static_mutex_trylock (&G_LOCK_NAME (name)))
3159 #  else  /* !G_DEBUG_LOCKS */
3160 #    define G_LOCK(name) g_static_mutex_lock       (&G_LOCK_NAME (name)) 
3161 #    define G_UNLOCK(name) g_static_mutex_unlock   (&G_LOCK_NAME (name))
3162 #    define G_TRYLOCK(name) g_static_mutex_trylock (&G_LOCK_NAME (name))
3163 #  endif /* !G_DEBUG_LOCKS */
3164 #else   /* !G_THREADS_ENABLED */
3165 #  define G_LOCK_DEFINE_STATIC(name)    extern void glib_dummy_decl (void)
3166 #  define G_LOCK_DEFINE(name)           extern void glib_dummy_decl (void)
3167 #  define G_LOCK_EXTERN(name)           extern void glib_dummy_decl (void)
3168 #  define G_LOCK(name)
3169 #  define G_UNLOCK(name)
3170 #  define G_TRYLOCK(name)               (TRUE)
3171 #endif  /* !G_THREADS_ENABLED */
3172
3173 /* Asyncronous Queues, can be used to communicate between threads
3174  */
3175
3176 /* Get a new GAsyncQueue with the ref_count 1 */
3177 GAsyncQueue*  g_async_queue_new                (void);
3178
3179 /* Lock and unlock an GAsyncQueue, all functions lock the queue for
3180  * themselves, but in certain cirumstances you want to hold the lock longer,
3181  * thus you lock the queue, call the *_unlocked functions and unlock it again
3182  */
3183 void          g_async_queue_lock               (GAsyncQueue *queue);
3184 void          g_async_queue_unlock             (GAsyncQueue *queue);
3185
3186 /* Ref and unref the GAsyncQueue. g_async_queue_unref_unlocked makes
3187  * no sense, as after the unreffing the Queue might be gone and can't
3188  * be unlocked. So you have a function to call, if you don't hold the
3189  * lock (g_async_queue_unref) and one to call, when you already hold
3190  * the lock (g_async_queue_unref_and_unlock). After that however, you
3191  * don't hold the lock anymore and the Queue might in fact be
3192  * destroyed, if you unrefed to zero */
3193 void          g_async_queue_ref                (GAsyncQueue *queue);
3194 void          g_async_queue_ref_unlocked       (GAsyncQueue *queue);
3195 void          g_async_queue_unref              (GAsyncQueue *queue);
3196 void          g_async_queue_unref_and_unlock   (GAsyncQueue *queue);
3197
3198 /* Push data into the async queue. Must not be NULL */
3199 void          g_async_queue_push               (GAsyncQueue *queue,
3200                                                 gpointer     data);
3201 void          g_async_queue_push_unlocked      (GAsyncQueue *queue,
3202                                                 gpointer     data);
3203
3204 /* Pop data from the async queue, when no data is there, the thread is blocked
3205  * until data arrives */
3206 gpointer      g_async_queue_pop                (GAsyncQueue *queue);
3207 gpointer      g_async_queue_pop_unlocked       (GAsyncQueue *queue);
3208
3209 /* Try to pop data, NULL is returned in case of empty queue */
3210 gpointer      g_async_queue_try_pop            (GAsyncQueue *queue);
3211 gpointer      g_async_queue_try_pop_unlocked   (GAsyncQueue *queue);
3212
3213 /* Wait for data until at maximum until end_time is reached, NULL is returned
3214  * in case of empty queue*/
3215 gpointer      g_async_queue_timed_pop          (GAsyncQueue *queue, 
3216                                                 GTimeVal    *end_time);
3217 gpointer      g_async_queue_timed_pop_unlocked (GAsyncQueue *queue, 
3218                                                 GTimeVal    *end_time);
3219
3220 /* Return the length of the queue, negative values mean, that threads
3221  * are waiting, positve values mean, that there are entries in the
3222  * queue. Actually this function returns the length of the queue minus
3223  * the number of waiting threads, g_async_queue_length == 0 could also
3224  * mean 'n' entries in the queue and 'n' thread waiting, such can
3225  * happen due to locking of the queue or due to scheduling. */
3226 gint          g_async_queue_length             (GAsyncQueue *queue);
3227 gint          g_async_queue_length_unlocked    (GAsyncQueue *queue);
3228
3229 /* Thread Pools
3230  */
3231
3232 /* The real GThreadPool is bigger, so you may only create a thread
3233  * pool with the constructor function */
3234 struct _GThreadPool
3235 {
3236   GFunc thread_func;
3237   gulong stack_size;
3238   gboolean bound; 
3239   GThreadPriority priority;
3240   gboolean exclusive;
3241   gpointer user_data;
3242 };
3243
3244 /* Get a thread pool with the function thread_func, at most max_threads may
3245  * run at a time (max_threads == -1 means no limit), stack_size, bound,
3246  * priority like in g_thread_create, exclusive == TRUE means, that the threads
3247  * shouldn't be shared and that they will be prestarted (otherwise they are
3248  * started, as needed) user_data is the 2nd argument to the thread_func */
3249 GThreadPool*    g_thread_pool_new             (GFunc            thread_func,
3250                                                gint             max_threads,
3251                                                gulong           stack_size,
3252                                                gboolean         bound,
3253                                                GThreadPriority  priority,
3254                                                gboolean         exclusive,
3255                                                gpointer         user_data);
3256
3257 /* Push new data into the thread pool. This task is assigned to a thread later
3258  * (when the maximal number of threads is reached for that pool) or now
3259  * (otherwise). If necessary a new thread will be started. The function
3260  * returns immediatly */
3261 void            g_thread_pool_push            (GThreadPool     *pool,
3262                                                gpointer         data);
3263
3264 /* Set the number of threads, which can run concurrently for that pool, -1
3265  * means no limit. 0 means has the effect, that the pool won't process
3266  * requests until the limit is set higher again */
3267 void            g_thread_pool_set_max_threads (GThreadPool     *pool,
3268                                                gint             max_threads);
3269 gint            g_thread_pool_get_max_threads (GThreadPool     *pool);
3270
3271 /* Get the number of threads assigned to that pool. This number doesn't
3272  * necessarily represent the number of working threads in that pool */
3273 guint           g_thread_pool_get_num_threads (GThreadPool     *pool);
3274
3275 /* Get the number of unprocessed items in the pool */
3276 guint           g_thread_pool_unprocessed     (GThreadPool     *pool);
3277
3278 /* Free the pool, immediate means, that all unprocessed items in the queue
3279  * wont be processed, wait means, that the function doesn't return immediatly,
3280  * but after all threads in the pool are ready processing items. immediate
3281  * does however not mean, that threads are killed. */
3282 void            g_thread_pool_free            (GThreadPool     *pool,
3283                                                gboolean         immediate,
3284                                                gboolean         wait);
3285
3286 /* Set the maximal number of unused threads before threads will be stopped by
3287  * GLib, -1 means no limit */
3288 void            g_thread_pool_set_max_unused_threads (gint      max_threads);
3289 gint            g_thread_pool_get_max_unused_threads (void);
3290 guint           g_thread_pool_get_num_unused_threads (void);
3291
3292 /* Stop all currently unused threads, but leave the limit untouched */
3293 void            g_thread_pool_stop_unused_threads    (void);
3294
3295 #ifdef __cplusplus
3296 }
3297 #endif /* __cplusplus */
3298
3299
3300 #endif /* __G_LIB_H__ */