use std::collections::{BTreeMap, BTreeSet};
use std::hash::{Hash, Hasher};
use crate::stdlib::backends::pres::LIST_RESERVED_KINDS;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum QuoteSection {
Text,
Lines,
Attributed,
Block,
}
impl QuoteSection {
pub const ALL: [QuoteSection; 4] =
[QuoteSection::Text, QuoteSection::Lines, QuoteSection::Attributed, QuoteSection::Block];
pub fn as_str(self) -> &'static str {
match self {
QuoteSection::Text => "text",
QuoteSection::Lines => "lines",
QuoteSection::Attributed => "attributed",
QuoteSection::Block => "block",
}
}
pub fn parse(name: &str) -> Option<QuoteSection> {
QuoteSection::ALL.into_iter().find(|section| section.as_str() == name)
}
pub fn role(self) -> &'static str {
match self {
QuoteSection::Text => super::TEXT_ROLE,
QuoteSection::Lines => super::LINES_ROLE,
QuoteSection::Attributed => super::ATTRIBUTED_ROLE,
QuoteSection::Block => super::BLOCK_ROLE,
}
}
pub fn is_inline(self) -> bool {
!matches!(self, QuoteSection::Block)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct QuoteEnvironment {
pub sections: BTreeSet<QuoteSection>,
pub bare: Option<QuoteSection>,
}
impl QuoteEnvironment {
pub fn new(sections: impl IntoIterator<Item = QuoteSection>) -> QuoteEnvironment {
QuoteEnvironment { sections: sections.into_iter().collect(), bare: None }
}
pub fn bare(mut self, kind: QuoteSection) -> QuoteEnvironment {
self.bare = Some(kind);
self
}
pub fn enables(&self, section: QuoteSection) -> bool {
self.sections.contains(§ion)
}
pub fn holds_blocks(&self) -> bool {
self.bare.is_none_or(|kind| !kind.is_inline())
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct QuoteConfig {
pub environments: BTreeMap<String, QuoteEnvironment>,
}
impl Default for QuoteConfig {
fn default() -> QuoteConfig {
QuoteConfig::new()
}
}
impl QuoteConfig {
pub fn new() -> QuoteConfig {
QuoteConfig::empty()
.environment("quote", QuoteEnvironment::new(QuoteSection::ALL))
.environment("blockquote", QuoteEnvironment::new([]).bare(QuoteSection::Block))
.environment("address", QuoteEnvironment::new([]).bare(QuoteSection::Lines))
}
pub fn empty() -> QuoteConfig {
QuoteConfig { environments: BTreeMap::new() }
}
pub fn environment(mut self, name: impl Into<String>, environment: QuoteEnvironment) -> QuoteConfig {
self.environments.insert(name.into(), environment);
self
}
pub fn without_environment(mut self, name: &str) -> QuoteConfig {
self.environments.remove(name);
self
}
pub fn get(&self, name: &str) -> Option<&QuoteEnvironment> {
self.environments.get(name)
}
pub fn validate(&self) -> Result<(), String> {
for (name, environment) in &self.environments {
if name.is_empty()
|| name.chars().any(|ch| ch.is_whitespace() || matches!(ch, '{' | '}' | '\\' | '%'))
{
return Err(format!(
"the quote environment name `{name}` must not be empty or contain \
whitespace, a brace, a backslash or `%`"
));
}
if LIST_RESERVED_KINDS.contains(&name.as_str()) {
let reserved = LIST_RESERVED_KINDS.iter().map(|kind| format!("`{kind}`"));
return Err(format!(
"the quote environment name `{name}` is reserved: a quote environment must \
not be named {}",
english_list(reserved, "or")
));
}
if environment.sections.is_empty() && environment.bare.is_none() {
let sections: Vec<String> = QuoteSection::ALL
.iter()
.map(|section| format!("`\\{}`", section.as_str()))
.collect();
return Err(format!(
"the quote environment `{name}` must accept at least one of {}, or content \
outside them",
sections.join(", ")
));
}
}
Ok(())
}
pub fn digest_bytes(&self) -> Vec<u8> {
let QuoteConfig { environments } = self;
let mut out = Vec::new();
push_len(&mut out, environments.len());
for (name, environment) in environments {
let QuoteEnvironment { sections, bare } = environment;
push_len(&mut out, name.len());
out.extend_from_slice(name.as_bytes());
push_len(&mut out, sections.len());
out.extend(sections.iter().map(|section| section_byte(*section)));
out.push(bare.map_or(0, |kind| section_byte(kind) + 1));
}
out
}
}
pub(super) fn english_list(items: impl IntoIterator<Item = String>, conjunction: &str) -> String {
let mut items: Vec<String> = items.into_iter().collect();
let last = items.pop().unwrap_or_default();
if items.is_empty() { last } else { format!("{} {conjunction} {last}", items.join(", ")) }
}
fn section_byte(section: QuoteSection) -> u8 {
match section {
QuoteSection::Text => 0,
QuoteSection::Lines => 1,
QuoteSection::Attributed => 2,
QuoteSection::Block => 3,
}
}
fn push_len(out: &mut Vec<u8>, len: usize) {
out.extend_from_slice(&(len as u64).to_le_bytes());
}
impl Hash for QuoteConfig {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.digest_bytes());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_shipped_environments_are_the_three_of_the_python_product() {
let config = QuoteConfig::new();
let names: Vec<&str> = config.environments.keys().map(String::as_str).collect();
assert_eq!(names, ["address", "blockquote", "quote"]);
let quote = config.get("quote").expect("shipped");
assert_eq!(quote.sections, BTreeSet::from(QuoteSection::ALL));
assert_eq!(quote.bare, None);
assert!(quote.holds_blocks());
let blockquote = config.get("blockquote").expect("shipped");
assert!(blockquote.sections.is_empty());
assert_eq!(blockquote.bare, Some(QuoteSection::Block));
assert!(blockquote.holds_blocks());
let address = config.get("address").expect("shipped");
assert!(address.sections.is_empty());
assert_eq!(address.bare, Some(QuoteSection::Lines));
assert!(!address.holds_blocks());
assert_eq!(config.validate(), Ok(()));
}
#[test]
fn a_section_kind_is_named_and_parsed_as_its_command() {
for section in QuoteSection::ALL {
assert_eq!(QuoteSection::parse(section.as_str()), Some(section));
assert!(section.role().ends_with(section.as_str()));
}
assert_eq!(QuoteSection::parse("quote"), None);
}
#[test]
fn an_environment_admitting_nothing_or_misnamed_is_refused() {
let nothing = QuoteConfig::empty().environment("empty", QuoteEnvironment::new([]));
assert!(nothing.validate().is_err());
for reserved in LIST_RESERVED_KINDS {
let config = QuoteConfig::empty().environment(reserved, QuoteEnvironment::new(QuoteSection::ALL));
assert!(config.validate().is_err(), "{reserved}");
}
let spaced = QuoteConfig::empty().environment("my quote", QuoteEnvironment::new(QuoteSection::ALL));
assert!(spaced.validate().is_err());
}
#[test]
fn the_digest_bytes_change_with_every_field() {
let base = QuoteConfig::new();
let changed = [
base.clone().environment("aside", QuoteEnvironment::new([]).bare(QuoteSection::Block)),
base.clone().without_environment("address"),
base.clone().environment("quote", QuoteEnvironment::new([QuoteSection::Text])),
base.clone().environment("quote", QuoteEnvironment::new(QuoteSection::ALL).bare(QuoteSection::Text)),
base.clone().environment("address", QuoteEnvironment::new([]).bare(QuoteSection::Text)),
];
for other in &changed {
assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
}
assert_eq!(QuoteConfig::new().digest_bytes(), base.digest_bytes());
}
#[test]
fn the_accepted_sections_are_a_set() {
let listed = QuoteConfig::empty().environment(
"quote",
QuoteEnvironment::new([QuoteSection::Lines, QuoteSection::Text, QuoteSection::Text]),
);
let canonical = QuoteConfig::empty()
.environment("quote", QuoteEnvironment::new([QuoteSection::Text, QuoteSection::Lines]));
assert_eq!(listed, canonical);
assert_eq!(listed.digest_bytes(), canonical.digest_bytes());
assert_eq!(listed.validate(), Ok(()));
}
}