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