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