1 use super::{abi, error};
3 ffi::{CStr, CString, OsStr, OsString},
5 io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom},
7 os::raw::{c_int, c_short},
8 os::solid::ffi::OsStrExt,
11 sys::time::SystemTime,
15 pub use crate::sys_common::fs::try_exists;
17 /// A file descriptor.
18 #[derive(Clone, Copy)]
19 #[rustc_layout_scalar_valid_range_start(0)]
20 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
21 // 32-bit c_int. Below is -2, in two's complement, but that only works out
22 // because c_int is 32 bits.
23 #[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
30 fn new(fd: c_int) -> FileDesc {
31 assert_ne!(fd, -1i32);
32 // Safety: we just asserted that the value is in the valid range and
33 // isn't `-1` (the only value bigger than `0xFF_FF_FF_FE` unsigned)
34 unsafe { FileDesc { fd } }
38 fn raw(&self) -> c_int {
52 // all DirEntry's will have a reference to this struct
59 inner: Arc<InnerReadDir>,
64 inner: Arc<InnerReadDir>,
67 #[derive(Clone, Debug)]
68 pub struct OpenOptions {
80 #[derive(Copy, Clone, Debug, Default)]
81 pub struct FileTimes {}
83 #[derive(Clone, PartialEq, Eq, Debug)]
84 pub struct FilePermissions(c_short);
86 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
87 pub struct FileType(c_short);
90 pub struct DirBuilder {}
93 pub fn size(&self) -> u64 {
94 self.stat.st_size as u64
97 pub fn perm(&self) -> FilePermissions {
98 FilePermissions(self.stat.st_mode)
101 pub fn file_type(&self) -> FileType {
102 FileType(self.stat.st_mode)
105 pub fn modified(&self) -> io::Result<SystemTime> {
106 Ok(SystemTime::from_time_t(self.stat.st_mtime))
109 pub fn accessed(&self) -> io::Result<SystemTime> {
110 Ok(SystemTime::from_time_t(self.stat.st_atime))
113 pub fn created(&self) -> io::Result<SystemTime> {
114 Ok(SystemTime::from_time_t(self.stat.st_ctime))
118 impl FilePermissions {
119 pub fn readonly(&self) -> bool {
120 (self.0 & abi::S_IWRITE) == 0
123 pub fn set_readonly(&mut self, readonly: bool) {
125 self.0 &= !abi::S_IWRITE;
127 self.0 |= abi::S_IWRITE;
133 pub fn set_accessed(&mut self, _t: SystemTime) {}
134 pub fn set_modified(&mut self, _t: SystemTime) {}
138 pub fn is_dir(&self) -> bool {
139 self.is(abi::S_IFDIR)
141 pub fn is_file(&self) -> bool {
142 self.is(abi::S_IFREG)
144 pub fn is_symlink(&self) -> bool {
148 pub fn is(&self, mode: c_short) -> bool {
149 self.0 & abi::S_IFMT == mode
153 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
155 let mut dir = MaybeUninit::uninit();
156 error::SolidError::err_if_negative(abi::SOLID_FS_OpenDir(
160 .map_err(|e| e.as_io_error())?;
161 let inner = Arc::new(InnerReadDir { dirp: dir.assume_init(), root: p.to_owned() });
162 Ok(ReadDir { inner })
166 impl fmt::Debug for ReadDir {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
169 // Thus the result will be e g 'ReadDir("/home")'
170 fmt::Debug::fmt(&*self.inner.root, f)
174 impl Iterator for ReadDir {
175 type Item = io::Result<DirEntry>;
177 fn next(&mut self) -> Option<io::Result<DirEntry>> {
179 let mut out_dirent = MaybeUninit::uninit();
180 error::SolidError::err_if_negative(abi::SOLID_FS_ReadDir(
182 out_dirent.as_mut_ptr(),
185 Some(Ok(DirEntry { entry: out_dirent.assume_init(), inner: Arc::clone(&self.inner) }))
190 impl Drop for InnerReadDir {
192 unsafe { abi::SOLID_FS_CloseDir(self.dirp) };
197 pub fn path(&self) -> PathBuf {
198 self.inner.root.join(OsStr::from_bytes(
199 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }.to_bytes(),
203 pub fn file_name(&self) -> OsString {
204 OsStr::from_bytes(unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }.to_bytes())
208 pub fn metadata(&self) -> io::Result<FileAttr> {
212 pub fn file_type(&self) -> io::Result<FileType> {
213 match self.entry.d_type {
214 abi::DT_CHR => Ok(FileType(abi::S_IFCHR)),
215 abi::DT_FIFO => Ok(FileType(abi::S_IFIFO)),
216 abi::DT_REG => Ok(FileType(abi::S_IFREG)),
217 abi::DT_DIR => Ok(FileType(abi::S_IFDIR)),
218 abi::DT_BLK => Ok(FileType(abi::S_IFBLK)),
219 _ => lstat(&self.path()).map(|m| m.file_type()),
225 pub fn new() -> OpenOptions {
239 pub fn read(&mut self, read: bool) {
242 pub fn write(&mut self, write: bool) {
245 pub fn append(&mut self, append: bool) {
246 self.append = append;
248 pub fn truncate(&mut self, truncate: bool) {
249 self.truncate = truncate;
251 pub fn create(&mut self, create: bool) {
252 self.create = create;
254 pub fn create_new(&mut self, create_new: bool) {
255 self.create_new = create_new;
258 pub fn custom_flags(&mut self, flags: i32) {
259 self.custom_flags = flags;
261 pub fn mode(&mut self, _mode: u32) {}
263 fn get_access_mode(&self) -> io::Result<c_int> {
264 match (self.read, self.write, self.append) {
265 (true, false, false) => Ok(abi::O_RDONLY),
266 (false, true, false) => Ok(abi::O_WRONLY),
267 (true, true, false) => Ok(abi::O_RDWR),
268 (false, _, true) => Ok(abi::O_WRONLY | abi::O_APPEND),
269 (true, _, true) => Ok(abi::O_RDWR | abi::O_APPEND),
270 (false, false, false) => Err(io::Error::from_raw_os_error(libc::EINVAL)),
274 fn get_creation_mode(&self) -> io::Result<c_int> {
275 match (self.write, self.append) {
278 if self.truncate || self.create || self.create_new {
279 return Err(io::Error::from_raw_os_error(libc::EINVAL));
283 if self.truncate && !self.create_new {
284 return Err(io::Error::from_raw_os_error(libc::EINVAL));
289 Ok(match (self.create, self.truncate, self.create_new) {
290 (false, false, false) => 0,
291 (true, false, false) => abi::O_CREAT,
292 (false, true, false) => abi::O_TRUNC,
293 (true, true, false) => abi::O_CREAT | abi::O_TRUNC,
294 (_, _, true) => abi::O_CREAT | abi::O_EXCL,
299 fn cstr(path: &Path) -> io::Result<CString> {
300 let path = path.as_os_str().as_bytes();
302 if !path.starts_with(br"\") {
303 // Relative paths aren't supported
304 return Err(crate::io::const_io_error!(
305 crate::io::ErrorKind::Unsupported,
306 "relative path is not supported on this platform",
310 // Apply the thread-safety wrapper
311 const SAFE_PREFIX: &[u8] = br"\TS";
312 let wrapped_path = [SAFE_PREFIX, &path, &[0]].concat();
314 CString::from_vec_with_nul(wrapped_path).map_err(|_| {
315 crate::io::const_io_error!(
316 io::ErrorKind::InvalidInput,
317 "path provided contains a nul byte",
323 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
324 let flags = opts.get_access_mode()?
325 | opts.get_creation_mode()?
326 | (opts.custom_flags as c_int & !abi::O_ACCMODE);
328 let mut fd = MaybeUninit::uninit();
329 error::SolidError::err_if_negative(abi::SOLID_FS_Open(
331 cstr(path)?.as_ptr(),
334 .map_err(|e| e.as_io_error())?;
335 Ok(File { fd: FileDesc::new(fd.assume_init()) })
339 pub fn file_attr(&self) -> io::Result<FileAttr> {
343 pub fn fsync(&self) -> io::Result<()> {
347 pub fn datasync(&self) -> io::Result<()> {
351 pub fn truncate(&self, _size: u64) -> io::Result<()> {
355 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
357 let mut out_num_bytes = MaybeUninit::uninit();
358 error::SolidError::err_if_negative(abi::SOLID_FS_Read(
362 out_num_bytes.as_mut_ptr(),
364 .map_err(|e| e.as_io_error())?;
365 Ok(out_num_bytes.assume_init())
369 pub fn read_buf(&self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
371 let len = cursor.capacity();
372 let mut out_num_bytes = MaybeUninit::uninit();
373 error::SolidError::err_if_negative(abi::SOLID_FS_Read(
375 cursor.as_mut().as_mut_ptr() as *mut u8,
377 out_num_bytes.as_mut_ptr(),
379 .map_err(|e| e.as_io_error())?;
381 // Safety: `out_num_bytes` is filled by the successful call to
383 let num_bytes_read = out_num_bytes.assume_init();
385 // Safety: `num_bytes_read` bytes were written to the unfilled
386 // portion of the buffer
387 cursor.advance(num_bytes_read);
393 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
394 crate::io::default_read_vectored(|buf| self.read(buf), bufs)
397 pub fn is_read_vectored(&self) -> bool {
401 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
403 let mut out_num_bytes = MaybeUninit::uninit();
404 error::SolidError::err_if_negative(abi::SOLID_FS_Write(
408 out_num_bytes.as_mut_ptr(),
410 .map_err(|e| e.as_io_error())?;
411 Ok(out_num_bytes.assume_init())
415 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
416 crate::io::default_write_vectored(|buf| self.write(buf), bufs)
419 pub fn is_write_vectored(&self) -> bool {
423 pub fn flush(&self) -> io::Result<()> {
424 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Sync(self.fd.raw()) })
425 .map_err(|e| e.as_io_error())?;
429 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
430 let (whence, pos) = match pos {
431 // Casting to `i64` is fine, too large values will end up as
432 // negative which will cause an error in `SOLID_FS_Lseek`.
433 SeekFrom::Start(off) => (abi::SEEK_SET, off as i64),
434 SeekFrom::End(off) => (abi::SEEK_END, off),
435 SeekFrom::Current(off) => (abi::SEEK_CUR, off),
437 error::SolidError::err_if_negative(unsafe {
438 abi::SOLID_FS_Lseek(self.fd.raw(), pos, whence)
440 .map_err(|e| e.as_io_error())?;
442 // Get the new offset
444 let mut out_offset = MaybeUninit::uninit();
445 error::SolidError::err_if_negative(abi::SOLID_FS_Ftell(
447 out_offset.as_mut_ptr(),
449 .map_err(|e| e.as_io_error())?;
450 Ok(out_offset.assume_init() as u64)
454 pub fn duplicate(&self) -> io::Result<File> {
458 pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> {
462 pub fn set_times(&self, _times: FileTimes) -> io::Result<()> {
469 unsafe { abi::SOLID_FS_Close(self.fd.raw()) };
474 pub fn new() -> DirBuilder {
478 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
479 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Mkdir(cstr(p)?.as_ptr()) })
480 .map_err(|e| e.as_io_error())?;
485 impl fmt::Debug for File {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 f.debug_struct("File").field("fd", &self.fd.raw()).finish()
491 pub fn unlink(p: &Path) -> io::Result<()> {
492 if stat(p)?.file_type().is_dir() {
493 Err(io::const_io_error!(io::ErrorKind::IsADirectory, "is a directory"))
495 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) })
496 .map_err(|e| e.as_io_error())?;
501 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
502 error::SolidError::err_if_negative(unsafe {
503 abi::SOLID_FS_Rename(cstr(old)?.as_ptr(), cstr(new)?.as_ptr())
505 .map_err(|e| e.as_io_error())?;
509 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
510 error::SolidError::err_if_negative(unsafe {
511 abi::SOLID_FS_Chmod(cstr(p)?.as_ptr(), perm.0.into())
513 .map_err(|e| e.as_io_error())?;
517 pub fn rmdir(p: &Path) -> io::Result<()> {
518 if stat(p)?.file_type().is_dir() {
519 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) })
520 .map_err(|e| e.as_io_error())?;
523 Err(io::const_io_error!(io::ErrorKind::NotADirectory, "not a directory"))
527 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
528 for child in readdir(path)? {
530 let child_type = child.file_type()?;
531 if child_type.is_dir() {
532 remove_dir_all(&child.path())?;
534 unlink(&child.path())?;
540 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
541 // This target doesn't support symlinks
543 Err(io::const_io_error!(io::ErrorKind::InvalidInput, "not a symbolic link"))
546 pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> {
547 // This target doesn't support symlinks
551 pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
552 // This target doesn't support symlinks
556 pub fn stat(p: &Path) -> io::Result<FileAttr> {
557 // This target doesn't support symlinks
561 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
563 let mut out_stat = MaybeUninit::uninit();
564 error::SolidError::err_if_negative(abi::SOLID_FS_Stat(
566 out_stat.as_mut_ptr(),
568 .map_err(|e| e.as_io_error())?;
569 Ok(FileAttr { stat: out_stat.assume_init() })
573 pub fn canonicalize(_p: &Path) -> io::Result<PathBuf> {
577 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
580 let mut reader = File::open(from)?;
581 let mut writer = File::create(to)?;
583 io::copy(&mut reader, &mut writer)