Skip to main content

gled_protocol/
bytes.rs

1//! Bytes that MessagePack sends as one binary blob instead of a list of
2//! numbers, shared so a frame is not copied for every client.
3
4use std::{fmt, sync::Arc};
5
6use serde::{
7    Deserialize, Deserializer, Serialize, Serializer,
8    de::{self, SeqAccess, Visitor},
9};
10
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct SharedBytes(pub Arc<Vec<u8>>);
13
14impl Serialize for SharedBytes {
15    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
16        serializer.serialize_bytes(&self.0)
17    }
18}
19
20impl<'de> Deserialize<'de> for SharedBytes {
21    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
22        struct BytesVisitor;
23
24        impl<'de> Visitor<'de> for BytesVisitor {
25            type Value = Vec<u8>;
26
27            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
28                formatter.write_str("bytes")
29            }
30
31            fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Vec<u8>, E> {
32                Ok(bytes.to_vec())
33            }
34
35            fn visit_byte_buf<E: de::Error>(self, bytes: Vec<u8>) -> Result<Vec<u8>, E> {
36                Ok(bytes)
37            }
38
39            // Formats without a byte type, such as JSON, send a list.
40            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
41                let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0));
42                while let Some(byte) = seq.next_element()? {
43                    bytes.push(byte);
44                }
45                Ok(bytes)
46            }
47        }
48
49        deserializer
50            .deserialize_byte_buf(BytesVisitor)
51            .map(|bytes| Self(Arc::new(bytes)))
52    }
53}