platform/
io.rs

1// SPDX-FileCopyrightText: 2024 Jens Pitkänen <jens.pitkanen@helsinki.fi>
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5use crate::Box;
6
7/// Platform-specific file handle.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub struct FileHandle(u64);
10
11impl FileHandle {
12    /// Creates a new [`FileHandle`]. Should only be created in the platform
13    /// implementation, which also knows how the inner value is going to be
14    /// used.
15    pub fn new(id: u64) -> FileHandle {
16        FileHandle(id)
17    }
18
19    /// Returns the inner value passed into [`FileHandle::new`]. Generally only
20    /// relevant to the platform implementation.
21    pub fn inner(self) -> u64 {
22        self.0
23    }
24}
25
26/// Handle to an asynchronous file reading operation.
27pub struct FileReadTask {
28    file: FileHandle,
29    task_id: u64,
30    buffer: Box<[u8]>,
31}
32
33impl FileReadTask {
34    /// Creates a new [`FileReadTask`] with the task id differentiating
35    /// different [`FileReadTask`]s. The platform implementation should create
36    /// and keep track of these.
37    pub fn new(file: FileHandle, task_id: u64, buffer: Box<[u8]>) -> FileReadTask {
38        FileReadTask {
39            file,
40            task_id,
41            buffer,
42        }
43    }
44
45    /// Returns the [`FileHandle`] this task is using.
46    pub fn file(&self) -> FileHandle {
47        self.file
48    }
49
50    /// Returns the task id for this particular task, the same one passed into
51    /// [`FileReadTask::new`].
52    pub fn task_id(&self) -> u64 {
53        self.task_id
54    }
55
56    /// Returns the size of the buffer, i.e. the amount of bytes read by this task.
57    pub fn read_size(&self) -> usize {
58        self.buffer.len()
59    }
60
61    /// Deconstructs this into the inner buffer. Intended for platform layers
62    /// implementing
63    /// [`Platform::finish_file_read`](crate::Platform::finish_file_read).
64    ///
65    /// ### Safety
66    ///
67    /// The platform may have shared a pointer to this buffer with e.g. the
68    /// kernel for async writing. The caller must ensure that when calling this
69    /// function, such a shared pointer will not be used anymore, as this
70    /// function makes said memory writable again (not owned and hidden in this
71    /// struct).
72    pub unsafe fn into_inner(self) -> Box<[u8]> {
73        self.buffer
74    }
75}