Skip to main content

rpgtool_common/
lib.rs

1#![warn(clippy::unwrap_used, clippy::pedantic, rust_2018_idioms)]
2#![allow(
3    clippy::must_use_candidate,
4    clippy::missing_errors_doc,
5    clippy::cast_possible_truncation
6)]
7
8mod de;
9mod ser;
10
11pub struct Value(pub alox_48::Value);
12
13impl<'de> serde::Deserialize<'de> for Value {
14    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
15    where
16        D: serde::Deserializer<'de>,
17    {
18        de::DeserializeValue::deserialize(deserializer).map(|v| Self(v.0))
19    }
20}
21
22impl serde::Serialize for Value {
23    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
24    where
25        S: serde::Serializer,
26    {
27        ser::SerializeValue(&self.0).serialize(serializer)
28    }
29}
30
31impl<'de> alox_48::Deserialize<'de> for Value {
32    fn deserialize<D>(deserializer: D) -> alox_48::DeResult<Self>
33    where
34        D: alox_48::DeserializerTrait<'de>,
35    {
36        alox_48::Value::deserialize(deserializer).map(Self)
37    }
38}
39
40impl alox_48::Serialize for Value {
41    fn serialize<S>(&self, serializer: S) -> alox_48::SerResult<S::Ok>
42    where
43        S: alox_48::SerializerTrait,
44    {
45        self.0.serialize(serializer)
46    }
47}
48
49#[derive(Debug, PartialEq, Eq, Clone, Copy, clap::ValueEnum)]
50#[non_exhaustive]
51pub enum Format {
52    Json,
53    Marshal,
54    Ron,
55    Yaml,
56    // Saphyr,
57}
58
59impl Format {
60    pub fn guess(path: &std::path::Path) -> Option<Format> {
61        let ext = path.extension()?;
62        Self::guess_from_ext(ext)
63    }
64
65    pub fn guess_from_ext(ext: impl AsRef<std::ffi::OsStr>) -> Option<Format> {
66        let ext = ext.as_ref().to_str()?;
67        match ext {
68            "json" | "jsonc" => Some(Format::Json),
69            "rxdata" | "rvdata" | "rvdata2" => Some(Format::Marshal),
70            "ron" => Some(Format::Ron),
71            "yaml" | "yml" => Some(Format::Yaml),
72            _ => None,
73        }
74    }
75
76    pub fn file_ext(self) -> &'static std::path::Path {
77        std::path::Path::new(match self {
78            Format::Json => "json",
79            Format::Marshal => "rxdata",
80            Format::Ron => "ron",
81            Format::Yaml /* | Format::Saphyr */ => "yaml",
82        })
83    }
84}
85
86// TODO provide trace
87#[derive(Debug, thiserror::Error)]
88#[non_exhaustive]
89pub enum ConvError {
90    #[error("{0}")]
91    MarshalDe(#[from] alox_48::DeError),
92    #[error("{0}")]
93    MarshalSer(#[from] alox_48::SerError),
94    #[error("{0}")]
95    Json(#[from] serde_json::Error),
96    #[error("{0}")]
97    RonDe(#[from] ron::de::SpannedError),
98    #[error("{0}")]
99    Ron(#[from] ron::Error),
100    // #[error("{0}")]
101    // SaphyrDe(#[from] serde_saphyr::Error),
102    // #[error("{0}")]
103    // SaphyrSer(#[from] serde_saphyr::ser_error::Error),
104    // #[error("No YAML document was present")]
105    // SaphyrNoDocument,
106    #[error("{0}")]
107    Yaml(#[from] serde_yaml_ng::Error),
108    #[error("{0}")]
109    Io(#[from] std::io::Error),
110}
111
112// FIXME shitty hack because serde_yaml doesn't support binary and we have no way to recover from serialization errors
113thread_local! {
114    static BYTES_ALLOWED: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
115}
116
117fn set_binary_bytes_allowed(allowed: bool) {
118    BYTES_ALLOWED.set(allowed);
119}
120
121fn binary_bytes_allowed() -> bool {
122    BYTES_ALLOWED.get()
123}
124
125pub fn conv_read<R, T>(from: Format, mut input: R) -> Result<T, ConvError>
126where
127    R: std::io::Read,
128    T: for<'de> serde::Deserialize<'de> + for<'de> alox_48::Deserialize<'de>,
129{
130    set_binary_bytes_allowed(from != Format::Yaml);
131
132    let value = match from {
133        Format::Marshal => {
134            let mut data = vec![];
135            input.read_to_end(&mut data)?;
136            alox_48::from_bytes::<T>(&data)?
137        }
138        Format::Json => serde_json::from_reader(input)?,
139        Format::Ron => ron::Options::default().from_reader(input)?,
140        // Format::Saphyr => {
141        //     let mut iter = serde_saphyr::read(&mut input);
142        //     iter.next().ok_or(ConvError::SaphyrNoDocument)??
143        // }
144        Format::Yaml => serde_yaml_ng::from_reader(input)?,
145    };
146    Ok(value)
147}
148
149pub fn conv_write<W, T>(value: T, to: Format, mut output: W) -> Result<(), ConvError>
150where
151    W: std::io::Write,
152    T: serde::Serialize + alox_48::Serialize,
153{
154    set_binary_bytes_allowed(to != Format::Yaml);
155
156    match to {
157        Format::Marshal => {
158            let data = alox_48::to_bytes(value)?;
159            output.write_all(&data)?;
160        }
161        Format::Json => {
162            let mut ser = serde_json::Serializer::pretty(output);
163            serde::Serialize::serialize(&value, &mut ser)?;
164        }
165        Format::Ron => {
166            let config = ron::ser::PrettyConfig::default();
167            ron::Options::default().to_io_writer_pretty(output, &value, config)?;
168        }
169        // Format::Saphyr => {
170        //     serde_saphyr::to_io_writer(&mut output, &value)?;
171        // }
172        Format::Yaml => {
173            let mut ser = serde_yaml_ng::Serializer::new(output);
174            serde::Serialize::serialize(&value, &mut ser)?;
175        }
176    }
177
178    Ok(())
179}