227 lines · 9.0 KB · RustRaw
//! The vectors (`vectors.json`, which both phones' tests read too) and the//! speed on a long note.use super::derive::{derive, opened_text, with_pictures};use super::format::{apply, Action};use super::style::{style, Block, Kind, Look, Span};use super::{len16, Selection};use serde_json::Value;const VECTORS: &str = include_str!("vectors.json");fn vectors() -> Value { serde_json::from_str(VECTORS).expect("vectors parse")}fn said(value: &impl serde::Serialize) -> String { serde_json::to_value(value).unwrap().as_str().unwrap_or_default().to_string()}fn span_line(span: &Span) -> String { let mut out = format!("{}-{} {} {}", span.start, span.end, said(&span.style), said(&span.look)); if let Some(glyph) = span.glyph { out.push_str(&format!(" {}", said(&glyph))); } if let Some(level) = span.level { out.push_str(&format!(" {level}")); } out}fn block_line(block: &Block) -> String { let mut out = format!("{}-{} {} {}", block.start, block.end, said(&block.kind), block.depth); if let Some(level) = block.level { out.push_str(&format!(" level{level}")); } if block.title { out.push_str(" title"); } match block.checked { Some(true) => out.push_str(" ticked"), Some(false) => out.push_str(" open"), None => {} } if let Some(number) = block.number { out.push_str(&format!(" n{number}")); } if let Some(src) = &block.src { out.push_str(&format!(" src={src}")); } out}/// A vector text with its ‸ or « » taken out, and the selection they mark.pub(crate) fn marked(written: &str) -> (String, Selection) { let mut text = String::new(); let (mut start, mut end) = (None, None); for c in written.chars() { match c { '‸' => { start = Some(len16(&text)); end = start; } '«' => start = Some(len16(&text)), '»' => end = Some(len16(&text)), _ => text.push(c), } } let start = start.unwrap_or(len16(&text)); (text, Selection { start, end: end.unwrap_or(start) })}fn mark(text: &str, selection: Selection) -> String { let units: Vec<u16> = text.encode_utf16().collect(); let piece = |a: u32, b: u32| String::from_utf16(&units[a as usize..b as usize]).unwrap(); if selection.start == selection.end { format!("{}‸{}", piece(0, selection.start), piece(selection.start, units.len() as u32)) } else { format!("{}«{}»{}", piece(0, selection.start), piece(selection.start, selection.end), piece(selection.end, units.len() as u32)) }}#[test]fn derive_vectors() { for case in vectors()["derive"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); let got = derive(case["text"].as_str().unwrap()); assert_eq!(got.title.as_deref(), case["title"].as_str(), "{name}: title"); assert_eq!(got.preview, case["preview"].as_str().unwrap(), "{name}: preview"); assert_eq!(got.preview_lines as u64, case["preview_lines"].as_u64().unwrap(), "{name}: preview lines"); let tags: Vec<String> = case["tags"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_string()).collect(); assert_eq!(got.tags, tags, "{name}: tags"); if let Some(picture) = case.get("picture") { assert_eq!(got.picture.as_deref(), picture.as_str(), "{name}: picture"); } }}#[test]fn opened_vectors() { for case in vectors()["opened"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); assert_eq!(opened_text(case["title"].as_str(), case["body"].as_str().unwrap()), case["text"].as_str().unwrap(), "{name}"); }}#[test]fn pictures_vectors() { for case in vectors()["pictures"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); let attached: Vec<String> = case["attached"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_string()).collect(); let once = with_pictures(case["text"].as_str().unwrap(), &attached); assert_eq!(once, case["after"].as_str().unwrap(), "{name}"); assert_eq!(with_pictures(&once, &attached), once, "{name}: a second time adds nothing"); }}#[test]fn style_vectors() { for case in vectors()["style"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); let styled = style(case["text"].as_str().unwrap(), case["cursor"].as_u64().map(|c| c as u32)); let blocks: Vec<String> = styled.blocks.iter().map(block_line).collect(); let want: Vec<String> = case["blocks"].as_array().unwrap().iter().map(|b| b.as_str().unwrap().to_string()).collect(); assert_eq!(blocks, want, "{name}: blocks"); let spans: Vec<String> = styled.spans.iter().map(span_line).collect(); let want: Vec<String> = case["spans"].as_array().unwrap().iter().map(|b| b.as_str().unwrap().to_string()).collect(); assert_eq!(spans, want, "{name}: spans"); if let Some(tables) = case.get("tables") { assert_eq!(serde_json::to_value(&styled.tables).unwrap(), *tables, "{name}: tables"); } }}#[test]fn format_vectors() { for case in vectors()["format"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); let (text, selection) = marked(case["text"].as_str().unwrap()); let action: Action = serde_json::from_value(case["action"].clone()).unwrap_or_else(|why| panic!("{name}: {why}")); let edited = apply(&text, selection, &action); assert_eq!(mark(&edited.text, edited.selection), case["after"].as_str().unwrap(), "{name}"); // The one replacement makes the same text from the old. let rebuilt = match &edited.replace { None => text.clone(), Some(replace) => { let units: Vec<u16> = text.encode_utf16().collect(); let mut out = String::from_utf16(&units[..replace.start as usize]).unwrap(); out.push_str(&replace.with); out.push_str(&String::from_utf16(&units[replace.end as usize..]).unwrap()); out } }; assert_eq!(rebuilt, edited.text, "{name}: the replacement"); }}/// Every syntax mark away from the cursor is hidden; in what it marks, dim.#[test]fn marks_follow_the_cursor() { let text = "a **b** c"; let away = style(text, Some(0)); let near = style(text, Some(5)); assert!(away.spans.iter().filter(|s| s.style == super::style::Style::Mark).all(|s| s.look == Look::Hidden)); assert!(near.spans.iter().filter(|s| s.style == super::style::Style::Mark).all(|s| s.look == Look::Dim));}fn long_note() -> String { let paragraph = "Some **bold** words, a [link](https://cottondb.com), `code`, #tag and ==light== on a line of ordinary length.\n"; let mut text = String::from("# A long note\n\n"); let mut k = 0; while text.len() < 50_000 { match k % 6 { 0 => text.push_str(paragraph), 1 => text.push_str("- an item with *some* style\n"), 2 => text.push_str("- [ ] a task to tick\n"), 3 => text.push_str("> a quoted line ~~struck~~\n"), 4 => text.push_str("| a | b |\n| --- | --- |\n| 1 | 2 |\n\n"), _ => text.push_str("1. numbered\n\n"), } k += 1; } text}/// Fast enough for every keystroke on a long note. The figure for the brief/// is printed by `cargo test --release -p cotton-rules writing::tests::speed -- --ignored --nocapture`;/// this guard holds a debug build to a generous bound so a quadratic slip fails.#[test]fn a_long_note_styles_in_time() { let text = long_note(); let started = std::time::Instant::now(); let styled = style(&text, Some(1000)); let _ = derive(&text); assert!(styled.blocks.len() > 1000); assert!(started.elapsed().as_millis() < 2_000, "{:?}", started.elapsed());}#[test]#[ignore]fn speed() { let text = long_note(); let rounds = 50; let started = std::time::Instant::now(); for k in 0..rounds { std::hint::black_box(style(&text, Some(k * 100))); } let style_each = started.elapsed() / rounds; let started = std::time::Instant::now(); for k in 0..rounds { std::hint::black_box(apply(&text, Selection::cursor(k * 100 + 20), &Action::Return)); } let return_each = started.elapsed() / rounds; let started = std::time::Instant::now(); for _ in 0..rounds { std::hint::black_box(derive(&text)); } let derive_each = started.elapsed() / rounds; println!("{} chars: style {:?}, return {:?}, derive {:?}", text.chars().count(), style_each, return_each, derive_each);}#[test]fn every_kind_is_read() { let text = "# T\n\n## H\npara\n- b\n- [ ] c\n1. n\n> q\n---\n```\nx\n```\n| a | b |\n| - | - |\n"; let kinds: Vec<Kind> = style(text, None).blocks.iter().map(|b| b.kind).collect(); use Kind::*; assert_eq!(kinds, vec![Heading, Blank, Heading, Paragraph, Bullet, Check, Numbered, Quote, Divider, Fence, Code, Fence, Table, TableRule, Picture]);}