|
| 1 | +use std::collections::BTreeSet; |
| 2 | +use std::fmt; |
| 3 | +use std::marker::PhantomData; |
| 4 | +use std::str::FromStr; |
| 5 | + |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | + |
| 8 | +/// Append-only templates for sorted, deduplicated lists of items. |
| 9 | +/// |
| 10 | +/// Last line of the rendered output is a comment encoding the next insertion point. |
| 11 | +#[derive(Debug, Clone)] |
| 12 | +pub(crate) struct SortedTemplate<F> { |
| 13 | + format: PhantomData<F>, |
| 14 | + before: String, |
| 15 | + after: String, |
| 16 | + contents: BTreeSet<String>, |
| 17 | +} |
| 18 | + |
| 19 | +/// Written to last line of file to specify the location of each fragment |
| 20 | +#[derive(Serialize, Deserialize, Debug, Clone)] |
| 21 | +struct Offset { |
| 22 | + /// Index of the first byte in the template |
| 23 | + start: usize, |
| 24 | + /// The length of each fragment in the encoded template, including the separator |
| 25 | + delta: Vec<usize>, |
| 26 | +} |
| 27 | + |
| 28 | +impl<F> SortedTemplate<F> { |
| 29 | + /// Generate this template from arbitary text. |
| 30 | + /// Will insert wherever the substring `magic` can be found. |
| 31 | + /// Errors if it does not appear exactly once. |
| 32 | + pub(crate) fn magic(template: &str, magic: &str) -> Result<Self, Error> { |
| 33 | + let mut split = template.split(magic); |
| 34 | + let before = split.next().ok_or(Error)?; |
| 35 | + let after = split.next().ok_or(Error)?; |
| 36 | + if split.next().is_some() { |
| 37 | + return Err(Error); |
| 38 | + } |
| 39 | + Ok(Self::before_after(before, after)) |
| 40 | + } |
| 41 | + |
| 42 | + /// Template will insert contents between `before` and `after` |
| 43 | + pub(crate) fn before_after<S: ToString, T: ToString>(before: S, after: T) -> Self { |
| 44 | + let before = before.to_string(); |
| 45 | + let after = after.to_string(); |
| 46 | + SortedTemplate { format: PhantomData, before, after, contents: Default::default() } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl<F: FileFormat> SortedTemplate<F> { |
| 51 | + /// Adds this text to the template |
| 52 | + pub(crate) fn append(&mut self, insert: String) { |
| 53 | + self.contents.insert(insert); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl<F: FileFormat> fmt::Display for SortedTemplate<F> { |
| 58 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 59 | + let mut delta = Vec::default(); |
| 60 | + write!(f, "{}", self.before)?; |
| 61 | + let contents: Vec<_> = self.contents.iter().collect(); |
| 62 | + let mut sep = ""; |
| 63 | + for content in contents { |
| 64 | + delta.push(sep.len() + content.len()); |
| 65 | + write!(f, "{}{}", sep, content)?; |
| 66 | + sep = F::SEPARATOR; |
| 67 | + } |
| 68 | + let offset = Offset { start: self.before.len(), delta }; |
| 69 | + let offset = serde_json::to_string(&offset).unwrap(); |
| 70 | + write!(f, "{}\n{}{}{}", self.after, F::COMMENT_START, offset, F::COMMENT_END)?; |
| 71 | + Ok(()) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +fn checked_split_at(s: &str, index: usize) -> Option<(&str, &str)> { |
| 76 | + s.is_char_boundary(index).then(|| s.split_at(index)) |
| 77 | +} |
| 78 | + |
| 79 | +impl<F: FileFormat> FromStr for SortedTemplate<F> { |
| 80 | + type Err = Error; |
| 81 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 82 | + let (s, offset) = s.rsplit_once("\n").ok_or(Error)?; |
| 83 | + let offset = offset.strip_prefix(F::COMMENT_START).ok_or(Error)?; |
| 84 | + let offset = offset.strip_suffix(F::COMMENT_END).ok_or(Error)?; |
| 85 | + let offset: Offset = serde_json::from_str(&offset).map_err(|_| Error)?; |
| 86 | + let (before, mut s) = checked_split_at(s, offset.start).ok_or(Error)?; |
| 87 | + let mut contents = BTreeSet::default(); |
| 88 | + let mut sep = ""; |
| 89 | + for &index in offset.delta.iter() { |
| 90 | + let (content, rest) = checked_split_at(s, index).ok_or(Error)?; |
| 91 | + s = rest; |
| 92 | + let content = content.strip_prefix(sep).ok_or(Error)?; |
| 93 | + contents.insert(content.to_string()); |
| 94 | + sep = F::SEPARATOR; |
| 95 | + } |
| 96 | + Ok(SortedTemplate { |
| 97 | + format: PhantomData, |
| 98 | + before: before.to_string(), |
| 99 | + after: s.to_string(), |
| 100 | + contents, |
| 101 | + }) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +pub(crate) trait FileFormat { |
| 106 | + const COMMENT_START: &'static str; |
| 107 | + const COMMENT_END: &'static str; |
| 108 | + const SEPARATOR: &'static str; |
| 109 | +} |
| 110 | + |
| 111 | +#[derive(Debug, Clone)] |
| 112 | +pub(crate) struct Html; |
| 113 | + |
| 114 | +impl FileFormat for Html { |
| 115 | + const COMMENT_START: &'static str = "<!--"; |
| 116 | + const COMMENT_END: &'static str = "-->"; |
| 117 | + const SEPARATOR: &'static str = ""; |
| 118 | +} |
| 119 | + |
| 120 | +#[derive(Debug, Clone)] |
| 121 | +pub(crate) struct Js; |
| 122 | + |
| 123 | +impl FileFormat for Js { |
| 124 | + const COMMENT_START: &'static str = "//"; |
| 125 | + const COMMENT_END: &'static str = ""; |
| 126 | + const SEPARATOR: &'static str = ","; |
| 127 | +} |
| 128 | + |
| 129 | +#[derive(Debug, Clone)] |
| 130 | +pub(crate) struct Error; |
| 131 | + |
| 132 | +impl fmt::Display for Error { |
| 133 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 134 | + write!(f, "invalid template") |
| 135 | + } |
| 136 | +} |
0 commit comments