use std::{
borrow::Borrow,
collections::HashMap,
fmt::{Debug, Display, Formatter},
sync::Arc,
};
use nom::{
branch::alt,
bytes::complete::take_while,
character::complete::{char, satisfy, space1},
combinator::{iterator, recognize},
sequence::preceded,
Parser,
};
use crate::{amount, empty_line, end_of_line, string, Currency, Decimal, IResult, Span};
pub type Map<D> = HashMap<Key, Value<D>>;
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Key(Arc<str>);
impl Display for Key {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
impl AsRef<str> for Key {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl Borrow<str> for Key {
fn borrow(&self) -> &str {
self.0.borrow()
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Value<D> {
String(String),
Number(D),
Currency(Currency),
}
pub(crate) fn parse<D: Decimal>(input: Span<'_>) -> IResult<'_, Map<D>> {
let mut iter = iterator(input, alt((entry.map(Some), empty_line.map(|()| None))));
let map: HashMap<_, _> = iter.flatten().collect();
let (input, ()) = iter.finish()?;
Ok((input, map))
}
fn entry<D: Decimal>(input: Span<'_>) -> IResult<'_, (Key, Value<D>)> {
let (input, _) = space1(input)?;
let (input, key) = recognize(preceded(
satisfy(char::is_lowercase),
take_while(|c: char| c.is_alphanumeric() || c == '-' || c == '_'),
))(input)?;
let (input, _) = char(':')(input)?;
let (input, _) = space1(input)?;
let (input, value) = alt((
string.map(Value::String),
amount::expression.map(Value::Number),
amount::currency.map(Value::Currency),
))(input)?;
let (input, ()) = end_of_line(input)?;
Ok((input, (Key((*key.fragment()).into()), value)))
}