Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/rust/macros.txt

1.3 KiB, 1 run

created by r1870400018:12048, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Utility macros for error handling and logging.
2
3/// Create a formatted error string and return it as an Err.
4macro_rules! bail {
5 ($($arg:tt)*) => {
6 return Err(format!($($arg)*))
7 };
8}
9
10/// Unwrap a Result, returning early on Err with context.
11macro_rules! try_with {
12 ($expr:expr, $ctx:expr) => {
13 match $expr {
14 Ok(val) => val,
15 Err(e) => return Err(format!("{}: {}", $ctx, e)),
16 }
17 };
18}
19
20/// Declare a set of string constants.
21macro_rules! string_consts {
22 ($($name:ident = $val:expr),* $(,)?) => {
23 $(pub const $name: &str = $val;)*
24 };
25}
26
27string_consts! {
28 VERSION = "0.1.0",
29 APP_NAME = "annealer",
30 CONFIG_DIR = ".config/annealer",
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn test_bail() {
39 fn inner() -> Result<(), String> {
40 bail!("something went wrong: {}", 42);
41 }
42 let err = inner().unwrap_err();
43 assert_eq!(err, "something went wrong: 42");
44 }
45
46 #[test]
47 fn test_try_with() {
48 fn parse(s: &str) -> Result<i32, String> {
49 let n: i32 = try_with!(s.parse(), "bad integer");
50 Ok(n * 2)
51 }
52 assert_eq!(parse("21").unwrap(), 42);
53 assert!(parse("abc").is_err());
54 }
55}