datastruct_rs/
binary_util.rs

1use anyhow::Context;
2use base64::{engine::general_purpose as base64_engine, Engine as _};
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct Binary {
9    data: Vec<u8>,
10}
11
12impl Binary {
13    /// Creates a new `BinaryUtil` instance from a `Vec<u8>`
14    pub fn new(data: Vec<u8>) -> Self {
15        Self { data }
16    }
17
18    /// Reads a binary file and returns a `BinaryUtil` instance.
19    pub fn from_file(path: PathBuf) -> anyhow::Result<Self> {
20        let data = fs::read(path)?;
21
22        return Ok(Self { data });
23    }
24
25    /// Decode a base64-encoded string and return a `BinaryUtil` instance.
26    pub fn from_b64(value: String) -> anyhow::Result<Self> {
27        let data = base64_engine::STANDARD
28            .decode(&value)
29            .context("Failed to decode base64 string")?;
30        return Ok(Self { data });
31    }
32
33    /// Gets the size of the binary data in bytes.
34    pub fn size(&self) -> usize {
35        return self.data.len();
36    }
37
38    /// Returns a clone of the binary data.
39    pub fn read(&self) -> Vec<u8> {
40        return self.data.clone();
41    }
42}
43
44impl ToString for Binary {
45    fn to_string(&self) -> String {
46        format!(
47            "binary util!({})",
48            base64_engine::STANDARD.encode(self.data.clone())
49        )
50    }
51}