refactor(parser): Abstract over lifetimes

This commit is contained in:
Ed Page 2020-12-31 19:29:45 -06:00
parent 663eb94d32
commit 48112a47e9
3 changed files with 39 additions and 6 deletions

View file

@ -27,6 +27,20 @@ impl<'c> Status<'c> {
}
}
pub fn into_owned(self) -> Status<'static> {
match self {
Status::Valid => Status::Valid,
Status::Invalid => Status::Invalid,
Status::Corrections(corrections) => {
let corrections = corrections
.into_iter()
.map(|c| Cow::Owned(c.into_owned()))
.collect();
Status::Corrections(corrections)
}
}
}
pub fn borrow(&self) -> Status<'_> {
match self {
Status::Corrections(corrections) => {

View file

@ -1,5 +1,6 @@
use crate::tokens;
use crate::Dictionary;
use std::borrow::Cow;
#[derive(Clone)]
pub struct ParserBuilder<'p, 'd> {
@ -86,7 +87,7 @@ impl<'p, 'd> TyposParser<'p, 'd> {
Some(corrections) => {
let typo = Typo {
byte_offset: ident.offset(),
typo: ident.token(),
typo: ident.token().into(),
corrections,
};
itertools::Either::Left(Some(typo).into_iter())
@ -105,7 +106,7 @@ impl<'p, 'd> TyposParser<'p, 'd> {
Some(corrections) => {
let typo = Typo {
byte_offset: word.offset(),
typo: word.token(),
typo: word.token().into(),
corrections,
};
Some(typo)
@ -119,15 +120,33 @@ impl<'p, 'd> TyposParser<'p, 'd> {
#[non_exhaustive]
pub struct Typo<'m> {
pub byte_offset: usize,
pub typo: &'m str,
pub typo: Cow<'m, str>,
pub corrections: crate::Status<'m>,
}
impl<'m> Typo<'m> {
pub fn into_owned(self) -> Typo<'static> {
Typo {
byte_offset: self.byte_offset,
typo: Cow::Owned(self.typo.into_owned()),
corrections: self.corrections.into_owned(),
}
}
pub fn borrow(&self) -> Typo<'_> {
Typo {
byte_offset: self.byte_offset,
typo: Cow::Borrowed(self.typo.as_ref()),
corrections: self.corrections.borrow(),
}
}
}
impl<'m> Default for Typo<'m> {
fn default() -> Self {
Self {
byte_offset: 0,
typo: "",
typo: "".into(),
corrections: crate::Status::Invalid,
}
}

View file

@ -111,7 +111,7 @@ impl Check for Typos {
context: Some(report::PathContext { path }.into()),
buffer: std::borrow::Cow::Borrowed(file_name.as_bytes()),
byte_offset: typo.byte_offset,
typo: typo.typo,
typo: typo.typo.as_ref(),
corrections: typo.corrections,
};
reporter.report(msg.into())?;
@ -134,7 +134,7 @@ impl Check for Typos {
context: Some(report::FileContext { path, line_num }.into()),
buffer: std::borrow::Cow::Borrowed(line),
byte_offset: line_offset,
typo: typo.typo,
typo: typo.typo.as_ref(),
corrections: typo.corrections,
};
reporter.report(msg.into())?;