session_log/
location.rs

1use crate::*;
2
3
4/// Location type is used to represent the location where the logging is happened. It cannot be created
5/// outside of the library.
6#[derive(Debug, Clone, Copy)]
7pub struct Location(&'static str, u32);
8
9
10impl Location {
11  #[track_caller]
12  pub(crate) fn new() -> Self {
13    let loc = std::panic::Location::caller();
14    Self(loc.file(), loc.line())
15  }
16
17  /// Returns the raw file path. (May not be consistent)
18  pub fn raw_file(&self) -> &'static str {
19    self.0
20  }
21
22  /// Returns the line number.
23  pub fn line(&self) -> u32 {
24    self.1
25  }
26
27  /// Returns the file path that is relative to the project root.
28  pub fn file(&self) -> String {
29    let path = self.0;
30    let path = path.strip_prefix(r"\\?\").unwrap_or(path);
31    let path = path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap_or(path);
32    let path = path.strip_prefix(r"\").unwrap_or(path);
33    let path = path.strip_prefix(r"/").unwrap_or(path);
34
35    path.to_string()
36  }
37}
38
39
40impl Output for Location {
41  fn for_write(&self, f: &mut impl std::fmt::Write) {
42    write!(f, "{}:{}", self.file(), self.line()).unwrap();
43  }
44
45  fn for_print(&self, f: &mut impl std::fmt::Write) {
46    write!(f, "{}:{}", self.file(), self.line()).unwrap();
47  }
48}