tests: Fix leak when checking for du binary
[glib.git] / glib / giochannel.c
blobd8c3b0b090e1c8acfd6b4f6f991b81137de60544
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.1 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, see <http://www.gnu.org/licenses/>.
22 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
23 * file for a list of people on the GLib Team. See the ChangeLog
24 * files for a list of changes. These files are distributed with
25 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 /*
29 * MT safe
32 #include "config.h"
34 #include <string.h>
35 #include <errno.h>
37 #include "giochannel.h"
39 #include "gstrfuncs.h"
40 #include "gtestutils.h"
41 #include "glibintl.h"
44 /**
45 * SECTION:iochannels
46 * @title: IO Channels
47 * @short_description: portable support for using files, pipes and sockets
48 * @see_also: g_io_add_watch(), g_io_add_watch_full(), g_source_remove(),
49 * #GMainLoop
51 * The #GIOChannel data type aims to provide a portable method for
52 * using file descriptors, pipes, and sockets, and integrating them
53 * into the [main event loop][glib-The-Main-Event-Loop]. Currently,
54 * full support is available on UNIX platforms, support for Windows
55 * is only partially complete.
57 * To create a new #GIOChannel on UNIX systems use
58 * g_io_channel_unix_new(). This works for plain file descriptors,
59 * pipes and sockets. Alternatively, a channel can be created for a
60 * file in a system independent manner using g_io_channel_new_file().
62 * Once a #GIOChannel has been created, it can be used in a generic
63 * manner with the functions g_io_channel_read_chars(),
64 * g_io_channel_write_chars(), g_io_channel_seek_position(), and
65 * g_io_channel_shutdown().
67 * To add a #GIOChannel to the [main event loop][glib-The-Main-Event-Loop],
68 * use g_io_add_watch() or g_io_add_watch_full(). Here you specify which
69 * events you are interested in on the #GIOChannel, and provide a
70 * function to be called whenever these events occur.
72 * #GIOChannel instances are created with an initial reference count of 1.
73 * g_io_channel_ref() and g_io_channel_unref() can be used to
74 * increment or decrement the reference count respectively. When the
75 * reference count falls to 0, the #GIOChannel is freed. (Though it
76 * isn't closed automatically, unless it was created using
77 * g_io_channel_new_file().) Using g_io_add_watch() or
78 * g_io_add_watch_full() increments a channel's reference count.
80 * The new functions g_io_channel_read_chars(),
81 * g_io_channel_read_line(), g_io_channel_read_line_string(),
82 * g_io_channel_read_to_end(), g_io_channel_write_chars(),
83 * g_io_channel_seek_position(), and g_io_channel_flush() should not be
84 * mixed with the deprecated functions g_io_channel_read(),
85 * g_io_channel_write(), and g_io_channel_seek() on the same channel.
86 **/
88 /**
89 * GIOChannel:
91 * A data structure representing an IO Channel. The fields should be
92 * considered private and should only be accessed with the following
93 * functions.
94 **/
96 /**
97 * GIOFuncs:
98 * @io_read: reads raw bytes from the channel. This is called from
99 * various functions such as g_io_channel_read_chars() to
100 * read raw bytes from the channel. Encoding and buffering
101 * issues are dealt with at a higher level.
102 * @io_write: writes raw bytes to the channel. This is called from
103 * various functions such as g_io_channel_write_chars() to
104 * write raw bytes to the channel. Encoding and buffering
105 * issues are dealt with at a higher level.
106 * @io_seek: (optional) seeks the channel. This is called from
107 * g_io_channel_seek() on channels that support it.
108 * @io_close: closes the channel. This is called from
109 * g_io_channel_close() after flushing the buffers.
110 * @io_create_watch: creates a watch on the channel. This call
111 * corresponds directly to g_io_create_watch().
112 * @io_free: called from g_io_channel_unref() when the channel needs to
113 * be freed. This function must free the memory associated
114 * with the channel, including freeing the #GIOChannel
115 * structure itself. The channel buffers have been flushed
116 * and possibly @io_close has been called by the time this
117 * function is called.
118 * @io_set_flags: sets the #GIOFlags on the channel. This is called
119 * from g_io_channel_set_flags() with all flags except
120 * for %G_IO_FLAG_APPEND and %G_IO_FLAG_NONBLOCK masked
121 * out.
122 * @io_get_flags: gets the #GIOFlags for the channel. This function
123 * need only return the %G_IO_FLAG_APPEND and
124 * %G_IO_FLAG_NONBLOCK flags; g_io_channel_get_flags()
125 * automatically adds the others as appropriate.
127 * A table of functions used to handle different types of #GIOChannel
128 * in a generic way.
132 * GIOStatus:
133 * @G_IO_STATUS_ERROR: An error occurred.
134 * @G_IO_STATUS_NORMAL: Success.
135 * @G_IO_STATUS_EOF: End of file.
136 * @G_IO_STATUS_AGAIN: Resource temporarily unavailable.
138 * Stati returned by most of the #GIOFuncs functions.
142 * GIOError:
143 * @G_IO_ERROR_NONE: no error
144 * @G_IO_ERROR_AGAIN: an EAGAIN error occurred
145 * @G_IO_ERROR_INVAL: an EINVAL error occurred
146 * @G_IO_ERROR_UNKNOWN: another error occurred
148 * #GIOError is only used by the deprecated functions
149 * g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().
152 #define G_IO_NICE_BUF_SIZE 1024
154 /* This needs to be as wide as the largest character in any possible encoding */
155 #define MAX_CHAR_SIZE 10
157 /* Some simplifying macros, which reduce the need to worry whether the
158 * buffers have been allocated. These also make USE_BUF () an lvalue,
159 * which is used in g_io_channel_read_to_end ().
161 #define USE_BUF(channel) ((channel)->encoding ? (channel)->encoded_read_buf \
162 : (channel)->read_buf)
163 #define BUF_LEN(string) ((string) ? (string)->len : 0)
165 static GIOError g_io_error_get_from_g_error (GIOStatus status,
166 GError *err);
167 static void g_io_channel_purge (GIOChannel *channel);
168 static GIOStatus g_io_channel_fill_buffer (GIOChannel *channel,
169 GError **err);
170 static GIOStatus g_io_channel_read_line_backend (GIOChannel *channel,
171 gsize *length,
172 gsize *terminator_pos,
173 GError **error);
176 * g_io_channel_init:
177 * @channel: a #GIOChannel
179 * Initializes a #GIOChannel struct.
181 * This is called by each of the above functions when creating a
182 * #GIOChannel, and so is not often needed by the application
183 * programmer (unless you are creating a new type of #GIOChannel).
185 void
186 g_io_channel_init (GIOChannel *channel)
188 channel->ref_count = 1;
189 channel->encoding = g_strdup ("UTF-8");
190 channel->line_term = NULL;
191 channel->line_term_len = 0;
192 channel->buf_size = G_IO_NICE_BUF_SIZE;
193 channel->read_cd = (GIConv) -1;
194 channel->write_cd = (GIConv) -1;
195 channel->read_buf = NULL; /* Lazy allocate buffers */
196 channel->encoded_read_buf = NULL;
197 channel->write_buf = NULL;
198 channel->partial_write_buf[0] = '\0';
199 channel->use_buffer = TRUE;
200 channel->do_encode = FALSE;
201 channel->close_on_unref = FALSE;
205 * g_io_channel_ref:
206 * @channel: a #GIOChannel
208 * Increments the reference count of a #GIOChannel.
210 * Returns: the @channel that was passed in (since 2.6)
212 GIOChannel *
213 g_io_channel_ref (GIOChannel *channel)
215 g_return_val_if_fail (channel != NULL, NULL);
217 g_atomic_int_inc (&channel->ref_count);
219 return channel;
223 * g_io_channel_unref:
224 * @channel: a #GIOChannel
226 * Decrements the reference count of a #GIOChannel.
228 void
229 g_io_channel_unref (GIOChannel *channel)
231 gboolean is_zero;
233 g_return_if_fail (channel != NULL);
235 is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
237 if (G_UNLIKELY (is_zero))
239 if (channel->close_on_unref)
240 g_io_channel_shutdown (channel, TRUE, NULL);
241 else
242 g_io_channel_purge (channel);
243 g_free (channel->encoding);
244 if (channel->read_cd != (GIConv) -1)
245 g_iconv_close (channel->read_cd);
246 if (channel->write_cd != (GIConv) -1)
247 g_iconv_close (channel->write_cd);
248 g_free (channel->line_term);
249 if (channel->read_buf)
250 g_string_free (channel->read_buf, TRUE);
251 if (channel->write_buf)
252 g_string_free (channel->write_buf, TRUE);
253 if (channel->encoded_read_buf)
254 g_string_free (channel->encoded_read_buf, TRUE);
255 channel->funcs->io_free (channel);
259 static GIOError
260 g_io_error_get_from_g_error (GIOStatus status,
261 GError *err)
263 switch (status)
265 case G_IO_STATUS_NORMAL:
266 case G_IO_STATUS_EOF:
267 return G_IO_ERROR_NONE;
268 case G_IO_STATUS_AGAIN:
269 return G_IO_ERROR_AGAIN;
270 case G_IO_STATUS_ERROR:
271 g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
273 if (err->domain != G_IO_CHANNEL_ERROR)
274 return G_IO_ERROR_UNKNOWN;
275 switch (err->code)
277 case G_IO_CHANNEL_ERROR_INVAL:
278 return G_IO_ERROR_INVAL;
279 default:
280 return G_IO_ERROR_UNKNOWN;
282 default:
283 g_assert_not_reached ();
288 * g_io_channel_read:
289 * @channel: a #GIOChannel
290 * @buf: a buffer to read the data into (which should be at least
291 * count bytes long)
292 * @count: the number of bytes to read from the #GIOChannel
293 * @bytes_read: returns the number of bytes actually read
295 * Reads data from a #GIOChannel.
297 * Returns: %G_IO_ERROR_NONE if the operation was successful.
299 * Deprecated:2.2: Use g_io_channel_read_chars() instead.
301 GIOError
302 g_io_channel_read (GIOChannel *channel,
303 gchar *buf,
304 gsize count,
305 gsize *bytes_read)
307 GError *err = NULL;
308 GIOError error;
309 GIOStatus status;
311 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
312 g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
314 if (count == 0)
316 if (bytes_read)
317 *bytes_read = 0;
318 return G_IO_ERROR_NONE;
321 g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
323 status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
325 error = g_io_error_get_from_g_error (status, err);
327 if (err)
328 g_error_free (err);
330 return error;
334 * g_io_channel_write:
335 * @channel: a #GIOChannel
336 * @buf: the buffer containing the data to write
337 * @count: the number of bytes to write
338 * @bytes_written: the number of bytes actually written
340 * Writes data to a #GIOChannel.
342 * Returns: %G_IO_ERROR_NONE if the operation was successful.
344 * Deprecated:2.2: Use g_io_channel_write_chars() instead.
346 GIOError
347 g_io_channel_write (GIOChannel *channel,
348 const gchar *buf,
349 gsize count,
350 gsize *bytes_written)
352 GError *err = NULL;
353 GIOError error;
354 GIOStatus status;
356 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
357 g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
359 status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
361 error = g_io_error_get_from_g_error (status, err);
363 if (err)
364 g_error_free (err);
366 return error;
370 * g_io_channel_seek:
371 * @channel: a #GIOChannel
372 * @offset: an offset, in bytes, which is added to the position specified
373 * by @type
374 * @type: the position in the file, which can be %G_SEEK_CUR (the current
375 * position), %G_SEEK_SET (the start of the file), or %G_SEEK_END
376 * (the end of the file)
378 * Sets the current position in the #GIOChannel, similar to the standard
379 * library function fseek().
381 * Returns: %G_IO_ERROR_NONE if the operation was successful.
383 * Deprecated:2.2: Use g_io_channel_seek_position() instead.
385 GIOError
386 g_io_channel_seek (GIOChannel *channel,
387 gint64 offset,
388 GSeekType type)
390 GError *err = NULL;
391 GIOError error;
392 GIOStatus status;
394 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
395 g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
397 switch (type)
399 case G_SEEK_CUR:
400 case G_SEEK_SET:
401 case G_SEEK_END:
402 break;
403 default:
404 g_warning ("g_io_channel_seek: unknown seek type");
405 return G_IO_ERROR_UNKNOWN;
408 status = channel->funcs->io_seek (channel, offset, type, &err);
410 error = g_io_error_get_from_g_error (status, err);
412 if (err)
413 g_error_free (err);
415 return error;
418 /* The function g_io_channel_new_file() is prototyped in both
419 * giounix.c and giowin32.c, so we stick its documentation here.
423 * g_io_channel_new_file:
424 * @filename: (type filename): A string containing the name of a file
425 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
426 * the same meaning as in fopen()
427 * @error: A location to return an error of type %G_FILE_ERROR
429 * Open a file @filename as a #GIOChannel using mode @mode. This
430 * channel will be closed when the last reference to it is dropped,
431 * so there is no need to call g_io_channel_close() (though doing
432 * so will not cause problems, as long as no attempt is made to
433 * access the channel after it is closed).
435 * Returns: A #GIOChannel on success, %NULL on failure.
439 * g_io_channel_close:
440 * @channel: A #GIOChannel
442 * Close an IO channel. Any pending data to be written will be
443 * flushed, ignoring errors. The channel will not be freed until the
444 * last reference is dropped using g_io_channel_unref().
446 * Deprecated:2.2: Use g_io_channel_shutdown() instead.
448 void
449 g_io_channel_close (GIOChannel *channel)
451 GError *err = NULL;
453 g_return_if_fail (channel != NULL);
455 g_io_channel_purge (channel);
457 channel->funcs->io_close (channel, &err);
459 if (err)
460 { /* No way to return the error */
461 g_warning ("Error closing channel: %s", err->message);
462 g_error_free (err);
465 channel->close_on_unref = FALSE; /* Because we already did */
466 channel->is_readable = FALSE;
467 channel->is_writeable = FALSE;
468 channel->is_seekable = FALSE;
472 * g_io_channel_shutdown:
473 * @channel: a #GIOChannel
474 * @flush: if %TRUE, flush pending
475 * @err: location to store a #GIOChannelError
477 * Close an IO channel. Any pending data to be written will be
478 * flushed if @flush is %TRUE. The channel will not be freed until the
479 * last reference is dropped using g_io_channel_unref().
481 * Returns: the status of the operation.
483 GIOStatus
484 g_io_channel_shutdown (GIOChannel *channel,
485 gboolean flush,
486 GError **err)
488 GIOStatus status, result;
489 GError *tmperr = NULL;
491 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
492 g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
494 if (channel->write_buf && channel->write_buf->len > 0)
496 if (flush)
498 GIOFlags flags;
500 /* Set the channel to blocking, to avoid a busy loop
502 flags = g_io_channel_get_flags (channel);
503 /* Ignore any errors here, they're irrelevant */
504 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
506 result = g_io_channel_flush (channel, &tmperr);
508 else
509 result = G_IO_STATUS_NORMAL;
511 g_string_truncate(channel->write_buf, 0);
513 else
514 result = G_IO_STATUS_NORMAL;
516 if (channel->partial_write_buf[0] != '\0')
518 if (flush)
519 g_warning ("Partial character at end of write buffer not flushed.");
520 channel->partial_write_buf[0] = '\0';
523 status = channel->funcs->io_close (channel, err);
525 channel->close_on_unref = FALSE; /* Because we already did */
526 channel->is_readable = FALSE;
527 channel->is_writeable = FALSE;
528 channel->is_seekable = FALSE;
530 if (status != G_IO_STATUS_NORMAL)
532 g_clear_error (&tmperr);
533 return status;
535 else if (result != G_IO_STATUS_NORMAL)
537 g_propagate_error (err, tmperr);
538 return result;
540 else
541 return G_IO_STATUS_NORMAL;
544 /* This function is used for the final flush on close or unref */
545 static void
546 g_io_channel_purge (GIOChannel *channel)
548 GError *err = NULL;
549 GIOStatus status G_GNUC_UNUSED;
551 g_return_if_fail (channel != NULL);
553 if (channel->write_buf && channel->write_buf->len > 0)
555 GIOFlags flags;
557 /* Set the channel to blocking, to avoid a busy loop
559 flags = g_io_channel_get_flags (channel);
560 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
562 status = g_io_channel_flush (channel, &err);
564 if (err)
565 { /* No way to return the error */
566 g_warning ("Error flushing string: %s", err->message);
567 g_error_free (err);
571 /* Flush these in case anyone tries to close without unrefing */
573 if (channel->read_buf)
574 g_string_truncate (channel->read_buf, 0);
575 if (channel->write_buf)
576 g_string_truncate (channel->write_buf, 0);
577 if (channel->encoding)
579 if (channel->encoded_read_buf)
580 g_string_truncate (channel->encoded_read_buf, 0);
582 if (channel->partial_write_buf[0] != '\0')
584 g_warning ("Partial character at end of write buffer not flushed.");
585 channel->partial_write_buf[0] = '\0';
591 * g_io_create_watch:
592 * @channel: a #GIOChannel to watch
593 * @condition: conditions to watch for
595 * Creates a #GSource that's dispatched when @condition is met for the
596 * given @channel. For example, if condition is #G_IO_IN, the source will
597 * be dispatched when there's data available for reading.
599 * g_io_add_watch() is a simpler interface to this same functionality, for
600 * the case where you want to add the source to the default main loop context
601 * at the default priority.
603 * On Windows, polling a #GSource created to watch a channel for a socket
604 * puts the socket in non-blocking mode. This is a side-effect of the
605 * implementation and unavoidable.
607 * Returns: a new #GSource
609 GSource *
610 g_io_create_watch (GIOChannel *channel,
611 GIOCondition condition)
613 g_return_val_if_fail (channel != NULL, NULL);
615 return channel->funcs->io_create_watch (channel, condition);
619 * g_io_add_watch_full: (rename-to g_io_add_watch)
620 * @channel: a #GIOChannel
621 * @priority: the priority of the #GIOChannel source
622 * @condition: the condition to watch for
623 * @func: the function to call when the condition is satisfied
624 * @user_data: user data to pass to @func
625 * @notify: the function to call when the source is removed
627 * Adds the #GIOChannel into the default main loop context
628 * with the given priority.
630 * This internally creates a main loop source using g_io_create_watch()
631 * and attaches it to the main loop context with g_source_attach().
632 * You can do these steps manually if you need greater control.
634 * Returns: the event source id
636 guint
637 g_io_add_watch_full (GIOChannel *channel,
638 gint priority,
639 GIOCondition condition,
640 GIOFunc func,
641 gpointer user_data,
642 GDestroyNotify notify)
644 GSource *source;
645 guint id;
647 g_return_val_if_fail (channel != NULL, 0);
649 source = g_io_create_watch (channel, condition);
651 if (priority != G_PRIORITY_DEFAULT)
652 g_source_set_priority (source, priority);
653 g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
655 id = g_source_attach (source, NULL);
656 g_source_unref (source);
658 return id;
662 * g_io_add_watch:
663 * @channel: a #GIOChannel
664 * @condition: the condition to watch for
665 * @func: the function to call when the condition is satisfied
666 * @user_data: user data to pass to @func
668 * Adds the #GIOChannel into the default main loop context
669 * with the default priority.
671 * Returns: the event source id
674 * GIOFunc:
675 * @source: the #GIOChannel event source
676 * @condition: the condition which has been satisfied
677 * @data: user data set in g_io_add_watch() or g_io_add_watch_full()
679 * Specifies the type of function passed to g_io_add_watch() or
680 * g_io_add_watch_full(), which is called when the requested condition
681 * on a #GIOChannel is satisfied.
683 * Returns: the function should return %FALSE if the event source
684 * should be removed
687 * GIOCondition:
688 * @G_IO_IN: There is data to read.
689 * @G_IO_OUT: Data can be written (without blocking).
690 * @G_IO_PRI: There is urgent data to read.
691 * @G_IO_ERR: Error condition.
692 * @G_IO_HUP: Hung up (the connection has been broken, usually for
693 * pipes and sockets).
694 * @G_IO_NVAL: Invalid request. The file descriptor is not open.
696 * A bitwise combination representing a condition to watch for on an
697 * event source.
699 guint
700 g_io_add_watch (GIOChannel *channel,
701 GIOCondition condition,
702 GIOFunc func,
703 gpointer user_data)
705 return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
709 * g_io_channel_get_buffer_condition:
710 * @channel: A #GIOChannel
712 * This function returns a #GIOCondition depending on whether there
713 * is data to be read/space to write data in the internal buffers in
714 * the #GIOChannel. Only the flags %G_IO_IN and %G_IO_OUT may be set.
716 * Returns: A #GIOCondition
718 GIOCondition
719 g_io_channel_get_buffer_condition (GIOChannel *channel)
721 GIOCondition condition = 0;
723 if (channel->encoding)
725 if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
726 condition |= G_IO_IN; /* Only return if we have full characters */
728 else
730 if (channel->read_buf && (channel->read_buf->len > 0))
731 condition |= G_IO_IN;
734 if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
735 condition |= G_IO_OUT;
737 return condition;
741 * g_io_channel_error_from_errno:
742 * @en: an `errno` error number, e.g. `EINVAL`
744 * Converts an `errno` error number to a #GIOChannelError.
746 * Returns: a #GIOChannelError error number, e.g.
747 * %G_IO_CHANNEL_ERROR_INVAL.
749 GIOChannelError
750 g_io_channel_error_from_errno (gint en)
752 #ifdef EAGAIN
753 g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
754 #endif
756 switch (en)
758 #ifdef EBADF
759 case EBADF:
760 g_warning ("Invalid file descriptor.");
761 return G_IO_CHANNEL_ERROR_FAILED;
762 #endif
764 #ifdef EFAULT
765 case EFAULT:
766 g_warning ("Buffer outside valid address space.");
767 return G_IO_CHANNEL_ERROR_FAILED;
768 #endif
770 #ifdef EFBIG
771 case EFBIG:
772 return G_IO_CHANNEL_ERROR_FBIG;
773 #endif
775 #ifdef EINTR
776 /* In general, we should catch EINTR before we get here,
777 * but close() is allowed to return EINTR by POSIX, so
778 * we need to catch it here; EINTR from close() is
779 * unrecoverable, because it's undefined whether
780 * the fd was actually closed or not, so we just return
781 * a generic error code.
783 case EINTR:
784 return G_IO_CHANNEL_ERROR_FAILED;
785 #endif
787 #ifdef EINVAL
788 case EINVAL:
789 return G_IO_CHANNEL_ERROR_INVAL;
790 #endif
792 #ifdef EIO
793 case EIO:
794 return G_IO_CHANNEL_ERROR_IO;
795 #endif
797 #ifdef EISDIR
798 case EISDIR:
799 return G_IO_CHANNEL_ERROR_ISDIR;
800 #endif
802 #ifdef ENOSPC
803 case ENOSPC:
804 return G_IO_CHANNEL_ERROR_NOSPC;
805 #endif
807 #ifdef ENXIO
808 case ENXIO:
809 return G_IO_CHANNEL_ERROR_NXIO;
810 #endif
812 #ifdef EOVERFLOW
813 #if EOVERFLOW != EFBIG
814 case EOVERFLOW:
815 return G_IO_CHANNEL_ERROR_OVERFLOW;
816 #endif
817 #endif
819 #ifdef EPIPE
820 case EPIPE:
821 return G_IO_CHANNEL_ERROR_PIPE;
822 #endif
824 default:
825 return G_IO_CHANNEL_ERROR_FAILED;
830 * g_io_channel_set_buffer_size:
831 * @channel: a #GIOChannel
832 * @size: the size of the buffer, or 0 to let GLib pick a good size
834 * Sets the buffer size.
835 **/
836 void
837 g_io_channel_set_buffer_size (GIOChannel *channel,
838 gsize size)
840 g_return_if_fail (channel != NULL);
842 if (size == 0)
843 size = G_IO_NICE_BUF_SIZE;
845 if (size < MAX_CHAR_SIZE)
846 size = MAX_CHAR_SIZE;
848 channel->buf_size = size;
852 * g_io_channel_get_buffer_size:
853 * @channel: a #GIOChannel
855 * Gets the buffer size.
857 * Returns: the size of the buffer.
858 **/
859 gsize
860 g_io_channel_get_buffer_size (GIOChannel *channel)
862 g_return_val_if_fail (channel != NULL, 0);
864 return channel->buf_size;
868 * g_io_channel_set_line_term:
869 * @channel: a #GIOChannel
870 * @line_term: (nullable): The line termination string. Use %NULL for
871 * autodetect. Autodetection breaks on "\n", "\r\n", "\r", "\0",
872 * and the Unicode paragraph separator. Autodetection should not be
873 * used for anything other than file-based channels.
874 * @length: The length of the termination string. If -1 is passed, the
875 * string is assumed to be nul-terminated. This option allows
876 * termination strings with embedded nuls.
878 * This sets the string that #GIOChannel uses to determine
879 * where in the file a line break occurs.
881 void
882 g_io_channel_set_line_term (GIOChannel *channel,
883 const gchar *line_term,
884 gint length)
886 g_return_if_fail (channel != NULL);
887 g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
889 if (line_term == NULL)
890 length = 0;
891 else if (length < 0)
892 length = strlen (line_term);
894 g_free (channel->line_term);
895 channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
896 channel->line_term_len = length;
900 * g_io_channel_get_line_term:
901 * @channel: a #GIOChannel
902 * @length: a location to return the length of the line terminator
904 * This returns the string that #GIOChannel uses to determine
905 * where in the file a line break occurs. A value of %NULL
906 * indicates autodetection.
908 * Returns: The line termination string. This value
909 * is owned by GLib and must not be freed.
911 const gchar *
912 g_io_channel_get_line_term (GIOChannel *channel,
913 gint *length)
915 g_return_val_if_fail (channel != NULL, NULL);
917 if (length)
918 *length = channel->line_term_len;
920 return channel->line_term;
924 * g_io_channel_set_flags:
925 * @channel: a #GIOChannel
926 * @flags: the flags to set on the IO channel
927 * @error: A location to return an error of type #GIOChannelError
929 * Sets the (writeable) flags in @channel to (@flags & %G_IO_FLAG_SET_MASK).
931 * Returns: the status of the operation.
934 * GIOFlags:
935 * @G_IO_FLAG_APPEND: turns on append mode, corresponds to %O_APPEND
936 * (see the documentation of the UNIX open() syscall)
937 * @G_IO_FLAG_NONBLOCK: turns on nonblocking mode, corresponds to
938 * %O_NONBLOCK/%O_NDELAY (see the documentation of the UNIX open()
939 * syscall)
940 * @G_IO_FLAG_IS_READABLE: indicates that the io channel is readable.
941 * This flag cannot be changed.
942 * @G_IO_FLAG_IS_WRITABLE: indicates that the io channel is writable.
943 * This flag cannot be changed.
944 * @G_IO_FLAG_IS_WRITEABLE: a misspelled version of @G_IO_FLAG_IS_WRITABLE
945 * that existed before the spelling was fixed in GLib 2.30. It is kept
946 * here for compatibility reasons. Deprecated since 2.30
947 * @G_IO_FLAG_IS_SEEKABLE: indicates that the io channel is seekable,
948 * i.e. that g_io_channel_seek_position() can be used on it.
949 * This flag cannot be changed.
950 * @G_IO_FLAG_MASK: the mask that specifies all the valid flags.
951 * @G_IO_FLAG_GET_MASK: the mask of the flags that are returned from
952 * g_io_channel_get_flags()
953 * @G_IO_FLAG_SET_MASK: the mask of the flags that the user can modify
954 * with g_io_channel_set_flags()
956 * Specifies properties of a #GIOChannel. Some of the flags can only be
957 * read with g_io_channel_get_flags(), but not changed with
958 * g_io_channel_set_flags().
960 GIOStatus
961 g_io_channel_set_flags (GIOChannel *channel,
962 GIOFlags flags,
963 GError **error)
965 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
966 g_return_val_if_fail ((error == NULL) || (*error == NULL),
967 G_IO_STATUS_ERROR);
969 return (*channel->funcs->io_set_flags) (channel,
970 flags & G_IO_FLAG_SET_MASK,
971 error);
975 * g_io_channel_get_flags:
976 * @channel: a #GIOChannel
978 * Gets the current flags for a #GIOChannel, including read-only
979 * flags such as %G_IO_FLAG_IS_READABLE.
981 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITABLE
982 * are cached for internal use by the channel when it is created.
983 * If they should change at some later point (e.g. partial shutdown
984 * of a socket with the UNIX shutdown() function), the user
985 * should immediately call g_io_channel_get_flags() to update
986 * the internal values of these flags.
988 * Returns: the flags which are set on the channel
990 GIOFlags
991 g_io_channel_get_flags (GIOChannel *channel)
993 GIOFlags flags;
995 g_return_val_if_fail (channel != NULL, 0);
997 flags = (* channel->funcs->io_get_flags) (channel);
999 /* Cross implementation code */
1001 if (channel->is_seekable)
1002 flags |= G_IO_FLAG_IS_SEEKABLE;
1003 if (channel->is_readable)
1004 flags |= G_IO_FLAG_IS_READABLE;
1005 if (channel->is_writeable)
1006 flags |= G_IO_FLAG_IS_WRITABLE;
1008 return flags;
1012 * g_io_channel_set_close_on_unref:
1013 * @channel: a #GIOChannel
1014 * @do_close: Whether to close the channel on the final unref of
1015 * the GIOChannel data structure.
1017 * Whether to close the channel on the final unref of the #GIOChannel
1018 * data structure. The default value of this is %TRUE for channels
1019 * created by g_io_channel_new_file (), and %FALSE for all other channels.
1021 * Setting this flag to %TRUE for a channel you have already closed
1022 * can cause problems when the final reference to the #GIOChannel is dropped.
1024 void
1025 g_io_channel_set_close_on_unref (GIOChannel *channel,
1026 gboolean do_close)
1028 g_return_if_fail (channel != NULL);
1030 channel->close_on_unref = do_close;
1034 * g_io_channel_get_close_on_unref:
1035 * @channel: a #GIOChannel.
1037 * Returns whether the file/socket/whatever associated with @channel
1038 * will be closed when @channel receives its final unref and is
1039 * destroyed. The default value of this is %TRUE for channels created
1040 * by g_io_channel_new_file (), and %FALSE for all other channels.
1042 * Returns: %TRUE if the channel will be closed, %FALSE otherwise.
1044 gboolean
1045 g_io_channel_get_close_on_unref (GIOChannel *channel)
1047 g_return_val_if_fail (channel != NULL, FALSE);
1049 return channel->close_on_unref;
1053 * g_io_channel_seek_position:
1054 * @channel: a #GIOChannel
1055 * @offset: The offset in bytes from the position specified by @type
1056 * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
1057 * cases where a call to g_io_channel_set_encoding ()
1058 * is allowed. See the documentation for
1059 * g_io_channel_set_encoding () for details.
1060 * @error: A location to return an error of type #GIOChannelError
1062 * Replacement for g_io_channel_seek() with the new API.
1064 * Returns: the status of the operation.
1067 * GSeekType:
1068 * @G_SEEK_CUR: the current position in the file.
1069 * @G_SEEK_SET: the start of the file.
1070 * @G_SEEK_END: the end of the file.
1072 * An enumeration specifying the base position for a
1073 * g_io_channel_seek_position() operation.
1075 GIOStatus
1076 g_io_channel_seek_position (GIOChannel *channel,
1077 gint64 offset,
1078 GSeekType type,
1079 GError **error)
1081 GIOStatus status;
1083 /* For files, only one of the read and write buffers can contain data.
1084 * For sockets, both can contain data.
1087 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1088 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1089 G_IO_STATUS_ERROR);
1090 g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
1092 switch (type)
1094 case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
1095 if (channel->use_buffer)
1097 if (channel->do_encode && channel->encoded_read_buf
1098 && channel->encoded_read_buf->len > 0)
1100 g_warning ("Seek type G_SEEK_CUR not allowed for this"
1101 " channel's encoding.");
1102 return G_IO_STATUS_ERROR;
1104 if (channel->read_buf)
1105 offset -= channel->read_buf->len;
1106 if (channel->encoded_read_buf)
1108 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1110 /* If there's anything here, it's because the encoding is UTF-8,
1111 * so we can just subtract the buffer length, the same as for
1112 * the unencoded data.
1115 offset -= channel->encoded_read_buf->len;
1118 break;
1119 case G_SEEK_SET:
1120 case G_SEEK_END:
1121 break;
1122 default:
1123 g_warning ("g_io_channel_seek_position: unknown seek type");
1124 return G_IO_STATUS_ERROR;
1127 if (channel->use_buffer)
1129 status = g_io_channel_flush (channel, error);
1130 if (status != G_IO_STATUS_NORMAL)
1131 return status;
1134 status = channel->funcs->io_seek (channel, offset, type, error);
1136 if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
1138 if (channel->read_buf)
1139 g_string_truncate (channel->read_buf, 0);
1141 /* Conversion state no longer matches position in file */
1142 if (channel->read_cd != (GIConv) -1)
1143 g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
1144 if (channel->write_cd != (GIConv) -1)
1145 g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
1147 if (channel->encoded_read_buf)
1149 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1150 g_string_truncate (channel->encoded_read_buf, 0);
1153 if (channel->partial_write_buf[0] != '\0')
1155 g_warning ("Partial character at end of write buffer not flushed.");
1156 channel->partial_write_buf[0] = '\0';
1160 return status;
1164 * g_io_channel_flush:
1165 * @channel: a #GIOChannel
1166 * @error: location to store an error of type #GIOChannelError
1168 * Flushes the write buffer for the GIOChannel.
1170 * Returns: the status of the operation: One of
1171 * #G_IO_STATUS_NORMAL, #G_IO_STATUS_AGAIN, or
1172 * #G_IO_STATUS_ERROR.
1174 GIOStatus
1175 g_io_channel_flush (GIOChannel *channel,
1176 GError **error)
1178 GIOStatus status;
1179 gsize this_time = 1, bytes_written = 0;
1181 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1182 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1184 if (channel->write_buf == NULL || channel->write_buf->len == 0)
1185 return G_IO_STATUS_NORMAL;
1189 g_assert (this_time > 0);
1191 status = channel->funcs->io_write (channel,
1192 channel->write_buf->str + bytes_written,
1193 channel->write_buf->len - bytes_written,
1194 &this_time, error);
1195 bytes_written += this_time;
1197 while ((bytes_written < channel->write_buf->len)
1198 && (status == G_IO_STATUS_NORMAL));
1200 g_string_erase (channel->write_buf, 0, bytes_written);
1202 return status;
1206 * g_io_channel_set_buffered:
1207 * @channel: a #GIOChannel
1208 * @buffered: whether to set the channel buffered or unbuffered
1210 * The buffering state can only be set if the channel's encoding
1211 * is %NULL. For any other encoding, the channel must be buffered.
1213 * A buffered channel can only be set unbuffered if the channel's
1214 * internal buffers have been flushed. Newly created channels or
1215 * channels which have returned %G_IO_STATUS_EOF
1216 * not require such a flush. For write-only channels, a call to
1217 * g_io_channel_flush () is sufficient. For all other channels,
1218 * the buffers may be flushed by a call to g_io_channel_seek_position ().
1219 * This includes the possibility of seeking with seek type %G_SEEK_CUR
1220 * and an offset of zero. Note that this means that socket-based
1221 * channels cannot be set unbuffered once they have had data
1222 * read from them.
1224 * On unbuffered channels, it is safe to mix read and write
1225 * calls from the new and old APIs, if this is necessary for
1226 * maintaining old code.
1228 * The default state of the channel is buffered.
1230 void
1231 g_io_channel_set_buffered (GIOChannel *channel,
1232 gboolean buffered)
1234 g_return_if_fail (channel != NULL);
1236 if (channel->encoding != NULL)
1238 g_warning ("Need to have NULL encoding to set the buffering state of the "
1239 "channel.");
1240 return;
1243 g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
1244 g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
1246 channel->use_buffer = buffered;
1250 * g_io_channel_get_buffered:
1251 * @channel: a #GIOChannel
1253 * Returns whether @channel is buffered.
1255 * Return Value: %TRUE if the @channel is buffered.
1257 gboolean
1258 g_io_channel_get_buffered (GIOChannel *channel)
1260 g_return_val_if_fail (channel != NULL, FALSE);
1262 return channel->use_buffer;
1266 * g_io_channel_set_encoding:
1267 * @channel: a #GIOChannel
1268 * @encoding: (nullable): the encoding type
1269 * @error: location to store an error of type #GConvertError
1271 * Sets the encoding for the input/output of the channel.
1272 * The internal encoding is always UTF-8. The default encoding
1273 * for the external file is UTF-8.
1275 * The encoding %NULL is safe to use with binary data.
1277 * The encoding can only be set if one of the following conditions
1278 * is true:
1280 * - The channel was just created, and has not been written to or read from yet.
1282 * - The channel is write-only.
1284 * - The channel is a file, and the file pointer was just repositioned
1285 * by a call to g_io_channel_seek_position(). (This flushes all the
1286 * internal buffers.)
1288 * - The current encoding is %NULL or UTF-8.
1290 * - One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1291 * (or, in the case of g_io_channel_read_to_end(), %G_IO_STATUS_NORMAL).
1293 * - One of the functions g_io_channel_read_chars() or
1294 * g_io_channel_read_unichar() has returned %G_IO_STATUS_AGAIN or
1295 * %G_IO_STATUS_ERROR. This may be useful in the case of
1296 * %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1297 * Returning one of these statuses from g_io_channel_read_line(),
1298 * g_io_channel_read_line_string(), or g_io_channel_read_to_end()
1299 * does not guarantee that the encoding can be changed.
1301 * Channels which do not meet one of the above conditions cannot call
1302 * g_io_channel_seek_position() with an offset of %G_SEEK_CUR, and, if
1303 * they are "seekable", cannot call g_io_channel_write_chars() after
1304 * calling one of the API "read" functions.
1306 * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set
1308 GIOStatus
1309 g_io_channel_set_encoding (GIOChannel *channel,
1310 const gchar *encoding,
1311 GError **error)
1313 GIConv read_cd, write_cd;
1314 gboolean did_encode;
1316 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1317 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1319 /* Make sure the encoded buffers are empty */
1321 g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1322 channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1324 if (!channel->use_buffer)
1326 g_warning ("Need to set the channel buffered before setting the encoding.");
1327 g_warning ("Assuming this is what you meant and acting accordingly.");
1329 channel->use_buffer = TRUE;
1332 if (channel->partial_write_buf[0] != '\0')
1334 g_warning ("Partial character at end of write buffer not flushed.");
1335 channel->partial_write_buf[0] = '\0';
1338 did_encode = channel->do_encode;
1340 if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1342 channel->do_encode = FALSE;
1343 read_cd = write_cd = (GIConv) -1;
1345 else
1347 gint err = 0;
1348 const gchar *from_enc = NULL, *to_enc = NULL;
1350 if (channel->is_readable)
1352 read_cd = g_iconv_open ("UTF-8", encoding);
1354 if (read_cd == (GIConv) -1)
1356 err = errno;
1357 from_enc = encoding;
1358 to_enc = "UTF-8";
1361 else
1362 read_cd = (GIConv) -1;
1364 if (channel->is_writeable && err == 0)
1366 write_cd = g_iconv_open (encoding, "UTF-8");
1368 if (write_cd == (GIConv) -1)
1370 err = errno;
1371 from_enc = "UTF-8";
1372 to_enc = encoding;
1375 else
1376 write_cd = (GIConv) -1;
1378 if (err != 0)
1380 g_assert (from_enc);
1381 g_assert (to_enc);
1383 if (err == EINVAL)
1384 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1385 _("Conversion from character set “%s” to “%s” is not supported"),
1386 from_enc, to_enc);
1387 else
1388 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1389 _("Could not open converter from “%s” to “%s”: %s"),
1390 from_enc, to_enc, g_strerror (err));
1392 if (read_cd != (GIConv) -1)
1393 g_iconv_close (read_cd);
1394 if (write_cd != (GIConv) -1)
1395 g_iconv_close (write_cd);
1397 return G_IO_STATUS_ERROR;
1400 channel->do_encode = TRUE;
1403 /* The encoding is ok, so set the fields in channel */
1405 if (channel->read_cd != (GIConv) -1)
1406 g_iconv_close (channel->read_cd);
1407 if (channel->write_cd != (GIConv) -1)
1408 g_iconv_close (channel->write_cd);
1410 if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1412 g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1414 /* This is just validated UTF-8, so we can copy it back into read_buf
1415 * so it can be encoded in whatever the new encoding is.
1418 g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1419 channel->encoded_read_buf->len);
1420 g_string_truncate (channel->encoded_read_buf, 0);
1423 channel->read_cd = read_cd;
1424 channel->write_cd = write_cd;
1426 g_free (channel->encoding);
1427 channel->encoding = g_strdup (encoding);
1429 return G_IO_STATUS_NORMAL;
1433 * g_io_channel_get_encoding:
1434 * @channel: a #GIOChannel
1436 * Gets the encoding for the input/output of the channel.
1437 * The internal encoding is always UTF-8. The encoding %NULL
1438 * makes the channel safe for binary data.
1440 * Returns: A string containing the encoding, this string is
1441 * owned by GLib and must not be freed.
1443 const gchar *
1444 g_io_channel_get_encoding (GIOChannel *channel)
1446 g_return_val_if_fail (channel != NULL, NULL);
1448 return channel->encoding;
1451 static GIOStatus
1452 g_io_channel_fill_buffer (GIOChannel *channel,
1453 GError **err)
1455 gsize read_size, cur_len, oldlen;
1456 GIOStatus status;
1458 if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1460 status = g_io_channel_flush (channel, err);
1461 if (status != G_IO_STATUS_NORMAL)
1462 return status;
1464 if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1466 g_warning ("Partial character at end of write buffer not flushed.");
1467 channel->partial_write_buf[0] = '\0';
1470 if (!channel->read_buf)
1471 channel->read_buf = g_string_sized_new (channel->buf_size);
1473 cur_len = channel->read_buf->len;
1475 g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1477 status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1478 channel->buf_size, &read_size, err);
1480 g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1482 g_string_truncate (channel->read_buf, read_size + cur_len);
1484 if ((status != G_IO_STATUS_NORMAL) &&
1485 ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1486 return status;
1488 g_assert (channel->read_buf->len > 0);
1490 if (channel->encoded_read_buf)
1491 oldlen = channel->encoded_read_buf->len;
1492 else
1494 oldlen = 0;
1495 if (channel->encoding)
1496 channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1499 if (channel->do_encode)
1501 gsize errnum, inbytes_left, outbytes_left;
1502 gchar *inbuf, *outbuf;
1503 int errval;
1505 g_assert (channel->encoded_read_buf);
1507 reencode:
1509 inbytes_left = channel->read_buf->len;
1510 outbytes_left = MAX (channel->read_buf->len,
1511 channel->encoded_read_buf->allocated_len
1512 - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1513 outbytes_left = MAX (outbytes_left, 6);
1515 inbuf = channel->read_buf->str;
1516 g_string_set_size (channel->encoded_read_buf,
1517 channel->encoded_read_buf->len + outbytes_left);
1518 outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1519 - outbytes_left;
1521 errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1522 &outbuf, &outbytes_left);
1523 errval = errno;
1525 g_assert (inbuf + inbytes_left == channel->read_buf->str
1526 + channel->read_buf->len);
1527 g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1528 + channel->encoded_read_buf->len);
1530 g_string_erase (channel->read_buf, 0,
1531 channel->read_buf->len - inbytes_left);
1532 g_string_truncate (channel->encoded_read_buf,
1533 channel->encoded_read_buf->len - outbytes_left);
1535 if (errnum == (gsize) -1)
1537 switch (errval)
1539 case EINVAL:
1540 if ((oldlen == channel->encoded_read_buf->len)
1541 && (status == G_IO_STATUS_EOF))
1542 status = G_IO_STATUS_EOF;
1543 else
1544 status = G_IO_STATUS_NORMAL;
1545 break;
1546 case E2BIG:
1547 /* Buffer size at least 6, wrote at least on character */
1548 g_assert (inbuf != channel->read_buf->str);
1549 goto reencode;
1550 case EILSEQ:
1551 if (oldlen < channel->encoded_read_buf->len)
1552 status = G_IO_STATUS_NORMAL;
1553 else
1555 g_set_error_literal (err, G_CONVERT_ERROR,
1556 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1557 _("Invalid byte sequence in conversion input"));
1558 return G_IO_STATUS_ERROR;
1560 break;
1561 default:
1562 g_assert (errval != EBADF); /* The converter should be open */
1563 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1564 _("Error during conversion: %s"), g_strerror (errval));
1565 return G_IO_STATUS_ERROR;
1568 g_assert ((status != G_IO_STATUS_NORMAL)
1569 || (channel->encoded_read_buf->len > 0));
1571 else if (channel->encoding) /* UTF-8 */
1573 gchar *nextchar, *lastchar;
1575 g_assert (channel->encoded_read_buf);
1577 nextchar = channel->read_buf->str;
1578 lastchar = channel->read_buf->str + channel->read_buf->len;
1580 while (nextchar < lastchar)
1582 gunichar val_char;
1584 val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1586 switch (val_char)
1588 case -2:
1589 /* stop, leave partial character in buffer */
1590 lastchar = nextchar;
1591 break;
1592 case -1:
1593 if (oldlen < channel->encoded_read_buf->len)
1594 status = G_IO_STATUS_NORMAL;
1595 else
1597 g_set_error_literal (err, G_CONVERT_ERROR,
1598 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1599 _("Invalid byte sequence in conversion input"));
1600 status = G_IO_STATUS_ERROR;
1602 lastchar = nextchar;
1603 break;
1604 default:
1605 nextchar = g_utf8_next_char (nextchar);
1606 break;
1610 if (lastchar > channel->read_buf->str)
1612 gint copy_len = lastchar - channel->read_buf->str;
1614 g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1615 copy_len);
1616 g_string_erase (channel->read_buf, 0, copy_len);
1620 return status;
1624 * g_io_channel_read_line:
1625 * @channel: a #GIOChannel
1626 * @str_return: (out): The line read from the #GIOChannel, including the
1627 * line terminator. This data should be freed with g_free()
1628 * when no longer needed. This is a nul-terminated string.
1629 * If a @length of zero is returned, this will be %NULL instead.
1630 * @length: (out) (optional): location to store length of the read data, or %NULL
1631 * @terminator_pos: (out) (optional): location to store position of line terminator, or %NULL
1632 * @error: A location to return an error of type #GConvertError
1633 * or #GIOChannelError
1635 * Reads a line, including the terminating character(s),
1636 * from a #GIOChannel into a newly-allocated string.
1637 * @str_return will contain allocated memory if the return
1638 * is %G_IO_STATUS_NORMAL.
1640 * Returns: the status of the operation.
1642 GIOStatus
1643 g_io_channel_read_line (GIOChannel *channel,
1644 gchar **str_return,
1645 gsize *length,
1646 gsize *terminator_pos,
1647 GError **error)
1649 GIOStatus status;
1650 gsize got_length;
1652 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1653 g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1654 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1655 G_IO_STATUS_ERROR);
1656 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1658 status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1660 if (length && status != G_IO_STATUS_ERROR)
1661 *length = got_length;
1663 if (status == G_IO_STATUS_NORMAL)
1665 g_assert (USE_BUF (channel));
1666 *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1667 g_string_erase (USE_BUF (channel), 0, got_length);
1669 else
1670 *str_return = NULL;
1672 return status;
1676 * g_io_channel_read_line_string:
1677 * @channel: a #GIOChannel
1678 * @buffer: a #GString into which the line will be written.
1679 * If @buffer already contains data, the old data will
1680 * be overwritten.
1681 * @terminator_pos: (nullable): location to store position of line terminator, or %NULL
1682 * @error: a location to store an error of type #GConvertError
1683 * or #GIOChannelError
1685 * Reads a line from a #GIOChannel, using a #GString as a buffer.
1687 * Returns: the status of the operation.
1689 GIOStatus
1690 g_io_channel_read_line_string (GIOChannel *channel,
1691 GString *buffer,
1692 gsize *terminator_pos,
1693 GError **error)
1695 gsize length;
1696 GIOStatus status;
1698 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1699 g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1700 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1701 G_IO_STATUS_ERROR);
1702 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1704 if (buffer->len > 0)
1705 g_string_truncate (buffer, 0); /* clear out the buffer */
1707 status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1709 if (status == G_IO_STATUS_NORMAL)
1711 g_assert (USE_BUF (channel));
1712 g_string_append_len (buffer, USE_BUF (channel)->str, length);
1713 g_string_erase (USE_BUF (channel), 0, length);
1716 return status;
1720 static GIOStatus
1721 g_io_channel_read_line_backend (GIOChannel *channel,
1722 gsize *length,
1723 gsize *terminator_pos,
1724 GError **error)
1726 GIOStatus status;
1727 gsize checked_to, line_term_len, line_length, got_term_len;
1728 gboolean first_time = TRUE;
1730 if (!channel->use_buffer)
1732 /* Can't do a raw read in read_line */
1733 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1734 _("Can’t do a raw read in g_io_channel_read_line_string"));
1735 return G_IO_STATUS_ERROR;
1738 status = G_IO_STATUS_NORMAL;
1740 if (channel->line_term)
1741 line_term_len = channel->line_term_len;
1742 else
1743 line_term_len = 3;
1744 /* This value used for setting checked_to, it's the longest of the four
1745 * we autodetect for.
1748 checked_to = 0;
1750 while (TRUE)
1752 gchar *nextchar, *lastchar;
1753 GString *use_buf;
1755 if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1757 read_again:
1758 status = g_io_channel_fill_buffer (channel, error);
1759 switch (status)
1761 case G_IO_STATUS_NORMAL:
1762 if (BUF_LEN (USE_BUF (channel)) == 0)
1763 /* Can happen when using conversion and only read
1764 * part of a character
1767 first_time = FALSE;
1768 continue;
1770 break;
1771 case G_IO_STATUS_EOF:
1772 if (BUF_LEN (USE_BUF (channel)) == 0)
1774 if (length)
1775 *length = 0;
1777 if (channel->encoding && channel->read_buf->len != 0)
1779 g_set_error_literal (error, G_CONVERT_ERROR,
1780 G_CONVERT_ERROR_PARTIAL_INPUT,
1781 _("Leftover unconverted data in "
1782 "read buffer"));
1783 return G_IO_STATUS_ERROR;
1785 else
1786 return G_IO_STATUS_EOF;
1788 break;
1789 default:
1790 if (length)
1791 *length = 0;
1792 return status;
1796 g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1798 use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1800 first_time = FALSE;
1802 lastchar = use_buf->str + use_buf->len;
1804 for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1805 channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1807 if (channel->line_term)
1809 if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1811 line_length = nextchar - use_buf->str;
1812 got_term_len = line_term_len;
1813 goto done;
1816 else /* auto detect */
1818 switch (*nextchar)
1820 case '\n': /* unix */
1821 line_length = nextchar - use_buf->str;
1822 got_term_len = 1;
1823 goto done;
1824 case '\r': /* Warning: do not use with sockets */
1825 line_length = nextchar - use_buf->str;
1826 if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1827 && (lastchar == use_buf->str + use_buf->len))
1828 goto read_again; /* Try to read more data */
1829 if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1830 got_term_len = 2;
1831 else /* mac */
1832 got_term_len = 1;
1833 goto done;
1834 case '\xe2': /* Unicode paragraph separator */
1835 if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1837 line_length = nextchar - use_buf->str;
1838 got_term_len = 3;
1839 goto done;
1841 break;
1842 case '\0': /* Embeded null in input */
1843 line_length = nextchar - use_buf->str;
1844 got_term_len = 1;
1845 goto done;
1846 default: /* no match */
1847 break;
1852 /* If encoding != NULL, valid UTF-8, didn't overshoot */
1853 g_assert (nextchar == lastchar);
1855 /* Check for EOF */
1857 if (status == G_IO_STATUS_EOF)
1859 if (channel->encoding && channel->read_buf->len > 0)
1861 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1862 _("Channel terminates in a partial character"));
1863 return G_IO_STATUS_ERROR;
1865 line_length = use_buf->len;
1866 got_term_len = 0;
1867 break;
1870 if (use_buf->len > line_term_len - 1)
1871 checked_to = use_buf->len - (line_term_len - 1);
1872 else
1873 checked_to = 0;
1876 done:
1878 if (terminator_pos)
1879 *terminator_pos = line_length;
1881 if (length)
1882 *length = line_length + got_term_len;
1884 return G_IO_STATUS_NORMAL;
1888 * g_io_channel_read_to_end:
1889 * @channel: a #GIOChannel
1890 * @str_return: (out) (array length=length) (element-type guint8): Location to
1891 * store a pointer to a string holding the remaining data in the
1892 * #GIOChannel. This data should be freed with g_free() when no
1893 * longer needed. This data is terminated by an extra nul
1894 * character, but there may be other nuls in the intervening data.
1895 * @length: (out): location to store length of the data
1896 * @error: location to return an error of type #GConvertError
1897 * or #GIOChannelError
1899 * Reads all the remaining data from the file.
1901 * Returns: %G_IO_STATUS_NORMAL on success.
1902 * This function never returns %G_IO_STATUS_EOF.
1904 GIOStatus
1905 g_io_channel_read_to_end (GIOChannel *channel,
1906 gchar **str_return,
1907 gsize *length,
1908 GError **error)
1910 GIOStatus status;
1912 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1913 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1914 G_IO_STATUS_ERROR);
1915 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1917 if (str_return)
1918 *str_return = NULL;
1919 if (length)
1920 *length = 0;
1922 if (!channel->use_buffer)
1924 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1925 _("Can’t do a raw read in g_io_channel_read_to_end"));
1926 return G_IO_STATUS_ERROR;
1930 status = g_io_channel_fill_buffer (channel, error);
1931 while (status == G_IO_STATUS_NORMAL);
1933 if (status != G_IO_STATUS_EOF)
1934 return status;
1936 if (channel->encoding && channel->read_buf->len > 0)
1938 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1939 _("Channel terminates in a partial character"));
1940 return G_IO_STATUS_ERROR;
1943 if (USE_BUF (channel) == NULL)
1945 /* length is already set to zero */
1946 if (str_return)
1947 *str_return = g_strdup ("");
1949 else
1951 if (length)
1952 *length = USE_BUF (channel)->len;
1954 if (str_return)
1955 *str_return = g_string_free (USE_BUF (channel), FALSE);
1956 else
1957 g_string_free (USE_BUF (channel), TRUE);
1959 if (channel->encoding)
1960 channel->encoded_read_buf = NULL;
1961 else
1962 channel->read_buf = NULL;
1965 return G_IO_STATUS_NORMAL;
1969 * g_io_channel_read_chars:
1970 * @channel: a #GIOChannel
1971 * @buf: (out caller-allocates) (array length=count) (element-type guint8):
1972 * a buffer to read data into
1973 * @count: (in): the size of the buffer. Note that the buffer may not be
1974 * complelely filled even if there is data in the buffer if the
1975 * remaining data is not a complete character.
1976 * @bytes_read: (out) (optional): The number of bytes read. This may be
1977 * zero even on success if count < 6 and the channel's encoding
1978 * is non-%NULL. This indicates that the next UTF-8 character is
1979 * too wide for the buffer.
1980 * @error: a location to return an error of type #GConvertError
1981 * or #GIOChannelError.
1983 * Replacement for g_io_channel_read() with the new API.
1985 * Returns: the status of the operation.
1987 GIOStatus
1988 g_io_channel_read_chars (GIOChannel *channel,
1989 gchar *buf,
1990 gsize count,
1991 gsize *bytes_read,
1992 GError **error)
1994 GIOStatus status;
1995 gsize got_bytes;
1997 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1998 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1999 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2001 if (count == 0)
2003 if (bytes_read)
2004 *bytes_read = 0;
2005 return G_IO_STATUS_NORMAL;
2007 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2009 if (!channel->use_buffer)
2011 gsize tmp_bytes;
2013 g_assert (!channel->read_buf || channel->read_buf->len == 0);
2015 status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
2017 if (bytes_read)
2018 *bytes_read = tmp_bytes;
2020 return status;
2023 status = G_IO_STATUS_NORMAL;
2025 while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
2026 status = g_io_channel_fill_buffer (channel, error);
2028 /* Only return an error if we have no data */
2030 if (BUF_LEN (USE_BUF (channel)) == 0)
2032 g_assert (status != G_IO_STATUS_NORMAL);
2034 if (status == G_IO_STATUS_EOF && channel->encoding
2035 && BUF_LEN (channel->read_buf) > 0)
2037 g_set_error_literal (error, G_CONVERT_ERROR,
2038 G_CONVERT_ERROR_PARTIAL_INPUT,
2039 _("Leftover unconverted data in read buffer"));
2040 status = G_IO_STATUS_ERROR;
2043 if (bytes_read)
2044 *bytes_read = 0;
2046 return status;
2049 if (status == G_IO_STATUS_ERROR)
2050 g_clear_error (error);
2052 got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
2054 g_assert (got_bytes > 0);
2056 if (channel->encoding)
2057 /* Don't validate for NULL encoding, binary safe */
2059 gchar *nextchar, *prevchar;
2061 g_assert (USE_BUF (channel) == channel->encoded_read_buf);
2063 nextchar = channel->encoded_read_buf->str;
2067 prevchar = nextchar;
2068 nextchar = g_utf8_next_char (nextchar);
2069 g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
2071 while (nextchar < channel->encoded_read_buf->str + got_bytes);
2073 if (nextchar > channel->encoded_read_buf->str + got_bytes)
2074 got_bytes = prevchar - channel->encoded_read_buf->str;
2076 g_assert (got_bytes > 0 || count < 6);
2079 memcpy (buf, USE_BUF (channel)->str, got_bytes);
2080 g_string_erase (USE_BUF (channel), 0, got_bytes);
2082 if (bytes_read)
2083 *bytes_read = got_bytes;
2085 return G_IO_STATUS_NORMAL;
2089 * g_io_channel_read_unichar:
2090 * @channel: a #GIOChannel
2091 * @thechar: (out): a location to return a character
2092 * @error: a location to return an error of type #GConvertError
2093 * or #GIOChannelError
2095 * Reads a Unicode character from @channel.
2096 * This function cannot be called on a channel with %NULL encoding.
2098 * Returns: a #GIOStatus
2100 GIOStatus
2101 g_io_channel_read_unichar (GIOChannel *channel,
2102 gunichar *thechar,
2103 GError **error)
2105 GIOStatus status = G_IO_STATUS_NORMAL;
2107 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2108 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2109 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2110 G_IO_STATUS_ERROR);
2111 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2113 while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
2114 status = g_io_channel_fill_buffer (channel, error);
2116 /* Only return an error if we have no data */
2118 if (BUF_LEN (USE_BUF (channel)) == 0)
2120 g_assert (status != G_IO_STATUS_NORMAL);
2122 if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
2124 g_set_error_literal (error, G_CONVERT_ERROR,
2125 G_CONVERT_ERROR_PARTIAL_INPUT,
2126 _("Leftover unconverted data in read buffer"));
2127 status = G_IO_STATUS_ERROR;
2130 if (thechar)
2131 *thechar = (gunichar) -1;
2133 return status;
2136 if (status == G_IO_STATUS_ERROR)
2137 g_clear_error (error);
2139 if (thechar)
2140 *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
2142 g_string_erase (channel->encoded_read_buf, 0,
2143 g_utf8_next_char (channel->encoded_read_buf->str)
2144 - channel->encoded_read_buf->str);
2146 return G_IO_STATUS_NORMAL;
2150 * g_io_channel_write_chars:
2151 * @channel: a #GIOChannel
2152 * @buf: (array) (element-type guint8): a buffer to write data from
2153 * @count: the size of the buffer. If -1, the buffer
2154 * is taken to be a nul-terminated string.
2155 * @bytes_written: (out): The number of bytes written. This can be nonzero
2156 * even if the return value is not %G_IO_STATUS_NORMAL.
2157 * If the return value is %G_IO_STATUS_NORMAL and the
2158 * channel is blocking, this will always be equal
2159 * to @count if @count >= 0.
2160 * @error: a location to return an error of type #GConvertError
2161 * or #GIOChannelError
2163 * Replacement for g_io_channel_write() with the new API.
2165 * On seekable channels with encodings other than %NULL or UTF-8, generic
2166 * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
2167 * may only be made on a channel from which data has been read in the
2168 * cases described in the documentation for g_io_channel_set_encoding ().
2170 * Returns: the status of the operation.
2172 GIOStatus
2173 g_io_channel_write_chars (GIOChannel *channel,
2174 const gchar *buf,
2175 gssize count,
2176 gsize *bytes_written,
2177 GError **error)
2179 GIOStatus status;
2180 gssize wrote_bytes = 0;
2182 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2183 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2184 G_IO_STATUS_ERROR);
2185 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2187 if ((count < 0) && buf)
2188 count = strlen (buf);
2190 if (count == 0)
2192 if (bytes_written)
2193 *bytes_written = 0;
2194 return G_IO_STATUS_NORMAL;
2197 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2198 g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
2200 /* Raw write case */
2202 if (!channel->use_buffer)
2204 gsize tmp_bytes;
2206 g_assert (!channel->write_buf || channel->write_buf->len == 0);
2207 g_assert (channel->partial_write_buf[0] == '\0');
2209 status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
2211 if (bytes_written)
2212 *bytes_written = tmp_bytes;
2214 return status;
2217 /* General case */
2219 if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
2220 || (BUF_LEN (channel->encoded_read_buf) > 0)))
2222 if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
2224 g_warning ("Mixed reading and writing not allowed on encoded files");
2225 return G_IO_STATUS_ERROR;
2227 status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
2228 if (status != G_IO_STATUS_NORMAL)
2230 if (bytes_written)
2231 *bytes_written = 0;
2232 return status;
2236 if (!channel->write_buf)
2237 channel->write_buf = g_string_sized_new (channel->buf_size);
2239 while (wrote_bytes < count)
2241 gsize space_in_buf;
2243 /* If the buffer is full, try a write immediately. In
2244 * the nonblocking case, this prevents the user from
2245 * writing just a little bit to the buffer every time
2246 * and never receiving an EAGAIN.
2249 if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2251 gsize did_write = 0, this_time;
2255 status = channel->funcs->io_write (channel, channel->write_buf->str
2256 + did_write, channel->write_buf->len
2257 - did_write, &this_time, error);
2258 did_write += this_time;
2260 while (status == G_IO_STATUS_NORMAL &&
2261 did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2263 g_string_erase (channel->write_buf, 0, did_write);
2265 if (status != G_IO_STATUS_NORMAL)
2267 if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2268 status = G_IO_STATUS_NORMAL;
2269 if (bytes_written)
2270 *bytes_written = wrote_bytes;
2271 return status;
2275 space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2276 - channel->write_buf->len; /* 1 for NULL */
2278 /* This is only true because g_io_channel_set_buffer_size ()
2279 * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2281 g_assert (space_in_buf >= MAX_CHAR_SIZE);
2283 if (!channel->encoding)
2285 gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2287 g_string_append_len (channel->write_buf, buf, write_this);
2288 buf += write_this;
2289 wrote_bytes += write_this;
2291 else
2293 const gchar *from_buf;
2294 gsize from_buf_len, from_buf_old_len, left_len;
2295 gsize err;
2296 gint errnum;
2298 if (channel->partial_write_buf[0] != '\0')
2300 g_assert (wrote_bytes == 0);
2302 from_buf = channel->partial_write_buf;
2303 from_buf_old_len = strlen (channel->partial_write_buf);
2304 g_assert (from_buf_old_len > 0);
2305 from_buf_len = MIN (6, from_buf_old_len + count);
2307 memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2308 from_buf_len - from_buf_old_len);
2310 else
2312 from_buf = buf;
2313 from_buf_len = count - wrote_bytes;
2314 from_buf_old_len = 0;
2317 reconvert:
2319 if (!channel->do_encode) /* UTF-8 encoding */
2321 const gchar *badchar;
2322 gsize try_len = MIN (from_buf_len, space_in_buf);
2324 /* UTF-8, just validate, emulate g_iconv */
2326 if (!g_utf8_validate (from_buf, try_len, &badchar))
2328 gunichar try_char;
2329 gsize incomplete_len = from_buf + try_len - badchar;
2331 left_len = from_buf + from_buf_len - badchar;
2333 try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2335 switch (try_char)
2337 case -2:
2338 g_assert (incomplete_len < 6);
2339 if (try_len == from_buf_len)
2341 errnum = EINVAL;
2342 err = (gsize) -1;
2344 else
2346 errnum = 0;
2347 err = (gsize) 0;
2349 break;
2350 case -1:
2351 g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2352 /* FIXME bail here? */
2353 errnum = EILSEQ;
2354 err = (gsize) -1;
2355 break;
2356 default:
2357 g_assert_not_reached ();
2358 err = (gsize) -1;
2359 errnum = 0; /* Don't confunse the compiler */
2362 else
2364 err = (gsize) 0;
2365 errnum = 0;
2366 left_len = from_buf_len - try_len;
2369 g_string_append_len (channel->write_buf, from_buf,
2370 from_buf_len - left_len);
2371 from_buf += from_buf_len - left_len;
2373 else
2375 gchar *outbuf;
2377 left_len = from_buf_len;
2378 g_string_set_size (channel->write_buf, channel->write_buf->len
2379 + space_in_buf);
2380 outbuf = channel->write_buf->str + channel->write_buf->len
2381 - space_in_buf;
2382 err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2383 &outbuf, &space_in_buf);
2384 errnum = errno;
2385 g_string_truncate (channel->write_buf, channel->write_buf->len
2386 - space_in_buf);
2389 if (err == (gsize) -1)
2391 switch (errnum)
2393 case EINVAL:
2394 g_assert (left_len < 6);
2396 if (from_buf_old_len == 0)
2398 /* Not from partial_write_buf */
2400 memcpy (channel->partial_write_buf, from_buf, left_len);
2401 channel->partial_write_buf[left_len] = '\0';
2402 if (bytes_written)
2403 *bytes_written = count;
2404 return G_IO_STATUS_NORMAL;
2407 /* Working in partial_write_buf */
2409 if (left_len == from_buf_len)
2411 /* Didn't convert anything, must still have
2412 * less than a full character
2415 g_assert (count == from_buf_len - from_buf_old_len);
2417 channel->partial_write_buf[from_buf_len] = '\0';
2419 if (bytes_written)
2420 *bytes_written = count;
2422 return G_IO_STATUS_NORMAL;
2425 g_assert (from_buf_len - left_len >= from_buf_old_len);
2427 /* We converted all the old data. This is fine */
2429 break;
2430 case E2BIG:
2431 if (from_buf_len == left_len)
2433 /* Nothing was written, add enough space for
2434 * at least one character.
2436 space_in_buf += MAX_CHAR_SIZE;
2437 goto reconvert;
2439 break;
2440 case EILSEQ:
2441 g_set_error_literal (error, G_CONVERT_ERROR,
2442 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2443 _("Invalid byte sequence in conversion input"));
2444 if (from_buf_old_len > 0 && from_buf_len == left_len)
2445 g_warning ("Illegal sequence due to partial character "
2446 "at the end of a previous write.");
2447 else
2448 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2449 if (bytes_written)
2450 *bytes_written = wrote_bytes;
2451 channel->partial_write_buf[0] = '\0';
2452 return G_IO_STATUS_ERROR;
2453 default:
2454 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2455 _("Error during conversion: %s"), g_strerror (errnum));
2456 if (from_buf_len >= left_len + from_buf_old_len)
2457 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2458 if (bytes_written)
2459 *bytes_written = wrote_bytes;
2460 channel->partial_write_buf[0] = '\0';
2461 return G_IO_STATUS_ERROR;
2465 g_assert (from_buf_len - left_len >= from_buf_old_len);
2467 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2469 if (from_buf_old_len > 0)
2471 /* We were working in partial_write_buf */
2473 buf += from_buf_len - left_len - from_buf_old_len;
2474 channel->partial_write_buf[0] = '\0';
2476 else
2477 buf = from_buf;
2481 if (bytes_written)
2482 *bytes_written = count;
2484 return G_IO_STATUS_NORMAL;
2488 * g_io_channel_write_unichar:
2489 * @channel: a #GIOChannel
2490 * @thechar: a character
2491 * @error: location to return an error of type #GConvertError
2492 * or #GIOChannelError
2494 * Writes a Unicode character to @channel.
2495 * This function cannot be called on a channel with %NULL encoding.
2497 * Returns: a #GIOStatus
2499 GIOStatus
2500 g_io_channel_write_unichar (GIOChannel *channel,
2501 gunichar thechar,
2502 GError **error)
2504 GIOStatus status;
2505 gchar static_buf[6];
2506 gsize char_len, wrote_len;
2508 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2509 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2510 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2511 G_IO_STATUS_ERROR);
2512 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2514 char_len = g_unichar_to_utf8 (thechar, static_buf);
2516 if (channel->partial_write_buf[0] != '\0')
2518 g_warning ("Partial character written before writing unichar.");
2519 channel->partial_write_buf[0] = '\0';
2522 status = g_io_channel_write_chars (channel, static_buf,
2523 char_len, &wrote_len, error);
2525 /* We validate UTF-8, so we can't get a partial write */
2527 g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2529 return status;
2533 * G_IO_CHANNEL_ERROR:
2535 * Error domain for #GIOChannel operations. Errors in this domain will
2536 * be from the #GIOChannelError enumeration. See #GError for
2537 * information on error domains.
2540 * GIOChannelError:
2541 * @G_IO_CHANNEL_ERROR_FBIG: File too large.
2542 * @G_IO_CHANNEL_ERROR_INVAL: Invalid argument.
2543 * @G_IO_CHANNEL_ERROR_IO: IO error.
2544 * @G_IO_CHANNEL_ERROR_ISDIR: File is a directory.
2545 * @G_IO_CHANNEL_ERROR_NOSPC: No space left on device.
2546 * @G_IO_CHANNEL_ERROR_NXIO: No such device or address.
2547 * @G_IO_CHANNEL_ERROR_OVERFLOW: Value too large for defined datatype.
2548 * @G_IO_CHANNEL_ERROR_PIPE: Broken pipe.
2549 * @G_IO_CHANNEL_ERROR_FAILED: Some other error.
2551 * Error codes returned by #GIOChannel operations.
2554 G_DEFINE_QUARK (g-io-channel-error-quark, g_io_channel_error)