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