rust: Use aligned_as macro in voxel

Use updated macro by ExpHP from
https://users.rust-lang.org/t/can-i-conveniently-compile-bytes-into-a-rust-program-with-a-specific-alignment/24049/2
This commit is contained in:
Wladimir J. van der Laan 2020-03-06 21:03:47 +00:00
parent e7de60ebbc
commit a2d4fc3445
3 changed files with 27 additions and 16 deletions

View File

@ -0,0 +1,24 @@
/*! Align an array of bytes to a specified alignment. This struct is generic in Bytes to admit unsizing coercions.
* See: https://users.rust-lang.org/t/can-i-conveniently-compile-bytes-into-a-rust-program-with-a-specific-alignment/24049
*/
#[repr(C)] // guarantee 'bytes' comes after '_align'
pub struct AlignedAs<Align, Bytes: ?Sized> {
pub _align: [Align; 0],
pub bytes: Bytes,
}
macro_rules! include_bytes_align_as {
($align_ty:ty, $path:literal) => {
{ // const block expression to encapsulate the static
use $crate::aligned_as::AlignedAs;
// this assignment is made possible by CoerceUnsized
static ALIGNED: &AlignedAs::<$align_ty, [u8]> = &AlignedAs {
_align: [],
bytes: *include_bytes!($path),
};
&ALIGNED.bytes
}
};
}

View File

@ -21,6 +21,8 @@ use k210_shared::soc::spi::SPIExt;
use k210_shared::soc::sysctl;
use riscv_rt::entry;
#[macro_use]
mod aligned_as;
mod map_data;
/** Euclidian modulus. */

View File

@ -1,18 +1,3 @@
/** Align an array of bytes to a specified alignment. This struct is generic in Bytes to admit unsizing coercions.
* See: https://users.rust-lang.org/t/can-i-conveniently-compile-bytes-into-a-rust-program-with-a-specific-alignment/24049
*/
#[repr(C)] // guarantee 'bytes' comes after '_align'
struct AlignedTo<Align, Bytes: ?Sized> {
_align: [Align; 0],
bytes: Bytes,
}
/** Dummy static used to create aligned data. */
static ALIGNED: &'static AlignedTo<u16, [u8]> = &AlignedTo {
_align: [],
bytes: *include_bytes!("../data/map15.dat"),
};
pub static WIDTH: u32 = 256;
pub static HEIGHT: u32 = 256;
pub static VOXEL_MAP: &'static [u8] = &ALIGNED.bytes;
pub static VOXEL_MAP: &'static [u8] = include_bytes_align_as!(u16, "../data/map15.dat");