use std::{marker, os::fd};
use dope_sys::io::{file, reactor::event::kind, request::Request};
use o3::alloc;
use crate::{
Backend,
driver::route,
io::fs::{Dir, File, Submission, open, path},
};
#[repr(C)]
pub struct OpenRequest<T = File> {
directory: Dir,
name: Box<std::ffi::CStr>,
beneath: <Backend as file::File>::Options,
output: marker::PhantomData<fn() -> T>,
}
impl OpenRequest {
pub fn new(path: path::Confined, options: open::Options) -> Self {
Self::at::<false>(path.directory, path.path.bytes, options)
}
pub fn directory(path: path::Confined) -> OpenRequest<Dir> {
OpenRequest::at::<false>(
path.directory,
path.path.bytes,
open::Options::new(open::Access::Directory),
)
}
pub fn into_path(self) -> path::Confined {
path::Confined::new(self.directory, path::Owned { bytes: self.name })
}
}
impl<T> OpenRequest<T> {
pub(super) fn at<const NO_SYMLINKS: bool>(
dir: Dir,
name: Box<std::ffi::CStr>,
options: open::Options,
) -> Self {
let (flags, mode) = options.nofollow().lower();
Self {
directory: dir,
name,
beneath: <<Backend as file::File>::Request<'_> as Request>::options::<NO_SYMLINKS>(
flags, mode,
),
output: marker::PhantomData,
}
}
pub fn submission<'d, Tag>(
&self,
target: route::Target<'d, Tag>,
) -> Submission<'_, 'd, Tag, kind::Open>
where
Tag: route::Tag + route::Select<kind::Open>,
{
Submission::bind(
Request::open(fd::AsFd::as_fd(&self.directory), &self.name, &self.beneath),
target.operation::<kind::Open>(),
)
}
}
impl OpenRequest<Dir> {
pub fn into_path(self) -> path::Confined {
path::Confined::new(self.directory, path::Owned { bytes: self.name })
}
pub unsafe fn try_complete(&self, file: File) -> Result<Dir, alloc::Exhausted> {
Dir::try_new(file.into())
}
}