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