Skip to content

Commit a5c203f

Browse files
committed
Add Display and FromStr to BlockPos for HashMap Key Serializing/Deserializing
1 parent 6194c52 commit a5c203f

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

azalea-core/src/position.rs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,18 @@
33
//! The most common ones are [`Vec3`] and [`BlockPos`], which are usually used
44
//! for entity positions and block positions, respectively.
55
6+
use crate::resource_location::ResourceLocation;
67
use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
8+
#[cfg(feature = "serde")]
9+
use serde::{Deserialize, Serialize};
10+
use std::fmt::Display;
11+
use std::str::FromStr;
712
use std::{
813
fmt,
914
hash::Hash,
1015
io::{Cursor, Write},
1116
ops::{Add, AddAssign, Mul, Rem, Sub},
1217
};
13-
#[cfg(feature = "serde")]
14-
use serde::{Deserialize, Serialize};
15-
use crate::resource_location::ResourceLocation;
1618

1719
macro_rules! vec3_impl {
1820
($name:ident, $type:ty) => {
@@ -270,6 +272,33 @@ impl BlockPos {
270272
}
271273
}
272274

275+
impl Display for BlockPos {
276+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277+
write!(f, "({}, {}, {})", self.x, self.y, self.z)
278+
}
279+
}
280+
281+
impl FromStr for BlockPos {
282+
type Err = &'static str;
283+
284+
fn from_str(s: &str) -> Result<Self, Self::Err> {
285+
let pos = s
286+
.trim_matches(|c| c == '(' || c == ')')
287+
.split(',')
288+
.collect::<Vec<_>>();
289+
290+
if pos.len() != 3 {
291+
return Err("Must be a length of 3");
292+
}
293+
294+
Ok(BlockPos {
295+
x: pos[0].parse()?,
296+
y: pos[1].parse()?,
297+
z: pos[2].parse()?,
298+
})
299+
}
300+
}
301+
273302
/// Chunk coordinates are used to represent where a chunk is in the world. You
274303
/// can convert the x and z to block coordinates by multiplying them by 16.
275304
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]

0 commit comments

Comments
 (0)