Skip to content

Commit c066a1e

Browse files
committed
add UnicodeStrSlice width() function
1 parent e624791 commit c066a1e

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/libcollections/str.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1056,6 +1056,15 @@ mod tests {
10561056
assert_eq!("\u2620".char_len(), 1u);
10571057
assert_eq!("\U0001d11e".char_len(), 1u);
10581058
assert_eq!("ประเทศไทย中华Việt Nam".char_len(), 19u);
1059+
1060+
assert_eq!("hello".width(false), 10u);
1061+
assert_eq!("hello".width(true), 10u);
1062+
assert_eq!("\0\0\0\0\0".width(false), 0u);
1063+
assert_eq!("\0\0\0\0\0".width(true), 0u);
1064+
assert_eq!("".width(false), 0u);
1065+
assert_eq!("".width(true), 0u);
1066+
assert_eq!("\u2081\u2082\u2083\u2084".width(false), 4u);
1067+
assert_eq!("\u2081\u2082\u2083\u2084".width(true), 8u);
10591068
}
10601069

10611070
#[test]

src/libunicode/u_str.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@
1616
*/
1717

1818
use core::collections::Collection;
19-
use core::iter::{Filter};
19+
use core::iter::{Filter, AdditiveIterator};
2020
use core::str::{CharSplits, StrSlice};
2121
use core::iter::Iterator;
2222
use u_char;
23+
use u_char::UnicodeChar;
2324

2425
/// An iterator over the words of a string, separated by a sequence of whitespace
2526
pub type Words<'a> =
@@ -78,7 +79,7 @@ pub trait UnicodeStrSlice<'a> {
7879
/// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
7980
/// recommends that these characters be treated as 1 column (i.e.,
8081
/// `is_cjk` = `false`) if the locale is unknown.
81-
//fn width(&self, is_cjk: bool) -> uint;
82+
fn width(&self, is_cjk: bool) -> uint;
8283

8384
/// Returns a string with leading and trailing whitespace removed.
8485
fn trim(&self) -> &'a str;
@@ -102,6 +103,11 @@ impl<'a> UnicodeStrSlice<'a> for &'a str {
102103
#[inline]
103104
fn is_alphanumeric(&self) -> bool { self.chars().all(u_char::is_alphanumeric) }
104105

106+
#[inline]
107+
fn width(&self, is_cjk: bool) -> uint {
108+
self.chars().map(|c| c.width(is_cjk).unwrap_or(0)).sum()
109+
}
110+
105111
#[inline]
106112
fn trim(&self) -> &'a str {
107113
self.trim_left().trim_right()

0 commit comments

Comments
 (0)