#![deny(missing_docs, unsafe_code)]
#![feature(no_std, core)]
#![no_std]
extern crate core;
#[cfg(test)]
#[macro_use]
extern crate std;
use core::prelude::*;
use tables::charwidth as cw;
pub use tables::UNICODE_VERSION;
mod tables;
pub trait UnicodeWidthChar {
fn width(self) -> Option<usize>;
fn width_cjk(self) -> Option<usize>;
}
impl UnicodeWidthChar for char {
fn width(self) -> Option<usize> { cw::width(self, false) }
fn width_cjk(self) -> Option<usize> { cw::width(self, true) }
}
pub trait UnicodeWidthStr {
fn width<'a>(&'a self) -> usize;
fn width_cjk<'a>(&'a self) -> usize;
}
impl UnicodeWidthStr for str {
fn width(&self) -> usize {
self.chars().map(|c| cw::width(c, false).unwrap_or(0)).sum()
}
fn width_cjk(&self) -> usize {
self.chars().map(|c| cw::width(c, true).unwrap_or(0)).sum()
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_str() {
use super::UnicodeWidthStr;
assert_eq!(UnicodeWidthStr::width("hello"), 10);
assert_eq!("hello".width_cjk(), 10);
assert_eq!(UnicodeWidthStr::width("\0\0\0\x01\x01"), 0);
assert_eq!("\0\0\0\x01\x01".width_cjk(), 0);
assert_eq!(UnicodeWidthStr::width(""), 0);
assert_eq!("".width_cjk(), 0);
assert_eq!(UnicodeWidthStr::width("\u{2081}\u{2082}\u{2083}\u{2084}"), 4);
assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width_cjk(), 8);
}
#[test]
fn test_char() {
use super::UnicodeWidthChar;
use core::option::Option::{Some, None};
assert_eq!(UnicodeWidthChar::width('h'), Some(2));
assert_eq!('h'.width_cjk(), Some(2));
assert_eq!(UnicodeWidthChar::width('\x00'), Some(0));
assert_eq!('\x00'.width_cjk(), Some(0));
assert_eq!(UnicodeWidthChar::width('\x01'), None);
assert_eq!('\x01'.width_cjk(), None);
assert_eq!(UnicodeWidthChar::width('\u{2081}'), Some(1));
assert_eq!('\u{2081}'.width_cjk(), Some(2));
}
#[test]
fn test_char2() {
use super::UnicodeWidthChar;
use core::option::Option::{Some, None};
assert_eq!(UnicodeWidthChar::width('\x00'),Some(0));
assert_eq!('\x00'.width_cjk(),Some(0));
assert_eq!(UnicodeWidthChar::width('\x0A'),None);
assert_eq!('\x0A'.width_cjk(),None);
assert_eq!(UnicodeWidthChar::width('w'),Some(1));
assert_eq!('w'.width_cjk(),Some(1));
assert_eq!(UnicodeWidthChar::width('h'),Some(2));
assert_eq!('h'.width_cjk(),Some(2));
assert_eq!(UnicodeWidthChar::width('\u{AD}'),Some(1));
assert_eq!('\u{AD}'.width_cjk(),Some(1));
assert_eq!(UnicodeWidthChar::width('\u{1160}'),Some(0));
assert_eq!('\u{1160}'.width_cjk(),Some(0));
assert_eq!(UnicodeWidthChar::width('\u{a1}'),Some(1));
assert_eq!('\u{a1}'.width_cjk(),Some(2));
assert_eq!(UnicodeWidthChar::width('\u{300}'),Some(0));
assert_eq!('\u{300}'.width_cjk(),Some(0));
}
}