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