Skip to content

Commit

Permalink
wip: Add PayloadValue type
Browse files Browse the repository at this point in the history
This will act as a replacement for serde_json::Value that can also hold
binary payloads.
  • Loading branch information
kelnos committed Mar 7, 2024
1 parent fc599c3 commit c243f6c
Show file tree
Hide file tree
Showing 6 changed files with 1,943 additions and 0 deletions.
2 changes: 2 additions & 0 deletions socketioxide/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,13 @@ pub use engineioxide::TransportType;
pub use errors::{AckError, AdapterError, BroadcastError, DisconnectError, SendError, SocketError};
pub use handler::extract;
pub use io::{SocketIo, SocketIoBuilder, SocketIoConfig};
pub use payload_value::{binary::Binary, PayloadValue};

mod client;
mod errors;
mod io;
mod ns;
mod payload_value;

/// Socket.IO protocol version.
/// It is accessible with the [`Socket::protocol`](socket::Socket) method or as an extractor
Expand Down
80 changes: 80 additions & 0 deletions socketioxide/src/payload_value/binary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::ops::{Deref, DerefMut};

use serde::de;

#[derive(Debug, Clone, PartialEq)]
pub struct Binary(Vec<u8>);

impl From<Vec<u8>> for Binary {
fn from(value: Vec<u8>) -> Self {
Binary(value)
}
}

impl<'a> From<&'a [u8]> for Binary {
fn from(value: &'a [u8]) -> Self {
Binary(value.to_vec())
}
}

impl From<Binary> for Vec<u8> {
fn from(value: Binary) -> Self {
value.0
}
}

impl Deref for Binary {
type Target = Vec<u8>;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl DerefMut for Binary {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

impl serde::Serialize for Binary {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_bytes(self.0.as_slice())
}
}

impl<'de> serde::Deserialize<'de> for Binary {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct BinaryVisitor;

impl<'de> de::Visitor<'de> for BinaryVisitor {
type Value = Binary;

fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("binary data")
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Binary(v.to_owned()))
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Binary(v.as_bytes().to_owned()))
}
}

deserializer.deserialize_any(BinaryVisitor)
}
}
Loading

0 comments on commit c243f6c

Please sign in to comment.