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