pub trait Serializer: Send + Sync {
type Error: Error + Send + Sync + 'static;
// Required methods
fn content_type(&self) -> &ContentType;
fn serialize<T: Message>(&self, body: &T) -> Result<Bytes, Self::Error>;
fn deserialize<T: Message>(&self, bytes: &[u8]) -> Result<T, Self::Error>;
}Expand description
Converts a typed Message body to and from bytes. Lives in reliar-core: it touches
neither storage nor transport (ADR 0010).
Stateless and cheap; implementations must never be placed behind a dyn Serializer on the
enqueue path — it runs once per message and static dispatch keeps it that cheap (ADR 0001).
use bytes::Bytes;
use reliar_core::{ContentType, Message, Serializer};
/// A minimal serializer wrapping a fixed encoder, for hosts that already have one.
struct Fixed(Bytes);
impl Serializer for Fixed {
type Error = std::convert::Infallible;
fn content_type(&self) -> &ContentType {
&ContentType::JSON
}
fn serialize<T: Message>(&self, _body: &T) -> Result<Bytes, Self::Error> {
Ok(self.0.clone())
}
fn deserialize<T: Message>(&self, _bytes: &[u8]) -> Result<T, Self::Error> {
unimplemented!("example encoder, not a real round trip")
}
}
let serializer = Fixed(Bytes::from_static(b"{}"));
assert_eq!(serializer.content_type().as_str(), "application/json");Required Associated Types§
Required Methods§
Sourcefn content_type(&self) -> &ContentType
fn content_type(&self) -> &ContentType
The content type this serializer produces. Populates both
DeliveryMetadata::content_type and a
provider’s content_type column — one value, chosen by the serializer, never by the
call site.
let serializer = Fixed(Bytes::from_static(b"{}"));
assert_eq!(serializer.content_type().as_str(), "application/json");Sourcefn serialize<T: Message>(&self, body: &T) -> Result<Bytes, Self::Error>
fn serialize<T: Message>(&self, body: &T) -> Result<Bytes, Self::Error>
Serializes a message body to bytes.
§Errors
Returns Self::Error if body cannot be represented in this serializer’s format.
let serializer = Fixed(Bytes::from_static(b"{}"));
let bytes = serializer.serialize(&Ping)?;
assert_eq!(bytes.as_ref(), b"{}");Sourcefn deserialize<T: Message>(&self, bytes: &[u8]) -> Result<T, Self::Error>
fn deserialize<T: Message>(&self, bytes: &[u8]) -> Result<T, Self::Error>
Deserializes bytes back into a message body.
§Errors
Returns Self::Error if bytes is not a valid encoding of T in this serializer’s
format.
use reliar_core::{JsonSerializer, Message, Serializer};
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
struct Ping;
impl Message for Ping {
const TYPE: &'static str = "ping";
const VERSION: u16 = 1;
}
let body: Ping = JsonSerializer.deserialize(b"null")?;
assert_eq!(body, Ping);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
Source§impl Serializer for JsonSerializer
Available on crate feature json only.
impl Serializer for JsonSerializer
json only.