orengine 0.7.0-alpha.1

Optimized ring engine for Rust. It is a lighter and faster asynchronous library than tokio-rs, async-std, may, and even smol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use crate as orengine;
use crate::io::io_request_data::IoRequestData;
use crate::io::sys::{AsRawFd, RawFd};
use crate::io::worker::{local_worker, IoWorker};
use crate::io::{Buffer, FixedBufferMut};
use orengine_macros::poll_for_io_request;
use std::future::Future;
use std::io::Result;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Future for the `read` operation.
pub struct ReadBytes<'buf> {
    fd: RawFd,
    buf: &'buf mut [u8],
    io_request_data: Option<IoRequestData>,
}

impl<'buf> ReadBytes<'buf> {
    /// Creates a new `read` io operation.
    pub fn new(fd: RawFd, buf: &'buf mut [u8]) -> Self {
        Self {
            fd,
            buf,
            io_request_data: None,
        }
    }
}

impl Future for ReadBytes<'_> {
    type Output = Result<usize>;

    #[allow(
        clippy::cast_possible_truncation,
        reason = "It never read more than u32::MAX bytes"
    )]
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        let ret;

        poll_for_io_request!((
            local_worker().read(
                this.fd,
                this.buf.as_mut_ptr(),
                this.buf.len() as u32,
                unsafe { this.io_request_data.as_mut().unwrap_unchecked() }
            ),
            ret
        ));
    }
}

unsafe impl Send for ReadBytes<'_> {}

/// Future for the `read` operation with __fixed__ [`Buffer`].
pub struct ReadFixed<'buf> {
    fd: RawFd,
    ptr: *mut u8,
    len: u32,
    fixed_index: u16,
    io_request_data: Option<IoRequestData>,
    phantom_data: PhantomData<&'buf Buffer>,
}

impl ReadFixed<'_> {
    /// Creates a new `read` io operation with __fixed__ [`Buffer`].
    pub fn new(fd: RawFd, ptr: *mut u8, len: u32, fixed_index: u16) -> Self {
        Self {
            fd,
            ptr,
            len,
            fixed_index,
            io_request_data: None,
            phantom_data: PhantomData,
        }
    }
}

impl Future for ReadFixed<'_> {
    type Output = Result<u32>;

    #[allow(
        clippy::cast_possible_truncation,
        reason = "It never read more than u32::MAX bytes"
    )]
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        let ret;

        poll_for_io_request!((
            local_worker().read_fixed(this.fd, this.ptr, this.len, this.fixed_index, unsafe {
                this.io_request_data.as_mut().unwrap_unchecked()
            }),
            ret as u32
        ));
    }
}

unsafe impl Send for ReadFixed<'_> {}

/// Future for the `pread` operation.
///
/// # Positional read
///
/// This is a variation of `read` that allows
/// to specify the offset from which the data should be read.
pub struct PositionedReadBytes<'buf> {
    fd: RawFd,
    buf: &'buf mut [u8],
    offset: usize,
    io_request_data: Option<IoRequestData>,
}

impl<'buf> PositionedReadBytes<'buf> {
    /// Creates a new `pread` io operation.
    pub fn new(fd: RawFd, buf: &'buf mut [u8], offset: usize) -> Self {
        Self {
            fd,
            buf,
            offset,
            io_request_data: None,
        }
    }
}

impl Future for PositionedReadBytes<'_> {
    type Output = Result<usize>;

    #[allow(
        clippy::cast_possible_truncation,
        reason = "It never read more than u32::MAX bytes"
    )]
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        let ret;

        poll_for_io_request!((
            local_worker().pread(
                this.fd,
                this.buf.as_mut_ptr(),
                this.buf.len() as u32,
                this.offset,
                unsafe { this.io_request_data.as_mut().unwrap_unchecked() }
            ),
            ret
        ));
    }
}

unsafe impl Send for PositionedReadBytes<'_> {}

/// Future for the `pread` operation with __fixed__ [`Buffer`].
///
/// # Positional read
///
/// This is a variation of `read` that allows
/// to specify the offset from which the data should be read.
pub struct PositionedReadFixed<'buf> {
    fd: RawFd,
    ptr: *mut u8,
    len: u32,
    fixed_index: u16,
    offset: usize,
    io_request_data: Option<IoRequestData>,
    phantom_data: PhantomData<&'buf Buffer>,
}

impl PositionedReadFixed<'_> {
    /// Creates a new `pread` io operation with __fixed__ [`Buffer`].
    pub fn new(fd: RawFd, ptr: *mut u8, len: u32, fixed_index: u16, offset: usize) -> Self {
        Self {
            fd,
            ptr,
            len,
            fixed_index,
            offset,
            io_request_data: None,
            phantom_data: PhantomData,
        }
    }
}

impl Future for PositionedReadFixed<'_> {
    type Output = Result<u32>;

    #[allow(
        clippy::cast_possible_truncation,
        reason = "It never read more than u32::MAX bytes"
    )]
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        let ret;

        poll_for_io_request!((
            local_worker().pread_fixed(
                this.fd,
                this.ptr,
                this.len,
                this.fixed_index,
                this.offset,
                unsafe { this.io_request_data.as_mut().unwrap_unchecked() }
            ),
            ret as u32
        ));
    }
}

unsafe impl Send for PositionedReadFixed<'_> {}

/// The `AsyncRead` trait provides asynchronous methods for reading bytes from readers.
///
/// This trait is implemented for types that can be represented
/// as raw file descriptors (via [`AsRawFd`]).
///
/// It includes basic asynchronous read operations,
/// as well as methods for performing positioned reads.
///
/// # Example
///
/// ```rust
/// use std::ops::Deref;
/// use orengine::io::full_buffer;
/// use orengine::fs::{File, OpenOptions};
/// use orengine::io::{AsyncRead, AsyncWrite};
///
/// # async fn foo() -> std::io::Result<()> {
/// let options = OpenOptions::new()
///                 .read(true)
///                 .write(true)
///                 .create(true);
/// let mut file = File::open("example.txt", &options).await?;
/// let mut buffer = full_buffer();
/// buffer.append(b"Hello world!");
/// file.write_all(&buffer).await?;
///
/// // Asynchronously read into buffer
/// let bytes_read = file.read(&mut buffer).await?;
/// // Asynchronously read exactly 12 bytes
/// file.read_exact(&mut buffer.slice_mut(..12)).await?;
/// assert_eq!(&buffer[..12], b"Hello world!");
///
/// let bytes_read = file.pread(&mut buffer, 6).await?;
/// // or read exactly 6 bytes
/// file.pread_exact(&mut buffer, 6).await?;
/// assert_eq!(&buffer[..6], b"world!");
/// # Ok(())
/// # }
/// ```
pub trait AsyncRead: AsRawFd {
    /// Asynchronously reads data from the reader into the provided byte slice.
    ///
    /// This method starts reading from the current file position
    /// and reads up to the length of the buffer.
    /// It returns a future that resolves to the number of bytes read.
    ///
    /// # Difference between `read` and `read_bytes`
    ///
    /// Use [`read`](Self::read) if it is possible, because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::fs::{File, OpenOptions};
    /// use orengine::io::AsyncRead;
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut arr = vec![0; 1024];
    /// let bytes_read = file.read_bytes(arr.as_mut()).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    fn read_bytes(&mut self, buf: &mut [u8]) -> impl Future<Output = Result<usize>> {
        ReadBytes::new(self.as_raw_fd(), buf)
    }

    /// Asynchronously reads data from the reader into the provided [`Buffer`].
    ///
    /// This method starts reading from the current file position
    /// and reads up to the length of the buffer.
    /// It returns a future that resolves to the number of bytes read.
    ///
    /// # Difference between `read` and `read_bytes`
    ///
    /// Use [`read`](Self::read) if it is possible, because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::io::{full_buffer, AsyncRead};
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut buffer = full_buffer();
    /// let bytes_read = file.read(&mut buffer).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    async fn read(&mut self, buf: &mut impl FixedBufferMut) -> Result<u32> {
        if buf.is_fixed() {
            ReadFixed::new(
                self.as_raw_fd(),
                buf.as_mut_ptr(),
                buf.len_u32(),
                buf.fixed_index(),
            )
            .await
        } else {
            #[allow(
                clippy::cast_possible_truncation,
                reason = "It never read more than u32::MAX bytes"
            )]
            ReadBytes::new(self.as_raw_fd(), buf.as_bytes_mut())
                .await
                .map(|r| r as u32)
        }
    }

    /// Asynchronously performs a positioned read, reading from the file at the specified offset.
    ///
    /// This method does not modify the file's current position but instead reads from the specified
    /// `offset`. It returns a future that resolves to the number of bytes read.
    ///
    /// # Difference between `pread` and `pread_bytes`
    ///
    /// Use [`pread`](Self::pread) if it is possible, because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::io::AsyncRead;
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut arr = vec![0; 1024];
    /// let bytes_read = file.pread_bytes(arr.as_mut(), 1024).await?;  // Read starting from offset 1024
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    fn pread_bytes(
        &mut self,
        buf: &mut [u8],
        offset: usize,
    ) -> impl Future<Output = Result<usize>> {
        PositionedReadBytes::new(self.as_raw_fd(), buf, offset)
    }

    /// Asynchronously performs a positioned read, reading from the file at the specified offset.
    ///
    /// This method does not modify the file's current position but instead reads from the specified
    /// `offset`. It returns a future that resolves to the number of bytes read.
    ///
    /// # Difference between `pread` and `pread_bytes`
    ///
    /// Use [`pread`](Self::pread) if it is possible, because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::io::{full_buffer, AsyncRead};
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut buf = full_buffer();
    /// let bytes_read = file.pread(&mut buf, 1024).await?;  // Read starting from offset 1024
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    async fn pread(&mut self, buf: &mut impl FixedBufferMut, offset: usize) -> Result<u32> {
        if buf.is_fixed() {
            PositionedReadFixed::new(
                self.as_raw_fd(),
                buf.as_mut_ptr(),
                buf.len_u32(),
                buf.fixed_index(),
                offset,
            )
            .await
        } else {
            #[allow(
                clippy::cast_possible_truncation,
                reason = "It never read more than u32::MAX bytes"
            )]
            PositionedReadBytes::new(self.as_raw_fd(), buf.as_bytes_mut(), offset)
                .await
                .map(|ret| ret as u32)
        }
    }

    /// Asynchronously reads the exact number of bytes required to fill the byte slice.
    ///
    /// This method continuously reads from the file descriptor until the entire buffer is filled.
    /// If the end of the file is reached before filling the buffer, it returns an error.
    ///
    /// # Difference between `read_exact` and `read_bytes_exact`
    ///
    /// Use [`read_exact`](Self::read_exact) if it is possible, because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::fs::{File, OpenOptions};
    /// use orengine::io::AsyncRead;
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut arr = vec![0; 1024];
    /// file.read_bytes_exact(arr.as_mut()).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    async fn read_bytes_exact(&mut self, buf: &mut [u8]) -> Result<()> {
        let mut read = 0;

        while read < buf.len() {
            read += self.read_bytes(&mut buf[read..]).await?;
        }

        Ok(())
    }

    /// Asynchronously reads the exact number of bytes required to fill the [`Buffer`].
    ///
    /// This method continuously reads from the file descriptor until the entire buffer is filled.
    /// If the end of the file is reached before filling the buffer, it returns an error.
    ///
    /// # Difference between `read_exact` and `read_bytes_exact`
    ///
    /// Use [`read_exact`](Self::read_exact) if it is possible, because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::io::{full_buffer, AsyncRead};
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut buffer = full_buffer();
    /// file.read_exact(&mut buffer).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    async fn read_exact(&mut self, buf: &mut impl FixedBufferMut) -> Result<()> {
        if buf.is_fixed() {
            let mut read = 0;

            #[allow(
                clippy::cast_possible_wrap,
                reason = "We believe it never read u32::MAX bytes"
            )]
            while read < buf.len_u32() {
                read += ReadFixed::new(
                    self.as_raw_fd(),
                    unsafe { buf.as_mut_ptr().offset(read as isize) },
                    buf.len_u32() - read,
                    buf.fixed_index(),
                )
                .await?;
            }
        } else {
            let mut read = 0;
            let slice = buf.as_bytes_mut();

            while read < slice.len() {
                read += self.read_bytes(&mut slice[read..]).await?;
            }
        }

        Ok(())
    }

    /// Asynchronously performs a positioned read, reading exactly the number of bytes needed to fill the byte slice.
    ///
    /// This method reads data starting at the specified `offset` until the entire buffer is filled.
    /// If the end of the file is reached before filling the buffer, it returns an error.
    ///
    /// # Difference between `pread_exact` and `pread_bytes_exact`
    ///
    /// Use [`pread_exact`](Self::pread_exact) if it is possible,
    /// because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::fs::{File, OpenOptions};
    /// use orengine::io::AsyncRead;
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut arr = vec![0; 1024];
    /// file.pread_bytes_exact(arr.as_mut(), 512).await?;  // Read exactly starting from offset 512
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    async fn pread_bytes_exact(&mut self, buf: &mut [u8], offset: usize) -> Result<()> {
        let mut read = 0;

        while read < buf.len() {
            read += self.pread_bytes(&mut buf[read..], offset + read).await?;
        }

        Ok(())
    }

    /// Asynchronously performs a positioned read, reading exactly the number
    /// of bytes needed to fill the [`Buffer`].
    ///
    /// This method reads data starting at the specified `offset` until the entire buffer is filled.
    /// If the end of the file is reached before filling the buffer, it returns an error.
    ///
    /// # Difference between `pread_exact` and `pread_bytes_exact`
    ///
    /// Use [`pread_exact`](Self::pread_exact) if it is possible,
    /// because [`Buffer`] can be __fixed__.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::io::{full_buffer, AsyncRead};
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let options = OpenOptions::new().read(true);
    /// let mut file = File::open("example.txt", &options).await?;
    /// let mut buffer = full_buffer();
    /// file.pread_exact(&mut buffer.slice_mut(..13), 512).await?;  // Read exactly 13 bytes starting from offset 512
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    async fn pread_exact(&mut self, buf: &mut impl FixedBufferMut, offset: usize) -> Result<()> {
        if buf.is_fixed() {
            let mut read = 0;

            #[allow(
                clippy::cast_possible_wrap,
                reason = "We believe it never read u32::MAX bytes"
            )]
            while read < buf.len_u32() {
                read += PositionedReadFixed::new(
                    self.as_raw_fd(),
                    unsafe { buf.as_mut_ptr().offset(read as isize) },
                    buf.len_u32() - read,
                    buf.fixed_index(),
                    offset + read as usize,
                )
                .await?;
            }
        } else {
            let mut read = 0;
            let slice = buf.as_bytes_mut();

            while read < slice.len() {
                read += self.pread_bytes(&mut slice[read..], offset + read).await?;
            }
        }

        Ok(())
    }
}