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