ghast-protocol 0.5.3

Minecraft Java Edition network protocol for the ghast client library: generated per-version packets, framing, compression, encryption, NBT
Documentation
//! The relative entity move of protocol 777+ (`rel_entity_move`, `entity_move_look`).
//!
//! Wire format: a VarInt of properties — bit 0 is `on_ground`, the bits above it (read as
//! an unsigned shift) are the step count. A step count of 0 is a linear move: three `i16`
//! deltas in 1/4096 block follow. Otherwise that many steps follow, each a VarInt tick
//! offset and three `i16` deltas.
//!
//! A step costs at least 7 bytes, so a step count above `remaining / 7` is rejected before
//! anything is allocated (vanilla rejects the same counts).

use bytes::BytesMut;

use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, McWrite, Reader};
use crate::error::DecodeError;

/// One step of a stepped move.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct MoveStep {
    /// Tick offset of the step.
    pub ticks: i32,
    /// x, y, z deltas in 1/4096 block.
    pub delta: [i16; 3],
}

/// The position change of a relative entity move.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MovePath {
    /// One delta (x, y, z in 1/4096 block), applied over the usual interpolation.
    Linear([i16; 3]),
    /// Several deltas with tick offsets. Never empty on the wire: an empty list would
    /// encode as step count 0, which reads back as [`MovePath::Linear`].
    Stepped(Vec<MoveStep>),
}

impl Default for MovePath {
    fn default() -> Self {
        MovePath::Linear([0; 3])
    }
}

/// `on_ground` and the position change of a relative entity move (protocol 777+).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct EntityMoveDelta {
    /// Whether the entity is on the ground.
    pub on_ground: bool,
    /// The position change.
    pub path: MovePath,
}

impl EntityMoveDelta {
    /// Reads the wire form.
    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 })
    }

    /// Writes the wire form.
    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() {
        // 10 steps announced, 7 bytes present.
        let b = bytes::Bytes::from(vec![20, 0, 0, 0, 0, 0, 0, 0]);
        assert!(decode_exact::<EntityMoveDelta>(&b).is_err());
    }
}