forked from Totodore/socketioxide
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This will act as a replacement for serde_json::Value that can also hold binary payloads.
- Loading branch information
Showing
6 changed files
with
1,943 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
Oops, something went wrong.