rust_web_server/json/array/float/
mod.rs

1use crate::json::array::RawUnprocessedJSONArray;
2use crate::symbol::SYMBOL;
3
4#[cfg(test)]
5mod example_list_f64_with_asserts;
6#[cfg(test)]
7mod example_list_f64;
8#[cfg(test)]
9mod example_list_f32_with_asserts;
10#[cfg(test)]
11mod example_list_f32;
12
13pub struct JSONArrayOfFloats;
14impl JSONArrayOfFloats {
15    pub fn parse_as_list_f64(json : String) -> Result<Vec<f64>, String> {
16        let items = RawUnprocessedJSONArray::split_into_vector_of_strings(json).unwrap();
17        let mut list: Vec<f64> = vec![];
18        for item in items {
19            let boxed_parse = item.parse::<f64>();
20            if boxed_parse.is_err() {
21                let message = boxed_parse.err().unwrap().to_string();
22                return Err(message);
23            }
24            let num : f64 = boxed_parse.unwrap();
25            list.push(num);
26        }
27        Ok(list)
28    }
29
30    pub fn to_json_from_list_f64(items : &Vec<f64>) -> Result<String, String> {
31        let mut json_vec = vec![];
32        json_vec.push(SYMBOL.opening_square_bracket.to_string());
33        for (pos, item) in items.iter().enumerate() {
34            let mut formatted = "0.0".to_string();
35            if item != &0.0 {
36                formatted = item.to_string();
37            }
38            json_vec.push(formatted);
39            if pos != items.len() - 1 {
40                json_vec.push(SYMBOL.comma.to_string());
41            }
42        }
43        json_vec.push(SYMBOL.closing_square_bracket.to_string());
44
45        let result = json_vec.join(SYMBOL.empty_string);
46        Ok(result)
47    }
48
49    pub fn parse_as_list_f32(json : String) -> Result<Vec<f32>, String> {
50        let items = RawUnprocessedJSONArray::split_into_vector_of_strings(json).unwrap();
51        let mut list: Vec<f32> = vec![];
52        for item in items {
53            let boxed_parse = item.parse::<f32>();
54            if boxed_parse.is_err() {
55                let message = boxed_parse.err().unwrap().to_string();
56                return Err(message);
57            }
58            let num : f32 = boxed_parse.unwrap();
59            list.push(num);
60        }
61        Ok(list)
62    }
63
64    pub fn to_json_from_list_f32(items : &Vec<f32>) -> Result<String, String> {
65        let mut json_vec = vec![];
66        json_vec.push(SYMBOL.opening_square_bracket.to_string());
67        for (pos, item) in items.iter().enumerate() {
68            let mut formatted = "0.0".to_string();
69            if item != &0.0 {
70                formatted = item.to_string();
71            }
72            json_vec.push(formatted);
73            if pos != items.len() - 1 {
74                json_vec.push(SYMBOL.comma.to_string());
75            }
76        }
77        json_vec.push(SYMBOL.closing_square_bracket.to_string());
78
79        let result = json_vec.join(SYMBOL.empty_string);
80        Ok(result)
81    }
82}