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