Put the g_return_val_if_fail() in the right place.
[glib.git] / glib / giochannel.c
bloba7c2f41870e0c7a34e49ce91e0e30676e5c83a2d
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/.
30 /*
31 * MT safe
34 #include "config.h"
36 #include <string.h>
37 #include <errno.h>
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
43 #undef G_DISABLE_DEPRECATED
45 #include "glib.h"
47 #include "giochannel.h"
49 #include "glibintl.h"
51 #define G_IO_NICE_BUF_SIZE 1024
53 /* This needs to be as wide as the largest character in any possible encoding */
54 #define MAX_CHAR_SIZE 10
56 /* Some simplifying macros, which reduce the need to worry whether the
57 * buffers have been allocated. These also make USE_BUF () an lvalue,
58 * which is used in g_io_channel_read_to_end ().
60 #define USE_BUF(channel) ((channel)->encoding ? (channel)->encoded_read_buf \
61 : (channel)->read_buf)
62 #define BUF_LEN(string) ((string) ? (string)->len : 0)
64 static GIOError g_io_error_get_from_g_error (GIOStatus status,
65 GError *err);
66 static void g_io_channel_purge (GIOChannel *channel);
67 static GIOStatus g_io_channel_fill_buffer (GIOChannel *channel,
68 GError **err);
69 static GIOStatus g_io_channel_read_line_backend (GIOChannel *channel,
70 gsize *length,
71 gsize *terminator_pos,
72 GError **error);
74 void
75 g_io_channel_init (GIOChannel *channel)
77 channel->ref_count = 1;
78 channel->encoding = g_strdup ("UTF-8");
79 channel->line_term = NULL;
80 channel->line_term_len = 0;
81 channel->buf_size = G_IO_NICE_BUF_SIZE;
82 channel->read_cd = (GIConv) -1;
83 channel->write_cd = (GIConv) -1;
84 channel->read_buf = NULL; /* Lazy allocate buffers */
85 channel->encoded_read_buf = NULL;
86 channel->write_buf = NULL;
87 channel->partial_write_buf[0] = '\0';
88 channel->use_buffer = TRUE;
89 channel->do_encode = FALSE;
90 channel->close_on_unref = FALSE;
93 void
94 g_io_channel_ref (GIOChannel *channel)
96 g_return_if_fail (channel != NULL);
98 channel->ref_count++;
101 void
102 g_io_channel_unref (GIOChannel *channel)
104 g_return_if_fail (channel != NULL);
106 channel->ref_count--;
107 if (channel->ref_count == 0)
109 if (channel->close_on_unref)
110 g_io_channel_shutdown (channel, TRUE, NULL);
111 else
112 g_io_channel_purge (channel);
113 g_free (channel->encoding);
114 if (channel->read_cd != (GIConv) -1)
115 g_iconv_close (channel->read_cd);
116 if (channel->write_cd != (GIConv) -1)
117 g_iconv_close (channel->write_cd);
118 if (channel->line_term)
119 g_free (channel->line_term);
120 if (channel->read_buf)
121 g_string_free (channel->read_buf, TRUE);
122 if (channel->write_buf)
123 g_string_free (channel->write_buf, TRUE);
124 if (channel->encoded_read_buf)
125 g_string_free (channel->encoded_read_buf, TRUE);
126 channel->funcs->io_free (channel);
130 static GIOError
131 g_io_error_get_from_g_error (GIOStatus status,
132 GError *err)
134 switch (status)
136 case G_IO_STATUS_NORMAL:
137 case G_IO_STATUS_EOF:
138 return G_IO_ERROR_NONE;
139 case G_IO_STATUS_AGAIN:
140 return G_IO_ERROR_AGAIN;
141 case G_IO_STATUS_ERROR:
142 g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
144 if (err->domain != G_IO_CHANNEL_ERROR)
145 return G_IO_ERROR_UNKNOWN;
146 switch (err->code)
148 case G_IO_CHANNEL_ERROR_INVAL:
149 return G_IO_ERROR_INVAL;
150 default:
151 return G_IO_ERROR_UNKNOWN;
153 default:
154 g_assert_not_reached ();
155 return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
160 * g_io_channel_read:
161 * @channel: a #GIOChannel.
162 * @buf: a buffer to read the data into (which should be at least count bytes long).
163 * @count: the number of bytes to read from the #GIOChannel.
164 * @bytes_read: returns the number of bytes actually read.
166 * Reads data from a #GIOChannel.
168 * Return value: %G_IO_ERROR_NONE if the operation was successful.
170 * Deprecated: Use g_io_channel_read_chars() instead.
172 GIOError
173 g_io_channel_read (GIOChannel *channel,
174 gchar *buf,
175 gsize count,
176 gsize *bytes_read)
178 GError *err = NULL;
179 GIOError error;
180 GIOStatus status;
182 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
183 g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
185 status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
187 error = g_io_error_get_from_g_error (status, err);
189 if (err)
190 g_error_free (err);
192 return error;
196 * g_io_channel_write:
197 * @channel: a #GIOChannel.
198 * @buf: the buffer containing the data to write.
199 * @count: the number of bytes to write.
200 * @bytes_written: the number of bytes actually written.
202 * Writes data to a #GIOChannel.
204 * Return value: %G_IO_ERROR_NONE if the operation was successful.
206 * Deprecated: Use g_io_channel_write_chars() instead.
208 GIOError
209 g_io_channel_write (GIOChannel *channel,
210 const gchar *buf,
211 gsize count,
212 gsize *bytes_written)
214 GError *err = NULL;
215 GIOError error;
216 GIOStatus status;
218 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
219 g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
221 status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
223 error = g_io_error_get_from_g_error (status, err);
225 if (err)
226 g_error_free (err);
228 return error;
232 * g_io_channel_seek:
233 * @channel: a #GIOChannel.
234 * @offset: an offset, in bytes, which is added to the position specified by @type
235 * @type: the position in the file, which can be %G_SEEK_CUR (the current
236 * position), %G_SEEK_SET (the start of the file), or %G_SEEK_END (the end of the
237 * file).
239 * Sets the current position in the #GIOChannel, similar to the standard library
240 * function <function>fseek()</function>.
242 * Return value: %G_IO_ERROR_NONE if the operation was successful.
244 * Deprecated: Use g_io_channel_seek_position() instead.
246 GIOError
247 g_io_channel_seek (GIOChannel *channel,
248 gint64 offset,
249 GSeekType type)
251 GError *err = NULL;
252 GIOError error;
253 GIOStatus status;
255 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
256 g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
258 switch (type)
260 case G_SEEK_CUR:
261 case G_SEEK_SET:
262 case G_SEEK_END:
263 break;
264 default:
265 g_warning ("g_io_channel_seek: unknown seek type");
266 return G_IO_ERROR_UNKNOWN;
269 status = channel->funcs->io_seek (channel, offset, type, &err);
271 error = g_io_error_get_from_g_error (status, err);
273 if (err)
274 g_error_free (err);
276 return error;
279 /* The function g_io_channel_new_file() is prototyped in both
280 * giounix.c and giowin32.c, so we stick its documentation here.
284 * g_io_channel_new_file:
285 * @filename: A string containing the name of a file.
286 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
287 * the same meaning as in <function>fopen()</function>.
288 * @error: A location to return an error of type %G_FILE_ERROR.
290 * Open a file @filename as a #GIOChannel using mode @mode. This
291 * channel will be closed when the last reference to it is dropped,
292 * so there is no need to call g_io_channel_close() (though doing
293 * so will not cause problems, as long as no attempt is made to
294 * access the channel after it is closed).
296 * Return value: A #GIOChannel on success, %NULL on failure.
300 * g_io_channel_close:
301 * @channel: A #GIOChannel
303 * Close an IO channel. Any pending data to be written will be
304 * flushed, ignoring errors. The channel will not be freed until the
305 * last reference is dropped using g_io_channel_unref().
307 * Deprecated: Use g_io_channel_shutdown() instead.
309 void
310 g_io_channel_close (GIOChannel *channel)
312 GError *err = NULL;
314 g_return_if_fail (channel != NULL);
316 g_io_channel_purge (channel);
318 channel->funcs->io_close (channel, &err);
320 if (err)
321 { /* No way to return the error */
322 g_warning ("Error closing channel: %s", err->message);
323 g_error_free (err);
326 channel->close_on_unref = FALSE; /* Because we already did */
327 channel->is_readable = FALSE;
328 channel->is_writeable = FALSE;
329 channel->is_seekable = FALSE;
333 * g_io_channel_shutdown:
334 * @channel: a #GIOChannel
335 * @flush: if %TRUE, flush pending
336 * @err: location to store a #GIOChannelError
338 * Close an IO channel. Any pending data to be written will be
339 * flushed if @flush is %TRUE. The channel will not be freed until the
340 * last reference is dropped using g_io_channel_unref().
342 * Return value: the status of the operation.
344 GIOStatus
345 g_io_channel_shutdown (GIOChannel *channel,
346 gboolean flush,
347 GError **err)
349 GIOStatus status, result;
350 GError *tmperr = NULL;
352 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
353 g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
355 if (channel->write_buf && channel->write_buf->len > 0)
357 if (flush)
359 GIOFlags flags;
361 /* Set the channel to blocking, to avoid a busy loop
363 flags = g_io_channel_get_flags (channel);
364 /* Ignore any errors here, they're irrelevant */
365 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
367 result = g_io_channel_flush (channel, &tmperr);
369 else
370 result = G_IO_STATUS_NORMAL;
372 g_string_truncate(channel->write_buf, 0);
374 else
375 result = G_IO_STATUS_NORMAL;
377 if (channel->partial_write_buf[0] != '\0')
379 if (flush)
380 g_warning ("Partial character at end of write buffer not flushed.\n");
381 channel->partial_write_buf[0] = '\0';
384 status = channel->funcs->io_close (channel, err);
386 channel->close_on_unref = FALSE; /* Because we already did */
387 channel->is_readable = FALSE;
388 channel->is_writeable = FALSE;
389 channel->is_seekable = FALSE;
391 if (status != G_IO_STATUS_NORMAL)
393 g_clear_error (&tmperr);
394 return status;
396 else if (result != G_IO_STATUS_NORMAL)
398 g_propagate_error (err, tmperr);
399 return result;
401 else
402 return G_IO_STATUS_NORMAL;
405 /* This function is used for the final flush on close or unref */
406 static void
407 g_io_channel_purge (GIOChannel *channel)
409 GError *err = NULL;
410 GIOStatus status;
412 g_return_if_fail (channel != NULL);
414 if (channel->write_buf && channel->write_buf->len > 0)
416 GIOFlags flags;
418 /* Set the channel to blocking, to avoid a busy loop
420 flags = g_io_channel_get_flags (channel);
421 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
423 status = g_io_channel_flush (channel, &err);
425 if (err)
426 { /* No way to return the error */
427 g_warning ("Error flushing string: %s", err->message);
428 g_error_free (err);
432 /* Flush these in case anyone tries to close without unrefing */
434 if (channel->read_buf)
435 g_string_truncate (channel->read_buf, 0);
436 if (channel->write_buf)
437 g_string_truncate (channel->write_buf, 0);
438 if (channel->encoding)
440 if (channel->encoded_read_buf)
441 g_string_truncate (channel->encoded_read_buf, 0);
443 if (channel->partial_write_buf[0] != '\0')
445 g_warning ("Partial character at end of write buffer not flushed.\n");
446 channel->partial_write_buf[0] = '\0';
451 GSource *
452 g_io_create_watch (GIOChannel *channel,
453 GIOCondition condition)
455 g_return_val_if_fail (channel != NULL, NULL);
457 return channel->funcs->io_create_watch (channel, condition);
460 guint
461 g_io_add_watch_full (GIOChannel *channel,
462 gint priority,
463 GIOCondition condition,
464 GIOFunc func,
465 gpointer user_data,
466 GDestroyNotify notify)
468 GSource *source;
469 guint id;
471 g_return_val_if_fail (channel != NULL, 0);
473 source = g_io_create_watch (channel, condition);
475 if (priority != G_PRIORITY_DEFAULT)
476 g_source_set_priority (source, priority);
477 g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
479 id = g_source_attach (source, NULL);
480 g_source_unref (source);
482 return id;
485 guint
486 g_io_add_watch (GIOChannel *channel,
487 GIOCondition condition,
488 GIOFunc func,
489 gpointer user_data)
491 return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
495 * g_io_channel_get_buffer_condition:
496 * @channel: A #GIOChannel
498 * This function returns a #GIOCondition depending on whether there
499 * is data to be read/space to write data in the
500 * internal buffers in the #GIOChannel. Only the flags %G_IO_IN and
501 * %G_IO_OUT may be set.
503 * Return value: A #GIOCondition
505 GIOCondition
506 g_io_channel_get_buffer_condition (GIOChannel *channel)
508 GIOCondition condition = 0;
510 if (channel->encoding)
512 if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
513 condition |= G_IO_IN; /* Only return if we have full characters */
515 else
517 if (channel->read_buf && (channel->read_buf->len > 0))
518 condition |= G_IO_IN;
521 if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
522 condition |= G_IO_OUT;
524 return condition;
528 * g_io_channel_error_from_errno:
529 * @en: an <literal>errno</literal> error number, e.g. %EINVAL.
531 * Converts an <literal>errno</literal> error number to a #GIOChannelError.
533 * Return value: a #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL.
535 GIOChannelError
536 g_io_channel_error_from_errno (gint en)
538 #ifdef EAGAIN
539 g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
540 #endif
542 switch (en)
544 #ifdef EBADF
545 case EBADF:
546 g_warning("Invalid file descriptor.\n");
547 return G_IO_CHANNEL_ERROR_FAILED;
548 #endif
550 #ifdef EFAULT
551 case EFAULT:
552 g_warning("File descriptor outside valid address space.\n");
553 return G_IO_CHANNEL_ERROR_FAILED;
554 #endif
556 #ifdef EFBIG
557 case EFBIG:
558 return G_IO_CHANNEL_ERROR_FBIG;
559 #endif
561 #ifdef EINTR
562 /* In general, we should catch EINTR before we get here,
563 * but close() is allowed to return EINTR by POSIX, so
564 * we need to catch it here; EINTR from close() is
565 * unrecoverable, because it's undefined whether
566 * the fd was actually closed or not, so we just return
567 * a generic error code.
569 case EINTR:
570 return G_IO_CHANNEL_ERROR_FAILED;
571 #endif
573 #ifdef EINVAL
574 case EINVAL:
575 return G_IO_CHANNEL_ERROR_INVAL;
576 #endif
578 #ifdef EIO
579 case EIO:
580 return G_IO_CHANNEL_ERROR_IO;
581 #endif
583 #ifdef EISDIR
584 case EISDIR:
585 return G_IO_CHANNEL_ERROR_ISDIR;
586 #endif
588 #ifdef ENOSPC
589 case ENOSPC:
590 return G_IO_CHANNEL_ERROR_NOSPC;
591 #endif
593 #ifdef ENXIO
594 case ENXIO:
595 return G_IO_CHANNEL_ERROR_NXIO;
596 #endif
598 #ifdef EOVERFLOW
599 case EOVERFLOW:
600 return G_IO_CHANNEL_ERROR_OVERFLOW;
601 #endif
603 #ifdef EPIPE
604 case EPIPE:
605 return G_IO_CHANNEL_ERROR_PIPE;
606 #endif
608 default:
609 return G_IO_CHANNEL_ERROR_FAILED;
614 * g_io_channel_set_buffer_size:
615 * @channel: a #GIOChannel
616 * @size: the size of the buffer. 0 == pick a good size
618 * Sets the buffer size.
619 **/
620 void
621 g_io_channel_set_buffer_size (GIOChannel *channel,
622 gsize size)
624 g_return_if_fail (channel != NULL);
626 if (size == 0)
627 size = G_IO_NICE_BUF_SIZE;
629 if (size < MAX_CHAR_SIZE)
630 size = MAX_CHAR_SIZE;
632 channel->buf_size = size;
636 * g_io_channel_get_buffer_size:
637 * @channel: a #GIOChannel
639 * Gets the buffer size.
641 * Return value: the size of the buffer.
642 **/
643 gsize
644 g_io_channel_get_buffer_size (GIOChannel *channel)
646 g_return_val_if_fail (channel != NULL, 0);
648 return channel->buf_size;
652 * g_io_channel_set_line_term:
653 * @channel: a #GIOChannel
654 * @line_term: The line termination string. Use %NULL for auto detect.
655 * Auto detection breaks on "\n", "\r\n", "\r", "\0", and
656 * the Unicode paragraph separator. Auto detection should
657 * not be used for anything other than file-based channels.
658 * @length: The length of the termination string. If -1 is passed, the
659 * string is assumed to be nul-terminated. This option allows
660 * termination strings with embeded nuls.
662 * This sets the string that #GIOChannel uses to determine
663 * where in the file a line break occurs.
665 void
666 g_io_channel_set_line_term (GIOChannel *channel,
667 const gchar *line_term,
668 gint length)
670 g_return_if_fail (channel != NULL);
671 g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
673 if (line_term == NULL)
674 length = 0;
675 else if (length < 0)
676 length = strlen (line_term);
678 if (channel->line_term)
679 g_free (channel->line_term);
680 channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
681 channel->line_term_len = length;
685 * g_io_channel_get_line_term:
686 * @channel: a #GIOChannel
687 * @length: a location to return the length of the line terminator
689 * This returns the string that #GIOChannel uses to determine
690 * where in the file a line break occurs. A value of %NULL
691 * indicates auto detection.
693 * Return value: The line termination string. This value
694 * is owned by GLib and must not be freed.
696 G_CONST_RETURN gchar*
697 g_io_channel_get_line_term (GIOChannel *channel,
698 gint *length)
700 g_return_val_if_fail (channel != NULL, 0);
702 if (length)
703 *length = channel->line_term_len;
705 return channel->line_term;
709 * g_io_channel_set_flags:
710 * @channel: a #GIOChannel.
711 * @flags: the flags to set on the IO channel.
712 * @error: A location to return an error of type #GIOChannelError.
714 * Sets the (writeable) flags in @channel to (@flags & %G_IO_CHANNEL_SET_MASK).
716 * Return value: the status of the operation.
718 GIOStatus
719 g_io_channel_set_flags (GIOChannel *channel,
720 GIOFlags flags,
721 GError **error)
723 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
724 g_return_val_if_fail ((error == NULL) || (*error == NULL),
725 G_IO_STATUS_ERROR);
727 return (* channel->funcs->io_set_flags)(channel,
728 flags & G_IO_FLAG_SET_MASK,
729 error);
733 * g_io_channel_get_flags:
734 * @channel: a #GIOChannel
736 * Gets the current flags for a #GIOChannel, including read-only
737 * flags such as %G_IO_FLAG_IS_READABLE.
739 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITEABLE
740 * are cached for internal use by the channel when it is created.
741 * If they should change at some later point (e.g. partial shutdown
742 * of a socket with the UNIX <function>shutdown()</function> function), the user
743 * should immediately call g_io_channel_get_flags () to update
744 * the internal values of these flags.
746 * Return value: the flags which are set on the channel
748 GIOFlags
749 g_io_channel_get_flags (GIOChannel *channel)
751 GIOFlags flags;
753 g_return_val_if_fail (channel != NULL, 0);
755 flags = (* channel->funcs->io_get_flags) (channel);
757 /* Cross implementation code */
759 if (channel->is_seekable)
760 flags |= G_IO_FLAG_IS_SEEKABLE;
761 if (channel->is_readable)
762 flags |= G_IO_FLAG_IS_READABLE;
763 if (channel->is_writeable)
764 flags |= G_IO_FLAG_IS_WRITEABLE;
766 return flags;
770 * g_io_channel_set_close_on_unref:
771 * @channel: a #GIOChannel
772 * @do_close: Whether to close the channel on the final unref of
773 * the GIOChannel data structure. The default value of
774 * this is %TRUE for channels created by g_io_channel_new_file (),
775 * and %FALSE for all other channels.
777 * Setting this flag to %TRUE for a channel you have already closed
778 * can cause problems.
780 void
781 g_io_channel_set_close_on_unref (GIOChannel *channel,
782 gboolean do_close)
784 g_return_if_fail (channel != NULL);
786 channel->close_on_unref = do_close;
790 * g_io_channel_get_close_on_unref:
791 * @channel: a #GIOChannel.
793 * Returns whether the file/socket/whatever associated with @channel
794 * will be closed when @channel receives its final unref and is
795 * destroyed. The default value of this is %TRUE for channels created
796 * by g_io_channel_new_file (), and %FALSE for all other channels.
798 * Return value: Whether the channel will be closed on the final unref of
799 * the GIOChannel data structure.
801 gboolean
802 g_io_channel_get_close_on_unref (GIOChannel *channel)
804 g_return_val_if_fail (channel != NULL, FALSE);
806 return channel->close_on_unref;
810 * g_io_channel_seek_position:
811 * @channel: a #GIOChannel
812 * @offset: The offset in bytes from the position specified by @type
813 * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
814 * cases where a call to g_io_channel_set_encoding ()
815 * is allowed. See the documentation for
816 * g_io_channel_set_encoding () for details.
817 * @error: A location to return an error of type #GIOChannelError
819 * Replacement for g_io_channel_seek() with the new API.
821 * Return value: the status of the operation.
823 GIOStatus
824 g_io_channel_seek_position (GIOChannel* channel,
825 gint64 offset,
826 GSeekType type,
827 GError **error)
829 GIOStatus status;
831 /* For files, only one of the read and write buffers can contain data.
832 * For sockets, both can contain data.
835 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
836 g_return_val_if_fail ((error == NULL) || (*error == NULL),
837 G_IO_STATUS_ERROR);
838 g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
840 switch (type)
842 case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
843 if (channel->use_buffer)
845 if (channel->do_encode && channel->encoded_read_buf
846 && channel->encoded_read_buf->len > 0)
848 g_warning ("Seek type G_SEEK_CUR not allowed for this"
849 " channel's encoding.\n");
850 return G_IO_STATUS_ERROR;
852 if (channel->read_buf)
853 offset -= channel->read_buf->len;
854 if (channel->encoded_read_buf)
856 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
858 /* If there's anything here, it's because the encoding is UTF-8,
859 * so we can just subtract the buffer length, the same as for
860 * the unencoded data.
863 offset -= channel->encoded_read_buf->len;
866 break;
867 case G_SEEK_SET:
868 case G_SEEK_END:
869 break;
870 default:
871 g_warning ("g_io_channel_seek_position: unknown seek type");
872 return G_IO_STATUS_ERROR;
875 if (channel->use_buffer)
877 status = g_io_channel_flush (channel, error);
878 if (status != G_IO_STATUS_NORMAL)
879 return status;
882 status = channel->funcs->io_seek (channel, offset, type, error);
884 if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
886 if (channel->read_buf)
887 g_string_truncate (channel->read_buf, 0);
889 /* Conversion state no longer matches position in file */
890 if (channel->read_cd != (GIConv) -1)
891 g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
892 if (channel->write_cd != (GIConv) -1)
893 g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
895 if (channel->encoded_read_buf)
897 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
898 g_string_truncate (channel->encoded_read_buf, 0);
901 if (channel->partial_write_buf[0] != '\0')
903 g_warning ("Partial character at end of write buffer not flushed.\n");
904 channel->partial_write_buf[0] = '\0';
908 return status;
912 * g_io_channel_flush:
913 * @channel: a #GIOChannel
914 * @error: location to store an error of type #GIOChannelError
916 * Flushes the write buffer for the GIOChannel.
918 * Return value: the status of the operation: One of
919 * #G_IO_CHANNEL_NORMAL, #G_IO_CHANNEL_AGAIN, or
920 * #G_IO_CHANNEL_ERROR.
922 GIOStatus
923 g_io_channel_flush (GIOChannel *channel,
924 GError **error)
926 GIOStatus status;
927 gsize this_time = 1, bytes_written = 0;
929 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
930 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
932 if (channel->write_buf == NULL || channel->write_buf->len == 0)
933 return G_IO_STATUS_NORMAL;
937 g_assert (this_time > 0);
939 status = channel->funcs->io_write (channel,
940 channel->write_buf->str + bytes_written,
941 channel->write_buf->len - bytes_written,
942 &this_time, error);
943 bytes_written += this_time;
945 while ((bytes_written < channel->write_buf->len)
946 && (status == G_IO_STATUS_NORMAL));
948 g_string_erase (channel->write_buf, 0, bytes_written);
950 return status;
954 * g_io_channel_set_buffered:
955 * @channel: a #GIOChannel
956 * @buffered: whether to set the channel buffered or unbuffered
958 * The buffering state can only be set if the channel's encoding
959 * is %NULL. For any other encoding, the channel must be buffered.
961 * A buffered channel can only be set unbuffered if the channel's
962 * internal buffers have been flushed. Newly created channels or
963 * channels which have returned %G_IO_STATUS_EOF
964 * not require such a flush. For write-only channels, a call to
965 * g_io_channel_flush () is sufficient. For all other channels,
966 * the buffers may be flushed by a call to g_io_channel_seek_position ().
967 * This includes the possibility of seeking with seek type %G_SEEK_CUR
968 * and an offset of zero. Note that this means that socket-based
969 * channels cannot be set unbuffered once they have had data
970 * read from them.
972 * On unbuffered channels, it is safe to mix read and write
973 * calls from the new and old APIs, if this is necessary for
974 * maintaining old code.
976 * The default state of the channel is buffered.
978 void
979 g_io_channel_set_buffered (GIOChannel *channel,
980 gboolean buffered)
982 g_return_if_fail (channel != NULL);
984 if (channel->encoding != NULL)
986 g_warning ("Need to have NULL encoding to set the buffering state of the "
987 "channel.\n");
988 return;
991 g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
992 g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
994 channel->use_buffer = buffered;
998 * g_io_channel_get_buffered:
999 * @channel: a #GIOChannel.
1001 * Returns whether @channel is buffered.
1003 * Return Value: %TRUE if the @channel is buffered.
1005 gboolean
1006 g_io_channel_get_buffered (GIOChannel *channel)
1008 g_return_val_if_fail (channel != NULL, FALSE);
1010 return channel->use_buffer;
1014 * g_io_channel_set_encoding:
1015 * @channel: a #GIOChannel
1016 * @encoding: the encoding type
1017 * @error: location to store an error of type #GConvertError.
1019 * Sets the encoding for the input/output of the channel. The internal
1020 * encoding is always UTF-8. The default encoding for the
1021 * external file is UTF-8.
1023 * The encoding %NULL is safe to use with binary data.
1025 * The encoding can only be set if one of the following conditions
1026 * is true:
1028 * 1. The channel was just created, and has not been written to
1029 * or read from yet.
1031 * 2. The channel is write-only.
1033 * 3. The channel is a file, and the file pointer was just
1034 * repositioned by a call to g_io_channel_seek_position().
1035 * (This flushes all the internal buffers.)
1037 * 4. The current encoding is %NULL or UTF-8.
1039 * 5. One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1040 * (or, in the case of g_io_channel_read_to_end (), %G_IO_STATUS_NORMAL).
1042 * 6. One of the functions g_io_channel_read_chars () or g_io_channel_read_unichar ()
1043 * has returned %G_IO_STATUS_AGAIN or %G_IO_STATUS_ERROR. This may be
1044 * useful in the case of %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1045 * Returning one of these statuses from g_io_channel_read_line (),
1046 * g_io_channel_read_line_string (), or g_io_channel_read_to_end ()
1047 * does <emphasis>not</emphasis> guarantee that the encoding can be changed.
1049 * Channels which do not meet one of the above conditions cannot call
1050 * g_io_channel_seek_position () with an offset of %G_SEEK_CUR,
1051 * and, if they are "seekable", cannot
1052 * call g_io_channel_write_chars () after calling one
1053 * of the API "read" functions.
1055 * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1057 GIOStatus
1058 g_io_channel_set_encoding (GIOChannel *channel,
1059 const gchar *encoding,
1060 GError **error)
1062 GIConv read_cd, write_cd;
1063 gboolean did_encode;
1065 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1066 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1068 /* Make sure the encoded buffers are empty */
1070 g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1071 channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1073 if (!channel->use_buffer)
1075 g_warning ("Need to set the channel buffered before setting the encoding.\n");
1076 g_warning ("Assuming this is what you meant and acting accordingly.\n");
1078 channel->use_buffer = TRUE;
1081 if (channel->partial_write_buf[0] != '\0')
1083 g_warning ("Partial character at end of write buffer not flushed.\n");
1084 channel->partial_write_buf[0] = '\0';
1087 did_encode = channel->do_encode;
1089 if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1091 channel->do_encode = FALSE;
1092 read_cd = write_cd = (GIConv) -1;
1094 else
1096 gint err = 0;
1097 const gchar *from_enc = NULL, *to_enc = NULL;
1099 if (channel->is_readable)
1101 read_cd = g_iconv_open ("UTF-8", encoding);
1103 if (read_cd == (GIConv) -1)
1105 err = errno;
1106 from_enc = "UTF-8";
1107 to_enc = encoding;
1110 else
1111 read_cd = (GIConv) -1;
1113 if (channel->is_writeable && err == 0)
1115 write_cd = g_iconv_open (encoding, "UTF-8");
1117 if (write_cd == (GIConv) -1)
1119 err = errno;
1120 from_enc = encoding;
1121 to_enc = "UTF-8";
1124 else
1125 write_cd = (GIConv) -1;
1127 if (err != 0)
1129 g_assert (from_enc);
1130 g_assert (to_enc);
1132 if (err == EINVAL)
1133 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1134 _("Conversion from character set `%s' to `%s' is not supported"),
1135 from_enc, to_enc);
1136 else
1137 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1138 _("Could not open converter from `%s' to `%s': %s"),
1139 from_enc, to_enc, g_strerror (err));
1141 if (read_cd != (GIConv) -1)
1142 g_iconv_close (read_cd);
1143 if (write_cd != (GIConv) -1)
1144 g_iconv_close (write_cd);
1146 return G_IO_STATUS_ERROR;
1149 channel->do_encode = TRUE;
1152 /* The encoding is ok, so set the fields in channel */
1154 if (channel->read_cd != (GIConv) -1)
1155 g_iconv_close (channel->read_cd);
1156 if (channel->write_cd != (GIConv) -1)
1157 g_iconv_close (channel->write_cd);
1159 if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1161 g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1163 /* This is just validated UTF-8, so we can copy it back into read_buf
1164 * so it can be encoded in whatever the new encoding is.
1167 g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1168 channel->encoded_read_buf->len);
1169 g_string_truncate (channel->encoded_read_buf, 0);
1172 channel->read_cd = read_cd;
1173 channel->write_cd = write_cd;
1175 g_free (channel->encoding);
1176 channel->encoding = g_strdup (encoding);
1178 return G_IO_STATUS_NORMAL;
1182 * g_io_channel_get_encoding:
1183 * @channel: a #GIOChannel
1185 * Gets the encoding for the input/output of the channel. The internal
1186 * encoding is always UTF-8. The encoding %NULL makes the
1187 * channel safe for binary data.
1189 * Return value: A string containing the encoding, this string is
1190 * owned by GLib and must not be freed.
1192 G_CONST_RETURN gchar*
1193 g_io_channel_get_encoding (GIOChannel *channel)
1195 g_return_val_if_fail (channel != NULL, NULL);
1197 return channel->encoding;
1200 static GIOStatus
1201 g_io_channel_fill_buffer (GIOChannel *channel,
1202 GError **err)
1204 gsize read_size, cur_len, oldlen;
1205 GIOStatus status;
1207 if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1209 status = g_io_channel_flush (channel, err);
1210 if (status != G_IO_STATUS_NORMAL)
1211 return status;
1213 if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1215 g_warning ("Partial character at end of write buffer not flushed.\n");
1216 channel->partial_write_buf[0] = '\0';
1219 if (!channel->read_buf)
1220 channel->read_buf = g_string_sized_new (channel->buf_size);
1222 cur_len = channel->read_buf->len;
1224 g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1226 status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1227 channel->buf_size, &read_size, err);
1229 g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1231 g_string_truncate (channel->read_buf, read_size + cur_len);
1233 if ((status != G_IO_STATUS_NORMAL)
1234 && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1235 return status;
1237 g_assert (channel->read_buf->len > 0);
1239 if (channel->encoded_read_buf)
1240 oldlen = channel->encoded_read_buf->len;
1241 else
1243 oldlen = 0;
1244 if (channel->encoding)
1245 channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1248 if (channel->do_encode)
1250 size_t errnum, inbytes_left, outbytes_left;
1251 gchar *inbuf, *outbuf;
1252 int errval;
1254 g_assert (channel->encoded_read_buf);
1256 reencode:
1258 inbytes_left = channel->read_buf->len;
1259 outbytes_left = MAX (channel->read_buf->len,
1260 channel->encoded_read_buf->allocated_len
1261 - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1262 outbytes_left = MAX (outbytes_left, 6);
1264 inbuf = channel->read_buf->str;
1265 g_string_set_size (channel->encoded_read_buf,
1266 channel->encoded_read_buf->len + outbytes_left);
1267 outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1268 - outbytes_left;
1270 errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1271 &outbuf, &outbytes_left);
1272 errval = errno;
1274 g_assert (inbuf + inbytes_left == channel->read_buf->str
1275 + channel->read_buf->len);
1276 g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1277 + channel->encoded_read_buf->len);
1279 g_string_erase (channel->read_buf, 0,
1280 channel->read_buf->len - inbytes_left);
1281 g_string_truncate (channel->encoded_read_buf,
1282 channel->encoded_read_buf->len - outbytes_left);
1284 if (errnum == (size_t) -1)
1286 switch (errval)
1288 case EINVAL:
1289 if ((oldlen == channel->encoded_read_buf->len)
1290 && (status == G_IO_STATUS_EOF))
1291 status = G_IO_STATUS_EOF;
1292 else
1293 status = G_IO_STATUS_NORMAL;
1294 break;
1295 case E2BIG:
1296 /* Buffer size at least 6, wrote at least on character */
1297 g_assert (inbuf != channel->read_buf->str);
1298 goto reencode;
1299 case EILSEQ:
1300 if (oldlen < channel->encoded_read_buf->len)
1301 status = G_IO_STATUS_NORMAL;
1302 else
1304 g_set_error (err, G_CONVERT_ERROR,
1305 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1306 _("Invalid byte sequence in conversion input"));
1307 return G_IO_STATUS_ERROR;
1309 break;
1310 default:
1311 g_assert (errval != EBADF); /* The converter should be open */
1312 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1313 _("Error during conversion: %s"), g_strerror (errval));
1314 return G_IO_STATUS_ERROR;
1317 g_assert ((status != G_IO_STATUS_NORMAL)
1318 || (channel->encoded_read_buf->len > 0));
1320 else if (channel->encoding) /* UTF-8 */
1322 gchar *nextchar, *lastchar;
1324 g_assert (channel->encoded_read_buf);
1326 nextchar = channel->read_buf->str;
1327 lastchar = channel->read_buf->str + channel->read_buf->len;
1329 while (nextchar < lastchar)
1331 gunichar val_char;
1333 val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1335 switch (val_char)
1337 case -2:
1338 /* stop, leave partial character in buffer */
1339 lastchar = nextchar;
1340 break;
1341 case -1:
1342 if (oldlen < channel->encoded_read_buf->len)
1343 status = G_IO_STATUS_NORMAL;
1344 else
1346 g_set_error (err, G_CONVERT_ERROR,
1347 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1348 _("Invalid byte sequence in conversion input"));
1349 status = G_IO_STATUS_ERROR;
1351 lastchar = nextchar;
1352 break;
1353 default:
1354 nextchar = g_utf8_next_char (nextchar);
1355 break;
1359 if (lastchar > channel->read_buf->str)
1361 gint copy_len = lastchar - channel->read_buf->str;
1363 g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1364 copy_len);
1365 g_string_erase (channel->read_buf, 0, copy_len);
1369 return status;
1373 * g_io_channel_read_line:
1374 * @channel: a #GIOChannel
1375 * @str_return: The line read from the #GIOChannel, including the
1376 * line terminator. This data should be freed with g_free()
1377 * when no longer needed. This is a nul-terminated string.
1378 * If a @length of zero is returned, this will be %NULL instead.
1379 * @length: location to store length of the read data, or %NULL
1380 * @terminator_pos: location to store position of line terminator, or %NULL
1381 * @error: A location to return an error of type #GConvertError
1382 * or #GIOChannelError
1384 * Reads a line, including the terminating character(s),
1385 * from a #GIOChannel into a newly-allocated string.
1386 * @str_return will contain allocated memory if the return
1387 * is %G_IO_STATUS_NORMAL.
1389 * Return value: the status of the operation.
1391 GIOStatus
1392 g_io_channel_read_line (GIOChannel *channel,
1393 gchar **str_return,
1394 gsize *length,
1395 gsize *terminator_pos,
1396 GError **error)
1398 GIOStatus status;
1399 gsize got_length;
1401 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1402 g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1403 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1404 G_IO_STATUS_ERROR);
1405 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1407 status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1409 if (length)
1410 *length = got_length;
1412 if (status == G_IO_STATUS_NORMAL)
1414 g_assert (USE_BUF (channel));
1415 *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1416 g_string_erase (USE_BUF (channel), 0, got_length);
1418 else
1419 *str_return = NULL;
1421 return status;
1425 * g_io_channel_read_line_string:
1426 * @channel: a #GIOChannel
1427 * @buffer: a #GString into which the line will be written.
1428 * If @buffer already contains data, the old data will
1429 * be overwritten.
1430 * @terminator_pos: location to store position of line terminator, or %NULL
1431 * @error: a location to store an error of type #GConvertError
1432 * or #GIOChannelError
1434 * Reads a line from a #GIOChannel, using a #GString as a buffer.
1436 * Return value: the status of the operation.
1438 GIOStatus
1439 g_io_channel_read_line_string (GIOChannel *channel,
1440 GString *buffer,
1441 gsize *terminator_pos,
1442 GError **error)
1444 gsize length;
1445 GIOStatus status;
1447 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1448 g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1449 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1450 G_IO_STATUS_ERROR);
1451 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1453 if (buffer->len > 0)
1454 g_string_truncate (buffer, 0); /* clear out the buffer */
1456 status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1458 if (status == G_IO_STATUS_NORMAL)
1460 g_assert (USE_BUF (channel));
1461 g_string_append_len (buffer, USE_BUF (channel)->str, length);
1462 g_string_erase (USE_BUF (channel), 0, length);
1465 return status;
1469 static GIOStatus
1470 g_io_channel_read_line_backend (GIOChannel *channel,
1471 gsize *length,
1472 gsize *terminator_pos,
1473 GError **error)
1475 GIOStatus status;
1476 gsize checked_to, line_term_len, line_length, got_term_len;
1477 gboolean first_time = TRUE;
1479 if (!channel->use_buffer)
1481 /* Can't do a raw read in read_line */
1482 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1483 _("Can't do a raw read in g_io_channel_read_line_string"));
1484 return G_IO_STATUS_ERROR;
1487 status = G_IO_STATUS_NORMAL;
1489 if (channel->line_term)
1490 line_term_len = channel->line_term_len;
1491 else
1492 line_term_len = 3;
1493 /* This value used for setting checked_to, it's the longest of the four
1494 * we autodetect for.
1497 checked_to = 0;
1499 while (TRUE)
1501 gchar *nextchar, *lastchar;
1502 GString *use_buf;
1504 if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1506 read_again:
1507 status = g_io_channel_fill_buffer (channel, error);
1508 switch (status)
1510 case G_IO_STATUS_NORMAL:
1511 if (BUF_LEN (USE_BUF (channel)) == 0)
1512 /* Can happen when using conversion and only read
1513 * part of a character
1516 first_time = FALSE;
1517 continue;
1519 break;
1520 case G_IO_STATUS_EOF:
1521 if (BUF_LEN (USE_BUF (channel)) == 0)
1523 if (length)
1524 *length = 0;
1526 if (channel->encoding && channel->read_buf->len != 0)
1528 g_set_error (error, G_CONVERT_ERROR,
1529 G_CONVERT_ERROR_PARTIAL_INPUT,
1530 _("Leftover unconverted data in read buffer"));
1531 return G_IO_STATUS_ERROR;
1533 else
1534 return G_IO_STATUS_EOF;
1536 break;
1537 default:
1538 if (length)
1539 *length = 0;
1540 return status;
1544 g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1546 use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1548 first_time = FALSE;
1550 lastchar = use_buf->str + use_buf->len;
1552 for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1553 channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1555 if (channel->line_term)
1557 if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1559 line_length = nextchar - use_buf->str;
1560 got_term_len = line_term_len;
1561 goto done;
1564 else /* auto detect */
1566 switch (*nextchar)
1568 case '\n': /* unix */
1569 line_length = nextchar - use_buf->str;
1570 got_term_len = 1;
1571 goto done;
1572 case '\r': /* Warning: do not use with sockets */
1573 line_length = nextchar - use_buf->str;
1574 if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1575 && (lastchar == use_buf->str + use_buf->len))
1576 goto read_again; /* Try to read more data */
1577 if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1578 got_term_len = 2;
1579 else /* mac */
1580 got_term_len = 1;
1581 goto done;
1582 case '\xe2': /* Unicode paragraph separator */
1583 if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1585 line_length = nextchar - use_buf->str;
1586 got_term_len = 3;
1587 goto done;
1589 break;
1590 case '\0': /* Embeded null in input */
1591 line_length = nextchar - use_buf->str;
1592 got_term_len = 1;
1593 goto done;
1594 default: /* no match */
1595 break;
1600 /* If encoding != NULL, valid UTF-8, didn't overshoot */
1601 g_assert (nextchar == lastchar);
1603 /* Check for EOF */
1605 if (status == G_IO_STATUS_EOF)
1607 if (channel->encoding && channel->read_buf->len > 0)
1609 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1610 _("Channel terminates in a partial character"));
1611 return G_IO_STATUS_ERROR;
1613 line_length = use_buf->len;
1614 got_term_len = 0;
1615 break;
1618 if (use_buf->len > line_term_len - 1)
1619 checked_to = use_buf->len - (line_term_len - 1);
1620 else
1621 checked_to = 0;
1624 done:
1626 if (terminator_pos)
1627 *terminator_pos = line_length;
1629 if (length)
1630 *length = line_length + got_term_len;
1632 return G_IO_STATUS_NORMAL;
1636 * g_io_channel_read_to_end:
1637 * @channel: a #GIOChannel
1638 * @str_return: Location to store a pointer to a string holding
1639 * the remaining data in the #GIOChannel. This data should
1640 * be freed with g_free() when no longer needed. This
1641 * data is terminated by an extra nul character, but there
1642 * may be other nuls in the intervening data.
1643 * @length: Location to store length of the data
1644 * @error: A location to return an error of type #GConvertError
1645 * or #GIOChannelError
1647 * Reads all the remaining data from the file.
1649 * Return value: %G_IO_STATUS_NORMAL on success.
1650 * This function never returns %G_IO_STATUS_EOF.
1652 GIOStatus
1653 g_io_channel_read_to_end (GIOChannel *channel,
1654 gchar **str_return,
1655 gsize *length,
1656 GError **error)
1658 GIOStatus status;
1660 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1661 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1662 G_IO_STATUS_ERROR);
1663 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1665 if (str_return)
1666 *str_return = NULL;
1667 if (length)
1668 *length = 0;
1670 if (!channel->use_buffer)
1672 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1673 _("Can't do a raw read in g_io_channel_read_to_end"));
1674 return G_IO_STATUS_ERROR;
1678 status = g_io_channel_fill_buffer (channel, error);
1679 while (status == G_IO_STATUS_NORMAL);
1681 if (status != G_IO_STATUS_EOF)
1682 return status;
1684 if (channel->encoding && channel->read_buf->len > 0)
1686 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1687 _("Channel terminates in a partial character"));
1688 return G_IO_STATUS_ERROR;
1691 if (USE_BUF (channel) == NULL)
1693 /* length is already set to zero */
1694 if (str_return)
1695 *str_return = g_strdup ("");
1697 else
1699 if (length)
1700 *length = USE_BUF (channel)->len;
1702 if (str_return)
1703 *str_return = g_string_free (USE_BUF (channel), FALSE);
1704 else
1705 g_string_free (USE_BUF (channel), TRUE);
1707 if (channel->encoding)
1708 channel->encoded_read_buf = NULL;
1709 else
1710 channel->read_buf = NULL;
1713 return G_IO_STATUS_NORMAL;
1717 * g_io_channel_read_chars:
1718 * @channel: a #GIOChannel
1719 * @buf: a buffer to read data into
1720 * @count: the size of the buffer. Note that the buffer may
1721 * not be complelely filled even if there is data
1722 * in the buffer if the remaining data is not a
1723 * complete character.
1724 * @bytes_read: The number of bytes read. This may be zero even on
1725 * success if count < 6 and the channel's encoding is non-%NULL.
1726 * This indicates that the next UTF-8 character is too wide for
1727 * the buffer.
1728 * @error: A location to return an error of type #GConvertError
1729 * or #GIOChannelError.
1731 * Replacement for g_io_channel_read() with the new API.
1733 * Return value: the status of the operation.
1735 GIOStatus
1736 g_io_channel_read_chars (GIOChannel *channel,
1737 gchar *buf,
1738 gsize count,
1739 gsize *bytes_read,
1740 GError **error)
1742 GIOStatus status;
1743 gsize got_bytes;
1745 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1746 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1747 G_IO_STATUS_ERROR);
1748 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1750 if (count == 0)
1752 *bytes_read = 0;
1753 return G_IO_STATUS_NORMAL;
1755 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1757 if (!channel->use_buffer)
1759 gsize tmp_bytes;
1761 g_assert (!channel->read_buf || channel->read_buf->len == 0);
1763 status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
1765 if (bytes_read)
1766 *bytes_read = tmp_bytes;
1768 return status;
1771 status = G_IO_STATUS_NORMAL;
1773 while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
1774 status = g_io_channel_fill_buffer (channel, error);
1776 /* Only return an error if we have no data */
1778 if (BUF_LEN (USE_BUF (channel)) == 0)
1780 g_assert (status != G_IO_STATUS_NORMAL);
1782 if (status == G_IO_STATUS_EOF && channel->encoding
1783 && BUF_LEN (channel->read_buf) > 0)
1785 g_set_error (error, G_CONVERT_ERROR,
1786 G_CONVERT_ERROR_PARTIAL_INPUT,
1787 _("Leftover unconverted data in read buffer"));
1788 status = G_IO_STATUS_ERROR;
1791 if (bytes_read)
1792 *bytes_read = 0;
1794 return status;
1797 if (status == G_IO_STATUS_ERROR)
1798 g_clear_error (error);
1800 got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
1802 g_assert (got_bytes > 0);
1804 if (channel->encoding)
1805 /* Don't validate for NULL encoding, binary safe */
1807 gchar *nextchar, *prevchar;
1809 g_assert (USE_BUF (channel) == channel->encoded_read_buf);
1811 nextchar = channel->encoded_read_buf->str;
1815 prevchar = nextchar;
1816 nextchar = g_utf8_next_char (nextchar);
1817 g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
1819 while (nextchar < channel->encoded_read_buf->str + got_bytes);
1821 if (nextchar > channel->encoded_read_buf->str + got_bytes)
1822 got_bytes = prevchar - channel->encoded_read_buf->str;
1824 g_assert (got_bytes > 0 || count < 6);
1827 memcpy (buf, USE_BUF (channel)->str, got_bytes);
1828 g_string_erase (USE_BUF (channel), 0, got_bytes);
1830 if (bytes_read)
1831 *bytes_read = got_bytes;
1833 return G_IO_STATUS_NORMAL;
1837 * g_io_channel_read_unichar:
1838 * @channel: a #GIOChannel
1839 * @thechar: a location to return a character
1840 * @error: A location to return an error of type #GConvertError
1841 * or #GIOChannelError
1843 * This function cannot be called on a channel with %NULL encoding.
1845 * Return value: a #GIOStatus
1847 GIOStatus
1848 g_io_channel_read_unichar (GIOChannel *channel,
1849 gunichar *thechar,
1850 GError **error)
1852 GIOStatus status = G_IO_STATUS_NORMAL;
1854 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1855 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
1856 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1857 G_IO_STATUS_ERROR);
1858 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1860 while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
1861 status = g_io_channel_fill_buffer (channel, error);
1863 /* Only return an error if we have no data */
1865 if (BUF_LEN (USE_BUF (channel)) == 0)
1867 g_assert (status != G_IO_STATUS_NORMAL);
1869 if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
1871 g_set_error (error, G_CONVERT_ERROR,
1872 G_CONVERT_ERROR_PARTIAL_INPUT,
1873 _("Leftover unconverted data in read buffer"));
1874 status = G_IO_STATUS_ERROR;
1877 if (thechar)
1878 *thechar = (gunichar) -1;
1880 return status;
1883 if (status == G_IO_STATUS_ERROR)
1884 g_clear_error (error);
1886 if (thechar)
1887 *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
1889 g_string_erase (channel->encoded_read_buf, 0,
1890 g_utf8_next_char (channel->encoded_read_buf->str)
1891 - channel->encoded_read_buf->str);
1893 return G_IO_STATUS_NORMAL;
1897 * g_io_channel_write_chars:
1898 * @channel: a #GIOChannel
1899 * @buf: a buffer to write data from
1900 * @count: the size of the buffer. If -1, the buffer
1901 * is taken to be a nul-terminated string.
1902 * @bytes_written: The number of bytes written. This can be nonzero
1903 * even if the return value is not %G_IO_STATUS_NORMAL.
1904 * If the return value is %G_IO_STATUS_NORMAL and the
1905 * channel is blocking, this will always be equal
1906 * to @count if @count >= 0.
1907 * @error: A location to return an error of type #GConvertError
1908 * or #GIOChannelError
1910 * Replacement for g_io_channel_write() with the new API.
1912 * On seekable channels with encodings other than %NULL or UTF-8, generic
1913 * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
1914 * may only be made on a channel from which data has been read in the
1915 * cases described in the documentation for g_io_channel_set_encoding ().
1917 * Return value: the status of the operation.
1919 GIOStatus
1920 g_io_channel_write_chars (GIOChannel *channel,
1921 const gchar *buf,
1922 gssize count,
1923 gsize *bytes_written,
1924 GError **error)
1926 GIOStatus status;
1927 gssize wrote_bytes = 0;
1929 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1930 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1931 G_IO_STATUS_ERROR);
1932 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1934 if ((count < 0) && buf)
1935 count = strlen (buf);
1937 if (count == 0)
1939 if (bytes_written)
1940 *bytes_written = 0;
1941 return G_IO_STATUS_NORMAL;
1944 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1945 g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1947 /* Raw write case */
1949 if (!channel->use_buffer)
1951 gsize tmp_bytes;
1953 g_assert (!channel->write_buf || channel->write_buf->len == 0);
1954 g_assert (channel->partial_write_buf[0] == '\0');
1956 status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
1958 if (bytes_written)
1959 *bytes_written = tmp_bytes;
1961 return status;
1964 /* General case */
1966 if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
1967 || (BUF_LEN (channel->encoded_read_buf) > 0)))
1969 if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
1971 g_warning("Mixed reading and writing not allowed on encoded files");
1972 return G_IO_STATUS_ERROR;
1974 status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1975 if (status != G_IO_STATUS_NORMAL)
1977 if (bytes_written)
1978 *bytes_written = 0;
1979 return status;
1983 if (!channel->write_buf)
1984 channel->write_buf = g_string_sized_new (channel->buf_size);
1986 while (wrote_bytes < count)
1988 gsize space_in_buf;
1990 /* If the buffer is full, try a write immediately. In
1991 * the nonblocking case, this prevents the user from
1992 * writing just a little bit to the buffer every time
1993 * and never receiving an EAGAIN.
1996 if (channel->write_buf->len >= channel->buf_size)
1998 gsize did_write = 0, this_time;
2002 status = channel->funcs->io_write (channel, channel->write_buf->str
2003 + did_write, channel->write_buf->len
2004 - did_write, &this_time, error);
2005 did_write += this_time;
2007 while (status == G_IO_STATUS_NORMAL &&
2008 did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2010 g_string_erase (channel->write_buf, 0, did_write);
2012 if (status != G_IO_STATUS_NORMAL)
2014 if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2015 status = G_IO_STATUS_NORMAL;
2016 if (bytes_written)
2017 *bytes_written = wrote_bytes;
2018 return status;
2022 space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2023 - channel->write_buf->len; /* 1 for NULL */
2025 /* This is only true because g_io_channel_set_buffer_size ()
2026 * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2028 g_assert (space_in_buf >= MAX_CHAR_SIZE);
2030 if (!channel->encoding)
2032 gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2034 g_string_append_len (channel->write_buf, buf, write_this);
2035 buf += write_this;
2036 wrote_bytes += write_this;
2038 else
2040 const gchar *from_buf;
2041 gsize from_buf_len, from_buf_old_len, left_len;
2042 size_t err;
2043 gint errnum;
2045 if (channel->partial_write_buf[0] != '\0')
2047 g_assert (wrote_bytes == 0);
2049 from_buf = channel->partial_write_buf;
2050 from_buf_old_len = strlen (channel->partial_write_buf);
2051 g_assert (from_buf_old_len > 0);
2052 from_buf_len = MIN (6, from_buf_old_len + count);
2054 memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2055 from_buf_len - from_buf_old_len);
2057 else
2059 from_buf = buf;
2060 from_buf_len = count - wrote_bytes;
2061 from_buf_old_len = 0;
2064 reconvert:
2066 if (!channel->do_encode) /* UTF-8 encoding */
2068 const gchar *badchar;
2069 gsize try_len = MIN (from_buf_len, space_in_buf);
2071 /* UTF-8, just validate, emulate g_iconv */
2073 if (!g_utf8_validate (from_buf, try_len, &badchar))
2075 gunichar try_char;
2076 gsize incomplete_len = from_buf + try_len - badchar;
2078 left_len = from_buf + from_buf_len - badchar;
2080 try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2082 switch (try_char)
2084 case -2:
2085 g_assert (incomplete_len < 6);
2086 if (try_len == from_buf_len)
2088 errnum = EINVAL;
2089 err = (size_t) -1;
2091 else
2093 errnum = 0;
2094 err = (size_t) 0;
2096 break;
2097 case -1:
2098 g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2099 /* FIXME bail here? */
2100 errnum = EILSEQ;
2101 err = (size_t) -1;
2102 break;
2103 default:
2104 g_assert_not_reached ();
2105 err = (size_t) -1;
2106 errnum = 0; /* Don't confunse the compiler */
2109 else
2111 err = (size_t) 0;
2112 errnum = 0;
2113 left_len = from_buf_len - try_len;
2116 g_string_append_len (channel->write_buf, from_buf,
2117 from_buf_len - left_len);
2118 from_buf += from_buf_len - left_len;
2120 else
2122 gchar *outbuf;
2124 left_len = from_buf_len;
2125 g_string_set_size (channel->write_buf, channel->write_buf->len
2126 + space_in_buf);
2127 outbuf = channel->write_buf->str + channel->write_buf->len
2128 - space_in_buf;
2129 err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2130 &outbuf, &space_in_buf);
2131 errnum = errno;
2132 g_string_truncate (channel->write_buf, channel->write_buf->len
2133 - space_in_buf);
2136 if (err == (size_t) -1)
2138 switch (errnum)
2140 case EINVAL:
2141 g_assert (left_len < 6);
2143 if (from_buf_old_len == 0)
2145 /* Not from partial_write_buf */
2147 memcpy (channel->partial_write_buf, from_buf, left_len);
2148 channel->partial_write_buf[left_len] = '\0';
2149 if (bytes_written)
2150 *bytes_written = count;
2151 return G_IO_STATUS_NORMAL;
2154 /* Working in partial_write_buf */
2156 if (left_len == from_buf_len)
2158 /* Didn't convert anything, must still have
2159 * less than a full character
2162 g_assert (count == from_buf_len - from_buf_old_len);
2164 channel->partial_write_buf[from_buf_len] = '\0';
2166 if (bytes_written)
2167 *bytes_written = count;
2169 return G_IO_STATUS_NORMAL;
2172 g_assert (from_buf_len - left_len >= from_buf_old_len);
2174 /* We converted all the old data. This is fine */
2176 break;
2177 case E2BIG:
2178 if (from_buf_len == left_len)
2180 /* Nothing was written, add enough space for
2181 * at least one character.
2183 space_in_buf += MAX_CHAR_SIZE;
2184 goto reconvert;
2186 break;
2187 case EILSEQ:
2188 g_set_error (error, G_CONVERT_ERROR,
2189 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2190 _("Invalid byte sequence in conversion input"));
2191 if (from_buf_old_len > 0 && from_buf_len == left_len)
2192 g_warning ("Illegal sequence due to partial character "
2193 "at the end of a previous write.\n");
2194 else
2195 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2196 if (bytes_written)
2197 *bytes_written = wrote_bytes;
2198 channel->partial_write_buf[0] = '\0';
2199 return G_IO_STATUS_ERROR;
2200 default:
2201 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2202 _("Error during conversion: %s"), g_strerror (errnum));
2203 if (from_buf_len >= left_len + from_buf_old_len)
2204 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2205 if (bytes_written)
2206 *bytes_written = wrote_bytes;
2207 channel->partial_write_buf[0] = '\0';
2208 return G_IO_STATUS_ERROR;
2212 g_assert (from_buf_len - left_len >= from_buf_old_len);
2214 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2216 if (from_buf_old_len > 0)
2218 /* We were working in partial_write_buf */
2220 buf += from_buf_len - left_len - from_buf_old_len;
2221 channel->partial_write_buf[0] = '\0';
2223 else
2224 buf = from_buf;
2228 if (bytes_written)
2229 *bytes_written = count;
2231 return G_IO_STATUS_NORMAL;
2235 * g_io_channel_write_unichar:
2236 * @channel: a #GIOChannel
2237 * @thechar: a character
2238 * @error: A location to return an error of type #GConvertError
2239 * or #GIOChannelError
2241 * This function cannot be called on a channel with %NULL encoding.
2243 * Return value: a #GIOStatus
2245 GIOStatus
2246 g_io_channel_write_unichar (GIOChannel *channel,
2247 gunichar thechar,
2248 GError **error)
2250 GIOStatus status;
2251 gchar static_buf[6];
2252 gsize char_len, wrote_len;
2254 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2255 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2256 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2257 G_IO_STATUS_ERROR);
2258 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2260 char_len = g_unichar_to_utf8 (thechar, static_buf);
2262 if (channel->partial_write_buf[0] != '\0')
2264 g_warning ("Partial charater written before writing unichar.\n");
2265 channel->partial_write_buf[0] = '\0';
2268 status = g_io_channel_write_chars (channel, static_buf,
2269 char_len, &wrote_len, error);
2271 /* We validate UTF-8, so we can't get a partial write */
2273 g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2275 return status;
2279 * g_io_channel_error_quark:
2281 * Return value: The quark used as %G_IO_CHANNEL_ERROR
2283 GQuark
2284 g_io_channel_error_quark (void)
2286 static GQuark q = 0;
2287 if (q == 0)
2288 q = g_quark_from_static_string ("g-io-channel-error-quark");
2290 return q;