Minor code cleanup

This commit is contained in:
topjohnwu
2025-01-13 12:29:42 +08:00
committed by John Wu
parent b62835cbeb
commit 4dcd733ddd
3 changed files with 26 additions and 54 deletions

View File

@@ -3,7 +3,7 @@ use crate::{
cstr, errno, error, FsPath, FsPathBuf, LibcReturn, Utf8CStr, Utf8CStrBuf, Utf8CStrBufArr,
Utf8CStrWrite,
};
use bytemuck::{bytes_of_mut, Pod};
use bytemuck::{bytes_of, bytes_of_mut, Pod};
use libc::{
c_uint, dirent, makedev, mode_t, EEXIST, ENOENT, F_OK, O_CLOEXEC, O_CREAT, O_PATH, O_RDONLY,
O_RDWR, O_TRUNC, O_WRONLY,
@@ -14,13 +14,11 @@ use std::cmp::min;
use std::ffi::CStr;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::os::fd::{AsFd, BorrowedFd, IntoRawFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::path::Path;
use std::sync::Arc;
use std::{io, mem, ptr, slice};
pub fn __open_fd_impl(path: &Utf8CStr, flags: i32, mode: mode_t) -> io::Result<OwnedFd> {
@@ -123,6 +121,7 @@ impl<T: BufRead> BufReadExt for T {
pub trait WriteExt {
fn write_zeros(&mut self, len: usize) -> io::Result<()>;
fn write_pod<F: Pod>(&mut self, data: &F) -> io::Result<()>;
}
impl<T: Write> WriteExt for T {
@@ -135,6 +134,10 @@ impl<T: Write> WriteExt for T {
}
Ok(())
}
fn write_pod<F: Pod>(&mut self, data: &F) -> io::Result<()> {
self.write_all(bytes_of(data))
}
}
pub struct FileAttr {
@@ -1030,32 +1033,3 @@ pub fn parse_mount_info(pid: &str) -> Vec<MountInfo> {
}
res
}
#[derive(Default, Clone)]
pub enum SharedFd {
#[default]
None,
Shared(Arc<OwnedFd>),
}
impl From<OwnedFd> for SharedFd {
fn from(fd: OwnedFd) -> Self {
SharedFd::Shared(Arc::new(fd))
}
}
impl SharedFd {
pub const fn new() -> Self {
SharedFd::None
}
// This is unsafe because we cannot create multiple mutable references to the same fd.
// This can only be safely used if and only if the underlying fd points to a pipe,
// and the read/write operations performed on the file involves bytes less than PIPE_BUF.
pub unsafe fn as_file(&self) -> Option<ManuallyDrop<File>> {
match self {
SharedFd::None => None,
SharedFd::Shared(arc) => Some(ManuallyDrop::new(File::from_raw_fd(arc.as_raw_fd()))),
}
}
}