Add Serialize/Deserialize impls to various types

We want to be able to store this data to disk temporarily.
This commit is contained in:
Matthias Schiffer 2023-02-25 23:23:00 +01:00
parent 2d0f2fb865
commit 551056803d
Signed by: neocturne
GPG key ID: 16EF3F64CB201D9C
3 changed files with 27 additions and 6 deletions

View file

@ -6,6 +6,7 @@ use std::collections::HashMap;
use enumflags2::{bitflags, BitFlags};
pub use legacy_block_types::LEGACY_BLOCK_TYPES;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
#[bitflags]
#[repr(u8)]
@ -19,11 +20,29 @@ pub enum BlockFlag {
Water,
}
#[derive(Debug, Clone, Copy)]
fn serialize_block_flags<S>(flags: &BitFlags<BlockFlag>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
flags.bits().serialize(serializer)
}
fn deserialize_block_flags<'de, D>(deserializer: D) -> Result<BitFlags<BlockFlag>, D::Error>
where
D: Deserializer<'de>,
{
let bits = u8::deserialize(deserializer)?;
BitFlags::<BlockFlag>::from_bits(bits).map_err(de::Error::custom)
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct BlockColor(pub u8, pub u8, pub u8);
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct BlockType {
#[serde(
serialize_with = "serialize_block_flags",
deserialize_with = "deserialize_block_flags"
)]
pub flags: BitFlags<BlockFlag>,
pub color: BlockColor,
}

View file

@ -5,6 +5,7 @@ use std::{
};
use itertools::iproduct;
use serde::{Deserialize, Serialize};
macro_rules! coord_impl {
($t:ident, $max:expr) => {
@ -55,7 +56,7 @@ impl Debug for LayerBlockCoords {
/// Generic array for data stored per block of a chunk layer
///
/// Includes various convenient iteration functions.
#[derive(Debug, Clone, Copy, Default)]
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct LayerBlockArray<T>(pub [[T; BLOCKS_PER_CHUNK]; BLOCKS_PER_CHUNK]);
impl<T> LayerBlockArray<T> {
@ -146,7 +147,7 @@ impl Debug for ChunkCoords {
/// Generic array for data stored per chunk of a region
///
/// Includes various convenient iteration functions.
#[derive(Debug, Clone, Copy, Default)]
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct ChunkArray<T>(pub [[T; CHUNKS_PER_REGION]; CHUNKS_PER_REGION]);
impl<T> ChunkArray<T> {

View file

@ -1,5 +1,6 @@
use anyhow::{Context, Result};
use itertools::iproduct;
use serde::{Deserialize, Serialize};
use super::chunk::Chunk;
use crate::{
@ -7,7 +8,7 @@ use crate::{
types::*,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlockHeight(i32);
impl BlockHeight {
@ -25,7 +26,7 @@ impl BlockHeight {
}
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct BlockInfo {
block_type: BlockType,
y: BlockHeight,