oxedyne/fe2o3/fe2o3_text/src/csl/page.rs
6.1 KiB, 1 run
created by r1870400018:73629, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Ported from hayagriva 0.10.1 (`src/types/page.rs`) and citationberg 0.7.0 |
| 2 | //! (`PageRangeFormat::format`), Copyright (c) Martin Haug and the hayagriva contributors, |
| 3 | //! MIT OR Apache-2.0. |
| 4 | use crate::csl::{ |
| 5 | item::Numeric, |
| 6 | style::PageRange, |
| 7 | }; |
| 8 | |
| 9 | use std::fmt::Write; |
| 10 | |
| 11 | |
| 12 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 13 | pub enum PagePart { |
| 14 | Ampersand, |
| 15 | Comma, |
| 16 | Escaped(Numeric, Numeric), // `12\-15`, always written expanded |
| 17 | Single(Numeric), |
| 18 | Range(Numeric, Numeric), |
| 19 | } |
| 20 | |
| 21 | /// A `page` value that parsed as pages, ranges and the `,` and `&` between them. |
| 22 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 23 | pub struct PageRanges(pub Vec<PagePart>); |
| 24 | |
| 25 | /// The `page` variable: typed when it parsed, otherwise the string as given. |
| 26 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 27 | pub enum PageVal { |
| 28 | Typed(PageRanges), |
| 29 | Str(String), |
| 30 | } |
| 31 | |
| 32 | impl PageVal { |
| 33 | /// Reads a page value as hayagriva's `MaybeTyped::infallible_from_str` does. |
| 34 | pub fn from_str(s: &str) -> Self { |
| 35 | match PageRanges::parse(s) { |
| 36 | Some(p) => Self::Typed(p), |
| 37 | None => Self::Str(s.to_string()), |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /// Is it plural for a label? A string never is (hayagriva). |
| 42 | pub fn is_plural(&self) -> bool { |
| 43 | match self { |
| 44 | Self::Typed(p) => p.is_plural(), |
| 45 | Self::Str(_) => false, |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl PageRanges { |
| 51 | |
| 52 | /// Parses runs split at `,` and `&` (each its own part), then each run as a page, `a-b`, |
| 53 | /// `a–b` or the escaped `a\-b`. `None` when any run fails. |
| 54 | pub fn parse(s: &str) -> Option<Self> { |
| 55 | let mut parts = Vec::new(); |
| 56 | let mut run = String::new(); |
| 57 | let flush = |run: &mut String, parts: &mut Vec<PagePart>| -> bool { |
| 58 | if run.is_empty() { |
| 59 | return true; |
| 60 | } |
| 61 | let r = PagePart::parse(run); |
| 62 | run.clear(); |
| 63 | match r { |
| 64 | Some(p) => { parts.push(p); true } |
| 65 | None => false, |
| 66 | } |
| 67 | }; |
| 68 | for c in s.chars() { |
| 69 | if c == ',' || c == '&' { |
| 70 | if !flush(&mut run, &mut parts) { |
| 71 | return None; |
| 72 | } |
| 73 | parts.push(if c == ',' { PagePart::Comma } else { PagePart::Ampersand }); |
| 74 | } else { |
| 75 | run.push(c); |
| 76 | } |
| 77 | } |
| 78 | if !flush(&mut run, &mut parts) { |
| 79 | return None; |
| 80 | } |
| 81 | Some(Self(parts)) |
| 82 | } |
| 83 | |
| 84 | /// Is there more than one page? A range of distinct ends counts at once. |
| 85 | pub fn is_plural(&self) -> bool { |
| 86 | let mut count = 0; |
| 87 | for p in &self.0 { |
| 88 | match p { |
| 89 | PagePart::Single(_) => count += 1, |
| 90 | PagePart::Range(s, e) | PagePart::Escaped(s, e) => { |
| 91 | if s != e { |
| 92 | return true; |
| 93 | } |
| 94 | count += 1; |
| 95 | } |
| 96 | _ => {} |
| 97 | } |
| 98 | } |
| 99 | count > 1 |
| 100 | } |
| 101 | |
| 102 | /// Writes the ranges in a `page-range-format` (hayagriva's default is expanded), the range |
| 103 | /// delimiter being the locale's `page-range-delimiter` term or an en dash. |
| 104 | pub fn write<W: Write>(&self, w: &mut W, fmt: Option<PageRange>, delim: Option<&str>) { |
| 105 | let fmt = fmt.unwrap_or(PageRange::Expanded); |
| 106 | for p in &self.0 { |
| 107 | match p { |
| 108 | PagePart::Ampersand => { let _ = w.write_str(" & "); } |
| 109 | PagePart::Comma => { let _ = w.write_str(", "); } |
| 110 | PagePart::Escaped(s, e) => format_range(w, PageRange::Expanded, &s.to_string(), &e.to_string(), delim), |
| 111 | PagePart::Single(s) => { let _ = w.write_str(&s.to_string()); } |
| 112 | PagePart::Range(s, e) => format_range(w, fmt, &s.to_string(), &e.to_string(), delim), |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | impl PagePart { |
| 119 | fn parse(s: &str) -> Option<Self> { |
| 120 | let s = s.trim(); |
| 121 | if s.is_empty() { |
| 122 | return None; |
| 123 | } |
| 124 | if s.contains("\\-") { |
| 125 | let mut it = s.split("\\-").map(str::trim); |
| 126 | let a = Numeric::parse(it.next().unwrap_or("")); |
| 127 | let b = Numeric::parse(it.next().unwrap_or("")); |
| 128 | if it.next().is_some() { |
| 129 | return None; |
| 130 | } |
| 131 | return match (a, b) { |
| 132 | (Some(a), Some(b)) => Some(Self::Escaped(a, b)), |
| 133 | _ => None, |
| 134 | }; |
| 135 | } |
| 136 | let mut it = s.split(['-', '–']).map(str::trim); |
| 137 | let a = it.next().and_then(Numeric::parse); |
| 138 | let r = match (a, it.next()) { |
| 139 | (Some(a), None) => Self::Single(a), |
| 140 | (Some(a), Some(b)) => match Numeric::parse(b) { |
| 141 | Some(b) => Self::Range(a, b), |
| 142 | None => return None, |
| 143 | }, |
| 144 | (None, _) => return None, |
| 145 | }; |
| 146 | if it.next().is_some() { |
| 147 | return None; |
| 148 | } |
| 149 | Some(r) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | /// citationberg's `PageRangeFormat::format`. `chicago` is `chicago-15`, as in citationberg. |
| 154 | pub fn format_range<W: Write>(w: &mut W, fmt: PageRange, start: &str, end: &str, delim: Option<&str>) { |
| 155 | let sep = delim.unwrap_or("–"); |
| 156 | let start = start.trim(); |
| 157 | let end = end.trim(); |
| 158 | let (spre, x) = split_digit_suffix(start); |
| 159 | let (epre, y) = split_digit_suffix(end); |
| 160 | if spre != epre { |
| 161 | let _ = write!(w, "{}{}{}", start, sep, end); |
| 162 | return; |
| 163 | } |
| 164 | let (xl, yl) = (x.len(), y.len()); |
| 165 | // A shorter end is shorthand (`101-7`): its missing digits come from the start. |
| 166 | let y = if xl <= yl { y.to_string() } else { format!("{}{}", &x[..xl - yl], y) }; |
| 167 | let _ = write!(w, "{}{}{}", spre, x, sep); |
| 168 | let chicago = matches!(fmt, PageRange::Chicago | PageRange::Chicago15 | PageRange::Chicago16); |
| 169 | let c15 = matches!(fmt, PageRange::Chicago | PageRange::Chicago15); |
| 170 | match fmt { |
| 171 | _ if chicago && (xl < 3 || x.ends_with("00")) => { let _ = w.write_str(&y); } |
| 172 | _ if chicago && x[xl - 2..].starts_with('0') => minimal(w, 1, x, &y), |
| 173 | _ if c15 && xl == 4 && changed_digits(x, &y) >= 3 => { let _ = w.write_str(&y); } |
| 174 | PageRange::Chicago | PageRange::Chicago15 | PageRange::Chicago16 => minimal(w, 2, x, &y), |
| 175 | // Only expanded repeats a shared prefix on the end: `S1–S12`, where the others give `S1–12`. |
| 176 | PageRange::Expanded => { let _ = write!(w, "{}{}", spre, y); } |
| 177 | PageRange::Minimal => minimal(w, 1, x, &y), |
| 178 | PageRange::MinimalTwo => minimal(w, 2, x, &y), |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | fn changed_digits(x: &str, y: &str) -> usize { |
| 183 | let x = if x.len() < y.len() { format!("{}{}", " ".repeat(y.len() - x.len()), x) } else { x.to_string() }; |
| 184 | for (i, (c, d)) in x.chars().rev().zip(y.chars().rev()).enumerate() { |
| 185 | if c == d { |
| 186 | return i; |
| 187 | } |
| 188 | } |
| 189 | x.len() |
| 190 | } |
| 191 | |
| 192 | fn minimal<W: Write>(w: &mut W, thresh: usize, x: &str, y: &str) { |
| 193 | if y.len() > x.len() { |
| 194 | let _ = w.write_str(y); |
| 195 | return; |
| 196 | } |
| 197 | let ys: String = x.chars().zip(y.chars()).skip_while(|(c, d)| c == d).map(|(_, d)| d).collect(); |
| 198 | if ys.len() < thresh && y.len() >= thresh { |
| 199 | let _ = w.write_str(&y[y.len() - thresh..]); |
| 200 | } else { |
| 201 | let _ = w.write_str(&ys); |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | fn split_digit_suffix(s: &str) -> (&str, &str) { |
| 206 | let n = s.chars().rev().take_while(|c| c.is_ascii_digit()).count(); |
| 207 | s.split_at(s.len() - n) |
| 208 | } |