pub mod presets {
pub const SHADE: &str = " .:-=+*#%@";
pub const SPARSE: &str = " .:oO@";
pub const DOTS: &str = " .·:•+";
pub const BLOCKS: &str = " ░▒▓█";
pub const FLAME: &str = " ▁▂▃▄▅▆▇█";
pub const INKED: &str = ".:-=+*#%@";
pub const ALL: &[(&str, &str)] = &[
("shade", SHADE),
("sparse", SPARSE),
("dots", DOTS),
("blocks", BLOCKS),
("flame", FLAME),
("inked", INKED),
];
pub fn by_name(name: &str) -> Option<&'static str> {
ALL.iter()
.find(|(preset, _)| preset.eq_ignore_ascii_case(name))
.map(|(_, glyphs)| *glyphs)
}
}
pub fn is_ambiguous_or_narrow(glyph: char) -> bool {
glyph.is_ascii()
|| ('\u{00A0}'..='\u{00FF}').contains(&glyph)
|| ('\u{2000}'..='\u{206F}').contains(&glyph)
|| ('\u{2190}'..='\u{2BFF}').contains(&glyph)
|| ('\u{FF61}'..='\u{FF9F}').contains(&glyph)
|| ('\u{2581}'..='\u{2588}').contains(&glyph)
|| ('\u{2591}'..='\u{2593}').contains(&glyph)
|| glyph == '\u{25A0}'
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GlyphRamp {
glyphs: Vec<char>,
}
const FALLBACK: &str = presets::SHADE;
impl GlyphRamp {
pub fn new(glyphs: Vec<char>) -> Self {
let glyphs: Vec<char> = glyphs
.into_iter()
.filter(|glyph| !glyph.is_control())
.collect();
if glyphs.is_empty() {
return Self::new_ascii(FALLBACK.chars().collect());
}
Self { glyphs }
}
pub fn from_text(glyphs: &str) -> Self {
Self::new(glyphs.chars().collect())
}
pub fn new_ascii(glyphs: Vec<char>) -> Self {
let glyphs: Vec<char> = glyphs
.into_iter()
.filter(|glyph| glyph.is_ascii() && !glyph.is_control())
.collect();
if glyphs.is_empty() {
return Self {
glyphs: FALLBACK.chars().collect(),
};
}
Self { glyphs }
}
pub fn len(&self) -> usize {
self.glyphs.len()
}
pub fn is_empty(&self) -> bool {
false
}
pub fn index_for(&self, value: f32) -> usize {
let value = if value.is_nan() {
0.0
} else {
value.clamp(0.0, 1.0)
};
if self.glyphs.len() == 1 {
return 0;
}
((value * (self.glyphs.len() - 1) as f32).round() as usize)
.min(self.glyphs.len() - 1)
}
pub fn index_wrapped(&self, value: f32) -> usize {
let value = if value.is_nan() { 0.0 } else { value };
if self.glyphs.len() == 1 {
return 0;
}
let scaled = (value * self.glyphs.len() as f32).floor() as isize;
scaled.rem_euclid(self.glyphs.len() as isize) as usize
}
pub fn at(&self, index: usize) -> char {
self.glyphs[index.min(self.glyphs.len() - 1)]
}
pub fn sample(&self, value: f32) -> char {
self.at(self.index_for(value))
}
pub fn glyphs(&self) -> &[char] {
&self.glyphs
}
}
impl Default for GlyphRamp {
fn default() -> Self {
Self::new_ascii(FALLBACK.chars().collect())
}
}
impl FromIterator<char> for GlyphRamp {
fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
Self::new(iter.into_iter().collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_step_of_the_value_range_is_reachable() {
let ramp = GlyphRamp::from_text(presets::SHADE);
let glyphs = ramp.glyphs();
assert_eq!(glyphs.len(), 10);
assert_eq!(ramp.sample(0.0), glyphs[0]);
assert_eq!(ramp.sample(1.0), glyphs[9]);
for (index, glyph) in glyphs.iter().enumerate() {
let value = index as f32 / (glyphs.len() - 1) as f32;
assert_eq!(ramp.sample(value), *glyph, "step {index} is unreachable");
}
}
#[test]
fn values_past_the_top_saturate_rather_than_wrapping() {
let ramp = GlyphRamp::from_text(presets::SHADE);
let top = ramp.sample(1.0);
for value in [1.0, 1.5, 12.0, 96.0, 1.0e9, f32::INFINITY] {
assert_eq!(ramp.sample(value), top, "{value} did not saturate");
}
}
#[test]
fn the_wrapping_index_returns_to_the_start() {
let ramp = GlyphRamp::from_text(presets::SHADE);
assert_eq!(ramp.index_wrapped(0.0), 0);
assert_eq!(ramp.index_wrapped(0.099), 0);
assert_eq!(ramp.index_wrapped(0.1), 1);
assert_eq!(ramp.index_wrapped(1.0), 0, "a full lap should land home");
assert_eq!(ramp.index_wrapped(1.5), 5);
assert_eq!(
ramp.index_wrapped(-0.5),
5,
"negative should wrap backwards"
);
}
#[test]
fn an_unusable_ramp_falls_back_rather_than_panicking() {
for configured in [vec![], vec!['\n'; 4], vec!['\t', '\u{7}']] {
let ramp = GlyphRamp::new(configured);
assert!(!ramp.is_empty());
assert_eq!(ramp.len(), 10, "the fallback is the default ramp");
assert_eq!(ramp.sample(0.5), '+', "the fallback is not in order");
}
assert_eq!(
GlyphRamp::new_ascii(vec!['░', '█']).len(),
10,
"new_ascii must fall back too, or it has the same panic"
);
}
#[test]
fn a_one_character_ramp_always_draws_that_character() {
let ramp = GlyphRamp::from_text("#");
assert_eq!(ramp.len(), 1);
for value in [-1.0, 0.0, 0.5, 1.0, 99.0] {
assert_eq!(ramp.sample(value), '#');
assert_eq!(ramp.index_wrapped(value), 0);
}
}
#[test]
fn a_nan_value_reads_as_the_sparsest_step() {
let ramp = GlyphRamp::from_text(presets::SHADE);
assert_eq!(ramp.sample(f32::NAN), ramp.sample(0.0));
assert_eq!(ramp.index_for(f32::NAN), 0);
}
#[test]
fn an_out_of_range_index_is_clamped() {
let ramp = GlyphRamp::from_text(presets::SHADE);
let top = ramp.sample(1.0);
for index in [9, 10, 1_000, usize::MAX] {
assert_eq!(ramp.at(index), top, "index {index}");
}
}
#[test]
fn every_preset_is_well_formed() {
for (name, glyphs) in presets::ALL {
let ramp = GlyphRamp::from_text(glyphs);
assert!(!ramp.is_empty(), "preset {name} is empty");
assert_eq!(
ramp.len(),
glyphs.chars().count(),
"preset {name} lost characters"
);
assert_eq!(ramp.sample(0.0), glyphs.chars().next().unwrap());
assert_eq!(
ramp.sample(1.0),
glyphs.chars().last().unwrap(),
"preset {name} does not reach its own last character"
);
assert_eq!(presets::by_name(name), Some(*glyphs));
assert_eq!(presets::by_name(&name.to_uppercase()), Some(*glyphs));
}
assert_eq!(presets::by_name("nonesuch"), None);
}
#[test]
fn the_presets_are_distinct_from_each_other() {
for (index, (name, glyphs)) in presets::ALL.iter().enumerate() {
for (other_name, other) in &presets::ALL[index + 1..] {
assert_ne!(
glyphs, other,
"{name} and {other_name} are the same set"
);
}
}
}
#[test]
fn the_ink_ordering_of_each_preset_is_as_documented() {
let blocks = GlyphRamp::from_text(presets::BLOCKS);
assert_eq!(blocks.sample(0.0), ' ');
assert_eq!(blocks.sample(0.25), '░');
assert_eq!(blocks.sample(0.5), '▒');
assert_eq!(blocks.sample(0.75), '▓');
assert_eq!(blocks.sample(1.0), '█');
let shade = GlyphRamp::from_text(presets::SHADE);
assert_eq!(shade.sample(0.45), '=');
assert_eq!(shade.sample(0.55), '+');
assert_eq!(shade.sample(0.65), '*');
}
#[test]
fn no_preset_contains_a_character_that_would_shear_a_grid() {
for (name, glyphs) in presets::ALL {
for glyph in glyphs.chars() {
assert!(
is_ambiguous_or_narrow(glyph),
"preset {name} contains {glyph:?} (U+{:04X})",
glyph as u32
);
}
}
}
}