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