From b91e6e060ab59d1ed5cc617f5d44a99e63cfbae6 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Fri, 30 Apr 2021 23:01:35 +0800 Subject: [PATCH] feat: add opt_result --- Cargo.toml | 2 +- examples/log.rs | 11 +++++++++-- src/lib.rs | 16 ++++++++++++++-- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 030b9bb..995a755 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust_util" -version = "0.6.31" +version = "0.6.32" authors = ["Hatter Jiang "] edition = "2018" description = "Hatter's Rust Util" diff --git a/examples/log.rs b/examples/log.rs index 2115474..44443aa 100644 --- a/examples/log.rs +++ b/examples/log.rs @@ -1,6 +1,6 @@ #[macro_use] extern crate rust_util; -use rust_util::XResult; +use rust_util::{XResult, SimpleError}; // cargo run --example log fn main() -> XResult<()> { @@ -18,5 +18,12 @@ error or ^"##); warning!("Hello {}", "world!"); failure!("Hello {}", "world!"); + println!("{:?}", test_opt_result()); + simple_error!("helloworld {}", 1) -} \ No newline at end of file +} + +fn test_opt_result() -> XResult<()> { + let a = Err(SimpleError::new("test".into())); + opt_result!(a, "error: {}") +} diff --git a/src/lib.rs b/src/lib.rs index 0c4c5b0..8752d05 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,7 @@ pub mod util_tlv; ($($arg:tt)+) => ( rust_util::util_msg::print_debug(&format!($($arg)+)); ) } #[macro_export] macro_rules! opt_value { - ($e: expr) => ( match $e { Some(o) => o, None => return, } ) + ($ex: expr) => ( match $ex { Some(o) => o, None => return, } ) } pub type XResult = Result>; @@ -54,8 +54,20 @@ pub fn new_box_ioerror(m: &str) -> Box { Box::new(IoError::new(ErrorKind::Other, m)) } +#[macro_export] macro_rules! opt_result { + ($ex: expr, $($arg:tt)+) => ( + match $ex { + Ok(o) => o, + Err(e) => return Err(rust_util::SimpleError::new( + format!("{}, file: {}, line: {}", format!($($arg)+, e), file!(), line!()) + ).into()), + } + ) +} #[macro_export] macro_rules! simple_error { - ($($arg:tt)+) => ( Err(rust_util::SimpleError::new(format!($($arg)+)).into()) ) + ($($arg:tt)+) => ( Err(rust_util::SimpleError::new( + format!("{}, file: {}, line: {}", format!($($arg)+), file!(), line!()) + ).into()) ) } #[derive(Debug)]