Keep StyledString markup-agnostic, push trait to methods

This commit is contained in:
Alexandre Bury 2018-01-10 14:02:54 +01:00
parent 7ecf5f540b
commit 59d67e891c

View File

@ -19,50 +19,54 @@ pub trait Markup {
/// Parses text and return the styled spans. /// Parses text and return the styled spans.
fn parse<'a>(input: &'a str) -> Result<Vec<Span<'a>>, Self::Error>; fn parse<'a>(input: &'a str) -> Result<Vec<Span<'a>>, Self::Error>;
}
type StyledHandle = OwningHandle<StringRef, Vec<Span<'static>>>; /// Returns a string and its parsed spans.
///
/// A String that parses a markup language. /// Generates a self-borrowing struct containing the source string, as well
pub struct StyledString<M> { /// as the styled spans borrowing this string.
content: StyledHandle, fn make_handle<S>(input: S) -> Result<StyledHandle, Self::Error>
_phantom: PhantomData<M>,
}
impl<M> StyledString<M>
where
M: Markup,
{
fn make_handle<S: Into<String>>(
content: S
) -> Result<StyledHandle, M::Error> {
let content = content.into();
OwningHandle::try_new(StringRef::new(content), |input| {
M::parse(unsafe { &*input })
})
}
/// Creates a new styled string, parsing the given content.
pub fn new<S>(content: S) -> Result<Self, M::Error>
where where
S: Into<String>, S: Into<String>,
{ {
let content = Self::make_handle(content)?; let input = input.into();
Ok(StyledString { OwningHandle::try_new(StringRef::new(input), |input| {
content, Self::parse(unsafe { &*input })
_phantom: PhantomData,
}) })
} }
}
/// Holds both parsed spans, and the input string they borrow.
///
/// This is used to pass around a parsed string.
pub type StyledHandle = OwningHandle<StringRef, Vec<Span<'static>>>;
/// A String that parses a markup language.
pub struct StyledString {
content: StyledHandle,
}
impl StyledString {
/// Creates a new styled string, parsing the given content.
pub fn new<S, M>(content: S) -> Result<Self, M::Error>
where
S: Into<String>,
M: Markup,
{
let content = M::make_handle(content)?;
Ok(StyledString { content })
}
/// Sets the content of this string. /// Sets the content of this string.
/// ///
/// The content will be parsed; if an error is found, /// The content will be parsed; if an error is found,
/// it will be returned here (and the content will be unchanged). /// it will be returned here (and the content will be unchanged).
pub fn set_content<S>(&mut self, content: S) -> Result<(), M::Error> pub fn set_content<S, M>(&mut self, content: S) -> Result<(), M::Error>
where where
S: Into<String>, S: Into<String>,
M: Markup,
{ {
self.content = Self::make_handle(content)?; self.content = M::make_handle(content)?;
Ok(()) Ok(())
} }