Skip to content

Commit

Permalink
Merge pull request #9 from woshiluo/builtin
Browse files Browse the repository at this point in the history
Refactor to minimize newtype struct & unsafe
  • Loading branch information
luojia65 authored Nov 26, 2024
2 parents 1ca431a + 097e294 commit 6d152e0
Show file tree
Hide file tree
Showing 11 changed files with 216 additions and 306 deletions.
7 changes: 4 additions & 3 deletions examples/qemu-virt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ fn main() -> Result<(), Error> {

{
// 解析!
let t: Tree = from_raw_mut(&dtb).unwrap();
let root: Node = from_raw_mut(&dtb).unwrap();
let t: Tree = root.deserialize();

println!("model = {:?}", t.model);
println!("compatible = {:?}", t.compatible);
Expand Down Expand Up @@ -133,7 +134,7 @@ fn main() -> Result<(), Error> {
}

println!("{:?}", t.soc);
for current_node in t.soc.nodes().unwrap() {
for current_node in t.soc.nodes() {
if current_node.get_parsed_name().0 == "virtio_mmio" {
let mmio = current_node.deserialize::<VirtIoMmio>();
println!("{:?} {:?}", current_node.get_parsed_name(), mmio.reg);
Expand All @@ -142,7 +143,7 @@ fn main() -> Result<(), Error> {

// 解析过程中,设备树的内容被修改了。
// 因此若要以其他方式再次访问设备树,先将这次解析的结果释放。
assert_ne!(slice, RAW_DEVICE_TREE);
// assert_ne!(slice, RAW_DEVICE_TREE);
}
// 释放后,内存会恢复原状。
assert_eq!(slice, RAW_DEVICE_TREE);
Expand Down
4 changes: 2 additions & 2 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use serde::de;
/// # Example
///
/// ```
/// # static RAW_DEVICE_TREE: &'static [u8] = include_bytes!("../examples/hifive-unmatched-a00.dtb");
/// # const RAW_DEVICE_TREE: &'static [u8] = include_bytes!("../examples/hifive-unmatched-a00.dtb");
/// # const BUFFER_SIZE: usize = RAW_DEVICE_TREE.len();
/// # #[repr(align(4))]
/// # struct AlignedBuffer {
Expand Down Expand Up @@ -521,7 +521,7 @@ mod tests {
#[cfg(any(feature = "std", feature = "alloc"))]
#[test]
fn error_invalid_magic() {
static DEVICE_TREE: &[u8] = &[0x11, 0x22, 0x33, 0x44]; // not device tree blob format
const DEVICE_TREE: &[u8] = &[0x11, 0x22, 0x33, 0x44]; // not device tree blob format
const DEVICE_TREE_LEN: usize = DEVICE_TREE.len();
#[repr(align(8))]
struct AlignedBuffer {
Expand Down
29 changes: 8 additions & 21 deletions src/de_mut/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,16 +129,18 @@ impl TitleCursor {
/// 切分节点名。
pub fn split_on<'de>(&self, dtb: RefDtb<'de>) -> (&'de str, BodyCursor) {
let mut index = self.0 + 1;
let mut len = 0;

let structure = &dtb.borrow().structure;
let ptr = structure[index..].as_ptr() as *const u8;
while let Some(block) = structure.get(index) {
index += 1;
if block.is_end_of_str() {
let end = block.str_end();
let s = unsafe { core::slice::from_raw_parts(ptr, end.offset_from(ptr) as _) };
let s = unsafe { core::str::from_utf8_unchecked(s) };
len += end;
let s = structure[self.0 + 1].lead_str(len);
return (s, AnyCursor(index, PhantomData));
} else {
len += 4;
}
}
todo!()
Expand All @@ -158,12 +160,7 @@ impl TitleCursor {
body.skip_str_on(dtb);
body.escape_from(dtb);
if let Cursor::Title(c) = body.move_on(dtb) {
let s = unsafe {
core::slice::from_raw_parts(
structure[c.0 + 1..].as_ptr() as *const u8,
name_bytes.len() + 1,
)
};
let s = structure[c.0 + 1].lead_slice(name_bytes.len() + 1);
if let [name @ .., b'@'] = s {
if name == name_bytes {
body.0 += 1 + name_skip;
Expand Down Expand Up @@ -213,15 +210,15 @@ impl PropCursor {

pub fn data_on<'a>(&self, dtb: RefDtb<'a>) -> &'a [u8] {
if let [_, len_data, _, data @ ..] = &dtb.borrow().structure[self.0..] {
unsafe { core::slice::from_raw_parts(data.as_ptr() as _, len_data.as_usize()) }
data[0].lead_slice(len_data.as_usize())
} else {
todo!()
}
}

pub fn map_on<T>(&self, dtb: RefDtb<'_>, f: impl FnOnce(&[u8]) -> T) -> T {
if let [_, len_data, _, data @ ..] = &dtb.borrow().structure[self.0..] {
f(unsafe { core::slice::from_raw_parts(data.as_ptr() as _, len_data.as_usize()) })
f(data[0].lead_slice(len_data.as_usize()))
} else {
todo!()
}
Expand All @@ -246,16 +243,6 @@ impl PropCursor {
))
}
}

pub fn operate_on(&self, dtb: RefDtb<'_>, f: impl FnOnce(&mut [u8])) {
if let [_, len_data, _, data @ ..] = &mut dtb.borrow_mut().structure[self.0..] {
f(unsafe {
core::slice::from_raw_parts_mut(data.as_mut_ptr() as _, len_data.as_usize())
});
} else {
todo!()
}
}
}

#[derive(Debug)]
Expand Down
32 changes: 1 addition & 31 deletions src/de_mut/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,37 +239,7 @@ impl<'de> de::Deserializer<'de> for &mut ValueDeserializer<'de> {
if name == super::VALUE_DESERIALIZER_NAME {
return visitor.visit_newtype_struct(self);
}
match self.cursor {
ValueCursor::Prop(_, cursor) => match name {
"StrSeq" => {
let inner = super::str_seq::Inner {
dtb: self.dtb,
cursor,
};
visitor.visit_borrowed_bytes(unsafe {
core::slice::from_raw_parts(
&inner as *const _ as *const u8,
core::mem::size_of_val(&inner),
)
})
}
"Reg" => {
let inner = super::reg::Inner {
dtb: self.dtb,
reg: self.reg,
cursor,
};
visitor.visit_borrowed_bytes(unsafe {
core::slice::from_raw_parts(
&inner as *const _ as *const u8,
core::mem::size_of_val(&inner),
)
})
}
_ => visitor.visit_newtype_struct(self),
},
ValueCursor::Body(_) => visitor.visit_newtype_struct(self),
}
unreachable!("unknown newtype struct");
}

fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
Expand Down
Loading

0 comments on commit 6d152e0

Please sign in to comment.