#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Annotator {
#[schemars(skip)]
pub command: String,
pub initials: Option<String>,
}
impl Annotator {
pub fn new(command: impl Into<String>) -> Annotator {
Annotator { command: command.into(), initials: None }
}
pub fn initials(mut self, initials: impl Into<String>) -> Annotator {
self.initials = Some(initials.into());
self
}
pub fn end_command(&self) -> String {
format!("end{}", self.command)
}
pub fn validate(&self) -> Result<(), String> {
let command = self.command.as_str();
if command.is_empty() || !command.chars().all(|ch| ch.is_ascii_alphabetic()) {
return Err(format!(
"the annotator command name `{command}` must be one or more ASCII letters, \
without the backslash"
));
}
if command == "begin" || command == "end" {
return Err(format!(
"the annotator command name may not be `{command}`, since `\\{command}` starts or ends \
an environment"
));
}
if self.initials.as_deref().is_some_and(|initials| initials.trim().is_empty()) {
return Err(format!(
"the initials of the annotator `\\{command}` may not be empty or only \
whitespace (leave them unset for no initials)"
));
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct AnnotationsConfig {
#[serde(deserialize_with = "crate::core::settings::named::deserialize")]
#[schemars(
transform = crate::core::settings::named::map_schema,
with = "std::collections::BTreeMap<String, Annotator>"
)]
pub annotators: Vec<Annotator>,
}
impl AnnotationsConfig {
pub fn new() -> AnnotationsConfig {
AnnotationsConfig::default()
}
pub fn annotator(mut self, annotator: Annotator) -> AnnotationsConfig {
self.annotators.push(annotator);
self
}
pub fn number_of(&self, command: &str) -> Option<usize> {
self.annotators.iter().position(|annotator| annotator.command == command)
}
pub fn validate(&self) -> Result<(), String> {
for (at, annotator) in self.annotators.iter().enumerate() {
annotator.validate()?;
if self.annotators[..at].iter().any(|earlier| earlier.command == annotator.command) {
return Err(format!(
"the command `\\{}` may not be declared for two annotators",
annotator.command
));
}
}
Ok(())
}
pub fn digest_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
push_len(&mut out, self.annotators.len());
for annotator in &self.annotators {
let Annotator { command, initials } = annotator;
push_text(&mut out, command);
match initials {
None => out.push(0),
Some(initials) => {
out.push(1);
push_text(&mut out, initials);
}
}
}
out
}
}
fn push_len(out: &mut Vec<u8>, len: usize) {
out.extend_from_slice(&(len as u64).to_le_bytes());
}
fn push_text(out: &mut Vec<u8>, text: &str) {
push_len(out, text.len());
out.extend_from_slice(text.as_bytes());
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct AnnotationsRenderOptions {
pub hidden: bool,
}
impl crate::core::settings::named::NamedEntry for Annotator {
fn read_entry(name: &str, data: serde_json::Value) -> Result<Annotator, String> {
crate::core::settings::named::read_with_name("command", name, data)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_command_is_ascii_letters_and_no_environment_word() {
for command in ["", "ph f", "phf1", "é", "p-f", "begin", "end"] {
assert!(Annotator::new(command).validate().is_err(), "{command}");
}
assert_eq!(Annotator::new("PhF").validate(), Ok(()));
assert_eq!(Annotator::new("endphf").validate(), Ok(()));
}
#[test]
fn blank_initials_are_refused_and_two_annotators_of_one_command_too() {
for initials in ["", " ", "\t"] {
assert!(Annotator::new("phf").initials(initials).validate().is_err(), "{initials:?}");
}
assert_eq!(Annotator::new("phf").initials(" P ").validate(), Ok(()));
let config = AnnotationsConfig::new()
.annotator(Annotator::new("phf"))
.annotator(Annotator::new("phf").initials("X"));
assert!(config.validate().is_err());
}
#[test]
fn the_digest_tells_every_field_apart() {
let one = AnnotationsConfig::new().annotator(Annotator::new("phf"));
let with_initials = AnnotationsConfig::new().annotator(Annotator::new("phf").initials("PhF"));
let other = AnnotationsConfig::new().annotator(Annotator::new("abc"));
let two = one.clone().annotator(Annotator::new("abc"));
let reordered = AnnotationsConfig::new().annotator(Annotator::new("abc")).annotator(Annotator::new("phf"));
let digests = [
AnnotationsConfig::new().digest_bytes(),
one.digest_bytes(),
with_initials.digest_bytes(),
other.digest_bytes(),
two.digest_bytes(),
reordered.digest_bytes(),
];
for (at, digest) in digests.iter().enumerate() {
for other in &digests[..at] {
assert_ne!(digest, other);
}
}
assert_eq!(one.digest_bytes(), AnnotationsConfig::new().annotator(Annotator::new("phf")).digest_bytes());
}
}