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
pub mod constants;
pub mod status_keys;
pub mod switch;
pub mod terminal_features;
pub mod user_option;

pub use constants::*;
pub use status_keys::StatusKeys;
pub use switch::Switch;
pub use terminal_features::*;
pub use user_option::*;

// command_alias[0] = "alias1" => command_alias["alias1"]
// command_alias[1] = "alias2" => command_alias["alias2"]
// ...
// command_alias[n] = "aliasN" => command_alias["aliasN"]
// TODO: optimization, merge server, session, window, pane?

const SEPARATOR: &str = " ";

use std::borrow::Cow;
use std::fmt;

pub fn option_to_string<S: fmt::Display>(v: &mut Vec<String>, name: &str, value: &Option<S>) {
    if let Some(data) = value {
        v.push(format!("{} {}", name, data))
    }
}

pub fn option_array_to_string<S: fmt::Display>(
    v: &mut Vec<String>,
    name: &str,
    value: &Option<Vec<S>>,
) {
    if let Some(data) = value {
        for item in data {
            v.push(format!("{} {}", name, item))
        }
    }
}

pub fn array_insert(v: &mut Option<Vec<Cow<'_, str>>>, i: Option<usize>, value: Option<String>) {
    if let Some(i) = i {
        match value {
            Some(data) => v.get_or_insert(Vec::new()).insert(i, data.into()),
            None => *v = None,
        }
    }
}

pub fn cow_parse<'a>(value: Option<&str>) -> Option<Cow<'a, str>> {
    value.map(|s| Cow::Owned(s.into()))
}

// split string in 3 parts, name, index (if option is an array) and value
// TODO: rename
pub fn get_parts(s: &str) -> Option<(&str, Option<usize>, Option<&str>)> {
    let v: Vec<&str> = s.trim().splitn(2, SEPARATOR).collect();
    let value = v.get(1).copied();
    match v.first() {
        Some(name) => {
            let v: Vec<&str> = name.split(|c| c == '[' || c == ']').collect();
            match v.first() {
                Some(name) => {
                    let index = v.get(1).and_then(|i| i.parse().ok());
                    Some((name, index, value))
                }
                None => None,
            }
        }
        None => None,
    }
}

#[cfg(test)]
#[path = "."]
mod common_tests {
    pub mod status_keys_tests;
    pub mod switch_tests;
}