diff --git a/src/lib.rs b/src/lib.rs index 15fa9ec..1fb146a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -use std::io::Write; +use std::{io::Write, ops::Deref}; use once_cell::sync::Lazy; use regex::{Captures, Regex, RegexBuilder}; @@ -13,17 +13,49 @@ const CODE_BLOCK_RE: Lazy = Lazy::new(|| { .unwrap() }); +pub enum MaybeOwned<'a, T: 'a> { + Owned(T), + Borrowed(&'a T), +} + +impl<'a, T> Deref for MaybeOwned<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + match self { + Self::Owned(v) => &v, + Self::Borrowed(v) => v + } + } +} + +impl<'a, T> From for MaybeOwned<'a, T> { + fn from(value: T) -> Self { + Self::Owned(value) + } +} + +impl<'a, T> From<&'a T> for MaybeOwned<'a, T> { + fn from(value: &'a T) -> Self { + Self::Borrowed(value) + } +} + pub struct SyntectParser<'a> { - syntax_set: SyntaxSet, - theme_set: ThemeSet, + syntax_set: MaybeOwned<'a, SyntaxSet>, + theme_set: MaybeOwned<'a, ThemeSet>, theme: &'a str, } impl<'a> SyntectParser<'a> { - pub fn new(syntax_set: SyntaxSet, theme_set: ThemeSet, theme: &'a str) -> Self { + pub fn new>, T: Into>>( + syntax_set: S, + theme_set: T, + theme: &'a str, + ) -> Self { Self { - syntax_set, - theme_set, + syntax_set: syntax_set.into(), + theme_set: theme_set.into(), theme, } } @@ -38,11 +70,11 @@ impl<'a> SyntectParser<'a> { impl<'a> Default for SyntectParser<'a> { fn default() -> Self { - Self { - syntax_set: SyntaxSet::load_defaults_newlines(), - theme_set: ThemeSet::load_defaults(), - theme: "base16-ocean.dark", - } + Self::new( + SyntaxSet::load_defaults_newlines(), + ThemeSet::load_defaults(), + "base16-ocean.dark", + ) } }