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