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