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