gio/auto/buffered_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::{ffi, AsyncResult, Cancellable, FilterInputStream, InputStream, Seekable};
6use glib::{
7 prelude::*,
8 signal::{connect_raw, SignalHandlerId},
9 translate::*,
10};
11use std::{boxed::Box as Box_, pin::Pin};
12
13glib::wrapper! {
14 /// Buffered input stream implements [`FilterInputStream`][crate::FilterInputStream] and provides
15 /// for buffered reads.
16 ///
17 /// By default, `GBufferedInputStream`'s buffer size is set at 4 kilobytes.
18 ///
19 /// To create a buffered input stream, use [`new()`][Self::new()],
20 /// or [`new_sized()`][Self::new_sized()] to specify the buffer's size at
21 /// construction.
22 ///
23 /// To get the size of a buffer within a buffered input stream, use
24 /// [`BufferedInputStreamExt::buffer_size()`][crate::prelude::BufferedInputStreamExt::buffer_size()]. To change the size of a
25 /// buffered input stream's buffer, use [`BufferedInputStreamExt::set_buffer_size()`][crate::prelude::BufferedInputStreamExt::set_buffer_size()].
26 /// Note that the buffer's size cannot be reduced below the size of the data within the buffer.
27 ///
28 /// ## Properties
29 ///
30 ///
31 /// #### `buffer-size`
32 /// The size of the backend buffer, in bytes.
33 ///
34 /// Readable | Writeable | Construct
35 /// <details><summary><h4>FilterInputStream</h4></summary>
36 ///
37 ///
38 /// #### `base-stream`
39 /// The underlying base stream on which the I/O ops will be done.
40 ///
41 /// Readable | Writeable | Construct Only
42 ///
43 ///
44 /// #### `close-base-stream`
45 /// Whether the base stream should be closed when the filter stream is closed.
46 ///
47 /// Readable | Writeable | Construct
48 /// </details>
49 ///
50 /// # Implements
51 ///
52 /// [`BufferedInputStreamExt`][trait@crate::prelude::BufferedInputStreamExt], [`FilterInputStreamExt`][trait@crate::prelude::FilterInputStreamExt], [`InputStreamExt`][trait@crate::prelude::InputStreamExt], [`trait@glib::ObjectExt`], [`SeekableExt`][trait@crate::prelude::SeekableExt], [`InputStreamExtManual`][trait@crate::prelude::InputStreamExtManual]
53 #[doc(alias = "GBufferedInputStream")]
54 pub struct BufferedInputStream(Object<ffi::GBufferedInputStream, ffi::GBufferedInputStreamClass>) @extends FilterInputStream, InputStream, @implements Seekable;
55
56 match fn {
57 type_ => || ffi::g_buffered_input_stream_get_type(),
58 }
59}
60
61impl BufferedInputStream {
62 pub const NONE: Option<&'static BufferedInputStream> = None;
63
64 /// Creates a new [`InputStream`][crate::InputStream] from the given @base_stream, with
65 /// a buffer set to the default size (4 kilobytes).
66 /// ## `base_stream`
67 /// a [`InputStream`][crate::InputStream]
68 ///
69 /// # Returns
70 ///
71 /// a [`InputStream`][crate::InputStream] for the given @base_stream.
72 #[doc(alias = "g_buffered_input_stream_new")]
73 pub fn new(base_stream: &impl IsA<InputStream>) -> BufferedInputStream {
74 unsafe {
75 InputStream::from_glib_full(ffi::g_buffered_input_stream_new(
76 base_stream.as_ref().to_glib_none().0,
77 ))
78 .unsafe_cast()
79 }
80 }
81
82 /// Creates a new [`BufferedInputStream`][crate::BufferedInputStream] from the given @base_stream,
83 /// with a buffer set to @size.
84 /// ## `base_stream`
85 /// a [`InputStream`][crate::InputStream]
86 /// ## `size`
87 /// a #gsize
88 ///
89 /// # Returns
90 ///
91 /// a [`InputStream`][crate::InputStream].
92 #[doc(alias = "g_buffered_input_stream_new_sized")]
93 pub fn new_sized(base_stream: &impl IsA<InputStream>, size: usize) -> BufferedInputStream {
94 unsafe {
95 InputStream::from_glib_full(ffi::g_buffered_input_stream_new_sized(
96 base_stream.as_ref().to_glib_none().0,
97 size,
98 ))
99 .unsafe_cast()
100 }
101 }
102
103 // rustdoc-stripper-ignore-next
104 /// Creates a new builder-pattern struct instance to construct [`BufferedInputStream`] objects.
105 ///
106 /// This method returns an instance of [`BufferedInputStreamBuilder`](crate::builders::BufferedInputStreamBuilder) which can be used to create [`BufferedInputStream`] objects.
107 pub fn builder() -> BufferedInputStreamBuilder {
108 BufferedInputStreamBuilder::new()
109 }
110}
111
112impl Default for BufferedInputStream {
113 fn default() -> Self {
114 glib::object::Object::new::<Self>()
115 }
116}
117
118// rustdoc-stripper-ignore-next
119/// A [builder-pattern] type to construct [`BufferedInputStream`] objects.
120///
121/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
122#[must_use = "The builder must be built to be used"]
123pub struct BufferedInputStreamBuilder {
124 builder: glib::object::ObjectBuilder<'static, BufferedInputStream>,
125}
126
127impl BufferedInputStreamBuilder {
128 fn new() -> Self {
129 Self {
130 builder: glib::object::Object::builder(),
131 }
132 }
133
134 /// The size of the backend buffer, in bytes.
135 pub fn buffer_size(self, buffer_size: u32) -> Self {
136 Self {
137 builder: self.builder.property("buffer-size", buffer_size),
138 }
139 }
140
141 /// The underlying base stream on which the I/O ops will be done.
142 pub fn base_stream(self, base_stream: &impl IsA<InputStream>) -> Self {
143 Self {
144 builder: self
145 .builder
146 .property("base-stream", base_stream.clone().upcast()),
147 }
148 }
149
150 /// Whether the base stream should be closed when the filter stream is closed.
151 pub fn close_base_stream(self, close_base_stream: bool) -> Self {
152 Self {
153 builder: self
154 .builder
155 .property("close-base-stream", close_base_stream),
156 }
157 }
158
159 // rustdoc-stripper-ignore-next
160 /// Build the [`BufferedInputStream`].
161 #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
162 pub fn build(self) -> BufferedInputStream {
163 self.builder.build()
164 }
165}
166
167/// Trait containing all [`struct@BufferedInputStream`] methods.
168///
169/// # Implementors
170///
171/// [`BufferedInputStream`][struct@crate::BufferedInputStream], [`DataInputStream`][struct@crate::DataInputStream]
172pub trait BufferedInputStreamExt: IsA<BufferedInputStream> + 'static {
173 /// Tries to read @count bytes from the stream into the buffer.
174 /// Will block during this read.
175 ///
176 /// If @count is zero, returns zero and does nothing. A value of @count
177 /// larger than `G_MAXSSIZE` will cause a
178 /// [error@Gio.IOErrorEnum.INVALID_ARGUMENT] error.
179 ///
180 /// On success, the number of bytes read into the buffer is returned.
181 /// It is not an error if this is not the same as the requested size, as it
182 /// can happen e.g. near the end of a file. Zero is returned on end of file
183 /// (or if @count is zero), but never otherwise.
184 ///
185 /// If @count is -1 then the attempted read size is equal to the number of
186 /// bytes that are required to fill the buffer.
187 ///
188 /// If @cancellable is not `NULL`, then the operation can be cancelled by
189 /// triggering the cancellable object from another thread. If the operation
190 /// was cancelled, the error [error@Gio.IOErrorEnum.CANCELLED] will be returned.
191 /// If an operation was partially finished when the operation was cancelled the
192 /// partial result will be returned, without an error.
193 ///
194 /// On error `-1` is returned and @error is set accordingly.
195 ///
196 /// For the asynchronous, non-blocking, version of this function, see
197 /// [`fill_async()`][Self::fill_async()].
198 /// ## `count`
199 /// the number of bytes that will be read from the stream
200 /// ## `cancellable`
201 /// optional [`Cancellable`][crate::Cancellable] object, `NULL` to ignore
202 ///
203 /// # Returns
204 ///
205 /// the number of bytes read into @self's buffer, up to @count,
206 /// or `-1` on error.
207 #[doc(alias = "g_buffered_input_stream_fill")]
208 fn fill(
209 &self,
210 count: isize,
211 cancellable: Option<&impl IsA<Cancellable>>,
212 ) -> Result<isize, glib::Error> {
213 unsafe {
214 let mut error = std::ptr::null_mut();
215 let ret = ffi::g_buffered_input_stream_fill(
216 self.as_ref().to_glib_none().0,
217 count,
218 cancellable.map(|p| p.as_ref()).to_glib_none().0,
219 &mut error,
220 );
221 if error.is_null() {
222 Ok(ret)
223 } else {
224 Err(from_glib_full(error))
225 }
226 }
227 }
228
229 /// Reads data into @self's buffer asynchronously, up to @count size.
230 /// @io_priority can be used to prioritize reads. For the synchronous
231 /// version of this function, see [`fill()`][Self::fill()].
232 ///
233 /// If @count is `-1` then the attempted read size is equal to the number
234 /// of bytes that are required to fill the buffer.
235 /// ## `count`
236 /// the number of bytes that will be read from the stream
237 /// ## `io_priority`
238 /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
239 /// ## `cancellable`
240 /// optional [`Cancellable`][crate::Cancellable] object
241 /// ## `callback`
242 /// a `callback::Gio::AsyncReadyCallback
243 #[doc(alias = "g_buffered_input_stream_fill_async")]
244 fn fill_async<P: FnOnce(Result<isize, glib::Error>) + 'static>(
245 &self,
246 count: isize,
247 io_priority: glib::Priority,
248 cancellable: Option<&impl IsA<Cancellable>>,
249 callback: P,
250 ) {
251 let main_context = glib::MainContext::ref_thread_default();
252 let is_main_context_owner = main_context.is_owner();
253 let has_acquired_main_context = (!is_main_context_owner)
254 .then(|| main_context.acquire().ok())
255 .flatten();
256 assert!(
257 is_main_context_owner || has_acquired_main_context.is_some(),
258 "Async operations only allowed if the thread is owning the MainContext"
259 );
260
261 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
262 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
263 unsafe extern "C" fn fill_async_trampoline<
264 P: FnOnce(Result<isize, glib::Error>) + 'static,
265 >(
266 _source_object: *mut glib::gobject_ffi::GObject,
267 res: *mut crate::ffi::GAsyncResult,
268 user_data: glib::ffi::gpointer,
269 ) {
270 let mut error = std::ptr::null_mut();
271 let ret =
272 ffi::g_buffered_input_stream_fill_finish(_source_object as *mut _, res, &mut error);
273 let result = if error.is_null() {
274 Ok(ret)
275 } else {
276 Err(from_glib_full(error))
277 };
278 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
279 Box_::from_raw(user_data as *mut _);
280 let callback: P = callback.into_inner();
281 callback(result);
282 }
283 let callback = fill_async_trampoline::<P>;
284 unsafe {
285 ffi::g_buffered_input_stream_fill_async(
286 self.as_ref().to_glib_none().0,
287 count,
288 io_priority.into_glib(),
289 cancellable.map(|p| p.as_ref()).to_glib_none().0,
290 Some(callback),
291 Box_::into_raw(user_data) as *mut _,
292 );
293 }
294 }
295
296 fn fill_future(
297 &self,
298 count: isize,
299 io_priority: glib::Priority,
300 ) -> Pin<Box_<dyn std::future::Future<Output = Result<isize, glib::Error>> + 'static>> {
301 Box_::pin(crate::GioFuture::new(
302 self,
303 move |obj, cancellable, send| {
304 obj.fill_async(count, io_priority, Some(cancellable), move |res| {
305 send.resolve(res);
306 });
307 },
308 ))
309 }
310
311 /// Gets the size of the available data within the stream.
312 ///
313 /// # Returns
314 ///
315 /// size of the available stream.
316 #[doc(alias = "g_buffered_input_stream_get_available")]
317 #[doc(alias = "get_available")]
318 fn available(&self) -> usize {
319 unsafe { ffi::g_buffered_input_stream_get_available(self.as_ref().to_glib_none().0) }
320 }
321
322 /// Gets the size of the input buffer.
323 ///
324 /// # Returns
325 ///
326 /// the current buffer size.
327 #[doc(alias = "g_buffered_input_stream_get_buffer_size")]
328 #[doc(alias = "get_buffer_size")]
329 #[doc(alias = "buffer-size")]
330 fn buffer_size(&self) -> usize {
331 unsafe { ffi::g_buffered_input_stream_get_buffer_size(self.as_ref().to_glib_none().0) }
332 }
333
334 /// Returns the buffer with the currently available bytes. The returned
335 /// buffer must not be modified and will become invalid when reading from
336 /// the stream or filling the buffer.
337 ///
338 /// # Returns
339 ///
340 ///
341 /// read-only buffer
342 #[doc(alias = "g_buffered_input_stream_peek_buffer")]
343 fn peek_buffer(&self) -> Vec<u8> {
344 unsafe {
345 let mut count = std::mem::MaybeUninit::uninit();
346 let ret = FromGlibContainer::from_glib_none_num(
347 ffi::g_buffered_input_stream_peek_buffer(
348 self.as_ref().to_glib_none().0,
349 count.as_mut_ptr(),
350 ),
351 count.assume_init() as _,
352 );
353 ret
354 }
355 }
356
357 /// Tries to read a single byte from the stream or the buffer. Will block
358 /// during this read.
359 ///
360 /// On success, the byte read from the stream is returned. On end of stream
361 /// `-1` is returned but it's not an exceptional error and @error is not set.
362 ///
363 /// If @cancellable is not `NULL`, then the operation can be cancelled by
364 /// triggering the cancellable object from another thread. If the operation
365 /// was cancelled, the error [error@Gio.IOErrorEnum.CANCELLED] will be returned.
366 /// If an operation was partially finished when the operation was cancelled the
367 /// partial result will be returned, without an error.
368 ///
369 /// On error `-1` is returned and @error is set accordingly.
370 /// ## `cancellable`
371 /// optional [`Cancellable`][crate::Cancellable] object, `NULL` to ignore
372 ///
373 /// # Returns
374 ///
375 /// the byte read from the @self, or `-1` on end of stream or error.
376 #[doc(alias = "g_buffered_input_stream_read_byte")]
377 fn read_byte(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<i32, glib::Error> {
378 unsafe {
379 let mut error = std::ptr::null_mut();
380 let ret = ffi::g_buffered_input_stream_read_byte(
381 self.as_ref().to_glib_none().0,
382 cancellable.map(|p| p.as_ref()).to_glib_none().0,
383 &mut error,
384 );
385 if error.is_null() {
386 Ok(ret)
387 } else {
388 Err(from_glib_full(error))
389 }
390 }
391 }
392
393 /// Sets the size of the internal buffer of @self to @size, or to the
394 /// size of the contents of the buffer. The buffer can never be resized
395 /// smaller than its current contents.
396 /// ## `size`
397 /// a #gsize
398 #[doc(alias = "g_buffered_input_stream_set_buffer_size")]
399 #[doc(alias = "buffer-size")]
400 fn set_buffer_size(&self, size: usize) {
401 unsafe {
402 ffi::g_buffered_input_stream_set_buffer_size(self.as_ref().to_glib_none().0, size);
403 }
404 }
405
406 #[doc(alias = "buffer-size")]
407 fn connect_buffer_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
408 unsafe extern "C" fn notify_buffer_size_trampoline<
409 P: IsA<BufferedInputStream>,
410 F: Fn(&P) + 'static,
411 >(
412 this: *mut ffi::GBufferedInputStream,
413 _param_spec: glib::ffi::gpointer,
414 f: glib::ffi::gpointer,
415 ) {
416 let f: &F = &*(f as *const F);
417 f(BufferedInputStream::from_glib_borrow(this).unsafe_cast_ref())
418 }
419 unsafe {
420 let f: Box_<F> = Box_::new(f);
421 connect_raw(
422 self.as_ptr() as *mut _,
423 c"notify::buffer-size".as_ptr() as *const _,
424 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
425 notify_buffer_size_trampoline::<Self, F> as *const (),
426 )),
427 Box_::into_raw(f),
428 )
429 }
430 }
431}
432
433impl<O: IsA<BufferedInputStream>> BufferedInputStreamExt for O {}