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