use drone_core::ffi::{c_char, c_int};
use drone_core::fs::OpenOptions;
use drone_core::io::SeekFrom;
use drone_micropython_raw::{
mp_import_stat_t, O_APPEND, O_CREAT, O_CREATNEW, O_READ, O_TRUNC, O_WRITE,
};
use io::Fd;
#[allow(missing_docs)]
pub enum IoReq {
Open { path: *const c_char, flags: Flags },
Read { fd: Fd, buf: *mut [u8] },
Write { fd: Fd, buf: *const [u8] },
Seek { fd: Fd, pos: SeekFrom },
Fsync { fd: Fd },
Close { fd: Fd },
ImportStat { path: *const c_char },
}
pub union IoReqRes {
pub(in io) open: Result<Fd, c_int>,
pub(in io) read: Result<usize, c_int>,
pub(in io) write: Result<usize, c_int>,
pub(in io) seek: Result<u64, c_int>,
pub(in io) fsync: Result<(), c_int>,
pub(in io) close: Result<(), c_int>,
pub(in io) import_stat: Result<mp_import_stat_t, c_int>,
}
#[derive(Clone, Copy)]
pub struct Flags(c_char);
impl IoReqRes {
pub unsafe fn open(open: Result<Fd, c_int>) -> Self {
Self { open }
}
pub unsafe fn read(read: Result<usize, c_int>) -> Self {
Self { read }
}
pub unsafe fn write(write: Result<usize, c_int>) -> Self {
Self { write }
}
pub unsafe fn seek(seek: Result<u64, c_int>) -> Self {
Self { seek }
}
pub unsafe fn fsync(fsync: Result<(), c_int>) -> Self {
Self { fsync }
}
pub unsafe fn close(close: Result<(), c_int>) -> Self {
Self { close }
}
pub unsafe fn import_stat(
import_stat: Result<mp_import_stat_t, c_int>,
) -> Self {
Self { import_stat }
}
}
impl Flags {
pub(crate) fn new(flags: c_char) -> Self {
Flags(flags)
}
pub fn set_options<T: OpenOptions>(self, options: T) -> T {
options
.read((self.0 & O_READ as u8) != 0)
.write((self.0 & O_WRITE as u8) != 0)
.append((self.0 & O_APPEND as u8) != 0)
.truncate((self.0 & O_TRUNC as u8) != 0)
.create((self.0 & O_CREAT as u8) != 0)
.create_new((self.0 & O_CREATNEW as u8) != 0)
}
}