//! Efficient decimal integer formatting. //! //! # Safety //! //! This uses `CStr::from_bytes_with_nul_unchecked` and //! `str::from_utf8_unchecked`on the buffer that it filled itself. #![allow(unsafe_code)]
usecrate::backend::fd::{AsFd, AsRawFd as _}; usecrate::ffi::CStr; use core::fmt; use core::hint::unreachable_unchecked; use core::mem::{self, MaybeUninit}; use core::num::{NonZeroU8, NonZeroUsize}; #[cfg(all(feature = "std", unix))] use std::os::unix::ffi::OsStrExt; #[cfg(all(
feature = "std",
target_os = "wasi",
any(not(target_env = "p2"), wasip2)
))] use std::os::wasi::ffi::OsStrExt; #[cfg(feature = "std")] use {std::ffi::OsStr, std::path::Path};
/// Format an integer into a decimal `Path` component, without constructing a /// temporary `PathBuf` or `String`. /// /// This is used for opening paths such as `/proc/self/fd/<fd>` on Linux. /// /// # Examples /// /// ``` /// # #[cfg(any(feature = "fs", feature = "net"))] /// use rustix::path::DecInt; /// /// # #[cfg(any(feature = "fs", feature = "net"))] /// assert_eq!( /// format!("hello {}", DecInt::new(9876).as_ref().display()), /// "hello 9876" /// ); /// ``` #[derive(Clone)] pubstruct DecInt {
buf: [MaybeUninit<u8>; BUF_LEN],
len: NonZeroU8,
}
/// Enough to hold an {u,i}64 and NUL terminator. const BUF_LEN: usize = U64_MAX_STR_LEN + 1;
/// Maximum length of a formatted [`u64`]. const U64_MAX_STR_LEN: usize = "18446744073709551615".len();
/// Maximum length of a formatted [`i64`]. #[allow(dead_code)] const I64_MAX_STR_LEN: usize = "-9223372036854775808".len();
/// An integer that can be used by [`DecInt::new`]. pubtrait Integer: private::Sealed {}
impl Integer for i8 {} impl Integer for i16 {} impl Integer for i32 {} impl Integer for i64 {} impl Integer for u8 {} impl Integer for u16 {} impl Integer for u32 {} impl Integer for u64 {}
impl DecInt { /// Construct a new path component from an integer. pubfn new<Int: Integer>(i: Int) -> Self { use private::Sealed as _;
let (is_neg, mut i) = i.as_unsigned(); letmut len = 1; letmut buf = [MaybeUninit::uninit(); BUF_LEN];
buf[BUF_LEN - 1] = MaybeUninit::new(b'\0');
// We use `loop { …; if cond { break } }` instead of // `while !cond { … }` so the loop is entered at least once. This way // `0` does not need a special handling. loop {
len += 1; if len > BUF_LEN { // SAFETY: A stringified `i64`/`u64` cannot be longer than // `U64_MAX_STR_LEN` bytes. unsafe { unreachable_unchecked() };
}
buf[BUF_LEN - len] = MaybeUninit::new(b'0' + i.div_mod_10()); if i.eq_zero() { break;
}
}
if is_neg {
len += 1; if len > BUF_LEN { // SAFETY: A stringified `i64`/`u64` cannot be longer than // `U64_MAX_STR_LEN` bytes. unsafe { unreachable_unchecked() };
}
buf[BUF_LEN - len] = MaybeUninit::new(b'-');
}
Self {
buf,
len: NonZeroU8::new(len as u8).unwrap(),
}
}
/// Construct a new path component from a file descriptor. #[inline] pubfn from_fd<Fd: AsFd>(fd: Fd) -> Self { Self::new(fd.as_fd().as_raw_fd())
}
/// Return the raw byte buffer as a `&str`. #[inline] pubfn as_str(&self) -> &str { // SAFETY: `DecInt` always holds a formatted decimal number, so it's // always valid UTF-8. unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
}
/// Return the raw byte buffer as a `&CStr`. #[inline] pubfn as_c_str(&self) -> &CStr { let bytes_with_nul = self.as_bytes_with_nul();
debug_assert!(CStr::from_bytes_with_nul(bytes_with_nul).is_ok());
// SAFETY: `self.buf` holds a single decimal ASCII representation and // at least one extra NUL byte. unsafe { CStr::from_bytes_with_nul_unchecked(bytes_with_nul) }
}
/// Return the raw byte buffer including the NUL byte. #[inline] pubfn as_bytes_with_nul(&self) -> &[u8] { let len = NonZeroUsize::from(self.len).get(); if len > BUF_LEN { // SAFETY: A stringified `i64`/`u64` cannot be longer than // `U64_MAX_STR_LEN` bytes. unsafe { unreachable_unchecked() };
} let init = &self.buf[(self.buf.len() - len)..]; // SAFETY: We're guaranteed to have initialized `len + 1` bytes. unsafe { mem::transmute::<&[MaybeUninit<u8>], &[u8]>(init) }
}
/// Return the raw byte buffer. #[inline] pubfn as_bytes(&self) -> &[u8] { let bytes = self.as_bytes_with_nul();
&bytes[..bytes.len() - 1]
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.