1#![warn(clippy::unwrap_used)]
2
3mod ser;
4pub use ser::SerializeValue;
5
6mod de;
7pub use de::DeserializeValue;
8
9use serde::Serialize;
10use std::io::{Read, Write};
11
12#[derive(Debug, Clone, Copy, clap::ValueEnum)]
13pub enum Format {
14 Json,
15 Marshal,
16 Ron,
17 Yaml,
18}
19
20impl Format {
21 pub fn guess(path: &std::path::Path) -> Option<Format> {
22 let ext = path.extension()?;
23 Self::guess_from_ext(ext)
24 }
25
26 pub fn guess_from_ext(ext: impl AsRef<std::ffi::OsStr>) -> Option<Format> {
27 let ext = ext.as_ref().to_str()?;
28 match ext {
29 "json" | "jsonc" => Some(Format::Json),
30 "rxdata" | "rvdata" | "rvdata2" => Some(Format::Marshal),
31 "ron" => Some(Format::Ron),
32 "yaml" | "yml" => Some(Format::Yaml),
33 _ => None,
34 }
35 }
36
37 pub fn file_ext(self) -> &'static std::path::Path {
38 std::path::Path::new(match self {
39 Format::Json => "json",
40 Format::Marshal => "rxdata",
41 Format::Ron => "ron",
42 Format::Yaml => "yaml",
43 })
44 }
45}
46
47#[derive(Debug, thiserror::Error)]
48pub enum ConvError {
49 #[error("{0}")]
50 MarshalDe(#[from] alox_48::DeError),
51 #[error("{0}")]
52 MarshalSer(#[from] alox_48::SerError),
53 #[error("{0}")]
54 Json(#[from] serde_json::Error),
55 #[error("{0}")]
56 RonDe(#[from] ron::de::SpannedError),
57 #[error("{0}")]
58 Ron(#[from] ron::Error),
59 #[error("{0}")]
60 Yaml(#[from] serde_yaml_ng::Error),
61 #[error("{0}")]
62 Io(#[from] std::io::Error),
63}
64
65pub fn conv_io<R, W>(from: Format, to: Format, mut input: R, mut output: W) -> Result<(), ConvError>
66where
67 R: Read,
68 W: Write,
69{
70 let value: alox_48::Value = match from {
71 Format::Marshal => {
72 let mut data = vec![];
73 input.read_to_end(&mut data)?;
74 alox_48::from_bytes(&data)?
75 }
76 Format::Json => {
77 let value: DeserializeValue = serde_json::from_reader(input)?;
78 value.0
79 }
80 Format::Ron => {
81 let value: DeserializeValue = ron::Options::default().from_reader(input)?;
82 value.0
83 }
84 Format::Yaml => {
85 let value: DeserializeValue = serde_yaml_ng::from_reader(input)?;
86 value.0
87 }
88 };
89
90 match to {
91 Format::Marshal => {
92 let data = alox_48::to_bytes(value)?;
93 output.write_all(&data)?;
94 }
95 Format::Json => {
96 let mut ser = serde_json::Serializer::pretty(output);
97 SerializeValue(&value).serialize(&mut ser)?;
98 }
99 Format::Ron => {
100 let config = ron::ser::PrettyConfig::default();
101 ron::Options::default().to_io_writer_pretty(output, &SerializeValue(&value), config)?;
102 }
103 Format::Yaml => {
104 let mut ser = serde_yaml_ng::Serializer::new(output);
105 SerializeValue(&value).serialize(&mut ser)?;
106 }
107 }
108
109 Ok(())
110}