add parse method to Parseable trait for easy parsing

This commit is contained in:
John Turner
2025-11-30 22:44:22 +00:00
parent abf784a784
commit b753519a3e

View File

@@ -21,12 +21,24 @@
)]
#![feature(impl_trait_in_assoc_type)]
use mon::{Parser, input::Input};
use mon::{
Parser,
input::{Input, InputIter},
};
pub trait Parseable<'a, I: Input + 'a> {
type Parser: Parser<I, Output = Self>;
fn parser() -> Self::Parser;
fn parse(input: I) -> Result<Self, I>
where
Self: Sized,
{
Self::parser()
.parse_finished(InputIter::new(input))
.map_err(|e| e.rest())
}
}
/// Strongly typed atom and cpv representations.
@@ -34,10 +46,9 @@ pub trait Parseable<'a, I: Input + 'a> {
/// Create atoms from parsers:
/// ```
/// use gentoo_utils::{Parseable, atom::Atom};
/// use mon::{Parser, input::InputIter};
///
/// let it = InputIter::new("=app-editors/emacs-31.0-r1");
/// let emacs = Atom::parser().parse_finished(it).unwrap();
/// let emacs = Atom::parse("=app-editors/emacs-31.0-r1")
/// .expect("failed to parse atom");
///
/// assert_eq!(emacs.to_string(), "=app-editors/emacs-31.0-r1");
/// ````
@@ -45,15 +56,9 @@ pub trait Parseable<'a, I: Input + 'a> {
/// Compare versions:
/// ```
/// use gentoo_utils::{Parseable, atom::Cpv};
/// use mon::{Parser, input::InputIter};
///
/// let a = Cpv::parser()
/// .parse_finished(InputIter::new("foo/bar-1.0"))
/// .unwrap();
///
/// let b = Cpv::parser()
/// .parse_finished(InputIter::new("foo/bar-2.0"))
/// .unwrap();
/// let a = Cpv::parse("foo/bar-1.0").unwrap();
/// let b = Cpv::parse("foo/bar-2.0").unwrap();
///
/// assert!(a < b);
/// ```