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