valence/src/block.rs

85 lines
2 KiB
Rust
Raw Normal View History

2022-07-14 23:18:20 -07:00
//! Blocks and related types.
#![allow(clippy::all, missing_docs)]
2022-04-17 17:04:39 -07:00
2022-07-06 18:46:03 -07:00
use std::fmt::{self, Display};
2022-04-29 00:48:41 -07:00
use std::io::{Read, Write};
2022-08-06 16:46:07 -07:00
use std::iter::FusedIterator;
2022-04-29 00:48:41 -07:00
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 {
2022-07-06 18:46:03 -07:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_block_state(*self, f)
}
}
impl Display for BlockState {
2022-07-11 05:08:02 -07:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2022-07-06 18:46:03 -07:00
fmt_block_state(*self, f)
}
}
2022-04-19 23:41:15 -07:00
2022-07-06 18:46:03 -07:00
fn fmt_block_state(bs: BlockState, f: &mut fmt::Formatter) -> fmt::Result {
let kind = bs.to_kind();
2022-04-19 23:41:15 -07:00
2022-07-06 18:46:03 -07:00
write!(f, "{}", kind.to_str())?;
2022-04-19 23:41:15 -07:00
2022-07-06 18:46:03 -07:00
let props = kind.props();
2022-04-19 23:41:15 -07:00
2022-07-06 18:46:03 -07:00
if !props.is_empty() {
let mut list = f.debug_list();
for &p in kind.props() {
struct KeyVal<'a>(&'a str, &'a str);
2022-04-19 23:41:15 -07:00
2022-07-06 18:46:03 -07:00
impl<'a> fmt::Debug for KeyVal<'a> {
2022-07-11 05:08:02 -07:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2022-07-06 18:46:03 -07:00
write!(f, "{}={}", self.0, self.1)
}
2022-04-19 23:41:15 -07:00
}
2022-07-06 18:46:03 -07:00
list.entry(&KeyVal(p.to_str(), bs.get(p).unwrap().to_str()));
2022-04-19 23:41:15 -07:00
}
2022-07-06 18:46:03 -07:00
list.finish()
} else {
Ok(())
2022-04-19 23:41:15 -07:00
}
}
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);
}
}
}
}