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
167mod sealed {
168 pub trait Sealed {}
169 impl<T: super::IsA<super::BufferedInputStream>> Sealed for T {}
170}
171
172/// Trait containing all [`struct@BufferedInputStream`] methods.
173///
174/// # Implementors
175///
176/// [`BufferedInputStream`][struct@crate::BufferedInputStream], [`DataInputStream`][struct@crate::DataInputStream]
177pub trait BufferedInputStreamExt: IsA<BufferedInputStream> + sealed::Sealed + 'static {
178 /// Tries to read @count bytes from the stream into the buffer.
179 /// Will block during this read.
180 ///
181 /// If @count is zero, returns zero and does nothing. A value of @count
182 /// larger than `G_MAXSSIZE` will cause a
183 /// [error@Gio.IOErrorEnum.INVALID_ARGUMENT] error.
184 ///
185 /// On success, the number of bytes read into the buffer is returned.
186 /// It is not an error if this is not the same as the requested size, as it
187 /// can happen e.g. near the end of a file. Zero is returned on end of file
188 /// (or if @count is zero), but never otherwise.
189 ///
190 /// If @count is -1 then the attempted read size is equal to the number of
191 /// bytes that are required to fill the buffer.
192 ///
193 /// If @cancellable is not `NULL`, then the operation can be cancelled by
194 /// triggering the cancellable object from another thread. If the operation
195 /// was cancelled, the error [error@Gio.IOErrorEnum.CANCELLED] will be returned.
196 /// If an operation was partially finished when the operation was cancelled the
197 /// partial result will be returned, without an error.
198 ///
199 /// On error `-1` is returned and @error is set accordingly.
200 ///
201 /// For the asynchronous, non-blocking, version of this function, see
202 /// [`fill_async()`][Self::fill_async()].
203 /// ## `count`
204 /// the number of bytes that will be read from the stream
205 /// ## `cancellable`
206 /// optional [`Cancellable`][crate::Cancellable] object, `NULL` to ignore
207 ///
208 /// # Returns
209 ///
210 /// the number of bytes read into @self's buffer, up to @count,
211 /// or `-1` on error.
212 #[doc(alias = "g_buffered_input_stream_fill")]
213 fn fill(
214 &self,
215 count: isize,
216 cancellable: Option<&impl IsA<Cancellable>>,
217 ) -> Result<isize, glib::Error> {
218 unsafe {
219 let mut error = std::ptr::null_mut();
220 let ret = ffi::g_buffered_input_stream_fill(
221 self.as_ref().to_glib_none().0,
222 count,
223 cancellable.map(|p| p.as_ref()).to_glib_none().0,
224 &mut error,
225 );
226 if error.is_null() {
227 Ok(ret)
228 } else {
229 Err(from_glib_full(error))
230 }
231 }
232 }
233
234 /// Reads data into @self's buffer asynchronously, up to @count size.
235 /// @io_priority can be used to prioritize reads. For the synchronous
236 /// version of this function, see [`fill()`][Self::fill()].
237 ///
238 /// If @count is `-1` then the attempted read size is equal to the number
239 /// of bytes that are required to fill the buffer.
240 /// ## `count`
241 /// the number of bytes that will be read from the stream
242 /// ## `io_priority`
243 /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
244 /// ## `cancellable`
245 /// optional [`Cancellable`][crate::Cancellable] object
246 /// ## `callback`
247 /// a `callback::Gio::AsyncReadyCallback
248 #[doc(alias = "g_buffered_input_stream_fill_async")]
249 fn fill_async<P: FnOnce(Result<isize, glib::Error>) + 'static>(
250 &self,
251 count: isize,
252 io_priority: glib::Priority,
253 cancellable: Option<&impl IsA<Cancellable>>,
254 callback: P,
255 ) {
256 let main_context = glib::MainContext::ref_thread_default();
257 let is_main_context_owner = main_context.is_owner();
258 let has_acquired_main_context = (!is_main_context_owner)
259 .then(|| main_context.acquire().ok())
260 .flatten();
261 assert!(
262 is_main_context_owner || has_acquired_main_context.is_some(),
263 "Async operations only allowed if the thread is owning the MainContext"
264 );
265
266 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
267 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
268 unsafe extern "C" fn fill_async_trampoline<
269 P: FnOnce(Result<isize, glib::Error>) + 'static,
270 >(
271 _source_object: *mut glib::gobject_ffi::GObject,
272 res: *mut crate::ffi::GAsyncResult,
273 user_data: glib::ffi::gpointer,
274 ) {
275 let mut error = std::ptr::null_mut();
276 let ret =
277 ffi::g_buffered_input_stream_fill_finish(_source_object as *mut _, res, &mut error);
278 let result = if error.is_null() {
279 Ok(ret)
280 } else {
281 Err(from_glib_full(error))
282 };
283 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
284 Box_::from_raw(user_data as *mut _);
285 let callback: P = callback.into_inner();
286 callback(result);
287 }
288 let callback = fill_async_trampoline::<P>;
289 unsafe {
290 ffi::g_buffered_input_stream_fill_async(
291 self.as_ref().to_glib_none().0,
292 count,
293 io_priority.into_glib(),
294 cancellable.map(|p| p.as_ref()).to_glib_none().0,
295 Some(callback),
296 Box_::into_raw(user_data) as *mut _,
297 );
298 }
299 }
300
301 fn fill_future(
302 &self,
303 count: isize,
304 io_priority: glib::Priority,
305 ) -> Pin<Box_<dyn std::future::Future<Output = Result<isize, glib::Error>> + 'static>> {
306 Box_::pin(crate::GioFuture::new(
307 self,
308 move |obj, cancellable, send| {
309 obj.fill_async(count, io_priority, Some(cancellable), move |res| {
310 send.resolve(res);
311 });
312 },
313 ))
314 }
315
316 /// Gets the size of the available data within the stream.
317 ///
318 /// # Returns
319 ///
320 /// size of the available stream.
321 #[doc(alias = "g_buffered_input_stream_get_available")]
322 #[doc(alias = "get_available")]
323 fn available(&self) -> usize {
324 unsafe { ffi::g_buffered_input_stream_get_available(self.as_ref().to_glib_none().0) }
325 }
326
327 /// Gets the size of the input buffer.
328 ///
329 /// # Returns
330 ///
331 /// the current buffer size.
332 #[doc(alias = "g_buffered_input_stream_get_buffer_size")]
333 #[doc(alias = "get_buffer_size")]
334 #[doc(alias = "buffer-size")]
335 fn buffer_size(&self) -> usize {
336 unsafe { ffi::g_buffered_input_stream_get_buffer_size(self.as_ref().to_glib_none().0) }
337 }
338
339 /// Returns the buffer with the currently available bytes. The returned
340 /// buffer must not be modified and will become invalid when reading from
341 /// the stream or filling the buffer.
342 ///
343 /// # Returns
344 ///
345 ///
346 /// read-only buffer
347 #[doc(alias = "g_buffered_input_stream_peek_buffer")]
348 fn peek_buffer(&self) -> Vec<u8> {
349 unsafe {
350 let mut count = std::mem::MaybeUninit::uninit();
351 let ret = FromGlibContainer::from_glib_none_num(
352 ffi::g_buffered_input_stream_peek_buffer(
353 self.as_ref().to_glib_none().0,
354 count.as_mut_ptr(),
355 ),
356 count.assume_init() as _,
357 );
358 ret
359 }
360 }
361
362 /// Tries to read a single byte from the stream or the buffer. Will block
363 /// during this read.
364 ///
365 /// On success, the byte read from the stream is returned. On end of stream
366 /// `-1` is returned but it's not an exceptional error and @error is not set.
367 ///
368 /// If @cancellable is not `NULL`, then the operation can be cancelled by
369 /// triggering the cancellable object from another thread. If the operation
370 /// was cancelled, the error [error@Gio.IOErrorEnum.CANCELLED] will be returned.
371 /// If an operation was partially finished when the operation was cancelled the
372 /// partial result will be returned, without an error.
373 ///
374 /// On error `-1` is returned and @error is set accordingly.
375 /// ## `cancellable`
376 /// optional [`Cancellable`][crate::Cancellable] object, `NULL` to ignore
377 ///
378 /// # Returns
379 ///
380 /// the byte read from the @self, or `-1` on end of stream or error.
381 #[doc(alias = "g_buffered_input_stream_read_byte")]
382 fn read_byte(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<i32, glib::Error> {
383 unsafe {
384 let mut error = std::ptr::null_mut();
385 let ret = ffi::g_buffered_input_stream_read_byte(
386 self.as_ref().to_glib_none().0,
387 cancellable.map(|p| p.as_ref()).to_glib_none().0,
388 &mut error,
389 );
390 if error.is_null() {
391 Ok(ret)
392 } else {
393 Err(from_glib_full(error))
394 }
395 }
396 }
397
398 /// Sets the size of the internal buffer of @self to @size, or to the
399 /// size of the contents of the buffer. The buffer can never be resized
400 /// smaller than its current contents.
401 /// ## `size`
402 /// a #gsize
403 #[doc(alias = "g_buffered_input_stream_set_buffer_size")]
404 #[doc(alias = "buffer-size")]
405 fn set_buffer_size(&self, size: usize) {
406 unsafe {
407 ffi::g_buffered_input_stream_set_buffer_size(self.as_ref().to_glib_none().0, size);
408 }
409 }
410
411 #[doc(alias = "buffer-size")]
412 fn connect_buffer_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
413 unsafe extern "C" fn notify_buffer_size_trampoline<
414 P: IsA<BufferedInputStream>,
415 F: Fn(&P) + 'static,
416 >(
417 this: *mut ffi::GBufferedInputStream,
418 _param_spec: glib::ffi::gpointer,
419 f: glib::ffi::gpointer,
420 ) {
421 let f: &F = &*(f as *const F);
422 f(BufferedInputStream::from_glib_borrow(this).unsafe_cast_ref())
423 }
424 unsafe {
425 let f: Box_<F> = Box_::new(f);
426 connect_raw(
427 self.as_ptr() as *mut _,
428 b"notify::buffer-size\0".as_ptr() as *const _,
429 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
430 notify_buffer_size_trampoline::<Self, F> as *const (),
431 )),
432 Box_::into_raw(f),
433 )
434 }
435 }
436}
437
438impl<O: IsA<BufferedInputStream>> BufferedInputStreamExt for O {}