Fix.
[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 <string.h>
35 #include <errno.h>
36
37 #include "config.h"
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #undef G_DISABLE_DEPRECATED
43
44 #include "glib.h"
45
46 #include "glibintl.h"
47
48 #define G_IO_NICE_BUF_SIZE      1024
49
50 static GIOError         g_io_error_get_from_g_error     (GIOStatus status,
51                                                          GError      *err);
52 static void             g_io_channel_purge              (GIOChannel  *channel);
53 static GIOStatus        g_io_channel_fill_buffer        (GIOChannel  *channel,
54                                                          GError     **err);
55
56 void
57 g_io_channel_init (GIOChannel *channel)
58 {
59   channel->channel_flags = 0;
60   channel->ref_count = 1;
61   channel->encoding = NULL;
62   channel->line_term = NULL;
63   channel->buf_size = G_IO_NICE_BUF_SIZE;
64   channel->read_buf = g_string_sized_new (G_IO_NICE_BUF_SIZE);
65   channel->encoded_read_buf = NULL; /* Allocate if we get an encoding */
66   channel->write_buf = g_string_sized_new (G_IO_NICE_BUF_SIZE);
67   channel->use_buffer = TRUE;
68   channel->do_encode = FALSE;
69   channel->ready_to_read = TRUE;
70   channel->ready_to_write = TRUE;
71   channel->close_on_unref = FALSE;
72   channel->seekable_cached = FALSE;
73 }
74
75 void 
76 g_io_channel_ref (GIOChannel *channel)
77 {
78   g_return_if_fail (channel != NULL);
79
80   channel->ref_count++;
81 }
82
83 void 
84 g_io_channel_unref (GIOChannel *channel)
85 {
86   g_return_if_fail (channel != NULL);
87
88   channel->ref_count--;
89   if (channel->ref_count == 0)
90     {
91       if (channel->close_on_unref)
92         g_io_channel_close (channel);
93       else
94         g_io_channel_purge (channel);
95       g_free (channel->encoding);
96       if (channel->do_encode)
97         {
98           g_iconv_close (channel->read_cd);
99           g_iconv_close (channel->write_cd);
100           g_string_free (channel->encoded_read_buf, TRUE);
101         }
102       g_free (channel->line_term);
103       g_string_free (channel->read_buf, TRUE);
104       g_string_free (channel->write_buf, TRUE);
105       channel->funcs->io_free (channel);
106     }
107 }
108
109 static GIOError
110 g_io_error_get_from_g_error (GIOStatus status,
111                              GError *err)
112 {
113   switch (status)
114     {
115       case G_IO_STATUS_NORMAL:
116       case G_IO_STATUS_EOF:
117         return G_IO_ERROR_NONE;
118       case G_IO_STATUS_AGAIN:
119         return G_IO_ERROR_AGAIN;
120       case G_IO_STATUS_ERROR:
121         if (err->domain != G_IO_CHANNEL_ERROR)
122           return G_IO_ERROR_UNKNOWN;
123         switch (err->code)
124           {
125             case G_IO_CHANNEL_ERROR_INVAL:
126               return G_IO_ERROR_INVAL;
127             default:
128               return G_IO_ERROR_UNKNOWN;
129           }
130       default:
131         g_assert_not_reached ();
132         return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
133     }
134 }
135
136 /**
137  * g_io_channel_read:
138  * @channel: a #GIOChannel. 
139  * @buf: a buffer to read the data into (which should be at least count bytes long).
140  * @count: the number of bytes to read from the #GIOChannel.
141  * @bytes_read: returns the number of bytes actually read. 
142  * 
143  * Reads data from a #GIOChannel. This function is depricated. New code should
144  * use g_io_channel_read_chars() instead.
145  * 
146  * Return value: %G_IO_ERROR_NONE if the operation was successful. 
147  **/
148 GIOError 
149 g_io_channel_read (GIOChannel *channel, 
150                    gchar      *buf, 
151                    gsize       count,
152                    gsize      *bytes_read)
153 {
154   GError *err = NULL;
155   GIOError error;
156   GIOStatus status;
157
158   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
159   g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
160
161   status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
162
163   error = g_io_error_get_from_g_error (status, err);
164
165   if (err)
166     g_error_free (err);
167
168   return error;
169 }
170
171 /**
172  * g_io_channel_write:
173  * @channel:  a #GIOChannel.
174  * @buf: the buffer containing the data to write. 
175  * @count: the number of bytes to write.
176  * @bytes_written:  the number of bytes actually written.
177  * 
178  * Writes data to a #GIOChannel. This function is depricated. New code should
179  * use g_io_channel_write_chars() instead.
180  * 
181  * Return value:  %G_IO_ERROR_NONE if the operation was successful.
182  **/
183 GIOError 
184 g_io_channel_write (GIOChannel  *channel, 
185                     const gchar *buf, 
186                     gsize        count,
187                     gsize       *bytes_written)
188 {
189   GError *err = NULL;
190   GIOError error;
191   GIOStatus status;
192
193   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
194   g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
195
196   status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
197
198   error = g_io_error_get_from_g_error (status, err);
199
200   if (err)
201     g_error_free (err);
202
203   return error;
204 }
205
206 /**
207  * g_io_channel_seek:
208  * @channel: a #GIOChannel. 
209  * @offset: an offset, in bytes, which is added to the position specified by @type
210  * @type: the position in the file, which can be %G_SEEK_CUR (the current
211  *        position), %G_SEEK_SET (the start of the file), or %G_SEEK_END (the end of the
212  *        file).
213  * 
214  * Sets the current position in the #GIOChannel, similar to the standard library
215  * function fseek(). This function is depricated. New code should
216  * use g_io_channel_seek_position() instead.
217  * 
218  * Return value: %G_IO_ERROR_NONE if the operation was successful.
219  **/
220 GIOError 
221 g_io_channel_seek  (GIOChannel   *channel,
222                     glong         offset, 
223                     GSeekType     type)
224 {
225   GError *err = NULL;
226   GIOError error;
227   GIOStatus status;
228
229   g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
230
231   switch (type)
232     {
233       case G_SEEK_CUR:
234       case G_SEEK_SET:
235       case G_SEEK_END:
236         break;
237       default:
238         g_warning ("g_io_channel_seek: unknown seek type");
239         return G_IO_ERROR_UNKNOWN;
240     }
241
242   status = channel->funcs->io_seek (channel, offset, type, &err);
243
244   error = g_io_error_get_from_g_error (status, err);
245
246   if (err)
247     g_error_free (err);
248
249   return error;
250 }
251
252 /* The function g_io_channel_new_file() is prototyped in both
253  * giounix.c and giowin32.c, so we stick its documentation here.
254  */
255
256 /**
257  * g_io_channel_new_file:
258  * @filename: A string containing the name of a file.
259  * @mode: A #GIOFileMode
260  * @error: A location to return an error of type %G_IO_CHANNEL_ERROR.
261  *
262  * Open a file @filename as a #GIOChannel using mode @mode. This
263  * channel will be closed when the last reference to it is dropped,
264  * so there is no need to call g_io_channel_close() (though doing
265  * so will not cause problems, as long as no attempt is made to
266  * access the channel after it is closed).
267  *
268  * Return value: A #GIOChannel on success, %NULL on failure.
269  **/
270
271 /**
272  * g_io_channel_close:
273  * @channel: A #GIOChannel
274  * 
275  * Close an IO channel. Any pending data to be written will be
276  * flushed, ignoring errors. The channel will not be freed until the
277  * last reference is dropped using g_io_channel_unref(). This
278  * function is deprecated: you should use g_io_channel_shutdown()
279  * instead.
280  **/
281 void
282 g_io_channel_close (GIOChannel *channel)
283 {
284   GError *err = NULL;
285   
286   g_return_if_fail (channel != NULL);
287
288   g_io_channel_purge (channel);
289
290   channel->funcs->io_close (channel, &err);
291
292   if (err)
293     { /* No way to return the error */
294       g_warning ("Error closing channel: %s", err->message);
295       g_error_free (err);
296     }
297   
298   channel->close_on_unref = FALSE; /* Because we already did */
299   channel->ready_to_read = FALSE;
300   channel->ready_to_write = FALSE;
301 }
302
303 /**
304  * g_io_channel_shutdown:
305  * @channel: a #GIOChannel
306  * @flush: if %TRUE, flush pending
307  * @err: location to store a #GIOChannelError
308  * 
309  * Close an IO channel. Any pending data to be written will be
310  * flushed. The channel will not be freed until the
311  * last reference is dropped using g_io_channel_unref().
312  **/
313 GIOStatus
314 g_io_channel_shutdown (GIOChannel *channel,
315                        gboolean    flush,
316                        GError     **err)
317 {
318   GIOStatus status;
319   GIOStatus result = G_IO_STATUS_NORMAL;
320   
321   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
322
323   if (flush && channel->write_buf->len > 0)
324     {
325       GIOFlags flags;
326       
327       /* Set the channel to blocking, to avoid a busy loop
328        */
329       flags = g_io_channel_get_flags (channel);
330       status = g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
331       if (status != G_IO_STATUS_NORMAL)
332         result = G_IO_STATUS_ERROR; 
333       
334       g_io_channel_flush (channel, err);
335     }
336
337   status = channel->funcs->io_close (channel, err && *err ? NULL : err);
338   if (status != G_IO_STATUS_NORMAL)
339     result = G_IO_STATUS_ERROR; 
340
341   channel->close_on_unref = FALSE; /* Because we already did */
342   channel->ready_to_read = FALSE;
343   channel->ready_to_write = FALSE;
344
345   return result;
346 }
347
348 /* This function is used for the final flush on close or unref */
349 static void
350 g_io_channel_purge (GIOChannel *channel)
351 {
352   GError *err = NULL;
353
354   g_return_if_fail (channel != NULL);
355
356   if (channel->write_buf->len > 0)
357     {
358       GIOFlags flags;
359       
360       /* Set the channel to blocking, to avoid a busy loop
361        */
362       flags = g_io_channel_get_flags (channel);
363       g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
364
365       g_io_channel_flush (channel, &err);
366
367       if (err)
368         { /* No way to return the error */
369           g_warning ("Error flushing string: %s", err->message);
370           g_error_free (err);
371         }
372     }
373
374   /* Flush these in case anyone tries to close without unrefing */
375
376   g_string_truncate (channel->read_buf, 0);
377   if (channel->do_encode)
378     g_string_truncate (channel->encoded_read_buf, 0);
379   g_string_truncate (channel->write_buf, 0);
380 }
381
382 GSource *
383 g_io_create_watch (GIOChannel  *channel,
384                    GIOCondition condition)
385 {
386   g_return_val_if_fail (channel != NULL, NULL);
387
388   return channel->funcs->io_create_watch (channel, condition);
389 }
390
391 guint 
392 g_io_add_watch_full (GIOChannel    *channel,
393                      gint           priority,
394                      GIOCondition   condition,
395                      GIOFunc        func,
396                      gpointer       user_data,
397                      GDestroyNotify notify)
398 {
399   GSource *source;
400   guint id;
401   
402   g_return_val_if_fail (channel != NULL, 0);
403
404   source = g_io_create_watch (channel, condition);
405
406   if (priority != G_PRIORITY_DEFAULT)
407     g_source_set_priority (source, priority);
408   g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
409
410   id = g_source_attach (source, NULL);
411   g_source_unref (source);
412
413   return id;
414 }
415
416 guint 
417 g_io_add_watch (GIOChannel    *channel,
418                 GIOCondition   condition,
419                 GIOFunc        func,
420                 gpointer       user_data)
421 {
422   return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
423 }
424
425 /**
426  * g_io_channel_get_buffer_condition:
427  * @channel: A #GIOChannel
428  *
429  * This function returns a #GIOCondition depending on the status of the
430  * internal buffers in the #GIOChannel. Only the flags %G_IO_IN and
431  * %G_IO_OUT will be set.
432  *
433  * Return value: A #GIOCondition
434  **/
435 GIOCondition
436 g_io_channel_get_buffer_condition (GIOChannel *channel)
437 {
438   return
439     ((channel->read_buf && channel->read_buf->len > 0) ? G_IO_IN : 0) |
440     ((channel->write_buf && channel->write_buf->len <= channel->buf_size) ? G_IO_OUT : 0);
441 }
442
443 /**
444  * g_channel_error_from_errno:
445  * @en: An errno error number, e.g. EINVAL
446  *
447  * Return value: A #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL
448  **/
449 GIOChannelError
450 g_channel_error_from_errno (gint en)
451 {
452 #ifdef EAGAIN
453   g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
454 #endif
455 #ifdef EINTR
456   g_return_val_if_fail (en != EINTR, G_IO_CHANNEL_ERROR_FAILED);
457 #endif
458
459   switch (en)
460     {
461 #ifdef EACCES
462     case EACCES:
463       return G_IO_CHANNEL_ERROR_ACCES;
464 #endif
465
466 #ifdef EBADF
467     case EBADF:
468       return G_IO_CHANNEL_ERROR_BADF;
469 #endif
470
471 #ifdef EFAULT
472     case EFAULT:
473       return G_IO_CHANNEL_ERROR_FAULT;
474 #endif
475
476 #ifdef EINVAL
477     case EINVAL:
478       return G_IO_CHANNEL_ERROR_INVAL;
479 #endif
480
481 #ifdef EIO
482     case EIO:
483       return G_IO_CHANNEL_ERROR_IO;
484 #endif
485
486 #ifdef EISDIR
487     case EISDIR:
488       return G_IO_CHANNEL_ERROR_ISDIR;
489 #endif
490
491 #ifdef EMFILE
492     case EMFILE:
493       return G_IO_CHANNEL_ERROR_MFILE;
494 #endif
495
496 #ifdef ENOLCK
497     case ENOLCK:
498       return G_IO_CHANNEL_ERROR_NOLCK;
499 #endif
500
501 #ifdef ENOSPC
502     case ENOSPC:
503       return G_IO_CHANNEL_ERROR_NOSPC;
504 #endif
505
506 #ifdef EPERM
507     case EPERM:
508       return G_IO_CHANNEL_ERROR_PERM;
509 #endif
510       
511 #ifdef EPIPE
512     case EPIPE:
513       return G_IO_CHANNEL_ERROR_PIPE;
514 #endif
515
516 #ifdef ESPIPE
517     case ESPIPE:
518       return G_IO_CHANNEL_ERROR_SPIPE;
519 #endif
520
521     default:
522       return G_IO_CHANNEL_ERROR_FAILED;
523     }
524 }
525
526 /**
527  * g_io_channel_set_buffer_size:
528  * @channel: a #GIOChannel
529  * @size: the size of the buffer. 0 == pick a good size
530  *
531  * Set the buffer size.
532  **/  
533 void
534 g_io_channel_set_buffer_size (GIOChannel        *channel,
535                               gsize              size)
536 {
537   g_return_if_fail (channel != NULL);
538
539   if (size == 0)
540     size = G_IO_NICE_BUF_SIZE;
541
542   channel->buf_size = size;
543 }
544
545 /**
546  * g_io_channel_get_buffer_size:
547  * @channel: a #GIOChannel
548  *
549  * Get the buffer size.
550  *
551  * Return value: the size of the buffer.
552  **/  
553 gsize
554 g_io_channel_get_buffer_size (GIOChannel        *channel)
555 {
556   g_return_val_if_fail (channel != NULL, 0);
557
558   return channel->buf_size;
559 }
560
561 /**
562  * g_io_channel_set_line_term:
563  * @channel: a #GIOChannel
564  * @line_term: The line termination string. Use %NULL for auto detect.
565  *
566  * This sets the string that #GIOChannel uses to determine
567  * where in the file a line break occurs.
568  **/
569 void
570 g_io_channel_set_line_term (GIOChannel  *channel,
571                             const gchar *line_term)
572 {
573   g_return_if_fail (channel != NULL);
574   g_return_if_fail (!line_term || line_term[0]); /* Disallow "" */
575
576   g_free (channel->line_term);
577   channel->line_term = g_strdup (line_term);
578 }
579
580 /**
581  * g_io_channel_get_line_term:
582  * @channel: a #GIOChannel
583  *
584  * This returns the string that #GIOChannel uses to determine
585  * where in the file a line break occurs. A value of %NULL
586  * indicates auto detection.
587  *
588  * Return value: The line termination string. This value
589  *   is owned by GLib and must not be freed.
590  **/
591 G_CONST_RETURN gchar*
592 g_io_channel_get_line_term (GIOChannel  *channel)
593 {
594   g_return_val_if_fail (channel != NULL, 0);
595
596   return channel->line_term;
597 }
598
599 /**
600  * g_io_channel_set_flags:
601  * @channel: a #GIOChannel
602  * @flags: the flags to set on the channel
603  * @error: A location to return an error of type #GIOChannelError
604  *
605  * Return value:
606  **/
607 GIOStatus
608 g_io_channel_set_flags (GIOChannel *channel,
609                         GIOFlags    flags,
610                         GError    **error)
611 {
612   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
613   g_return_val_if_fail ((error == NULL) || (*error == NULL),
614                         G_IO_STATUS_ERROR);
615
616   return (* channel->funcs->io_set_flags)(channel,
617                                           flags & G_IO_FLAG_SET_MASK,
618                                           error);
619 }
620
621 /**
622  * g_io_channel_get_flags:
623  * @channel: a #GIOChannel
624  * @flags: the flags which are set on the channel
625  *
626  * Gets the current flags for a #GIOChannel, including read-only
627  * flags such as %G_IO_FLAG_IS_READABLE.
628  **/
629 GIOFlags
630 g_io_channel_get_flags (GIOChannel *channel)
631 {
632   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
633
634   return (* channel->funcs->io_get_flags) (channel);
635 }
636
637 /**
638  * g_io_channel_seek_position:
639  * @channel: a #GIOChannel
640  * @offset: The offset in bytes from the position specified by @type
641  * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed if
642  *        the channel has the default encoding or the
643  *        encoding %G_IO_CHANNEL_ENCODE_RAW for raw file access.
644  * @error: A location to return an error of type #GIOChannelError
645  *
646  * Replacement for g_io_channel_seek() with the new API.
647  *
648  * Return value:
649  **/
650 GIOStatus
651 g_io_channel_seek_position      (GIOChannel* channel,
652                                  glong       offset,
653                                  GSeekType   type,
654                                  GError    **error)
655 {
656   GIOStatus status;
657
658   /* For files, only one of the read and write buffers can contain data.
659    * For sockets, both can contain data.
660    */
661
662   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
663   g_return_val_if_fail ((error == NULL) || (*error == NULL),
664                         G_IO_STATUS_ERROR);
665
666   switch (type)
667     {
668       case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
669         if (channel->do_encode)
670           {
671             g_warning ("Seek type G_SEEK_CUR not allowed for this channel's encoding.\n");
672             return G_IO_STATUS_ERROR;
673           }
674           break;
675       case G_SEEK_SET:
676       case G_SEEK_END:
677         break;
678       default:
679         g_warning ("g_io_channel_seek_position: unknown seek type");
680         return G_IO_STATUS_ERROR;
681     }
682
683   /* Do a quick check for easy failure
684    */
685   if (!channel->seekable_cached)
686     g_io_channel_get_flags (channel);
687
688   g_assert (channel->seekable_cached);
689
690   if (!channel->is_seekable)
691     {
692       g_set_error (error, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_SPIPE,
693         _("Seeking not allowed on this type of channel"));
694       return G_IO_STATUS_ERROR;
695     }
696
697   if (channel->use_buffer)
698     {
699       status = g_io_channel_flush (channel, error);
700       if (status != G_IO_STATUS_NORMAL)
701         return status;
702
703       if (type == G_SEEK_CUR)
704         {
705           g_assert (!channel->do_encode);
706           offset -= channel->read_buf->len;
707         }
708     }
709
710   status = channel->funcs->io_seek (channel, offset, type, error);
711
712   if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
713     {
714       g_string_erase (channel->read_buf, 0, channel->read_buf->len);
715       g_string_erase (channel->encoded_read_buf, 0, channel->read_buf->len);
716       channel->ready_to_write = TRUE;
717       if (channel->do_encode) /* Conversion state no longer matches position in file */
718         {
719           g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
720           g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
721         }
722     }
723
724   return status;
725 }
726
727 /**
728  * g_io_channel_flush:
729  * @channel: a #GIOChannel
730  * @error: location to store an error of type #GIOChannelError
731  *
732  * Flush the write buffer for the GIOChannel.
733  *
734  * Return value: the status of the operation: One of
735  *   G_IO_CHANNEL_NORMAL, G_IO_CHANNEL_AGAIN, or
736  *   G_IO_CHANNEL_ERROR.
737  **/
738 GIOStatus
739 g_io_channel_flush (GIOChannel  *channel,
740                     GError     **error)
741 {
742   GIOStatus status;
743   gsize this_time, bytes_written = 0;
744
745   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
746   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
747
748   if (channel->write_buf->len == 0)
749     {
750       channel->ready_to_read = TRUE;
751       return G_IO_STATUS_NORMAL;
752     }
753
754   do
755     {
756       status = channel->funcs->io_write (channel,
757                                       channel->write_buf->str + bytes_written,
758                                       channel->write_buf->len - bytes_written,
759                                       &this_time, error);
760       bytes_written += this_time;
761     }
762   while ((bytes_written < channel->write_buf->len)
763          && (status == G_IO_STATUS_NORMAL)
764          && (this_time > 0)); /* Prevent an infinite loop */
765
766   g_string_erase (channel->write_buf, 0, bytes_written);
767
768   if (status != G_IO_STATUS_NORMAL)
769     return status;
770
771   if (channel->write_buf->len > 0)
772     return G_IO_STATUS_AGAIN;
773
774   channel->ready_to_read = TRUE;
775
776   return G_IO_STATUS_NORMAL;
777 }
778
779 /**
780  * g_io_channel_set_encoding:
781  * @channel: a #GIOChannel
782  * @encoding: the encoding type
783  * @error: location to store an error of type #GConvertError.
784  *
785  * Set the encoding for the input/output of the channel. The internal
786  * encoding is always UTF-8.
787  *
788  * The encoding %G_IO_CHANNEL_ENCODE_RAW disables encoding and turns
789  * off internal buffering. Data can be read from it only with
790  * g_io_channel_read_chars(). Both %G_IO_CHANNEL_ENCODE_RAW and
791  * the default state (no encoding, but buffered)
792  * are safe to use with binary data.
793  *
794  * Encodings
795  * other than the default and %G_IO_CHANNEL_ENCODE_RAW cannot
796 b * use g_io_channel_seek_position() with seek type %G_SEEK_CUR,
797  * and cannot mix reading and writing if the channel is
798  * a file without first doing a seek of type %G_SEEK_SET or
799  * %G_SEEK_END.
800  *
801  * The encoding can only be set under three conditions:
802  *
803  * 1. The channel was just created, and has not been written to
804  *    or read from yet.
805  *
806  * 2. The channel is a file, and the file pointer was just
807  *    repositioned by a call to g_io_channel_seek_position().
808  *    (This flushes all the internal buffers.)
809  *
810  * 3. The current encoding is %G_IO_CHANNEL_ENCODE_RAW.
811  *
812  * Return Value: %G_IO_STATUS_NORMAL if the encoding was succesfully set.
813  **/
814 GIOStatus
815 g_io_channel_set_encoding (GIOChannel   *channel,
816                            const gchar  *encoding,
817                            GError      **error)
818 {
819   GIConv read_cd, write_cd;
820   gboolean did_encode;
821
822   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
823   g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
824
825   /* Make sure the buffers are empty */
826
827   g_return_val_if_fail (channel->read_buf->len == 0, G_IO_STATUS_ERROR);
828   g_return_val_if_fail (channel->write_buf->len == 0, G_IO_STATUS_ERROR);
829   g_return_val_if_fail (channel->encoded_read_buf == NULL ||
830                         channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
831
832   did_encode = channel->do_encode;
833
834   if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
835     {
836       channel->use_buffer = TRUE;
837       channel->do_encode = FALSE;
838       read_cd = write_cd = (GIConv) -1; /* keep the compiler happy */
839     }
840   else if (!strcmp (encoding, G_IO_CHANNEL_ENCODE_RAW))
841     {
842       channel->use_buffer = FALSE;
843       channel->do_encode = FALSE;
844       read_cd = write_cd = (GIConv) -1; /* keep the compiler happy */
845     }
846   else
847     {
848       gint err;
849       const gchar *from_enc, *to_enc;
850
851       read_cd = g_iconv_open ("UTF-8", encoding);
852
853       if (read_cd == (GIConv) -1)
854         {
855           err = errno;
856           from_enc = "UTF-8";
857           to_enc = encoding;
858           write_cd = (GIConv) -1; /* keep the compiler happy */
859         }
860       else
861         {
862           write_cd = g_iconv_open (encoding, "UTF-8");
863           if (write_cd == (GIConv) -1)
864             {
865               err = errno;
866               g_iconv_close (read_cd);
867               from_enc = encoding;
868               to_enc = "UTF-8";
869             }
870           else
871             {
872               err = 0;
873               from_enc = to_enc = NULL; /* Keep the compiler happy */
874             }
875         }
876
877       if (err)
878         {
879           /* Something went wrong.  */
880           if (err == EINVAL)
881             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
882                          _("Conversion from character set `%s' to `%s' is not supported"),
883                          from_enc, to_enc);
884           else
885             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
886                          _("Could not open converter from `%s' to `%s': %s"),
887                          from_enc, to_enc, strerror (errno));
888           return G_IO_STATUS_ERROR;
889         }
890
891       channel->use_buffer = TRUE;
892       channel->do_encode = TRUE;
893       if (!did_encode)
894         channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
895     }
896
897   /* The encoding is ok, so set the fields in channel */
898
899   if (did_encode)
900     {
901       g_iconv_close (channel->read_cd);
902       g_iconv_close (channel->write_cd);
903       if (!channel->do_encode)
904         {
905           g_string_free (channel->encoded_read_buf, TRUE);
906           channel->encoded_read_buf = NULL;
907         }
908     }
909
910   if (channel->do_encode)
911     {
912       channel->read_cd = read_cd;
913       channel->write_cd = write_cd;
914     }
915
916   g_free (channel->encoding);
917   channel->encoding = g_strdup (encoding);
918
919   return G_IO_STATUS_NORMAL;
920 }
921
922 /**
923  * g_io_channel_get_encoding:
924  * @channel: a #GIOChannel
925  *
926  * Get the encoding for the input/output of the channel. The internal
927  * encoding is always UTF-8. The encoding %G_IO_CHANNEL_ENCODE_RAW
928  * disables encoding and turns off internal buffering. Both
929  * %G_IO_CHANNEL_ENCODE_RAW and the default (no encoding, but buffered)
930  * are safe to use with binary data.
931  *
932  * Return value: A string containing the encoding, this string is
933  *   owned by GLib and must not be freed.
934  **/
935 G_CONST_RETURN gchar*
936 g_io_channel_get_encoding (GIOChannel      *channel)
937 {
938   g_return_val_if_fail (channel != NULL, NULL);
939
940   return channel->encoding;
941 }
942
943 static GIOStatus
944 g_io_channel_fill_buffer (GIOChannel *channel,
945                           GError    **err)
946 {
947   gsize read_size, cur_len, oldlen;
948   GIOStatus status;
949
950   if (!channel->ready_to_read)
951     {
952     status = g_io_channel_flush (channel, err);
953     if (status != G_IO_STATUS_NORMAL)
954       return status;
955     }
956   g_assert (channel->ready_to_read);
957
958   if (!channel->seekable_cached)
959     g_io_channel_get_flags (channel);
960
961   g_assert (channel->seekable_cached);
962
963   if (channel->is_seekable)
964     channel->ready_to_write = FALSE;
965
966   cur_len = channel->read_buf->len;
967
968   g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
969
970   status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
971                                     channel->buf_size, &read_size, err);
972
973   g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
974
975   g_string_truncate (channel->read_buf, read_size + cur_len);
976
977   if ((status != G_IO_STATUS_NORMAL)
978     && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
979     return status;
980
981   g_assert (channel->read_buf->len > 0);
982
983   if (channel->do_encode)
984     {
985       size_t errnum, inbytes_left, outbytes_left;
986       gchar *inbuf, *outbuf;
987
988       oldlen = channel->encoded_read_buf->len;
989
990 reencode:
991
992       inbytes_left = channel->read_buf->len;
993       outbytes_left = channel->buf_size;
994
995       g_string_set_size (channel->encoded_read_buf, channel->encoded_read_buf->len + outbytes_left);
996
997       inbuf = channel->read_buf->str;
998       outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len - outbytes_left;
999
1000       errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1001                         &outbuf, &outbytes_left);
1002
1003       g_string_erase (channel->read_buf, 0,
1004                       channel->read_buf->len - inbytes_left);
1005       g_string_truncate (channel->encoded_read_buf,
1006                          channel->encoded_read_buf->len - outbytes_left);
1007
1008       if (errnum == (size_t) -1)
1009         {
1010           switch (errno)
1011             {
1012               case EINVAL:
1013                 if ((oldlen == channel->encoded_read_buf->len)
1014                   && (status == G_IO_STATUS_EOF))
1015                   status = G_IO_STATUS_PARTIAL_CHARS;
1016                 else
1017                   status = G_IO_STATUS_NORMAL;
1018                 break;
1019               case E2BIG:
1020                 goto reencode;
1021               case EILSEQ:
1022                 if (oldlen < channel->encoded_read_buf->len)
1023                   status = G_IO_STATUS_NORMAL;
1024                 else
1025                   {
1026                     g_set_error (err, G_CONVERT_ERROR,
1027                       G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1028                       _("Invalid byte sequence in conversion input"));
1029                     return G_IO_STATUS_ERROR;
1030                   }
1031                 break;
1032               default:
1033                 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1034                   _("Error during conversion: %s"), strerror (errno));
1035                 return G_IO_STATUS_ERROR;
1036             }
1037         }
1038       if (channel->encoded_read_buf->len == 0)
1039         {
1040           g_assert (status != G_IO_STATUS_NORMAL);
1041           return status;
1042         }
1043     }
1044
1045   return status;
1046 }
1047
1048 /**
1049  * g_io_channel_read_line:
1050  * @channel: a #GIOChannel
1051  * @str_return: The line read from the #GIOChannel, not including the
1052  *              line terminator. This data should be freed with g_free()
1053  *              when no longer needed. This
1054  *              is a null terminated string. If a @length of zero is
1055  *              returned, this will be %NULL instead.
1056  * @length: location to store length of the read data, or %NULL
1057  * @terminator_pos: location to store position of line terminator, or %NULL
1058  * @error: A location to return an error of type #GConvertError
1059  *         or #GIOChannelError
1060  *
1061  * Read a line, not including the terminating character(s),
1062  * from a #GIOChannel into a newly allocated string.
1063  * @length will contain allocated memory if the return
1064  * is %G_IO_STATUS_NORMAL.
1065  *
1066  * Return value: a newly allocated string. Free this string
1067  *   with g_free() when you are done with it.
1068  **/
1069 GIOStatus
1070 g_io_channel_read_line (GIOChannel *channel,
1071                         gchar     **str_return,
1072                         gsize      *length,
1073                         gsize      *terminator_pos,
1074                         GError    **error)
1075 {
1076   GIOStatus status;
1077   GString *string;
1078   
1079   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1080   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1081   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1082                         G_IO_STATUS_ERROR);
1083
1084   string = g_string_sized_new (channel->buf_size);
1085
1086   status = g_io_channel_read_line_string (channel, string, terminator_pos, error);
1087
1088   if (length)
1089     *length = string->len;
1090
1091   if (str_return)
1092     *str_return = g_string_free (string, FALSE);
1093   else
1094     g_string_free (string, TRUE);
1095   
1096   return status;
1097 }
1098
1099 /**
1100  * g_io_channel_read_line_string:
1101  * @channel: a #GIOChannel
1102  * @buffer: a #GString into which the line will be written.
1103  *          If @buffer already contains data, the new data will
1104  *          be appended to it.
1105  * @terminator_pos: location to store position of line terminator, or %NULL
1106  * @error: a location to store an error of type #GConvertError
1107  *         or #GIOChannelError
1108  *
1109  * Read a line from a #GIOChannel, using a #GString as a buffer.
1110  *
1111  * Return value:
1112  **/
1113 GIOStatus
1114 g_io_channel_read_line_string (GIOChannel *channel,
1115                                GString    *buffer,
1116                                gsize      *terminator_pos,
1117                                GError    **error)
1118 {
1119   GIOStatus status;
1120   gsize checked_to, line_term_len, line_length;
1121   GString *use_buf;
1122   gboolean first_time = TRUE;
1123
1124   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1125   g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1126   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1127                         G_IO_STATUS_ERROR);
1128   
1129   if (!channel->use_buffer)
1130     {
1131       /* Can't do a raw read in read_line */
1132       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1133                    _("Can't do a raw read in g_io_channel_read_line_string"));
1134       return G_IO_STATUS_ERROR;
1135     }
1136
1137   if (!channel->ready_to_read)
1138     {
1139       status = g_io_channel_flush (channel, error);
1140       if (status != G_IO_STATUS_NORMAL)
1141         return status;
1142     }
1143   g_assert (channel->ready_to_read);
1144
1145   if (channel->do_encode)
1146     use_buf = channel->encoded_read_buf;
1147   else
1148     use_buf = channel->read_buf;
1149
1150   status = G_IO_STATUS_NORMAL;
1151
1152   if (channel->line_term)
1153     line_term_len = strlen (channel->line_term);
1154   else
1155     line_term_len = 2;
1156
1157   checked_to = 0;
1158
1159   while (TRUE)
1160     {
1161       if (!first_time || (use_buf->len == 0))
1162         {
1163           status = g_io_channel_fill_buffer (channel, error);
1164           switch (status)
1165             {
1166               case G_IO_STATUS_NORMAL:
1167                 g_assert (use_buf->len > 0);
1168                 break;
1169               case G_IO_STATUS_EOF:
1170               case G_IO_STATUS_PARTIAL_CHARS:
1171                 if (use_buf->len == 0)
1172                   return status;
1173                 break;
1174               default:
1175                 return status;
1176             }
1177         }
1178
1179       g_assert (use_buf->len > 0);
1180
1181       first_time = FALSE;
1182
1183       if (channel->line_term)
1184         {
1185           gchar *line_end = strstr (use_buf->str + checked_to, channel->line_term);
1186           if (line_end)
1187             {
1188               line_length = line_end - use_buf->str;
1189               break;
1190             }
1191         }
1192       else /* auto detect */
1193         {
1194           gchar *newline_pos, *linefeed_pos;
1195
1196           newline_pos = strchr (use_buf->str + checked_to, '\n');
1197           linefeed_pos = strchr (use_buf->str + checked_to, '\r');
1198
1199           g_assert (!newline_pos || !linefeed_pos || (newline_pos != linefeed_pos));
1200
1201           if (newline_pos && (!linefeed_pos || (linefeed_pos > newline_pos))) /* unix */
1202             {
1203               line_length = newline_pos - use_buf->str;
1204               line_term_len = 1;
1205               break;
1206             }
1207           else if (linefeed_pos &&
1208                    (linefeed_pos < use_buf->str + use_buf->len - 1 ||
1209                     status == G_IO_STATUS_EOF))
1210             {
1211               line_length = linefeed_pos - use_buf->str;
1212               if (newline_pos && (newline_pos == linefeed_pos + 1)) /* dos */
1213                 line_term_len = 2;
1214               else /* mac */
1215                 line_term_len = 1;
1216               break;
1217             }
1218         }
1219
1220       /* Also terminate on '\0' */
1221
1222       line_length = strlen (use_buf->str);
1223       if (line_length < use_buf->len)
1224         {
1225           line_term_len = 0;
1226           break;
1227         }
1228
1229       /* Check for EOF */
1230
1231       if (status != G_IO_STATUS_NORMAL)
1232         {
1233           line_length = use_buf->len;
1234           line_term_len = 0;
1235           break;
1236         }
1237
1238       if (use_buf->len > line_term_len - 1)
1239         checked_to = use_buf->len - (line_term_len - 1);
1240       else
1241         checked_to = 0;
1242     }
1243
1244   g_string_append_len (buffer, use_buf->str, line_length + line_term_len);
1245   g_string_erase (use_buf, 0, line_length + line_term_len);
1246
1247   if (terminator_pos)
1248     *terminator_pos = line_length;
1249
1250   return G_IO_STATUS_NORMAL;
1251 }
1252
1253 /**
1254  * g_io_channel_read_to_end:
1255  * @channel: a #GIOChannel
1256  * @str_return: Location to store a pointer to a string holding
1257  *              the remaining data in the #GIOChannel. This data should
1258  *              be freed with g_free() when no longer needed. This
1259  *              data is terminated by an extra null, but there may be other
1260  *              nulls in the intervening data.
1261  * @length: Location to store length of the data
1262  * @error: A location to return an error of type #GConvertError
1263  *         or #GIOChannelError
1264  *
1265  * Read all the remaining data from the file. Parameters as
1266  * for g_io_channel_read_line.
1267  *
1268  * Return value: One of #G_IO_STATUS_EOF or #G_IO_STATUS_PARTIAL_CHARS
1269  *               on success
1270  **/
1271 GIOStatus
1272 g_io_channel_read_to_end (GIOChannel    *channel,
1273                           gchar        **str_return,
1274                           gsize         *length,
1275                           GError       **error)
1276 {
1277   GIOStatus status;
1278   GString **use_buf;
1279     
1280   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1281   g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1282   g_return_val_if_fail (length != NULL, G_IO_STATUS_ERROR);
1283   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1284     G_IO_STATUS_ERROR);
1285
1286   *str_return = NULL;
1287   *length = 0;
1288
1289   if (!channel->use_buffer)
1290     {
1291       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1292                    _("Can't do a raw read in g_io_channel_read_to_end"));
1293       return G_IO_STATUS_ERROR;
1294     }
1295
1296   do
1297     status = g_io_channel_fill_buffer (channel, error);
1298   while (status == G_IO_STATUS_NORMAL);
1299
1300   if ((status != G_IO_STATUS_EOF)
1301     && (status != G_IO_STATUS_PARTIAL_CHARS))
1302     return status;
1303
1304   if (channel->do_encode)
1305     use_buf = &channel->encoded_read_buf;
1306   else
1307     use_buf = &channel->read_buf;
1308
1309   if (length)
1310     *length = (*use_buf)->len;
1311
1312   if (str_return)
1313     *str_return = g_string_free (*use_buf, FALSE);
1314   else
1315     g_string_free (*use_buf, TRUE);
1316   
1317   *use_buf = g_string_sized_new (channel->buf_size);
1318
1319   return status;
1320 }
1321
1322 /**
1323  * g_io_channel_read_chars:
1324  * @channel: a #GIOChannel
1325  * @buf: a buffer to read data into
1326  * @count: the size of the buffer. Note that the buffer may
1327  *         not be complelely filled even if there is data
1328  *         in the buffer if the remaining data is not a
1329  *         complete character.
1330  * @bytes_read: The number of bytes read.
1331  * @error: A location to return an error of type #GConvertError
1332  *         or #GIOChannelError.
1333  *
1334  * Replacement for g_io_channel_read() with the new API.
1335  *
1336  * Return value:
1337  **/
1338 GIOStatus
1339 g_io_channel_read_chars (GIOChannel     *channel,
1340                          gchar          *buf,
1341                          gsize           count,
1342                          gsize          *bytes_read,
1343                          GError        **error)
1344 {
1345   GIOStatus status;
1346   GString *use_buf;
1347
1348   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1349   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1350                         G_IO_STATUS_ERROR);
1351   g_return_val_if_fail (bytes_read != NULL, G_IO_STATUS_ERROR);
1352
1353   if (count == 0)
1354     {
1355       *bytes_read = 0;
1356       return G_IO_STATUS_NORMAL;
1357     }
1358   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1359
1360   if (!channel->use_buffer)
1361     {
1362       g_assert (channel->ready_to_read);
1363       g_assert (channel->read_buf->len == 0);
1364
1365       return channel->funcs->io_read (channel, buf, count, bytes_read, error);
1366     }
1367
1368   if (!channel->ready_to_read)
1369     {
1370       status = g_io_channel_flush (channel, error);
1371       if (status != G_IO_STATUS_NORMAL)
1372         return status;
1373     }
1374   g_assert (channel->ready_to_read);
1375
1376   if (channel->do_encode)
1377     use_buf = channel->encoded_read_buf;
1378   else
1379     use_buf = channel->read_buf;
1380
1381   status = G_IO_STATUS_NORMAL;
1382
1383   while (use_buf->len < count && status == G_IO_STATUS_NORMAL)
1384     {
1385       status = g_io_channel_fill_buffer (channel, error);
1386     }
1387
1388   switch (status)
1389     {
1390     case G_IO_STATUS_NORMAL:
1391       g_assert (use_buf->len > 0);
1392       break;
1393     case G_IO_STATUS_EOF:
1394     case G_IO_STATUS_PARTIAL_CHARS:
1395       if (use_buf->len == 0)
1396         {
1397           *bytes_read = 0;
1398           return status;
1399         }
1400       break;
1401     default:
1402       *bytes_read = 0;
1403       return status;
1404     }
1405
1406   *bytes_read = MIN (count, use_buf->len);
1407   memcpy (buf, use_buf->str, *bytes_read);
1408   g_string_erase (use_buf, 0, *bytes_read);
1409
1410   return G_IO_STATUS_NORMAL;
1411 }
1412
1413 /**
1414  * g_io_channel_write_chars:
1415  * @channel: a #GIOChannel
1416  * @buf: a buffer to write data from
1417  * @count: the size of the buffer. If -1, the buffer
1418  *         is taken to be a nul terminated string.
1419  * @bytes_written: The number of bytes written.
1420  * @error: A location to return an error of type #GConvertError
1421  *         or #GIOChannelError
1422  *
1423  * Replacement for g_io_channel_write() with the new API.
1424  *
1425  * Return value: a return value of %G_IO_STATUS_PARTIAL_CHARS
1426  *               indicates that @buf contains less than one
1427  *               complete UTF-8 character.
1428  **/
1429 GIOStatus
1430 g_io_channel_write_chars (GIOChannel    *channel,
1431                           const gchar   *buf,
1432                           gssize         count,
1433                           gsize         *bytes_written,
1434                           GError       **error)
1435 {
1436   GIOStatus status;
1437
1438   g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1439   g_return_val_if_fail (bytes_written != NULL, G_IO_STATUS_ERROR);
1440   g_return_val_if_fail ((error == NULL) || (*error == NULL),
1441                         G_IO_STATUS_ERROR);
1442
1443   if (count < 0)
1444     count = strlen (buf);
1445   
1446   if (count == 0)
1447     return G_IO_STATUS_NORMAL;
1448
1449   g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1450   g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1451
1452   /* Raw write case */
1453
1454   if (!channel->use_buffer)
1455     {
1456       g_assert (channel->write_buf->len == 0);
1457       return channel->funcs->io_write (channel, buf, count, bytes_written, error);
1458     }
1459
1460   /* General case */
1461
1462   if (channel->write_buf->len == 0)
1463     {
1464       /* Check to make sure the channel's writeable before we stick
1465        * the first data in the buffer.
1466        */
1467       GIOFlags flags = g_io_channel_get_flags (channel);
1468
1469       if (!(flags & G_IO_FLAG_IS_WRITEABLE))
1470         {
1471           /* Mimic a failure of channel->funcs->io_write */
1472           g_set_error (error, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_BADF,
1473                        _("Channel is not writeable"));
1474           return G_IO_STATUS_ERROR;
1475         }
1476     }
1477   g_assert (channel->seekable_cached);
1478
1479   if (!channel->ready_to_write)
1480     {
1481       if (channel->is_seekable)
1482         {
1483           if (channel->do_encode)
1484             {
1485               g_set_error (error, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_ENCODE_RW,
1486                            _("Mixed reading and writing not allowed on encoded files"));
1487               return G_IO_STATUS_ERROR;
1488             }
1489           status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1490           if (status != G_IO_STATUS_NORMAL)
1491             return status;
1492         }
1493       channel->ready_to_write = TRUE;
1494     }
1495
1496   if (channel->is_seekable)
1497     channel->ready_to_read = FALSE;
1498
1499   if (!channel->do_encode)
1500     {
1501       g_string_append_len (channel->write_buf, buf, count);
1502       *bytes_written = count;
1503     }
1504   else
1505     {
1506       gsize bytes_to_go = count, buf_space, err;
1507       gchar *outbuf;
1508       gsize oldlen = channel->write_buf->len;
1509
1510       do
1511         {
1512           g_string_set_size (channel->write_buf, channel->write_buf->len + channel->buf_size);
1513           buf_space = channel->buf_size;
1514           outbuf = channel->write_buf->str + channel->write_buf->len - buf_space;
1515     
1516           err = g_iconv (channel->write_cd, (gchar**) &buf, &bytes_to_go,
1517                          &outbuf, &buf_space);
1518
1519           g_string_truncate (channel->write_buf, channel->write_buf->len - buf_space);
1520           *bytes_written = count - bytes_to_go;
1521
1522           if (err == (size_t) -1)
1523             {
1524               switch (errno)
1525                 {
1526                   case EINVAL:
1527                     if (*bytes_written > 0)
1528                       return G_IO_STATUS_NORMAL;
1529                     else
1530                       return G_IO_STATUS_PARTIAL_CHARS;
1531                   case E2BIG:
1532                     break;
1533                   case EILSEQ:
1534                     if (*bytes_written > 0)
1535                       return G_IO_STATUS_NORMAL;
1536                     else
1537                       {
1538                         g_set_error (error, G_CONVERT_ERROR,
1539                          G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1540                           _("Invalid byte sequence in conversion input"));
1541                         return G_IO_STATUS_ERROR;
1542                       }
1543                   default:
1544                     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1545                       _("Error during conversion: %s"), strerror (errno));
1546                     g_string_truncate (channel->write_buf, oldlen);
1547                     *bytes_written = 0;
1548                     return G_IO_STATUS_ERROR;
1549                 }
1550             }
1551         }
1552       while (bytes_to_go > 0);
1553     }
1554
1555   if (channel->write_buf->len > channel->buf_size)
1556     return g_io_channel_flush (channel, error);
1557   else
1558     return G_IO_STATUS_NORMAL;
1559 }
1560
1561 /**
1562  * g_channel_error_quark:
1563  *
1564  * Return value: The quark used as %G_IO_CHANNEL_ERROR
1565  **/
1566 GQuark
1567 g_channel_error_quark (void)
1568 {
1569   static GQuark q = 0;
1570   if (q == 0)
1571     q = g_quark_from_static_string ("g-channel-error-quark");
1572
1573   return q;
1574 }