Skip to main content

umya_spreadsheet/helper/
utils.rs

1#![allow(unused_imports)]
2
3/// A macro that implements the `From` trait for converting from one error type
4/// to another.
5///
6/// # Usage
7/// ```
8/// # use std::{io,fmt};
9///
10/// use umya_spreadsheet::from_err;
11///
12/// #[derive(Debug)]
13/// enum MyError {
14///     Io(std::io::Error),
15/// };
16/// # impl fmt::Display for MyError {
17/// #   fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18/// #       unimplemented!()
19/// #   }
20/// # }
21/// # impl std::error::Error for MyError {}
22///
23/// from_err!(std::io::Error, MyError, Io);
24///
25/// let io_err = io::Error::new(io::ErrorKind::Other, "An I/O error occurred");
26/// let my_err: MyError = io_err.into();
27/// ```
28#[macro_export]
29macro_rules! from_err {
30    ($from:ty, $to:tt, $var:tt) => {
31        impl From<$from> for $to {
32            #[inline]
33            fn from(e: $from) -> $to {
34                $to::$var(e)
35            }
36        }
37    };
38}
39
40/// Asserts that the SHA-256 hash of a given input matches the expected
41/// hexadecimal string.
42///
43/// # Arguments
44///
45/// * `$input` - The input data to hash.
46/// * `$expected_hex` - The expected SHA-256 hash as a hexadecimal string.
47///
48/// # Panics
49///
50/// This macro will panic if the actual SHA-256 hash does not match the
51/// expected hash.
52///
53/// # Examples
54///
55/// ```ignore
56/// let data = b"Hello, world!";
57/// assert_sha256!(
58///     data,
59///     "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"
60/// );
61/// // This will not panic
62///
63/// assert_sha256!(data, "invalid_hash");
64/// // This will panic with a message indicating the mismatch
65/// ```
66macro_rules! assert_sha256 {
67    ($input:expr, $expected_hex:expr) => {{
68        let hash = Sha256::digest($input).to_vec();
69        let expected_bytes = hex_literal::hex!($expected_hex);
70        assert_eq!(
71            &hash,
72            &expected_bytes,
73            "SHA256({}) mismatch! Expected: {:?}, Actual: {:?}",
74            stringify!($input),
75            &expected_bytes
76                .iter()
77                .map(|b| format!("{:02x}", b))
78                .collect::<String>(),
79            &hash
80                .iter()
81                .map(|b| format!("{:02x}", b))
82                .collect::<String>()
83        );
84    }};
85}
86
87/// A macro that compiles a regular expression and caches it.
88///
89/// # Usage
90/// ```rust,ignore
91/// // Unable to run because function is private
92/// let re = compile_regex!(r"^\d+$");
93///
94/// assert!(re.is_match("123").unwrap());
95/// assert!(!re.is_match("abc").unwrap());
96/// ```
97macro_rules! compile_regex {
98    ($re:literal $(,)?) => {{
99        static RE: std::sync::OnceLock<fancy_regex::Regex> = std::sync::OnceLock::new();
100        RE.get_or_init(|| fancy_regex::Regex::new($re).unwrap())
101    }};
102}
103
104/// Prints a byte slice as a hex string, prefixed with the variable name.
105///
106/// This macro takes a reference to a byte slice (`&[u8]`) and prints both
107/// the variable name and its hexadecimal representation to stdout.
108macro_rules! print_hex {
109    ($var:expr) => {
110        println!(
111            "{} = {}",
112            stringify!($var),
113            $var.iter()
114                .map(|b| format!("{:02x}", b))
115                .collect::<String>()
116        );
117    };
118}
119
120/// Prints the SHA-256 hash of a given input as a hexadecimal string.
121///
122/// # Examples
123///
124/// ```ignore
125/// let data = b"Hello, world!";
126/// print_sha256_hex!(data);
127/// // Output: SHA256(data) = 5eb63bbbe01eeed093cb22bb8f5acdc3
128/// ```
129macro_rules! print_sha256_hex {
130    ($var:expr) => {
131        let hash = Sha256::digest($var);
132        println!(
133            "SHA256({}) = {}",
134            stringify!($var),
135            hash.iter()
136                .map(|b| format!("{:02x}", b))
137                .collect::<String>()
138        );
139    };
140}
141
142pub(crate) use assert_sha256;
143pub(crate) use compile_regex;
144pub(crate) use print_hex;
145pub(crate) use print_sha256_hex;