Replace all usage of `from_bytes` with `from_first_bytes`

This commit is contained in:
Jianfeng Jiang 2026-02-05 07:36:31 +00:00 committed by Tate, Hongliang Tian
parent 4a80f0e5eb
commit bf13673b97
11 changed files with 48 additions and 41 deletions

View File

@ -229,7 +229,7 @@ fn parse_gpt(device: &Arc<dyn BlockDevice>) -> Vec<Option<PartitionInfo>> {
for j in 0..entries_per_sector { for j in 0..entries_per_sector {
let entry_offset = j * gpt.size_of_partition_entry as usize; let entry_offset = j * gpt.size_of_partition_entry as usize;
let entry = GptEntry::from_bytes(&buf[entry_offset..entry_offset + entry_size]); let entry = GptEntry::from_first_bytes(&buf[entry_offset..entry_offset + entry_size]);
if entry.is_valid() { if entry.is_valid() {
partitions.push(Some(PartitionInfo::Gpt(entry))); partitions.push(Some(PartitionInfo::Gpt(entry)));
} else { } else {

View File

@ -110,7 +110,7 @@ impl<L: BlockLog> CryptoChain<L> {
// Read block and get footer. // Read block and get footer.
let mut block_buf = Buf::alloc(1)?; let mut block_buf = Buf::alloc(1)?;
self.block_log.read(pos, block_buf.as_mut())?; self.block_log.read(pos, block_buf.as_mut())?;
let footer: Footer = Pod::from_bytes(&block_buf.as_slice()[Self::AVAIL_BLOCK_SIZE..]); let footer: Footer = Pod::from_first_bytes(&block_buf.as_slice()[Self::AVAIL_BLOCK_SIZE..]);
let payload_len = footer.len as usize; let payload_len = footer.len as usize;
if payload_len > Self::AVAIL_BLOCK_SIZE || payload_len > buf.len() { if payload_len > Self::AVAIL_BLOCK_SIZE || payload_len > buf.len() {
@ -290,7 +290,7 @@ impl<L: BlockLog> LendingIterator for Recovery<L> {
// Deserialize footer. // Deserialize footer.
let footer: Footer = let footer: Footer =
Pod::from_bytes(&self.read_buf.as_slice()[CryptoChain::<L>::AVAIL_BLOCK_SIZE..]); Pod::from_first_bytes(&self.read_buf.as_slice()[CryptoChain::<L>::AVAIL_BLOCK_SIZE..]);
let payload_len = footer.len as usize; let payload_len = footer.len as usize;
if payload_len > CryptoChain::<L>::AVAIL_BLOCK_SIZE { if payload_len > CryptoChain::<L>::AVAIL_BLOCK_SIZE {
return None; return None;

View File

@ -739,7 +739,7 @@ impl Superblock {
plain.as_mut_slice(), plain.as_mut_slice(),
)?; )?;
let superblock = Superblock::from_bytes(&plain.as_slice()[..Self::SUPERBLOCK_SIZE]); let superblock = Superblock::from_first_bytes(&plain.as_slice()[..Self::SUPERBLOCK_SIZE]);
if superblock.magic != MAGIC_NUMBER { if superblock.magic != MAGIC_NUMBER {
Err(Error::with_msg(InvalidArgs, "open superblock failed")) Err(Error::with_msg(InvalidArgs, "open superblock failed"))
} else { } else {
@ -762,7 +762,7 @@ impl Superblock {
} }
fn derive_skcipher_key(root_key: &Key) -> SkcipherKey { fn derive_skcipher_key(root_key: &Key) -> SkcipherKey {
SkcipherKey::from_bytes(root_key.as_bytes()) SkcipherKey::from_first_bytes(root_key.as_bytes())
} }
} }

View File

@ -509,7 +509,7 @@ impl<K: RecordKey<K>, V: RecordValue> SSTable<K, V> {
let mut rbuf = Buf::alloc(1)?; let mut rbuf = Buf::alloc(1)?;
// Load footer block (last block) // Load footer block (last block)
tx_log.read(nblocks - 1, rbuf.as_mut())?; tx_log.read(nblocks - 1, rbuf.as_mut())?;
let meta = FooterMeta::from_bytes(&rbuf.as_slice()[BLOCK_SIZE - FOOTER_META_SIZE..]); let meta = FooterMeta::from_first_bytes(&rbuf.as_slice()[BLOCK_SIZE - FOOTER_META_SIZE..]);
let mut rbuf = Buf::alloc(meta.index_nblocks as _)?; let mut rbuf = Buf::alloc(meta.index_nblocks as _)?;
tx_log.read(nblocks - meta.index_nblocks as usize, rbuf.as_mut())?; tx_log.read(nblocks - meta.index_nblocks as usize, rbuf.as_mut())?;
@ -521,9 +521,10 @@ impl<K: RecordKey<K>, V: RecordValue> SSTable<K, V> {
&rbuf.as_slice()[i * Self::INDEX_ENTRY_SIZE..(i + 1) * Self::INDEX_ENTRY_SIZE]; &rbuf.as_slice()[i * Self::INDEX_ENTRY_SIZE..(i + 1) * Self::INDEX_ENTRY_SIZE];
let pos = BlockId::from_le_bytes(buf[..BID_SIZE].try_into().unwrap()); let pos = BlockId::from_le_bytes(buf[..BID_SIZE].try_into().unwrap());
let first = K::from_bytes(&buf[BID_SIZE..BID_SIZE + Self::K_SIZE]); let first = K::from_first_bytes(&buf[BID_SIZE..BID_SIZE + Self::K_SIZE]);
let last = let last = K::from_first_bytes(
K::from_bytes(&buf[Self::INDEX_ENTRY_SIZE - Self::K_SIZE..Self::INDEX_ENTRY_SIZE]); &buf[Self::INDEX_ENTRY_SIZE - Self::K_SIZE..Self::INDEX_ENTRY_SIZE],
);
tx_log.read(pos, BufMut::try_from(&mut record_block[..]).unwrap())?; tx_log.read(pos, BufMut::try_from(&mut record_block[..]).unwrap())?;
let _ = cache.put(pos, Arc::new(RecordBlock::from_buf(record_block.clone()))); let _ = cache.put(pos, Arc::new(RecordBlock::from_buf(record_block.clone())));
@ -592,7 +593,7 @@ impl<K: RecordKey<K>, V: RecordValue> Iterator for BlockQueryIter<'_, K, V> {
return None; return None;
} }
let key = K::from_bytes(&buf_slice[offset..offset + k_size]); let key = K::from_first_bytes(&buf_slice[offset..offset + k_size]);
offset += k_size; offset += k_size;
let flag = RecordFlag::from(buf_slice[offset]); let flag = RecordFlag::from(buf_slice[offset]);
@ -605,7 +606,7 @@ impl<K: RecordKey<K>, V: RecordValue> Iterator for BlockQueryIter<'_, K, V> {
let value_opt = match flag { let value_opt = match flag {
RecordFlag::Synced | RecordFlag::Unsynced => { RecordFlag::Synced | RecordFlag::Unsynced => {
let v_opt = if hit_target { let v_opt = if hit_target {
Some(V::from_bytes(&buf_slice[offset..offset + v_size])) Some(V::from_first_bytes(&buf_slice[offset..offset + v_size]))
} else { } else {
None None
}; };
@ -614,7 +615,7 @@ impl<K: RecordKey<K>, V: RecordValue> Iterator for BlockQueryIter<'_, K, V> {
} }
RecordFlag::SyncedAndUnsynced => { RecordFlag::SyncedAndUnsynced => {
let v_opt = if hit_target { let v_opt = if hit_target {
Some(V::from_bytes( Some(V::from_first_bytes(
&buf_slice[offset + v_size..offset + 2 * v_size], &buf_slice[offset + v_size..offset + 2 * v_size],
)) ))
} else { } else {
@ -649,7 +650,7 @@ impl<K: RecordKey<K>, V: RecordValue> Iterator for BlockScanIter<'_, K, V> {
return None; return None;
} }
let key = K::from_bytes(&buf_slice[offset..offset + k_size]); let key = K::from_first_bytes(&buf_slice[offset..offset + k_size]);
offset += k_size; offset += k_size;
let flag = RecordFlag::from(buf_slice[offset]); let flag = RecordFlag::from(buf_slice[offset]);
@ -660,12 +661,12 @@ impl<K: RecordKey<K>, V: RecordValue> Iterator for BlockScanIter<'_, K, V> {
let v_ex = match flag { let v_ex = match flag {
RecordFlag::Synced => { RecordFlag::Synced => {
let v = V::from_bytes(&buf_slice[offset..offset + v_size]); let v = V::from_first_bytes(&buf_slice[offset..offset + v_size]);
offset += v_size; offset += v_size;
ValueEx::Synced(v) ValueEx::Synced(v)
} }
RecordFlag::Unsynced => { RecordFlag::Unsynced => {
let v = V::from_bytes(&buf_slice[offset..offset + v_size]); let v = V::from_first_bytes(&buf_slice[offset..offset + v_size]);
offset += v_size; offset += v_size;
if all_synced { if all_synced {
ValueEx::Synced(v) ValueEx::Synced(v)
@ -679,9 +680,9 @@ impl<K: RecordKey<K>, V: RecordValue> Iterator for BlockScanIter<'_, K, V> {
} }
} }
RecordFlag::SyncedAndUnsynced => { RecordFlag::SyncedAndUnsynced => {
let sv = V::from_bytes(&buf_slice[offset..offset + v_size]); let sv = V::from_first_bytes(&buf_slice[offset..offset + v_size]);
offset += v_size; offset += v_size;
let usv = V::from_bytes(&buf_slice[offset..offset + v_size]); let usv = V::from_first_bytes(&buf_slice[offset..offset + v_size]);
offset += v_size; offset += v_size;
if all_synced { if all_synced {
if let Some(listener) = event_listener { if let Some(listener) = event_listener {

View File

@ -188,9 +188,10 @@ impl<D: BlockSet + 'static> WalAppendTx<D> {
match flag.unwrap() { match flag.unwrap() {
WalAppendFlag::Record => { WalAppendFlag::Record => {
let record = { let record = {
let k = K::from_bytes(&buf_slice[offset..offset + k_size]); let k = K::from_first_bytes(&buf_slice[offset..offset + k_size]);
let v = let v = V::from_first_bytes(
V::from_bytes(&buf_slice[offset + k_size..offset + k_size + v_size]); &buf_slice[offset + k_size..offset + k_size + v_size],
);
offset += k_size + v_size; offset += k_size + v_size;
(k, v) (k, v)
}; };

View File

@ -196,7 +196,7 @@ impl AllocTable {
if diff == AllocDiff::Invalid { if diff == AllocDiff::Invalid {
continue; continue;
} }
let bid = BlockId::from_bytes(&buf_slice[offset..offset + BID_SIZE]); let bid = BlockId::from_first_bytes(&buf_slice[offset..offset + BID_SIZE]);
offset += BID_SIZE; offset += BID_SIZE;
match diff { match diff {
AllocDiff::Alloc => bitmap.set(bid, false), AllocDiff::Alloc => bitmap.set(bid, false),

View File

@ -338,7 +338,7 @@ impl Debug for SocketDevice {
fn read_header_and_body(buffer: &[u8]) -> Result<(VirtioVsockHdr, &[u8]), SocketError> { fn read_header_and_body(buffer: &[u8]) -> Result<(VirtioVsockHdr, &[u8]), SocketError> {
// Shouldn't panic, because we know `RX_BUFFER_SIZE > size_of::<VirtioVsockHdr>()`. // Shouldn't panic, because we know `RX_BUFFER_SIZE > size_of::<VirtioVsockHdr>()`.
let header = VirtioVsockHdr::from_bytes(&buffer[..VIRTIO_VSOCK_HDR_LEN]); let header = VirtioVsockHdr::from_first_bytes(&buffer[..VIRTIO_VSOCK_HDR_LEN]);
let body_length = header.len() as usize; let body_length = header.len() as usize;
// This could fail if the device returns an unreasonably long body length. // This could fail if the device returns an unreasonably long body length.

View File

@ -91,36 +91,40 @@ impl TryFrom<RawExfatDentry> for ExfatDentry {
#[expect(clippy::match_overlapping_arm)] #[expect(clippy::match_overlapping_arm)]
// FIXME: `EXFAT_STREAM` and `0xC0..=0xFF` overlap. Is the overlapping case expected? // FIXME: `EXFAT_STREAM` and `0xC0..=0xFF` overlap. Is the overlapping case expected?
match dentry.dentry_type { match dentry.dentry_type {
EXFAT_FILE => Ok(ExfatDentry::File(ExfatFileDentry::from_bytes(dentry_bytes))), EXFAT_FILE => Ok(ExfatDentry::File(ExfatFileDentry::from_first_bytes(
EXFAT_STREAM => Ok(ExfatDentry::Stream(ExfatStreamDentry::from_bytes(
dentry_bytes, dentry_bytes,
))), ))),
EXFAT_NAME => Ok(ExfatDentry::Name(ExfatNameDentry::from_bytes(dentry_bytes))), EXFAT_STREAM => Ok(ExfatDentry::Stream(ExfatStreamDentry::from_first_bytes(
EXFAT_BITMAP => Ok(ExfatDentry::Bitmap(ExfatBitmapDentry::from_bytes(
dentry_bytes, dentry_bytes,
))), ))),
EXFAT_UPCASE => Ok(ExfatDentry::Upcase(ExfatUpcaseDentry::from_bytes( EXFAT_NAME => Ok(ExfatDentry::Name(ExfatNameDentry::from_first_bytes(
dentry_bytes, dentry_bytes,
))), ))),
EXFAT_VENDOR_EXT => Ok(ExfatDentry::VendorExt(ExfatVendorExtDentry::from_bytes( EXFAT_BITMAP => Ok(ExfatDentry::Bitmap(ExfatBitmapDentry::from_first_bytes(
dentry_bytes, dentry_bytes,
))), ))),
EXFAT_UPCASE => Ok(ExfatDentry::Upcase(ExfatUpcaseDentry::from_first_bytes(
dentry_bytes,
))),
EXFAT_VENDOR_EXT => Ok(ExfatDentry::VendorExt(
ExfatVendorExtDentry::from_first_bytes(dentry_bytes),
)),
EXFAT_VENDOR_ALLOC => Ok(ExfatDentry::VendorAlloc( EXFAT_VENDOR_ALLOC => Ok(ExfatDentry::VendorAlloc(
ExfatVendorAllocDentry::from_bytes(dentry_bytes), ExfatVendorAllocDentry::from_first_bytes(dentry_bytes),
)), )),
EXFAT_UNUSED => Ok(ExfatDentry::UnUsed), EXFAT_UNUSED => Ok(ExfatDentry::UnUsed),
// Deleted // Deleted
0x01..0x80 => Ok(ExfatDentry::Deleted(ExfatDeletedDentry::from_bytes( 0x01..0x80 => Ok(ExfatDentry::Deleted(ExfatDeletedDentry::from_first_bytes(
dentry_bytes, dentry_bytes,
))), ))),
// Primary // Primary
0x80..0xC0 => Ok(ExfatDentry::GenericPrimary( 0x80..0xC0 => Ok(ExfatDentry::GenericPrimary(
ExfatGenericPrimaryDentry::from_bytes(dentry_bytes), ExfatGenericPrimaryDentry::from_first_bytes(dentry_bytes),
)), )),
// Secondary // Secondary
0xC0..=0xFF => Ok(ExfatDentry::GenericSecondary( 0xC0..=0xFF => Ok(ExfatDentry::GenericSecondary(
ExfatGenericSecondaryDentry::from_bytes(dentry_bytes), ExfatGenericSecondaryDentry::from_first_bytes(dentry_bytes),
)), )),
} }
} }
@ -490,7 +494,8 @@ impl Iterator for ExfatDentryIterator<'_> {
} }
// The result is always OK. // The result is always OK.
let dentry_result = ExfatDentry::try_from(RawExfatDentry::from_bytes(&dentry_buf)).unwrap(); let dentry_result =
ExfatDentry::try_from(RawExfatDentry::from_first_bytes(&dentry_buf)).unwrap();
self.entry += 1; self.entry += 1;
if let Some(s) = self.size { if let Some(s) = self.size {

View File

@ -1147,7 +1147,7 @@ impl ExfatInode {
for i in 0..num_dentry { for i in 0..num_dentry {
let buf_offset = DENTRY_SIZE * i; let buf_offset = DENTRY_SIZE * i;
// Delete cluster chain if needed. // Delete cluster chain if needed.
let dentry = ExfatDentry::try_from(RawExfatDentry::from_bytes( let dentry = ExfatDentry::try_from(RawExfatDentry::from_first_bytes(
&buf[buf_offset..buf_offset + DENTRY_SIZE], &buf[buf_offset..buf_offset + DENTRY_SIZE],
))?; ))?;
self.inner self.inner

View File

@ -152,7 +152,7 @@ pub fn read_socket_addr_from_user(addr: Vaddr, addr_len: usize) -> Result<Socket
if addr_len < size_of::<CSocketAddrInet>() { if addr_len < size_of::<CSocketAddrInet>() {
return_errno_with_message!(Errno::EINVAL, "the socket address length is too small"); return_errno_with_message!(Errno::EINVAL, "the socket address length is too small");
} }
let (addr, port) = CSocketAddrInet::from_bytes(storage.as_bytes()).into(); let (addr, port) = CSocketAddrInet::from_first_bytes(storage.as_bytes()).into();
SocketAddr::IPv4(addr, port) SocketAddr::IPv4(addr, port)
} }
Ok(CSocketAddrFamily::AF_UNIX) => { Ok(CSocketAddrFamily::AF_UNIX) => {
@ -163,14 +163,14 @@ pub fn read_socket_addr_from_user(addr: Vaddr, addr_len: usize) -> Result<Socket
if addr_len < size_of::<CSocketAddrNetlink>() { if addr_len < size_of::<CSocketAddrNetlink>() {
return_errno_with_message!(Errno::EINVAL, "the socket address length is too small"); return_errno_with_message!(Errno::EINVAL, "the socket address length is too small");
} }
let addr = CSocketAddrNetlink::from_bytes(storage.as_bytes()); let addr = CSocketAddrNetlink::from_first_bytes(storage.as_bytes());
SocketAddr::Netlink(addr.into()) SocketAddr::Netlink(addr.into())
} }
Ok(CSocketAddrFamily::AF_VSOCK) => { Ok(CSocketAddrFamily::AF_VSOCK) => {
if addr_len < size_of::<CSocketAddrVm>() { if addr_len < size_of::<CSocketAddrVm>() {
return_errno_with_message!(Errno::EINVAL, "the socket address length is too small"); return_errno_with_message!(Errno::EINVAL, "the socket address length is too small");
} }
let addr = CSocketAddrVm::from_bytes(storage.as_bytes()); let addr = CSocketAddrVm::from_first_bytes(storage.as_bytes());
SocketAddr::Vsock(addr.into()) SocketAddr::Vsock(addr.into())
} }
_ => { _ => {

View File

@ -191,7 +191,7 @@ macro_rules! impl_from_bytes {
"`].", "`].",
)] )]
pub fn from_bytes(bytes: &[u8]) -> Self { pub fn from_bytes(bytes: &[u8]) -> Self {
let header = $header_struct::from_bytes(bytes); let header = $header_struct::from_first_bytes(bytes);
debug_assert_eq!(header.length as usize, bytes.len()); debug_assert_eq!(header.length as usize, bytes.len());
let mut index = size_of::<$header_struct>(); let mut index = size_of::<$header_struct>();
@ -226,7 +226,7 @@ impl DeviceScope {
/// ///
/// This method may panic if the byte prefix does not represent a valid [`DeviceScope`]. /// This method may panic if the byte prefix does not represent a valid [`DeviceScope`].
fn from_bytes_prefix(bytes: &[u8]) -> Self { fn from_bytes_prefix(bytes: &[u8]) -> Self {
let header = DeviceScopeHeader::from_bytes(bytes); let header = DeviceScopeHeader::from_first_bytes(bytes);
debug_assert!((header.length as usize) <= bytes.len()); debug_assert!((header.length as usize) <= bytes.len());
let mut index = size_of::<DeviceScopeHeader>(); let mut index = size_of::<DeviceScopeHeader>();
@ -250,7 +250,7 @@ impl Rhsa {
/// ///
/// This method may panic if the bytes do not represent a valid [`Rhsa`]. /// This method may panic if the bytes do not represent a valid [`Rhsa`].
pub fn from_bytes(bytes: &[u8]) -> Self { pub fn from_bytes(bytes: &[u8]) -> Self {
let val = <Self as Pod>::from_bytes(bytes); let val = <Self as Pod>::from_first_bytes(bytes);
debug_assert_eq!(val.length as usize, bytes.len()); debug_assert_eq!(val.length as usize, bytes.len());
val val
@ -264,7 +264,7 @@ impl Andd {
/// ///
/// This method may panic if the bytes do not represent a valid [`Andd`]. /// This method may panic if the bytes do not represent a valid [`Andd`].
pub fn from_bytes(bytes: &[u8]) -> Self { pub fn from_bytes(bytes: &[u8]) -> Self {
let header = AnddHeader::from_bytes(bytes); let header = AnddHeader::from_first_bytes(bytes);
debug_assert_eq!(header.length as usize, bytes.len()); debug_assert_eq!(header.length as usize, bytes.len());
let header_len = size_of::<AnddHeader>(); let header_len = size_of::<AnddHeader>();