File tree Expand file tree Collapse file tree 2 files changed +32
-6
lines changed Expand file tree Collapse file tree 2 files changed +32
-6
lines changed Original file line number Diff line number Diff line change @@ -3,7 +3,6 @@ name = "unicode-columns"
3
3
version = " 0.1.0"
4
4
edition = " 2021"
5
5
6
- # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7
6
8
7
[dependencies ]
9
8
unicode-width = " 0.1"
Original file line number Diff line number Diff line change 1
1
use unicode_width:: UnicodeWidthChar ;
2
2
3
+ const ZWJ : u32 = 0x200d ;
4
+
5
+ /// Get the column width of a string
6
+ pub fn width ( string : & str ) -> usize {
7
+ let mut cw = 0 ;
8
+ let mut iter = string. chars ( ) ;
9
+ while let Some ( c) = iter. next ( ) {
10
+ if u32:: from ( c) == ZWJ {
11
+ iter. next ( ) ;
12
+ continue ;
13
+ }
14
+ cw += c. width ( ) . unwrap_or ( 0 ) ;
15
+ }
16
+ cw
17
+ }
18
+
3
19
/// Truncate a string to a specific column width
4
20
pub fn truncate ( string : & str , width : usize ) -> & str {
5
21
let mut cw = 0 ;
6
22
let mut iter = string. char_indices ( ) ;
7
23
while let Some ( ( i, c) ) = iter. next ( ) {
8
- if u32:: from ( c) == /* ZWJ */ 0x200d {
24
+ if u32:: from ( c) == ZWJ {
9
25
iter. next ( ) ;
10
26
continue ;
11
27
}
12
- let nw = cw + c. width ( ) . unwrap_or ( 0 ) ;
13
- if nw > width {
28
+ cw += c. width ( ) . unwrap_or ( 0 ) ;
29
+ if cw > width {
14
30
return & string[ ..i] ;
15
31
}
16
- cw = nw;
17
32
}
18
33
string
19
34
}
20
35
21
36
#[ cfg( test) ]
22
37
mod tests {
23
- use crate :: truncate;
38
+ use super :: * ;
39
+
40
+ #[ test]
41
+ fn test_width ( ) {
42
+ // basic tests
43
+ assert_eq ! ( width( "teststring" ) , 10 ) ;
44
+ // full-width (2 column) characters test
45
+ assert_eq ! ( width( "잘라야" ) , 6 ) ;
46
+ // combining characters (zalgo text) test
47
+ assert_eq ! ( width( "ę̵̡̛̮̹̼̝̲͓̳̣͉̞͔̳̥̝͍̩̣̹͙̘̼̥̗̼͈̯͎̮̥̤̪̻̮͕̩̮͓͔̟͈͇͎̣͉͇̦͔̝̣͎͎͔͇̭͈̌̂̈̄̈́̾͑̀̈̓̂͗̾̉͊͒̆̽͊̽͘̕͜͜͝͠ :width" ) , 8 ) ;
48
+ // zero-width-joiner (emoji) test
49
+ assert_eq ! ( width( "👨👩👦:width" ) , 8 ) ;
50
+ }
24
51
25
52
#[ test]
26
53
fn test_truncation ( ) {
You can’t perform that action at this time.
0 commit comments