1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * giochannel.c: IO Channel abstraction
5 * Copyright 1998 Owen Taylor
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.
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.
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.
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/.
43 #undef G_DISABLE_DEPRECATED
47 #include "giochannel.h"
53 #define G_IO_NICE_BUF_SIZE 1024
55 /* This needs to be as wide as the largest character in any possible encoding */
56 #define MAX_CHAR_SIZE 10
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 ().
62 #define USE_BUF(channel) ((channel)->encoding ? (channel)->encoded_read_buf \
63 : (channel)->read_buf)
64 #define BUF_LEN(string) ((string) ? (string)->len : 0)
66 static GIOError g_io_error_get_from_g_error (GIOStatus status,
68 static void g_io_channel_purge (GIOChannel *channel);
69 static GIOStatus g_io_channel_fill_buffer (GIOChannel *channel,
71 static GIOStatus g_io_channel_read_line_backend (GIOChannel *channel,
73 gsize *terminator_pos,
78 * @channel: a #GIOChannel
80 * Initializes a #GIOChannel struct.
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).
87 g_io_channel_init (GIOChannel *channel)
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;
107 * @channel: a #GIOChannel
109 * Increments the reference count of a #GIOChannel.
111 * Returns: the @channel that was passed in (since 2.6)
114 g_io_channel_ref (GIOChannel *channel)
116 g_return_val_if_fail (channel != NULL, NULL);
118 g_atomic_int_inc (&channel->ref_count);
124 * g_io_channel_unref:
125 * @channel: a #GIOChannel
127 * Decrements the reference count of a #GIOChannel.
130 g_io_channel_unref (GIOChannel *channel)
134 g_return_if_fail (channel != NULL);
136 is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
138 if (G_UNLIKELY (is_zero))
140 if (channel->close_on_unref)
141 g_io_channel_shutdown (channel, TRUE, NULL);
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);
161 g_io_error_get_from_g_error (GIOStatus status,
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);
174 if (err->domain != G_IO_CHANNEL_ERROR)
175 return G_IO_ERROR_UNKNOWN;
178 case G_IO_CHANNEL_ERROR_INVAL:
179 return G_IO_ERROR_INVAL;
181 return G_IO_ERROR_UNKNOWN;
184 g_assert_not_reached ();
185 return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
191 * @channel: a #GIOChannel
192 * @buf: a buffer to read the data into (which should be at least
194 * @count: the number of bytes to read from the #GIOChannel
195 * @bytes_read: returns the number of bytes actually read
197 * Reads data from a #GIOChannel.
199 * Return value: %G_IO_ERROR_NONE if the operation was successful.
201 * Deprecated:2.2: Use g_io_channel_read_chars() instead.
204 g_io_channel_read (GIOChannel *channel,
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);
220 return G_IO_ERROR_NONE;
223 g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
225 status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
227 error = g_io_error_get_from_g_error (status, err);
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
242 * Writes data to a #GIOChannel.
244 * Return value: %G_IO_ERROR_NONE if the operation was successful.
246 * Deprecated:2.2: Use g_io_channel_write_chars() instead.
249 g_io_channel_write (GIOChannel *channel,
252 gsize *bytes_written)
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);
261 status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
263 error = g_io_error_get_from_g_error (status, err);
273 * @channel: a #GIOChannel
274 * @offset: an offset, in bytes, which is added to the position specified
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)
280 * Sets the current position in the #GIOChannel, similar to the standard
281 * library function fseek().
283 * Return value: %G_IO_ERROR_NONE if the operation was successful.
285 * Deprecated:2.2: Use g_io_channel_seek_position() instead.
288 g_io_channel_seek (GIOChannel *channel,
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);
306 g_warning ("g_io_channel_seek: unknown seek type");
307 return G_IO_ERROR_UNKNOWN;
310 status = channel->funcs->io_seek (channel, offset, type, &err);
312 error = g_io_error_get_from_g_error (status, err);
320 /* The function g_io_channel_new_file() is prototyped in both
321 * giounix.c and giowin32.c, so we stick its documentation here.
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
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).
337 * Return value: A #GIOChannel on success, %NULL on failure.
341 * g_io_channel_close:
342 * @channel: A #GIOChannel
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().
348 * Deprecated:2.2: Use g_io_channel_shutdown() instead.
351 g_io_channel_close (GIOChannel *channel)
355 g_return_if_fail (channel != NULL);
357 g_io_channel_purge (channel);
359 channel->funcs->io_close (channel, &err);
362 { /* No way to return the error */
363 g_warning ("Error closing channel: %s", err->message);
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;
374 * g_io_channel_shutdown:
375 * @channel: a #GIOChannel
376 * @flush: if %TRUE, flush pending
377 * @err: location to store a #GIOChannelError
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().
383 * Return value: the status of the operation.
386 g_io_channel_shutdown (GIOChannel *channel,
390 GIOStatus status, result;
391 GError *tmperr = NULL;
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);
396 if (channel->write_buf && channel->write_buf->len > 0)
402 /* Set the channel to blocking, to avoid a busy loop
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);
408 result = g_io_channel_flush (channel, &tmperr);
411 result = G_IO_STATUS_NORMAL;
413 g_string_truncate(channel->write_buf, 0);
416 result = G_IO_STATUS_NORMAL;
418 if (channel->partial_write_buf[0] != '\0')
421 g_warning ("Partial character at end of write buffer not flushed.\n");
422 channel->partial_write_buf[0] = '\0';
425 status = channel->funcs->io_close (channel, err);
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;
432 if (status != G_IO_STATUS_NORMAL)
434 g_clear_error (&tmperr);
437 else if (result != G_IO_STATUS_NORMAL)
439 g_propagate_error (err, tmperr);
443 return G_IO_STATUS_NORMAL;
446 /* This function is used for the final flush on close or unref */
448 g_io_channel_purge (GIOChannel *channel)
453 g_return_if_fail (channel != NULL);
455 if (channel->write_buf && channel->write_buf->len > 0)
459 /* Set the channel to blocking, to avoid a busy loop
461 flags = g_io_channel_get_flags (channel);
462 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
464 status = g_io_channel_flush (channel, &err);
467 { /* No way to return the error */
468 g_warning ("Error flushing string: %s", err->message);
473 /* Flush these in case anyone tries to close without unrefing */
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)
481 if (channel->encoded_read_buf)
482 g_string_truncate (channel->encoded_read_buf, 0);
484 if (channel->partial_write_buf[0] != '\0')
486 g_warning ("Partial character at end of write buffer not flushed.\n");
487 channel->partial_write_buf[0] = '\0';
494 * @channel: a #GIOChannel to watch
495 * @condition: conditions to watch for
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.
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.
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.
509 * Returns: a new #GSource
512 g_io_create_watch (GIOChannel *channel,
513 GIOCondition condition)
515 g_return_val_if_fail (channel != NULL, NULL);
517 return channel->funcs->io_create_watch (channel, condition);
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
529 * Adds the #GIOChannel into the default main loop context
530 * with the given priority.
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.
536 * Returns: the event source id
539 g_io_add_watch_full (GIOChannel *channel,
541 GIOCondition condition,
544 GDestroyNotify notify)
549 g_return_val_if_fail (channel != NULL, 0);
551 source = g_io_create_watch (channel, condition);
553 if (priority != G_PRIORITY_DEFAULT)
554 g_source_set_priority (source, priority);
555 g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
557 id = g_source_attach (source, NULL);
558 g_source_unref (source);
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
570 * Adds the #GIOChannel into the default main loop context
571 * with the default priority.
573 * Returns: the event source id
576 g_io_add_watch (GIOChannel *channel,
577 GIOCondition condition,
581 return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
585 * g_io_channel_get_buffer_condition:
586 * @channel: A #GIOChannel
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.
592 * Return value: A #GIOCondition
595 g_io_channel_get_buffer_condition (GIOChannel *channel)
597 GIOCondition condition = 0;
599 if (channel->encoding)
601 if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
602 condition |= G_IO_IN; /* Only return if we have full characters */
606 if (channel->read_buf && (channel->read_buf->len > 0))
607 condition |= G_IO_IN;
610 if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
611 condition |= G_IO_OUT;
617 * g_io_channel_error_from_errno:
618 * @en: an <literal>errno</literal> error number, e.g. %EINVAL
620 * Converts an <literal>errno</literal> error number to a #GIOChannelError.
622 * Return value: a #GIOChannelError error number, e.g.
623 * %G_IO_CHANNEL_ERROR_INVAL.
626 g_io_channel_error_from_errno (gint en)
629 g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
636 g_warning("Invalid file descriptor.\n");
637 return G_IO_CHANNEL_ERROR_FAILED;
642 g_warning("Buffer outside valid address space.\n");
643 return G_IO_CHANNEL_ERROR_FAILED;
648 return G_IO_CHANNEL_ERROR_FBIG;
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.
660 return G_IO_CHANNEL_ERROR_FAILED;
665 return G_IO_CHANNEL_ERROR_INVAL;
670 return G_IO_CHANNEL_ERROR_IO;
675 return G_IO_CHANNEL_ERROR_ISDIR;
680 return G_IO_CHANNEL_ERROR_NOSPC;
685 return G_IO_CHANNEL_ERROR_NXIO;
690 return G_IO_CHANNEL_ERROR_OVERFLOW;
695 return G_IO_CHANNEL_ERROR_PIPE;
699 return G_IO_CHANNEL_ERROR_FAILED;
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
708 * Sets the buffer size.
711 g_io_channel_set_buffer_size (GIOChannel *channel,
714 g_return_if_fail (channel != NULL);
717 size = G_IO_NICE_BUF_SIZE;
719 if (size < MAX_CHAR_SIZE)
720 size = MAX_CHAR_SIZE;
722 channel->buf_size = size;
726 * g_io_channel_get_buffer_size:
727 * @channel: a #GIOChannel
729 * Gets the buffer size.
731 * Return value: the size of the buffer.
734 g_io_channel_get_buffer_size (GIOChannel *channel)
736 g_return_val_if_fail (channel != NULL, 0);
738 return channel->buf_size;
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.
752 * This sets the string that #GIOChannel uses to determine
753 * where in the file a line break occurs.
756 g_io_channel_set_line_term (GIOChannel *channel,
757 const gchar *line_term,
760 g_return_if_fail (channel != NULL);
761 g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
763 if (line_term == NULL)
766 length = strlen (line_term);
768 g_free (channel->line_term);
769 channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
770 channel->line_term_len = length;
774 * g_io_channel_get_line_term:
775 * @channel: a #GIOChannel
776 * @length: a location to return the length of the line terminator
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.
782 * Return value: The line termination string. This value
783 * is owned by GLib and must not be freed.
785 G_CONST_RETURN gchar*
786 g_io_channel_get_line_term (GIOChannel *channel,
789 g_return_val_if_fail (channel != NULL, NULL);
792 *length = channel->line_term_len;
794 return channel->line_term;
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
803 * Sets the (writeable) flags in @channel to (@flags & %G_IO_CHANNEL_SET_MASK).
805 * Return value: the status of the operation.
808 g_io_channel_set_flags (GIOChannel *channel,
812 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
813 g_return_val_if_fail ((error == NULL) || (*error == NULL),
816 return (*channel->funcs->io_set_flags) (channel,
817 flags & G_IO_FLAG_SET_MASK,
822 * g_io_channel_get_flags:
823 * @channel: a #GIOChannel
825 * Gets the current flags for a #GIOChannel, including read-only
826 * flags such as %G_IO_FLAG_IS_READABLE.
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.
835 * Return value: the flags which are set on the channel
838 g_io_channel_get_flags (GIOChannel *channel)
842 g_return_val_if_fail (channel != NULL, 0);
844 flags = (* channel->funcs->io_get_flags) (channel);
846 /* Cross implementation code */
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;
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.
866 * Setting this flag to %TRUE for a channel you have already closed
867 * can cause problems.
870 g_io_channel_set_close_on_unref (GIOChannel *channel,
873 g_return_if_fail (channel != NULL);
875 channel->close_on_unref = do_close;
879 * g_io_channel_get_close_on_unref:
880 * @channel: a #GIOChannel.
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.
887 * Return value: Whether the channel will be closed on the final unref of
888 * the GIOChannel data structure.
891 g_io_channel_get_close_on_unref (GIOChannel *channel)
893 g_return_val_if_fail (channel != NULL, FALSE);
895 return channel->close_on_unref;
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
908 * Replacement for g_io_channel_seek() with the new API.
910 * Return value: the status of the operation.
913 g_io_channel_seek_position (GIOChannel *channel,
920 /* For files, only one of the read and write buffers can contain data.
921 * For sockets, both can contain data.
924 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
925 g_return_val_if_fail ((error == NULL) || (*error == NULL),
927 g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
931 case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
932 if (channel->use_buffer)
934 if (channel->do_encode && channel->encoded_read_buf
935 && channel->encoded_read_buf->len > 0)
937 g_warning ("Seek type G_SEEK_CUR not allowed for this"
938 " channel's encoding.\n");
939 return G_IO_STATUS_ERROR;
941 if (channel->read_buf)
942 offset -= channel->read_buf->len;
943 if (channel->encoded_read_buf)
945 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
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.
952 offset -= channel->encoded_read_buf->len;
960 g_warning ("g_io_channel_seek_position: unknown seek type");
961 return G_IO_STATUS_ERROR;
964 if (channel->use_buffer)
966 status = g_io_channel_flush (channel, error);
967 if (status != G_IO_STATUS_NORMAL)
971 status = channel->funcs->io_seek (channel, offset, type, error);
973 if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
975 if (channel->read_buf)
976 g_string_truncate (channel->read_buf, 0);
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);
984 if (channel->encoded_read_buf)
986 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
987 g_string_truncate (channel->encoded_read_buf, 0);
990 if (channel->partial_write_buf[0] != '\0')
992 g_warning ("Partial character at end of write buffer not flushed.\n");
993 channel->partial_write_buf[0] = '\0';
1001 * g_io_channel_flush:
1002 * @channel: a #GIOChannel
1003 * @error: location to store an error of type #GIOChannelError
1005 * Flushes the write buffer for the GIOChannel.
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.
1012 g_io_channel_flush (GIOChannel *channel,
1016 gsize this_time = 1, bytes_written = 0;
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);
1021 if (channel->write_buf == NULL || channel->write_buf->len == 0)
1022 return G_IO_STATUS_NORMAL;
1026 g_assert (this_time > 0);
1028 status = channel->funcs->io_write (channel,
1029 channel->write_buf->str + bytes_written,
1030 channel->write_buf->len - bytes_written,
1032 bytes_written += this_time;
1034 while ((bytes_written < channel->write_buf->len)
1035 && (status == G_IO_STATUS_NORMAL));
1037 g_string_erase (channel->write_buf, 0, bytes_written);
1043 * g_io_channel_set_buffered:
1044 * @channel: a #GIOChannel
1045 * @buffered: whether to set the channel buffered or unbuffered
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.
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
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.
1065 * The default state of the channel is buffered.
1068 g_io_channel_set_buffered (GIOChannel *channel,
1071 g_return_if_fail (channel != NULL);
1073 if (channel->encoding != NULL)
1075 g_warning ("Need to have NULL encoding to set the buffering state of the "
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);
1083 channel->use_buffer = buffered;
1087 * g_io_channel_get_buffered:
1088 * @channel: a #GIOChannel
1090 * Returns whether @channel is buffered.
1092 * Return Value: %TRUE if the @channel is buffered.
1095 g_io_channel_get_buffered (GIOChannel *channel)
1097 g_return_val_if_fail (channel != NULL, FALSE);
1099 return channel->use_buffer;
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
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.
1112 * The encoding %NULL is safe to use with binary data.
1114 * The encoding can only be set if one of the following conditions
1118 * The channel was just created, and has not been written to or read
1120 * </para></listitem>
1122 * The channel is write-only.
1123 * </para></listitem>
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>
1130 * The current encoding is %NULL or UTF-8.
1131 * </para></listitem>
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>
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
1145 * </para></listitem>
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.
1152 * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1155 g_io_channel_set_encoding (GIOChannel *channel,
1156 const gchar *encoding,
1159 GIConv read_cd, write_cd;
1160 gboolean did_encode;
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);
1165 /* Make sure the encoded buffers are empty */
1167 g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1168 channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1170 if (!channel->use_buffer)
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");
1175 channel->use_buffer = TRUE;
1178 if (channel->partial_write_buf[0] != '\0')
1180 g_warning ("Partial character at end of write buffer not flushed.\n");
1181 channel->partial_write_buf[0] = '\0';
1184 did_encode = channel->do_encode;
1186 if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1188 channel->do_encode = FALSE;
1189 read_cd = write_cd = (GIConv) -1;
1194 const gchar *from_enc = NULL, *to_enc = NULL;
1196 if (channel->is_readable)
1198 read_cd = g_iconv_open ("UTF-8", encoding);
1200 if (read_cd == (GIConv) -1)
1203 from_enc = encoding;
1208 read_cd = (GIConv) -1;
1210 if (channel->is_writeable && err == 0)
1212 write_cd = g_iconv_open (encoding, "UTF-8");
1214 if (write_cd == (GIConv) -1)
1222 write_cd = (GIConv) -1;
1226 g_assert (from_enc);
1230 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1231 _("Conversion from character set '%s' to '%s' is not supported"),
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));
1238 if (read_cd != (GIConv) -1)
1239 g_iconv_close (read_cd);
1240 if (write_cd != (GIConv) -1)
1241 g_iconv_close (write_cd);
1243 return G_IO_STATUS_ERROR;
1246 channel->do_encode = TRUE;
1249 /* The encoding is ok, so set the fields in channel */
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);
1256 if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1258 g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
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.
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);
1269 channel->read_cd = read_cd;
1270 channel->write_cd = write_cd;
1272 g_free (channel->encoding);
1273 channel->encoding = g_strdup (encoding);
1275 return G_IO_STATUS_NORMAL;
1279 * g_io_channel_get_encoding:
1280 * @channel: a #GIOChannel
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.
1286 * Return value: A string containing the encoding, this string is
1287 * owned by GLib and must not be freed.
1289 G_CONST_RETURN gchar*
1290 g_io_channel_get_encoding (GIOChannel *channel)
1292 g_return_val_if_fail (channel != NULL, NULL);
1294 return channel->encoding;
1298 g_io_channel_fill_buffer (GIOChannel *channel,
1301 gsize read_size, cur_len, oldlen;
1304 if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1306 status = g_io_channel_flush (channel, err);
1307 if (status != G_IO_STATUS_NORMAL)
1310 if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1312 g_warning ("Partial character at end of write buffer not flushed.\n");
1313 channel->partial_write_buf[0] = '\0';
1316 if (!channel->read_buf)
1317 channel->read_buf = g_string_sized_new (channel->buf_size);
1319 cur_len = channel->read_buf->len;
1321 g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1323 status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1324 channel->buf_size, &read_size, err);
1326 g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1328 g_string_truncate (channel->read_buf, read_size + cur_len);
1330 if ((status != G_IO_STATUS_NORMAL) &&
1331 ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1334 g_assert (channel->read_buf->len > 0);
1336 if (channel->encoded_read_buf)
1337 oldlen = channel->encoded_read_buf->len;
1341 if (channel->encoding)
1342 channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1345 if (channel->do_encode)
1347 gsize errnum, inbytes_left, outbytes_left;
1348 gchar *inbuf, *outbuf;
1351 g_assert (channel->encoded_read_buf);
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);
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
1367 errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1368 &outbuf, &outbytes_left);
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);
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);
1381 if (errnum == (gsize) -1)
1386 if ((oldlen == channel->encoded_read_buf->len)
1387 && (status == G_IO_STATUS_EOF))
1388 status = G_IO_STATUS_EOF;
1390 status = G_IO_STATUS_NORMAL;
1393 /* Buffer size at least 6, wrote at least on character */
1394 g_assert (inbuf != channel->read_buf->str);
1397 if (oldlen < channel->encoded_read_buf->len)
1398 status = G_IO_STATUS_NORMAL;
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;
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;
1414 g_assert ((status != G_IO_STATUS_NORMAL)
1415 || (channel->encoded_read_buf->len > 0));
1417 else if (channel->encoding) /* UTF-8 */
1419 gchar *nextchar, *lastchar;
1421 g_assert (channel->encoded_read_buf);
1423 nextchar = channel->read_buf->str;
1424 lastchar = channel->read_buf->str + channel->read_buf->len;
1426 while (nextchar < lastchar)
1430 val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1435 /* stop, leave partial character in buffer */
1436 lastchar = nextchar;
1439 if (oldlen < channel->encoded_read_buf->len)
1440 status = G_IO_STATUS_NORMAL;
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;
1448 lastchar = nextchar;
1451 nextchar = g_utf8_next_char (nextchar);
1456 if (lastchar > channel->read_buf->str)
1458 gint copy_len = lastchar - channel->read_buf->str;
1460 g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1462 g_string_erase (channel->read_buf, 0, copy_len);
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
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.
1486 * Return value: the status of the operation.
1489 g_io_channel_read_line (GIOChannel *channel,
1492 gsize *terminator_pos,
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),
1502 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1504 status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1507 *length = got_length;
1509 if (status == G_IO_STATUS_NORMAL)
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);
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
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
1531 * Reads a line from a #GIOChannel, using a #GString as a buffer.
1533 * Return value: the status of the operation.
1536 g_io_channel_read_line_string (GIOChannel *channel,
1538 gsize *terminator_pos,
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),
1548 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1550 if (buffer->len > 0)
1551 g_string_truncate (buffer, 0); /* clear out the buffer */
1553 status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1555 if (status == G_IO_STATUS_NORMAL)
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);
1567 g_io_channel_read_line_backend (GIOChannel *channel,
1569 gsize *terminator_pos,
1573 gsize checked_to, line_term_len, line_length, got_term_len;
1574 gboolean first_time = TRUE;
1576 if (!channel->use_buffer)
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;
1584 status = G_IO_STATUS_NORMAL;
1586 if (channel->line_term)
1587 line_term_len = channel->line_term_len;
1590 /* This value used for setting checked_to, it's the longest of the four
1591 * we autodetect for.
1598 gchar *nextchar, *lastchar;
1601 if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1604 status = g_io_channel_fill_buffer (channel, error);
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
1617 case G_IO_STATUS_EOF:
1618 if (BUF_LEN (USE_BUF (channel)) == 0)
1623 if (channel->encoding && channel->read_buf->len != 0)
1625 g_set_error_literal (error, G_CONVERT_ERROR,
1626 G_CONVERT_ERROR_PARTIAL_INPUT,
1627 _("Leftover unconverted data in "
1629 return G_IO_STATUS_ERROR;
1632 return G_IO_STATUS_EOF;
1642 g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1644 use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1648 lastchar = use_buf->str + use_buf->len;
1650 for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1651 channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1653 if (channel->line_term)
1655 if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1657 line_length = nextchar - use_buf->str;
1658 got_term_len = line_term_len;
1662 else /* auto detect */
1666 case '\n': /* unix */
1667 line_length = nextchar - use_buf->str;
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 */
1680 case '\xe2': /* Unicode paragraph separator */
1681 if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1683 line_length = nextchar - use_buf->str;
1688 case '\0': /* Embeded null in input */
1689 line_length = nextchar - use_buf->str;
1692 default: /* no match */
1698 /* If encoding != NULL, valid UTF-8, didn't overshoot */
1699 g_assert (nextchar == lastchar);
1703 if (status == G_IO_STATUS_EOF)
1705 if (channel->encoding && channel->read_buf->len > 0)
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;
1711 line_length = use_buf->len;
1716 if (use_buf->len > line_term_len - 1)
1717 checked_to = use_buf->len - (line_term_len - 1);
1725 *terminator_pos = line_length;
1728 *length = line_length + got_term_len;
1730 return G_IO_STATUS_NORMAL;
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
1745 * Reads all the remaining data from the file.
1747 * Return value: %G_IO_STATUS_NORMAL on success.
1748 * This function never returns %G_IO_STATUS_EOF.
1751 g_io_channel_read_to_end (GIOChannel *channel,
1758 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1759 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1761 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1768 if (!channel->use_buffer)
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;
1776 status = g_io_channel_fill_buffer (channel, error);
1777 while (status == G_IO_STATUS_NORMAL);
1779 if (status != G_IO_STATUS_EOF)
1782 if (channel->encoding && channel->read_buf->len > 0)
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;
1789 if (USE_BUF (channel) == NULL)
1791 /* length is already set to zero */
1793 *str_return = g_strdup ("");
1798 *length = USE_BUF (channel)->len;
1801 *str_return = g_string_free (USE_BUF (channel), FALSE);
1803 g_string_free (USE_BUF (channel), TRUE);
1805 if (channel->encoding)
1806 channel->encoded_read_buf = NULL;
1808 channel->read_buf = NULL;
1811 return G_IO_STATUS_NORMAL;
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
1826 * @error: a location to return an error of type #GConvertError
1827 * or #GIOChannelError.
1829 * Replacement for g_io_channel_read() with the new API.
1831 * Return value: the status of the operation.
1834 g_io_channel_read_chars (GIOChannel *channel,
1843 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1844 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1846 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1851 return G_IO_STATUS_NORMAL;
1853 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1855 if (!channel->use_buffer)
1859 g_assert (!channel->read_buf || channel->read_buf->len == 0);
1861 status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
1864 *bytes_read = tmp_bytes;
1869 status = G_IO_STATUS_NORMAL;
1871 while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
1872 status = g_io_channel_fill_buffer (channel, error);
1874 /* Only return an error if we have no data */
1876 if (BUF_LEN (USE_BUF (channel)) == 0)
1878 g_assert (status != G_IO_STATUS_NORMAL);
1880 if (status == G_IO_STATUS_EOF && channel->encoding
1881 && BUF_LEN (channel->read_buf) > 0)
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;
1895 if (status == G_IO_STATUS_ERROR)
1896 g_clear_error (error);
1898 got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
1900 g_assert (got_bytes > 0);
1902 if (channel->encoding)
1903 /* Don't validate for NULL encoding, binary safe */
1905 gchar *nextchar, *prevchar;
1907 g_assert (USE_BUF (channel) == channel->encoded_read_buf);
1909 nextchar = channel->encoded_read_buf->str;
1913 prevchar = nextchar;
1914 nextchar = g_utf8_next_char (nextchar);
1915 g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
1917 while (nextchar < channel->encoded_read_buf->str + got_bytes);
1919 if (nextchar > channel->encoded_read_buf->str + got_bytes)
1920 got_bytes = prevchar - channel->encoded_read_buf->str;
1922 g_assert (got_bytes > 0 || count < 6);
1925 memcpy (buf, USE_BUF (channel)->str, got_bytes);
1926 g_string_erase (USE_BUF (channel), 0, got_bytes);
1929 *bytes_read = got_bytes;
1931 return G_IO_STATUS_NORMAL;
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
1941 * Reads a Unicode character from @channel.
1942 * This function cannot be called on a channel with %NULL encoding.
1944 * Return value: a #GIOStatus
1947 g_io_channel_read_unichar (GIOChannel *channel,
1951 GIOStatus status = G_IO_STATUS_NORMAL;
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),
1957 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1959 while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
1960 status = g_io_channel_fill_buffer (channel, error);
1962 /* Only return an error if we have no data */
1964 if (BUF_LEN (USE_BUF (channel)) == 0)
1966 g_assert (status != G_IO_STATUS_NORMAL);
1968 if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
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;
1977 *thechar = (gunichar) -1;
1982 if (status == G_IO_STATUS_ERROR)
1983 g_clear_error (error);
1986 *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
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);
1992 return G_IO_STATUS_NORMAL;
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
2009 * Replacement for g_io_channel_write() with the new API.
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 ().
2016 * Return value: the status of the operation.
2019 g_io_channel_write_chars (GIOChannel *channel,
2022 gsize *bytes_written,
2026 gssize wrote_bytes = 0;
2028 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2029 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2031 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2033 if ((count < 0) && buf)
2034 count = strlen (buf);
2040 return G_IO_STATUS_NORMAL;
2043 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2044 g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
2046 /* Raw write case */
2048 if (!channel->use_buffer)
2052 g_assert (!channel->write_buf || channel->write_buf->len == 0);
2053 g_assert (channel->partial_write_buf[0] == '\0');
2055 status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
2058 *bytes_written = tmp_bytes;
2065 if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
2066 || (BUF_LEN (channel->encoded_read_buf) > 0)))
2068 if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
2070 g_warning("Mixed reading and writing not allowed on encoded files");
2071 return G_IO_STATUS_ERROR;
2073 status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
2074 if (status != G_IO_STATUS_NORMAL)
2082 if (!channel->write_buf)
2083 channel->write_buf = g_string_sized_new (channel->buf_size);
2085 while (wrote_bytes < count)
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.
2095 if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2097 gsize did_write = 0, this_time;
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;
2106 while (status == G_IO_STATUS_NORMAL &&
2107 did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2109 g_string_erase (channel->write_buf, 0, did_write);
2111 if (status != G_IO_STATUS_NORMAL)
2113 if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2114 status = G_IO_STATUS_NORMAL;
2116 *bytes_written = wrote_bytes;
2121 space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2122 - channel->write_buf->len; /* 1 for NULL */
2124 /* This is only true because g_io_channel_set_buffer_size ()
2125 * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2127 g_assert (space_in_buf >= MAX_CHAR_SIZE);
2129 if (!channel->encoding)
2131 gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2133 g_string_append_len (channel->write_buf, buf, write_this);
2135 wrote_bytes += write_this;
2139 const gchar *from_buf;
2140 gsize from_buf_len, from_buf_old_len, left_len;
2144 if (channel->partial_write_buf[0] != '\0')
2146 g_assert (wrote_bytes == 0);
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);
2153 memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2154 from_buf_len - from_buf_old_len);
2159 from_buf_len = count - wrote_bytes;
2160 from_buf_old_len = 0;
2165 if (!channel->do_encode) /* UTF-8 encoding */
2167 const gchar *badchar;
2168 gsize try_len = MIN (from_buf_len, space_in_buf);
2170 /* UTF-8, just validate, emulate g_iconv */
2172 if (!g_utf8_validate (from_buf, try_len, &badchar))
2175 gsize incomplete_len = from_buf + try_len - badchar;
2177 left_len = from_buf + from_buf_len - badchar;
2179 try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2184 g_assert (incomplete_len < 6);
2185 if (try_len == from_buf_len)
2197 g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2198 /* FIXME bail here? */
2203 g_assert_not_reached ();
2205 errnum = 0; /* Don't confunse the compiler */
2212 left_len = from_buf_len - try_len;
2215 g_string_append_len (channel->write_buf, from_buf,
2216 from_buf_len - left_len);
2217 from_buf += from_buf_len - left_len;
2223 left_len = from_buf_len;
2224 g_string_set_size (channel->write_buf, channel->write_buf->len
2226 outbuf = channel->write_buf->str + channel->write_buf->len
2228 err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2229 &outbuf, &space_in_buf);
2231 g_string_truncate (channel->write_buf, channel->write_buf->len
2235 if (err == (gsize) -1)
2240 g_assert (left_len < 6);
2242 if (from_buf_old_len == 0)
2244 /* Not from partial_write_buf */
2246 memcpy (channel->partial_write_buf, from_buf, left_len);
2247 channel->partial_write_buf[left_len] = '\0';
2249 *bytes_written = count;
2250 return G_IO_STATUS_NORMAL;
2253 /* Working in partial_write_buf */
2255 if (left_len == from_buf_len)
2257 /* Didn't convert anything, must still have
2258 * less than a full character
2261 g_assert (count == from_buf_len - from_buf_old_len);
2263 channel->partial_write_buf[from_buf_len] = '\0';
2266 *bytes_written = count;
2268 return G_IO_STATUS_NORMAL;
2271 g_assert (from_buf_len - left_len >= from_buf_old_len);
2273 /* We converted all the old data. This is fine */
2277 if (from_buf_len == left_len)
2279 /* Nothing was written, add enough space for
2280 * at least one character.
2282 space_in_buf += MAX_CHAR_SIZE;
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");
2294 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2296 *bytes_written = wrote_bytes;
2297 channel->partial_write_buf[0] = '\0';
2298 return G_IO_STATUS_ERROR;
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;
2305 *bytes_written = wrote_bytes;
2306 channel->partial_write_buf[0] = '\0';
2307 return G_IO_STATUS_ERROR;
2311 g_assert (from_buf_len - left_len >= from_buf_old_len);
2313 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2315 if (from_buf_old_len > 0)
2317 /* We were working in partial_write_buf */
2319 buf += from_buf_len - left_len - from_buf_old_len;
2320 channel->partial_write_buf[0] = '\0';
2328 *bytes_written = count;
2330 return G_IO_STATUS_NORMAL;
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
2340 * Writes a Unicode character to @channel.
2341 * This function cannot be called on a channel with %NULL encoding.
2343 * Return value: a #GIOStatus
2346 g_io_channel_write_unichar (GIOChannel *channel,
2351 gchar static_buf[6];
2352 gsize char_len, wrote_len;
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),
2358 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2360 char_len = g_unichar_to_utf8 (thechar, static_buf);
2362 if (channel->partial_write_buf[0] != '\0')
2364 g_warning ("Partial charater written before writing unichar.\n");
2365 channel->partial_write_buf[0] = '\0';
2368 status = g_io_channel_write_chars (channel, static_buf,
2369 char_len, &wrote_len, error);
2371 /* We validate UTF-8, so we can't get a partial write */
2373 g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2379 * g_io_channel_error_quark:
2381 * Return value: the quark used as %G_IO_CHANNEL_ERROR
2384 g_io_channel_error_quark (void)
2386 return g_quark_from_static_string ("g-io-channel-error-quark");
2389 #define __G_IOCHANNEL_C__
2390 #include "galiasdef.c"