shindan_maker/
segment.rs

1use std::fmt;
2use std::ops::Deref;
3use serde_json::Value;
4use serde::{Deserialize, Serialize};
5
6/// A segment of a shindan result.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct Segment {
9    #[serde(rename = "type")]
10    pub type_: String,
11    pub data: Value,
12}
13
14impl Segment {
15    /**
16    Create a new segment.
17
18    # Arguments
19    - `type_` - The type of the segment.
20    - `data` - The data of the segment.
21
22    # Returns
23    A new segment.
24
25    # Examples
26    ```
27    use serde_json::json;
28    use shindan_maker::Segment;
29
30    let segment = Segment::new("text", json!({"text": "Hello, world!"}));
31    ```
32    */
33    pub fn new(type_: &str, data: Value) -> Self {
34        Segment {
35            type_: type_.to_string(),
36            data,
37        }
38    }
39
40    /**
41    Get the string representation of the segment.
42
43    # Returns
44    - `Some(String)`: The string representation of the segment.
45    - `None`: If the segment type is not text or image.
46
47    # Examples
48    ```
49    use serde_json::json;
50    use shindan_maker::Segment;
51
52    let segment = Segment::new("text", json!({"text": "Hello, world!"}));
53    assert_eq!(segment.get_str(), Some("Hello, world!".to_string()));
54    ```
55    */
56    pub fn get_str(&self) -> Option<String> {
57        match self.type_.as_str() {
58            "text" => self.data.as_object().and_then(|map| map.get("text")).and_then(Value::as_str).map(String::from),
59            "image" => self.data.as_object().and_then(|map| map.get("file")).and_then(Value::as_str).map(String::from),
60            _ => None,
61        }
62    }
63}
64
65impl PartialEq for Segment {
66    fn eq(&self, other: &Self) -> bool {
67        self.type_ == other.type_ && self.data == other.data
68    }
69}
70
71impl Eq for Segment {}
72
73/// A collection of segments.
74#[derive(Debug, Clone)]
75pub struct Segments(pub Vec<Segment>);
76
77impl Deref for Segments {
78    type Target = Vec<Segment>;
79
80    fn deref(&self) -> &Self::Target {
81        &self.0
82    }
83}
84
85impl fmt::Display for Segments {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        let str = self.iter()
88            .map(|segment| segment.get_str().unwrap())
89            .collect::<Vec<String>>()
90            .join("");
91        write!(f, "{}", str)
92    }
93}