doson/
binary.rs

1use std::path::PathBuf;
2use std::fs;
3
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct Binary {
8    data: Vec<u8>
9}
10
11impl Binary {
12    
13    /// 使用 Vec<U8> 构造二进制数据集
14    pub fn build(data: Vec<u8>) -> Self {
15        Self {
16            data
17        }
18    }
19
20    /// 通过文件读取直接构造二进制数据集
21    pub fn from_file(path: PathBuf) -> anyhow::Result<Self> {
22        let data = fs::read(path)?;
23        return Ok (
24            Self {
25                data
26            }
27        );
28    }
29
30    pub fn from_b64(value: String) -> anyhow::Result<Self> {
31        let data = base64::decode(value)?;
32        return Ok (
33            Self {
34                data
35            }
36        );
37    }
38
39    pub fn size(&self) -> usize {
40        return self.data.len();
41    }
42
43    pub fn read(&self) -> Vec<u8> {
44        return self.data.clone();
45    }
46
47}
48
49impl ToString for Binary {
50    fn to_string(&self) -> String {
51        format!("binary!({})",base64::encode(self.data.clone()))
52    }
53}