rain_metadata/cli/
output.rs1use std::io::Write;
2use strum::EnumIter;
3use strum::EnumString;
4use std::path::PathBuf;
5
6#[derive(serde::Serialize, Clone, Copy, EnumString, EnumIter, strum::Display)]
7#[strum(serialize_all = "kebab_case")]
8#[serde(rename_all = "kebab-case")]
9#[repr(u64)]
10pub enum SupportedOutputEncoding {
11 Binary,
12 Hex,
13}
14
15pub fn output(
16 output_path: &Option<PathBuf>,
17 output_encoding: SupportedOutputEncoding,
18 bytes: &[u8],
19) -> anyhow::Result<()> {
20 let hex_encoded: String;
21 let encoded_bytes: &[u8] = match output_encoding {
22 SupportedOutputEncoding::Binary => bytes,
23 SupportedOutputEncoding::Hex => {
24 hex_encoded = alloy::primitives::hex::encode_prefixed(bytes);
25 hex_encoded.as_bytes()
26 }
27 };
28 if let Some(output_path) = output_path {
29 std::fs::write(output_path, encoded_bytes)?
30 } else {
31 std::io::stdout().write_all(encoded_bytes)?
32 }
33 Ok(())
34}
35
36#[cfg(all(test, not(target_family = "wasm")))]
37mod tests {
38 use super::*;
39
40 #[test]
42 fn test_output_binary_writes_exact_bytes_to_file() {
43 let file = tempfile::NamedTempFile::new().unwrap();
44 let path = file.path().to_path_buf();
45 output(
46 &Some(path.clone()),
47 SupportedOutputEncoding::Binary,
48 &[0x00, 0x01, 0xff],
49 )
50 .unwrap();
51 assert_eq!(std::fs::read(&path).unwrap(), vec![0x00, 0x01, 0xff]);
52 }
53
54 #[test]
56 fn test_output_hex_writes_prefixed_hex_to_file() {
57 let file = tempfile::NamedTempFile::new().unwrap();
58 let path = file.path().to_path_buf();
59 output(
60 &Some(path.clone()),
61 SupportedOutputEncoding::Hex,
62 &[0x00, 0x01, 0xff],
63 )
64 .unwrap();
65 assert_eq!(std::fs::read_to_string(&path).unwrap(), "0x0001ff");
66 }
67}