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
mod error;
use error::ExtractError;

/// Extract the characters at the given indices from the input string.
///
/// # Examples
///
/// ```
/// use cha_rs::*;
/// let chars = extract("hello", &[1,5]).unwrap();
/// assert_eq!(chars, &['h', 'o']);
/// ```
pub fn extract(input: &str, indices: &[usize]) -> Result<Vec<char>, ExtractError> {
    if indices.is_empty() {
        return Err(ExtractError::NoIndices);
    }
    if indices.iter().any(|i| i == &0 || i > &input.len()) {
        return Err(ExtractError::OutOfRange(input.len()));
    }

    let c: Vec<char> = input
        .chars()
        .enumerate()
        .filter(|&(i, _)| indices.contains(&(i + 1)))
        .map(|(_, c)| c)
        .collect();
    Ok(c)
}

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

    #[test]
    fn test_extract() {
        let got = extract("hello", &[1, 3, 5]).unwrap();
        assert_eq!(got, &['h', 'l', 'o']);
    }

    #[test]
    fn test_extract_out_of_range_low() {
        let got = extract("hello", &[0]);
        assert!(got.is_err())
    }

    #[test]
    fn test_extract_out_of_range_high() {
        let got = extract("hello", &[6]);
        assert!(got.is_err())
    }

    #[test]
    fn test_extract_some_inputs_out_of_range() {
        let got = extract("hello", &[3, 5, 6]);
        assert!(got.is_err())
    }

    #[test]
    fn test_extract_empty_indices() {
        let got = extract("hello", &[]);
        assert!(got.is_err())
    }

    #[test]
    fn test_extract_empty_input() {
        let got = extract("", &[1, 3, 5]);
        assert!(got.is_err())
    }
}