Skip to main content

useceleris_client/
payload.rs

1//! Payloads are opaque bytes on the wire. These helpers cover text; every
2//! other format, JSON included, goes through [`PayloadCodec`], which keeps
3//! serializer libraries out of this crate (HELP-01).
4
5use std::fmt;
6use std::sync::Arc;
7
8use crate::errors::CelerisError;
9
10/// Encodes text as UTF-8.
11pub fn text_payload(text: &str) -> Vec<u8> {
12    text.as_bytes().to_vec()
13} // end fn text_payload
14
15/// Decodes a UTF-8 payload. It fails with [`CelerisError::Configuration`] when
16/// the payload is not valid UTF-8.
17pub fn read_text(payload: &[u8]) -> Result<String, CelerisError> {
18    match std::str::from_utf8(payload) {
19        Ok(text) => Ok(text.to_owned()),
20        Err(_) => Err(CelerisError::Configuration(
21            "Payload is not valid UTF-8, so it cannot be read as text.".to_owned(),
22        )),
23    }
24} // end fn read_text
25
26type Encode<Value, Failure> = dyn Fn(&Value) -> Result<Vec<u8>, Failure> + Send + Sync;
27
28type Decode<Value, Failure> = dyn Fn(&[u8]) -> Result<Value, Failure> + Send + Sync;
29
30/// Gives a serializer of your choice, such as JSON, MessagePack or protobuf,
31/// one shape for both directions. The encoder's and the decoder's own errors
32/// are returned unchanged: they are yours, not this crate's.
33///
34/// ```
35/// use useceleris_client::PayloadCodec;
36///
37/// // With serde_json, this is
38/// // PayloadCodec::new(serde_json::to_vec, |payload| serde_json::from_slice(payload)).
39/// let numbers = PayloadCodec::new(
40///     |value: &u32| Ok::<_, std::num::ParseIntError>(value.to_string().into_bytes()),
41///     |payload: &[u8]| String::from_utf8_lossy(payload).parse::<u32>(),
42/// );
43///
44/// let payload = numbers.encode_payload(&42).unwrap();
45/// assert_eq!(numbers.read_payload(&payload).unwrap(), 42);
46/// ```
47pub struct PayloadCodec<Value, Failure> {
48    encode: Arc<Encode<Value, Failure>>,
49    decode: Arc<Decode<Value, Failure>>,
50} // end struct PayloadCodec
51
52impl<Value, Failure> PayloadCodec<Value, Failure> {
53    /// Wraps an encoder and a decoder.
54    pub fn new(
55        encode: impl Fn(&Value) -> Result<Vec<u8>, Failure> + Send + Sync + 'static,
56        decode: impl Fn(&[u8]) -> Result<Value, Failure> + Send + Sync + 'static,
57    ) -> PayloadCodec<Value, Failure> {
58        PayloadCodec {
59            encode: Arc::new(encode),
60            decode: Arc::new(decode),
61        }
62    } // end fn new
63
64    /// Encodes `value` with the codec's encoder.
65    pub fn encode_payload(&self, value: &Value) -> Result<Vec<u8>, Failure> {
66        (self.encode)(value)
67    } // end method encode_payload
68
69    /// Decodes `payload` with the codec's decoder.
70    pub fn read_payload(&self, payload: &[u8]) -> Result<Value, Failure> {
71        (self.decode)(payload)
72    } // end method read_payload
73} // end impl PayloadCodec
74
75impl<Value, Failure> Clone for PayloadCodec<Value, Failure> {
76    fn clone(&self) -> PayloadCodec<Value, Failure> {
77        PayloadCodec {
78            encode: Arc::clone(&self.encode),
79            decode: Arc::clone(&self.decode),
80        }
81    } // end method clone
82} // end impl Clone for PayloadCodec
83
84impl<Value, Failure> fmt::Debug for PayloadCodec<Value, Failure> {
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        formatter.write_str("PayloadCodec")
87    } // end method fmt
88} // end impl Debug for PayloadCodec