You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
2.5 KiB

//! Source traces
use super::*;
/// Contains backtrace info from where the log macro was invoked
#[derive(Debug)]
pub struct Trace
{
line: Option<usize>,
file: Option<&'static str>,
column: Option<usize>,
display: Opaque<RwLock<Option<String>>>,
}
impl Clone for Trace
{
#[inline]
fn clone(&self) -> Self
{
Self {
line: self.line.clone(),
file: self.file.clone(),
column: self.column.clone(),
display: Opaque::new(RwLock::new(None)),
}
}
}
impl std::hash::Hash for Trace
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H)
{
self.line.hash(state);
self.file.hash(state);
self.column.hash(state);
}
}
impl std::cmp::PartialEq for Trace
{
fn eq(&self, other: &Self)->bool
{
self.line == other.line &&
self.file == other.file &&
self.column == other.column
}
}
impl Trace
{
/// Create a new `Trace` manually. Generally not desireable, use `get_trace!()` instead.
pub fn new(file: Option<&'static str>, line: Option<u32>, column: Option<u32>) -> Self
{
use std::convert::TryInto;
let this = Self{
file,
line: line.and_then(|x| x.try_into().ok()),
column: column.and_then(|x| x.try_into().ok()),
display: Opaque::new(RwLock::new(None)),
};
this
}
fn genstring(&self) -> Result<String, fmt::Error>
{
let mut out = String::new();
use std::fmt::Write as FmtWrite;
write!(out, "{}", self.file.unwrap_or("(unbound)"))?;
if let Some(line) = self.line {
write!(&mut out, ":{}", line)?;
} else {
write!(&mut out, ":?")?;
}
if let Some(column) = self.column {
write!(&mut out, ":{}", column)?;
} else {
write!(&mut out, ":?")?;
}
Ok(out)
}
}
impl std::fmt::Display for Trace
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
{
let read = self.display.read().expect("Poisoned");
if let Some(opt) = read.as_ref()
{
write!(f, "{}", opt)?;
return Ok(());
}
}
let out = self.genstring()?;
write!(f, "{}", out)?;
let mut write = self.display.write().expect("Poisoned");
*write = Some(out);
Ok(())
}
}
impl Default for Trace
{
#[inline]
fn default() -> Self
{
Self{
line:None,
file:None,
column:None,
display: Opaque::new(RwLock::new(None)),
}
}
}
/// Get a source code trace of the current file, line and column.
#[macro_export] macro_rules! get_trace
{
() => {
$crate::log::Trace::new(Some(file!()), Some(line!()), Some(column!()))
}
}