termichart_data/
json_adapter.rs1use std::fs;
2
3use termichart_core::{Candle, DataAdapter, Point, Result, TermichartError};
4
5pub struct JsonAdapter {
7 data: String,
8}
9
10impl JsonAdapter {
11 pub fn from_str(s: &str) -> Self {
13 Self {
14 data: s.to_owned(),
15 }
16 }
17
18 pub fn from_file(path: &str) -> Result<Self> {
20 let data = fs::read_to_string(path)?;
21 Ok(Self { data })
22 }
23}
24
25impl DataAdapter for JsonAdapter {
26 fn candles(&self) -> Result<Vec<Candle>> {
27 serde_json::from_str(&self.data).map_err(|e| TermichartError::ParseError(e.to_string()))
28 }
29
30 fn points(&self) -> Result<Vec<Point>> {
31 serde_json::from_str(&self.data).map_err(|e| TermichartError::ParseError(e.to_string()))
32 }
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn parse_candles_from_json() {
41 let json = r#"[
42 {"time":1.0,"open":10.0,"high":15.0,"low":9.0,"close":14.0,"volume":100.0},
43 {"time":2.0,"open":14.0,"high":16.0,"low":13.0,"close":15.0,"volume":200.0}
44 ]"#;
45 let adapter = JsonAdapter::from_str(json);
46 let candles = adapter.candles().unwrap();
47 assert_eq!(candles.len(), 2);
48 assert_eq!(candles[0].open, 10.0);
49 assert_eq!(candles[1].close, 15.0);
50 }
51
52 #[test]
53 fn parse_points_from_json() {
54 let json = r#"[{"x":1.0,"y":2.0},{"x":3.0,"y":4.0}]"#;
55 let adapter = JsonAdapter::from_str(json);
56 let points = adapter.points().unwrap();
57 assert_eq!(points.len(), 2);
58 assert_eq!(points[0].x, 1.0);
59 assert_eq!(points[1].y, 4.0);
60 }
61
62 #[test]
63 fn invalid_json_returns_parse_error() {
64 let adapter = JsonAdapter::from_str("not json");
65 assert!(adapter.candles().is_err());
66 }
67}