Use g_set_error_literal where appropriate. Patch from bug #535947.
[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       g_free (channel->line_term);
126       if (channel->read_buf)
127         g_string_free (channel->read_buf, TRUE);
128       if (channel->write_buf)
129         g_string_free (channel->write_buf, TRUE);
130       if (channel->encoded_read_buf)
131         g_string_free (channel->encoded_read_buf, TRUE);
132       channel->funcs->io_free (channel);
133     }
134 }
135
136 static GIOError
137 g_io_error_get_from_g_error (GIOStatus  status,
138                              GError    *err)
139 {
140   switch (status)
141     {
142       case G_IO_STATUS_NORMAL:
143       case G_IO_STATUS_EOF:
144         return G_IO_ERROR_NONE;
145       case G_IO_STATUS_AGAIN:
146         return G_IO_ERROR_AGAIN;
147       case G_IO_STATUS_ERROR:
148         g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
149         
150         if (err->domain != G_IO_CHANNEL_ERROR)
151           return G_IO_ERROR_UNKNOWN;
152         switch (err->code)
153           {
154             case G_IO_CHANNEL_ERROR_INVAL:
155               return G_IO_ERROR_INVAL;
156             default:
157               return G_IO_ERROR_UNKNOWN;
158           }
159       default:
160         g_assert_not_reached ();
161         return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
162     }
163 }
164
165 /**
166  * g_io_channel_read:
167  * @channel: a #GIOChannel
168  * @buf: a buffer to read the data into (which should be at least 
169  *       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:2.2: 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:2.2: 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 
251  *          by @type
252  * @type: the position in the file, which can be %G_SEEK_CUR (the current
253  *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END 
254  *        (the end of the file)
255  * 
256  * Sets the current position in the #GIOChannel, similar to the standard 
257  * library function fseek(). 
258  * 
259  * Return value: %G_IO_ERROR_NONE if the operation was successful.
260  *
261  * Deprecated:2.2: Use g_io_channel_seek_position() instead.
262  **/
263 GIOError 
264 g_io_channel_seek (GIOChannel *channel,
265                    gint64      offset, 
266                    GSeekType   type)
267 {
268   GError *err = NULL;
269   GIOError error;
270   GIOStatus status;
271
272   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
273   g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
274
275   switch (type)
276     {
277       case G_SEEK_CUR:
278       case G_SEEK_SET:
279       case G_SEEK_END:
280         break;
281       default:
282         g_warning ("g_io_channel_seek: unknown seek type");
283         return G_IO_ERROR_UNKNOWN;
284     }
285
286   status = channel->funcs->io_seek (channel, offset, type, &err);
287
288   error = g_io_error_get_from_g_error (status, err);
289
290   if (err)
291     g_error_free (err);
292
293   return error;
294 }
295
296 /* The function g_io_channel_new_file() is prototyped in both
297  * giounix.c and giowin32.c, so we stick its documentation here.
298  */
299
300 /**
301  * g_io_channel_new_file:
302  * @filename: A string containing the name of a file
303  * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
304  *        the same meaning as in fopen()
305  * @error: A location to return an error of type %G_FILE_ERROR
306  *
307  * Open a file @filename as a #GIOChannel using mode @mode. This
308  * channel will be closed when the last reference to it is dropped,
309  * so there is no need to call g_io_channel_close() (though doing
310  * so will not cause problems, as long as no attempt is made to
311  * access the channel after it is closed).
312  *
313  * Return value: A #GIOChannel on success, %NULL on failure.
314  **/
315
316 /**
317  * g_io_channel_close:
318  * @channel: A #GIOChannel
319  * 
320  * Close an IO channel. Any pending data to be written will be
321  * flushed, ignoring errors. The channel will not be freed until the
322  * last reference is dropped using g_io_channel_unref(). 
323  *
324  * Deprecated:2.2: Use g_io_channel_shutdown() instead.
325  **/
326 void
327 g_io_channel_close (GIOChannel *channel)
328 {
329   GError *err = NULL;
330   
331   g_return_if_fail (channel != NULL);
332
333   g_io_channel_purge (channel);
334
335   channel->funcs->io_close (channel, &err);
336
337   if (err)
338     { /* No way to return the error */
339       g_warning ("Error closing channel: %s", err->message);
340       g_error_free (err);
341     }
342   
343   channel->close_on_unref = FALSE; /* Because we already did */
344   channel->is_readable = FALSE;
345   channel->is_writeable = FALSE;
346   channel->is_seekable = FALSE;
347 }
348
349 /**
350  * g_io_channel_shutdown:
351  * @channel: a #GIOChannel
352  * @flush: if %TRUE, flush pending
353  * @err: location to store a #GIOChannelError
354  * 
355  * Close an IO channel. Any pending data to be written will be
356  * flushed if @flush is %TRUE. The channel will not be freed until the
357  * last reference is dropped using g_io_channel_unref().
358  *
359  * Return value: the status of the operation.
360  **/
361 GIOStatus
362 g_io_channel_shutdown (GIOChannel  *channel,
363                        gboolean     flush,
364                        GError     **err)
365 {
366   GIOStatus status, result;
367   GError *tmperr = NULL;
368   
369   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
370   g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
371
372   if (channel->write_buf && channel->write_buf->len > 0)
373     {
374       if (flush)
375         {
376           GIOFlags flags;
377       
378           /* Set the channel to blocking, to avoid a busy loop
379            */
380           flags = g_io_channel_get_flags (channel);
381           /* Ignore any errors here, they're irrelevant */
382           g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
383
384           result = g_io_channel_flush (channel, &tmperr);
385         }
386       else
387         result = G_IO_STATUS_NORMAL;
388
389       g_string_truncate(channel->write_buf, 0);
390     }
391   else
392     result = G_IO_STATUS_NORMAL;
393
394   if (channel->partial_write_buf[0] != '\0')
395     {
396       if (flush)
397         g_warning ("Partial character at end of write buffer not flushed.\n");
398       channel->partial_write_buf[0] = '\0';
399     }
400
401   status = channel->funcs->io_close (channel, err);
402
403   channel->close_on_unref = FALSE; /* Because we already did */
404   channel->is_readable = FALSE;
405   channel->is_writeable = FALSE;
406   channel->is_seekable = FALSE;
407
408   if (status != G_IO_STATUS_NORMAL)
409     {
410       g_clear_error (&tmperr);
411       return status;
412     }
413   else if (result != G_IO_STATUS_NORMAL)
414     {
415       g_propagate_error (err, tmperr);
416       return result;
417     }
418   else
419     return G_IO_STATUS_NORMAL;
420 }
421
422 /* This function is used for the final flush on close or unref */
423 static void
424 g_io_channel_purge (GIOChannel *channel)
425 {
426   GError *err = NULL;
427   GIOStatus status;
428
429   g_return_if_fail (channel != NULL);
430
431   if (channel->write_buf && channel->write_buf->len > 0)
432     {
433       GIOFlags flags;
434       
435       /* Set the channel to blocking, to avoid a busy loop
436        */
437       flags = g_io_channel_get_flags (channel);
438       g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
439
440       status = g_io_channel_flush (channel, &err);
441
442       if (err)
443         { /* No way to return the error */
444           g_warning ("Error flushing string: %s", err->message);
445           g_error_free (err);
446         }
447     }
448
449   /* Flush these in case anyone tries to close without unrefing */
450
451   if (channel->read_buf)
452     g_string_truncate (channel->read_buf, 0);
453   if (channel->write_buf)
454     g_string_truncate (channel->write_buf, 0);
455   if (channel->encoding)
456     {
457       if (channel->encoded_read_buf)
458         g_string_truncate (channel->encoded_read_buf, 0);
459
460       if (channel->partial_write_buf[0] != '\0')
461         {
462           g_warning ("Partial character at end of write buffer not flushed.\n");
463           channel->partial_write_buf[0] = '\0';
464         }
465     }
466 }
467
468 GSource *
469 g_io_create_watch (GIOChannel   *channel,
470                    GIOCondition  condition)
471 {
472   g_return_val_if_fail (channel != NULL, NULL);
473
474   return channel->funcs->io_create_watch (channel, condition);
475 }
476
477 guint 
478 g_io_add_watch_full (GIOChannel    *channel,
479                      gint           priority,
480                      GIOCondition   condition,
481                      GIOFunc        func,
482                      gpointer       user_data,
483                      GDestroyNotify notify)
484 {
485   GSource *source;
486   guint id;
487   
488   g_return_val_if_fail (channel != NULL, 0);
489
490   source = g_io_create_watch (channel, condition);
491
492   if (priority != G_PRIORITY_DEFAULT)
493     g_source_set_priority (source, priority);
494   g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
495
496   id = g_source_attach (source, NULL);
497   g_source_unref (source);
498
499   return id;
500 }
501
502 guint 
503 g_io_add_watch (GIOChannel   *channel,
504                 GIOCondition  condition,
505                 GIOFunc       func,
506                 gpointer      user_data)
507 {
508   return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
509 }
510
511 /**
512  * g_io_channel_get_buffer_condition:
513  * @channel: A #GIOChannel
514  *
515  * This function returns a #GIOCondition depending on whether there
516  * is data to be read/space to write data in the internal buffers in 
517  * the #GIOChannel. Only the flags %G_IO_IN and %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. 
550  *      %G_IO_CHANNEL_ERROR_INVAL.
551  **/
552 GIOChannelError
553 g_io_channel_error_from_errno (gint en)
554 {
555 #ifdef EAGAIN
556   g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
557 #endif
558
559   switch (en)
560     {
561 #ifdef EBADF
562     case EBADF:
563       g_warning("Invalid file descriptor.\n");
564       return G_IO_CHANNEL_ERROR_FAILED;
565 #endif
566
567 #ifdef EFAULT
568     case EFAULT:
569       g_warning("Buffer outside valid address space.\n");
570       return G_IO_CHANNEL_ERROR_FAILED;
571 #endif
572
573 #ifdef EFBIG
574     case EFBIG:
575       return G_IO_CHANNEL_ERROR_FBIG;
576 #endif
577
578 #ifdef EINTR
579     /* In general, we should catch EINTR before we get here,
580      * but close() is allowed to return EINTR by POSIX, so
581      * we need to catch it here; EINTR from close() is
582      * unrecoverable, because it's undefined whether
583      * the fd was actually closed or not, so we just return
584      * a generic error code.
585      */
586     case EINTR:
587       return G_IO_CHANNEL_ERROR_FAILED;
588 #endif
589
590 #ifdef EINVAL
591     case EINVAL:
592       return G_IO_CHANNEL_ERROR_INVAL;
593 #endif
594
595 #ifdef EIO
596     case EIO:
597       return G_IO_CHANNEL_ERROR_IO;
598 #endif
599
600 #ifdef EISDIR
601     case EISDIR:
602       return G_IO_CHANNEL_ERROR_ISDIR;
603 #endif
604
605 #ifdef ENOSPC
606     case ENOSPC:
607       return G_IO_CHANNEL_ERROR_NOSPC;
608 #endif
609
610 #ifdef ENXIO
611     case ENXIO:
612       return G_IO_CHANNEL_ERROR_NXIO;
613 #endif
614
615 #ifdef EOVERFLOW
616     case EOVERFLOW:
617       return G_IO_CHANNEL_ERROR_OVERFLOW;
618 #endif
619
620 #ifdef EPIPE
621     case EPIPE:
622       return G_IO_CHANNEL_ERROR_PIPE;
623 #endif
624
625     default:
626       return G_IO_CHANNEL_ERROR_FAILED;
627     }
628 }
629
630 /**
631  * g_io_channel_set_buffer_size:
632  * @channel: a #GIOChannel
633  * @size: the size of the buffer, or 0 to let GLib pick a good size
634  *
635  * Sets the buffer size.
636  **/  
637 void
638 g_io_channel_set_buffer_size (GIOChannel *channel,
639                               gsize       size)
640 {
641   g_return_if_fail (channel != NULL);
642
643   if (size == 0)
644     size = G_IO_NICE_BUF_SIZE;
645
646   if (size < MAX_CHAR_SIZE)
647     size = MAX_CHAR_SIZE;
648
649   channel->buf_size = size;
650 }
651
652 /**
653  * g_io_channel_get_buffer_size:
654  * @channel: a #GIOChannel
655  *
656  * Gets the buffer size.
657  *
658  * Return value: the size of the buffer.
659  **/  
660 gsize
661 g_io_channel_get_buffer_size (GIOChannel *channel)
662 {
663   g_return_val_if_fail (channel != NULL, 0);
664
665   return channel->buf_size;
666 }
667
668 /**
669  * g_io_channel_set_line_term:
670  * @channel: a #GIOChannel
671  * @line_term: The line termination string. Use %NULL for autodetect.
672  *             Autodetection breaks on "\n", "\r\n", "\r", "\0", and
673  *             the Unicode paragraph separator. Autodetection should
674  *             not be used for anything other than file-based channels.
675  * @length: The length of the termination string. If -1 is passed, the
676  *          string is assumed to be nul-terminated. This option allows
677  *          termination strings with embedded nuls.
678  *
679  * This sets the string that #GIOChannel uses to determine
680  * where in the file a line break occurs.
681  **/
682 void
683 g_io_channel_set_line_term (GIOChannel  *channel,
684                             const gchar *line_term,
685                             gint         length)
686 {
687   g_return_if_fail (channel != NULL);
688   g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
689
690   if (line_term == NULL)
691     length = 0;
692   else if (length < 0)
693     length = strlen (line_term);
694
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 autodetection.
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. 
1036  * The internal encoding is always UTF-8. The default encoding 
1037  * for the 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  * <itemizedlist>
1044  * <listitem><para>
1045  *    The channel was just created, and has not been written to or read 
1046  *    from yet.
1047  * </para></listitem>
1048  * <listitem><para>
1049  *    The channel is write-only.
1050  * </para></listitem>
1051  * <listitem><para>
1052  *    The channel is a file, and the file pointer was just
1053  *    repositioned by a call to g_io_channel_seek_position().
1054  *    (This flushes all the internal buffers.)
1055  * </para></listitem>
1056  * <listitem><para>
1057  *    The current encoding is %NULL or UTF-8.
1058  * </para></listitem>
1059  * <listitem><para>
1060  *    One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1061  *    (or, in the case of g_io_channel_read_to_end(), %G_IO_STATUS_NORMAL).
1062  * </para></listitem>
1063  * <listitem><para>
1064  *    One of the functions g_io_channel_read_chars() or 
1065  *    g_io_channel_read_unichar() has returned %G_IO_STATUS_AGAIN or 
1066  *    %G_IO_STATUS_ERROR. This may be useful in the case of 
1067  *    %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1068  *    Returning one of these statuses from g_io_channel_read_line(),
1069  *    g_io_channel_read_line_string(), or g_io_channel_read_to_end()
1070  *    does <emphasis>not</emphasis> guarantee that the encoding can 
1071  *    be changed.
1072  * </para></listitem>
1073  * </itemizedlist>
1074  * Channels which do not meet one of the above conditions cannot call
1075  * g_io_channel_seek_position() with an offset of %G_SEEK_CUR, and, if 
1076  * they are "seekable", cannot call g_io_channel_write_chars() after 
1077  * calling one of the API "read" functions.
1078  *
1079  * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1080  **/
1081 GIOStatus
1082 g_io_channel_set_encoding (GIOChannel   *channel,
1083                            const gchar  *encoding,
1084                            GError      **error)
1085 {
1086   GIConv read_cd, write_cd;
1087   gboolean did_encode;
1088
1089   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1090   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1091
1092   /* Make sure the encoded buffers are empty */
1093
1094   g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1095                         channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1096
1097   if (!channel->use_buffer)
1098     {
1099       g_warning ("Need to set the channel buffered before setting the encoding.\n");
1100       g_warning ("Assuming this is what you meant and acting accordingly.\n");
1101
1102       channel->use_buffer = TRUE;
1103     }
1104
1105   if (channel->partial_write_buf[0] != '\0')
1106     {
1107       g_warning ("Partial character at end of write buffer not flushed.\n");
1108       channel->partial_write_buf[0] = '\0';
1109     }
1110
1111   did_encode = channel->do_encode;
1112
1113   if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1114     {
1115       channel->do_encode = FALSE;
1116       read_cd = write_cd = (GIConv) -1;
1117     }
1118   else
1119     {
1120       gint err = 0;
1121       const gchar *from_enc = NULL, *to_enc = NULL;
1122
1123       if (channel->is_readable)
1124         {
1125           read_cd = g_iconv_open ("UTF-8", encoding);
1126
1127           if (read_cd == (GIConv) -1)
1128             {
1129               err = errno;
1130               from_enc = encoding;
1131               to_enc = "UTF-8";
1132             }
1133         }
1134       else
1135         read_cd = (GIConv) -1;
1136
1137       if (channel->is_writeable && err == 0)
1138         {
1139           write_cd = g_iconv_open (encoding, "UTF-8");
1140
1141           if (write_cd == (GIConv) -1)
1142             {
1143               err = errno;
1144               from_enc = "UTF-8";
1145               to_enc = encoding;
1146             }
1147         }
1148       else
1149         write_cd = (GIConv) -1;
1150
1151       if (err != 0)
1152         {
1153           g_assert (from_enc);
1154           g_assert (to_enc);
1155
1156           if (err == EINVAL)
1157             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1158                          _("Conversion from character set '%s' to '%s' is not supported"),
1159                          from_enc, to_enc);
1160           else
1161             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1162                          _("Could not open converter from '%s' to '%s': %s"),
1163                          from_enc, to_enc, g_strerror (err));
1164
1165           if (read_cd != (GIConv) -1)
1166             g_iconv_close (read_cd);
1167           if (write_cd != (GIConv) -1)
1168             g_iconv_close (write_cd);
1169
1170           return G_IO_STATUS_ERROR;
1171         }
1172
1173       channel->do_encode = TRUE;
1174     }
1175
1176   /* The encoding is ok, so set the fields in channel */
1177
1178   if (channel->read_cd != (GIConv) -1)
1179     g_iconv_close (channel->read_cd);
1180   if (channel->write_cd != (GIConv) -1)
1181     g_iconv_close (channel->write_cd);
1182
1183   if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1184     {
1185       g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1186
1187       /* This is just validated UTF-8, so we can copy it back into read_buf
1188        * so it can be encoded in whatever the new encoding is.
1189        */
1190
1191       g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1192                             channel->encoded_read_buf->len);
1193       g_string_truncate (channel->encoded_read_buf, 0);
1194     }
1195
1196   channel->read_cd = read_cd;
1197   channel->write_cd = write_cd;
1198
1199   g_free (channel->encoding);
1200   channel->encoding = g_strdup (encoding);
1201
1202   return G_IO_STATUS_NORMAL;
1203 }
1204
1205 /**
1206  * g_io_channel_get_encoding:
1207  * @channel: a #GIOChannel
1208  *
1209  * Gets the encoding for the input/output of the channel. 
1210  * The internal encoding is always UTF-8. The encoding %NULL 
1211  * makes the channel safe for binary data.
1212  *
1213  * Return value: A string containing the encoding, this string is
1214  *   owned by GLib and must not be freed.
1215  **/
1216 G_CONST_RETURN gchar*
1217 g_io_channel_get_encoding (GIOChannel *channel)
1218 {
1219   g_return_val_if_fail (channel != NULL, NULL);
1220
1221   return channel->encoding;
1222 }
1223
1224 static GIOStatus
1225 g_io_channel_fill_buffer (GIOChannel  *channel,
1226                           GError     **err)
1227 {
1228   gsize read_size, cur_len, oldlen;
1229   GIOStatus status;
1230
1231   if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1232     {
1233       status = g_io_channel_flush (channel, err);
1234       if (status != G_IO_STATUS_NORMAL)
1235         return status;
1236     }
1237   if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1238     {
1239       g_warning ("Partial character at end of write buffer not flushed.\n");
1240       channel->partial_write_buf[0] = '\0';
1241     }
1242
1243   if (!channel->read_buf)
1244     channel->read_buf = g_string_sized_new (channel->buf_size);
1245
1246   cur_len = channel->read_buf->len;
1247
1248   g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1249
1250   status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1251                                     channel->buf_size, &read_size, err);
1252
1253   g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1254
1255   g_string_truncate (channel->read_buf, read_size + cur_len);
1256
1257   if ((status != G_IO_STATUS_NORMAL) &&
1258       ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1259     return status;
1260
1261   g_assert (channel->read_buf->len > 0);
1262
1263   if (channel->encoded_read_buf)
1264     oldlen = channel->encoded_read_buf->len;
1265   else
1266     {
1267       oldlen = 0;
1268       if (channel->encoding)
1269         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1270     }
1271
1272   if (channel->do_encode)
1273     {
1274       gsize errnum, inbytes_left, outbytes_left;
1275       gchar *inbuf, *outbuf;
1276       int errval;
1277
1278       g_assert (channel->encoded_read_buf);
1279
1280 reencode:
1281
1282       inbytes_left = channel->read_buf->len;
1283       outbytes_left = MAX (channel->read_buf->len,
1284                            channel->encoded_read_buf->allocated_len
1285                            - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1286       outbytes_left = MAX (outbytes_left, 6);
1287
1288       inbuf = channel->read_buf->str;
1289       g_string_set_size (channel->encoded_read_buf,
1290                          channel->encoded_read_buf->len + outbytes_left);
1291       outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1292                - outbytes_left;
1293
1294       errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1295                         &outbuf, &outbytes_left);
1296       errval = errno;
1297
1298       g_assert (inbuf + inbytes_left == channel->read_buf->str
1299                 + channel->read_buf->len);
1300       g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1301                 + channel->encoded_read_buf->len);
1302
1303       g_string_erase (channel->read_buf, 0,
1304                       channel->read_buf->len - inbytes_left);
1305       g_string_truncate (channel->encoded_read_buf,
1306                          channel->encoded_read_buf->len - outbytes_left);
1307
1308       if (errnum == (gsize) -1)
1309         {
1310           switch (errval)
1311             {
1312               case EINVAL:
1313                 if ((oldlen == channel->encoded_read_buf->len)
1314                   && (status == G_IO_STATUS_EOF))
1315                   status = G_IO_STATUS_EOF;
1316                 else
1317                   status = G_IO_STATUS_NORMAL;
1318                 break;
1319               case E2BIG:
1320                 /* Buffer size at least 6, wrote at least on character */
1321                 g_assert (inbuf != channel->read_buf->str);
1322                 goto reencode;
1323               case EILSEQ:
1324                 if (oldlen < channel->encoded_read_buf->len)
1325                   status = G_IO_STATUS_NORMAL;
1326                 else
1327                   {
1328                     g_set_error_literal (err, G_CONVERT_ERROR,
1329                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1330                       _("Invalid byte sequence in conversion input"));
1331                     return G_IO_STATUS_ERROR;
1332                   }
1333                 break;
1334               default:
1335                 g_assert (errval != EBADF); /* The converter should be open */
1336                 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1337                   _("Error during conversion: %s"), g_strerror (errval));
1338                 return G_IO_STATUS_ERROR;
1339             }
1340         }
1341       g_assert ((status != G_IO_STATUS_NORMAL)
1342                || (channel->encoded_read_buf->len > 0));
1343     }
1344   else if (channel->encoding) /* UTF-8 */
1345     {
1346       gchar *nextchar, *lastchar;
1347
1348       g_assert (channel->encoded_read_buf);
1349
1350       nextchar = channel->read_buf->str;
1351       lastchar = channel->read_buf->str + channel->read_buf->len;
1352
1353       while (nextchar < lastchar)
1354         {
1355           gunichar val_char;
1356
1357           val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1358
1359           switch (val_char)
1360             {
1361               case -2:
1362                 /* stop, leave partial character in buffer */
1363                 lastchar = nextchar;
1364                 break;
1365               case -1:
1366                 if (oldlen < channel->encoded_read_buf->len)
1367                   status = G_IO_STATUS_NORMAL;
1368                 else
1369                   {
1370                     g_set_error_literal (err, G_CONVERT_ERROR,
1371                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1372                       _("Invalid byte sequence in conversion input"));
1373                     status = G_IO_STATUS_ERROR;
1374                   }
1375                 lastchar = nextchar;
1376                 break;
1377               default:
1378                 nextchar = g_utf8_next_char (nextchar);
1379                 break;
1380             }
1381         }
1382
1383       if (lastchar > channel->read_buf->str)
1384         {
1385           gint copy_len = lastchar - channel->read_buf->str;
1386
1387           g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1388                                copy_len);
1389           g_string_erase (channel->read_buf, 0, copy_len);
1390         }
1391     }
1392
1393   return status;
1394 }
1395
1396 /**
1397  * g_io_channel_read_line:
1398  * @channel: a #GIOChannel
1399  * @str_return: The line read from the #GIOChannel, including the
1400  *              line terminator. This data should be freed with g_free()
1401  *              when no longer needed. This is a nul-terminated string. 
1402  *              If a @length of zero is returned, this will be %NULL instead.
1403  * @length: location to store length of the read data, or %NULL
1404  * @terminator_pos: location to store position of line terminator, or %NULL
1405  * @error: A location to return an error of type #GConvertError
1406  *         or #GIOChannelError
1407  *
1408  * Reads a line, including the terminating character(s),
1409  * from a #GIOChannel into a newly-allocated string.
1410  * @str_return will contain allocated memory if the return
1411  * is %G_IO_STATUS_NORMAL.
1412  *
1413  * Return value: the status of the operation.
1414  **/
1415 GIOStatus
1416 g_io_channel_read_line (GIOChannel  *channel,
1417                         gchar      **str_return,
1418                         gsize       *length,
1419                         gsize       *terminator_pos,
1420                         GError     **error)
1421 {
1422   GIOStatus status;
1423   gsize got_length;
1424   
1425   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1426   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1427   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1428                         G_IO_STATUS_ERROR);
1429   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1430
1431   status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1432
1433   if (length)
1434     *length = got_length;
1435
1436   if (status == G_IO_STATUS_NORMAL)
1437     {
1438       g_assert (USE_BUF (channel));
1439       *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1440       g_string_erase (USE_BUF (channel), 0, got_length);
1441     }
1442   else
1443     *str_return = NULL;
1444   
1445   return status;
1446 }
1447
1448 /**
1449  * g_io_channel_read_line_string:
1450  * @channel: a #GIOChannel
1451  * @buffer: a #GString into which the line will be written.
1452  *          If @buffer already contains data, the old data will
1453  *          be overwritten.
1454  * @terminator_pos: location to store position of line terminator, or %NULL
1455  * @error: a location to store an error of type #GConvertError
1456  *         or #GIOChannelError
1457  *
1458  * Reads a line from a #GIOChannel, using a #GString as a buffer.
1459  *
1460  * Return value: the status of the operation.
1461  **/
1462 GIOStatus
1463 g_io_channel_read_line_string (GIOChannel  *channel,
1464                                GString     *buffer,
1465                                gsize       *terminator_pos,
1466                                GError     **error)
1467 {
1468   gsize length;
1469   GIOStatus status;
1470
1471   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1472   g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1473   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1474                         G_IO_STATUS_ERROR);
1475   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1476
1477   if (buffer->len > 0)
1478     g_string_truncate (buffer, 0); /* clear out the buffer */
1479
1480   status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1481
1482   if (status == G_IO_STATUS_NORMAL)
1483     {
1484       g_assert (USE_BUF (channel));
1485       g_string_append_len (buffer, USE_BUF (channel)->str, length);
1486       g_string_erase (USE_BUF (channel), 0, length);
1487     }
1488
1489   return status;
1490 }
1491
1492
1493 static GIOStatus
1494 g_io_channel_read_line_backend (GIOChannel  *channel,
1495                                 gsize       *length,
1496                                 gsize       *terminator_pos,
1497                                 GError     **error)
1498 {
1499   GIOStatus status;
1500   gsize checked_to, line_term_len, line_length, got_term_len;
1501   gboolean first_time = TRUE;
1502
1503   if (!channel->use_buffer)
1504     {
1505       /* Can't do a raw read in read_line */
1506       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1507                            _("Can't do a raw read in g_io_channel_read_line_string"));
1508       return G_IO_STATUS_ERROR;
1509     }
1510
1511   status = G_IO_STATUS_NORMAL;
1512
1513   if (channel->line_term)
1514     line_term_len = channel->line_term_len;
1515   else
1516     line_term_len = 3;
1517     /* This value used for setting checked_to, it's the longest of the four
1518      * we autodetect for.
1519      */
1520
1521   checked_to = 0;
1522
1523   while (TRUE)
1524     {
1525       gchar *nextchar, *lastchar;
1526       GString *use_buf;
1527
1528       if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1529         {
1530 read_again:
1531           status = g_io_channel_fill_buffer (channel, error);
1532           switch (status)
1533             {
1534               case G_IO_STATUS_NORMAL:
1535                 if (BUF_LEN (USE_BUF (channel)) == 0)
1536                   /* Can happen when using conversion and only read
1537                    * part of a character
1538                    */
1539                   {
1540                     first_time = FALSE;
1541                     continue;
1542                   }
1543                 break;
1544               case G_IO_STATUS_EOF:
1545                 if (BUF_LEN (USE_BUF (channel)) == 0)
1546                   {
1547                     if (length)
1548                       *length = 0;
1549
1550                     if (channel->encoding && channel->read_buf->len != 0)
1551                       {
1552                         g_set_error_literal (error, G_CONVERT_ERROR,
1553                                              G_CONVERT_ERROR_PARTIAL_INPUT,
1554                                              _("Leftover unconverted data in "
1555                                                "read buffer"));
1556                         return G_IO_STATUS_ERROR;
1557                       }
1558                     else
1559                       return G_IO_STATUS_EOF;
1560                   }
1561                 break;
1562               default:
1563                 if (length)
1564                   *length = 0;
1565                 return status;
1566             }
1567         }
1568
1569       g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1570
1571       use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1572
1573       first_time = FALSE;
1574
1575       lastchar = use_buf->str + use_buf->len;
1576
1577       for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1578            channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1579         {
1580           if (channel->line_term)
1581             {
1582               if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1583                 {
1584                   line_length = nextchar - use_buf->str;
1585                   got_term_len = line_term_len;
1586                   goto done;
1587                 }
1588             }
1589           else /* auto detect */
1590             {
1591               switch (*nextchar)
1592                 {
1593                   case '\n': /* unix */
1594                     line_length = nextchar - use_buf->str;
1595                     got_term_len = 1;
1596                     goto done;
1597                   case '\r': /* Warning: do not use with sockets */
1598                     line_length = nextchar - use_buf->str;
1599                     if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1600                        && (lastchar == use_buf->str + use_buf->len))
1601                       goto read_again; /* Try to read more data */
1602                     if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1603                       got_term_len = 2;
1604                     else /* mac */
1605                       got_term_len = 1;
1606                     goto done;
1607                   case '\xe2': /* Unicode paragraph separator */
1608                     if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1609                       {
1610                         line_length = nextchar - use_buf->str;
1611                         got_term_len = 3;
1612                         goto done;
1613                       }
1614                     break;
1615                   case '\0': /* Embeded null in input */
1616                     line_length = nextchar - use_buf->str;
1617                     got_term_len = 1;
1618                     goto done;
1619                   default: /* no match */
1620                     break;
1621                 }
1622             }
1623         }
1624
1625       /* If encoding != NULL, valid UTF-8, didn't overshoot */
1626       g_assert (nextchar == lastchar);
1627
1628       /* Check for EOF */
1629
1630       if (status == G_IO_STATUS_EOF)
1631         {
1632           if (channel->encoding && channel->read_buf->len > 0)
1633             {
1634               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1635                                    _("Channel terminates in a partial character"));
1636               return G_IO_STATUS_ERROR;
1637             }
1638           line_length = use_buf->len;
1639           got_term_len = 0;
1640           break;
1641         }
1642
1643       if (use_buf->len > line_term_len - 1)
1644         checked_to = use_buf->len - (line_term_len - 1);
1645       else
1646         checked_to = 0;
1647     }
1648
1649 done:
1650
1651   if (terminator_pos)
1652     *terminator_pos = line_length;
1653
1654   if (length)
1655     *length = line_length + got_term_len;
1656
1657   return G_IO_STATUS_NORMAL;
1658 }
1659
1660 /**
1661  * g_io_channel_read_to_end:
1662  * @channel: a #GIOChannel
1663  * @str_return: Location to store a pointer to a string holding
1664  *              the remaining data in the #GIOChannel. This data should
1665  *              be freed with g_free() when no longer needed. This
1666  *              data is terminated by an extra nul character, but there 
1667  *              may be other nuls in the intervening data.
1668  * @length: location to store length of the data
1669  * @error: location to return an error of type #GConvertError
1670  *         or #GIOChannelError
1671  *
1672  * Reads all the remaining data from the file.
1673  *
1674  * Return value: %G_IO_STATUS_NORMAL on success. 
1675  *     This function never returns %G_IO_STATUS_EOF.
1676  **/
1677 GIOStatus
1678 g_io_channel_read_to_end (GIOChannel  *channel,
1679                           gchar      **str_return,
1680                           gsize       *length,
1681                           GError     **error)
1682 {
1683   GIOStatus status;
1684     
1685   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1686   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1687     G_IO_STATUS_ERROR);
1688   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1689
1690   if (str_return)
1691     *str_return = NULL;
1692   if (length)
1693     *length = 0;
1694
1695   if (!channel->use_buffer)
1696     {
1697       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1698                            _("Can't do a raw read in g_io_channel_read_to_end"));
1699       return G_IO_STATUS_ERROR;
1700     }
1701
1702   do
1703     status = g_io_channel_fill_buffer (channel, error);
1704   while (status == G_IO_STATUS_NORMAL);
1705
1706   if (status != G_IO_STATUS_EOF)
1707     return status;
1708
1709   if (channel->encoding && channel->read_buf->len > 0)
1710     {
1711       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1712                            _("Channel terminates in a partial character"));
1713       return G_IO_STATUS_ERROR;
1714     }
1715
1716   if (USE_BUF (channel) == NULL)
1717     {
1718       /* length is already set to zero */
1719       if (str_return)
1720         *str_return = g_strdup ("");
1721     }
1722   else
1723     {
1724       if (length)
1725         *length = USE_BUF (channel)->len;
1726
1727       if (str_return)
1728         *str_return = g_string_free (USE_BUF (channel), FALSE);
1729       else
1730         g_string_free (USE_BUF (channel), TRUE);
1731
1732       if (channel->encoding)
1733         channel->encoded_read_buf = NULL;
1734       else
1735         channel->read_buf = NULL;
1736     }
1737
1738   return G_IO_STATUS_NORMAL;
1739 }
1740
1741 /**
1742  * g_io_channel_read_chars:
1743  * @channel: a #GIOChannel
1744  * @buf: a buffer to read data into
1745  * @count: the size of the buffer. Note that the buffer may
1746  *         not be complelely filled even if there is data
1747  *         in the buffer if the remaining data is not a
1748  *         complete character.
1749  * @bytes_read: The number of bytes read. This may be zero even on
1750  *              success if count < 6 and the channel's encoding is non-%NULL.
1751  *              This indicates that the next UTF-8 character is too wide for
1752  *              the buffer.
1753  * @error: a location to return an error of type #GConvertError
1754  *         or #GIOChannelError.
1755  *
1756  * Replacement for g_io_channel_read() with the new API.
1757  *
1758  * Return value: the status of the operation.
1759  **/
1760 GIOStatus
1761 g_io_channel_read_chars (GIOChannel  *channel,
1762                          gchar       *buf,
1763                          gsize        count,
1764                          gsize       *bytes_read,
1765                          GError     **error)
1766 {
1767   GIOStatus status;
1768   gsize got_bytes;
1769
1770   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1771   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1772                         G_IO_STATUS_ERROR);
1773   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1774
1775   if (count == 0)
1776     {
1777       *bytes_read = 0;
1778       return G_IO_STATUS_NORMAL;
1779     }
1780   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1781
1782   if (!channel->use_buffer)
1783     {
1784       gsize tmp_bytes;
1785       
1786       g_assert (!channel->read_buf || channel->read_buf->len == 0);
1787
1788       status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
1789       
1790       if (bytes_read)
1791         *bytes_read = tmp_bytes;
1792
1793       return status;
1794     }
1795
1796   status = G_IO_STATUS_NORMAL;
1797
1798   while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
1799     status = g_io_channel_fill_buffer (channel, error);
1800
1801   /* Only return an error if we have no data */
1802
1803   if (BUF_LEN (USE_BUF (channel)) == 0)
1804     {
1805       g_assert (status != G_IO_STATUS_NORMAL);
1806
1807       if (status == G_IO_STATUS_EOF && channel->encoding
1808           && BUF_LEN (channel->read_buf) > 0)
1809         {
1810           g_set_error_literal (error, G_CONVERT_ERROR,
1811                                G_CONVERT_ERROR_PARTIAL_INPUT,
1812                                _("Leftover unconverted data in read buffer"));
1813           status = G_IO_STATUS_ERROR;
1814         }
1815
1816       if (bytes_read)
1817         *bytes_read = 0;
1818
1819       return status;
1820     }
1821
1822   if (status == G_IO_STATUS_ERROR)
1823     g_clear_error (error);
1824
1825   got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
1826
1827   g_assert (got_bytes > 0);
1828
1829   if (channel->encoding)
1830     /* Don't validate for NULL encoding, binary safe */
1831     {
1832       gchar *nextchar, *prevchar;
1833
1834       g_assert (USE_BUF (channel) == channel->encoded_read_buf);
1835
1836       nextchar = channel->encoded_read_buf->str;
1837
1838       do
1839         {
1840           prevchar = nextchar;
1841           nextchar = g_utf8_next_char (nextchar);
1842           g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
1843         }
1844       while (nextchar < channel->encoded_read_buf->str + got_bytes);
1845
1846       if (nextchar > channel->encoded_read_buf->str + got_bytes)
1847         got_bytes = prevchar - channel->encoded_read_buf->str;
1848
1849       g_assert (got_bytes > 0 || count < 6);
1850     }
1851
1852   memcpy (buf, USE_BUF (channel)->str, got_bytes);
1853   g_string_erase (USE_BUF (channel), 0, got_bytes);
1854
1855   if (bytes_read)
1856     *bytes_read = got_bytes;
1857
1858   return G_IO_STATUS_NORMAL;
1859 }
1860
1861 /**
1862  * g_io_channel_read_unichar:
1863  * @channel: a #GIOChannel
1864  * @thechar: a location to return a character
1865  * @error: a location to return an error of type #GConvertError
1866  *         or #GIOChannelError
1867  *
1868  * Reads a Unicode character from @channel.
1869  * This function cannot be called on a channel with %NULL encoding.
1870  *
1871  * Return value: a #GIOStatus
1872  **/
1873 GIOStatus
1874 g_io_channel_read_unichar (GIOChannel  *channel,
1875                            gunichar    *thechar,
1876                            GError     **error)
1877 {
1878   GIOStatus status = G_IO_STATUS_NORMAL;
1879
1880   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1881   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
1882   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1883                         G_IO_STATUS_ERROR);
1884   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1885
1886   while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
1887     status = g_io_channel_fill_buffer (channel, error);
1888
1889   /* Only return an error if we have no data */
1890
1891   if (BUF_LEN (USE_BUF (channel)) == 0)
1892     {
1893       g_assert (status != G_IO_STATUS_NORMAL);
1894
1895       if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
1896         {
1897           g_set_error_literal (error, G_CONVERT_ERROR,
1898                                G_CONVERT_ERROR_PARTIAL_INPUT,
1899                                _("Leftover unconverted data in read buffer"));
1900           status = G_IO_STATUS_ERROR;
1901         }
1902
1903       if (thechar)
1904         *thechar = (gunichar) -1;
1905
1906       return status;
1907     }
1908
1909   if (status == G_IO_STATUS_ERROR)
1910     g_clear_error (error);
1911
1912   if (thechar)
1913     *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
1914
1915   g_string_erase (channel->encoded_read_buf, 0,
1916                   g_utf8_next_char (channel->encoded_read_buf->str)
1917                   - channel->encoded_read_buf->str);
1918
1919   return G_IO_STATUS_NORMAL;
1920 }
1921
1922 /**
1923  * g_io_channel_write_chars:
1924  * @channel: a #GIOChannel
1925  * @buf: a buffer to write data from
1926  * @count: the size of the buffer. If -1, the buffer
1927  *         is taken to be a nul-terminated string.
1928  * @bytes_written: The number of bytes written. This can be nonzero
1929  *                 even if the return value is not %G_IO_STATUS_NORMAL.
1930  *                 If the return value is %G_IO_STATUS_NORMAL and the
1931  *                 channel is blocking, this will always be equal
1932  *                 to @count if @count >= 0.
1933  * @error: a location to return an error of type #GConvertError
1934  *         or #GIOChannelError
1935  *
1936  * Replacement for g_io_channel_write() with the new API.
1937  *
1938  * On seekable channels with encodings other than %NULL or UTF-8, generic
1939  * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
1940  * may only be made on a channel from which data has been read in the
1941  * cases described in the documentation for g_io_channel_set_encoding ().
1942  *
1943  * Return value: the status of the operation.
1944  **/
1945 GIOStatus
1946 g_io_channel_write_chars (GIOChannel   *channel,
1947                           const gchar  *buf,
1948                           gssize        count,
1949                           gsize        *bytes_written,
1950                           GError      **error)
1951 {
1952   GIOStatus status;
1953   gssize wrote_bytes = 0;
1954
1955   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1956   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1957                         G_IO_STATUS_ERROR);
1958   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1959
1960   if ((count < 0) && buf)
1961     count = strlen (buf);
1962   
1963   if (count == 0)
1964     {
1965       if (bytes_written)
1966         *bytes_written = 0;
1967       return G_IO_STATUS_NORMAL;
1968     }
1969
1970   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1971   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1972
1973   /* Raw write case */
1974
1975   if (!channel->use_buffer)
1976     {
1977       gsize tmp_bytes;
1978       
1979       g_assert (!channel->write_buf || channel->write_buf->len == 0);
1980       g_assert (channel->partial_write_buf[0] == '\0');
1981       
1982       status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
1983
1984       if (bytes_written)
1985         *bytes_written = tmp_bytes;
1986
1987       return status;
1988     }
1989
1990   /* General case */
1991
1992   if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
1993     || (BUF_LEN (channel->encoded_read_buf) > 0)))
1994     {
1995       if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
1996         {
1997           g_warning("Mixed reading and writing not allowed on encoded files");
1998           return G_IO_STATUS_ERROR;
1999         }
2000       status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
2001       if (status != G_IO_STATUS_NORMAL)
2002         {
2003           if (bytes_written)
2004             *bytes_written = 0;
2005           return status;
2006         }
2007     }
2008
2009   if (!channel->write_buf)
2010     channel->write_buf = g_string_sized_new (channel->buf_size);
2011
2012   while (wrote_bytes < count)
2013     {
2014       gsize space_in_buf;
2015
2016       /* If the buffer is full, try a write immediately. In
2017        * the nonblocking case, this prevents the user from
2018        * writing just a little bit to the buffer every time
2019        * and never receiving an EAGAIN.
2020        */
2021
2022       if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2023         {
2024           gsize did_write = 0, this_time;
2025
2026           do
2027             {
2028               status = channel->funcs->io_write (channel, channel->write_buf->str
2029                                                  + did_write, channel->write_buf->len
2030                                                  - did_write, &this_time, error);
2031               did_write += this_time;
2032             }
2033           while (status == G_IO_STATUS_NORMAL &&
2034                  did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2035
2036           g_string_erase (channel->write_buf, 0, did_write);
2037
2038           if (status != G_IO_STATUS_NORMAL)
2039             {
2040               if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2041                 status = G_IO_STATUS_NORMAL;
2042               if (bytes_written)
2043                 *bytes_written = wrote_bytes;
2044               return status;
2045             }
2046         }
2047
2048       space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2049                      - channel->write_buf->len; /* 1 for NULL */
2050
2051       /* This is only true because g_io_channel_set_buffer_size ()
2052        * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2053        */
2054       g_assert (space_in_buf >= MAX_CHAR_SIZE);
2055
2056       if (!channel->encoding)
2057         {
2058           gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2059
2060           g_string_append_len (channel->write_buf, buf, write_this);
2061           buf += write_this;
2062           wrote_bytes += write_this;
2063         }
2064       else
2065         {
2066           const gchar *from_buf;
2067           gsize from_buf_len, from_buf_old_len, left_len;
2068           gsize err;
2069           gint errnum;
2070
2071           if (channel->partial_write_buf[0] != '\0')
2072             {
2073               g_assert (wrote_bytes == 0);
2074
2075               from_buf = channel->partial_write_buf;
2076               from_buf_old_len = strlen (channel->partial_write_buf);
2077               g_assert (from_buf_old_len > 0);
2078               from_buf_len = MIN (6, from_buf_old_len + count);
2079
2080               memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2081                       from_buf_len - from_buf_old_len);
2082             }
2083           else
2084             {
2085               from_buf = buf;
2086               from_buf_len = count - wrote_bytes;
2087               from_buf_old_len = 0;
2088             }
2089
2090 reconvert:
2091
2092           if (!channel->do_encode) /* UTF-8 encoding */
2093             {
2094               const gchar *badchar;
2095               gsize try_len = MIN (from_buf_len, space_in_buf);
2096
2097               /* UTF-8, just validate, emulate g_iconv */
2098
2099               if (!g_utf8_validate (from_buf, try_len, &badchar))
2100                 {
2101                   gunichar try_char;
2102                   gsize incomplete_len = from_buf + try_len - badchar;
2103
2104                   left_len = from_buf + from_buf_len - badchar;
2105
2106                   try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2107
2108                   switch (try_char)
2109                     {
2110                       case -2:
2111                         g_assert (incomplete_len < 6);
2112                         if (try_len == from_buf_len)
2113                           {
2114                             errnum = EINVAL;
2115                             err = (gsize) -1;
2116                           }
2117                         else
2118                           {
2119                             errnum = 0;
2120                             err = (gsize) 0;
2121                           }
2122                         break;
2123                       case -1:
2124                         g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2125                         /* FIXME bail here? */
2126                         errnum = EILSEQ;
2127                         err = (gsize) -1;
2128                         break;
2129                       default:
2130                         g_assert_not_reached ();
2131                         err = (gsize) -1;
2132                         errnum = 0; /* Don't confunse the compiler */
2133                     }
2134                 }
2135               else
2136                 {
2137                   err = (gsize) 0;
2138                   errnum = 0;
2139                   left_len = from_buf_len - try_len;
2140                 }
2141
2142               g_string_append_len (channel->write_buf, from_buf,
2143                                    from_buf_len - left_len);
2144               from_buf += from_buf_len - left_len;
2145             }
2146           else
2147             {
2148                gchar *outbuf;
2149
2150                left_len = from_buf_len;
2151                g_string_set_size (channel->write_buf, channel->write_buf->len
2152                                   + space_in_buf);
2153                outbuf = channel->write_buf->str + channel->write_buf->len
2154                         - space_in_buf;
2155                err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2156                               &outbuf, &space_in_buf);
2157                errnum = errno;
2158                g_string_truncate (channel->write_buf, channel->write_buf->len
2159                                   - space_in_buf);
2160             }
2161
2162           if (err == (gsize) -1)
2163             {
2164               switch (errnum)
2165                 {
2166                   case EINVAL:
2167                     g_assert (left_len < 6);
2168
2169                     if (from_buf_old_len == 0)
2170                       {
2171                         /* Not from partial_write_buf */
2172
2173                         memcpy (channel->partial_write_buf, from_buf, left_len);
2174                         channel->partial_write_buf[left_len] = '\0';
2175                         if (bytes_written)
2176                           *bytes_written = count;
2177                         return G_IO_STATUS_NORMAL;
2178                       }
2179
2180                     /* Working in partial_write_buf */
2181
2182                     if (left_len == from_buf_len)
2183                       {
2184                         /* Didn't convert anything, must still have
2185                          * less than a full character
2186                          */
2187
2188                         g_assert (count == from_buf_len - from_buf_old_len);
2189
2190                         channel->partial_write_buf[from_buf_len] = '\0';
2191
2192                         if (bytes_written)
2193                           *bytes_written = count;
2194
2195                         return G_IO_STATUS_NORMAL;
2196                       }
2197
2198                     g_assert (from_buf_len - left_len >= from_buf_old_len);
2199
2200                     /* We converted all the old data. This is fine */
2201
2202                     break;
2203                   case E2BIG:
2204                     if (from_buf_len == left_len)
2205                       {
2206                         /* Nothing was written, add enough space for
2207                          * at least one character.
2208                          */
2209                         space_in_buf += MAX_CHAR_SIZE;
2210                         goto reconvert;
2211                       }
2212                     break;
2213                   case EILSEQ:
2214                     g_set_error_literal (error, G_CONVERT_ERROR,
2215                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2216                       _("Invalid byte sequence in conversion input"));
2217                     if (from_buf_old_len > 0 && from_buf_len == left_len)
2218                       g_warning ("Illegal sequence due to partial character "
2219                                  "at the end of a previous write.\n");
2220                     else
2221                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2222                     if (bytes_written)
2223                       *bytes_written = wrote_bytes;
2224                     channel->partial_write_buf[0] = '\0';
2225                     return G_IO_STATUS_ERROR;
2226                   default:
2227                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2228                       _("Error during conversion: %s"), g_strerror (errnum));
2229                     if (from_buf_len >= left_len + from_buf_old_len)
2230                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2231                     if (bytes_written)
2232                       *bytes_written = wrote_bytes;
2233                     channel->partial_write_buf[0] = '\0';
2234                     return G_IO_STATUS_ERROR;
2235                 }
2236             }
2237
2238           g_assert (from_buf_len - left_len >= from_buf_old_len);
2239
2240           wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2241
2242           if (from_buf_old_len > 0)
2243             {
2244               /* We were working in partial_write_buf */
2245
2246               buf += from_buf_len - left_len - from_buf_old_len;
2247               channel->partial_write_buf[0] = '\0';
2248             }
2249           else
2250             buf = from_buf;
2251         }
2252     }
2253
2254   if (bytes_written)
2255     *bytes_written = count;
2256
2257   return G_IO_STATUS_NORMAL;
2258 }
2259
2260 /**
2261  * g_io_channel_write_unichar:
2262  * @channel: a #GIOChannel
2263  * @thechar: a character
2264  * @error: location to return an error of type #GConvertError
2265  *         or #GIOChannelError
2266  *
2267  * Writes a Unicode character to @channel.
2268  * This function cannot be called on a channel with %NULL encoding.
2269  *
2270  * Return value: a #GIOStatus
2271  **/
2272 GIOStatus
2273 g_io_channel_write_unichar (GIOChannel  *channel,
2274                             gunichar     thechar,
2275                             GError     **error)
2276 {
2277   GIOStatus status;
2278   gchar static_buf[6];
2279   gsize char_len, wrote_len;
2280
2281   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2282   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2283   g_return_val_if_fail ((error == NULL) || (*error == NULL),
2284                         G_IO_STATUS_ERROR);
2285   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2286
2287   char_len = g_unichar_to_utf8 (thechar, static_buf);
2288
2289   if (channel->partial_write_buf[0] != '\0')
2290     {
2291       g_warning ("Partial charater written before writing unichar.\n");
2292       channel->partial_write_buf[0] = '\0';
2293     }
2294
2295   status = g_io_channel_write_chars (channel, static_buf,
2296                                      char_len, &wrote_len, error);
2297
2298   /* We validate UTF-8, so we can't get a partial write */
2299
2300   g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2301
2302   return status;
2303 }
2304
2305 /**
2306  * g_io_channel_error_quark:
2307  *
2308  * Return value: the quark used as %G_IO_CHANNEL_ERROR
2309  **/
2310 GQuark
2311 g_io_channel_error_quark (void)
2312 {
2313   return g_quark_from_static_string ("g-io-channel-error-quark");
2314 }
2315
2316 #define __G_IOCHANNEL_C__
2317 #include "galiasdef.c"