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
extern crate bczhc_lib;

use bczhc_lib::io::ReadLines;
use clap::{Arg, ArgAction, Command};
use std::io::{stdin, Read};
use unicode_segmentation::UnicodeSegmentation;

enum ReverseMode {
    Line,
    All,
}

fn main() -> Result<(), String> {
    let matches = Command::new("reverse")
        .arg(
            Arg::new("line")
                .short('l')
                .long("line")
                .conflicts_with("all")
                .action(ArgAction::SetTrue)
                .help("Reverse string by each line"),
        )
        .arg(
            Arg::new("all")
                .short('a')
                .long("all")
                .conflicts_with("line")
                .action(ArgAction::SetTrue)
                .help("Reverse all string read from stdin; this is the default mode"),
        )
        .arg(
            Arg::new("grapheme")
                .short('g')
                .long("grapheme")
                .help("Reverse by Unicode grapheme clusters")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    let mut reverse_mode = ReverseMode::Line;
    if matches.get_flag("all") {
        reverse_mode = ReverseMode::All
    }

    let grapheme = matches.get_flag("grapheme");

    let mut stdin = stdin().lock();

    match reverse_mode {
        ReverseMode::All => {
            let mut read = String::new();
            stdin.read_to_string(&mut read).unwrap();
            println!("{}", reverse_string(&read, grapheme));
        }
        ReverseMode::Line => {
            for line in stdin.lines() {
                println!("{}", reverse_string(&line, grapheme));
            }
        }
    }

    Ok(())
}

fn reverse_string(s: &str, grapheme_cluster: bool) -> String {
    if grapheme_cluster {
        s.graphemes(true).rev().collect()
    } else {
        s.chars().rev().collect()
    }
}