full2half 0.1.1

Library and CLI for converting full-width characters to half-width characters and vice versa.
Documentation
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! # Full2Half
//!
//! A simple library for converting full-width characters to half-width characters and vice versa.
//!
//! ## References
//!
//! [Wikipedia](https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block))
//! [Unicode](https://www.unicode.org/charts/PDF/UFF00.pdf)
//!
//! ## Basic Example
//!
//! This is the most basic use case, where no customization is needed.
//!
//! ```
//! use full2half::CharacterWidth;
//!
//! let full_width_string = "Hello World!";
//! let half_width_string = "Hello World!";
//!
//! assert_eq!(full_width_string.to_half_width(), half_width_string);
//! assert_eq!(half_width_string.to_full_width(), full_width_string);
//! ```
//!
//! ## Extended Example
//!
//! Furthermore this library allows to customize which charactersets and specific characters to ignore.
//!
//! ```
//! use full2half::CharacterWidth;
//!
//! let full_width_string = "Hello World!";
//! let expected_string = "Hello World!";
//! let ignore = vec!["!", "e"];
//!
//! assert_eq!(full_width_string.to_half_width_ext(ignore, true, true, true, false).unwrap(), expected_string);
//! ```

use std::collections::HashMap;

/// Trait for converting full-width characters to half-width characters and vice versa.
pub trait CharacterWidth {
    /// Converts full-width characters to half-width characters.
    ///
    /// # Returns
    ///
    /// A String with full-width characters converted to half-width characters.
    fn to_half_width(&self) -> String;

    /// Converts half-width characters to full-width characters.
    ///
    /// # Returns
    ///
    /// A String with half-width characters converted to full-width characters.
    fn to_full_width(&self) -> String;

    /// Converts full-width characters to half-width characters, allowing to customize which characters to ignore.
    ///
    /// # Arguments
    ///
    /// * `ignore` - A vector of characters that will be ignored when converting.
    /// * `alpha` - A boolean that determines whether or not to convert alphanumeric characters.
    /// * `symbols` - A boolean that determines whether or not to convert symbols.
    /// * `kana` - A boolean that determines whether or not to convert kana characters.
    /// * `hangul` - A boolean that determines whether or not to convert hangul characters.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the characters in `ignore` are not valid characters to ignore.
    ///
    /// # Returns
    ///
    /// A String with full-width characters converted to half-width characters, with the desired characters ignored.
    fn to_half_width_ext(&self, ignore: Vec<&str>, alpha: bool, symbols: bool, kana: bool, hangul: bool) -> Result<String, String>;

    /// Converts half-width characters to full-width characters, allowing to customize which characters to ignore.
    ///
    /// # Arguments
    ///
    /// * `ignore` - A vector of characters that will be ignored when converting.
    /// * `alpha` - A boolean that determines whether or not to convert alphanumeric characters.
    /// * `symbols` - A boolean that determines whether or not to convert symbols.
    /// * `kana` - A boolean that determines whether or not to convert kana characters.
    /// * `hangul` - A boolean that determines whether or not to convert hangul characters.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the characters in `ignore` are not valid characters to ignore.
    ///
    /// # Returns
    ///
    /// A String with half-width characters converted to full-width characters, with the desired characters ignored.
    fn to_full_width_ext(&self, ignore: Vec<&str>, alpha: bool, symbols: bool, kana: bool, hangul: bool) -> Result<String, String>;
}

impl<T: AsRef<str>> CharacterWidth for T {
    fn to_half_width(&self) -> String {
        let map = create_map(false);
        self.replace_characters(&map)
    }

    fn to_full_width(&self) -> String {
        let map = create_map(true);
        self.replace_characters(&map)
    }

    fn to_half_width_ext(&self, ignore: Vec<&str>, alpha: bool, symbols: bool, kana: bool, hangul: bool) -> Result<String, String> {
        let map = create_map_ext(ignore, alpha, symbols, kana, hangul, false)?;
        Ok(self.replace_characters(&map))
    }

    fn to_full_width_ext(&self, ignore: Vec<&str>, alpha: bool, symbols: bool, kana: bool, hangul: bool) -> Result<String, String> {
        let map = create_map_ext(ignore, alpha, symbols, kana, hangul, true)?;
        Ok(self.replace_characters(&map))
    }
}

/// Trait for replacing characters in a string.
trait ReplaceCharacters {
    /// Replaces characters in a string by iterating over a HashMap and replacing matched keys with it's value.
    ///
    /// # Arguments
    ///
    /// * `map` - A HashMap that maps characters to be replaced with the character to replace it with.
    fn replace_characters(&self, map: &HashMap<String, String>) -> String;
}

impl<T: AsRef<str>> ReplaceCharacters for T {
    fn replace_characters(&self, map: &HashMap<String, String>) -> String {
        let mut sorted_map: Vec<_> = map.iter().collect();
        sorted_map.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
    
        sorted_map.iter().fold(self.as_ref().to_string(), |acc, (k, v)| {
            acc.replace(k.as_str(), v.as_str())
        })
    }
}

/// Creates a HashMap that maps full-width characters to half-width characters or vice versa.
///
/// # Arguments
///
/// * `reverse` - A boolean that determines whether or not to reverse the mapping for
/// converting half-width characters to full-width characters.
fn create_map(reverse: bool) -> HashMap<String, String> {
    let mut map = HashMap::new();

    map.extend(create_alpha_numeric_map(reverse));
    map.extend(create_symbols_map(reverse));
    map.extend(create_kana_map(reverse));
    map.extend(create_hangul_map(reverse));

    map
}

/// Creates a HashMap that maps full-width characters to half-width characters or vice versa,
/// allowing to customize which characters to ignore.
///
/// # Arguments
///
/// * `ignore` - A vector of strings that will be ignored when converting.
/// * `alpha` - A boolean that determines whether or not to convert alphanumeric characters.
/// * `symbols` - A boolean that determines whether or not to convert symbols.
/// * `kana` - A boolean that determines whether or not to convert kana characters.
/// * `hangul` - A boolean that determines whether or not to convert hangul characters.
/// * `reverse` - A boolean that determines whether or not to reverse the mapping for
/// converting half-width characters to full-width characters.
///
/// # Errors
///
/// Returns an error if any of the characters in `ignore` are not valid characters to ignore.
/// Meaning they are not alphanumeric, symbols, kana, hangul characters or are not half-width
/// when converting to full-width and vice versa.
fn create_map_ext(
    ignore: Vec<&str>,
    alpha: bool,
    symbols: bool,
    kana: bool,
    hangul: bool,
    reverse: bool,
) -> Result<HashMap<String, String>, String> {
    let mut map = HashMap::new();

    if alpha { map.extend(create_alpha_numeric_map(reverse)); }
    if symbols { map.extend(create_symbols_map(reverse)); }
    if kana { map.extend(create_kana_map(reverse)); }
    if hangul { map.extend(create_hangul_map(reverse)); }

    for i in ignore.iter() {
        match map.remove(*i) {
            Some(_) => (),
            None => return Err(format!("'{}' is not a valid character to ignore.", i)),
        }
    }

    Ok(map)
}

/// Creates a HashMap that maps full-width characters to half-width characters for
/// alphanumeric characters.
///
/// # Arguments
///
/// * `reverse` - A boolean that determines whether or not to reverse the mapping for
/// converting half-width characters to full-width characters.
fn create_alpha_numeric_map(reverse: bool) -> HashMap<String, String> {
    let mut map = HashMap::new();

    let full_width = vec![
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "",
    ];

    let half_width = vec![
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
        "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b",
        "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
        "v", "w", "x", "y", "z",
    ];

    for (i, j) in full_width.iter().zip(half_width.iter()) {
        match reverse {
            true => map.insert(j.to_string(), i.to_string()),
            false => map.insert(i.to_string(), j.to_string()),
        };
    }

    map
}

/// Creates a HashMap that maps full-width characters to half-width characters for symbols.
///
/// # Arguments
///
/// * `reverse` - A boolean that determines whether or not to reverse the mapping for
/// converting half-width characters to full-width characters.
fn create_symbols_map(reverse: bool) -> HashMap<String, String> {
    let mut map = HashMap::new();

    let full_width = vec![
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "_", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", " ",
    ];

    let half_width = vec![
        "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/",
        ":", ";", "<", "=", ">", "?", "@", "[", "\\", "]", "^", "_", "`", "{", "|",
        "}", "~", "", "", "¢", "£", "¬", "¯", "¦", "¥", "", " ",
    ];

    for (i, j) in full_width.iter().zip(half_width.iter()) {
        match reverse {
            true => map.insert(j.to_string(), i.to_string()),
            false => map.insert(i.to_string(), j.to_string()),
        };
    }

    map
}

/// Creates a HashMap that maps full-width characters to half-width characters for
/// kana characters.
///
/// # Arguments
///
/// * `reverse` - A boolean that determines whether or not to reverse the mapping for
/// converting half-width characters to full-width characters.
fn create_kana_map(reverse: bool) -> HashMap<String, String> {
    let mut map = HashMap::new();

    let mut full_width = vec![
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "", "", "", "", "", "", "",
    ];

    let mut half_width = vec![
        "", "", "", "", "", "", "", "", "", "", "", "ガ", "", "ギ", "",
        "グ", "", "ゲ", "", "ゴ", "", "ザ", "", "ジ", "", "ズ", "", "ゼ", "ソ", "ゾ", "",
        "ダ", "", "ヂ", "", "", "ヅ", "", "デ", "", "ド", "", "", "", "", "", "",
        "バ", "パ", "", "ビ", "ピ", "", "ブ", "プ", "", "ベ", "ペ", "", "ボ", "ポ", "", "",
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "", "", "ヴ", "ヷ", "ヺ", "", "", "", "",
    ];

    if !reverse {
        full_width.push("");
        half_width.push("");

        full_width.push("");
        half_width.push("");
    }

    for (i, j) in full_width.iter().zip(half_width.iter()) {
        match reverse {
            true => map.insert(j.to_string(), i.to_string()),
            false => map.insert(i.to_string(), j.to_string()),
        };
    }

    map
}

/// Creates a HashMap that maps full-width characters to half-width characters for
/// hangul characters.
///
/// # Arguments
///
/// * `reverse` - A boolean that determines whether or not to reverse the mapping for
/// converting half-width characters to full-width characters.
fn create_hangul_map(reverse: bool) -> HashMap<String, String> {
    let mut map = HashMap::new();

    let full_width = vec![
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // U+313x
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // U+314x
        "", "", "", "", "", "", "", "", "", "", "", "", // U+314F, U+315x
        "", "", "", "", "", "", "", "", "", // U+315B-F, U+316x
    ];

    let half_width = vec![
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // U+FFAx
        "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // U+FFBx
        "", "", "", "", "", "", "", "", "", "", "", "", // U+FFCx
        "", "", "", "", "", "", "", "", "", // U+FFDx
    ];

    for (i, j) in full_width.iter().zip(half_width.iter()) {
        match reverse {
            true => map.insert(j.to_string(), i.to_string()),
            false => map.insert(i.to_string(), j.to_string()),
        };
    }

    map
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_alpha_numeric_map() {
        let full_width = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        let half_width = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        for (full, half) in full_width.chars().zip(half_width.chars()) {
            assert_eq!(full.to_string().to_half_width(), half.to_string());
            assert_eq!(half.to_string().to_full_width(), full.to_string());
        }
    }

    #[test]
    fn test_symbols_map() {
        let full_width = "!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~。、¢£¬ ̄¦¥₩ ";
        let half_width = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~。、¢£¬¯¦¥₩ ";

        for (full, half) in full_width.chars().zip(half_width.chars()) {
            assert_eq!(full.to_string().to_half_width(), half.to_string());
            assert_eq!(half.to_string().to_full_width(), full.to_string());
        }
    }

    #[test]
    fn test_kana_map() {
        let full_width = "ァアィイゥウェエォオカキクケコサシスセソタチッツテトナニヌネノハヒフヘホマミムメモャヤュユョヨラリルレロヮワヲン・ー「」ヵヶ";
        let half_width = "ァアィイゥウェエォオカキクケコサシスセソタチッツテトナニヌネノハヒフヘホマミムメモャヤュユョヨラリルレロワワヲン・ー「」カケ";

        for (full, half) in full_width.chars().zip(half_width.chars()) {
            // EDGE CASE: ヮワ -> ワワ
            if full == '' || half == '' {
                assert_eq!(full.to_string().to_half_width(), "".to_string());
                assert_eq!(half.to_string().to_full_width(), "".to_string());
                continue;
            }

            // EDGE CASE: ヵヶ -> カケ -> カケ
            // These characters are not in the map in reverse mode.
            if full == '' || half == '' {
                assert_eq!(full.to_string().to_half_width(), "".to_string());
                assert_eq!(half.to_string().to_full_width(), "".to_string());
                continue;
            }

            if full == '' || half == '' {
                assert_eq!(full.to_string().to_half_width(), "".to_string());
                assert_eq!(half.to_string().to_full_width(), "".to_string());
                continue;
            }

            assert_eq!(full.to_string().to_half_width(), half.to_string());
            assert_eq!(half.to_string().to_full_width(), full.to_string());
        }

        let special_full_width = "ガギグゲゴザジズゼゾダヂヅデドバパビピブプベペボポヴヷヺ";
        let special_half_width = vec![
            "ガ", "ギ", "グ", "ゲ", "ゴ", "ザ", "ジ", "ズ", "ゼ", "ゾ", "ダ", "ヂ", "ヅ", "デ", "ド",
            "バ", "パ", "ビ", "ピ", "ブ", "プ", "ベ", "ペ", "ボ", "ポ", "ヴ", "ヷ", "ヺ"
        ];

        for (full, half) in special_full_width.chars().zip(special_half_width.iter()) {
            assert_eq!(full.to_string().to_half_width(), half.to_string());
            assert_eq!(half.to_string().to_full_width(), full.to_string());
        }
    }

    #[test]
    fn test_hangul_map() {
        let full_width = "ㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ"; 
        let half_width = "ᄀᄁᆪᄂᆬᆭᄃᄄᄅᆰᆱᆲᆳᆴᆵᄚᄆᄇᄈᄡᄉᄊᄋᄌᄍᄎᄏᄐᄑ하ᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵ";

        for (full, half) in full_width.chars().zip(half_width.chars()) {
            assert_eq!(full.to_string().to_half_width(), half.to_string());
            assert_eq!(half.to_string().to_full_width(), full.to_string());
        }
    }

    #[test]
    fn test_character_width_trait() {
        let full_width_string = "Hello World!";
        let half_width_string = "Hello World!";
        assert_eq!(full_width_string.to_half_width(), half_width_string);

        // Alpha Numerics Ignored
        assert_eq!(
            full_width_string.to_half_width_ext(vec![], false, true, true, true).unwrap(),
            "Hello World!"
        );

        // Symbols Ignored
        assert_eq!(
            full_width_string.to_half_width_ext(vec![], true, false, true, true).unwrap(),
            "Hello World!"
        );

        let full_width_string = "カタカナ";
        let half_width_string = "カタカナ";
        assert_eq!(full_width_string.to_half_width(), half_width_string);

        // Kana Ignored
        assert_eq!(
            full_width_string.to_half_width_ext(vec![], true, true, false, true).unwrap(),
            full_width_string
        );

        let full_width_string = "ㅈㅉ";
        let half_width_string = "ᄌᄍ";
        assert_eq!(full_width_string.to_half_width(), half_width_string);

        // Hangul Ignored
        assert_eq!(
            full_width_string.to_half_width_ext(vec![], true, true, true, false).unwrap(),
            full_width_string
        );

        let full_width_string = "Hello World!カタカナㅈㅉ";
        let half_width_string = "Hello World!カタカナᄌᄍ";
        assert_eq!(full_width_string.to_half_width(), half_width_string);

        // All Ignored
        assert_eq!(
            full_width_string.to_half_width_ext(vec![], false, false, false, false).unwrap(),
            full_width_string
        );

        // Test specific characters ignored
        let full_width_string = "Hello World!カタカナㅈㅉ";
        let half_width_string = "Hello World!カタカナㅈᄍ";
        assert_eq!(
            full_width_string.to_half_width_ext(vec!["", "", "", ""], true, true, true, true).unwrap(),
            half_width_string
        );

        // Test invalid characters ignored
        assert!(full_width_string.to_half_width_ext(vec!["!"], true, true, true, true).is_err());
        assert!(half_width_string.to_full_width_ext(vec![""], true, true, true, true).is_err());
    }

    #[test]
    fn test_replace_characters_trait() {
        let mut map = HashMap::new();
        map.insert("a".to_string(), "b".to_string());

        let string = "abcdefg";
        assert_eq!(string.replace_characters(&map), "bbcdefg");
    }
}