aboutsummaryrefslogtreecommitdiff
path: root/azalea-block/src/lib.rs
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2022-06-17 23:10:54 +0000
committerGitHub <noreply@github.com>2022-06-17 23:10:54 +0000
commitf414aa4d37e0c6a7adf55b772fa93714be6e9c9c (patch)
tree8cfb7d33114b9537b50477d5d6980995eec6cc5c /azalea-block/src/lib.rs
parent56f98c1b243d1ba8906ac73a2f2d8eec5646183e (diff)
parent0a945e73ec43b3b0389e004e138c83f41cddc532 (diff)
downloadazalea-drasl-f414aa4d37e0c6a7adf55b772fa93714be6e9c9c.tar.xz
Merge pull request #9 from mat-1/azalea-block
azalea-block
Diffstat (limited to 'azalea-block/src/lib.rs')
-rw-r--r--azalea-block/src/lib.rs47
1 files changed, 47 insertions, 0 deletions
diff --git a/azalea-block/src/lib.rs b/azalea-block/src/lib.rs
new file mode 100644
index 00000000..a6de1e92
--- /dev/null
+++ b/azalea-block/src/lib.rs
@@ -0,0 +1,47 @@
+mod behavior;
+mod blocks;
+
+pub use behavior::BlockBehavior;
+pub use blocks::*;
+
+use std::mem;
+
+impl BlockState {
+ /// Transmutes a u32 to a block state. UB if the value is not a valid block
+ /// state.
+ #[inline]
+ pub unsafe fn from_u32_unsafe(state_id: u32) -> Self {
+ mem::transmute::<u32, BlockState>(state_id)
+ }
+
+ #[inline]
+ pub fn is_valid_state(state_id: u32) -> bool {
+ state_id <= Self::max_state()
+ }
+}
+
+impl TryFrom<u32> for BlockState {
+ type Error = ();
+
+ /// Safely converts a state id to a block state.
+ fn try_from(state_id: u32) -> Result<Self, Self::Error> {
+ if Self::is_valid_state(state_id) {
+ Ok(unsafe { Self::from_u32_unsafe(state_id) })
+ } else {
+ Err(())
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_from_u32() {
+ assert_eq!(BlockState::try_from(0).unwrap(), BlockState::Air);
+
+ assert!(BlockState::try_from(BlockState::max_state()).is_ok());
+ assert!(BlockState::try_from(BlockState::max_state() + 1).is_err());
+ }
+}