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