Make refcounting threadsafe by using atomic operations. (#166020, Wim
[platform/upstream/glib.git] / glib / giochannel.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * giochannel.c: IO Channel abstraction
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /*
24  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
28  */
29
30 /* 
31  * MT safe
32  */
33
34 #include "config.h"
35
36 #include <string.h>
37 #include <errno.h>
38
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42
43 #undef G_DISABLE_DEPRECATED
44
45 #include "glib.h"
46
47 #include "giochannel.h"
48
49 #include "glibintl.h"
50
51 #include "galias.h"
52
53 #define G_IO_NICE_BUF_SIZE      1024
54
55 /* This needs to be as wide as the largest character in any possible encoding */
56 #define MAX_CHAR_SIZE           10
57
58 /* Some simplifying macros, which reduce the need to worry whether the
59  * buffers have been allocated. These also make USE_BUF () an lvalue,
60  * which is used in g_io_channel_read_to_end ().
61  */
62 #define USE_BUF(channel)        ((channel)->encoding ? (channel)->encoded_read_buf \
63                                  : (channel)->read_buf)
64 #define BUF_LEN(string)         ((string) ? (string)->len : 0)
65
66 static GIOError         g_io_error_get_from_g_error     (GIOStatus    status,
67                                                          GError      *err);
68 static void             g_io_channel_purge              (GIOChannel  *channel);
69 static GIOStatus        g_io_channel_fill_buffer        (GIOChannel  *channel,
70                                                          GError     **err);
71 static GIOStatus        g_io_channel_read_line_backend  (GIOChannel  *channel,
72                                                          gsize       *length,
73                                                          gsize       *terminator_pos,
74                                                          GError     **error);
75
76 void
77 g_io_channel_init (GIOChannel *channel)
78 {
79   channel->ref_count = 1;
80   channel->encoding = g_strdup ("UTF-8");
81   channel->line_term = NULL;
82   channel->line_term_len = 0;
83   channel->buf_size = G_IO_NICE_BUF_SIZE;
84   channel->read_cd = (GIConv) -1;
85   channel->write_cd = (GIConv) -1;
86   channel->read_buf = NULL; /* Lazy allocate buffers */
87   channel->encoded_read_buf = NULL;
88   channel->write_buf = NULL;
89   channel->partial_write_buf[0] = '\0';
90   channel->use_buffer = TRUE;
91   channel->do_encode = FALSE;
92   channel->close_on_unref = FALSE;
93 }
94
95 GIOChannel *
96 g_io_channel_ref (GIOChannel *channel)
97 {
98   g_return_val_if_fail (channel != NULL, NULL);
99
100   g_atomic_int_inc (&channel->ref_count);
101
102   return channel;
103 }
104
105 void 
106 g_io_channel_unref (GIOChannel *channel)
107 {
108   gboolean is_zero;
109
110   g_return_if_fail (channel != NULL);
111
112   is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
113
114   if (G_UNLIKELY (is_zero))
115     {
116       if (channel->close_on_unref)
117         g_io_channel_shutdown (channel, TRUE, NULL);
118       else
119         g_io_channel_purge (channel);
120       g_free (channel->encoding);
121       if (channel->read_cd != (GIConv) -1)
122         g_iconv_close (channel->read_cd);
123       if (channel->write_cd != (GIConv) -1)
124         g_iconv_close (channel->write_cd);
125       if (channel->line_term)
126         g_free (channel->line_term);
127       if (channel->read_buf)
128         g_string_free (channel->read_buf, TRUE);
129       if (channel->write_buf)
130         g_string_free (channel->write_buf, TRUE);
131       if (channel->encoded_read_buf)
132         g_string_free (channel->encoded_read_buf, TRUE);
133       channel->funcs->io_free (channel);
134     }
135 }
136
137 static GIOError
138 g_io_error_get_from_g_error (GIOStatus status,
139                              GError *err)
140 {
141   switch (status)
142     {
143       case G_IO_STATUS_NORMAL:
144       case G_IO_STATUS_EOF:
145         return G_IO_ERROR_NONE;
146       case G_IO_STATUS_AGAIN:
147         return G_IO_ERROR_AGAIN;
148       case G_IO_STATUS_ERROR:
149         g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
150         
151         if (err->domain != G_IO_CHANNEL_ERROR)
152           return G_IO_ERROR_UNKNOWN;
153         switch (err->code)
154           {
155             case G_IO_CHANNEL_ERROR_INVAL:
156               return G_IO_ERROR_INVAL;
157             default:
158               return G_IO_ERROR_UNKNOWN;
159           }
160       default:
161         g_assert_not_reached ();
162         return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
163     }
164 }
165
166 /**
167  * g_io_channel_read:
168  * @channel: a #GIOChannel. 
169  * @buf: a buffer to read the data into (which should be at least count bytes long).
170  * @count: the number of bytes to read from the #GIOChannel.
171  * @bytes_read: returns the number of bytes actually read. 
172  * 
173  * Reads data from a #GIOChannel. 
174  * 
175  * Return value: %G_IO_ERROR_NONE if the operation was successful. 
176  *
177  * Deprecated: Use g_io_channel_read_chars() instead.
178  **/
179 GIOError 
180 g_io_channel_read (GIOChannel *channel, 
181                    gchar      *buf, 
182                    gsize       count,
183                    gsize      *bytes_read)
184 {
185   GError *err = NULL;
186   GIOError error;
187   GIOStatus status;
188
189   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
190   g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
191
192   if (count == 0)
193     {
194       if (bytes_read)
195         *bytes_read = 0;
196       return G_IO_ERROR_NONE;
197     }
198
199   g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
200
201   status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
202
203   error = g_io_error_get_from_g_error (status, err);
204
205   if (err)
206     g_error_free (err);
207
208   return error;
209 }
210
211 /**
212  * g_io_channel_write:
213  * @channel:  a #GIOChannel.
214  * @buf: the buffer containing the data to write. 
215  * @count: the number of bytes to write.
216  * @bytes_written:  the number of bytes actually written.
217  * 
218  * Writes data to a #GIOChannel. 
219  * 
220  * Return value:  %G_IO_ERROR_NONE if the operation was successful.
221  *
222  * Deprecated: Use g_io_channel_write_chars() instead.
223  **/
224 GIOError 
225 g_io_channel_write (GIOChannel  *channel, 
226                     const gchar *buf, 
227                     gsize        count,
228                     gsize       *bytes_written)
229 {
230   GError *err = NULL;
231   GIOError error;
232   GIOStatus status;
233
234   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
235   g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
236
237   status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
238
239   error = g_io_error_get_from_g_error (status, err);
240
241   if (err)
242     g_error_free (err);
243
244   return error;
245 }
246
247 /**
248  * g_io_channel_seek:
249  * @channel: a #GIOChannel. 
250  * @offset: an offset, in bytes, which is added to the position specified by @type
251  * @type: the position in the file, which can be %G_SEEK_CUR (the current
252  *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END (the end of the
253  *        file).
254  * 
255  * Sets the current position in the #GIOChannel, similar to the standard library
256  * function fseek(). 
257  * 
258  * Return value: %G_IO_ERROR_NONE if the operation was successful.
259  *
260  * Deprecated: Use g_io_channel_seek_position() instead.
261  **/
262 GIOError 
263 g_io_channel_seek  (GIOChannel   *channel,
264                     gint64        offset, 
265                     GSeekType     type)
266 {
267   GError *err = NULL;
268   GIOError error;
269   GIOStatus status;
270
271   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
272   g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
273
274   switch (type)
275     {
276       case G_SEEK_CUR:
277       case G_SEEK_SET:
278       case G_SEEK_END:
279         break;
280       default:
281         g_warning ("g_io_channel_seek: unknown seek type");
282         return G_IO_ERROR_UNKNOWN;
283     }
284
285   status = channel->funcs->io_seek (channel, offset, type, &err);
286
287   error = g_io_error_get_from_g_error (status, err);
288
289   if (err)
290     g_error_free (err);
291
292   return error;
293 }
294
295 /* The function g_io_channel_new_file() is prototyped in both
296  * giounix.c and giowin32.c, so we stick its documentation here.
297  */
298
299 /**
300  * g_io_channel_new_file:
301  * @filename: A string containing the name of a file.
302  * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
303  *        the same meaning as in fopen().
304  * @error: A location to return an error of type %G_FILE_ERROR.
305  *
306  * Open a file @filename as a #GIOChannel using mode @mode. This
307  * channel will be closed when the last reference to it is dropped,
308  * so there is no need to call g_io_channel_close() (though doing
309  * so will not cause problems, as long as no attempt is made to
310  * access the channel after it is closed).
311  *
312  * Return value: A #GIOChannel on success, %NULL on failure.
313  **/
314
315 /**
316  * g_io_channel_close:
317  * @channel: A #GIOChannel
318  * 
319  * Close an IO channel. Any pending data to be written will be
320  * flushed, ignoring errors. The channel will not be freed until the
321  * last reference is dropped using g_io_channel_unref(). 
322  *
323  * Deprecated: Use g_io_channel_shutdown() instead.
324  **/
325 void
326 g_io_channel_close (GIOChannel *channel)
327 {
328   GError *err = NULL;
329   
330   g_return_if_fail (channel != NULL);
331
332   g_io_channel_purge (channel);
333
334   channel->funcs->io_close (channel, &err);
335
336   if (err)
337     { /* No way to return the error */
338       g_warning ("Error closing channel: %s", err->message);
339       g_error_free (err);
340     }
341   
342   channel->close_on_unref = FALSE; /* Because we already did */
343   channel->is_readable = FALSE;
344   channel->is_writeable = FALSE;
345   channel->is_seekable = FALSE;
346 }
347
348 /**
349  * g_io_channel_shutdown:
350  * @channel: a #GIOChannel
351  * @flush: if %TRUE, flush pending
352  * @err: location to store a #GIOChannelError
353  * 
354  * Close an IO channel. Any pending data to be written will be
355  * flushed if @flush is %TRUE. The channel will not be freed until the
356  * last reference is dropped using g_io_channel_unref().
357  *
358  * Return value: the status of the operation.
359  **/
360 GIOStatus
361 g_io_channel_shutdown (GIOChannel *channel,
362                        gboolean    flush,
363                        GError    **err)
364 {
365   GIOStatus status, result;
366   GError *tmperr = NULL;
367   
368   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
369   g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
370
371   if (channel->write_buf && channel->write_buf->len > 0)
372     {
373       if (flush)
374         {
375           GIOFlags flags;
376       
377           /* Set the channel to blocking, to avoid a busy loop
378            */
379           flags = g_io_channel_get_flags (channel);
380           /* Ignore any errors here, they're irrelevant */
381           g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
382
383           result = g_io_channel_flush (channel, &tmperr);
384         }
385       else
386         result = G_IO_STATUS_NORMAL;
387
388       g_string_truncate(channel->write_buf, 0);
389     }
390   else
391     result = G_IO_STATUS_NORMAL;
392
393   if (channel->partial_write_buf[0] != '\0')
394     {
395       if (flush)
396         g_warning ("Partial character at end of write buffer not flushed.\n");
397       channel->partial_write_buf[0] = '\0';
398     }
399
400   status = channel->funcs->io_close (channel, err);
401
402   channel->close_on_unref = FALSE; /* Because we already did */
403   channel->is_readable = FALSE;
404   channel->is_writeable = FALSE;
405   channel->is_seekable = FALSE;
406
407   if (status != G_IO_STATUS_NORMAL)
408     {
409       g_clear_error (&tmperr);
410       return status;
411     }
412   else if (result != G_IO_STATUS_NORMAL)
413     {
414       g_propagate_error (err, tmperr);
415       return result;
416     }
417   else
418     return G_IO_STATUS_NORMAL;
419 }
420
421 /* This function is used for the final flush on close or unref */
422 static void
423 g_io_channel_purge (GIOChannel *channel)
424 {
425   GError *err = NULL;
426   GIOStatus status;
427
428   g_return_if_fail (channel != NULL);
429
430   if (channel->write_buf && channel->write_buf->len > 0)
431     {
432       GIOFlags flags;
433       
434       /* Set the channel to blocking, to avoid a busy loop
435        */
436       flags = g_io_channel_get_flags (channel);
437       g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
438
439       status = g_io_channel_flush (channel, &err);
440
441       if (err)
442         { /* No way to return the error */
443           g_warning ("Error flushing string: %s", err->message);
444           g_error_free (err);
445         }
446     }
447
448   /* Flush these in case anyone tries to close without unrefing */
449
450   if (channel->read_buf)
451     g_string_truncate (channel->read_buf, 0);
452   if (channel->write_buf)
453     g_string_truncate (channel->write_buf, 0);
454   if (channel->encoding)
455     {
456       if (channel->encoded_read_buf)
457         g_string_truncate (channel->encoded_read_buf, 0);
458
459       if (channel->partial_write_buf[0] != '\0')
460         {
461           g_warning ("Partial character at end of write buffer not flushed.\n");
462           channel->partial_write_buf[0] = '\0';
463         }
464     }
465 }
466
467 GSource *
468 g_io_create_watch (GIOChannel  *channel,
469                    GIOCondition condition)
470 {
471   g_return_val_if_fail (channel != NULL, NULL);
472
473   return channel->funcs->io_create_watch (channel, condition);
474 }
475
476 guint 
477 g_io_add_watch_full (GIOChannel    *channel,
478                      gint           priority,
479                      GIOCondition   condition,
480                      GIOFunc        func,
481                      gpointer       user_data,
482                      GDestroyNotify notify)
483 {
484   GSource *source;
485   guint id;
486   
487   g_return_val_if_fail (channel != NULL, 0);
488
489   source = g_io_create_watch (channel, condition);
490
491   if (priority != G_PRIORITY_DEFAULT)
492     g_source_set_priority (source, priority);
493   g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
494
495   id = g_source_attach (source, NULL);
496   g_source_unref (source);
497
498   return id;
499 }
500
501 guint 
502 g_io_add_watch (GIOChannel    *channel,
503                 GIOCondition   condition,
504                 GIOFunc        func,
505                 gpointer       user_data)
506 {
507   return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
508 }
509
510 /**
511  * g_io_channel_get_buffer_condition:
512  * @channel: A #GIOChannel
513  *
514  * This function returns a #GIOCondition depending on whether there
515  * is data to be read/space to write data in the
516  * internal buffers in the #GIOChannel. Only the flags %G_IO_IN and
517  * %G_IO_OUT may be set.
518  *
519  * Return value: A #GIOCondition
520  **/
521 GIOCondition
522 g_io_channel_get_buffer_condition (GIOChannel *channel)
523 {
524   GIOCondition condition = 0;
525
526   if (channel->encoding)
527     {
528       if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
529         condition |= G_IO_IN; /* Only return if we have full characters */
530     }
531   else
532     {
533       if (channel->read_buf && (channel->read_buf->len > 0))
534         condition |= G_IO_IN;
535     }
536
537   if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
538     condition |= G_IO_OUT;
539
540   return condition;
541 }
542
543 /**
544  * g_io_channel_error_from_errno:
545  * @en: an <literal>errno</literal> error number, e.g. %EINVAL.
546  *
547  * Converts an <literal>errno</literal> error number to a #GIOChannelError.
548  *
549  * Return value: a #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL.
550  **/
551 GIOChannelError
552 g_io_channel_error_from_errno (gint en)
553 {
554 #ifdef EAGAIN
555   g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
556 #endif
557
558   switch (en)
559     {
560 #ifdef EBADF
561     case EBADF:
562       g_warning("Invalid file descriptor.\n");
563       return G_IO_CHANNEL_ERROR_FAILED;
564 #endif
565
566 #ifdef EFAULT
567     case EFAULT:
568       g_warning("Buffer outside valid address space.\n");
569       return G_IO_CHANNEL_ERROR_FAILED;
570 #endif
571
572 #ifdef EFBIG
573     case EFBIG:
574       return G_IO_CHANNEL_ERROR_FBIG;
575 #endif
576
577 #ifdef EINTR
578     /* In general, we should catch EINTR before we get here,
579      * but close() is allowed to return EINTR by POSIX, so
580      * we need to catch it here; EINTR from close() is
581      * unrecoverable, because it's undefined whether
582      * the fd was actually closed or not, so we just return
583      * a generic error code.
584      */
585     case EINTR:
586       return G_IO_CHANNEL_ERROR_FAILED;
587 #endif
588
589 #ifdef EINVAL
590     case EINVAL:
591       return G_IO_CHANNEL_ERROR_INVAL;
592 #endif
593
594 #ifdef EIO
595     case EIO:
596       return G_IO_CHANNEL_ERROR_IO;
597 #endif
598
599 #ifdef EISDIR
600     case EISDIR:
601       return G_IO_CHANNEL_ERROR_ISDIR;
602 #endif
603
604 #ifdef ENOSPC
605     case ENOSPC:
606       return G_IO_CHANNEL_ERROR_NOSPC;
607 #endif
608
609 #ifdef ENXIO
610     case ENXIO:
611       return G_IO_CHANNEL_ERROR_NXIO;
612 #endif
613
614 #ifdef EOVERFLOW
615     case EOVERFLOW:
616       return G_IO_CHANNEL_ERROR_OVERFLOW;
617 #endif
618
619 #ifdef EPIPE
620     case EPIPE:
621       return G_IO_CHANNEL_ERROR_PIPE;
622 #endif
623
624     default:
625       return G_IO_CHANNEL_ERROR_FAILED;
626     }
627 }
628
629 /**
630  * g_io_channel_set_buffer_size:
631  * @channel: a #GIOChannel
632  * @size: the size of the buffer. 0 == pick a good size
633  *
634  * Sets the buffer size.
635  **/  
636 void
637 g_io_channel_set_buffer_size (GIOChannel        *channel,
638                               gsize              size)
639 {
640   g_return_if_fail (channel != NULL);
641
642   if (size == 0)
643     size = G_IO_NICE_BUF_SIZE;
644
645   if (size < MAX_CHAR_SIZE)
646     size = MAX_CHAR_SIZE;
647
648   channel->buf_size = size;
649 }
650
651 /**
652  * g_io_channel_get_buffer_size:
653  * @channel: a #GIOChannel
654  *
655  * Gets the buffer size.
656  *
657  * Return value: the size of the buffer.
658  **/  
659 gsize
660 g_io_channel_get_buffer_size (GIOChannel        *channel)
661 {
662   g_return_val_if_fail (channel != NULL, 0);
663
664   return channel->buf_size;
665 }
666
667 /**
668  * g_io_channel_set_line_term:
669  * @channel: a #GIOChannel
670  * @line_term: The line termination string. Use %NULL for auto detect.
671  *             Auto detection breaks on "\n", "\r\n", "\r", "\0", and
672  *             the Unicode paragraph separator. Auto detection should
673  *             not be used for anything other than file-based channels.
674  * @length: The length of the termination string. If -1 is passed, the
675  *          string is assumed to be nul-terminated. This option allows
676  *          termination strings with embeded nuls.
677  *
678  * This sets the string that #GIOChannel uses to determine
679  * where in the file a line break occurs.
680  **/
681 void
682 g_io_channel_set_line_term (GIOChannel  *channel,
683                             const gchar *line_term,
684                             gint         length)
685 {
686   g_return_if_fail (channel != NULL);
687   g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
688
689   if (line_term == NULL)
690     length = 0;
691   else if (length < 0)
692     length = strlen (line_term);
693
694   if (channel->line_term)
695     g_free (channel->line_term);
696   channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
697   channel->line_term_len = length;
698 }
699
700 /**
701  * g_io_channel_get_line_term:
702  * @channel: a #GIOChannel
703  * @length: a location to return the length of the line terminator
704  *
705  * This returns the string that #GIOChannel uses to determine
706  * where in the file a line break occurs. A value of %NULL
707  * indicates auto detection.
708  *
709  * Return value: The line termination string. This value
710  *   is owned by GLib and must not be freed.
711  **/
712 G_CONST_RETURN gchar*
713 g_io_channel_get_line_term (GIOChannel  *channel,
714                             gint        *length)
715 {
716   g_return_val_if_fail (channel != NULL, NULL);
717
718   if (length)
719     *length = channel->line_term_len;
720
721   return channel->line_term;
722 }
723
724 /**
725  * g_io_channel_set_flags:
726  * @channel: a #GIOChannel.
727  * @flags: the flags to set on the IO channel.
728  * @error: A location to return an error of type #GIOChannelError.
729  *
730  * Sets the (writeable) flags in @channel to (@flags & %G_IO_CHANNEL_SET_MASK).
731  *
732  * Return value: the status of the operation. 
733  **/
734 GIOStatus
735 g_io_channel_set_flags (GIOChannel *channel,
736                         GIOFlags    flags,
737                         GError    **error)
738 {
739   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
740   g_return_val_if_fail ((error == NULL) || (*error == NULL),
741                         G_IO_STATUS_ERROR);
742
743   return (* channel->funcs->io_set_flags)(channel,
744                                           flags & G_IO_FLAG_SET_MASK,
745                                           error);
746 }
747
748 /**
749  * g_io_channel_get_flags:
750  * @channel: a #GIOChannel
751  *
752  * Gets the current flags for a #GIOChannel, including read-only
753  * flags such as %G_IO_FLAG_IS_READABLE.
754  *
755  * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITEABLE
756  * are cached for internal use by the channel when it is created.
757  * If they should change at some later point (e.g. partial shutdown
758  * of a socket with the UNIX shutdown() function), the user
759  * should immediately call g_io_channel_get_flags () to update
760  * the internal values of these flags.
761  *
762  * Return value: the flags which are set on the channel
763  **/
764 GIOFlags
765 g_io_channel_get_flags (GIOChannel *channel)
766 {
767   GIOFlags flags;
768
769   g_return_val_if_fail (channel != NULL, 0);
770
771   flags = (* channel->funcs->io_get_flags) (channel);
772
773   /* Cross implementation code */
774
775   if (channel->is_seekable)
776     flags |= G_IO_FLAG_IS_SEEKABLE;
777   if (channel->is_readable)
778     flags |= G_IO_FLAG_IS_READABLE;
779   if (channel->is_writeable)
780     flags |= G_IO_FLAG_IS_WRITEABLE;
781
782   return flags;
783 }
784
785 /**
786  * g_io_channel_set_close_on_unref:
787  * @channel: a #GIOChannel
788  * @do_close: Whether to close the channel on the final unref of
789  *            the GIOChannel data structure. The default value of
790  *            this is %TRUE for channels created by g_io_channel_new_file (),
791  *            and %FALSE for all other channels.
792  *
793  * Setting this flag to %TRUE for a channel you have already closed
794  * can cause problems.
795  **/
796 void
797 g_io_channel_set_close_on_unref (GIOChannel *channel,
798                                  gboolean    do_close)
799 {
800   g_return_if_fail (channel != NULL);
801
802   channel->close_on_unref = do_close;
803 }
804
805 /**
806  * g_io_channel_get_close_on_unref:
807  * @channel: a #GIOChannel.
808  *
809  * Returns whether the file/socket/whatever associated with @channel
810  * will be closed when @channel receives its final unref and is
811  * destroyed. The default value of this is %TRUE for channels created
812  * by g_io_channel_new_file (), and %FALSE for all other channels.
813  *
814  * Return value: Whether the channel will be closed on the final unref of
815  *               the GIOChannel data structure.
816  **/
817 gboolean
818 g_io_channel_get_close_on_unref (GIOChannel *channel)
819 {
820   g_return_val_if_fail (channel != NULL, FALSE);
821
822   return channel->close_on_unref;
823 }
824
825 /**
826  * g_io_channel_seek_position:
827  * @channel: a #GIOChannel
828  * @offset: The offset in bytes from the position specified by @type
829  * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
830  *                      cases where a call to g_io_channel_set_encoding ()
831  *                      is allowed. See the documentation for
832  *                      g_io_channel_set_encoding () for details.
833  * @error: A location to return an error of type #GIOChannelError
834  *
835  * Replacement for g_io_channel_seek() with the new API.
836  *
837  * Return value: the status of the operation.
838  **/
839 GIOStatus
840 g_io_channel_seek_position      (GIOChannel* channel,
841                                  gint64      offset,
842                                  GSeekType   type,
843                                  GError    **error)
844 {
845   GIOStatus status;
846
847   /* For files, only one of the read and write buffers can contain data.
848    * For sockets, both can contain data.
849    */
850
851   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
852   g_return_val_if_fail ((error == NULL) || (*error == NULL),
853                         G_IO_STATUS_ERROR);
854   g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
855
856   switch (type)
857     {
858       case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
859         if (channel->use_buffer)
860           {
861             if (channel->do_encode && channel->encoded_read_buf
862                 && channel->encoded_read_buf->len > 0)
863               {
864                 g_warning ("Seek type G_SEEK_CUR not allowed for this"
865                   " channel's encoding.\n");
866                 return G_IO_STATUS_ERROR;
867               }
868           if (channel->read_buf)
869             offset -= channel->read_buf->len;
870           if (channel->encoded_read_buf)
871             {
872               g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
873
874               /* If there's anything here, it's because the encoding is UTF-8,
875                * so we can just subtract the buffer length, the same as for
876                * the unencoded data.
877                */
878
879               offset -= channel->encoded_read_buf->len;
880             }
881           }
882         break;
883       case G_SEEK_SET:
884       case G_SEEK_END:
885         break;
886       default:
887         g_warning ("g_io_channel_seek_position: unknown seek type");
888         return G_IO_STATUS_ERROR;
889     }
890
891   if (channel->use_buffer)
892     {
893       status = g_io_channel_flush (channel, error);
894       if (status != G_IO_STATUS_NORMAL)
895         return status;
896     }
897
898   status = channel->funcs->io_seek (channel, offset, type, error);
899
900   if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
901     {
902       if (channel->read_buf)
903         g_string_truncate (channel->read_buf, 0);
904
905       /* Conversion state no longer matches position in file */
906       if (channel->read_cd != (GIConv) -1)
907         g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
908       if (channel->write_cd != (GIConv) -1)
909         g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
910
911       if (channel->encoded_read_buf)
912         {
913           g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
914           g_string_truncate (channel->encoded_read_buf, 0);
915         }
916
917       if (channel->partial_write_buf[0] != '\0')
918         {
919           g_warning ("Partial character at end of write buffer not flushed.\n");
920           channel->partial_write_buf[0] = '\0';
921         }
922     }
923
924   return status;
925 }
926
927 /**
928  * g_io_channel_flush:
929  * @channel: a #GIOChannel
930  * @error: location to store an error of type #GIOChannelError
931  *
932  * Flushes the write buffer for the GIOChannel.
933  *
934  * Return value: the status of the operation: One of
935  *   #G_IO_CHANNEL_NORMAL, #G_IO_CHANNEL_AGAIN, or
936  *   #G_IO_CHANNEL_ERROR.
937  **/
938 GIOStatus
939 g_io_channel_flush (GIOChannel  *channel,
940                     GError     **error)
941 {
942   GIOStatus status;
943   gsize this_time = 1, bytes_written = 0;
944
945   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
946   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
947
948   if (channel->write_buf == NULL || channel->write_buf->len == 0)
949     return G_IO_STATUS_NORMAL;
950
951   do
952     {
953       g_assert (this_time > 0);
954
955       status = channel->funcs->io_write (channel,
956                                          channel->write_buf->str + bytes_written,
957                                          channel->write_buf->len - bytes_written,
958                                          &this_time, error);
959       bytes_written += this_time;
960     }
961   while ((bytes_written < channel->write_buf->len)
962          && (status == G_IO_STATUS_NORMAL));
963
964   g_string_erase (channel->write_buf, 0, bytes_written);
965
966   return status;
967 }
968
969 /**
970  * g_io_channel_set_buffered:
971  * @channel: a #GIOChannel
972  * @buffered: whether to set the channel buffered or unbuffered
973  *
974  * The buffering state can only be set if the channel's encoding
975  * is %NULL. For any other encoding, the channel must be buffered.
976  *
977  * A buffered channel can only be set unbuffered if the channel's
978  * internal buffers have been flushed. Newly created channels or
979  * channels which have returned %G_IO_STATUS_EOF
980  * not require such a flush. For write-only channels, a call to
981  * g_io_channel_flush () is sufficient. For all other channels,
982  * the buffers may be flushed by a call to g_io_channel_seek_position ().
983  * This includes the possibility of seeking with seek type %G_SEEK_CUR
984  * and an offset of zero. Note that this means that socket-based
985  * channels cannot be set unbuffered once they have had data
986  * read from them.
987  *
988  * On unbuffered channels, it is safe to mix read and write
989  * calls from the new and old APIs, if this is necessary for
990  * maintaining old code.
991  *
992  * The default state of the channel is buffered.
993  **/
994 void
995 g_io_channel_set_buffered       (GIOChannel *channel,
996                                  gboolean    buffered)
997 {
998   g_return_if_fail (channel != NULL);
999
1000   if (channel->encoding != NULL)
1001     {
1002       g_warning ("Need to have NULL encoding to set the buffering state of the "
1003                  "channel.\n");
1004       return;
1005     }
1006
1007   g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
1008   g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
1009
1010   channel->use_buffer = buffered;
1011 }
1012
1013 /**
1014  * g_io_channel_get_buffered:
1015  * @channel: a #GIOChannel.
1016  *
1017  * Returns whether @channel is buffered.
1018  *
1019  * Return Value: %TRUE if the @channel is buffered. 
1020  **/
1021 gboolean
1022 g_io_channel_get_buffered       (GIOChannel *channel)
1023 {
1024   g_return_val_if_fail (channel != NULL, FALSE);
1025
1026   return channel->use_buffer;
1027 }
1028
1029 /**
1030  * g_io_channel_set_encoding:
1031  * @channel: a #GIOChannel
1032  * @encoding: the encoding type
1033  * @error: location to store an error of type #GConvertError.
1034  *
1035  * Sets the encoding for the input/output of the channel. The internal
1036  * encoding is always UTF-8. The default encoding for the
1037  * external file is UTF-8.
1038  *
1039  * The encoding %NULL is safe to use with binary data.
1040  *
1041  * The encoding can only be set if one of the following conditions
1042  * is true:
1043  *
1044  * 1. The channel was just created, and has not been written to
1045  *    or read from yet.
1046  *
1047  * 2. The channel is write-only.
1048  *
1049  * 3. The channel is a file, and the file pointer was just
1050  *    repositioned by a call to g_io_channel_seek_position().
1051  *    (This flushes all the internal buffers.)
1052  *
1053  * 4. The current encoding is %NULL or UTF-8.
1054  *
1055  * 5. One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1056  *    (or, in the case of g_io_channel_read_to_end (), %G_IO_STATUS_NORMAL).
1057  *
1058  * 6. One of the functions g_io_channel_read_chars () or g_io_channel_read_unichar ()
1059  *    has returned %G_IO_STATUS_AGAIN or %G_IO_STATUS_ERROR. This may be
1060  *    useful in the case of %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1061  *    Returning one of these statuses from g_io_channel_read_line (),
1062  *    g_io_channel_read_line_string (), or g_io_channel_read_to_end ()
1063  *    does <emphasis>not</emphasis> guarantee that the encoding can be changed.
1064  *
1065  * Channels which do not meet one of the above conditions cannot call
1066  * g_io_channel_seek_position () with an offset of %G_SEEK_CUR,
1067  * and, if they are "seekable", cannot
1068  * call g_io_channel_write_chars () after calling one
1069  * of the API "read" functions.
1070  *
1071  * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1072  **/
1073 GIOStatus
1074 g_io_channel_set_encoding (GIOChannel   *channel,
1075                            const gchar  *encoding,
1076                            GError      **error)
1077 {
1078   GIConv read_cd, write_cd;
1079   gboolean did_encode;
1080
1081   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1082   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1083
1084   /* Make sure the encoded buffers are empty */
1085
1086   g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1087                         channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1088
1089   if (!channel->use_buffer)
1090     {
1091       g_warning ("Need to set the channel buffered before setting the encoding.\n");
1092       g_warning ("Assuming this is what you meant and acting accordingly.\n");
1093
1094       channel->use_buffer = TRUE;
1095     }
1096
1097   if (channel->partial_write_buf[0] != '\0')
1098     {
1099       g_warning ("Partial character at end of write buffer not flushed.\n");
1100       channel->partial_write_buf[0] = '\0';
1101     }
1102
1103   did_encode = channel->do_encode;
1104
1105   if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1106     {
1107       channel->do_encode = FALSE;
1108       read_cd = write_cd = (GIConv) -1;
1109     }
1110   else
1111     {
1112       gint err = 0;
1113       const gchar *from_enc = NULL, *to_enc = NULL;
1114
1115       if (channel->is_readable)
1116         {
1117           read_cd = g_iconv_open ("UTF-8", encoding);
1118
1119           if (read_cd == (GIConv) -1)
1120             {
1121               err = errno;
1122               from_enc = "UTF-8";
1123               to_enc = encoding;
1124             }
1125         }
1126       else
1127         read_cd = (GIConv) -1;
1128
1129       if (channel->is_writeable && err == 0)
1130         {
1131           write_cd = g_iconv_open (encoding, "UTF-8");
1132
1133           if (write_cd == (GIConv) -1)
1134             {
1135               err = errno;
1136               from_enc = encoding;
1137               to_enc = "UTF-8";
1138             }
1139         }
1140       else
1141         write_cd = (GIConv) -1;
1142
1143       if (err != 0)
1144         {
1145           g_assert (from_enc);
1146           g_assert (to_enc);
1147
1148           if (err == EINVAL)
1149             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1150                          _("Conversion from character set `%s' to `%s' is not supported"),
1151                          from_enc, to_enc);
1152           else
1153             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1154                          _("Could not open converter from `%s' to `%s': %s"),
1155                          from_enc, to_enc, g_strerror (err));
1156
1157           if (read_cd != (GIConv) -1)
1158             g_iconv_close (read_cd);
1159           if (write_cd != (GIConv) -1)
1160             g_iconv_close (write_cd);
1161
1162           return G_IO_STATUS_ERROR;
1163         }
1164
1165       channel->do_encode = TRUE;
1166     }
1167
1168   /* The encoding is ok, so set the fields in channel */
1169
1170   if (channel->read_cd != (GIConv) -1)
1171     g_iconv_close (channel->read_cd);
1172   if (channel->write_cd != (GIConv) -1)
1173     g_iconv_close (channel->write_cd);
1174
1175   if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1176     {
1177       g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1178
1179       /* This is just validated UTF-8, so we can copy it back into read_buf
1180        * so it can be encoded in whatever the new encoding is.
1181        */
1182
1183       g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1184                             channel->encoded_read_buf->len);
1185       g_string_truncate (channel->encoded_read_buf, 0);
1186     }
1187
1188   channel->read_cd = read_cd;
1189   channel->write_cd = write_cd;
1190
1191   g_free (channel->encoding);
1192   channel->encoding = g_strdup (encoding);
1193
1194   return G_IO_STATUS_NORMAL;
1195 }
1196
1197 /**
1198  * g_io_channel_get_encoding:
1199  * @channel: a #GIOChannel
1200  *
1201  * Gets the encoding for the input/output of the channel. The internal
1202  * encoding is always UTF-8. The encoding %NULL makes the
1203  * channel safe for binary data.
1204  *
1205  * Return value: A string containing the encoding, this string is
1206  *   owned by GLib and must not be freed.
1207  **/
1208 G_CONST_RETURN gchar*
1209 g_io_channel_get_encoding (GIOChannel      *channel)
1210 {
1211   g_return_val_if_fail (channel != NULL, NULL);
1212
1213   return channel->encoding;
1214 }
1215
1216 static GIOStatus
1217 g_io_channel_fill_buffer (GIOChannel *channel,
1218                           GError    **err)
1219 {
1220   gsize read_size, cur_len, oldlen;
1221   GIOStatus status;
1222
1223   if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1224     {
1225       status = g_io_channel_flush (channel, err);
1226       if (status != G_IO_STATUS_NORMAL)
1227         return status;
1228     }
1229   if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1230     {
1231       g_warning ("Partial character at end of write buffer not flushed.\n");
1232       channel->partial_write_buf[0] = '\0';
1233     }
1234
1235   if (!channel->read_buf)
1236     channel->read_buf = g_string_sized_new (channel->buf_size);
1237
1238   cur_len = channel->read_buf->len;
1239
1240   g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1241
1242   status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1243                                     channel->buf_size, &read_size, err);
1244
1245   g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1246
1247   g_string_truncate (channel->read_buf, read_size + cur_len);
1248
1249   if ((status != G_IO_STATUS_NORMAL)
1250     && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1251     return status;
1252
1253   g_assert (channel->read_buf->len > 0);
1254
1255   if (channel->encoded_read_buf)
1256     oldlen = channel->encoded_read_buf->len;
1257   else
1258     {
1259       oldlen = 0;
1260       if (channel->encoding)
1261         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1262     }
1263
1264   if (channel->do_encode)
1265     {
1266       size_t errnum, inbytes_left, outbytes_left;
1267       gchar *inbuf, *outbuf;
1268       int errval;
1269
1270       g_assert (channel->encoded_read_buf);
1271
1272 reencode:
1273
1274       inbytes_left = channel->read_buf->len;
1275       outbytes_left = MAX (channel->read_buf->len,
1276                            channel->encoded_read_buf->allocated_len
1277                            - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1278       outbytes_left = MAX (outbytes_left, 6);
1279
1280       inbuf = channel->read_buf->str;
1281       g_string_set_size (channel->encoded_read_buf,
1282                          channel->encoded_read_buf->len + outbytes_left);
1283       outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1284                - outbytes_left;
1285
1286       errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1287                         &outbuf, &outbytes_left);
1288       errval = errno;
1289
1290       g_assert (inbuf + inbytes_left == channel->read_buf->str
1291                 + channel->read_buf->len);
1292       g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1293                 + channel->encoded_read_buf->len);
1294
1295       g_string_erase (channel->read_buf, 0,
1296                       channel->read_buf->len - inbytes_left);
1297       g_string_truncate (channel->encoded_read_buf,
1298                          channel->encoded_read_buf->len - outbytes_left);
1299
1300       if (errnum == (size_t) -1)
1301         {
1302           switch (errval)
1303             {
1304               case EINVAL:
1305                 if ((oldlen == channel->encoded_read_buf->len)
1306                   && (status == G_IO_STATUS_EOF))
1307                   status = G_IO_STATUS_EOF;
1308                 else
1309                   status = G_IO_STATUS_NORMAL;
1310                 break;
1311               case E2BIG:
1312                 /* Buffer size at least 6, wrote at least on character */
1313                 g_assert (inbuf != channel->read_buf->str);
1314                 goto reencode;
1315               case EILSEQ:
1316                 if (oldlen < channel->encoded_read_buf->len)
1317                   status = G_IO_STATUS_NORMAL;
1318                 else
1319                   {
1320                     g_set_error (err, G_CONVERT_ERROR,
1321                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1322                       _("Invalid byte sequence in conversion input"));
1323                     return G_IO_STATUS_ERROR;
1324                   }
1325                 break;
1326               default:
1327                 g_assert (errval != EBADF); /* The converter should be open */
1328                 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1329                   _("Error during conversion: %s"), g_strerror (errval));
1330                 return G_IO_STATUS_ERROR;
1331             }
1332         }
1333       g_assert ((status != G_IO_STATUS_NORMAL)
1334                || (channel->encoded_read_buf->len > 0));
1335     }
1336   else if (channel->encoding) /* UTF-8 */
1337     {
1338       gchar *nextchar, *lastchar;
1339
1340       g_assert (channel->encoded_read_buf);
1341
1342       nextchar = channel->read_buf->str;
1343       lastchar = channel->read_buf->str + channel->read_buf->len;
1344
1345       while (nextchar < lastchar)
1346         {
1347           gunichar val_char;
1348
1349           val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1350
1351           switch (val_char)
1352             {
1353               case -2:
1354                 /* stop, leave partial character in buffer */
1355                 lastchar = nextchar;
1356                 break;
1357               case -1:
1358                 if (oldlen < channel->encoded_read_buf->len)
1359                   status = G_IO_STATUS_NORMAL;
1360                 else
1361                   {
1362                     g_set_error (err, G_CONVERT_ERROR,
1363                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1364                       _("Invalid byte sequence in conversion input"));
1365                     status = G_IO_STATUS_ERROR;
1366                   }
1367                 lastchar = nextchar;
1368                 break;
1369               default:
1370                 nextchar = g_utf8_next_char (nextchar);
1371                 break;
1372             }
1373         }
1374
1375       if (lastchar > channel->read_buf->str)
1376         {
1377           gint copy_len = lastchar - channel->read_buf->str;
1378
1379           g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1380                                copy_len);
1381           g_string_erase (channel->read_buf, 0, copy_len);
1382         }
1383     }
1384
1385   return status;
1386 }
1387
1388 /**
1389  * g_io_channel_read_line:
1390  * @channel: a #GIOChannel
1391  * @str_return: The line read from the #GIOChannel, including the
1392  *              line terminator. This data should be freed with g_free()
1393  *              when no longer needed. This is a nul-terminated string. 
1394  *              If a @length of zero is returned, this will be %NULL instead.
1395  * @length: location to store length of the read data, or %NULL
1396  * @terminator_pos: location to store position of line terminator, or %NULL
1397  * @error: A location to return an error of type #GConvertError
1398  *         or #GIOChannelError
1399  *
1400  * Reads a line, including the terminating character(s),
1401  * from a #GIOChannel into a newly-allocated string.
1402  * @str_return will contain allocated memory if the return
1403  * is %G_IO_STATUS_NORMAL.
1404  *
1405  * Return value: the status of the operation.
1406  **/
1407 GIOStatus
1408 g_io_channel_read_line (GIOChannel *channel,
1409                         gchar     **str_return,
1410                         gsize      *length,
1411                         gsize      *terminator_pos,
1412                         GError    **error)
1413 {
1414   GIOStatus status;
1415   gsize got_length;
1416   
1417   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1418   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1419   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1420                         G_IO_STATUS_ERROR);
1421   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1422
1423   status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1424
1425   if (length)
1426     *length = got_length;
1427
1428   if (status == G_IO_STATUS_NORMAL)
1429     {
1430       g_assert (USE_BUF (channel));
1431       *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1432       g_string_erase (USE_BUF (channel), 0, got_length);
1433     }
1434   else
1435     *str_return = NULL;
1436   
1437   return status;
1438 }
1439
1440 /**
1441  * g_io_channel_read_line_string:
1442  * @channel: a #GIOChannel
1443  * @buffer: a #GString into which the line will be written.
1444  *          If @buffer already contains data, the old data will
1445  *          be overwritten.
1446  * @terminator_pos: location to store position of line terminator, or %NULL
1447  * @error: a location to store an error of type #GConvertError
1448  *         or #GIOChannelError
1449  *
1450  * Reads a line from a #GIOChannel, using a #GString as a buffer.
1451  *
1452  * Return value: the status of the operation.
1453  **/
1454 GIOStatus
1455 g_io_channel_read_line_string (GIOChannel *channel,
1456                                GString    *buffer,
1457                                gsize      *terminator_pos,
1458                                GError    **error)
1459 {
1460   gsize length;
1461   GIOStatus status;
1462
1463   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1464   g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1465   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1466                         G_IO_STATUS_ERROR);
1467   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1468
1469   if (buffer->len > 0)
1470     g_string_truncate (buffer, 0); /* clear out the buffer */
1471
1472   status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1473
1474   if (status == G_IO_STATUS_NORMAL)
1475     {
1476       g_assert (USE_BUF (channel));
1477       g_string_append_len (buffer, USE_BUF (channel)->str, length);
1478       g_string_erase (USE_BUF (channel), 0, length);
1479     }
1480
1481   return status;
1482 }
1483
1484
1485 static GIOStatus
1486 g_io_channel_read_line_backend  (GIOChannel *channel,
1487                                  gsize      *length,
1488                                  gsize      *terminator_pos,
1489                                  GError    **error)
1490 {
1491   GIOStatus status;
1492   gsize checked_to, line_term_len, line_length, got_term_len;
1493   gboolean first_time = TRUE;
1494
1495   if (!channel->use_buffer)
1496     {
1497       /* Can't do a raw read in read_line */
1498       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1499                    _("Can't do a raw read in g_io_channel_read_line_string"));
1500       return G_IO_STATUS_ERROR;
1501     }
1502
1503   status = G_IO_STATUS_NORMAL;
1504
1505   if (channel->line_term)
1506     line_term_len = channel->line_term_len;
1507   else
1508     line_term_len = 3;
1509     /* This value used for setting checked_to, it's the longest of the four
1510      * we autodetect for.
1511      */
1512
1513   checked_to = 0;
1514
1515   while (TRUE)
1516     {
1517       gchar *nextchar, *lastchar;
1518       GString *use_buf;
1519
1520       if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1521         {
1522 read_again:
1523           status = g_io_channel_fill_buffer (channel, error);
1524           switch (status)
1525             {
1526               case G_IO_STATUS_NORMAL:
1527                 if (BUF_LEN (USE_BUF (channel)) == 0)
1528                   /* Can happen when using conversion and only read
1529                    * part of a character
1530                    */
1531                   {
1532                     first_time = FALSE;
1533                     continue;
1534                   }
1535                 break;
1536               case G_IO_STATUS_EOF:
1537                 if (BUF_LEN (USE_BUF (channel)) == 0)
1538                   {
1539                     if (length)
1540                       *length = 0;
1541
1542                     if (channel->encoding && channel->read_buf->len != 0)
1543                       {
1544                         g_set_error (error, G_CONVERT_ERROR,
1545                                      G_CONVERT_ERROR_PARTIAL_INPUT,
1546                                      _("Leftover unconverted data in read buffer"));
1547                         return G_IO_STATUS_ERROR;
1548                       }
1549                     else
1550                       return G_IO_STATUS_EOF;
1551                   }
1552                 break;
1553               default:
1554                 if (length)
1555                   *length = 0;
1556                 return status;
1557             }
1558         }
1559
1560       g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1561
1562       use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1563
1564       first_time = FALSE;
1565
1566       lastchar = use_buf->str + use_buf->len;
1567
1568       for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1569            channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1570         {
1571           if (channel->line_term)
1572             {
1573               if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1574                 {
1575                   line_length = nextchar - use_buf->str;
1576                   got_term_len = line_term_len;
1577                   goto done;
1578                 }
1579             }
1580           else /* auto detect */
1581             {
1582               switch (*nextchar)
1583                 {
1584                   case '\n': /* unix */
1585                     line_length = nextchar - use_buf->str;
1586                     got_term_len = 1;
1587                     goto done;
1588                   case '\r': /* Warning: do not use with sockets */
1589                     line_length = nextchar - use_buf->str;
1590                     if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1591                        && (lastchar == use_buf->str + use_buf->len))
1592                       goto read_again; /* Try to read more data */
1593                     if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1594                       got_term_len = 2;
1595                     else /* mac */
1596                       got_term_len = 1;
1597                     goto done;
1598                   case '\xe2': /* Unicode paragraph separator */
1599                     if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1600                       {
1601                         line_length = nextchar - use_buf->str;
1602                         got_term_len = 3;
1603                         goto done;
1604                       }
1605                     break;
1606                   case '\0': /* Embeded null in input */
1607                     line_length = nextchar - use_buf->str;
1608                     got_term_len = 1;
1609                     goto done;
1610                   default: /* no match */
1611                     break;
1612                 }
1613             }
1614         }
1615
1616       /* If encoding != NULL, valid UTF-8, didn't overshoot */
1617       g_assert (nextchar == lastchar);
1618
1619       /* Check for EOF */
1620
1621       if (status == G_IO_STATUS_EOF)
1622         {
1623           if (channel->encoding && channel->read_buf->len > 0)
1624             {
1625               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1626                            _("Channel terminates in a partial character"));
1627               return G_IO_STATUS_ERROR;
1628             }
1629           line_length = use_buf->len;
1630           got_term_len = 0;
1631           break;
1632         }
1633
1634       if (use_buf->len > line_term_len - 1)
1635         checked_to = use_buf->len - (line_term_len - 1);
1636       else
1637         checked_to = 0;
1638     }
1639
1640 done:
1641
1642   if (terminator_pos)
1643     *terminator_pos = line_length;
1644
1645   if (length)
1646     *length = line_length + got_term_len;
1647
1648   return G_IO_STATUS_NORMAL;
1649 }
1650
1651 /**
1652  * g_io_channel_read_to_end:
1653  * @channel: a #GIOChannel
1654  * @str_return: Location to store a pointer to a string holding
1655  *              the remaining data in the #GIOChannel. This data should
1656  *              be freed with g_free() when no longer needed. This
1657  *              data is terminated by an extra nul character, but there 
1658  *              may be other nuls in the intervening data.
1659  * @length: Location to store length of the data
1660  * @error: A location to return an error of type #GConvertError
1661  *         or #GIOChannelError
1662  *
1663  * Reads all the remaining data from the file.
1664  *
1665  * Return value: %G_IO_STATUS_NORMAL on success. 
1666  * This function never returns %G_IO_STATUS_EOF.
1667  **/
1668 GIOStatus
1669 g_io_channel_read_to_end (GIOChannel    *channel,
1670                           gchar        **str_return,
1671                           gsize         *length,
1672                           GError       **error)
1673 {
1674   GIOStatus status;
1675     
1676   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1677   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1678     G_IO_STATUS_ERROR);
1679   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1680
1681   if (str_return)
1682     *str_return = NULL;
1683   if (length)
1684     *length = 0;
1685
1686   if (!channel->use_buffer)
1687     {
1688       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1689                    _("Can't do a raw read in g_io_channel_read_to_end"));
1690       return G_IO_STATUS_ERROR;
1691     }
1692
1693   do
1694     status = g_io_channel_fill_buffer (channel, error);
1695   while (status == G_IO_STATUS_NORMAL);
1696
1697   if (status != G_IO_STATUS_EOF)
1698     return status;
1699
1700   if (channel->encoding && channel->read_buf->len > 0)
1701     {
1702       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1703                    _("Channel terminates in a partial character"));
1704       return G_IO_STATUS_ERROR;
1705     }
1706
1707   if (USE_BUF (channel) == NULL)
1708     {
1709       /* length is already set to zero */
1710       if (str_return)
1711         *str_return = g_strdup ("");
1712     }
1713   else
1714     {
1715       if (length)
1716         *length = USE_BUF (channel)->len;
1717
1718       if (str_return)
1719         *str_return = g_string_free (USE_BUF (channel), FALSE);
1720       else
1721         g_string_free (USE_BUF (channel), TRUE);
1722
1723       if (channel->encoding)
1724         channel->encoded_read_buf = NULL;
1725       else
1726         channel->read_buf = NULL;
1727     }
1728
1729   return G_IO_STATUS_NORMAL;
1730 }
1731
1732 /**
1733  * g_io_channel_read_chars:
1734  * @channel: a #GIOChannel
1735  * @buf: a buffer to read data into
1736  * @count: the size of the buffer. Note that the buffer may
1737  *         not be complelely filled even if there is data
1738  *         in the buffer if the remaining data is not a
1739  *         complete character.
1740  * @bytes_read: The number of bytes read. This may be zero even on
1741  *              success if count < 6 and the channel's encoding is non-%NULL.
1742  *              This indicates that the next UTF-8 character is too wide for
1743  *              the buffer.
1744  * @error: A location to return an error of type #GConvertError
1745  *         or #GIOChannelError.
1746  *
1747  * Replacement for g_io_channel_read() with the new API.
1748  *
1749  * Return value: the status of the operation.
1750  **/
1751 GIOStatus
1752 g_io_channel_read_chars (GIOChannel     *channel,
1753                          gchar          *buf,
1754                          gsize           count,
1755                          gsize          *bytes_read,
1756                          GError        **error)
1757 {
1758   GIOStatus status;
1759   gsize got_bytes;
1760
1761   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1762   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1763                         G_IO_STATUS_ERROR);
1764   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1765
1766   if (count == 0)
1767     {
1768       *bytes_read = 0;
1769       return G_IO_STATUS_NORMAL;
1770     }
1771   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1772
1773   if (!channel->use_buffer)
1774     {
1775       gsize tmp_bytes;
1776       
1777       g_assert (!channel->read_buf || channel->read_buf->len == 0);
1778
1779       status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
1780       
1781       if (bytes_read)
1782         *bytes_read = tmp_bytes;
1783
1784       return status;
1785     }
1786
1787   status = G_IO_STATUS_NORMAL;
1788
1789   while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
1790     status = g_io_channel_fill_buffer (channel, error);
1791
1792   /* Only return an error if we have no data */
1793
1794   if (BUF_LEN (USE_BUF (channel)) == 0)
1795     {
1796       g_assert (status != G_IO_STATUS_NORMAL);
1797
1798       if (status == G_IO_STATUS_EOF && channel->encoding
1799           && BUF_LEN (channel->read_buf) > 0)
1800         {
1801           g_set_error (error, G_CONVERT_ERROR,
1802                        G_CONVERT_ERROR_PARTIAL_INPUT,
1803                        _("Leftover unconverted data in read buffer"));
1804           status = G_IO_STATUS_ERROR;
1805         }
1806
1807       if (bytes_read)
1808         *bytes_read = 0;
1809
1810       return status;
1811     }
1812
1813   if (status == G_IO_STATUS_ERROR)
1814     g_clear_error (error);
1815
1816   got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
1817
1818   g_assert (got_bytes > 0);
1819
1820   if (channel->encoding)
1821     /* Don't validate for NULL encoding, binary safe */
1822     {
1823       gchar *nextchar, *prevchar;
1824
1825       g_assert (USE_BUF (channel) == channel->encoded_read_buf);
1826
1827       nextchar = channel->encoded_read_buf->str;
1828
1829       do
1830         {
1831           prevchar = nextchar;
1832           nextchar = g_utf8_next_char (nextchar);
1833           g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
1834         }
1835       while (nextchar < channel->encoded_read_buf->str + got_bytes);
1836
1837       if (nextchar > channel->encoded_read_buf->str + got_bytes)
1838         got_bytes = prevchar - channel->encoded_read_buf->str;
1839
1840       g_assert (got_bytes > 0 || count < 6);
1841     }
1842
1843   memcpy (buf, USE_BUF (channel)->str, got_bytes);
1844   g_string_erase (USE_BUF (channel), 0, got_bytes);
1845
1846   if (bytes_read)
1847     *bytes_read = got_bytes;
1848
1849   return G_IO_STATUS_NORMAL;
1850 }
1851
1852 /**
1853  * g_io_channel_read_unichar:
1854  * @channel: a #GIOChannel
1855  * @thechar: a location to return a character
1856  * @error: A location to return an error of type #GConvertError
1857  *         or #GIOChannelError
1858  *
1859  * This function cannot be called on a channel with %NULL encoding.
1860  *
1861  * Return value: a #GIOStatus
1862  **/
1863 GIOStatus
1864 g_io_channel_read_unichar     (GIOChannel   *channel,
1865                                gunichar     *thechar,
1866                                GError      **error)
1867 {
1868   GIOStatus status = G_IO_STATUS_NORMAL;
1869
1870   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1871   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
1872   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1873                         G_IO_STATUS_ERROR);
1874   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1875
1876   while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
1877     status = g_io_channel_fill_buffer (channel, error);
1878
1879   /* Only return an error if we have no data */
1880
1881   if (BUF_LEN (USE_BUF (channel)) == 0)
1882     {
1883       g_assert (status != G_IO_STATUS_NORMAL);
1884
1885       if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
1886         {
1887           g_set_error (error, G_CONVERT_ERROR,
1888                        G_CONVERT_ERROR_PARTIAL_INPUT,
1889                        _("Leftover unconverted data in read buffer"));
1890           status = G_IO_STATUS_ERROR;
1891         }
1892
1893       if (thechar)
1894         *thechar = (gunichar) -1;
1895
1896       return status;
1897     }
1898
1899   if (status == G_IO_STATUS_ERROR)
1900     g_clear_error (error);
1901
1902   if (thechar)
1903     *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
1904
1905   g_string_erase (channel->encoded_read_buf, 0,
1906                   g_utf8_next_char (channel->encoded_read_buf->str)
1907                   - channel->encoded_read_buf->str);
1908
1909   return G_IO_STATUS_NORMAL;
1910 }
1911
1912 /**
1913  * g_io_channel_write_chars:
1914  * @channel: a #GIOChannel
1915  * @buf: a buffer to write data from
1916  * @count: the size of the buffer. If -1, the buffer
1917  *         is taken to be a nul-terminated string.
1918  * @bytes_written: The number of bytes written. This can be nonzero
1919  *                 even if the return value is not %G_IO_STATUS_NORMAL.
1920  *                 If the return value is %G_IO_STATUS_NORMAL and the
1921  *                 channel is blocking, this will always be equal
1922  *                 to @count if @count >= 0.
1923  * @error: A location to return an error of type #GConvertError
1924  *         or #GIOChannelError
1925  *
1926  * Replacement for g_io_channel_write() with the new API.
1927  *
1928  * On seekable channels with encodings other than %NULL or UTF-8, generic
1929  * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
1930  * may only be made on a channel from which data has been read in the
1931  * cases described in the documentation for g_io_channel_set_encoding ().
1932  *
1933  * Return value: the status of the operation.
1934  **/
1935 GIOStatus
1936 g_io_channel_write_chars (GIOChannel    *channel,
1937                           const gchar   *buf,
1938                           gssize         count,
1939                           gsize         *bytes_written,
1940                           GError       **error)
1941 {
1942   GIOStatus status;
1943   gssize wrote_bytes = 0;
1944
1945   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1946   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1947                         G_IO_STATUS_ERROR);
1948   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1949
1950   if ((count < 0) && buf)
1951     count = strlen (buf);
1952   
1953   if (count == 0)
1954     {
1955       if (bytes_written)
1956         *bytes_written = 0;
1957       return G_IO_STATUS_NORMAL;
1958     }
1959
1960   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1961   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1962
1963   /* Raw write case */
1964
1965   if (!channel->use_buffer)
1966     {
1967       gsize tmp_bytes;
1968       
1969       g_assert (!channel->write_buf || channel->write_buf->len == 0);
1970       g_assert (channel->partial_write_buf[0] == '\0');
1971       
1972       status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
1973
1974       if (bytes_written)
1975         *bytes_written = tmp_bytes;
1976
1977       return status;
1978     }
1979
1980   /* General case */
1981
1982   if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
1983     || (BUF_LEN (channel->encoded_read_buf) > 0)))
1984     {
1985       if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
1986         {
1987           g_warning("Mixed reading and writing not allowed on encoded files");
1988           return G_IO_STATUS_ERROR;
1989         }
1990       status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1991       if (status != G_IO_STATUS_NORMAL)
1992         {
1993           if (bytes_written)
1994             *bytes_written = 0;
1995           return status;
1996         }
1997     }
1998
1999   if (!channel->write_buf)
2000     channel->write_buf = g_string_sized_new (channel->buf_size);
2001
2002   while (wrote_bytes < count)
2003     {
2004       gsize space_in_buf;
2005
2006       /* If the buffer is full, try a write immediately. In
2007        * the nonblocking case, this prevents the user from
2008        * writing just a little bit to the buffer every time
2009        * and never receiving an EAGAIN.
2010        */
2011
2012       if (channel->write_buf->len >= channel->buf_size)
2013         {
2014           gsize did_write = 0, this_time;
2015
2016           do
2017             {
2018               status = channel->funcs->io_write (channel, channel->write_buf->str
2019                                                  + did_write, channel->write_buf->len
2020                                                  - did_write, &this_time, error);
2021               did_write += this_time;
2022             }
2023           while (status == G_IO_STATUS_NORMAL &&
2024                  did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2025
2026           g_string_erase (channel->write_buf, 0, did_write);
2027
2028           if (status != G_IO_STATUS_NORMAL)
2029             {
2030               if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2031                 status = G_IO_STATUS_NORMAL;
2032               if (bytes_written)
2033                 *bytes_written = wrote_bytes;
2034               return status;
2035             }
2036         }
2037
2038       space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2039                      - channel->write_buf->len; /* 1 for NULL */
2040
2041       /* This is only true because g_io_channel_set_buffer_size ()
2042        * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2043        */
2044       g_assert (space_in_buf >= MAX_CHAR_SIZE);
2045
2046       if (!channel->encoding)
2047         {
2048           gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2049
2050           g_string_append_len (channel->write_buf, buf, write_this);
2051           buf += write_this;
2052           wrote_bytes += write_this;
2053         }
2054       else
2055         {
2056           const gchar *from_buf;
2057           gsize from_buf_len, from_buf_old_len, left_len;
2058           size_t err;
2059           gint errnum;
2060
2061           if (channel->partial_write_buf[0] != '\0')
2062             {
2063               g_assert (wrote_bytes == 0);
2064
2065               from_buf = channel->partial_write_buf;
2066               from_buf_old_len = strlen (channel->partial_write_buf);
2067               g_assert (from_buf_old_len > 0);
2068               from_buf_len = MIN (6, from_buf_old_len + count);
2069
2070               memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2071                       from_buf_len - from_buf_old_len);
2072             }
2073           else
2074             {
2075               from_buf = buf;
2076               from_buf_len = count - wrote_bytes;
2077               from_buf_old_len = 0;
2078             }
2079
2080 reconvert:
2081
2082           if (!channel->do_encode) /* UTF-8 encoding */
2083             {
2084               const gchar *badchar;
2085               gsize try_len = MIN (from_buf_len, space_in_buf);
2086
2087               /* UTF-8, just validate, emulate g_iconv */
2088
2089               if (!g_utf8_validate (from_buf, try_len, &badchar))
2090                 {
2091                   gunichar try_char;
2092                   gsize incomplete_len = from_buf + try_len - badchar;
2093
2094                   left_len = from_buf + from_buf_len - badchar;
2095
2096                   try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2097
2098                   switch (try_char)
2099                     {
2100                       case -2:
2101                         g_assert (incomplete_len < 6);
2102                         if (try_len == from_buf_len)
2103                           {
2104                             errnum = EINVAL;
2105                             err = (size_t) -1;
2106                           }
2107                         else
2108                           {
2109                             errnum = 0;
2110                             err = (size_t) 0;
2111                           }
2112                         break;
2113                       case -1:
2114                         g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2115                         /* FIXME bail here? */
2116                         errnum = EILSEQ;
2117                         err = (size_t) -1;
2118                         break;
2119                       default:
2120                         g_assert_not_reached ();
2121                         err = (size_t) -1;
2122                         errnum = 0; /* Don't confunse the compiler */
2123                     }
2124                 }
2125               else
2126                 {
2127                   err = (size_t) 0;
2128                   errnum = 0;
2129                   left_len = from_buf_len - try_len;
2130                 }
2131
2132               g_string_append_len (channel->write_buf, from_buf,
2133                                    from_buf_len - left_len);
2134               from_buf += from_buf_len - left_len;
2135             }
2136           else
2137             {
2138                gchar *outbuf;
2139
2140                left_len = from_buf_len;
2141                g_string_set_size (channel->write_buf, channel->write_buf->len
2142                                   + space_in_buf);
2143                outbuf = channel->write_buf->str + channel->write_buf->len
2144                         - space_in_buf;
2145                err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2146                               &outbuf, &space_in_buf);
2147                errnum = errno;
2148                g_string_truncate (channel->write_buf, channel->write_buf->len
2149                                   - space_in_buf);
2150             }
2151
2152           if (err == (size_t) -1)
2153             {
2154               switch (errnum)
2155                 {
2156                   case EINVAL:
2157                     g_assert (left_len < 6);
2158
2159                     if (from_buf_old_len == 0)
2160                       {
2161                         /* Not from partial_write_buf */
2162
2163                         memcpy (channel->partial_write_buf, from_buf, left_len);
2164                         channel->partial_write_buf[left_len] = '\0';
2165                         if (bytes_written)
2166                           *bytes_written = count;
2167                         return G_IO_STATUS_NORMAL;
2168                       }
2169
2170                     /* Working in partial_write_buf */
2171
2172                     if (left_len == from_buf_len)
2173                       {
2174                         /* Didn't convert anything, must still have
2175                          * less than a full character
2176                          */
2177
2178                         g_assert (count == from_buf_len - from_buf_old_len);
2179
2180                         channel->partial_write_buf[from_buf_len] = '\0';
2181
2182                         if (bytes_written)
2183                           *bytes_written = count;
2184
2185                         return G_IO_STATUS_NORMAL;
2186                       }
2187
2188                     g_assert (from_buf_len - left_len >= from_buf_old_len);
2189
2190                     /* We converted all the old data. This is fine */
2191
2192                     break;
2193                   case E2BIG:
2194                     if (from_buf_len == left_len)
2195                       {
2196                         /* Nothing was written, add enough space for
2197                          * at least one character.
2198                          */
2199                         space_in_buf += MAX_CHAR_SIZE;
2200                         goto reconvert;
2201                       }
2202                     break;
2203                   case EILSEQ:
2204                     g_set_error (error, G_CONVERT_ERROR,
2205                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2206                       _("Invalid byte sequence in conversion input"));
2207                     if (from_buf_old_len > 0 && from_buf_len == left_len)
2208                       g_warning ("Illegal sequence due to partial character "
2209                                  "at the end of a previous write.\n");
2210                     else
2211                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2212                     if (bytes_written)
2213                       *bytes_written = wrote_bytes;
2214                     channel->partial_write_buf[0] = '\0';
2215                     return G_IO_STATUS_ERROR;
2216                   default:
2217                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2218                       _("Error during conversion: %s"), g_strerror (errnum));
2219                     if (from_buf_len >= left_len + from_buf_old_len)
2220                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2221                     if (bytes_written)
2222                       *bytes_written = wrote_bytes;
2223                     channel->partial_write_buf[0] = '\0';
2224                     return G_IO_STATUS_ERROR;
2225                 }
2226             }
2227
2228           g_assert (from_buf_len - left_len >= from_buf_old_len);
2229
2230           wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2231
2232           if (from_buf_old_len > 0)
2233             {
2234               /* We were working in partial_write_buf */
2235
2236               buf += from_buf_len - left_len - from_buf_old_len;
2237               channel->partial_write_buf[0] = '\0';
2238             }
2239           else
2240             buf = from_buf;
2241         }
2242     }
2243
2244   if (bytes_written)
2245     *bytes_written = count;
2246
2247   return G_IO_STATUS_NORMAL;
2248 }
2249
2250 /**
2251  * g_io_channel_write_unichar:
2252  * @channel: a #GIOChannel
2253  * @thechar: a character
2254  * @error: A location to return an error of type #GConvertError
2255  *         or #GIOChannelError
2256  *
2257  * This function cannot be called on a channel with %NULL encoding.
2258  *
2259  * Return value: a #GIOStatus
2260  **/
2261 GIOStatus
2262 g_io_channel_write_unichar    (GIOChannel   *channel,
2263                                gunichar      thechar,
2264                                GError      **error)
2265 {
2266   GIOStatus status;
2267   gchar static_buf[6];
2268   gsize char_len, wrote_len;
2269
2270   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2271   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2272   g_return_val_if_fail ((error == NULL) || (*error == NULL),
2273                         G_IO_STATUS_ERROR);
2274   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2275
2276   char_len = g_unichar_to_utf8 (thechar, static_buf);
2277
2278   if (channel->partial_write_buf[0] != '\0')
2279     {
2280       g_warning ("Partial charater written before writing unichar.\n");
2281       channel->partial_write_buf[0] = '\0';
2282     }
2283
2284   status = g_io_channel_write_chars (channel, static_buf,
2285                                      char_len, &wrote_len, error);
2286
2287   /* We validate UTF-8, so we can't get a partial write */
2288
2289   g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2290
2291   return status;
2292 }
2293
2294 /**
2295  * g_io_channel_error_quark:
2296  *
2297  * Return value: The quark used as %G_IO_CHANNEL_ERROR
2298  **/
2299 GQuark
2300 g_io_channel_error_quark (void)
2301 {
2302   static GQuark q = 0;
2303   if (q == 0)
2304     q = g_quark_from_static_string ("g-io-channel-error-quark");
2305
2306   return q;
2307 }
2308
2309 #define __G_IOCHANNEL_C__
2310 #include "galiasdef.c"