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