Skip to main content

opys_core/
source.rs

1use base64::Engine;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5#[serde(tag = "kind", rename_all = "lowercase")]
6pub enum Source {
7    Url { url: String },
8    File { file: String },
9    String { string: String },
10    Bytes { bytes: String },
11    Pointer { pointer: String },
12}
13
14impl Source {
15    /// Construct a `Bytes` source from raw bytes, base64-encoding for transit.
16    pub fn from_bytes(bytes: &[u8]) -> Self {
17        Source::Bytes {
18            bytes: base64::engine::general_purpose::STANDARD.encode(bytes),
19        }
20    }
21}
22
23/// Wire shape — discriminated by which field is present, NOT by a `kind` tag.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(untagged)]
26pub enum SourceWire {
27    Url { url: String },
28    File { file: String },
29    String { string: String },
30    Bytes { bytes: String },
31    Pointer { pointer: String },
32}
33
34pub fn decode_source(raw: SourceWire) -> Source {
35    match raw {
36        SourceWire::Url { url } => Source::Url { url },
37        SourceWire::File { file } => Source::File { file },
38        SourceWire::String { string } => Source::String { string },
39        SourceWire::Bytes { bytes } => Source::Bytes { bytes },
40        SourceWire::Pointer { pointer } => Source::Pointer { pointer },
41    }
42}
43
44pub fn encode_source(source: &Source) -> SourceWire {
45    match source {
46        Source::Url { url } => SourceWire::Url { url: url.clone() },
47        Source::File { file } => SourceWire::File { file: file.clone() },
48        Source::String { string } => SourceWire::String {
49            string: string.clone(),
50        },
51        Source::Bytes { bytes } => SourceWire::Bytes {
52            bytes: bytes.clone(),
53        },
54        Source::Pointer { pointer } => SourceWire::Pointer {
55            pointer: pointer.clone(),
56        },
57    }
58}