feat(offsets): nice utility function to get an offset from a Rust callsite

Fixes: https://github.com/zkat/miette/issues/19
This commit is contained in:
Kat Marchán 2021-08-17 19:14:27 -07:00
parent 75c2312755
commit 26f409c525
No known key found for this signature in database
GPG Key ID: AEB529C08A3C7E9E
1 changed files with 22 additions and 1 deletions

View File

@ -4,7 +4,7 @@ that you can implement to get access to miette's (and related library's) full
reporting and such features.
*/
use std::fmt::Display;
use std::{fmt::Display, fs, panic::Location};
use crate::MietteError;
@ -313,6 +313,27 @@ impl SourceOffset {
SourceOffset(offset)
}
/// Returns an offset for the _file_ location of wherever this function is
/// called. If you want to get _that_ caller's location, mark this
/// function's caller with #[track_caller] (and so on and so forth).
///
/// Returns both the filename that was given and the offset of the caller
/// as a SourceOffset
///
/// Keep in mind that this fill only work if the file your Rust source
/// file was compiled from is actually available at that location. If
/// you're shipping binaries for your application, you'll want to ignore
/// the Err case or otherwise report it.
#[track_caller]
pub fn from_current_location() -> Result<(String, Self), MietteError> {
let loc = Location::caller();
Ok((
loc.file().into(),
fs::read_to_string(loc.file())
.map(|txt| Self::from_location(&txt, loc.line() as usize, loc.column() as usize))?,
))
}
}
impl From<ByteOffset> for SourceOffset {