sc_cli/params/
message_params.rs1use crate::error::Error;
22use array_bytes::{hex2bytes, hex_bytes2hex_str};
23use clap::Args;
24use std::io::BufRead;
25
26#[derive(Debug, Clone, Args)]
28pub struct MessageParams {
29 #[arg(long)]
33 message: Option<String>,
34
35 #[arg(long)]
37 hex: bool,
38}
39
40impl MessageParams {
41 pub(crate) fn message_from<F, R>(&self, create_reader: F) -> Result<Vec<u8>, Error>
45 where
46 R: BufRead,
47 F: FnOnce() -> R,
48 {
49 let raw = match &self.message {
50 Some(raw) => raw.as_bytes().to_vec(),
51 None => {
52 let mut raw = vec![];
53 create_reader().read_to_end(&mut raw)?;
54 raw
55 },
56 };
57 if self.hex {
58 hex2bytes(hex_bytes2hex_str(&raw)?).map_err(Into::into)
59 } else {
60 Ok(raw)
61 }
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
71 fn message_decode_immediate() {
72 for (name, input, hex, output) in test_closures() {
73 println!("Testing: immediate_{}", name);
74 let params = MessageParams { message: Some(input.into()), hex };
75 let message = params.message_from(|| std::io::stdin().lock());
76
77 match output {
78 Some(output) => {
79 let message = message.expect(&format!("{}: should decode but did not", name));
80 assert_eq!(message, output, "{}: decoded a wrong message", name);
81 },
82 None => {
83 message.err().expect(&format!("{}: should not decode but did", name));
84 },
85 }
86 }
87 }
88
89 #[test]
91 fn message_decode_stream() {
92 for (name, input, hex, output) in test_closures() {
93 println!("Testing: stream_{}", name);
94 let params = MessageParams { message: None, hex };
95 let message = params.message_from(|| input.as_bytes());
96
97 match output {
98 Some(output) => {
99 let message = message.expect(&format!("{}: should decode but did not", name));
100 assert_eq!(message, output, "{}: decoded a wrong message", name);
101 },
102 None => {
103 message.err().expect(&format!("{}: should not decode but did", name));
104 },
105 }
106 }
107 }
108
109 fn test_closures() -> Vec<(&'static str, &'static str, bool, Option<&'static [u8]>)> {
111 vec![
112 ("decode_no_hex_works", "Hello this is not hex", false, Some(b"Hello this is not hex")),
113 ("decode_no_hex_with_hex_string_works", "0xffffffff", false, Some(b"0xffffffff")),
114 ("decode_hex_works", "0x00112233", true, Some(&[0, 17, 34, 51])),
115 ("decode_hex_without_prefix_works", "00112233", true, Some(&[0, 17, 34, 51])),
116 ("decode_hex_uppercase_works", "0xaAbbCCDd", true, Some(&[170, 187, 204, 221])),
117 ("decode_hex_wrong_len_errors", "0x0011223", true, None),
118 ]
119 }
120}