use std::sync::Arc;
use techy::core::node::{NodeRef, NodeTree};
use unicode_normalization::UnicodeNormalization;
use crate::model::aspects::{ContentRef, Label};
use crate::lang::copy::{ValueContent, copy_run_into_value};
use crate::lang::guard::GuardPolicy;
use crate::lang::Flm;
pub use crate::lang::copy::CopyError;
pub fn value_of(
nodes: &[NodeRef<'_, Flm>],
anchor: &NodeRef<'_, Flm>,
guard: GuardPolicy,
) -> Result<Arc<NodeTree<Flm>>, CopyError> {
copy_run_into_value(nodes, anchor, ValueContent::Shown, guard)
}
pub fn content_value(
node: &NodeRef<'_, Flm>,
content: &ContentRef,
guard: GuardPolicy,
) -> Result<Option<Arc<NodeTree<Flm>>>, CopyError> {
if let ContentRef::Synthesized(tree) = content {
return Ok(Some(Arc::clone(tree)));
}
match content.nodes(node) {
Some(nodes) => value_of(&nodes, node, guard).map(Some),
None => Ok(None),
}
}
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
fn fnv1a_64(bytes: &[u8]) -> u64 {
let mut hash = FNV_OFFSET_BASIS;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(FNV_PRIME);
}
hash
}
fn anchor_tag(text: &str) -> String {
format!("{:06x}", fnv1a_64(text.as_bytes()) >> 40)
}
const ANCHOR_LETTERS: u32 = 4;
fn anchor_letters(text: &str) -> String {
let mut value = (fnv1a_64(text.as_bytes()) >> 32) % 26u64.pow(ANCHOR_LETTERS);
let mut letters = vec![b'a'; ANCHOR_LETTERS as usize];
for slot in letters.iter_mut().rev() {
*slot = b'a' + u8::try_from(value % 26).expect("a remainder below twenty-six");
value /= 26;
}
String::from_utf8(letters).expect("ASCII lowercase letters")
}
fn passes_through(ch: char) -> bool {
ch.is_ascii_alphanumeric() || ch == '.' || ch == '-'
}
fn is_exact(text: &str) -> bool {
!text.is_empty()
&& !text.starts_with('-')
&& !text.ends_with('-')
&& !text.starts_with(' ')
&& !text.ends_with(' ')
&& !text.contains(" ")
&& text.chars().all(|ch| passes_through(ch) || ch == ' ')
}
pub fn encode_anchor(text: &str) -> String {
if is_exact(text) {
return text.replace(' ', "_");
}
let folded: String =
text.nfkd().filter(|ch| !unicode_normalization::char::is_combining_mark(*ch)).collect();
let mut slug = String::with_capacity(folded.len() + 7);
let mut run: Option<bool> = None;
for ch in folded.chars() {
if passes_through(ch) {
if let Some(whitespace_only) = run.take() {
if !slug.is_empty() {
slug.push(if whitespace_only { '_' } else { '-' });
}
}
slug.push(ch);
} else {
run = Some(run.unwrap_or(true) && ch.is_whitespace());
}
}
let mut anchor = slug.trim_matches(|ch| ch == '-' || ch == '_').to_string();
anchor.push('~');
anchor.push_str(&anchor_tag(text));
anchor
}
pub fn label_anchor(label: &Label) -> String {
format!("{}-{}", encode_anchor(&label.ref_type), encode_anchor(&label.ref_label))
}
pub fn title_anchor(prefix: &str, title: &str) -> String {
format!("{}--{}", encode_anchor(prefix), encode_anchor(title))
}
pub fn auto_anchor(prefix: &str, position: u32) -> String {
let base = format!("{}--{position}", encode_anchor(prefix));
let letters = anchor_letters(&base);
format!("{base}{letters}")
}
pub fn value_anchor(prefix: &str, numbers: &str) -> String {
format!("{}-{}", encode_anchor(prefix), encode_anchor(numbers))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_exact_path_reproduces_a_plain_label_with_spaces_as_underscores() {
assert_eq!(encode_anchor("intro"), "intro");
let phrase = "quantum error-correcting code";
assert_eq!(encode_anchor(phrase), "quantum_error-correcting_code");
assert_eq!(encode_anchor("main.v2"), "main.v2");
assert_eq!(encode_anchor("Mixed-Case.42"), "Mixed-Case.42");
}
#[test]
fn the_exact_path_stops_at_a_leading_a_trailing_or_a_doubled_space() {
assert!(encode_anchor(" x").contains('~'));
assert!(encode_anchor("x ").contains('~'));
assert!(encode_anchor("a b").contains('~'));
assert!(!encode_anchor("a b").contains('~'));
}
#[test]
fn the_exact_path_stops_at_a_hyphen_at_either_end() {
assert!(encode_anchor("-7").contains('~'));
assert!(encode_anchor("-Foo").contains('~'));
assert!(encode_anchor("a-").contains('~'));
assert_eq!(encode_anchor("-7"), format!("7~{}", anchor_tag("-7")));
assert_eq!(encode_anchor("a-"), format!("a~{}", anchor_tag("a-")));
assert_eq!(encode_anchor("7"), "7");
assert_eq!(encode_anchor("a"), "a");
assert_eq!(encode_anchor("a-b"), "a-b");
}
#[test]
fn a_label_beginning_with_a_hyphen_cannot_take_a_double_hyphen_shape() {
let section = label_anchor(&Label::new("sec", "-Foo"));
assert!(!section.starts_with("sec--"), "{section}");
assert_ne!(section, title_anchor("sec", "Foo"));
let equation = label_anchor(&Label::new("eq", "-7"));
assert!(!equation.starts_with("eq--"), "{equation}");
assert_ne!(equation, auto_anchor("eq", 7));
}
#[test]
fn a_label_type_ending_in_a_hyphen_cannot_take_a_double_hyphen_shape() {
let section = label_anchor(&Label::new("sec-", "Foo"));
assert!(!section.starts_with("sec--"), "{section}");
assert_ne!(section, title_anchor("sec", "Foo"));
}
#[test]
fn the_exact_path_stops_at_a_character_it_cannot_write() {
assert!(encode_anchor("a_b").contains('~'));
assert!(encode_anchor("a:b").contains('~'));
assert!(encode_anchor("é").contains('~'));
}
#[test]
fn the_tagged_path_strips_the_accents_of_an_nfkd_decomposition() {
let text = "Éléments 2";
assert_eq!(encode_anchor(text), format!("Elements_2~{}", anchor_tag(text)));
}
#[test]
fn the_tagged_path_writes_one_dash_per_run_and_trims_the_ends() {
let raw = r"\(\mathcal{C}_\alpha^\infty\)";
assert_eq!(encode_anchor(raw), format!("mathcal-C-alpha-infty~{}", anchor_tag(raw)));
}
#[test]
fn the_tagged_path_allows_an_empty_slug() {
assert_eq!(encode_anchor("!!"), format!("~{}", anchor_tag("!!")));
assert_eq!(encode_anchor(""), format!("~{}", anchor_tag("")));
}
#[test]
fn the_tag_is_the_fixed_fnv_1a_64_hash_of_the_raw_text() {
assert_eq!(fnv1a_64(b""), FNV_OFFSET_BASIS);
assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
assert_eq!(anchor_tag(""), "cbf29c");
assert_eq!(anchor_tag("a"), "af63dc");
}
#[test]
fn a_label_anchor_joins_the_type_and_the_label_with_one_hyphen() {
assert_eq!(label_anchor(&Label::new("sec", "intro")), "sec-intro");
assert_eq!(
label_anchor(&Label::new("term", "quantum error-correcting code")),
"term-quantum_error-correcting_code"
);
assert_eq!(label_anchor(&Label::new("eq", "main.v2")), "eq-main.v2");
}
#[test]
fn the_letters_are_the_fixed_base_twenty_six_reduction_of_the_hash() {
assert_eq!(anchor_letters(""), "qvaa");
assert_eq!(anchor_letters("eq--8"), "otbc");
for text in ["", "eq--8", "eq--1", "sec--12"] {
let letters = anchor_letters(text);
assert_eq!(letters.len(), 4, "{text}: {letters}");
assert!(letters.bytes().all(|b| b.is_ascii_lowercase()), "{text}: {letters}");
}
}
#[test]
fn a_position_anchor_is_the_prefix_the_position_and_four_letters() {
assert_eq!(auto_anchor("eq", 8), format!("eq--8{}", anchor_letters("eq--8")));
assert_ne!(auto_anchor("eq", 8), auto_anchor("eq", 9));
assert_ne!(auto_anchor("eq", 8), auto_anchor("sec", 8));
assert_eq!(auto_anchor("a b", 1), format!("a_b--1{}", anchor_letters("a_b--1")));
}
#[test]
fn a_value_anchor_joins_the_prefix_and_the_numbers_with_one_hyphen() {
assert_eq!(value_anchor("theorem", "2-3"), "theorem-2-3");
assert_eq!(value_anchor("theorem", "13"), "theorem-13");
assert_eq!(value_anchor("a b", "1"), "a_b-1");
assert_eq!(value_anchor("theorem", "2-3"), label_anchor(&Label::new("theorem", "2-3")));
}
#[test]
fn a_title_anchor_joins_the_prefix_and_the_title_with_two_hyphens() {
let title = "The Sum, of Things";
assert_eq!(
title_anchor("sec", title),
format!("sec--The_Sum-of_Things~{}", anchor_tag(title))
);
assert_eq!(title_anchor("sec", "Intro"), "sec--Intro");
}
}