Skip to main content

gio/auto/
input_stream.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4
5use crate::{AsyncResult, Cancellable, ffi};
6use glib::{prelude::*, translate::*};
7use std::{boxed::Box as Box_, pin::Pin};
8
9glib::wrapper! {
10    /// `GInputStream` is a base class for implementing streaming input.
11    ///
12    /// It has functions to read from a stream ([`InputStreamExtManual::read()`][crate::prelude::InputStreamExtManual::read()]),
13    /// to close a stream ([`InputStreamExt::close()`][crate::prelude::InputStreamExt::close()]) and to skip some content
14    /// ([`InputStreamExt::skip()`][crate::prelude::InputStreamExt::skip()]).
15    ///
16    /// To copy the content of an input stream to an output stream without
17    /// manually handling the reads and writes, use [`OutputStreamExt::splice()`][crate::prelude::OutputStreamExt::splice()].
18    ///
19    /// See the documentation for [`IOStream`][crate::IOStream] for details of thread safety
20    /// of streaming APIs.
21    ///
22    /// All of these functions have async variants too.
23    ///
24    /// This is an Abstract Base Class, you cannot instantiate it.
25    ///
26    /// # Implements
27    ///
28    /// [`InputStreamExt`][trait@crate::prelude::InputStreamExt], [`trait@glib::ObjectExt`], [`InputStreamExtManual`][trait@crate::prelude::InputStreamExtManual]
29    #[doc(alias = "GInputStream")]
30    pub struct InputStream(Object<ffi::GInputStream, ffi::GInputStreamClass>);
31
32    match fn {
33        type_ => || ffi::g_input_stream_get_type(),
34    }
35}
36
37impl InputStream {
38    pub const NONE: Option<&'static InputStream> = None;
39}
40
41/// Trait containing all [`struct@InputStream`] methods.
42///
43/// # Implementors
44///
45/// [`FileInputStream`][struct@crate::FileInputStream], [`FilterInputStream`][struct@crate::FilterInputStream], [`InputStream`][struct@crate::InputStream], [`MemoryInputStream`][struct@crate::MemoryInputStream], [`PollableInputStream`][struct@crate::PollableInputStream]
46pub trait InputStreamExt: IsA<InputStream> + 'static {
47    /// Clears the pending flag on @self.
48    #[doc(alias = "g_input_stream_clear_pending")]
49    fn clear_pending(&self) {
50        unsafe {
51            ffi::g_input_stream_clear_pending(self.as_ref().to_glib_none().0);
52        }
53    }
54
55    /// Closes the stream, releasing resources related to it.
56    ///
57    /// Once the stream is closed, all other operations will return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
58    /// Closing a stream multiple times will not return an error.
59    ///
60    /// Streams will be automatically closed when the last reference
61    /// is dropped, but you might want to call this function to make sure
62    /// resources are released as early as possible.
63    ///
64    /// Some streams might keep the backing store of the stream (e.g. a file descriptor)
65    /// open after the stream is closed. See the documentation for the individual
66    /// stream for details.
67    ///
68    /// On failure the first error that happened will be reported, but the close
69    /// operation will finish as much as possible. A stream that failed to
70    /// close will still return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed] for all operations. Still, it
71    /// is important to check and report the error to the user.
72    ///
73    /// If @cancellable is not [`None`], then the operation can be cancelled by
74    /// triggering the cancellable object from another thread. If the operation
75    /// was cancelled, the error [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] will be returned.
76    /// Cancelling a close will still leave the stream closed, but some streams
77    /// can use a faster close that doesn't block to e.g. check errors.
78    /// ## `cancellable`
79    /// optional #GCancellable object, [`None`] to ignore.
80    ///
81    /// # Returns
82    ///
83    /// [`true`] on success, [`false`] on failure
84    #[doc(alias = "g_input_stream_close")]
85    fn close(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<(), glib::Error> {
86        unsafe {
87            let mut error = std::ptr::null_mut();
88            let is_ok = ffi::g_input_stream_close(
89                self.as_ref().to_glib_none().0,
90                cancellable.map(|p| p.as_ref()).to_glib_none().0,
91                &mut error,
92            );
93            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
94            if error.is_null() {
95                Ok(())
96            } else {
97                Err(from_glib_full(error))
98            }
99        }
100    }
101
102    /// Requests an asynchronous closes of the stream, releasing resources related to it.
103    /// When the operation is finished @callback will be called.
104    /// You can then call g_input_stream_close_finish() to get the result of the
105    /// operation.
106    ///
107    /// For behaviour details see g_input_stream_close().
108    ///
109    /// The asynchronous methods have a default fallback that uses threads to implement
110    /// asynchronicity, so they are optional for inheriting classes. However, if you
111    /// override one you must override all.
112    /// ## `io_priority`
113    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
114    /// ## `cancellable`
115    /// optional cancellable object
116    /// ## `callback`
117    /// a #GAsyncReadyCallback
118    ///   to call when the request is satisfied
119    #[doc(alias = "g_input_stream_close_async")]
120    fn close_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
121        &self,
122        io_priority: glib::Priority,
123        cancellable: Option<&impl IsA<Cancellable>>,
124        callback: P,
125    ) {
126        let main_context = glib::MainContext::ref_thread_default();
127        let is_main_context_owner = main_context.is_owner();
128        let has_acquired_main_context = (!is_main_context_owner)
129            .then(|| main_context.acquire().ok())
130            .flatten();
131        assert!(
132            is_main_context_owner || has_acquired_main_context.is_some(),
133            "Async operations only allowed if the thread is owning the MainContext"
134        );
135
136        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
137            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
138        unsafe extern "C" fn close_async_trampoline<
139            P: FnOnce(Result<(), glib::Error>) + 'static,
140        >(
141            _source_object: *mut glib::gobject_ffi::GObject,
142            res: *mut crate::ffi::GAsyncResult,
143            user_data: glib::ffi::gpointer,
144        ) {
145            unsafe {
146                let mut error = std::ptr::null_mut();
147                ffi::g_input_stream_close_finish(_source_object as *mut _, res, &mut error);
148                let result = if error.is_null() {
149                    Ok(())
150                } else {
151                    Err(from_glib_full(error))
152                };
153                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
154                    Box_::from_raw(user_data as *mut _);
155                let callback: P = callback.into_inner();
156                callback(result);
157            }
158        }
159        let callback = close_async_trampoline::<P>;
160        unsafe {
161            ffi::g_input_stream_close_async(
162                self.as_ref().to_glib_none().0,
163                io_priority.into_glib(),
164                cancellable.map(|p| p.as_ref()).to_glib_none().0,
165                Some(callback),
166                Box_::into_raw(user_data) as *mut _,
167            );
168        }
169    }
170
171    fn close_future(
172        &self,
173        io_priority: glib::Priority,
174    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
175        Box_::pin(crate::GioFuture::new(
176            self,
177            move |obj, cancellable, send| {
178                obj.close_async(io_priority, Some(cancellable), move |res| {
179                    send.resolve(res);
180                });
181            },
182        ))
183    }
184
185    /// Checks if an input stream has pending actions.
186    ///
187    /// # Returns
188    ///
189    /// [`true`] if @self has pending actions.
190    #[doc(alias = "g_input_stream_has_pending")]
191    fn has_pending(&self) -> bool {
192        unsafe {
193            from_glib(ffi::g_input_stream_has_pending(
194                self.as_ref().to_glib_none().0,
195            ))
196        }
197    }
198
199    /// Checks if an input stream has been closed.
200    ///
201    /// This only indicates whether the stream has been closed from this end by
202    /// calling [`close()`][Self::close()]. If the stream is a pipe or socket,
203    /// for example, and the process on the other end has closed its end, this method
204    /// will still return false. Methods which try to read from the input stream will
205    /// return any remaining data, end-of-file or an error, however.
206    ///
207    /// # Returns
208    ///
209    /// true if the stream has been closed; false otherwise
210    #[doc(alias = "g_input_stream_is_closed")]
211    fn is_closed(&self) -> bool {
212        unsafe {
213            from_glib(ffi::g_input_stream_is_closed(
214                self.as_ref().to_glib_none().0,
215            ))
216        }
217    }
218
219    /// Like g_input_stream_read(), this tries to read @count bytes from
220    /// the stream in a blocking fashion. However, rather than reading into
221    /// a user-supplied buffer, this will create a new #GBytes containing
222    /// the data that was read. This may be easier to use from language
223    /// bindings.
224    ///
225    /// If count is zero, returns a zero-length #GBytes and does nothing. A
226    /// value of @count larger than `G_MAXSSIZE` will cause a
227    /// [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument] error.
228    ///
229    /// On success, a new #GBytes is returned. It is not an error if the
230    /// size of this object is not the same as the requested size, as it
231    /// can happen e.g. near the end of a file. A zero-length #GBytes is
232    /// returned on end of file (or if @count is zero), but never
233    /// otherwise.
234    ///
235    /// If @cancellable is not [`None`], then the operation can be cancelled by
236    /// triggering the cancellable object from another thread. If the operation
237    /// was cancelled, the error [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] will be returned. If an
238    /// operation was partially finished when the operation was cancelled the
239    /// partial result will be returned, without an error.
240    ///
241    /// On error [`None`] is returned and @error is set accordingly.
242    /// ## `count`
243    /// maximum number of bytes that will be read from the stream. Common
244    /// values include 4096 and 8192.
245    /// ## `cancellable`
246    /// optional #GCancellable object, [`None`] to ignore.
247    ///
248    /// # Returns
249    ///
250    /// a new #GBytes, or [`None`] on error
251    #[doc(alias = "g_input_stream_read_bytes")]
252    fn read_bytes(
253        &self,
254        count: usize,
255        cancellable: Option<&impl IsA<Cancellable>>,
256    ) -> Result<glib::Bytes, glib::Error> {
257        unsafe {
258            let mut error = std::ptr::null_mut();
259            let ret = ffi::g_input_stream_read_bytes(
260                self.as_ref().to_glib_none().0,
261                count,
262                cancellable.map(|p| p.as_ref()).to_glib_none().0,
263                &mut error,
264            );
265            if error.is_null() {
266                Ok(from_glib_full(ret))
267            } else {
268                Err(from_glib_full(error))
269            }
270        }
271    }
272
273    /// Request an asynchronous read of @count bytes from the stream into a
274    /// new #GBytes. When the operation is finished @callback will be
275    /// called. You can then call g_input_stream_read_bytes_finish() to get the
276    /// result of the operation.
277    ///
278    /// During an async request no other sync and async calls are allowed
279    /// on @self, and will result in [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] errors.
280    ///
281    /// A value of @count larger than `G_MAXSSIZE` will cause a
282    /// [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument] error.
283    ///
284    /// On success, the new #GBytes will be passed to the callback. It is
285    /// not an error if this is smaller than the requested size, as it can
286    /// happen e.g. near the end of a file, but generally we try to read as
287    /// many bytes as requested. Zero is returned on end of file (or if
288    /// @count is zero), but never otherwise.
289    ///
290    /// Any outstanding I/O request with higher priority (lower numerical
291    /// value) will be executed before an outstanding request with lower
292    /// priority. Default priority is `G_PRIORITY_DEFAULT`.
293    /// ## `count`
294    /// the number of bytes that will be read from the stream
295    /// ## `io_priority`
296    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
297    /// ## `cancellable`
298    /// optional #GCancellable object, [`None`] to ignore.
299    /// ## `callback`
300    /// a #GAsyncReadyCallback
301    ///   to call when the request is satisfied
302    #[doc(alias = "g_input_stream_read_bytes_async")]
303    fn read_bytes_async<P: FnOnce(Result<glib::Bytes, glib::Error>) + 'static>(
304        &self,
305        count: usize,
306        io_priority: glib::Priority,
307        cancellable: Option<&impl IsA<Cancellable>>,
308        callback: P,
309    ) {
310        let main_context = glib::MainContext::ref_thread_default();
311        let is_main_context_owner = main_context.is_owner();
312        let has_acquired_main_context = (!is_main_context_owner)
313            .then(|| main_context.acquire().ok())
314            .flatten();
315        assert!(
316            is_main_context_owner || has_acquired_main_context.is_some(),
317            "Async operations only allowed if the thread is owning the MainContext"
318        );
319
320        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
321            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
322        unsafe extern "C" fn read_bytes_async_trampoline<
323            P: FnOnce(Result<glib::Bytes, glib::Error>) + 'static,
324        >(
325            _source_object: *mut glib::gobject_ffi::GObject,
326            res: *mut crate::ffi::GAsyncResult,
327            user_data: glib::ffi::gpointer,
328        ) {
329            unsafe {
330                let mut error = std::ptr::null_mut();
331                let ret = ffi::g_input_stream_read_bytes_finish(
332                    _source_object as *mut _,
333                    res,
334                    &mut error,
335                );
336                let result = if error.is_null() {
337                    Ok(from_glib_full(ret))
338                } else {
339                    Err(from_glib_full(error))
340                };
341                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
342                    Box_::from_raw(user_data as *mut _);
343                let callback: P = callback.into_inner();
344                callback(result);
345            }
346        }
347        let callback = read_bytes_async_trampoline::<P>;
348        unsafe {
349            ffi::g_input_stream_read_bytes_async(
350                self.as_ref().to_glib_none().0,
351                count,
352                io_priority.into_glib(),
353                cancellable.map(|p| p.as_ref()).to_glib_none().0,
354                Some(callback),
355                Box_::into_raw(user_data) as *mut _,
356            );
357        }
358    }
359
360    fn read_bytes_future(
361        &self,
362        count: usize,
363        io_priority: glib::Priority,
364    ) -> Pin<Box_<dyn std::future::Future<Output = Result<glib::Bytes, glib::Error>> + 'static>>
365    {
366        Box_::pin(crate::GioFuture::new(
367            self,
368            move |obj, cancellable, send| {
369                obj.read_bytes_async(count, io_priority, Some(cancellable), move |res| {
370                    send.resolve(res);
371                });
372            },
373        ))
374    }
375
376    /// Sets @self to have actions pending. If the pending flag is
377    /// already set or @self is closed, it will return [`false`] and set
378    /// @error.
379    ///
380    /// # Returns
381    ///
382    /// [`true`] if pending was previously unset and is now set.
383    #[doc(alias = "g_input_stream_set_pending")]
384    fn set_pending(&self) -> Result<(), glib::Error> {
385        unsafe {
386            let mut error = std::ptr::null_mut();
387            let is_ok = ffi::g_input_stream_set_pending(self.as_ref().to_glib_none().0, &mut error);
388            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
389            if error.is_null() {
390                Ok(())
391            } else {
392                Err(from_glib_full(error))
393            }
394        }
395    }
396
397    /// Tries to skip @count bytes from the stream. Will block during the operation.
398    ///
399    /// This is identical to g_input_stream_read(), from a behaviour standpoint,
400    /// but the bytes that are skipped are not returned to the user. Some
401    /// streams have an implementation that is more efficient than reading the data.
402    ///
403    /// This function is optional for inherited classes, as the default implementation
404    /// emulates it using read.
405    ///
406    /// If @cancellable is not [`None`], then the operation can be cancelled by
407    /// triggering the cancellable object from another thread. If the operation
408    /// was cancelled, the error [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] will be returned. If an
409    /// operation was partially finished when the operation was cancelled the
410    /// partial result will be returned, without an error.
411    /// ## `count`
412    /// the number of bytes that will be skipped from the stream
413    /// ## `cancellable`
414    /// optional #GCancellable object, [`None`] to ignore.
415    ///
416    /// # Returns
417    ///
418    /// Number of bytes skipped, or -1 on error
419    #[doc(alias = "g_input_stream_skip")]
420    fn skip(
421        &self,
422        count: usize,
423        cancellable: Option<&impl IsA<Cancellable>>,
424    ) -> Result<isize, glib::Error> {
425        unsafe {
426            let mut error = std::ptr::null_mut();
427            let ret = ffi::g_input_stream_skip(
428                self.as_ref().to_glib_none().0,
429                count,
430                cancellable.map(|p| p.as_ref()).to_glib_none().0,
431                &mut error,
432            );
433            if error.is_null() {
434                Ok(ret)
435            } else {
436                Err(from_glib_full(error))
437            }
438        }
439    }
440
441    /// Request an asynchronous skip of @count bytes from the stream.
442    /// When the operation is finished @callback will be called.
443    /// You can then call g_input_stream_skip_finish() to get the result
444    /// of the operation.
445    ///
446    /// During an async request no other sync and async calls are allowed,
447    /// and will result in [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] errors.
448    ///
449    /// A value of @count larger than `G_MAXSSIZE` will cause a [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument] error.
450    ///
451    /// On success, the number of bytes skipped will be passed to the callback.
452    /// It is not an error if this is not the same as the requested size, as it
453    /// can happen e.g. near the end of a file, but generally we try to skip
454    /// as many bytes as requested. Zero is returned on end of file
455    /// (or if @count is zero), but never otherwise.
456    ///
457    /// Any outstanding i/o request with higher priority (lower numerical value)
458    /// will be executed before an outstanding request with lower priority.
459    /// Default priority is `G_PRIORITY_DEFAULT`.
460    ///
461    /// The asynchronous methods have a default fallback that uses threads to
462    /// implement asynchronicity, so they are optional for inheriting classes.
463    /// However, if you override one, you must override all.
464    /// ## `count`
465    /// the number of bytes that will be skipped from the stream
466    /// ## `io_priority`
467    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
468    /// ## `cancellable`
469    /// optional #GCancellable object, [`None`] to ignore.
470    /// ## `callback`
471    /// a #GAsyncReadyCallback
472    ///   to call when the request is satisfied
473    #[doc(alias = "g_input_stream_skip_async")]
474    fn skip_async<P: FnOnce(Result<isize, glib::Error>) + 'static>(
475        &self,
476        count: usize,
477        io_priority: glib::Priority,
478        cancellable: Option<&impl IsA<Cancellable>>,
479        callback: P,
480    ) {
481        let main_context = glib::MainContext::ref_thread_default();
482        let is_main_context_owner = main_context.is_owner();
483        let has_acquired_main_context = (!is_main_context_owner)
484            .then(|| main_context.acquire().ok())
485            .flatten();
486        assert!(
487            is_main_context_owner || has_acquired_main_context.is_some(),
488            "Async operations only allowed if the thread is owning the MainContext"
489        );
490
491        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
492            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
493        unsafe extern "C" fn skip_async_trampoline<
494            P: FnOnce(Result<isize, glib::Error>) + 'static,
495        >(
496            _source_object: *mut glib::gobject_ffi::GObject,
497            res: *mut crate::ffi::GAsyncResult,
498            user_data: glib::ffi::gpointer,
499        ) {
500            unsafe {
501                let mut error = std::ptr::null_mut();
502                let ret =
503                    ffi::g_input_stream_skip_finish(_source_object as *mut _, res, &mut error);
504                let result = if error.is_null() {
505                    Ok(ret)
506                } else {
507                    Err(from_glib_full(error))
508                };
509                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
510                    Box_::from_raw(user_data as *mut _);
511                let callback: P = callback.into_inner();
512                callback(result);
513            }
514        }
515        let callback = skip_async_trampoline::<P>;
516        unsafe {
517            ffi::g_input_stream_skip_async(
518                self.as_ref().to_glib_none().0,
519                count,
520                io_priority.into_glib(),
521                cancellable.map(|p| p.as_ref()).to_glib_none().0,
522                Some(callback),
523                Box_::into_raw(user_data) as *mut _,
524            );
525        }
526    }
527
528    fn skip_future(
529        &self,
530        count: usize,
531        io_priority: glib::Priority,
532    ) -> Pin<Box_<dyn std::future::Future<Output = Result<isize, glib::Error>> + 'static>> {
533        Box_::pin(crate::GioFuture::new(
534            self,
535            move |obj, cancellable, send| {
536                obj.skip_async(count, io_priority, Some(cancellable), move |res| {
537                    send.resolve(res);
538                });
539            },
540        ))
541    }
542}
543
544impl<O: IsA<InputStream>> InputStreamExt for O {}