hu Jul 25 19:41:03 2002 Owen Taylor <otaylor@redhat.com>
[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, not 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       checked_to = MAX (use_buf->len - (line_term_len - 1), 0);
1604     }
1605
1606 done:
1607
1608   if (terminator_pos)
1609     *terminator_pos = line_length;
1610
1611   if (length)
1612     *length = line_length + got_term_len;
1613
1614   return G_IO_STATUS_NORMAL;
1615 }
1616
1617 /**
1618  * g_io_channel_read_to_end:
1619  * @channel: a #GIOChannel
1620  * @str_return: Location to store a pointer to a string holding
1621  *              the remaining data in the #GIOChannel. This data should
1622  *              be freed with g_free() when no longer needed. This
1623  *              data is terminated by an extra nul character, but there 
1624  *              may be other nuls in the intervening data.
1625  * @length: Location to store length of the data
1626  * @error: A location to return an error of type #GConvertError
1627  *         or #GIOChannelError
1628  *
1629  * Reads all the remaining data from the file.
1630  *
1631  * Return value: %G_IO_STATUS_NORMAL on success. This function never
1632  *               returns %G_IO_STATUS_EOF.
1633  **/
1634 GIOStatus
1635 g_io_channel_read_to_end (GIOChannel    *channel,
1636                           gchar        **str_return,
1637                           gsize         *length,
1638                           GError       **error)
1639 {
1640   GIOStatus status;
1641     
1642   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1643   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1644     G_IO_STATUS_ERROR);
1645   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1646
1647   if (str_return)
1648     *str_return = NULL;
1649   if (length)
1650     *length = 0;
1651
1652   if (!channel->use_buffer)
1653     {
1654       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1655                    _("Can't do a raw read in g_io_channel_read_to_end"));
1656       return G_IO_STATUS_ERROR;
1657     }
1658
1659   do
1660     status = g_io_channel_fill_buffer (channel, error);
1661   while (status == G_IO_STATUS_NORMAL);
1662
1663   if (status != G_IO_STATUS_EOF)
1664     return status;
1665
1666   if (channel->encoding && channel->read_buf->len > 0)
1667     {
1668       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1669                    _("Channel terminates in a partial character"));
1670       return G_IO_STATUS_ERROR;
1671     }
1672
1673   if (USE_BUF (channel) == NULL)
1674     {
1675       /* length is already set to zero */
1676       if (str_return)
1677         *str_return = g_strdup ("");
1678     }
1679   else
1680     {
1681       if (length)
1682         *length = USE_BUF (channel)->len;
1683
1684       if (str_return)
1685         *str_return = g_string_free (USE_BUF (channel), FALSE);
1686       else
1687         g_string_free (USE_BUF (channel), TRUE);
1688
1689       if (channel->encoding)
1690         channel->encoded_read_buf = NULL;
1691       else
1692         channel->read_buf = NULL;
1693     }
1694
1695   return G_IO_STATUS_NORMAL;
1696 }
1697
1698 /**
1699  * g_io_channel_read_chars:
1700  * @channel: a #GIOChannel
1701  * @buf: a buffer to read data into
1702  * @count: the size of the buffer. Note that the buffer may
1703  *         not be complelely filled even if there is data
1704  *         in the buffer if the remaining data is not a
1705  *         complete character.
1706  * @bytes_read: The number of bytes read. This may be zero even on
1707  *              success if count < 6 and the channel's encoding is non-%NULL.
1708  *              This indicates that the next UTF-8 character is too wide for
1709  *              the buffer.
1710  * @error: A location to return an error of type #GConvertError
1711  *         or #GIOChannelError.
1712  *
1713  * Replacement for g_io_channel_read() with the new API.
1714  *
1715  * Return value: the status of the operation.
1716  **/
1717 GIOStatus
1718 g_io_channel_read_chars (GIOChannel     *channel,
1719                          gchar          *buf,
1720                          gsize           count,
1721                          gsize          *bytes_read,
1722                          GError        **error)
1723 {
1724   GIOStatus status;
1725   gsize got_bytes;
1726
1727   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1728   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1729                         G_IO_STATUS_ERROR);
1730   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1731
1732   if (count == 0)
1733     {
1734       *bytes_read = 0;
1735       return G_IO_STATUS_NORMAL;
1736     }
1737   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1738
1739   if (!channel->use_buffer)
1740     {
1741       gsize tmp_bytes;
1742       
1743       g_assert (!channel->read_buf || channel->read_buf->len == 0);
1744
1745       status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
1746       
1747       if (bytes_read)
1748         *bytes_read = tmp_bytes;
1749
1750       return status;
1751     }
1752
1753   status = G_IO_STATUS_NORMAL;
1754
1755   while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
1756     status = g_io_channel_fill_buffer (channel, error);
1757
1758   /* Only return an error if we have no data */
1759
1760   if (BUF_LEN (USE_BUF (channel)) == 0)
1761     {
1762       g_assert (status != G_IO_STATUS_NORMAL);
1763
1764       if (status == G_IO_STATUS_EOF && channel->encoding
1765           && BUF_LEN (channel->read_buf) > 0)
1766         {
1767           g_set_error (error, G_CONVERT_ERROR,
1768                        G_CONVERT_ERROR_PARTIAL_INPUT,
1769                        _("Leftover unconverted data in read buffer"));
1770           status = G_IO_STATUS_ERROR;
1771         }
1772
1773       if (bytes_read)
1774         *bytes_read = 0;
1775
1776       return status;
1777     }
1778
1779   if (status == G_IO_STATUS_ERROR)
1780     g_clear_error (error);
1781
1782   got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
1783
1784   g_assert (got_bytes > 0);
1785
1786   if (channel->encoding)
1787     /* Don't validate for NULL encoding, binary safe */
1788     {
1789       gchar *nextchar, *prevchar;
1790
1791       g_assert (USE_BUF (channel) == channel->encoded_read_buf);
1792
1793       nextchar = channel->encoded_read_buf->str;
1794
1795       do
1796         {
1797           prevchar = nextchar;
1798           nextchar = g_utf8_next_char (nextchar);
1799           g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
1800         }
1801       while (nextchar < channel->encoded_read_buf->str + got_bytes);
1802
1803       if (nextchar > channel->encoded_read_buf->str + got_bytes)
1804         got_bytes = prevchar - channel->encoded_read_buf->str;
1805
1806       g_assert (got_bytes > 0 || count < 6);
1807     }
1808
1809   memcpy (buf, USE_BUF (channel)->str, got_bytes);
1810   g_string_erase (USE_BUF (channel), 0, got_bytes);
1811
1812   if (bytes_read)
1813     *bytes_read = got_bytes;
1814
1815   return G_IO_STATUS_NORMAL;
1816 }
1817
1818 /**
1819  * g_io_channel_read_unichar:
1820  * @channel: a #GIOChannel
1821  * @thechar: a location to return a character
1822  * @error: A location to return an error of type #GConvertError
1823  *         or #GIOChannelError
1824  *
1825  * This function cannot be called on a channel with %NULL encoding.
1826  *
1827  * Return value: a #GIOStatus
1828  **/
1829 GIOStatus
1830 g_io_channel_read_unichar     (GIOChannel   *channel,
1831                                gunichar     *thechar,
1832                                GError      **error)
1833 {
1834   GIOStatus status = G_IO_STATUS_NORMAL;
1835
1836   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1837   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
1838   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1839                         G_IO_STATUS_ERROR);
1840   g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1841
1842   while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
1843     status = g_io_channel_fill_buffer (channel, error);
1844
1845   /* Only return an error if we have no data */
1846
1847   if (BUF_LEN (USE_BUF (channel)) == 0)
1848     {
1849       g_assert (status != G_IO_STATUS_NORMAL);
1850
1851       if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
1852         {
1853           g_set_error (error, G_CONVERT_ERROR,
1854                        G_CONVERT_ERROR_PARTIAL_INPUT,
1855                        _("Leftover unconverted data in read buffer"));
1856           status = G_IO_STATUS_ERROR;
1857         }
1858
1859       if (thechar)
1860         *thechar = (gunichar) -1;
1861
1862       return status;
1863     }
1864
1865   if (status == G_IO_STATUS_ERROR)
1866     g_clear_error (error);
1867
1868   if (thechar)
1869     *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
1870
1871   g_string_erase (channel->encoded_read_buf, 0,
1872                   g_utf8_next_char (channel->encoded_read_buf->str)
1873                   - channel->encoded_read_buf->str);
1874
1875   return G_IO_STATUS_NORMAL;
1876 }
1877
1878 /**
1879  * g_io_channel_write_chars:
1880  * @channel: a #GIOChannel
1881  * @buf: a buffer to write data from
1882  * @count: the size of the buffer. If -1, the buffer
1883  *         is taken to be a nul-terminated string.
1884  * @bytes_written: The number of bytes written. This can be nonzero
1885  *                 even if the return value is not %G_IO_STATUS_NORMAL.
1886  *                 If the return value is %G_IO_STATUS_NORMAL and the
1887  *                 channel is blocking, this will always be equal
1888  *                 to @count if @count >= 0.
1889  * @error: A location to return an error of type #GConvertError
1890  *         or #GIOChannelError
1891  *
1892  * Replacement for g_io_channel_write() with the new API.
1893  *
1894  * On seekable channels with encodings other than %NULL or UTF-8, generic
1895  * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
1896  * may only be made on a channel from which data has been read in the
1897  * cases described in the documentation for g_io_channel_set_encoding ().
1898  *
1899  * Return value: the status of the operation.
1900  **/
1901 GIOStatus
1902 g_io_channel_write_chars (GIOChannel    *channel,
1903                           const gchar   *buf,
1904                           gssize         count,
1905                           gsize         *bytes_written,
1906                           GError       **error)
1907 {
1908   GIOStatus status;
1909   gssize wrote_bytes = 0;
1910
1911   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1912   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1913                         G_IO_STATUS_ERROR);
1914   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1915
1916   if ((count < 0) && buf)
1917     count = strlen (buf);
1918   
1919   if (count == 0)
1920     {
1921       if (bytes_written)
1922         *bytes_written = 0;
1923       return G_IO_STATUS_NORMAL;
1924     }
1925
1926   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1927   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1928
1929   /* Raw write case */
1930
1931   if (!channel->use_buffer)
1932     {
1933       gsize tmp_bytes;
1934       
1935       g_assert (!channel->write_buf || channel->write_buf->len == 0);
1936       g_assert (channel->partial_write_buf[0] == '\0');
1937       
1938       status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
1939
1940       if (bytes_written)
1941         *bytes_written = tmp_bytes;
1942
1943       return status;
1944     }
1945
1946   /* General case */
1947
1948   if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
1949     || (BUF_LEN (channel->encoded_read_buf) > 0)))
1950     {
1951       if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
1952         {
1953           g_warning("Mixed reading and writing not allowed on encoded files");
1954           return G_IO_STATUS_ERROR;
1955         }
1956       status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1957       if (status != G_IO_STATUS_NORMAL)
1958         {
1959           if (bytes_written)
1960             *bytes_written = 0;
1961           return status;
1962         }
1963     }
1964
1965   if (!channel->write_buf)
1966     channel->write_buf = g_string_sized_new (channel->buf_size);
1967
1968   while (wrote_bytes < count)
1969     {
1970       gsize space_in_buf;
1971
1972       /* If the buffer is full, try a write immediately. In
1973        * the nonblocking case, this prevents the user from
1974        * writing just a little bit to the buffer every time
1975        * and never receiving an EAGAIN.
1976        */
1977
1978       if (channel->write_buf->len >= channel->buf_size)
1979         {
1980           gsize did_write = 0, this_time;
1981
1982           do
1983             {
1984               status = channel->funcs->io_write (channel, channel->write_buf->str
1985                                                  + did_write, channel->write_buf->len
1986                                                  - did_write, &this_time, error);
1987               did_write += this_time;
1988             }
1989           while (status == G_IO_STATUS_NORMAL &&
1990                  did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
1991
1992           g_string_erase (channel->write_buf, 0, did_write);
1993
1994           if (status != G_IO_STATUS_NORMAL)
1995             {
1996               if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
1997                 status = G_IO_STATUS_NORMAL;
1998               if (bytes_written)
1999                 *bytes_written = wrote_bytes;
2000               return status;
2001             }
2002         }
2003
2004       space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2005                      - channel->write_buf->len; /* 1 for NULL */
2006
2007       /* This is only true because g_io_channel_set_buffer_size ()
2008        * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2009        */
2010       g_assert (space_in_buf >= MAX_CHAR_SIZE);
2011
2012       if (!channel->encoding)
2013         {
2014           gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2015
2016           g_string_append_len (channel->write_buf, buf, write_this);
2017           buf += write_this;
2018           wrote_bytes += write_this;
2019         }
2020       else
2021         {
2022           const gchar *from_buf;
2023           gsize from_buf_len, from_buf_old_len, left_len;
2024           size_t err;
2025           gint errnum;
2026
2027           if (channel->partial_write_buf[0] != '\0')
2028             {
2029               g_assert (wrote_bytes == 0);
2030
2031               from_buf = channel->partial_write_buf;
2032               from_buf_old_len = strlen (channel->partial_write_buf);
2033               g_assert (from_buf_old_len > 0);
2034               from_buf_len = MIN (6, from_buf_old_len + count);
2035
2036               memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2037                       from_buf_len - from_buf_old_len);
2038             }
2039           else
2040             {
2041               from_buf = buf;
2042               from_buf_len = count - wrote_bytes;
2043               from_buf_old_len = 0;
2044             }
2045
2046 reconvert:
2047
2048           if (!channel->do_encode) /* UTF-8 encoding */
2049             {
2050               const gchar *badchar;
2051               gsize try_len = MIN (from_buf_len, space_in_buf);
2052
2053               /* UTF-8, just validate, emulate g_iconv */
2054
2055               if (!g_utf8_validate (from_buf, try_len, &badchar))
2056                 {
2057                   gunichar try_char;
2058
2059                   left_len = from_buf + try_len - badchar;
2060
2061                   try_char = g_utf8_get_char_validated (badchar, left_len);
2062
2063                   switch (try_char)
2064                     {
2065                       case -2:
2066                         g_assert (left_len < 6);
2067                         if (try_len == from_buf_len)
2068                           {
2069                             errnum = EINVAL;
2070                             err = (size_t) -1;
2071                           }
2072                         else
2073                           {
2074                             errnum = 0;
2075                             err = (size_t) -1;
2076                           }
2077                         break;
2078                       case -1:
2079                         g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2080                         /* FIXME bail here? */
2081                         errnum = EILSEQ;
2082                         err = (size_t) -1;
2083                         break;
2084                       default:
2085                         g_assert_not_reached ();
2086                         err = (size_t) -1;
2087                         errnum = 0; /* Don't confunse the compiler */
2088                     }
2089                 }
2090               else
2091                 {
2092                   err = (size_t) 0;
2093                   errnum = 0;
2094                   left_len = 0;
2095                 }
2096
2097               g_string_append_len (channel->write_buf, from_buf,
2098                                    try_len - left_len);
2099               from_buf += try_len - left_len;
2100             }
2101           else
2102             {
2103                gchar *outbuf;
2104
2105                left_len = from_buf_len;
2106                g_string_set_size (channel->write_buf, channel->write_buf->len
2107                                   + space_in_buf);
2108                outbuf = channel->write_buf->str + channel->write_buf->len
2109                         - space_in_buf;
2110                err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2111                               &outbuf, &space_in_buf);
2112                errnum = errno;
2113                g_string_truncate (channel->write_buf, channel->write_buf->len
2114                                   - space_in_buf);
2115             }
2116
2117           if (err == (size_t) -1)
2118             {
2119               switch (errnum)
2120                 {
2121                   case EINVAL:
2122                     g_assert (left_len < 6);
2123
2124                     if (from_buf_old_len == 0)
2125                       {
2126                         /* Not from partial_write_buf */
2127
2128                         memcpy (channel->partial_write_buf, from_buf, left_len);
2129                         channel->partial_write_buf[left_len] = '\0';
2130                         if (bytes_written)
2131                           *bytes_written = count;
2132                         return G_IO_STATUS_NORMAL;
2133                       }
2134
2135                     /* Working in partial_write_buf */
2136
2137                     if (left_len == from_buf_len)
2138                       {
2139                         /* Didn't convert anything, must still have
2140                          * less than a full character
2141                          */
2142
2143                         g_assert (count == from_buf_len - from_buf_old_len);
2144
2145                         channel->partial_write_buf[from_buf_len] = '\0';
2146
2147                         if (bytes_written)
2148                           *bytes_written = count;
2149
2150                         return G_IO_STATUS_NORMAL;
2151                       }
2152
2153                     g_assert (from_buf_len - left_len >= from_buf_old_len);
2154
2155                     /* We converted all the old data. This is fine */
2156
2157                     break;
2158                   case E2BIG:
2159                     if (from_buf_len == left_len)
2160                       {
2161                         /* Nothing was written, add enough space for
2162                          * at least one character.
2163                          */
2164                         space_in_buf += MAX_CHAR_SIZE;
2165                         goto reconvert;
2166                       }
2167                     break;
2168                   case EILSEQ:
2169                     g_set_error (error, G_CONVERT_ERROR,
2170                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2171                       _("Invalid byte sequence in conversion input"));
2172                     if (from_buf_old_len > 0 && from_buf_len == left_len)
2173                       g_warning ("Illegal sequence due to partial character "
2174                                  "at the end of a previous write.\n");
2175                     else
2176                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2177                     if (bytes_written)
2178                       *bytes_written = wrote_bytes;
2179                     channel->partial_write_buf[0] = '\0';
2180                     return G_IO_STATUS_ERROR;
2181                   default:
2182                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2183                       _("Error during conversion: %s"), g_strerror (errnum));
2184                     if (from_buf_len >= left_len + from_buf_old_len)
2185                       wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2186                     if (bytes_written)
2187                       *bytes_written = wrote_bytes;
2188                     channel->partial_write_buf[0] = '\0';
2189                     return G_IO_STATUS_ERROR;
2190                 }
2191             }
2192
2193           g_assert (from_buf_len - left_len >= from_buf_old_len);
2194
2195           wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2196
2197           if (from_buf_old_len > 0)
2198             {
2199               /* We were working in partial_write_buf */
2200
2201               buf += from_buf_len - left_len - from_buf_old_len;
2202               channel->partial_write_buf[0] = '\0';
2203             }
2204           else
2205             buf = from_buf;
2206         }
2207     }
2208
2209   if (bytes_written)
2210     *bytes_written = count;
2211
2212   return G_IO_STATUS_NORMAL;
2213 }
2214
2215 /**
2216  * g_io_channel_write_unichar:
2217  * @channel: a #GIOChannel
2218  * @thechar: a character
2219  * @error: A location to return an error of type #GConvertError
2220  *         or #GIOChannelError
2221  *
2222  * This function cannot be called on a channel with %NULL encoding.
2223  *
2224  * Return value: a #GIOStatus
2225  **/
2226 GIOStatus
2227 g_io_channel_write_unichar    (GIOChannel   *channel,
2228                                gunichar      thechar,
2229                                GError      **error)
2230 {
2231   GIOStatus status;
2232   gchar static_buf[6];
2233   gsize char_len, wrote_len;
2234
2235   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2236   g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2237   g_return_val_if_fail ((error == NULL) || (*error == NULL),
2238                         G_IO_STATUS_ERROR);
2239   g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2240
2241   char_len = g_unichar_to_utf8 (thechar, static_buf);
2242
2243   if (channel->partial_write_buf[0] != '\0')
2244     {
2245       g_warning ("Partial charater written before writing unichar.\n");
2246       channel->partial_write_buf[0] = '\0';
2247     }
2248
2249   status = g_io_channel_write_chars (channel, static_buf,
2250                                      char_len, &wrote_len, error);
2251
2252   /* We validate UTF-8, so we can't get a partial write */
2253
2254   g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2255
2256   return status;
2257 }
2258
2259 /**
2260  * g_io_channel_error_quark:
2261  *
2262  * Return value: The quark used as %G_IO_CHANNEL_ERROR
2263  **/
2264 GQuark
2265 g_io_channel_error_quark (void)
2266 {
2267   static GQuark q = 0;
2268   if (q == 0)
2269     q = g_quark_from_static_string ("g-io-channel-error-quark");
2270
2271   return q;
2272 }