nimble_sample_step/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/nimble-rust/nimble
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */
use flood_rs::prelude::*;
use flood_rs::BufferDeserializer;
use std::fmt::Display;
use std::io;

#[derive(Debug)]
pub struct SampleState {
    pub buf: Vec<u8>,
}

impl BufferDeserializer for SampleState {
    fn deserialize(buf: &[u8]) -> io::Result<(Self, usize)>
    where
        Self: Sized,
    {
        Ok((Self { buf: buf.into() }, buf.len()))
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SampleStep {
    MoveLeft(i16),
    MoveRight(i16),
    Jump,
    Nothing,
}

impl Display for SampleStep {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MoveLeft(_) => write!(f, "Move left"),
            Self::MoveRight(_) => write!(f, "Move right"),
            Self::Jump => write!(f, "Jump"),
            Self::Nothing => write!(f, "No Game-pad Input"),
        }
    }
}

impl Serialize for SampleStep {
    fn serialize(&self, stream: &mut impl WriteOctetStream) -> io::Result<()> {
        match self {
            Self::Nothing => stream.write_u8(0x00),
            Self::MoveLeft(amount) => {
                stream.write_u8(0x01)?;
                stream.write_i16(*amount)
            }
            Self::MoveRight(amount) => {
                stream.write_u8(0x02)?;
                stream.write_i16(*amount)
            }
            Self::Jump => stream.write_u8(0x03),
        }
    }
}

impl Deserialize for SampleStep {
    fn deserialize(stream: &mut impl ReadOctetStream) -> io::Result<Self> {
        let octet = stream.read_u8()?;
        Ok(match octet {
            0x00 => Self::Nothing,
            0x01 => Self::MoveLeft(stream.read_i16()?),
            0x02 => Self::MoveRight(stream.read_i16()?),
            0x03 => Self::Jump,
            _ => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("Unknown sample step enum {octet:X}"),
            ))?,
        })
    }
}