1use std::fmt;
2use std::ops::Deref;
3use serde_json::Value;
4use serde::{Deserialize, Serialize};
5
6#[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 pub fn new(type_: &str, data: Value) -> Self {
34 Segment {
35 type_: type_.to_string(),
36 data,
37 }
38 }
39
40 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#[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}