@@ -16,10 +16,21 @@ use serde_device_tree::{
1616 from_raw_mut, Dtb , DtbPtr ,
1717} ;
1818
19+ const RAW_DEVICE_TREE : & ' static [ u8 ] = include_bytes ! ( "qemu-virt.dtb" ) ;
20+ const BUFFER_SIZE : usize = RAW_DEVICE_TREE . len ( ) ;
21+
22+ #[ repr( align( 4 ) ) ]
23+ struct AlignedBuffer {
24+ pub data : [ u8 ; RAW_DEVICE_TREE . len ( ) ] ,
25+ }
26+
1927fn main ( ) -> Result < ( ) , Error > {
2028 // 整个设备树二进制文件需要装载到一块可写的内存区域
21- static DEVICE_TREE : & [ u8 ] = include_bytes ! ( "qemu-virt.dtb" ) ;
22- let mut slice = DEVICE_TREE . to_vec ( ) ;
29+ let mut aligned_data: Box < AlignedBuffer > = Box :: new ( AlignedBuffer {
30+ data : [ 0 ; BUFFER_SIZE ] ,
31+ } ) ;
32+ aligned_data. data [ ..BUFFER_SIZE ] . clone_from_slice ( & RAW_DEVICE_TREE ) ;
33+ let mut slice = aligned_data. data . to_vec ( ) ;
2334 // 这一步验证了设备树首部的正确性,`DtbPtr` 类型可以安全地传递到任何地方,
2435 // 甚至跨地址空间(如果你知道偏移的话)。
2536 let ptr = DtbPtr :: from_raw ( slice. as_mut_ptr ( ) ) ?;
@@ -127,10 +138,10 @@ fn main() -> Result<(), Error> {
127138
128139 // 解析过程中,设备树的内容被修改了。
129140 // 因此若要以其他方式再次访问设备树,先将这次解析的结果释放。
130- assert_ne ! ( slice, DEVICE_TREE ) ;
141+ assert_ne ! ( slice, RAW_DEVICE_TREE ) ;
131142 }
132143 // 释放后,内存会恢复原状。
133- assert_eq ! ( slice, DEVICE_TREE ) ;
144+ assert_eq ! ( slice, RAW_DEVICE_TREE ) ;
134145
135146 Ok ( ( ) )
136147}
0 commit comments