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