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
use crate::fs::OpenOptions;
use crate::io::fallocate::AsyncFallocate;
use crate::io::open::Open;
use crate::io::remove::Remove;
use crate::io::rename::Rename;
use crate::io::sync_all::AsyncSyncAll;
use crate::io::sync_data::AsyncSyncData;
use crate::io::sys::OsPath::{get_os_path, OsPath};
use crate::io::sys::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use crate::io::{AsyncClose, AsyncRead, AsyncWrite};
use crate::runtime::local_executor;
use std::io::{Error, Result};
use std::mem::ManuallyDrop;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::{io, mem};

/// An object providing access to an [`open`](File::open) file on the filesystem.
/// An instance of a File can be read and/ or written depending on what options it was opened with.
///
/// # Close
///
/// Files are automatically closed when they go out of scope.
/// Errors detected on closing are ignored by the implementation of Drop.
/// Use the method [`sync_all`](File::sync_all) if these errors must be manually handled.
///
/// # Examples
///
/// ```rust
/// use orengine::fs::{File, OpenOptions};
///
/// # async fn foo() -> std::io::Result<()> {
/// let open_options = OpenOptions::new().read(true).write(true);
/// let file = File::open("example.txt", &open_options).await?;
/// # Ok(())
/// # }
/// ```
pub struct File {
    fd: RawFd,
}

impl File {
    /// Returns the file descriptor [`RawFd`] of the [`File`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let file = File::open("foo.txt", &OpenOptions::new()).await?;
    /// let fd = file.fd();
    /// # Ok(())
    /// # }
    #[inline(always)]
    pub fn fd(&self) -> RawFd {
        self.fd
    }

    /// Opens a file at the given path with the specified options.
    ///
    /// This function takes an asynchronous approach to file opening.
    /// The `as_path` argument specifies the path
    /// to the file, and `open_options` contains various settings such as read/write access,
    /// append mode, and more.
    ///
    /// # Errors
    ///
    /// This method will return an `Err` if:
    /// - The provided path is empty.
    /// - There is an issue converting the path to an OS-specific format.
    /// - The file could not be opened due to other I/O errors
    ///   (e.g., permission denied, file not found).
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let open_options = OpenOptions::new().read(true).write(true);
    /// let file = File::open("foo.txt", &open_options).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn open<P: AsRef<Path> + Send>(
        as_path: P,
        open_options: &OpenOptions,
    ) -> Result<Self> {
        let path = as_path.as_ref();
        if path == Path::new("") {
            return Err(Error::new(io::ErrorKind::InvalidInput, "path is empty"));
        }
        let os_path = match OsPath::new(path.as_os_str().as_bytes()) {
            Ok(path) => path,
            Err(err) => return Err(Error::new(io::ErrorKind::InvalidInput, err)),
        };
        let os_open_options = open_options.into_os_options()?;

        match Open::new(os_path, os_open_options).await {
            Ok(file) => Ok(file),
            Err(err) => Err(err),
        }
    }

    /// Renames a file from one path to another.
    ///
    /// This method renames the file at `old_path` to `new_path`. Both paths must be valid.
    ///
    /// # Errors
    ///
    /// This function will return an `Err` if:
    /// - Either `old_path` or `new_path` cannot be converted into an OS path.
    /// - The rename operation fails due to I/O issues such as permission errors or file not found.
    ///
    /// # Example
    ///
    /// ```rust
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let file = File::rename("foo.txt", "bar.txt").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn rename<OldPath, NewPath>(old_path: OldPath, new_path: NewPath) -> Result<()>
    where
        OldPath: AsRef<Path> + Send,
        NewPath: AsRef<Path> + Send,
    {
        let old_path = get_os_path(old_path.as_ref())?;
        let new_path = get_os_path(new_path.as_ref())?;
        Rename::new(old_path, new_path).await
    }

    /// Removes (deletes) the file at the specified path.
    ///
    /// This method asynchronously deletes the file located at `path`.
    /// If the file does not exist,
    /// or if the operation fails for any other reason, an `Err` is returned.
    ///
    /// # Errors
    ///
    /// This function will return an `Err` if:
    /// - The provided path cannot be converted into an OS path.
    /// - The file removal operation fails due to I/O issues such as permission errors
    ///   or file not found.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::path::Path;
    /// use orengine::fs::{File, OpenOptions};
    ///
    /// # async fn foo() -> std::io::Result<()> {
    /// let file = File::remove("foo.txt").await?;
    /// assert!(!Path::new("foo.txt").exists());
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn remove<P: AsRef<Path> + Send>(path: P) -> Result<()> {
        let path = get_os_path(path.as_ref())?;
        Remove::new(path).await
    }

    /// Executes a closure with a shared reference to the underlying `std::fs::File` object.
    ///
    /// It allows to call sync methods on the file from standard library.
    #[inline(always)]
    pub fn with_std_file<Ret, F: FnOnce(&std::fs::File) -> Ret>(&self, f: F) -> Ret {
        unsafe {
            let std_file = std::fs::File::from_raw_fd(self.fd);
            let ret = f(&std_file);
            mem::forget(std_file);

            ret
        }
    }

    /// Executes a closure with a mutable reference to the underlying `std::fs::File` object.
    ///
    /// It allows to call sync methods on the file from standard library.
    #[inline(always)]
    pub fn with_std_mut_file<Ret, F: FnOnce(&mut std::fs::File) -> Ret>(&mut self, f: F) -> Ret {
        unsafe {
            let mut std_file = std::fs::File::from_raw_fd(self.fd);
            let ret = f(&mut std_file);
            mem::forget(std_file);

            ret
        }
    }
}

impl From<File> for std::fs::File {
    fn from(file: File) -> Self {
        unsafe { Self::from_raw_fd(ManuallyDrop::new(file).fd) }
    }
}

impl From<std::fs::File> for File {
    fn from(file: std::fs::File) -> Self {
        Self {
            fd: file.into_raw_fd(),
        }
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        Self { fd }
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl AsyncFallocate for File {}

impl AsyncSyncAll for File {}

impl AsyncSyncData for File {}

impl AsyncRead for File {}

impl AsyncWrite for File {}

impl AsyncClose for File {}

impl Drop for File {
    fn drop(&mut self) {
        let close_future = self.close();
        local_executor().exec_local_future(async {
            close_future.await.expect("Failed to close file");
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate as orengine;
    use crate::fs::test_helper::{create_test_dir_if_not_exist, is_exists, TEST_DIR_PATH};
    use crate::io::{full_buffer, get_fixed_buffer, get_full_fixed_buffer, FixedBuffer};
    use std::fs::{create_dir, create_dir_all};
    use std::io::{Seek, SeekFrom};
    use std::path::PathBuf;

    #[orengine::test::test_local]
    fn test_file_create_write_read_pread_pwrite_remove_close_with_nonfixed() {
        const MSG: &[u8] = b"Hello, world!";

        let test_file_dir_path: &str = &(TEST_DIR_PATH.to_string() + "/test_file_nonfixed/");

        create_test_dir_if_not_exist();

        let file_path = {
            let mut file_path_ = PathBuf::from(test_file_dir_path);
            let _ = create_dir(test_file_dir_path);
            file_path_.push("test.txt");
            file_path_
        };
        let options = OpenOptions::new()
            .write(true)
            .read(true)
            .truncate(true)
            .create(true);
        let mut file = match File::open(&file_path, &options).await {
            Ok(file) => file,
            Err(err) => panic!("Can't open (create) file: {err}"),
        };

        assert!(is_exists(file_path.clone()));

        let mut buf = Vec::with_capacity(0);
        buf.extend(MSG);

        match file.write_all_bytes(buf.as_ref()).await {
            Ok(()) => (),
            Err(err) => panic!("Can't write file: {err}"),
        }

        file.with_std_mut_file(|file| file.seek(SeekFrom::Start(0)))
            .unwrap();
        match file.read_bytes_exact(buf.as_mut()).await {
            Ok(()) => assert_eq!(buf, MSG),
            Err(err) => panic!("Can't read file: {err}"),
        }

        buf.clear();
        buf.extend(b"great World!");
        match file.pwrite_all_bytes(buf.as_ref(), 7).await {
            Ok(()) => (),
            Err(err) => panic!("Can't pwrite file: {err}"),
        }

        buf.clear();
        unsafe { buf.set_len(b"Hello, great World!".len()) };
        match file.pread_bytes_exact(buf.as_mut(), 0).await {
            Ok(()) => assert_eq!(buf, b"Hello, great World!"),
            Err(err) => panic!("Can't read file: {err}"),
        }

        File::rename(
            test_file_dir_path.to_string() + "test.txt",
            test_file_dir_path.to_string() + "test2.txt",
        )
        .await
        .expect("Can't rename file");
        assert!(is_exists(test_file_dir_path.to_string() + "/test2.txt"));

        File::remove(test_file_dir_path.to_string() + "/test2.txt")
            .await
            .expect("Can't remove file");
        assert!(!is_exists(file_path));

        std::fs::remove_dir("./test/test_file_nonfixed").expect("failed to remove test file dir");
    }

    #[orengine::test::test_local]
    fn test_file_unpositional_read_write_with_nonfixed() {
        create_test_dir_if_not_exist();

        let test_file_dir_path: &str =
            &(TEST_DIR_PATH.to_string() + "/unpositional_file_nonfixed/");
        let file_path = {
            let mut file_path_ = PathBuf::from(test_file_dir_path);
            let _ = create_dir_all(test_file_dir_path);
            file_path_.push("test.txt");
            file_path_
        };
        let options = OpenOptions::new()
            .write(true)
            .read(true)
            .truncate(true)
            .create(true);
        let mut file = match File::open(&file_path, &options).await {
            Ok(file) => file,
            Err(err) => panic!("Can't open (create) file: {err}"),
        };

        let mut write_buf = vec![0u8; 4096];
        for i in 0..write_buf.capacity() {
            write_buf[i] = u8::try_from(i % 256).unwrap();
        }

        file.write_all_bytes(write_buf.as_ref()).await.unwrap();

        let mut read_buf = [0; 10];
        let mut read = 0usize;
        let mut read_file = File::open(&file_path, &OpenOptions::new().read(true))
            .await
            .unwrap();

        while read < write_buf.capacity() {
            let n = read_file.read_bytes(&mut read_buf).await.unwrap();
            assert_eq!(write_buf[read..read + n], read_buf[..n]);
            read += n;
        }

        let mut large_big_buff = full_buffer();
        read_file
            .with_std_mut_file(|file| file.seek(SeekFrom::Start(0)))
            .unwrap();
        read_file
            .read_bytes_exact(&mut large_big_buff[..write_buf.capacity()])
            .await
            .unwrap();
        assert_eq!(large_big_buff.as_ref(), write_buf);
    }

    #[orengine::test::test_local]
    fn test_file_create_write_read_pread_pwrite_remove_close_with_fixed() {
        const MSG: &[u8] = b"Hello, world!";

        let test_file_dir_path: &str = &(TEST_DIR_PATH.to_string() + "/test_file/");

        create_test_dir_if_not_exist();

        let file_path = {
            let mut file_path_ = PathBuf::from(test_file_dir_path);
            let _ = create_dir(test_file_dir_path);
            file_path_.push("test.txt");
            file_path_
        };
        let options = OpenOptions::new()
            .write(true)
            .read(true)
            .truncate(true)
            .create(true);
        let mut file = match File::open(&file_path, &options).await {
            Ok(file) => file,
            Err(err) => panic!("Can't open (create) file: {err}"),
        };

        assert!(is_exists(file_path.clone()));

        let mut buf = get_fixed_buffer().await;
        buf.append(MSG);

        match file.write_all(&buf).await {
            Ok(()) => (),
            Err(err) => panic!("Can't write file: {err}"),
        }

        file.with_std_mut_file(|file| file.seek(SeekFrom::Start(0)))
            .unwrap();
        match file.read_exact(&mut buf).await {
            Ok(()) => assert_eq!(buf.as_ref(), MSG),
            Err(err) => panic!("Can't read file: {err}"),
        }

        buf.clear();
        buf.append(b"great World!");
        match file.pwrite_all(&buf, 7).await {
            Ok(()) => (),
            Err(err) => panic!("Can't pwrite file: {err}"),
        }

        buf.clear();
        buf.set_len(u32::try_from(b"Hello, great World!".len()).unwrap())
            .unwrap();
        match file.pread_exact(&mut buf, 0).await {
            Ok(()) => assert_eq!(buf.as_ref(), b"Hello, great World!"),
            Err(err) => panic!("Can't read file: {err}"),
        }

        File::rename(
            test_file_dir_path.to_string() + "test.txt",
            test_file_dir_path.to_string() + "test2.txt",
        )
        .await
        .expect("Can't rename file");
        assert!(is_exists(test_file_dir_path.to_string() + "/test2.txt"));

        File::remove(test_file_dir_path.to_string() + "/test2.txt")
            .await
            .expect("Can't remove file");
        assert!(!is_exists(file_path));

        std::fs::remove_dir("./test/test_file").expect("failed to remove test file dir");
    }

    #[orengine::test::test_local]
    fn test_file_unpositional_read_write_with_fixed() {
        create_test_dir_if_not_exist();

        let test_file_dir_path: &str = &(TEST_DIR_PATH.to_string() + "/unpositional_file/");

        create_test_dir_if_not_exist();

        let file_path = {
            let mut file_path_ = PathBuf::from(test_file_dir_path);
            let _ = create_dir_all(test_file_dir_path);
            file_path_.push("test.txt");
            file_path_
        };
        let options = OpenOptions::new()
            .write(true)
            .read(true)
            .truncate(true)
            .create(true);
        let mut file = match File::open(&file_path, &options).await {
            Ok(file) => file,
            Err(err) => panic!("Can't open (create) file: {err}"),
        };

        let mut write_buf = get_full_fixed_buffer().await;
        for i in 0..write_buf.capacity() as usize {
            write_buf[i] = u8::try_from(i % 256).unwrap();
        }

        file.write_all(&write_buf).await.unwrap();

        let mut read_buf = get_fixed_buffer().await;
        read_buf.set_len(10).unwrap();
        let mut read = 0;
        let mut read_file = File::open(&file_path, &OpenOptions::new().read(true))
            .await
            .unwrap();

        while read < write_buf.capacity() {
            let n = read_file.read(&mut read_buf).await.unwrap();
            assert_eq!(
                write_buf.as_bytes()[read as usize..read as usize + n as usize],
                read_buf.as_bytes()[..n as usize]
            );
            read += n;
        }

        let mut large_big_buff = full_buffer();
        read_file
            .with_std_mut_file(|file| file.seek(SeekFrom::Start(0)))
            .unwrap();
        read_file
            .read_bytes_exact(&mut large_big_buff[..write_buf.capacity() as usize])
            .await
            .unwrap();
        assert_eq!(large_big_buff.as_ref(), write_buf.as_ref());
    }
}