rust_voice_chat_room/protocol/src/protocol.rs

89 lines
2.1 KiB
Rust
Raw Normal View History

use bincode::{Decode, Encode};
use crate::Error;
const SIGNAL_DATA_LENGTH: usize = 4;
const NETWORK_DATA_LENGTH: usize = 6;
type SignalBufferReturn = [u8; SIGNAL_DATA_LENGTH];
type NetworkBufferReturn = [u8; NETWORK_DATA_LENGTH];
static BINCODE_CONFIG: bincode::config::Configuration<bincode::config::BigEndian> =
bincode::config::standard().with_big_endian();
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
pub struct Speaker {
id: u8,
}
impl Speaker {
pub fn new(id: u8) -> Self {
Self { id }
}
pub fn get_id(&self) -> u8 {
self.id
}
}
#[derive(Debug, Encode, Decode)]
pub enum SignalType {
AudioDatum,
SpeakerLeft,
}
#[derive(Debug, Encode, Decode)]
pub struct Signal {
signal_type: SignalType,
speaker: Speaker,
data: [u8; SIGNAL_DATA_LENGTH],
}
impl Signal {
pub fn unpack(data: NetworkBufferReturn) -> Result<Self, Error> {
Ok(bincode::decode_from_slice::<Self, _>(&data, BINCODE_CONFIG)
.map_err(|inner| Error::Deserialization(inner.to_string()))?
.0)
}
fn pack(self) -> NetworkBufferReturn {
let encoded = serialize(self);
assert_eq!(encoded.len(), NETWORK_DATA_LENGTH);
let mut buffer = NetworkBufferReturn::default();
buffer.copy_from_slice(&encoded);
buffer
}
pub fn pack_audio_datum(speaker: Speaker, audio_datum: f32) -> NetworkBufferReturn {
let signal = Self {
signal_type: SignalType::AudioDatum,
speaker,
data: audio_datum.to_be_bytes(),
};
Self::pack(signal)
}
pub fn pack_speaker_left(speaker: Speaker) -> NetworkBufferReturn {
let signal = Self {
signal_type: SignalType::SpeakerLeft,
speaker,
data: SignalBufferReturn::default(),
};
signal.pack()
}
}
fn serialize<E>(value: E) -> Vec<u8>
where
E: bincode::enc::Encode,
{
bincode::encode_to_vec(value, BINCODE_CONFIG)
.map_err(|inner| Error::Serialization(inner.to_string()))
.unwrap()
}