petitcarnets 0.0.11

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
//! Unicode answers checked against Go's.

use super::*;

#[test]
fn printable_as_go_says() {
    for (r, print) in [
        (u32::from('a'), true),
        (0x20, true),
        (0xA0, false),
        (0x1F, false),
        (0x85, false),
        (0xAD, false),
        (0xE09C, false),
        (0x10_FFFF, false),
        (0xFFFD, true),
        (0xD800, false),
        (0x0301, true),
        (0x1F600, true),
    ] {
        assert_eq!(is_print(r), print, "U+{r:04X}");
    }
}

#[test]
fn case_maps_one_to_one() {
    assert_eq!(to_upper('ß'), 'ß');
    assert_eq!(to_upper('é'), 'É');
    assert_eq!(to_upper('Dž'), 'DŽ');
    assert_eq!(to_lower('İ'), 'i');
    assert_eq!(to_lower('O'), 'o');
}

#[test]
fn runes_decode_as_go_decodes_them() {
    assert_eq!(decode_rune(b"a"), ('a', 1));
    assert_eq!(decode_rune("é!".as_bytes()), ('é', 2));
    assert_eq!(decode_rune(b"\xc3"), (REPLACEMENT, 1));
    assert_eq!(decode_rune(b"\xed\xa0\x80"), (REPLACEMENT, 1));
    assert_eq!(decode_rune(b"\xff"), (REPLACEMENT, 1));
    assert_eq!(decode_rune("\u{FFFD}".as_bytes()), (REPLACEMENT, 3));
}

#[test]
fn noncharacters_and_format_characters_are_reserved() {
    for r in [
        0xFDD0, 0xFDEF, 0xFFFE, 0xFFFF, 0x1_FFFE, 0x10_FFFF, 0x200B, 0xE0001,
    ] {
        assert!(is_reserved(r), "{r:X}");
    }
    for r in [0x41, 0xFDCF, 0xFDF0, 0xFFFD, 0x1_FFFD, 0x2010] {
        assert!(!is_reserved(r), "{r:X}");
    }
}

/// Unicode's own conformance files, vendored in `tests/fixtures/unicode`.
/// They are not in the published crate, so these tests return early
/// there; in the repository (where `.git` is) a missing file fails.
mod ucd {
    use super::super::{WidthMethod, first_cluster, first_width_cluster};
    use std::path::{Path, PathBuf};

    fn fixture(name: &str) -> Option<String> {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let path: PathBuf = root.join("tests/fixtures/unicode").join(name);
        match std::fs::read_to_string(&path) {
            Ok(text) => Some(text),
            Err(e) if root.join(".git").exists() => panic!("{}: {e}", path.display()),
            Err(_) => None,
        }
    }

    /// A `GraphemeBreakTest.txt` line, `÷ 0061 × 0308 ÷ 0062 ÷  # …`:
    /// the text, and its clusters as Unicode splits it.
    fn break_case(line: &str) -> Option<(String, Vec<String>)> {
        let data = line.split('#').next()?.trim();
        if data.is_empty() {
            return None;
        }
        let (mut text, mut clusters, mut current) = (String::new(), Vec::new(), String::new());
        for token in data.split_whitespace() {
            match token {
                "÷" if !current.is_empty() => clusters.push(std::mem::take(&mut current)),
                "÷" | "×" => {}
                hex => {
                    let c = char::from_u32(u32::from_str_radix(hex, 16).ok()?)?;
                    text.push(c);
                    current.push(c);
                }
            }
        }
        Some((text, clusters))
    }

    /// Every line of a break test, split by `first`, as Unicode splits it.
    fn check_breaks(file: &str, first: impl Fn(&str) -> usize) {
        let Some(text) = fixture(file) else { return };
        let (mut checked, mut wrong) = (0, Vec::new());
        for (number, line) in text.lines().enumerate() {
            let Some((input, want)) = break_case(line) else {
                continue;
            };
            let mut got = Vec::new();
            let mut rest = input.as_str();
            while !rest.is_empty() {
                let length = first(rest);
                got.push(rest[..length].to_owned());
                rest = &rest[length..];
            }
            checked += 1;
            if got != want {
                wrong.push(format!("line {}: {want:?}, got {got:?}", number + 1));
            }
        }
        assert!(checked > 500, "{file}: only {checked} cases read");
        assert!(
            wrong.is_empty(),
            "{file}: {} of {checked} wrong:\n{}",
            wrong.len(),
            wrong.join("\n")
        );
    }

    #[test]
    fn measuring_splits_as_unicode_17_does() {
        check_breaks("GraphemeBreakTest-17.0.0.txt", |s| {
            first_width_cluster(s, WidthMethod::GraphemeWidth).0.len()
        });
    }

    #[test]
    fn input_splits_as_unicode_15_does() {
        check_breaks("GraphemeBreakTest-15.0.0.txt", |s| {
            first_cluster(s.as_bytes())
        });
    }

    /// The code points of every fully-qualified emoji in `emoji-test.txt`.
    fn qualified_emoji(text: &str) -> Vec<(usize, String)> {
        let mut found = Vec::new();
        for (number, line) in text.lines().enumerate() {
            let Some((points, rest)) = line.split_once(';') else {
                continue;
            };
            if !rest.trim_start().starts_with("fully-qualified") {
                continue;
            }
            let emoji = points
                .split_whitespace()
                .filter_map(|hex| char::from_u32(u32::from_str_radix(hex, 16).ok()?))
                .collect();
            found.push((number + 1, emoji));
        }
        found
    }

    /// The width Go's `x/ansi` gives an emoji: 2 when its first code
    /// point is wide or is followed by U+FE0F (emoji presentation), else
    /// that code point's own width. So a text-presentation base with a
    /// skin tone and no U+FE0F after it (`✌🏽`, `🖐🏻`: 85 emoji in 17.0)
    /// is 1 cell, in Go and here.
    fn go_emoji_width(emoji: &str) -> usize {
        let mut chars = emoji.chars();
        let base = chars.next().map_or(0, |c| {
            let mut buffer = [0; 4];
            WidthMethod::GraphemeWidth.string_width(c.encode_utf8(&mut buffer))
        });
        if chars.next() == Some('\u{FE0F}') {
            2
        } else {
            base
        }
    }

    #[test]
    fn every_emoji_is_one_cluster_as_wide_as_go_says() {
        let Some(text) = fixture("emoji-test-17.0.0.txt") else {
            return;
        };
        let emoji = qualified_emoji(&text);
        assert!(emoji.len() > 3000, "only {} emoji read", emoji.len());
        let narrow = emoji.iter().filter(|(_, e)| go_emoji_width(e) == 1).count();
        assert_eq!(narrow, 85, "text-presentation emoji with a skin tone");
        let wrong: Vec<String> = emoji
            .iter()
            .filter(|(_, e)| {
                let (cluster, width) = first_width_cluster(e, WidthMethod::GraphemeWidth);
                cluster.len() != e.len() || width != go_emoji_width(e)
            })
            .map(|(n, e)| format!("line {n}: {e:?}"))
            .collect();
        assert!(
            wrong.is_empty(),
            "{} of {} emoji wrong:\n{}",
            wrong.len(),
            emoji.len(),
            wrong.join("\n")
        );
    }

    /// The code points `EastAsianWidth.txt` marks Wide (`W`) or Fullwidth
    /// (`F`): assigned ones only (its ranges also cover unassigned blocks,
    /// marked `<reserved-…>`), and not the nonspacing marks (`Mn`, such as
    /// U+3099), which combine with the character before and take no cell
    /// of their own, in Go and here.
    fn east_asian_wide(text: &str) -> Vec<char> {
        let mut wide = Vec::new();
        for line in text.lines() {
            let Some((data, comment)) = line.split_once('#') else {
                continue;
            };
            let Some((range, class)) = data.split_once(';') else {
                continue;
            };
            let mark = comment.trim_start().starts_with("Mn");
            if !matches!(class.trim(), "W" | "F") || mark || comment.contains("<reserved") {
                continue;
            }
            let (from, to) = range
                .trim()
                .split_once("..")
                .unwrap_or((range.trim(), range.trim()));
            let (Ok(from), Ok(to)) = (u32::from_str_radix(from, 16), u32::from_str_radix(to, 16))
            else {
                continue;
            };
            wide.extend((from..=to).filter_map(char::from_u32));
        }
        wide
    }

    #[test]
    fn east_asian_wide_is_two_cells() {
        let Some(text) = fixture("EastAsianWidth-17.0.0.txt") else {
            return;
        };
        let wide = east_asian_wide(&text);
        assert!(
            wide.len() > 50_000,
            "only {} wide code points read",
            wide.len()
        );
        let wrong: Vec<String> = wide
            .iter()
            .filter(|c| {
                let mut buffer = [0; 4];
                WidthMethod::GraphemeWidth.string_width(c.encode_utf8(&mut buffer)) != 2
            })
            .map(|c| format!("U+{:04X}", u32::from(*c)))
            .collect();
        assert!(
            wrong.is_empty(),
            "{} of {} wide code points wrong: {}",
            wrong.len(),
            wide.len(),
            wrong.join(" ")
        );
    }
}