1use std::{
2 fmt::{self, Display},
3 hash::{Hash, Hasher},
4 io::{self, Cursor},
5};
6
7use azalea_buf::{AzBuf, AzBufVar, BufReadError};
8use derive_more::{Deref, DerefMut};
9
10#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
31#[derive(Clone, Copy, Debug, Default, Deref, DerefMut, Eq, PartialEq)]
32pub struct MinecraftEntityId(pub i32);
33
34impl Hash for MinecraftEntityId {
35 fn hash<H: Hasher>(&self, hasher: &mut H) {
36 hasher.write_i32(self.0);
37 }
38}
39impl nohash_hasher::IsEnabled for MinecraftEntityId {}
40
41impl AzBuf for MinecraftEntityId {
44 fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
45 i32::azalea_read(ctx, buf).map(MinecraftEntityId)
46 }
47 fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl io::Write) -> io::Result<()> {
48 i32::azalea_write(&self.0, ctx, buf)
49 }
50}
51impl AzBufVar for MinecraftEntityId {
52 fn azalea_read_var(
53 ctx: azalea_buf::Ctx,
54 buf: &mut Cursor<&[u8]>,
55 ) -> Result<Self, BufReadError> {
56 i32::azalea_read_var(ctx, buf).map(MinecraftEntityId)
57 }
58 fn azalea_write_var(&self, ctx: azalea_buf::Ctx, buf: &mut impl io::Write) -> io::Result<()> {
59 i32::azalea_write_var(&self.0, ctx, buf)
60 }
61}
62impl Display for MinecraftEntityId {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "eid({})", self.0)
65 }
66}
67impl From<i32> for MinecraftEntityId {
68 fn from(id: i32) -> Self {
69 Self(id)
70 }
71}
72impl From<u32> for MinecraftEntityId {
73 fn from(id: u32) -> Self {
74 Self(id as i32)
75 }
76}
77
78#[derive(Clone, Debug, PartialEq)]
83pub struct OptionalEntityId(pub Option<MinecraftEntityId>);
84impl AzBuf for OptionalEntityId {
85 fn azalea_read(
86 ctx: azalea_buf::Ctx,
87 buf: &mut Cursor<&[u8]>,
88 ) -> Result<Self, azalea_buf::BufReadError> {
89 let id = match i32::azalea_read_var(ctx, buf)? {
90 0 => None,
91 id => Some(MinecraftEntityId(id.wrapping_sub(1))),
92 };
93 Ok(OptionalEntityId(id))
94 }
95 fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl io::Write) -> io::Result<()> {
96 match self.0 {
97 Some(id) => id.0.wrapping_add(1).azalea_write_var(ctx, buf),
98 None => 0u32.azalea_write_var(ctx, buf),
99 }
100 }
101}