valence/src/block.rs

72 lines
1.7 KiB
Rust
Raw Normal View History

#![allow(clippy::all, missing_docs)]
2022-04-17 17:04:39 -07:00
2022-04-19 23:41:15 -07:00
use std::fmt;
2022-04-29 00:48:41 -07:00
use std::io::{Read, Write};
use anyhow::Context;
pub use crate::block_pos::BlockPos;
use crate::protocol::{Decode, Encode, VarInt};
2022-04-19 23:41:15 -07:00
2022-04-17 17:04:39 -07:00
include!(concat!(env!("OUT_DIR"), "/block.rs"));
2022-04-19 23:41:15 -07:00
impl fmt::Debug for BlockState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = self.to_kind();
2022-04-19 23:41:15 -07:00
write!(f, "{}", kind.to_str())?;
2022-04-19 23:41:15 -07:00
let props = kind.props();
2022-04-19 23:41:15 -07:00
if !props.is_empty() {
let mut list = f.debug_list();
for &p in kind.props() {
2022-04-19 23:41:15 -07:00
struct KeyVal<'a>(&'a str, &'a str);
impl<'a> fmt::Debug for KeyVal<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}={}", self.0, self.1)
}
}
list.entry(&KeyVal(p.to_str(), self.get(p).unwrap().to_str()));
}
list.finish()
} else {
Ok(())
}
}
}
2022-04-29 00:48:41 -07:00
impl Encode for BlockState {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
VarInt(self.0 as i32).encode(w)
}
}
impl Decode for BlockState {
fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
let id = VarInt::decode(r)?.0;
let errmsg = "invalid block state ID";
BlockState::from_raw(id.try_into().context(errmsg)?).context(errmsg)
}
}
2022-04-17 17:04:39 -07:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_set_consistency() {
for kind in BlockKind::ALL {
let block = kind.to_state();
2022-04-17 17:04:39 -07:00
for &prop in kind.props() {
2022-04-17 17:04:39 -07:00
let new_block = block.set(prop, block.get(prop).unwrap());
assert_eq!(new_block, block);
}
}
}
}