|
| 1 | +use std::fs; |
| 2 | +use std::process; |
| 3 | + |
| 4 | +fn read_colors(path: &str) -> Vec<String> { |
| 5 | + /* |
| 6 | + * read colors from a raw text file located at path |
| 7 | + * append the colors to a vector of String and return it |
| 8 | + */ |
| 9 | + let mut colors: Vec<String> = Vec::new(); |
| 10 | + |
| 11 | + let contents = fs::read_to_string(&path) |
| 12 | + .unwrap_or_else(|err| { |
| 13 | + println!("error: {}", err); |
| 14 | + process::exit(0); |
| 15 | + }); |
| 16 | + |
| 17 | + let contents: Vec<&str> = contents.lines().collect(); |
| 18 | + |
| 19 | + for color in contents { |
| 20 | + colors.push(String::from(color)); |
| 21 | + } |
| 22 | + |
| 23 | + return colors; |
| 24 | +} |
| 25 | + |
| 26 | +fn get_color_num(line: &String) -> Vec<String> { |
| 27 | + /* |
| 28 | + * in a template file, Xn indicates the nth color |
| 29 | + * which should be substituted. this function retuns |
| 30 | + * all the n in a line |
| 31 | + */ |
| 32 | + |
| 33 | + // the vector which will be returned |
| 34 | + let mut result: Vec<String> = Vec::new(); |
| 35 | + |
| 36 | + let matches: Vec<_> = line.match_indices(char::is_numeric).collect(); |
| 37 | + |
| 38 | + // find a better to avoid edge cases |
| 39 | + let mut prev_index = 1000; |
| 40 | + |
| 41 | + for m in matches.iter() { |
| 42 | + // get the index number |
| 43 | + let ind = m.0; |
| 44 | + |
| 45 | + // get the matching character |
| 46 | + let mut ch = String::from(m.1); |
| 47 | + |
| 48 | + // get the previous char is an X |
| 49 | + let prev_ch = line.get(ind-1..ind).unwrap_or(""); |
| 50 | + |
| 51 | + // check if the previous char is an X |
| 52 | + // if it is not, skip the iteration |
| 53 | + if prev_ch != "X" { |
| 54 | + continue; |
| 55 | + } |
| 56 | + |
| 57 | + // get the next char and see if it is numeric |
| 58 | + let next_ch = line.get(ind+1..ind+2).unwrap_or(""); |
| 59 | + let next_ch: Vec<_> = next_ch.matches(char::is_numeric).collect(); |
| 60 | + |
| 61 | + // if it is numeric, then set the approriate prev_index and skip |
| 62 | + // the iteration |
| 63 | + if next_ch.len() > 0 { |
| 64 | + prev_index = ind; |
| 65 | + continue; |
| 66 | + } |
| 67 | + |
| 68 | + // check if the previous index is the one we stored |
| 69 | + // if it is, then it means we have to prepend it |
| 70 | + if ind-1 == prev_index { |
| 71 | + ch = String::from(format!("{}{}", line.get(prev_index..ind).unwrap(), ch)); |
| 72 | + } |
| 73 | + |
| 74 | + // update the prev_index |
| 75 | + prev_index = ind; |
| 76 | + |
| 77 | + result.push(String::from(ch)); |
| 78 | + } |
| 79 | + |
| 80 | + return result |
| 81 | +} |
0 commit comments