nimble_sample_step/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/nimble-rust/nimble
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use flood_rs::prelude::*;
6use flood_rs::BufferDeserializer;
7use std::fmt::Display;
8use std::io;
9
10#[derive(Debug)]
11pub struct SampleState {
12    pub buf: Vec<u8>,
13}
14
15impl BufferDeserializer for SampleState {
16    fn deserialize(buf: &[u8]) -> io::Result<(Self, usize)>
17    where
18        Self: Sized,
19    {
20        Ok((Self { buf: buf.into() }, buf.len()))
21    }
22}
23
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub enum SampleStep {
26    MoveLeft(i16),
27    MoveRight(i16),
28    Jump,
29    Nothing,
30}
31
32impl Display for SampleStep {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        match self {
35            Self::MoveLeft(_) => write!(f, "Move left"),
36            Self::MoveRight(_) => write!(f, "Move right"),
37            Self::Jump => write!(f, "Jump"),
38            Self::Nothing => write!(f, "No Game-pad Input"),
39        }
40    }
41}
42
43impl Serialize for SampleStep {
44    fn serialize(&self, stream: &mut impl WriteOctetStream) -> io::Result<()> {
45        match self {
46            Self::Nothing => stream.write_u8(0x00),
47            Self::MoveLeft(amount) => {
48                stream.write_u8(0x01)?;
49                stream.write_i16(*amount)
50            }
51            Self::MoveRight(amount) => {
52                stream.write_u8(0x02)?;
53                stream.write_i16(*amount)
54            }
55            Self::Jump => stream.write_u8(0x03),
56        }
57    }
58}
59
60impl Deserialize for SampleStep {
61    fn deserialize(stream: &mut impl ReadOctetStream) -> io::Result<Self> {
62        let octet = stream.read_u8()?;
63        Ok(match octet {
64            0x00 => Self::Nothing,
65            0x01 => Self::MoveLeft(stream.read_i16()?),
66            0x02 => Self::MoveRight(stream.read_i16()?),
67            0x03 => Self::Jump,
68            _ => Err(io::Error::new(
69                io::ErrorKind::InvalidInput,
70                format!("Unknown sample step enum {octet:X}"),
71            ))?,
72        })
73    }
74}