texlab/citation/field/
number.rs

1use std::{fmt, str::FromStr};
2
3use strum::EnumString;
4
5use crate::syntax::bibtex::Value;
6
7use super::text::TextFieldData;
8
9#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, EnumString)]
10#[strum(ascii_case_insensitive)]
11pub enum NumberField {
12    Edition,
13    Number,
14    Pages,
15    PageTotal,
16    Part,
17    Volume,
18    Volumes,
19}
20
21impl NumberField {
22    pub fn parse(input: &str) -> Option<Self> {
23        Self::from_str(input).ok()
24    }
25}
26
27#[derive(Debug, PartialEq, Eq, Clone, Hash)]
28pub enum NumberFieldData {
29    Scalar(u32),
30    Range(u32, u32),
31    Other(String),
32}
33
34impl fmt::Display for NumberFieldData {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            Self::Scalar(value) => write!(f, "{}", value),
38            Self::Range(start, end) => write!(f, "{}-{}", start, end),
39            Self::Other(value) => write!(f, "{}", value.replace("--", "-")),
40        }
41    }
42}
43
44impl NumberFieldData {
45    pub fn parse(value: &Value) -> Option<Self> {
46        let TextFieldData { text } = TextFieldData::parse(value)?;
47        text.split_once("--")
48            .or_else(|| text.split_once('-'))
49            .and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
50            .map(|(a, b)| Self::Range(a, b))
51            .or_else(|| text.parse().ok().map(Self::Scalar))
52            .or(Some(Self::Other(text)))
53    }
54}