From 48601fc5e6e0ee0e753c892f0eb42a9b0b48be99 Mon Sep 17 00:00:00 2001 From: KitsuneCafe <10284516+kitsunecafe@users.noreply.github.com> Date: Sun, 4 Feb 2024 16:24:34 -0500 Subject: [PATCH] improve ergonomics --- src/lib.rs | 54 +++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 11 deletions(-) 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", + ) } }