use bytes::BytesMut;
use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, McWrite, Reader};
use crate::error::DecodeError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct MoveStep {
pub ticks: i32,
pub delta: [i16; 3],
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MovePath {
Linear([i16; 3]),
Stepped(Vec<MoveStep>),
}
impl Default for MovePath {
fn default() -> Self {
MovePath::Linear([0; 3])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct EntityMoveDelta {
pub on_ground: bool,
pub path: MovePath,
}
impl EntityMoveDelta {
pub fn read(r: &mut Reader<'_>) -> DecodeResult<Self> {
let properties = r.read_varint()? as u32;
let on_ground = properties & 1 != 0;
let steps = (properties >> 1) as usize;
let read_delta = |r: &mut Reader<'_>| -> DecodeResult<[i16; 3]> {
Ok([r.read_i16()?, r.read_i16()?, r.read_i16()?])
};
let path = if steps == 0 {
MovePath::Linear(read_delta(r)?)
} else {
if steps > r.remaining() / 7 {
return Err(DecodeError::Invalid("move delta: more steps than bytes"));
}
let mut v = Vec::with_capacity(steps);
for _ in 0..steps {
let ticks = r.read_varint()?;
v.push(MoveStep {
ticks,
delta: read_delta(r)?,
});
}
MovePath::Stepped(v)
};
Ok(EntityMoveDelta { on_ground, path })
}
pub fn write(&self, w: &mut BytesMut) {
let steps = match &self.path {
MovePath::Linear(_) => 0,
MovePath::Stepped(v) => v.len() as u32,
};
w.put_varint((u32::from(self.on_ground) | steps << 1) as i32);
let put = |w: &mut BytesMut, d: &[i16; 3]| {
for c in d {
bytes::BufMut::put_i16(w, *c);
}
};
match &self.path {
MovePath::Linear(d) => put(w, d),
MovePath::Stepped(v) => {
for s in v {
w.put_varint(s.ticks);
put(w, &s.delta);
}
}
}
}
}
impl Decode for EntityMoveDelta {
#[inline]
fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
Self::read(r)
}
}
impl Encode for EntityMoveDelta {
#[inline]
fn encode(&self, w: &mut BytesMut) -> EncodeResult {
self.write(w);
Ok(())
}
}
#[cfg(feature = "testgen")]
impl crate::testgen::Generate for EntityMoveDelta {
fn generate(g: &mut crate::testgen::Gen) -> Self {
let delta = |g: &mut crate::testgen::Gen| [g.u64() as i16, g.u64() as i16, g.u64() as i16];
let on_ground = g.bool();
let path = if g.chance(60) {
MovePath::Linear(delta(g))
} else {
let n = 1 + g.below(4) as usize;
MovePath::Stepped(
(0..n)
.map(|_| MoveStep {
ticks: g.int_in(0, i64::from(i32::MAX), &[0, 1, 2, 127, 128]) as i32,
delta: delta(g),
})
.collect(),
)
};
EntityMoveDelta { on_ground, path }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codec::decode_exact;
fn rt(v: &EntityMoveDelta) -> Vec<u8> {
let mut w = BytesMut::new();
v.write(&mut w);
assert_eq!(
&decode_exact::<EntityMoveDelta>(&w.clone().freeze()).unwrap(),
v
);
w.to_vec()
}
#[test]
fn linear_and_stepped() {
let lin = EntityMoveDelta {
on_ground: true,
path: MovePath::Linear([1, -1, 256]),
};
assert_eq!(rt(&lin), vec![1, 0, 1, 0xff, 0xff, 1, 0]);
let st = EntityMoveDelta {
on_ground: false,
path: MovePath::Stepped(vec![
MoveStep {
ticks: 0,
delta: [0, 0, 1],
},
MoveStep {
ticks: 3,
delta: [2, 0, 0],
},
]),
};
assert_eq!(rt(&st), vec![4, 0, 0, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0]);
}
#[test]
fn step_count_is_bounded_by_the_input() {
let b = bytes::Bytes::from(vec![20, 0, 0, 0, 0, 0, 0, 0]);
assert!(decode_exact::<EntityMoveDelta>(&b).is_err());
}
}