colors_transform/
from_str.rs1use super::converters::hex_num_to_rgb;
2use super::error::{
3 make_def_parse_err, make_hex_parse_err, make_hsl_parse_err, make_hsla_parse_err,
4 make_rgb_parse_err, make_rgba_parse_err, ParseError,
5};
6use super::{ColorTuple, ColorTupleA};
7
8pub fn hex(s: &str) -> Result<ColorTuple, ParseError> {
9 let mut hex = s.replace("#", "").to_lowercase();
10 let count = hex.chars().count();
11
12 if count == 3 {
13 hex = hex.chars().map(|c| c.to_string().repeat(2)).collect::<Vec<String>>().join("");
14 } else if count != 6 {
15 return Err(make_hex_parse_err(s));
16 }
17
18 match usize::from_str_radix(&hex, 16) {
19 Ok(num) => Ok(hex_num_to_rgb(num)),
20 Err(_) => Err(make_hex_parse_err(s)),
21 }
22}
23
24fn clear_str(s: &str) -> String {
25 let mut result = s.to_lowercase();
26 for p in ["rgba", "rgb", "hsla", "hsl", "(", ")", "%", " "].iter() {
27 result = result.replace(p, "");
28 }
29 result
30}
31
32fn collect_vec_and_parse(s: &str) -> Result<Vec<f32>, std::num::ParseFloatError> {
33 let v = s.split(',').map(|c| c.to_string()).collect::<Vec<String>>();
34
35 let mut units = Vec::new();
36
37 for unit in v {
38 let u = unit.parse::<f32>()?;
39 units.push(u);
40 }
41
42 Ok(units)
43}
44
45fn parse_color_tuple(s: &str) -> Result<ColorTuple, ParseError> {
46 match collect_vec_and_parse(&clear_str(s)) {
47 Ok(num_vec) => {
48 if num_vec.len() != 3 {
49 Err(make_def_parse_err(&s))
50 } else {
51 Ok((num_vec[0], num_vec[1], num_vec[2]))
52 }
53 }
54 Err(_) => Err(make_def_parse_err(&s)),
55 }
56}
57
58fn parse_color_tuple_a(s: &str) -> Result<ColorTupleA, ParseError> {
59 match collect_vec_and_parse(&clear_str(s)) {
60 Ok(num_vec) => {
61 if num_vec.len() != 4 {
62 Err(make_def_parse_err(&s))
63 } else {
64 Ok((num_vec[0], num_vec[1], num_vec[2], num_vec[3]))
65 }
66 }
67 Err(_) => Err(make_def_parse_err(&s)),
68 }
69}
70
71pub fn rgb(s: &str) -> Result<ColorTuple, ParseError> {
72 match parse_color_tuple(s) {
73 Err(_) => Err(make_rgb_parse_err(s)),
74 Ok(rgb) => Ok(rgb),
75 }
76}
77
78pub fn rgba(s: &str) -> Result<ColorTupleA, ParseError> {
79 match parse_color_tuple_a(s) {
80 Err(_) => Err(make_rgba_parse_err(s)),
81 Ok(rgba) => Ok(rgba),
82 }
83}
84
85pub fn hsl(s: &str) -> Result<ColorTuple, ParseError> {
86 match parse_color_tuple(s) {
87 Err(_) => Err(make_hsl_parse_err(s)),
88 Ok(hsl) => Ok(hsl),
89 }
90}
91
92pub fn hsla(s: &str) -> Result<ColorTupleA, ParseError> {
93 match parse_color_tuple_a(s) {
94 Err(_) => Err(make_hsla_parse_err(s)),
95 Ok(hsla) => Ok(hsla),
96 }
97}