1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! Convert a decimal number to its Chinese form.
//!
//! [![Build Status](https://travis-ci.org/lilydjwg/chinese-num.svg)](https://travis-ci.org/lilydjwg/chinese-num)
//! [![Crates.io Version](https://img.shields.io/crates/v/chinese-num.svg)](https://crates.io/crates/chinese-num)
//! [![GitHub stars](https://img.shields.io/github/stars/lilydjwg/chinese-num.svg?style=social&label=Star)](https://github.com/lilydjwg/chinese-num)
//!
//!
//! # Examples
//!
//! ```
//! let s = chinese_num::to_chinese_num("121").unwrap();
//! assert_eq!(s, "一百二十一");
//! ```
//!
//! ```
//! let s = chinese_num::to_chinese_num("1004000007000500").unwrap();
//! assert_eq!(s, "一千零四万亿零七百万零五百");
//! ```
//!
//! ```
//! let s = chinese_num::to_chinese_num("123000520").unwrap();
//! assert_eq!(s, "一亿二千三百万零五百二十");
//! ```
//!
//! ```
//! let s = chinese_num::to_chinese_num("1234070000123780000087006786520988800000").unwrap();
//! assert_eq!(s, "一千二百三十四万零七百亿零一十二万三千七百八十亿零八千七百亿六千七百八十六万五千二百零九亿八千八百八十万");
//! ```
//!
//! If the given string is not a number, or begins with "0", `None` is returned:
//!
//! ```
//! let s = chinese_num::to_chinese_num("不是数字");
//! assert!(s.is_none());
//! ```
//!
//! ```
//! let s = chinese_num::to_chinese_num("020");
//! assert!(s.is_none());
//! ```
//!
//! The algorithm is taken from here:
//! http://zhuanlan.zhihu.com/iobject/20370983.

const DIGITS: &'static str = "零一二三四五六七八九";
const TENS_NAME: &'static str = "个十百千";
const UNIT_RANK: &'static str = "个十百千万亿";

fn digit_pos_to_name(pos: usize) -> char {
  if pos == 0 {
    '个'
  } else if pos % 8 == 0 {
    '亿'
  } else if pos % 4 == 0 {
    '万'
  } else {
    TENS_NAME.chars().nth(pos % 4).unwrap()
  }
}

struct ResultS (String, bool, char);

fn append_digit(result: ResultS, tuple: (usize, char)) -> ResultS {
  let (digit, this_unit) = tuple;
  let ResultS(mut result, pending_zero, last_unit) = result;
  let this_str = DIGITS.chars().nth(digit).unwrap();
  if digit == 0 {
    if UNIT_RANK.find(last_unit).unwrap() > UNIT_RANK.find(this_unit).unwrap() {
      ResultS(result, true, last_unit)
    } else {
      result.push(this_unit);
      ResultS(result, false, this_unit)
    }
  } else {
    if pending_zero {
      result.push('零');
    }
    result.push(this_str);
    result.push(this_unit);
    ResultS(result, false, this_unit)
  }
}

pub fn to_chinese_num<N: AsRef<str>>(n: N) -> Option<String> {
  let n = n.as_ref();

  // special cases
  if n == "0" {
    return Some("零".to_owned());
  }

  // non-digit found, nothing, leading zeros
  if !n.chars().all(|x| x.is_digit(10)) || n.len() == 0
    || n.chars().nth(0).unwrap() == '0' {
    return None;
  }

  let v = n.as_bytes().iter().rev().enumerate().map(
    |(i, c)| ((c - '0' as u8) as usize, digit_pos_to_name(i)))
    .rev().fold(ResultS(String::new(), false, '个'), append_digit);

  let mut r = v.0;
  if r.chars().last().unwrap() == '个' {
    r.pop();;
  }
  if r.starts_with("一十") {
    r.remove(0);
  }
  Some(r)
}

pub trait ToChineseNum {
  /// A trait adding a `to_chinese_num` method to types, e.g.:
  ///
  /// ```
  /// use chinese_num::ToChineseNum;
  ///
  /// assert_eq!(20.to_chinese_num(), Some(String::from("二十")));
  /// ```
  fn to_chinese_num(&self) -> Option<String>;
}

impl ToChineseNum for usize {
  fn to_chinese_num(&self) -> Option<String> {
    to_chinese_num(self.to_string())
  }
}

#[test]
fn empty_number() {
  let s = to_chinese_num("");
  assert!(s.is_none());
}

#[test]
fn num_0() {
  let s = to_chinese_num("0").unwrap();
  assert_eq!(s, "零");
}

#[test]
fn num_1() {
  let s = to_chinese_num("1").unwrap();
  assert_eq!(s, "一");
}

#[test]
fn num_10() {
  let s = to_chinese_num("10").unwrap();
  assert_eq!(s, "十");
}

#[test]
fn num_12() {
  let s = to_chinese_num("12").unwrap();
  assert_eq!(s, "十二");
}

#[test]
fn num_20() {
  let s = to_chinese_num("20").unwrap();
  assert_eq!(s, "二十");
}