Cotton code
66 lines · 2.8 KB · RustRaw
//! Who speaks in a scene, and the names to offer on a character line.use super::lines::{same_name, Kind, Line};/// The names that speak in these lines, in the order they first speak, each/// once (the first spelling kept).pub fn speakers(lines: &[Line]) -> Vec<String> {    let mut out: Vec<String> = Vec::new();    for name in lines.iter().filter(|line| line.kind == Kind::Character).filter_map(|line| line.name.as_deref()) {        if !name.is_empty() && !out.iter().any(|seen| same_name(seen, name)) {            out.push(name.to_string());        }    }    out}/// How many speeches each name has in these lines, in first-speech order.pub fn speeches(lines: &[Line]) -> Vec<(String, u64)> {    let mut out: Vec<(String, u64)> = Vec::new();    for name in lines.iter().filter(|line| line.kind == Kind::Character).filter_map(|line| line.name.as_deref()) {        if name.is_empty() {            continue;        }        match out.iter_mut().find(|(seen, _)| same_name(seen, name)) {            Some((_, count)) => *count += 1,            None => out.push((name.to_string(), 1)),        }    }    out}/// The names to offer on a character line, filtered by `prefix` (any case,/// any script): the scene's other speaker first — the latest speaker who is/// not the last one — then the scene's speakers by how lately they spoke,/// then the story's names in the order given (the caller orders them by how/// much each speaks). `before` is how many of the scene's lines stand above/// the line being typed (all of them when it is unknown).pub fn offered(scene: &[Line], before: usize, story: &[String], prefix: &str) -> Vec<String> {    let prefix = prefix.trim().to_lowercase();    let mut recent: Vec<String> = Vec::new();    for name in scene.iter().take(before).rev().filter(|line| line.kind == Kind::Character).filter_map(|line| line.name.as_deref()) {        if !name.is_empty() && !recent.iter().any(|seen| same_name(seen, name)) {            recent.push(name.to_string());        }    }    let mut ordered: Vec<String> = Vec::new();    if recent.len() >= 2 {        ordered.push(recent[1].clone());        ordered.push(recent[0].clone());        ordered.extend(recent.iter().skip(2).cloned());    } else {        ordered.extend(recent.iter().cloned());    }    for name in speakers(scene).into_iter().chain(story.iter().cloned()) {        if !ordered.iter().any(|seen| same_name(seen, &name)) {            ordered.push(name);        }    }    // A scene of one speaker so far offers someone else first: the last    // speaker answering themself is the rarer line.    if recent.len() == 1 && ordered.len() > 1 {        let last = ordered.remove(0);        ordered.insert(1, last);    }    ordered.into_iter().filter(|name| prefix.is_empty() || name.to_lowercase().starts_with(&prefix)).collect()}