evident/event/
origin.rs

1//! Contains the [`Origin`] structure used to know where the event was set.
2
3/// Structure to point to a location in the program code.
4/// It is used to know where the event was set, but may be used for other use cases aswell.
5///
6/// [req:event.origin]
7#[derive(Debug, Default, PartialEq, Eq, Clone)]
8pub struct Origin {
9    /// Module path to the code location.
10    ///
11    /// Note: Use `module_path!()`.
12    pub module_path: &'static str,
13
14    /// Filename where the code is located.
15    ///
16    /// Note: Use `file!()`.
17    pub filename: &'static str,
18
19    /// Line number where the code is located.
20    ///
21    /// Note: Use `line!()`.
22    pub line_nr: u32,
23}
24
25impl Origin {
26    /// Create a new [`Origin`].
27    ///
28    /// # Arguments
29    ///
30    /// * `module_path` ... Module path to the code location
31    /// * `filename` ... Filename where the code is located
32    /// * `line_nr` ... Line number where the code is located
33    ///
34    /// [req:event.origin]
35    pub fn new(module_path: &'static str, filename: &'static str, line_nr: u32) -> Self {
36        Origin {
37            module_path,
38            filename,
39            line_nr,
40        }
41    }
42}
43
44impl From<&Origin> for String {
45    /// Formats given [`Origin`] as `module="<module path>", file="<filename>", line=<line number>`.
46    fn from(origin: &Origin) -> Self {
47        format!(
48            "module=\"{}\", file=\"{}\", line={}",
49            origin.module_path, origin.filename, origin.line_nr
50        )
51    }
52}
53
54impl core::fmt::Display for Origin {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        write!(f, "{}", String::from(self))
57    }
58}
59
60/// Convenience wrapper to create an [`Origin`] for the code position this macro is used at.
61///
62/// [req:event.origin], [req:qa.ux.macros]
63#[macro_export]
64macro_rules! this_origin {
65    () => {
66        $crate::event::origin::Origin::new(module_path!(), file!(), line!())
67    };
68}