use crate::{Error, Result, Screen};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum GlyphInner {
Char(char),
Str(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Glyph {
inner: GlyphInner,
width: usize,
}
pub trait IntoGlyph {
fn into_glyph(self) -> Result<Glyph>;
}
impl IntoGlyph for char {
fn into_glyph(self) -> Result<Glyph> {
let width = self.width().unwrap_or(0);
if width == 1 || width == 2 {
let inner = GlyphInner::Char(self);
return Ok(Glyph { inner, width });
}
Err(Error::InvalidGlyphWidth(width))
}
}
impl IntoGlyph for &str {
fn into_glyph(self) -> Result<Glyph> {
let width = self.width();
if width == 1 || width == 2 {
let inner = GlyphInner::Str(self.to_string());
return Ok(Glyph { inner, width });
}
Err(Error::InvalidGlyphWidth(width))
}
}
impl Glyph {
pub fn width(&self) -> usize {
self.width
}
pub fn print(&self, screen: &mut Screen) -> Result<()> {
match &self.inner {
GlyphInner::Char(ch) => screen.print_char(*ch)?,
GlyphInner::Str(st) => screen.print_str(st)?,
}
Ok(())
}
}