If a character can't be converted, don't replace it with a NUL byte, but
[glib.git] / glib / giochannel.c
blob49d7cb33dc080e935a03e5e6b69ca57bb47b5fd2
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 #include "galias.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,
67 GError *err);
68 static void g_io_channel_purge (GIOChannel *channel);
69 static GIOStatus g_io_channel_fill_buffer (GIOChannel *channel,
70 GError **err);
71 static GIOStatus g_io_channel_read_line_backend (GIOChannel *channel,
72 gsize *length,
73 gsize *terminator_pos,
74 GError **error);
76 void
77 g_io_channel_init (GIOChannel *channel)
79 channel->ref_count = 1;
80 channel->encoding = g_strdup ("UTF-8");
81 channel->line_term = NULL;
82 channel->line_term_len = 0;
83 channel->buf_size = G_IO_NICE_BUF_SIZE;
84 channel->read_cd = (GIConv) -1;
85 channel->write_cd = (GIConv) -1;
86 channel->read_buf = NULL; /* Lazy allocate buffers */
87 channel->encoded_read_buf = NULL;
88 channel->write_buf = NULL;
89 channel->partial_write_buf[0] = '\0';
90 channel->use_buffer = TRUE;
91 channel->do_encode = FALSE;
92 channel->close_on_unref = FALSE;
95 GIOChannel *
96 g_io_channel_ref (GIOChannel *channel)
98 g_return_val_if_fail (channel != NULL, NULL);
100 g_atomic_int_inc (&channel->ref_count);
102 return channel;
105 void
106 g_io_channel_unref (GIOChannel *channel)
108 gboolean is_zero;
110 g_return_if_fail (channel != NULL);
112 is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
114 if (G_UNLIKELY (is_zero))
116 if (channel->close_on_unref)
117 g_io_channel_shutdown (channel, TRUE, NULL);
118 else
119 g_io_channel_purge (channel);
120 g_free (channel->encoding);
121 if (channel->read_cd != (GIConv) -1)
122 g_iconv_close (channel->read_cd);
123 if (channel->write_cd != (GIConv) -1)
124 g_iconv_close (channel->write_cd);
125 if (channel->line_term)
126 g_free (channel->line_term);
127 if (channel->read_buf)
128 g_string_free (channel->read_buf, TRUE);
129 if (channel->write_buf)
130 g_string_free (channel->write_buf, TRUE);
131 if (channel->encoded_read_buf)
132 g_string_free (channel->encoded_read_buf, TRUE);
133 channel->funcs->io_free (channel);
137 static GIOError
138 g_io_error_get_from_g_error (GIOStatus status,
139 GError *err)
141 switch (status)
143 case G_IO_STATUS_NORMAL:
144 case G_IO_STATUS_EOF:
145 return G_IO_ERROR_NONE;
146 case G_IO_STATUS_AGAIN:
147 return G_IO_ERROR_AGAIN;
148 case G_IO_STATUS_ERROR:
149 g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
151 if (err->domain != G_IO_CHANNEL_ERROR)
152 return G_IO_ERROR_UNKNOWN;
153 switch (err->code)
155 case G_IO_CHANNEL_ERROR_INVAL:
156 return G_IO_ERROR_INVAL;
157 default:
158 return G_IO_ERROR_UNKNOWN;
160 default:
161 g_assert_not_reached ();
162 return G_IO_ERROR_UNKNOWN; /* Keep the compiler happy */
167 * g_io_channel_read:
168 * @channel: a #GIOChannel.
169 * @buf: a buffer to read the data into (which should be at least count bytes long).
170 * @count: the number of bytes to read from the #GIOChannel.
171 * @bytes_read: returns the number of bytes actually read.
173 * Reads data from a #GIOChannel.
175 * Return value: %G_IO_ERROR_NONE if the operation was successful.
177 * Deprecated:2.2: Use g_io_channel_read_chars() instead.
179 GIOError
180 g_io_channel_read (GIOChannel *channel,
181 gchar *buf,
182 gsize count,
183 gsize *bytes_read)
185 GError *err = NULL;
186 GIOError error;
187 GIOStatus status;
189 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
190 g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
192 if (count == 0)
194 if (bytes_read)
195 *bytes_read = 0;
196 return G_IO_ERROR_NONE;
199 g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
201 status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
203 error = g_io_error_get_from_g_error (status, err);
205 if (err)
206 g_error_free (err);
208 return error;
212 * g_io_channel_write:
213 * @channel: a #GIOChannel.
214 * @buf: the buffer containing the data to write.
215 * @count: the number of bytes to write.
216 * @bytes_written: the number of bytes actually written.
218 * Writes data to a #GIOChannel.
220 * Return value: %G_IO_ERROR_NONE if the operation was successful.
222 * Deprecated:2.2: Use g_io_channel_write_chars() instead.
224 GIOError
225 g_io_channel_write (GIOChannel *channel,
226 const gchar *buf,
227 gsize count,
228 gsize *bytes_written)
230 GError *err = NULL;
231 GIOError error;
232 GIOStatus status;
234 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
235 g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
237 status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
239 error = g_io_error_get_from_g_error (status, err);
241 if (err)
242 g_error_free (err);
244 return error;
248 * g_io_channel_seek:
249 * @channel: a #GIOChannel.
250 * @offset: an offset, in bytes, which is added to the position specified by @type
251 * @type: the position in the file, which can be %G_SEEK_CUR (the current
252 * position), %G_SEEK_SET (the start of the file), or %G_SEEK_END (the end of the
253 * file).
255 * Sets the current position in the #GIOChannel, similar to the standard library
256 * function fseek().
258 * Return value: %G_IO_ERROR_NONE if the operation was successful.
260 * Deprecated:2.2: Use g_io_channel_seek_position() instead.
262 GIOError
263 g_io_channel_seek (GIOChannel *channel,
264 gint64 offset,
265 GSeekType type)
267 GError *err = NULL;
268 GIOError error;
269 GIOStatus status;
271 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
272 g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
274 switch (type)
276 case G_SEEK_CUR:
277 case G_SEEK_SET:
278 case G_SEEK_END:
279 break;
280 default:
281 g_warning ("g_io_channel_seek: unknown seek type");
282 return G_IO_ERROR_UNKNOWN;
285 status = channel->funcs->io_seek (channel, offset, type, &err);
287 error = g_io_error_get_from_g_error (status, err);
289 if (err)
290 g_error_free (err);
292 return error;
295 /* The function g_io_channel_new_file() is prototyped in both
296 * giounix.c and giowin32.c, so we stick its documentation here.
300 * g_io_channel_new_file:
301 * @filename: A string containing the name of a file.
302 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
303 * the same meaning as in fopen().
304 * @error: A location to return an error of type %G_FILE_ERROR.
306 * Open a file @filename as a #GIOChannel using mode @mode. This
307 * channel will be closed when the last reference to it is dropped,
308 * so there is no need to call g_io_channel_close() (though doing
309 * so will not cause problems, as long as no attempt is made to
310 * access the channel after it is closed).
312 * Return value: A #GIOChannel on success, %NULL on failure.
316 * g_io_channel_close:
317 * @channel: A #GIOChannel
319 * Close an IO channel. Any pending data to be written will be
320 * flushed, ignoring errors. The channel will not be freed until the
321 * last reference is dropped using g_io_channel_unref().
323 * Deprecated:2.2: Use g_io_channel_shutdown() instead.
325 void
326 g_io_channel_close (GIOChannel *channel)
328 GError *err = NULL;
330 g_return_if_fail (channel != NULL);
332 g_io_channel_purge (channel);
334 channel->funcs->io_close (channel, &err);
336 if (err)
337 { /* No way to return the error */
338 g_warning ("Error closing channel: %s", err->message);
339 g_error_free (err);
342 channel->close_on_unref = FALSE; /* Because we already did */
343 channel->is_readable = FALSE;
344 channel->is_writeable = FALSE;
345 channel->is_seekable = FALSE;
349 * g_io_channel_shutdown:
350 * @channel: a #GIOChannel
351 * @flush: if %TRUE, flush pending
352 * @err: location to store a #GIOChannelError
354 * Close an IO channel. Any pending data to be written will be
355 * flushed if @flush is %TRUE. The channel will not be freed until the
356 * last reference is dropped using g_io_channel_unref().
358 * Return value: the status of the operation.
360 GIOStatus
361 g_io_channel_shutdown (GIOChannel *channel,
362 gboolean flush,
363 GError **err)
365 GIOStatus status, result;
366 GError *tmperr = NULL;
368 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
369 g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
371 if (channel->write_buf && channel->write_buf->len > 0)
373 if (flush)
375 GIOFlags flags;
377 /* Set the channel to blocking, to avoid a busy loop
379 flags = g_io_channel_get_flags (channel);
380 /* Ignore any errors here, they're irrelevant */
381 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
383 result = g_io_channel_flush (channel, &tmperr);
385 else
386 result = G_IO_STATUS_NORMAL;
388 g_string_truncate(channel->write_buf, 0);
390 else
391 result = G_IO_STATUS_NORMAL;
393 if (channel->partial_write_buf[0] != '\0')
395 if (flush)
396 g_warning ("Partial character at end of write buffer not flushed.\n");
397 channel->partial_write_buf[0] = '\0';
400 status = channel->funcs->io_close (channel, err);
402 channel->close_on_unref = FALSE; /* Because we already did */
403 channel->is_readable = FALSE;
404 channel->is_writeable = FALSE;
405 channel->is_seekable = FALSE;
407 if (status != G_IO_STATUS_NORMAL)
409 g_clear_error (&tmperr);
410 return status;
412 else if (result != G_IO_STATUS_NORMAL)
414 g_propagate_error (err, tmperr);
415 return result;
417 else
418 return G_IO_STATUS_NORMAL;
421 /* This function is used for the final flush on close or unref */
422 static void
423 g_io_channel_purge (GIOChannel *channel)
425 GError *err = NULL;
426 GIOStatus status;
428 g_return_if_fail (channel != NULL);
430 if (channel->write_buf && channel->write_buf->len > 0)
432 GIOFlags flags;
434 /* Set the channel to blocking, to avoid a busy loop
436 flags = g_io_channel_get_flags (channel);
437 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
439 status = g_io_channel_flush (channel, &err);
441 if (err)
442 { /* No way to return the error */
443 g_warning ("Error flushing string: %s", err->message);
444 g_error_free (err);
448 /* Flush these in case anyone tries to close without unrefing */
450 if (channel->read_buf)
451 g_string_truncate (channel->read_buf, 0);
452 if (channel->write_buf)
453 g_string_truncate (channel->write_buf, 0);
454 if (channel->encoding)
456 if (channel->encoded_read_buf)
457 g_string_truncate (channel->encoded_read_buf, 0);
459 if (channel->partial_write_buf[0] != '\0')
461 g_warning ("Partial character at end of write buffer not flushed.\n");
462 channel->partial_write_buf[0] = '\0';
467 GSource *
468 g_io_create_watch (GIOChannel *channel,
469 GIOCondition condition)
471 g_return_val_if_fail (channel != NULL, NULL);
473 return channel->funcs->io_create_watch (channel, condition);
476 guint
477 g_io_add_watch_full (GIOChannel *channel,
478 gint priority,
479 GIOCondition condition,
480 GIOFunc func,
481 gpointer user_data,
482 GDestroyNotify notify)
484 GSource *source;
485 guint id;
487 g_return_val_if_fail (channel != NULL, 0);
489 source = g_io_create_watch (channel, condition);
491 if (priority != G_PRIORITY_DEFAULT)
492 g_source_set_priority (source, priority);
493 g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
495 id = g_source_attach (source, NULL);
496 g_source_unref (source);
498 return id;
501 guint
502 g_io_add_watch (GIOChannel *channel,
503 GIOCondition condition,
504 GIOFunc func,
505 gpointer user_data)
507 return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
511 * g_io_channel_get_buffer_condition:
512 * @channel: A #GIOChannel
514 * This function returns a #GIOCondition depending on whether there
515 * is data to be read/space to write data in the
516 * internal buffers in the #GIOChannel. Only the flags %G_IO_IN and
517 * %G_IO_OUT may be set.
519 * Return value: A #GIOCondition
521 GIOCondition
522 g_io_channel_get_buffer_condition (GIOChannel *channel)
524 GIOCondition condition = 0;
526 if (channel->encoding)
528 if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
529 condition |= G_IO_IN; /* Only return if we have full characters */
531 else
533 if (channel->read_buf && (channel->read_buf->len > 0))
534 condition |= G_IO_IN;
537 if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
538 condition |= G_IO_OUT;
540 return condition;
544 * g_io_channel_error_from_errno:
545 * @en: an <literal>errno</literal> error number, e.g. %EINVAL.
547 * Converts an <literal>errno</literal> error number to a #GIOChannelError.
549 * Return value: a #GIOChannelError error number, e.g. %G_IO_CHANNEL_ERROR_INVAL.
551 GIOChannelError
552 g_io_channel_error_from_errno (gint en)
554 #ifdef EAGAIN
555 g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
556 #endif
558 switch (en)
560 #ifdef EBADF
561 case EBADF:
562 g_warning("Invalid file descriptor.\n");
563 return G_IO_CHANNEL_ERROR_FAILED;
564 #endif
566 #ifdef EFAULT
567 case EFAULT:
568 g_warning("Buffer outside valid address space.\n");
569 return G_IO_CHANNEL_ERROR_FAILED;
570 #endif
572 #ifdef EFBIG
573 case EFBIG:
574 return G_IO_CHANNEL_ERROR_FBIG;
575 #endif
577 #ifdef EINTR
578 /* In general, we should catch EINTR before we get here,
579 * but close() is allowed to return EINTR by POSIX, so
580 * we need to catch it here; EINTR from close() is
581 * unrecoverable, because it's undefined whether
582 * the fd was actually closed or not, so we just return
583 * a generic error code.
585 case EINTR:
586 return G_IO_CHANNEL_ERROR_FAILED;
587 #endif
589 #ifdef EINVAL
590 case EINVAL:
591 return G_IO_CHANNEL_ERROR_INVAL;
592 #endif
594 #ifdef EIO
595 case EIO:
596 return G_IO_CHANNEL_ERROR_IO;
597 #endif
599 #ifdef EISDIR
600 case EISDIR:
601 return G_IO_CHANNEL_ERROR_ISDIR;
602 #endif
604 #ifdef ENOSPC
605 case ENOSPC:
606 return G_IO_CHANNEL_ERROR_NOSPC;
607 #endif
609 #ifdef ENXIO
610 case ENXIO:
611 return G_IO_CHANNEL_ERROR_NXIO;
612 #endif
614 #ifdef EOVERFLOW
615 case EOVERFLOW:
616 return G_IO_CHANNEL_ERROR_OVERFLOW;
617 #endif
619 #ifdef EPIPE
620 case EPIPE:
621 return G_IO_CHANNEL_ERROR_PIPE;
622 #endif
624 default:
625 return G_IO_CHANNEL_ERROR_FAILED;
630 * g_io_channel_set_buffer_size:
631 * @channel: a #GIOChannel
632 * @size: the size of the buffer. 0 == pick a good size
634 * Sets the buffer size.
635 **/
636 void
637 g_io_channel_set_buffer_size (GIOChannel *channel,
638 gsize size)
640 g_return_if_fail (channel != NULL);
642 if (size == 0)
643 size = G_IO_NICE_BUF_SIZE;
645 if (size < MAX_CHAR_SIZE)
646 size = MAX_CHAR_SIZE;
648 channel->buf_size = size;
652 * g_io_channel_get_buffer_size:
653 * @channel: a #GIOChannel
655 * Gets the buffer size.
657 * Return value: the size of the buffer.
658 **/
659 gsize
660 g_io_channel_get_buffer_size (GIOChannel *channel)
662 g_return_val_if_fail (channel != NULL, 0);
664 return channel->buf_size;
668 * g_io_channel_set_line_term:
669 * @channel: a #GIOChannel
670 * @line_term: The line termination string. Use %NULL for auto detect.
671 * Auto detection breaks on "\n", "\r\n", "\r", "\0", and
672 * the Unicode paragraph separator. Auto detection should
673 * not be used for anything other than file-based channels.
674 * @length: The length of the termination string. If -1 is passed, the
675 * string is assumed to be nul-terminated. This option allows
676 * termination strings with embeded nuls.
678 * This sets the string that #GIOChannel uses to determine
679 * where in the file a line break occurs.
681 void
682 g_io_channel_set_line_term (GIOChannel *channel,
683 const gchar *line_term,
684 gint length)
686 g_return_if_fail (channel != NULL);
687 g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
689 if (line_term == NULL)
690 length = 0;
691 else if (length < 0)
692 length = strlen (line_term);
694 if (channel->line_term)
695 g_free (channel->line_term);
696 channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
697 channel->line_term_len = length;
701 * g_io_channel_get_line_term:
702 * @channel: a #GIOChannel
703 * @length: a location to return the length of the line terminator
705 * This returns the string that #GIOChannel uses to determine
706 * where in the file a line break occurs. A value of %NULL
707 * indicates auto detection.
709 * Return value: The line termination string. This value
710 * is owned by GLib and must not be freed.
712 G_CONST_RETURN gchar*
713 g_io_channel_get_line_term (GIOChannel *channel,
714 gint *length)
716 g_return_val_if_fail (channel != NULL, NULL);
718 if (length)
719 *length = channel->line_term_len;
721 return channel->line_term;
725 * g_io_channel_set_flags:
726 * @channel: a #GIOChannel.
727 * @flags: the flags to set on the IO channel.
728 * @error: A location to return an error of type #GIOChannelError.
730 * Sets the (writeable) flags in @channel to (@flags & %G_IO_CHANNEL_SET_MASK).
732 * Return value: the status of the operation.
734 GIOStatus
735 g_io_channel_set_flags (GIOChannel *channel,
736 GIOFlags flags,
737 GError **error)
739 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
740 g_return_val_if_fail ((error == NULL) || (*error == NULL),
741 G_IO_STATUS_ERROR);
743 return (* channel->funcs->io_set_flags)(channel,
744 flags & G_IO_FLAG_SET_MASK,
745 error);
749 * g_io_channel_get_flags:
750 * @channel: a #GIOChannel
752 * Gets the current flags for a #GIOChannel, including read-only
753 * flags such as %G_IO_FLAG_IS_READABLE.
755 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITEABLE
756 * are cached for internal use by the channel when it is created.
757 * If they should change at some later point (e.g. partial shutdown
758 * of a socket with the UNIX shutdown() function), the user
759 * should immediately call g_io_channel_get_flags () to update
760 * the internal values of these flags.
762 * Return value: the flags which are set on the channel
764 GIOFlags
765 g_io_channel_get_flags (GIOChannel *channel)
767 GIOFlags flags;
769 g_return_val_if_fail (channel != NULL, 0);
771 flags = (* channel->funcs->io_get_flags) (channel);
773 /* Cross implementation code */
775 if (channel->is_seekable)
776 flags |= G_IO_FLAG_IS_SEEKABLE;
777 if (channel->is_readable)
778 flags |= G_IO_FLAG_IS_READABLE;
779 if (channel->is_writeable)
780 flags |= G_IO_FLAG_IS_WRITEABLE;
782 return flags;
786 * g_io_channel_set_close_on_unref:
787 * @channel: a #GIOChannel
788 * @do_close: Whether to close the channel on the final unref of
789 * the GIOChannel data structure. The default value of
790 * this is %TRUE for channels created by g_io_channel_new_file (),
791 * and %FALSE for all other channels.
793 * Setting this flag to %TRUE for a channel you have already closed
794 * can cause problems.
796 void
797 g_io_channel_set_close_on_unref (GIOChannel *channel,
798 gboolean do_close)
800 g_return_if_fail (channel != NULL);
802 channel->close_on_unref = do_close;
806 * g_io_channel_get_close_on_unref:
807 * @channel: a #GIOChannel.
809 * Returns whether the file/socket/whatever associated with @channel
810 * will be closed when @channel receives its final unref and is
811 * destroyed. The default value of this is %TRUE for channels created
812 * by g_io_channel_new_file (), and %FALSE for all other channels.
814 * Return value: Whether the channel will be closed on the final unref of
815 * the GIOChannel data structure.
817 gboolean
818 g_io_channel_get_close_on_unref (GIOChannel *channel)
820 g_return_val_if_fail (channel != NULL, FALSE);
822 return channel->close_on_unref;
826 * g_io_channel_seek_position:
827 * @channel: a #GIOChannel
828 * @offset: The offset in bytes from the position specified by @type
829 * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
830 * cases where a call to g_io_channel_set_encoding ()
831 * is allowed. See the documentation for
832 * g_io_channel_set_encoding () for details.
833 * @error: A location to return an error of type #GIOChannelError
835 * Replacement for g_io_channel_seek() with the new API.
837 * Return value: the status of the operation.
839 GIOStatus
840 g_io_channel_seek_position (GIOChannel* channel,
841 gint64 offset,
842 GSeekType type,
843 GError **error)
845 GIOStatus status;
847 /* For files, only one of the read and write buffers can contain data.
848 * For sockets, both can contain data.
851 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
852 g_return_val_if_fail ((error == NULL) || (*error == NULL),
853 G_IO_STATUS_ERROR);
854 g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
856 switch (type)
858 case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
859 if (channel->use_buffer)
861 if (channel->do_encode && channel->encoded_read_buf
862 && channel->encoded_read_buf->len > 0)
864 g_warning ("Seek type G_SEEK_CUR not allowed for this"
865 " channel's encoding.\n");
866 return G_IO_STATUS_ERROR;
868 if (channel->read_buf)
869 offset -= channel->read_buf->len;
870 if (channel->encoded_read_buf)
872 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
874 /* If there's anything here, it's because the encoding is UTF-8,
875 * so we can just subtract the buffer length, the same as for
876 * the unencoded data.
879 offset -= channel->encoded_read_buf->len;
882 break;
883 case G_SEEK_SET:
884 case G_SEEK_END:
885 break;
886 default:
887 g_warning ("g_io_channel_seek_position: unknown seek type");
888 return G_IO_STATUS_ERROR;
891 if (channel->use_buffer)
893 status = g_io_channel_flush (channel, error);
894 if (status != G_IO_STATUS_NORMAL)
895 return status;
898 status = channel->funcs->io_seek (channel, offset, type, error);
900 if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
902 if (channel->read_buf)
903 g_string_truncate (channel->read_buf, 0);
905 /* Conversion state no longer matches position in file */
906 if (channel->read_cd != (GIConv) -1)
907 g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
908 if (channel->write_cd != (GIConv) -1)
909 g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
911 if (channel->encoded_read_buf)
913 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
914 g_string_truncate (channel->encoded_read_buf, 0);
917 if (channel->partial_write_buf[0] != '\0')
919 g_warning ("Partial character at end of write buffer not flushed.\n");
920 channel->partial_write_buf[0] = '\0';
924 return status;
928 * g_io_channel_flush:
929 * @channel: a #GIOChannel
930 * @error: location to store an error of type #GIOChannelError
932 * Flushes the write buffer for the GIOChannel.
934 * Return value: the status of the operation: One of
935 * #G_IO_CHANNEL_NORMAL, #G_IO_CHANNEL_AGAIN, or
936 * #G_IO_CHANNEL_ERROR.
938 GIOStatus
939 g_io_channel_flush (GIOChannel *channel,
940 GError **error)
942 GIOStatus status;
943 gsize this_time = 1, bytes_written = 0;
945 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
946 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
948 if (channel->write_buf == NULL || channel->write_buf->len == 0)
949 return G_IO_STATUS_NORMAL;
953 g_assert (this_time > 0);
955 status = channel->funcs->io_write (channel,
956 channel->write_buf->str + bytes_written,
957 channel->write_buf->len - bytes_written,
958 &this_time, error);
959 bytes_written += this_time;
961 while ((bytes_written < channel->write_buf->len)
962 && (status == G_IO_STATUS_NORMAL));
964 g_string_erase (channel->write_buf, 0, bytes_written);
966 return status;
970 * g_io_channel_set_buffered:
971 * @channel: a #GIOChannel
972 * @buffered: whether to set the channel buffered or unbuffered
974 * The buffering state can only be set if the channel's encoding
975 * is %NULL. For any other encoding, the channel must be buffered.
977 * A buffered channel can only be set unbuffered if the channel's
978 * internal buffers have been flushed. Newly created channels or
979 * channels which have returned %G_IO_STATUS_EOF
980 * not require such a flush. For write-only channels, a call to
981 * g_io_channel_flush () is sufficient. For all other channels,
982 * the buffers may be flushed by a call to g_io_channel_seek_position ().
983 * This includes the possibility of seeking with seek type %G_SEEK_CUR
984 * and an offset of zero. Note that this means that socket-based
985 * channels cannot be set unbuffered once they have had data
986 * read from them.
988 * On unbuffered channels, it is safe to mix read and write
989 * calls from the new and old APIs, if this is necessary for
990 * maintaining old code.
992 * The default state of the channel is buffered.
994 void
995 g_io_channel_set_buffered (GIOChannel *channel,
996 gboolean buffered)
998 g_return_if_fail (channel != NULL);
1000 if (channel->encoding != NULL)
1002 g_warning ("Need to have NULL encoding to set the buffering state of the "
1003 "channel.\n");
1004 return;
1007 g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
1008 g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
1010 channel->use_buffer = buffered;
1014 * g_io_channel_get_buffered:
1015 * @channel: a #GIOChannel.
1017 * Returns whether @channel is buffered.
1019 * Return Value: %TRUE if the @channel is buffered.
1021 gboolean
1022 g_io_channel_get_buffered (GIOChannel *channel)
1024 g_return_val_if_fail (channel != NULL, FALSE);
1026 return channel->use_buffer;
1030 * g_io_channel_set_encoding:
1031 * @channel: a #GIOChannel
1032 * @encoding: the encoding type
1033 * @error: location to store an error of type #GConvertError.
1035 * Sets the encoding for the input/output of the channel. The internal
1036 * encoding is always UTF-8. The default encoding for the
1037 * external file is UTF-8.
1039 * The encoding %NULL is safe to use with binary data.
1041 * The encoding can only be set if one of the following conditions
1042 * is true:
1044 * 1. The channel was just created, and has not been written to
1045 * or read from yet.
1047 * 2. The channel is write-only.
1049 * 3. The channel is a file, and the file pointer was just
1050 * repositioned by a call to g_io_channel_seek_position().
1051 * (This flushes all the internal buffers.)
1053 * 4. The current encoding is %NULL or UTF-8.
1055 * 5. One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1056 * (or, in the case of g_io_channel_read_to_end (), %G_IO_STATUS_NORMAL).
1058 * 6. One of the functions g_io_channel_read_chars () or g_io_channel_read_unichar ()
1059 * has returned %G_IO_STATUS_AGAIN or %G_IO_STATUS_ERROR. This may be
1060 * useful in the case of %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1061 * Returning one of these statuses from g_io_channel_read_line (),
1062 * g_io_channel_read_line_string (), or g_io_channel_read_to_end ()
1063 * does <emphasis>not</emphasis> guarantee that the encoding can be changed.
1065 * Channels which do not meet one of the above conditions cannot call
1066 * g_io_channel_seek_position () with an offset of %G_SEEK_CUR,
1067 * and, if they are "seekable", cannot
1068 * call g_io_channel_write_chars () after calling one
1069 * of the API "read" functions.
1071 * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1073 GIOStatus
1074 g_io_channel_set_encoding (GIOChannel *channel,
1075 const gchar *encoding,
1076 GError **error)
1078 GIConv read_cd, write_cd;
1079 gboolean did_encode;
1081 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1082 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1084 /* Make sure the encoded buffers are empty */
1086 g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1087 channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1089 if (!channel->use_buffer)
1091 g_warning ("Need to set the channel buffered before setting the encoding.\n");
1092 g_warning ("Assuming this is what you meant and acting accordingly.\n");
1094 channel->use_buffer = TRUE;
1097 if (channel->partial_write_buf[0] != '\0')
1099 g_warning ("Partial character at end of write buffer not flushed.\n");
1100 channel->partial_write_buf[0] = '\0';
1103 did_encode = channel->do_encode;
1105 if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1107 channel->do_encode = FALSE;
1108 read_cd = write_cd = (GIConv) -1;
1110 else
1112 gint err = 0;
1113 const gchar *from_enc = NULL, *to_enc = NULL;
1115 if (channel->is_readable)
1117 read_cd = g_iconv_open ("UTF-8", encoding);
1119 if (read_cd == (GIConv) -1)
1121 err = errno;
1122 from_enc = "UTF-8";
1123 to_enc = encoding;
1126 else
1127 read_cd = (GIConv) -1;
1129 if (channel->is_writeable && err == 0)
1131 write_cd = g_iconv_open (encoding, "UTF-8");
1133 if (write_cd == (GIConv) -1)
1135 err = errno;
1136 from_enc = encoding;
1137 to_enc = "UTF-8";
1140 else
1141 write_cd = (GIConv) -1;
1143 if (err != 0)
1145 g_assert (from_enc);
1146 g_assert (to_enc);
1148 if (err == EINVAL)
1149 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1150 _("Conversion from character set '%s' to '%s' is not supported"),
1151 from_enc, to_enc);
1152 else
1153 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1154 _("Could not open converter from '%s' to '%s': %s"),
1155 from_enc, to_enc, g_strerror (err));
1157 if (read_cd != (GIConv) -1)
1158 g_iconv_close (read_cd);
1159 if (write_cd != (GIConv) -1)
1160 g_iconv_close (write_cd);
1162 return G_IO_STATUS_ERROR;
1165 channel->do_encode = TRUE;
1168 /* The encoding is ok, so set the fields in channel */
1170 if (channel->read_cd != (GIConv) -1)
1171 g_iconv_close (channel->read_cd);
1172 if (channel->write_cd != (GIConv) -1)
1173 g_iconv_close (channel->write_cd);
1175 if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1177 g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1179 /* This is just validated UTF-8, so we can copy it back into read_buf
1180 * so it can be encoded in whatever the new encoding is.
1183 g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1184 channel->encoded_read_buf->len);
1185 g_string_truncate (channel->encoded_read_buf, 0);
1188 channel->read_cd = read_cd;
1189 channel->write_cd = write_cd;
1191 g_free (channel->encoding);
1192 channel->encoding = g_strdup (encoding);
1194 return G_IO_STATUS_NORMAL;
1198 * g_io_channel_get_encoding:
1199 * @channel: a #GIOChannel
1201 * Gets the encoding for the input/output of the channel. The internal
1202 * encoding is always UTF-8. The encoding %NULL makes the
1203 * channel safe for binary data.
1205 * Return value: A string containing the encoding, this string is
1206 * owned by GLib and must not be freed.
1208 G_CONST_RETURN gchar*
1209 g_io_channel_get_encoding (GIOChannel *channel)
1211 g_return_val_if_fail (channel != NULL, NULL);
1213 return channel->encoding;
1216 static GIOStatus
1217 g_io_channel_fill_buffer (GIOChannel *channel,
1218 GError **err)
1220 gsize read_size, cur_len, oldlen;
1221 GIOStatus status;
1223 if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1225 status = g_io_channel_flush (channel, err);
1226 if (status != G_IO_STATUS_NORMAL)
1227 return status;
1229 if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1231 g_warning ("Partial character at end of write buffer not flushed.\n");
1232 channel->partial_write_buf[0] = '\0';
1235 if (!channel->read_buf)
1236 channel->read_buf = g_string_sized_new (channel->buf_size);
1238 cur_len = channel->read_buf->len;
1240 g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1242 status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1243 channel->buf_size, &read_size, err);
1245 g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1247 g_string_truncate (channel->read_buf, read_size + cur_len);
1249 if ((status != G_IO_STATUS_NORMAL)
1250 && ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1251 return status;
1253 g_assert (channel->read_buf->len > 0);
1255 if (channel->encoded_read_buf)
1256 oldlen = channel->encoded_read_buf->len;
1257 else
1259 oldlen = 0;
1260 if (channel->encoding)
1261 channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1264 if (channel->do_encode)
1266 size_t errnum, inbytes_left, outbytes_left;
1267 gchar *inbuf, *outbuf;
1268 int errval;
1270 g_assert (channel->encoded_read_buf);
1272 reencode:
1274 inbytes_left = channel->read_buf->len;
1275 outbytes_left = MAX (channel->read_buf->len,
1276 channel->encoded_read_buf->allocated_len
1277 - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1278 outbytes_left = MAX (outbytes_left, 6);
1280 inbuf = channel->read_buf->str;
1281 g_string_set_size (channel->encoded_read_buf,
1282 channel->encoded_read_buf->len + outbytes_left);
1283 outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1284 - outbytes_left;
1286 errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1287 &outbuf, &outbytes_left);
1288 errval = errno;
1290 g_assert (inbuf + inbytes_left == channel->read_buf->str
1291 + channel->read_buf->len);
1292 g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1293 + channel->encoded_read_buf->len);
1295 g_string_erase (channel->read_buf, 0,
1296 channel->read_buf->len - inbytes_left);
1297 g_string_truncate (channel->encoded_read_buf,
1298 channel->encoded_read_buf->len - outbytes_left);
1300 if (errnum == (size_t) -1)
1302 switch (errval)
1304 case EINVAL:
1305 if ((oldlen == channel->encoded_read_buf->len)
1306 && (status == G_IO_STATUS_EOF))
1307 status = G_IO_STATUS_EOF;
1308 else
1309 status = G_IO_STATUS_NORMAL;
1310 break;
1311 case E2BIG:
1312 /* Buffer size at least 6, wrote at least on character */
1313 g_assert (inbuf != channel->read_buf->str);
1314 goto reencode;
1315 case EILSEQ:
1316 if (oldlen < channel->encoded_read_buf->len)
1317 status = G_IO_STATUS_NORMAL;
1318 else
1320 g_set_error (err, G_CONVERT_ERROR,
1321 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1322 _("Invalid byte sequence in conversion input"));
1323 return G_IO_STATUS_ERROR;
1325 break;
1326 default:
1327 g_assert (errval != EBADF); /* The converter should be open */
1328 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1329 _("Error during conversion: %s"), g_strerror (errval));
1330 return G_IO_STATUS_ERROR;
1333 g_assert ((status != G_IO_STATUS_NORMAL)
1334 || (channel->encoded_read_buf->len > 0));
1336 else if (channel->encoding) /* UTF-8 */
1338 gchar *nextchar, *lastchar;
1340 g_assert (channel->encoded_read_buf);
1342 nextchar = channel->read_buf->str;
1343 lastchar = channel->read_buf->str + channel->read_buf->len;
1345 while (nextchar < lastchar)
1347 gunichar val_char;
1349 val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1351 switch (val_char)
1353 case -2:
1354 /* stop, leave partial character in buffer */
1355 lastchar = nextchar;
1356 break;
1357 case -1:
1358 if (oldlen < channel->encoded_read_buf->len)
1359 status = G_IO_STATUS_NORMAL;
1360 else
1362 g_set_error (err, G_CONVERT_ERROR,
1363 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1364 _("Invalid byte sequence in conversion input"));
1365 status = G_IO_STATUS_ERROR;
1367 lastchar = nextchar;
1368 break;
1369 default:
1370 nextchar = g_utf8_next_char (nextchar);
1371 break;
1375 if (lastchar > channel->read_buf->str)
1377 gint copy_len = lastchar - channel->read_buf->str;
1379 g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1380 copy_len);
1381 g_string_erase (channel->read_buf, 0, copy_len);
1385 return status;
1389 * g_io_channel_read_line:
1390 * @channel: a #GIOChannel
1391 * @str_return: The line read from the #GIOChannel, including the
1392 * line terminator. This data should be freed with g_free()
1393 * when no longer needed. This is a nul-terminated string.
1394 * If a @length of zero is returned, this will be %NULL instead.
1395 * @length: location to store length of the read data, or %NULL
1396 * @terminator_pos: location to store position of line terminator, or %NULL
1397 * @error: A location to return an error of type #GConvertError
1398 * or #GIOChannelError
1400 * Reads a line, including the terminating character(s),
1401 * from a #GIOChannel into a newly-allocated string.
1402 * @str_return will contain allocated memory if the return
1403 * is %G_IO_STATUS_NORMAL.
1405 * Return value: the status of the operation.
1407 GIOStatus
1408 g_io_channel_read_line (GIOChannel *channel,
1409 gchar **str_return,
1410 gsize *length,
1411 gsize *terminator_pos,
1412 GError **error)
1414 GIOStatus status;
1415 gsize got_length;
1417 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1418 g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1419 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1420 G_IO_STATUS_ERROR);
1421 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1423 status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1425 if (length)
1426 *length = got_length;
1428 if (status == G_IO_STATUS_NORMAL)
1430 g_assert (USE_BUF (channel));
1431 *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1432 g_string_erase (USE_BUF (channel), 0, got_length);
1434 else
1435 *str_return = NULL;
1437 return status;
1441 * g_io_channel_read_line_string:
1442 * @channel: a #GIOChannel
1443 * @buffer: a #GString into which the line will be written.
1444 * If @buffer already contains data, the old data will
1445 * be overwritten.
1446 * @terminator_pos: location to store position of line terminator, or %NULL
1447 * @error: a location to store an error of type #GConvertError
1448 * or #GIOChannelError
1450 * Reads a line from a #GIOChannel, using a #GString as a buffer.
1452 * Return value: the status of the operation.
1454 GIOStatus
1455 g_io_channel_read_line_string (GIOChannel *channel,
1456 GString *buffer,
1457 gsize *terminator_pos,
1458 GError **error)
1460 gsize length;
1461 GIOStatus status;
1463 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1464 g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1465 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1466 G_IO_STATUS_ERROR);
1467 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1469 if (buffer->len > 0)
1470 g_string_truncate (buffer, 0); /* clear out the buffer */
1472 status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1474 if (status == G_IO_STATUS_NORMAL)
1476 g_assert (USE_BUF (channel));
1477 g_string_append_len (buffer, USE_BUF (channel)->str, length);
1478 g_string_erase (USE_BUF (channel), 0, length);
1481 return status;
1485 static GIOStatus
1486 g_io_channel_read_line_backend (GIOChannel *channel,
1487 gsize *length,
1488 gsize *terminator_pos,
1489 GError **error)
1491 GIOStatus status;
1492 gsize checked_to, line_term_len, line_length, got_term_len;
1493 gboolean first_time = TRUE;
1495 if (!channel->use_buffer)
1497 /* Can't do a raw read in read_line */
1498 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1499 _("Can't do a raw read in g_io_channel_read_line_string"));
1500 return G_IO_STATUS_ERROR;
1503 status = G_IO_STATUS_NORMAL;
1505 if (channel->line_term)
1506 line_term_len = channel->line_term_len;
1507 else
1508 line_term_len = 3;
1509 /* This value used for setting checked_to, it's the longest of the four
1510 * we autodetect for.
1513 checked_to = 0;
1515 while (TRUE)
1517 gchar *nextchar, *lastchar;
1518 GString *use_buf;
1520 if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1522 read_again:
1523 status = g_io_channel_fill_buffer (channel, error);
1524 switch (status)
1526 case G_IO_STATUS_NORMAL:
1527 if (BUF_LEN (USE_BUF (channel)) == 0)
1528 /* Can happen when using conversion and only read
1529 * part of a character
1532 first_time = FALSE;
1533 continue;
1535 break;
1536 case G_IO_STATUS_EOF:
1537 if (BUF_LEN (USE_BUF (channel)) == 0)
1539 if (length)
1540 *length = 0;
1542 if (channel->encoding && channel->read_buf->len != 0)
1544 g_set_error (error, G_CONVERT_ERROR,
1545 G_CONVERT_ERROR_PARTIAL_INPUT,
1546 _("Leftover unconverted data in read buffer"));
1547 return G_IO_STATUS_ERROR;
1549 else
1550 return G_IO_STATUS_EOF;
1552 break;
1553 default:
1554 if (length)
1555 *length = 0;
1556 return status;
1560 g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1562 use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1564 first_time = FALSE;
1566 lastchar = use_buf->str + use_buf->len;
1568 for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1569 channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1571 if (channel->line_term)
1573 if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1575 line_length = nextchar - use_buf->str;
1576 got_term_len = line_term_len;
1577 goto done;
1580 else /* auto detect */
1582 switch (*nextchar)
1584 case '\n': /* unix */
1585 line_length = nextchar - use_buf->str;
1586 got_term_len = 1;
1587 goto done;
1588 case '\r': /* Warning: do not use with sockets */
1589 line_length = nextchar - use_buf->str;
1590 if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1591 && (lastchar == use_buf->str + use_buf->len))
1592 goto read_again; /* Try to read more data */
1593 if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1594 got_term_len = 2;
1595 else /* mac */
1596 got_term_len = 1;
1597 goto done;
1598 case '\xe2': /* Unicode paragraph separator */
1599 if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1601 line_length = nextchar - use_buf->str;
1602 got_term_len = 3;
1603 goto done;
1605 break;
1606 case '\0': /* Embeded null in input */
1607 line_length = nextchar - use_buf->str;
1608 got_term_len = 1;
1609 goto done;
1610 default: /* no match */
1611 break;
1616 /* If encoding != NULL, valid UTF-8, didn't overshoot */
1617 g_assert (nextchar == lastchar);
1619 /* Check for EOF */
1621 if (status == G_IO_STATUS_EOF)
1623 if (channel->encoding && channel->read_buf->len > 0)
1625 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1626 _("Channel terminates in a partial character"));
1627 return G_IO_STATUS_ERROR;
1629 line_length = use_buf->len;
1630 got_term_len = 0;
1631 break;
1634 if (use_buf->len > line_term_len - 1)
1635 checked_to = use_buf->len - (line_term_len - 1);
1636 else
1637 checked_to = 0;
1640 done:
1642 if (terminator_pos)
1643 *terminator_pos = line_length;
1645 if (length)
1646 *length = line_length + got_term_len;
1648 return G_IO_STATUS_NORMAL;
1652 * g_io_channel_read_to_end:
1653 * @channel: a #GIOChannel
1654 * @str_return: Location to store a pointer to a string holding
1655 * the remaining data in the #GIOChannel. This data should
1656 * be freed with g_free() when no longer needed. This
1657 * data is terminated by an extra nul character, but there
1658 * may be other nuls in the intervening data.
1659 * @length: Location to store length of the data
1660 * @error: A location to return an error of type #GConvertError
1661 * or #GIOChannelError
1663 * Reads all the remaining data from the file.
1665 * Return value: %G_IO_STATUS_NORMAL on success.
1666 * This function never returns %G_IO_STATUS_EOF.
1668 GIOStatus
1669 g_io_channel_read_to_end (GIOChannel *channel,
1670 gchar **str_return,
1671 gsize *length,
1672 GError **error)
1674 GIOStatus status;
1676 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1677 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1678 G_IO_STATUS_ERROR);
1679 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1681 if (str_return)
1682 *str_return = NULL;
1683 if (length)
1684 *length = 0;
1686 if (!channel->use_buffer)
1688 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1689 _("Can't do a raw read in g_io_channel_read_to_end"));
1690 return G_IO_STATUS_ERROR;
1694 status = g_io_channel_fill_buffer (channel, error);
1695 while (status == G_IO_STATUS_NORMAL);
1697 if (status != G_IO_STATUS_EOF)
1698 return status;
1700 if (channel->encoding && channel->read_buf->len > 0)
1702 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1703 _("Channel terminates in a partial character"));
1704 return G_IO_STATUS_ERROR;
1707 if (USE_BUF (channel) == NULL)
1709 /* length is already set to zero */
1710 if (str_return)
1711 *str_return = g_strdup ("");
1713 else
1715 if (length)
1716 *length = USE_BUF (channel)->len;
1718 if (str_return)
1719 *str_return = g_string_free (USE_BUF (channel), FALSE);
1720 else
1721 g_string_free (USE_BUF (channel), TRUE);
1723 if (channel->encoding)
1724 channel->encoded_read_buf = NULL;
1725 else
1726 channel->read_buf = NULL;
1729 return G_IO_STATUS_NORMAL;
1733 * g_io_channel_read_chars:
1734 * @channel: a #GIOChannel
1735 * @buf: a buffer to read data into
1736 * @count: the size of the buffer. Note that the buffer may
1737 * not be complelely filled even if there is data
1738 * in the buffer if the remaining data is not a
1739 * complete character.
1740 * @bytes_read: The number of bytes read. This may be zero even on
1741 * success if count < 6 and the channel's encoding is non-%NULL.
1742 * This indicates that the next UTF-8 character is too wide for
1743 * the buffer.
1744 * @error: A location to return an error of type #GConvertError
1745 * or #GIOChannelError.
1747 * Replacement for g_io_channel_read() with the new API.
1749 * Return value: the status of the operation.
1751 GIOStatus
1752 g_io_channel_read_chars (GIOChannel *channel,
1753 gchar *buf,
1754 gsize count,
1755 gsize *bytes_read,
1756 GError **error)
1758 GIOStatus status;
1759 gsize got_bytes;
1761 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1762 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1763 G_IO_STATUS_ERROR);
1764 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1766 if (count == 0)
1768 *bytes_read = 0;
1769 return G_IO_STATUS_NORMAL;
1771 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1773 if (!channel->use_buffer)
1775 gsize tmp_bytes;
1777 g_assert (!channel->read_buf || channel->read_buf->len == 0);
1779 status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
1781 if (bytes_read)
1782 *bytes_read = tmp_bytes;
1784 return status;
1787 status = G_IO_STATUS_NORMAL;
1789 while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
1790 status = g_io_channel_fill_buffer (channel, error);
1792 /* Only return an error if we have no data */
1794 if (BUF_LEN (USE_BUF (channel)) == 0)
1796 g_assert (status != G_IO_STATUS_NORMAL);
1798 if (status == G_IO_STATUS_EOF && channel->encoding
1799 && BUF_LEN (channel->read_buf) > 0)
1801 g_set_error (error, G_CONVERT_ERROR,
1802 G_CONVERT_ERROR_PARTIAL_INPUT,
1803 _("Leftover unconverted data in read buffer"));
1804 status = G_IO_STATUS_ERROR;
1807 if (bytes_read)
1808 *bytes_read = 0;
1810 return status;
1813 if (status == G_IO_STATUS_ERROR)
1814 g_clear_error (error);
1816 got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
1818 g_assert (got_bytes > 0);
1820 if (channel->encoding)
1821 /* Don't validate for NULL encoding, binary safe */
1823 gchar *nextchar, *prevchar;
1825 g_assert (USE_BUF (channel) == channel->encoded_read_buf);
1827 nextchar = channel->encoded_read_buf->str;
1831 prevchar = nextchar;
1832 nextchar = g_utf8_next_char (nextchar);
1833 g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
1835 while (nextchar < channel->encoded_read_buf->str + got_bytes);
1837 if (nextchar > channel->encoded_read_buf->str + got_bytes)
1838 got_bytes = prevchar - channel->encoded_read_buf->str;
1840 g_assert (got_bytes > 0 || count < 6);
1843 memcpy (buf, USE_BUF (channel)->str, got_bytes);
1844 g_string_erase (USE_BUF (channel), 0, got_bytes);
1846 if (bytes_read)
1847 *bytes_read = got_bytes;
1849 return G_IO_STATUS_NORMAL;
1853 * g_io_channel_read_unichar:
1854 * @channel: a #GIOChannel
1855 * @thechar: a location to return a character
1856 * @error: A location to return an error of type #GConvertError
1857 * or #GIOChannelError
1859 * This function cannot be called on a channel with %NULL encoding.
1861 * Return value: a #GIOStatus
1863 GIOStatus
1864 g_io_channel_read_unichar (GIOChannel *channel,
1865 gunichar *thechar,
1866 GError **error)
1868 GIOStatus status = G_IO_STATUS_NORMAL;
1870 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1871 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
1872 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1873 G_IO_STATUS_ERROR);
1874 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1876 while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
1877 status = g_io_channel_fill_buffer (channel, error);
1879 /* Only return an error if we have no data */
1881 if (BUF_LEN (USE_BUF (channel)) == 0)
1883 g_assert (status != G_IO_STATUS_NORMAL);
1885 if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
1887 g_set_error (error, G_CONVERT_ERROR,
1888 G_CONVERT_ERROR_PARTIAL_INPUT,
1889 _("Leftover unconverted data in read buffer"));
1890 status = G_IO_STATUS_ERROR;
1893 if (thechar)
1894 *thechar = (gunichar) -1;
1896 return status;
1899 if (status == G_IO_STATUS_ERROR)
1900 g_clear_error (error);
1902 if (thechar)
1903 *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
1905 g_string_erase (channel->encoded_read_buf, 0,
1906 g_utf8_next_char (channel->encoded_read_buf->str)
1907 - channel->encoded_read_buf->str);
1909 return G_IO_STATUS_NORMAL;
1913 * g_io_channel_write_chars:
1914 * @channel: a #GIOChannel
1915 * @buf: a buffer to write data from
1916 * @count: the size of the buffer. If -1, the buffer
1917 * is taken to be a nul-terminated string.
1918 * @bytes_written: The number of bytes written. This can be nonzero
1919 * even if the return value is not %G_IO_STATUS_NORMAL.
1920 * If the return value is %G_IO_STATUS_NORMAL and the
1921 * channel is blocking, this will always be equal
1922 * to @count if @count >= 0.
1923 * @error: A location to return an error of type #GConvertError
1924 * or #GIOChannelError
1926 * Replacement for g_io_channel_write() with the new API.
1928 * On seekable channels with encodings other than %NULL or UTF-8, generic
1929 * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
1930 * may only be made on a channel from which data has been read in the
1931 * cases described in the documentation for g_io_channel_set_encoding ().
1933 * Return value: the status of the operation.
1935 GIOStatus
1936 g_io_channel_write_chars (GIOChannel *channel,
1937 const gchar *buf,
1938 gssize count,
1939 gsize *bytes_written,
1940 GError **error)
1942 GIOStatus status;
1943 gssize wrote_bytes = 0;
1945 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1946 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1947 G_IO_STATUS_ERROR);
1948 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
1950 if ((count < 0) && buf)
1951 count = strlen (buf);
1953 if (count == 0)
1955 if (bytes_written)
1956 *bytes_written = 0;
1957 return G_IO_STATUS_NORMAL;
1960 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
1961 g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
1963 /* Raw write case */
1965 if (!channel->use_buffer)
1967 gsize tmp_bytes;
1969 g_assert (!channel->write_buf || channel->write_buf->len == 0);
1970 g_assert (channel->partial_write_buf[0] == '\0');
1972 status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
1974 if (bytes_written)
1975 *bytes_written = tmp_bytes;
1977 return status;
1980 /* General case */
1982 if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
1983 || (BUF_LEN (channel->encoded_read_buf) > 0)))
1985 if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
1987 g_warning("Mixed reading and writing not allowed on encoded files");
1988 return G_IO_STATUS_ERROR;
1990 status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
1991 if (status != G_IO_STATUS_NORMAL)
1993 if (bytes_written)
1994 *bytes_written = 0;
1995 return status;
1999 if (!channel->write_buf)
2000 channel->write_buf = g_string_sized_new (channel->buf_size);
2002 while (wrote_bytes < count)
2004 gsize space_in_buf;
2006 /* If the buffer is full, try a write immediately. In
2007 * the nonblocking case, this prevents the user from
2008 * writing just a little bit to the buffer every time
2009 * and never receiving an EAGAIN.
2012 if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2014 gsize did_write = 0, this_time;
2018 status = channel->funcs->io_write (channel, channel->write_buf->str
2019 + did_write, channel->write_buf->len
2020 - did_write, &this_time, error);
2021 did_write += this_time;
2023 while (status == G_IO_STATUS_NORMAL &&
2024 did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2026 g_string_erase (channel->write_buf, 0, did_write);
2028 if (status != G_IO_STATUS_NORMAL)
2030 if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2031 status = G_IO_STATUS_NORMAL;
2032 if (bytes_written)
2033 *bytes_written = wrote_bytes;
2034 return status;
2038 space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2039 - channel->write_buf->len; /* 1 for NULL */
2041 /* This is only true because g_io_channel_set_buffer_size ()
2042 * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2044 g_assert (space_in_buf >= MAX_CHAR_SIZE);
2046 if (!channel->encoding)
2048 gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2050 g_string_append_len (channel->write_buf, buf, write_this);
2051 buf += write_this;
2052 wrote_bytes += write_this;
2054 else
2056 const gchar *from_buf;
2057 gsize from_buf_len, from_buf_old_len, left_len;
2058 size_t err;
2059 gint errnum;
2061 if (channel->partial_write_buf[0] != '\0')
2063 g_assert (wrote_bytes == 0);
2065 from_buf = channel->partial_write_buf;
2066 from_buf_old_len = strlen (channel->partial_write_buf);
2067 g_assert (from_buf_old_len > 0);
2068 from_buf_len = MIN (6, from_buf_old_len + count);
2070 memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2071 from_buf_len - from_buf_old_len);
2073 else
2075 from_buf = buf;
2076 from_buf_len = count - wrote_bytes;
2077 from_buf_old_len = 0;
2080 reconvert:
2082 if (!channel->do_encode) /* UTF-8 encoding */
2084 const gchar *badchar;
2085 gsize try_len = MIN (from_buf_len, space_in_buf);
2087 /* UTF-8, just validate, emulate g_iconv */
2089 if (!g_utf8_validate (from_buf, try_len, &badchar))
2091 gunichar try_char;
2092 gsize incomplete_len = from_buf + try_len - badchar;
2094 left_len = from_buf + from_buf_len - badchar;
2096 try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2098 switch (try_char)
2100 case -2:
2101 g_assert (incomplete_len < 6);
2102 if (try_len == from_buf_len)
2104 errnum = EINVAL;
2105 err = (size_t) -1;
2107 else
2109 errnum = 0;
2110 err = (size_t) 0;
2112 break;
2113 case -1:
2114 g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2115 /* FIXME bail here? */
2116 errnum = EILSEQ;
2117 err = (size_t) -1;
2118 break;
2119 default:
2120 g_assert_not_reached ();
2121 err = (size_t) -1;
2122 errnum = 0; /* Don't confunse the compiler */
2125 else
2127 err = (size_t) 0;
2128 errnum = 0;
2129 left_len = from_buf_len - try_len;
2132 g_string_append_len (channel->write_buf, from_buf,
2133 from_buf_len - left_len);
2134 from_buf += from_buf_len - left_len;
2136 else
2138 gchar *outbuf;
2140 left_len = from_buf_len;
2141 g_string_set_size (channel->write_buf, channel->write_buf->len
2142 + space_in_buf);
2143 outbuf = channel->write_buf->str + channel->write_buf->len
2144 - space_in_buf;
2145 err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2146 &outbuf, &space_in_buf);
2147 errnum = errno;
2148 g_string_truncate (channel->write_buf, channel->write_buf->len
2149 - space_in_buf);
2152 if (err == (size_t) -1)
2154 switch (errnum)
2156 case EINVAL:
2157 g_assert (left_len < 6);
2159 if (from_buf_old_len == 0)
2161 /* Not from partial_write_buf */
2163 memcpy (channel->partial_write_buf, from_buf, left_len);
2164 channel->partial_write_buf[left_len] = '\0';
2165 if (bytes_written)
2166 *bytes_written = count;
2167 return G_IO_STATUS_NORMAL;
2170 /* Working in partial_write_buf */
2172 if (left_len == from_buf_len)
2174 /* Didn't convert anything, must still have
2175 * less than a full character
2178 g_assert (count == from_buf_len - from_buf_old_len);
2180 channel->partial_write_buf[from_buf_len] = '\0';
2182 if (bytes_written)
2183 *bytes_written = count;
2185 return G_IO_STATUS_NORMAL;
2188 g_assert (from_buf_len - left_len >= from_buf_old_len);
2190 /* We converted all the old data. This is fine */
2192 break;
2193 case E2BIG:
2194 if (from_buf_len == left_len)
2196 /* Nothing was written, add enough space for
2197 * at least one character.
2199 space_in_buf += MAX_CHAR_SIZE;
2200 goto reconvert;
2202 break;
2203 case EILSEQ:
2204 g_set_error (error, G_CONVERT_ERROR,
2205 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2206 _("Invalid byte sequence in conversion input"));
2207 if (from_buf_old_len > 0 && from_buf_len == left_len)
2208 g_warning ("Illegal sequence due to partial character "
2209 "at the end of a previous write.\n");
2210 else
2211 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2212 if (bytes_written)
2213 *bytes_written = wrote_bytes;
2214 channel->partial_write_buf[0] = '\0';
2215 return G_IO_STATUS_ERROR;
2216 default:
2217 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2218 _("Error during conversion: %s"), g_strerror (errnum));
2219 if (from_buf_len >= left_len + from_buf_old_len)
2220 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2221 if (bytes_written)
2222 *bytes_written = wrote_bytes;
2223 channel->partial_write_buf[0] = '\0';
2224 return G_IO_STATUS_ERROR;
2228 g_assert (from_buf_len - left_len >= from_buf_old_len);
2230 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2232 if (from_buf_old_len > 0)
2234 /* We were working in partial_write_buf */
2236 buf += from_buf_len - left_len - from_buf_old_len;
2237 channel->partial_write_buf[0] = '\0';
2239 else
2240 buf = from_buf;
2244 if (bytes_written)
2245 *bytes_written = count;
2247 return G_IO_STATUS_NORMAL;
2251 * g_io_channel_write_unichar:
2252 * @channel: a #GIOChannel
2253 * @thechar: a character
2254 * @error: A location to return an error of type #GConvertError
2255 * or #GIOChannelError
2257 * This function cannot be called on a channel with %NULL encoding.
2259 * Return value: a #GIOStatus
2261 GIOStatus
2262 g_io_channel_write_unichar (GIOChannel *channel,
2263 gunichar thechar,
2264 GError **error)
2266 GIOStatus status;
2267 gchar static_buf[6];
2268 gsize char_len, wrote_len;
2270 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2271 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2272 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2273 G_IO_STATUS_ERROR);
2274 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2276 char_len = g_unichar_to_utf8 (thechar, static_buf);
2278 if (channel->partial_write_buf[0] != '\0')
2280 g_warning ("Partial charater written before writing unichar.\n");
2281 channel->partial_write_buf[0] = '\0';
2284 status = g_io_channel_write_chars (channel, static_buf,
2285 char_len, &wrote_len, error);
2287 /* We validate UTF-8, so we can't get a partial write */
2289 g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2291 return status;
2295 * g_io_channel_error_quark:
2297 * Return value: The quark used as %G_IO_CHANNEL_ERROR
2299 GQuark
2300 g_io_channel_error_quark (void)
2302 return g_quark_from_static_string ("g-io-channel-error-quark");
2305 #define __G_IOCHANNEL_C__
2306 #include "galiasdef.c"