1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::fmt;
4use std::ops::Deref;
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
59 .data
60 .as_object()
61 .and_then(|map| map.get("text"))
62 .and_then(Value::as_str)
63 .map(String::from),
64 "image" => self
65 .data
66 .as_object()
67 .and_then(|map| map.get("file"))
68 .and_then(Value::as_str)
69 .map(String::from),
70 _ => None,
71 }
72 }
73}
74
75impl PartialEq for Segment {
76 fn eq(&self, other: &Self) -> bool {
77 self.type_ == other.type_ && self.data == other.data
78 }
79}
80
81impl Eq for Segment {}
82
83#[derive(Debug, Clone)]
85pub struct Segments(pub Vec<Segment>);
86
87impl Deref for Segments {
88 type Target = Vec<Segment>;
89
90 fn deref(&self) -> &Self::Target {
91 &self.0
92 }
93}
94
95impl fmt::Display for Segments {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 let str = self
98 .iter()
99 .map(|segment| segment.get_str().unwrap())
100 .collect::<Vec<String>>()
101 .join("");
102 write!(f, "{}", str)
103 }
104}