Skip to main content

printobserver_types/
raw.rs

1//! The bytes an externally sourced event arrived as.
2//!
3//! Held exactly as received and serialized as a base64 string, because JSON
4//! denotes no byte sequence: it is what makes the history auditable when a
5//! normalization turns out to have been wrong.
6
7use core::fmt;
8use std::borrow::Cow;
9
10use base64::Engine as _;
11use base64::engine::general_purpose::STANDARD;
12use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
13use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
14
15/// Bytes exactly as received, serialized as a base64 string.
16#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
17pub struct RawBytes(Vec<u8>);
18
19impl RawBytes {
20    /// Hold these bytes.
21    #[must_use]
22    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
23        Self(bytes.into())
24    }
25
26    /// The bytes, exactly as received.
27    #[must_use]
28    pub fn as_slice(&self) -> &[u8] {
29        &self.0
30    }
31}
32
33impl fmt::Display for RawBytes {
34    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35        formatter.write_str(&STANDARD.encode(&self.0))
36    }
37}
38
39impl Serialize for RawBytes {
40    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41        serializer.collect_str(&STANDARD.encode(&self.0))
42    }
43}
44
45impl<'de> Deserialize<'de> for RawBytes {
46    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
47        let text = String::deserialize(deserializer)?;
48        STANDARD
49            .decode(text.as_bytes())
50            .map(Self)
51            .map_err(D::Error::custom)
52    }
53}
54
55impl JsonSchema for RawBytes {
56    fn schema_name() -> Cow<'static, str> {
57        Cow::Borrowed("RawBytes")
58    }
59
60    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
61        json_schema!({
62            "type": "string",
63            "title": "RawBytes",
64            "description": "Bytes exactly as received, base64-encoded.",
65            "contentEncoding": "base64"
66        })
67    }
68}