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