Skip to content

Commit

Permalink
use rust 1.82.0 features
Browse files Browse the repository at this point in the history
  • Loading branch information
kadiwa4 committed Dec 4, 2024
1 parent 8ecb95d commit f9da8bc
Show file tree
Hide file tree
Showing 9 changed files with 29 additions and 40 deletions.
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ unescaped_backticks = "warn"
name = "deforest"
version = "0.3.2"
edition = "2021"
rust-version = "1.74"
rust-version = "1.82.0"
description = "efficient `#![no_std]` parser for devicetree blobs"
repository = "https://github.com/kadiwa4/deforest"
license = "MIT"
Expand Down Expand Up @@ -56,7 +56,6 @@ zerocopy = { version = "0.8.7", features = ["derive"] }

[features]
alloc = ["fallible-iterator/alloc"]
std = ["alloc", "fallible-iterator/std"]

derive = ["deforest_derive"]
model = []
Expand Down
2 changes: 1 addition & 1 deletion deforest_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "deforest_derive"
version = "0.3.0"
edition = "2021"
rust-version = "1.70"
rust-version = "1.82.0"
description = "derive macros for the crate deforest"
readme = "../README.md"
repository = "https://github.com/kadiwa4/deforest"
Expand Down
4 changes: 2 additions & 2 deletions deforest_derive/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,10 +328,10 @@ Valid forms are:
"children" => match meta {
Meta::Path(_) => Some((ItemKind::Children, None)),
Meta::List(list) => {
if !meta_list_get_single(&list)
if meta_list_get_single(&list)
.as_ref()
.and_then(|i| i.path().get_ident())
.is_some_and(|i| *i == "rest")
.is_none_or(|i| *i != "rest")
{
panic_invalid();
}
Expand Down
10 changes: 3 additions & 7 deletions src/alloc.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
//! Features depending on memory allocation.
use core::{
iter::Map,
mem::{size_of, size_of_val},
slice,
};
use core::{iter::Map, slice};
use std_alloc::{boxed::Box, string::String, vec::Vec};

use fallible_iterator::FallibleIterator;
Expand Down Expand Up @@ -84,14 +80,14 @@ impl<'a> DevicetreeBuilder<'a> {
}
));
blob.extend(self.mem_reserve_entries.iter().flat_map(
|e| -> [u64; blob::RawReserveEntry::FIELD_COUNT] {
|e| -> [u64; blob::RawReserveEntry::NUM_FIELDS] {
zerocopy::transmute!(blob::RawReserveEntry {
address: e.address.to_be(),
size: e.size.to_be(),
})
},
));
blob.extend([0; blob::RawReserveEntry::FIELD_COUNT]);
blob.extend([0; blob::RawReserveEntry::NUM_FIELDS]);

// SAFETY: after the requested buffer is filled with data, len can be set to the capacity.
// the constructed Devicetree would pass all of the checks, so we can skip them
Expand Down
7 changes: 3 additions & 4 deletions src/blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ mod token;

use core::{
fmt::{self, Debug, Display, Formatter, Write},
mem::{size_of, size_of_val},
ptr::NonNull,
slice,
};
Expand Down Expand Up @@ -253,10 +252,10 @@ impl Devicetree {
return Err(BlobError::InvalidBlockOrder);
}

if !usize::try_from(u32::from_be(self.header().size_dt_strings))
if usize::try_from(u32::from_be(self.header().size_dt_strings))
.ok()
.and_then(|s| usize::checked_add(strings_offset, s))
.is_some_and(|e| e <= exact_size)
.is_none_or(|e| e > exact_size)
{
return Err(BlobError::BlockOutOfBounds);
}
Expand Down Expand Up @@ -584,5 +583,5 @@ pub(crate) struct RawReserveEntry {
}

impl RawReserveEntry {
pub(crate) const FIELD_COUNT: usize = size_of::<Self>() / DTB_OPTIMAL_ALIGN;
pub(crate) const NUM_FIELDS: usize = size_of::<Self>() / DTB_OPTIMAL_ALIGN;
}
3 changes: 2 additions & 1 deletion src/blob/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ impl<'dtb> Node<'dtb> {
pub fn get_children<'n>(
&self,
name: &'n str,
) -> fallible_iterator::Filter<Children<'dtb>, impl FnMut(&Node<'dtb>) -> Result<bool> + 'n> {
) -> fallible_iterator::Filter<Children<'dtb>, impl FnMut(&Self) -> Result<bool> + use<'dtb, 'n>>
{
Children(Items::new(self, self.contents))
.filter(move |n| n.split_name().map(|(n, _)| n == name))
}
Expand Down
9 changes: 4 additions & 5 deletions src/blob/token.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use core::{
cmp::Ordering,
hash::{Hash, Hasher},
mem::size_of,
};

use zerocopy::FromBytes;
Expand Down Expand Up @@ -167,7 +166,8 @@ impl Devicetree {

let len = DtUint::try_from(u32::from_be(header.len))
.map_err(|_| BlobError::InvalidPropertyHeader)?;
let value = util::slice_get_with_len(blob, offset, len as usize)
let value = blob
.get(offset..offset + len as usize)
.ok_or(BlobError::InvalidPropertyHeader)?;

cursor.increase_offset(len, blob)?;
Expand Down Expand Up @@ -196,13 +196,12 @@ fn next_raw(blob: &[u8], cursor: &mut Cursor) -> Result<Option<RawToken>> {
const END: u32 = RawToken::End as u32;

let offset = cursor.offset as usize;
let Some(token) = util::slice_get_with_len(blob, offset, TOKEN_SIZE as usize) else {
let Some(&token) = blob[offset..].first_chunk::<{ TOKEN_SIZE as usize }>() else {
return Ok(None);
};
let token = u32::from_ne_bytes(token.try_into().unwrap());

cursor.offset += TOKEN_SIZE;
let token = match token {
let token = match u32::from_ne_bytes(token) {
BEGIN_NODE => RawToken::BeginNode,
END_NODE => RawToken::EndNode,
PROP => RawToken::Prop,
Expand Down
22 changes: 6 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;
#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "alloc")]
pub mod alloc;
Expand Down Expand Up @@ -70,8 +68,7 @@ impl Display for Error {
}
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}
impl core::error::Error for Error {}

pub type Result<T, E = Error> = core::result::Result<T, E>;

Expand Down Expand Up @@ -115,8 +112,7 @@ impl Display for BlobError {
}
}

#[cfg(feature = "std")]
impl std::error::Error for BlobError {}
impl core::error::Error for BlobError {}

impl From<BlobError> for Error {
#[inline]
Expand Down Expand Up @@ -212,7 +208,7 @@ impl FallibleIterator for MemReserveEntries<'_> {
fn next(&mut self) -> Result<Option<Self::Item>, Self::Error> {
let (raw, _) = blob::RawReserveEntry::read_from_prefix(self.blob.as_bytes())
.map_err(|_| BlobError::UnexpectedEnd)?;
self.blob = &self.blob[blob::RawReserveEntry::FIELD_COUNT..];
self.blob = &self.blob[blob::RawReserveEntry::NUM_FIELDS..];

let entry = (raw.address != 0 || raw.size != 0).then(|| MemReserveEntry {
address: u64::from_be(raw.address),
Expand Down Expand Up @@ -464,10 +460,11 @@ pub mod util {
return None;
}
let mut ret: u128 = 0;
for &word in value.get(..cells as usize)? {
let (content, rest) = value.split_at_checked(cells as usize)?;
for &word in content {
ret = ret << 0x20 | u32::from_be(word) as u128;
}
*value = &value[cells as usize..];
*value = rest;
Some(ret)
}

Expand Down Expand Up @@ -495,13 +492,6 @@ pub mod util {
AsciiStr::from_ascii(blob).ok().map(AsciiStr::as_str)
}

/// Same as `<[_]>::get` with a range except that it takes a length, not an end
/// offset.
#[inline]
pub(crate) fn slice_get_with_len<T>(slice: &[T], offset: usize, len: usize) -> Option<&[T]> {
slice.get(offset..offset + len)
}

/// Same as `<[_]>::get_unchecked` with a range except that it takes a length,
/// not an end offset.
///
Expand Down
9 changes: 7 additions & 2 deletions src/prop_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,10 @@ impl<'dtb> DeserializeProperty<'dtb> for SmallU64 {
}
}

/// Zero-sized type that throws if the property value isn't `"memory"`.
/// Zero-sized type that throws [an error] if the property value isn't
/// `"memory"`.
///
/// [an error]: Error::InvalidDeviceType
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceTypeMemory;

Expand All @@ -575,7 +578,9 @@ impl<'dtb> DeserializeProperty<'dtb> for DeviceTypeMemory {
}
}

/// Zero-sized type that throws if the property value isn't `"cpu"`.
/// Zero-sized type that throws [an error] if the property value isn't `"cpu"`.
///
/// [an error]: Error::InvalidDeviceType
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceTypeCpu;

Expand Down

0 comments on commit f9da8bc

Please sign in to comment.