hayagriva 0.10.1

Work with references: Literature database management, storage, and citation formatting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::borrow::Cow;
use std::convert::{TryFrom, TryInto};
use std::fmt::Write;
use std::fmt::{self, Display};
use std::str::FromStr;

use citationberg::{GrammarGender, NumberForm, OrdinalLookup};
use serde::de::Visitor;
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use unscanny::Scanner;

use super::MaybeTyped;

/// A numeric value that can be pluralized.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Numeric {
    /// The numeric value.
    pub value: NumericValue,
    /// A string that is prepended to the value.
    pub prefix: Option<Box<String>>,
    /// A string that is appended to the value.
    pub suffix: Option<Box<String>>,
}

impl<'de> Deserialize<'de> for Numeric {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;
        struct OurVisitor;

        /// The visitor parses numbers and strings.
        impl Visitor<'_> for OurVisitor {
            type Value = Numeric;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a numeric value with optional prefix and suffix")
            }

            /// A default serde fallthrough handler for unsigned integers.
            fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
                Ok(Numeric::new(v.try_into().map_err(|_| E::custom("value too large"))?))
            }

            /// A default serde fallthrough handler for signed integers.
            fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
                Ok(Numeric::new(
                    v.try_into().map_err(|_| E::custom("value out of bounds"))?,
                ))
            }

            fn visit_i32<E: Error>(self, v: i32) -> Result<Self::Value, E> {
                Ok(Numeric::new(v))
            }

            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
                Self::Value::from_str(v).map_err(|e| E::custom(e.to_string()))
            }
        }

        deserializer.deserialize_any(OurVisitor)
    }
}

impl Serialize for Numeric {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self.value {
            NumericValue::Number(n) if self.will_transform() => {
                serializer.serialize_i32(n)
            }
            _ => serializer.serialize_str(&self.to_string()),
        }
    }
}

impl Numeric {
    /// Creates a new `Numeric` from a number.
    pub fn new(value: i32) -> Self {
        Self {
            value: NumericValue::Number(value),
            prefix: None,
            suffix: None,
        }
    }

    /// Creates a new `Numeric` from a range.
    pub fn from_range(range: std::ops::Range<i32>) -> Self {
        Self {
            value: NumericValue::Set(vec![
                (range.start, Some(NumericDelimiter::Hyphen)),
                (range.end, None),
            ]),
            prefix: None,
            suffix: None,
        }
    }

    /// Whether the numeric value contains only numbers.
    pub fn will_transform(&self) -> bool {
        self.prefix.is_none() && self.suffix.is_none()
    }

    /// Retrieve the prefix string slice.
    pub fn prefix_str(&self) -> Option<&str> {
        self.prefix.as_deref().map(String::as_str)
    }

    /// Retrieve the suffix string slice.
    pub fn suffix_str(&self) -> Option<&str> {
        self.suffix.as_deref().map(String::as_str)
    }

    /// Format the value without the prefix and suffix.
    pub fn fmt_value<T>(&self, buf: &mut T, machine_readable: bool) -> std::fmt::Result
    where
        T: fmt::Write,
    {
        let format = |n: i32, buf: &mut T| -> std::fmt::Result { write!(buf, "{n}") };

        match &self.value {
            &NumericValue::Number(n) => format(n, buf)?,
            NumericValue::Set(s) => {
                for &(n, sep) in s {
                    format(n, buf)?;
                    if let Some(sep) = sep {
                        if machine_readable {
                            buf.write_char(sep.as_char())?
                        } else {
                            write!(buf, "{sep}")?
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn fmt_custom<T>(&self, buf: &mut T, machine_readable: bool) -> std::fmt::Result
    where
        T: fmt::Write,
    {
        if let Some(prefix) = &self.prefix {
            buf.write_str(prefix)?;
        }
        self.fmt_value(buf, machine_readable)?;
        if let Some(suffix) = &self.suffix {
            buf.write_str(suffix)?;
        }

        Ok(())
    }

    /// Format the value with a given form.
    pub fn with_form<T>(
        &self,
        buf: &mut T,
        form: NumberForm,
        gender: Option<GrammarGender>,
        ords: &OrdinalLookup<'_>,
    ) -> std::fmt::Result
    where
        T: Write,
    {
        let format = |n: i32, buf: &mut T| -> std::fmt::Result {
            match form {
                NumberForm::Ordinal => {
                    write!(buf, "{}{}", n, ords.lookup(n, gender).unwrap_or_default())
                }
                NumberForm::LongOrdinal => match ords.lookup_long(n) {
                    Some(str) => buf.write_str(str),
                    None => {
                        write!(buf, "{}{}", n, ords.lookup(n, gender).unwrap_or_default())
                    }
                },
                NumberForm::Roman => match roman_numerals_rs::RomanNumeral::try_from(n) {
                    Ok(roman) => write!(buf, "{:x}", roman),
                    Err(_) => write!(buf, "{n}"),
                },
                NumberForm::Numeric => write!(buf, "{n}"),
            }
        };

        match &self.value {
            &NumericValue::Number(n) => format(n, buf)?,
            NumericValue::Set(s) => {
                for &(n, sep) in s {
                    format(n, buf)?;
                    if let Some(sep) = sep {
                        write!(buf, "{sep}")?
                    }
                }
            }
        }

        Ok(())
    }

    /// Whether the numeric value is plural.
    pub fn is_plural(&self, is_number_of: bool) -> bool {
        match &self.value {
            NumericValue::Number(n) if is_number_of => n != &1,
            NumericValue::Number(_) => false,
            NumericValue::Set(vec) => vec.len() != 1,
        }
    }

    /// Whether the value is a single number with no prefix or suffix.
    pub fn single_number(&self) -> Option<i32> {
        (self.prefix.is_none() && self.suffix.is_none())
            .then_some(match &self.value {
                NumericValue::Number(n) => Some(*n),
                _ => None,
            })
            .flatten()
    }

    /// Returns the nth number in the set.
    pub fn nth(&self, n: usize) -> Option<i32> {
        self.value.nth(n)
    }

    /// Order the values according to CSL rules.
    pub(crate) fn csl_cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.value.into_iter().cmp(&other.value)
    }
}

impl MaybeTyped<Cow<'_, Numeric>> {
    /// Order the values according to CSL rules.
    pub(crate) fn csl_cmp(&self, other: &Self) -> std::cmp::Ordering {
        match (self, other) {
            (MaybeTyped::Typed(a), MaybeTyped::Typed(b)) => a.csl_cmp(b),
            _ => self.to_string().cmp(&other.to_string()),
        }
    }
}

impl FromStr for Numeric {
    type Err = NumericError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let mut s = Scanner::new(value);
        s.eat_whitespace();

        let prefix = {
            // Eat non-numeric characters and leading zeros.
            let start = s.cursor();
            s.eat_while(|c: char| !c.is_numeric() && c != '-');
            let zeros = s.eat_while('0');
            if !zeros.is_empty() && s.peek().is_none_or(|c| !c.is_numeric()) {
                // Uneat the last zero if the value is just zero.
                s.uneat();
            }
            s.from(start)
        };

        let value = number(&mut s).ok_or(NumericError::NoNumber)?;
        let space_after_value = s.eat_whitespace();

        let value = match s.peek() {
            Some(c) if is_delimiter(c) => {
                s.eat();
                s.eat_until(|c: char| !is_delimiter(c));
                let mut items = vec![(value, Some(NumericDelimiter::try_from(c)?))];
                loop {
                    s.eat_whitespace();
                    let num = number(&mut s).ok_or(NumericError::NoNumber)?;
                    s.eat_whitespace();
                    match NumericDelimiter::from_str(s.eat_while(is_delimiter)) {
                        Ok(d) => {
                            items.push((num, Some(d)));
                        }
                        Err(_) => {
                            items.push((num, None));
                            break;
                        }
                    }
                }
                NumericValue::Set(items)
            }

            _ => NumericValue::Number(value),
        };
        s.eat_whitespace();
        let post = s.eat_while(|c: char| !c.is_numeric() && !c.is_whitespace());

        if !s.after().is_empty() {
            return Err(NumericError::UnexpectedCharactersAfterPostfix);
        }

        Ok(Self {
            value,
            prefix: if prefix.is_empty() {
                None
            } else {
                Some(Box::new(prefix.to_string()))
            },
            suffix: if post.is_empty() {
                None
            } else {
                Some(Box::new(format!("{space_after_value}{post}")))
            },
        })
    }
}

impl From<i32> for Numeric {
    fn from(n: i32) -> Self {
        Self::new(n)
    }
}

impl From<u32> for Numeric {
    fn from(n: u32) -> Self {
        Self::new(n as i32)
    }
}

/// Error when parsing a numeric value.
#[derive(Debug, Clone, Copy, Error, PartialEq, Eq)]
pub enum NumericError {
    /// No number was found.
    #[error("no number found")]
    NoNumber,
    /// Unexpected characters after the postfix. It must not contain any
    /// non-whitespace characters.
    #[error("unexpected characters after postfix")]
    UnexpectedCharactersAfterPostfix,
    /// The string is not a delimiter.
    #[error("not a delimiter")]
    NotADelimiter,
    /// The string does not contain a delimiter.
    #[error("missing delimiter")]
    MissingDelimiter,
}

/// Eat a number from the scanner, assuming leading whitespaces and zeros have
/// already been eaten.
///
/// The number can be positive, negative, or zero.
fn number(s: &mut Scanner) -> Option<i32> {
    let negative = s.eat_if('-');
    let num = s.eat_while(|c: char| c.is_numeric());
    if num.is_empty() {
        return None;
    }

    num.parse::<i32>().ok().map(|n| if negative { -n } else { n })
}

impl Display for Numeric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_custom(f, false)
    }
}

/// The numeric value.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum NumericValue {
    /// A single number.
    Number(i32),
    /// A set of numbers.
    Set(Vec<(i32, Option<NumericDelimiter>)>),
}

impl NumericValue {
    /// Return the length of the numeric value.
    pub fn len(&self) -> usize {
        match self {
            NumericValue::Number(_) => 1,
            NumericValue::Set(vec) => vec.len(),
        }
    }

    /// Whether the numeric value is an empty set.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the nth number in the set.
    fn nth(&self, n: usize) -> Option<i32> {
        match self {
            NumericValue::Number(val) if n == 0 => Some(*val),
            NumericValue::Number(_) => None,
            NumericValue::Set(vec) => vec.get(n).map(|(val, _)| *val),
        }
    }
}

/// An iterator over the numbers in a numeric value.
pub struct NumIterator<'a> {
    num: &'a NumericValue,
    idx: usize,
}

impl Iterator for NumIterator<'_> {
    type Item = i32;

    fn next(&mut self) -> Option<Self::Item> {
        let val = self.num.nth(self.idx);
        self.idx += 1;
        val
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.num.len() - self.idx;
        (len, Some(len))
    }
}

impl ExactSizeIterator for NumIterator<'_> {
    fn len(&self) -> usize {
        self.size_hint().0
    }
}

impl<'a> IntoIterator for &'a NumericValue {
    type Item = i32;
    type IntoIter = NumIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        NumIterator { num: self, idx: 0 }
    }
}

/// Delimits individual numbers in a numeric value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NumericDelimiter {
    /// A comma.
    Comma,
    /// An ampersand.
    Ampersand,
    /// A hyphen. Will be converted to an en dash for display.
    Hyphen,
}

impl NumericDelimiter {
    /// Get the character representation of the delimiter.
    pub fn as_char(&self) -> char {
        match self {
            NumericDelimiter::Comma => ',',
            NumericDelimiter::Ampersand => '&',
            NumericDelimiter::Hyphen => '-',
        }
    }
}

impl std::fmt::Display for NumericDelimiter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NumericDelimiter::Comma => f.write_str(", "),
            NumericDelimiter::Ampersand => f.write_str(" & "),
            NumericDelimiter::Hyphen => f.write_char(''),
        }
    }
}

fn is_delimiter(c: char) -> bool {
    c == ',' || c == '&' || c == '-' || c == ''
}

impl FromStr for NumericDelimiter {
    type Err = NumericError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let first_char = s.chars().next().ok_or(NumericError::MissingDelimiter)?;
        if first_char != '-' && s.len() > first_char.len_utf8() {
            return Err(NumericError::NotADelimiter);
        }

        Self::try_from(first_char)
    }
}

impl TryFrom<char> for NumericDelimiter {
    type Error = NumericError;

    fn try_from(c: char) -> Result<Self, Self::Error> {
        match c {
            ',' => Ok(NumericDelimiter::Comma),
            '&' => Ok(NumericDelimiter::Ampersand),
            '-' | '' => Ok(NumericDelimiter::Hyphen),
            _ => Err(NumericError::NotADelimiter),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_mixed_range() {
        let s = "34,37--39";
        let n: Numeric = s.parse().unwrap();
        assert_eq!(
            n.value,
            NumericValue::Set(vec![
                (34, Some(NumericDelimiter::Comma)),
                (37, Some(NumericDelimiter::Hyphen)),
                (39, None)
            ])
        );
    }
}