use super::traits::Serializer;
use crate::common::error::{FlareError, Result};
use crate::common::protobuf_decoder::{ProtobufDecoder, safe_protobuf_decode};
use crate::common::protocol::{Frame, SerializationFormat};
pub struct ProtobufSerializer;
impl Serializer for ProtobufSerializer {
fn serialize(&self, frame: &Frame) -> Result<Vec<u8>> {
let mut buf = Vec::new();
prost::Message::encode(frame, &mut buf)
.map_err(|e| FlareError::encoding_error(format!("Protobuf encode error: {}", e)))?;
Ok(buf)
}
fn deserialize(&self, data: &[u8]) -> Result<Frame> {
safe_protobuf_decode::<Frame>(data)
.map_err(|e| FlareError::deserialization_error(format!("Protobuf decode error: {}", e)))
}
fn format(&self) -> SerializationFormat {
SerializationFormat::Protobuf
}
fn name(&self) -> &'static str {
"protobuf"
}
fn can_detect(&self, data: &[u8]) -> bool {
!data.is_empty()
}
}
pub struct FramedProtobufSerializer {
_decoder: Option<ProtobufDecoder<Frame>>,
}
impl FramedProtobufSerializer {
pub fn new() -> Self {
Self { _decoder: None }
}
#[allow(dead_code)]
fn get_or_create_decoder(&mut self) -> &mut ProtobufDecoder<Frame> {
if self._decoder.is_none() {
self._decoder = Some(ProtobufDecoder::new());
}
self._decoder.as_mut().unwrap()
}
}
impl Default for FramedProtobufSerializer {
fn default() -> Self {
Self::new()
}
}
impl Serializer for FramedProtobufSerializer {
fn serialize(&self, frame: &Frame) -> Result<Vec<u8>> {
let mut buf = Vec::new();
prost::Message::encode(frame, &mut buf).map_err(|e| {
FlareError::encoding_error(format!("Framed Protobuf encode error: {}", e))
})?;
let mut prefixed_buf = Vec::new();
prost::encoding::encode_varint(buf.len() as u64, &mut prefixed_buf);
prefixed_buf.extend_from_slice(&buf);
Ok(prefixed_buf)
}
fn deserialize(&self, data: &[u8]) -> Result<Frame> {
safe_protobuf_decode::<Frame>(data).map_err(|e| {
FlareError::deserialization_error(format!("Framed Protobuf decode error: {}", e))
})
}
fn format(&self) -> SerializationFormat {
SerializationFormat::Protobuf
}
fn name(&self) -> &'static str {
"framed_protobuf"
}
fn can_detect(&self, data: &[u8]) -> bool {
!data.is_empty()
}
}
pub struct JsonSerializer;
impl Serializer for JsonSerializer {
fn serialize(&self, frame: &Frame) -> Result<Vec<u8>> {
serde_json::to_vec(frame)
.map_err(|e| FlareError::serialization_error(format!("JSON encode error: {}", e)))
}
fn deserialize(&self, data: &[u8]) -> Result<Frame> {
serde_json::from_slice(data)
.map_err(|e| FlareError::deserialization_error(format!("JSON decode error: {}", e)))
}
fn format(&self) -> SerializationFormat {
SerializationFormat::Json
}
fn name(&self) -> &'static str {
"json"
}
fn can_detect(&self, data: &[u8]) -> bool {
if data.is_empty() {
return false;
}
let first = data[0];
first == b'{' || first == b'['
}
}