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