1 use super::{abi, error};
3 ffi::{CStr, CString, OsStr, OsString},
5 io::{self, IoSlice, IoSliceMut, ReadBuf, 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(Clone, PartialEq, Eq, Debug)]
81 pub struct FilePermissions(c_short);
83 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
84 pub struct FileType(c_short);
87 pub struct DirBuilder {}
90 pub fn size(&self) -> u64 {
91 self.stat.st_size as u64
94 pub fn perm(&self) -> FilePermissions {
95 FilePermissions(self.stat.st_mode)
98 pub fn file_type(&self) -> FileType {
99 FileType(self.stat.st_mode)
102 pub fn modified(&self) -> io::Result<SystemTime> {
103 Ok(SystemTime::from_time_t(self.stat.st_mtime))
106 pub fn accessed(&self) -> io::Result<SystemTime> {
107 Ok(SystemTime::from_time_t(self.stat.st_atime))
110 pub fn created(&self) -> io::Result<SystemTime> {
111 Ok(SystemTime::from_time_t(self.stat.st_ctime))
115 impl FilePermissions {
116 pub fn readonly(&self) -> bool {
117 (self.0 & abi::S_IWRITE) == 0
120 pub fn set_readonly(&mut self, readonly: bool) {
122 self.0 &= !abi::S_IWRITE;
124 self.0 |= abi::S_IWRITE;
130 pub fn is_dir(&self) -> bool {
131 self.is(abi::S_IFDIR)
133 pub fn is_file(&self) -> bool {
134 self.is(abi::S_IFREG)
136 pub fn is_symlink(&self) -> bool {
140 pub fn is(&self, mode: c_short) -> bool {
141 self.0 & abi::S_IFMT == mode
145 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
147 let mut dir = MaybeUninit::uninit();
148 error::SolidError::err_if_negative(abi::SOLID_FS_OpenDir(
152 .map_err(|e| e.as_io_error())?;
153 let inner = Arc::new(InnerReadDir { dirp: dir.assume_init(), root: p.to_owned() });
154 Ok(ReadDir { inner })
158 impl fmt::Debug for ReadDir {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
161 // Thus the result will be e g 'ReadDir("/home")'
162 fmt::Debug::fmt(&*self.inner.root, f)
166 impl Iterator for ReadDir {
167 type Item = io::Result<DirEntry>;
169 fn next(&mut self) -> Option<io::Result<DirEntry>> {
171 let mut out_dirent = MaybeUninit::uninit();
172 error::SolidError::err_if_negative(abi::SOLID_FS_ReadDir(
174 out_dirent.as_mut_ptr(),
177 Some(Ok(DirEntry { entry: out_dirent.assume_init(), inner: Arc::clone(&self.inner) }))
182 impl Drop for InnerReadDir {
184 unsafe { abi::SOLID_FS_CloseDir(self.dirp) };
189 pub fn path(&self) -> PathBuf {
190 self.inner.root.join(OsStr::from_bytes(
191 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }.to_bytes(),
195 pub fn file_name(&self) -> OsString {
196 OsStr::from_bytes(unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }.to_bytes())
200 pub fn metadata(&self) -> io::Result<FileAttr> {
204 pub fn file_type(&self) -> io::Result<FileType> {
205 match self.entry.d_type {
206 abi::DT_CHR => Ok(FileType(abi::S_IFCHR)),
207 abi::DT_FIFO => Ok(FileType(abi::S_IFIFO)),
208 abi::DT_REG => Ok(FileType(abi::S_IFREG)),
209 abi::DT_DIR => Ok(FileType(abi::S_IFDIR)),
210 abi::DT_BLK => Ok(FileType(abi::S_IFBLK)),
211 _ => lstat(&self.path()).map(|m| m.file_type()),
217 pub fn new() -> OpenOptions {
231 pub fn read(&mut self, read: bool) {
234 pub fn write(&mut self, write: bool) {
237 pub fn append(&mut self, append: bool) {
238 self.append = append;
240 pub fn truncate(&mut self, truncate: bool) {
241 self.truncate = truncate;
243 pub fn create(&mut self, create: bool) {
244 self.create = create;
246 pub fn create_new(&mut self, create_new: bool) {
247 self.create_new = create_new;
250 pub fn custom_flags(&mut self, flags: i32) {
251 self.custom_flags = flags;
253 pub fn mode(&mut self, _mode: u32) {}
255 fn get_access_mode(&self) -> io::Result<c_int> {
256 match (self.read, self.write, self.append) {
257 (true, false, false) => Ok(abi::O_RDONLY),
258 (false, true, false) => Ok(abi::O_WRONLY),
259 (true, true, false) => Ok(abi::O_RDWR),
260 (false, _, true) => Ok(abi::O_WRONLY | abi::O_APPEND),
261 (true, _, true) => Ok(abi::O_RDWR | abi::O_APPEND),
262 (false, false, false) => Err(io::Error::from_raw_os_error(libc::EINVAL)),
266 fn get_creation_mode(&self) -> io::Result<c_int> {
267 match (self.write, self.append) {
270 if self.truncate || self.create || self.create_new {
271 return Err(io::Error::from_raw_os_error(libc::EINVAL));
275 if self.truncate && !self.create_new {
276 return Err(io::Error::from_raw_os_error(libc::EINVAL));
281 Ok(match (self.create, self.truncate, self.create_new) {
282 (false, false, false) => 0,
283 (true, false, false) => abi::O_CREAT,
284 (false, true, false) => abi::O_TRUNC,
285 (true, true, false) => abi::O_CREAT | abi::O_TRUNC,
286 (_, _, true) => abi::O_CREAT | abi::O_EXCL,
291 fn cstr(path: &Path) -> io::Result<CString> {
292 Ok(CString::new(path.as_os_str().as_bytes())?)
296 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
297 let flags = opts.get_access_mode()?
298 | opts.get_creation_mode()?
299 | (opts.custom_flags as c_int & !abi::O_ACCMODE);
301 let mut fd = MaybeUninit::uninit();
302 error::SolidError::err_if_negative(abi::SOLID_FS_Open(
304 cstr(path)?.as_ptr(),
307 .map_err(|e| e.as_io_error())?;
308 Ok(File { fd: FileDesc::new(fd.assume_init()) })
312 pub fn file_attr(&self) -> io::Result<FileAttr> {
316 pub fn fsync(&self) -> io::Result<()> {
320 pub fn datasync(&self) -> io::Result<()> {
324 pub fn truncate(&self, _size: u64) -> io::Result<()> {
328 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
330 let mut out_num_bytes = MaybeUninit::uninit();
331 error::SolidError::err_if_negative(abi::SOLID_FS_Read(
335 out_num_bytes.as_mut_ptr(),
337 .map_err(|e| e.as_io_error())?;
338 Ok(out_num_bytes.assume_init())
342 pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
344 let len = buf.remaining();
345 let mut out_num_bytes = MaybeUninit::uninit();
346 error::SolidError::err_if_negative(abi::SOLID_FS_Read(
348 buf.unfilled_mut().as_mut_ptr() as *mut u8,
350 out_num_bytes.as_mut_ptr(),
352 .map_err(|e| e.as_io_error())?;
354 // Safety: `out_num_bytes` is filled by the successful call to
356 let num_bytes_read = out_num_bytes.assume_init();
358 // Safety: `num_bytes_read` bytes were written to the unfilled
359 // portion of the buffer
360 buf.assume_init(num_bytes_read);
362 buf.add_filled(num_bytes_read);
368 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
369 crate::io::default_read_vectored(|buf| self.read(buf), bufs)
372 pub fn is_read_vectored(&self) -> bool {
376 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
378 let mut out_num_bytes = MaybeUninit::uninit();
379 error::SolidError::err_if_negative(abi::SOLID_FS_Write(
383 out_num_bytes.as_mut_ptr(),
385 .map_err(|e| e.as_io_error())?;
386 Ok(out_num_bytes.assume_init())
390 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
391 crate::io::default_write_vectored(|buf| self.write(buf), bufs)
394 pub fn is_write_vectored(&self) -> bool {
398 pub fn flush(&self) -> io::Result<()> {
399 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Sync(self.fd.raw()) })
400 .map_err(|e| e.as_io_error())?;
404 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
405 let (whence, pos) = match pos {
406 // Casting to `i64` is fine, too large values will end up as
407 // negative which will cause an error in `SOLID_FS_Lseek`.
408 SeekFrom::Start(off) => (abi::SEEK_SET, off as i64),
409 SeekFrom::End(off) => (abi::SEEK_END, off),
410 SeekFrom::Current(off) => (abi::SEEK_CUR, off),
412 error::SolidError::err_if_negative(unsafe {
413 abi::SOLID_FS_Lseek(self.fd.raw(), pos, whence)
415 .map_err(|e| e.as_io_error())?;
417 // Get the new offset
419 let mut out_offset = MaybeUninit::uninit();
420 error::SolidError::err_if_negative(abi::SOLID_FS_Ftell(
422 out_offset.as_mut_ptr(),
424 .map_err(|e| e.as_io_error())?;
425 Ok(out_offset.assume_init() as u64)
429 pub fn duplicate(&self) -> io::Result<File> {
433 pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> {
440 unsafe { abi::SOLID_FS_Close(self.fd.raw()) };
445 pub fn new() -> DirBuilder {
449 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
450 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Mkdir(cstr(p)?.as_ptr()) })
451 .map_err(|e| e.as_io_error())?;
456 impl fmt::Debug for File {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 f.debug_struct("File").field("fd", &self.fd.raw()).finish()
462 pub fn unlink(p: &Path) -> io::Result<()> {
463 if stat(p)?.file_type().is_dir() {
464 Err(io::const_io_error!(io::ErrorKind::IsADirectory, "is a directory"))
466 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) })
467 .map_err(|e| e.as_io_error())?;
472 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
473 error::SolidError::err_if_negative(unsafe {
474 abi::SOLID_FS_Rename(cstr(old)?.as_ptr(), cstr(new)?.as_ptr())
476 .map_err(|e| e.as_io_error())?;
480 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
481 error::SolidError::err_if_negative(unsafe {
482 abi::SOLID_FS_Chmod(cstr(p)?.as_ptr(), perm.0.into())
484 .map_err(|e| e.as_io_error())?;
488 pub fn rmdir(p: &Path) -> io::Result<()> {
489 if stat(p)?.file_type().is_dir() {
490 error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) })
491 .map_err(|e| e.as_io_error())?;
494 Err(io::const_io_error!(io::ErrorKind::NotADirectory, "not a directory"))
498 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
499 for child in readdir(path)? {
501 let child_type = child.file_type()?;
502 if child_type.is_dir() {
503 remove_dir_all(&child.path())?;
505 unlink(&child.path())?;
511 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
512 // This target doesn't support symlinks
514 Err(io::const_io_error!(io::ErrorKind::InvalidInput, "not a symbolic link"))
517 pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> {
518 // This target doesn't support symlinks
522 pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
523 // This target doesn't support symlinks
527 pub fn stat(p: &Path) -> io::Result<FileAttr> {
528 // This target doesn't support symlinks
532 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
534 let mut out_stat = MaybeUninit::uninit();
535 error::SolidError::err_if_negative(abi::SOLID_FS_Stat(
537 out_stat.as_mut_ptr(),
539 .map_err(|e| e.as_io_error())?;
540 Ok(FileAttr { stat: out_stat.assume_init() })
544 pub fn canonicalize(_p: &Path) -> io::Result<PathBuf> {
548 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
551 let mut reader = File::open(from)?;
552 let mut writer = File::create(to)?;
554 io::copy(&mut reader, &mut writer)