azalea_block/
block_state.rs

1use std::{
2    fmt::{self, Debug},
3    io::{self, Cursor, Write},
4};
5
6use azalea_buf::{AzaleaRead, AzaleaReadVar, AzaleaWrite, AzaleaWriteVar, BufReadError};
7
8use crate::BlockTrait;
9
10/// The type that's used internally to represent a block state ID.
11///
12/// This should be either `u16` or `u32`. If you choose to modify it, you must
13/// also change it in `azalea-block-macros/src/lib.rs`.
14///
15/// This does not affect protocol serialization, it just allows you to make the
16/// internal type smaller if you want.
17pub type BlockStateIntegerRepr = u16;
18
19/// A representation of a state a block can be in.
20///
21/// For example, a stone block only has one state but each possible stair
22/// rotation is a different state.
23///
24/// Note that this type is internally either a `u16` or `u32`, depending on
25/// [`BlockStateIntegerRepr`].
26#[derive(Copy, Clone, PartialEq, Eq, Default, Hash)]
27pub struct BlockState {
28    /// The protocol ID for the block state. IDs may change every
29    /// version, so you shouldn't hard-code them or store them in databases.
30    id: BlockStateIntegerRepr,
31}
32
33impl BlockState {
34    /// A shortcut for getting the air block state, since it always has an ID of
35    /// 0.
36    pub const AIR: BlockState = BlockState { id: 0 };
37
38    /// Create a new BlockState and panic if the block is not a valid state.
39    ///
40    /// You should probably use [`BlockState::try_from`] instead.
41    #[inline]
42    pub(crate) const fn new_const(id: BlockStateIntegerRepr) -> Self {
43        assert!(Self::is_valid_state(id));
44        Self { id }
45    }
46
47    /// Whether the block state is possible to exist in vanilla Minecraft.
48    ///
49    /// It's equivalent to checking that the state ID is not greater than
50    /// [`Self::MAX_STATE`].
51    #[inline]
52    pub const fn is_valid_state(state_id: BlockStateIntegerRepr) -> bool {
53        state_id <= Self::MAX_STATE
54    }
55
56    /// Returns true if the block is air. This only checks for normal air, not
57    /// other types like cave air.
58    #[inline]
59    pub fn is_air(&self) -> bool {
60        self == &Self::AIR
61    }
62
63    /// Returns the protocol ID for the block state. IDs may change every
64    /// version, so you shouldn't hard-code them or store them in databases.
65    #[inline]
66    pub const fn id(&self) -> BlockStateIntegerRepr {
67        self.id
68    }
69}
70
71impl TryFrom<u32> for BlockState {
72    type Error = ();
73
74    /// Safely converts a u32 state id to a block state.
75    fn try_from(state_id: u32) -> Result<Self, Self::Error> {
76        let state_id = state_id as BlockStateIntegerRepr;
77        if Self::is_valid_state(state_id) {
78            Ok(BlockState { id: state_id })
79        } else {
80            Err(())
81        }
82    }
83}
84impl TryFrom<u16> for BlockState {
85    type Error = ();
86
87    /// Safely converts a u16 state id to a block state.
88    fn try_from(state_id: u16) -> Result<Self, Self::Error> {
89        let state_id = state_id as BlockStateIntegerRepr;
90        if Self::is_valid_state(state_id) {
91            Ok(BlockState { id: state_id })
92        } else {
93            Err(())
94        }
95    }
96}
97impl From<BlockState> for u32 {
98    /// See [`BlockState::id`].
99    fn from(value: BlockState) -> Self {
100        value.id as u32
101    }
102}
103
104impl AzaleaRead for BlockState {
105    fn azalea_read(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
106        let state_id = u32::azalea_read_var(buf)?;
107        Self::try_from(state_id).map_err(|_| BufReadError::UnexpectedEnumVariant {
108            id: state_id as i32,
109        })
110    }
111}
112impl AzaleaWrite for BlockState {
113    fn azalea_write(&self, buf: &mut impl Write) -> io::Result<()> {
114        u32::azalea_write_var(&(self.id as u32), buf)
115    }
116}
117
118impl Debug for BlockState {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(
121            f,
122            "BlockState(id: {}, {:?})",
123            self.id,
124            Box::<dyn BlockTrait>::from(*self)
125        )
126    }
127}
128
129impl From<BlockState> for azalea_registry::Block {
130    fn from(value: BlockState) -> Self {
131        Box::<dyn BlockTrait>::from(value).as_registry_block()
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn test_from_u32() {
141        assert_eq!(
142            BlockState::try_from(0 as BlockStateIntegerRepr).unwrap(),
143            BlockState::AIR
144        );
145
146        assert!(BlockState::try_from(BlockState::MAX_STATE).is_ok());
147        assert!(BlockState::try_from(BlockState::MAX_STATE + 1).is_err());
148    }
149
150    #[test]
151    fn test_from_blockstate() {
152        let block: Box<dyn BlockTrait> = Box::<dyn BlockTrait>::from(BlockState::AIR);
153        assert_eq!(block.id(), "air");
154
155        let block: Box<dyn BlockTrait> =
156            Box::<dyn BlockTrait>::from(BlockState::from(azalea_registry::Block::FloweringAzalea));
157        assert_eq!(block.id(), "flowering_azalea");
158    }
159
160    #[test]
161    fn test_debug_blockstate() {
162        let formatted = format!(
163            "{:?}",
164            BlockState::from(azalea_registry::Block::FloweringAzalea)
165        );
166        assert!(formatted.ends_with(", FloweringAzalea)"), "{}", formatted);
167
168        let formatted = format!(
169            "{:?}",
170            BlockState::from(azalea_registry::Block::BigDripleafStem)
171        );
172        assert!(
173            formatted.ends_with(", BigDripleafStem { facing: North, waterlogged: false })"),
174            "{}",
175            formatted
176        );
177    }
178}