use crate::debug_print_bytes;
use base64::DecodeError;
use bytes::Bytes;
#[cfg(feature = "fp-bindgen")]
use fp_bindgen::prelude::Serializable;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fmt::{self, Debug, Formatter};
use typed_builder::TypedBuilder;
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
feature = "fp-bindgen",
derive(Serializable),
fp(rust_module = "fiberplane_models::blobs")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Blob {
#[builder(setter(into))]
pub data: Bytes,
#[builder(setter(into))]
pub mime_type: String,
}
impl TryFrom<EncodedBlob> for Blob {
type Error = DecodeError;
fn try_from(blob: EncodedBlob) -> Result<Self, Self::Error> {
Ok(Self {
data: base64::decode(&blob.data)?.into(),
mime_type: blob.mime_type,
})
}
}
impl TryFrom<&EncodedBlob> for Blob {
type Error = DecodeError;
fn try_from(blob: &EncodedBlob) -> Result<Self, Self::Error> {
Ok(Self {
data: base64::decode(&blob.data)?.into(),
mime_type: blob.mime_type.clone(),
})
}
}
impl Debug for Blob {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Blob")
.field("mime_type", &self.mime_type)
.field("data_length", &self.data.len())
.field("data", &debug_print_bytes(&self.data))
.finish()
}
}
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
feature = "fp-bindgen",
derive(Serializable),
fp(rust_module = "fiberplane_models::blobs")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct EncodedBlob {
#[builder(setter(into))]
pub data: String,
#[builder(setter(into))]
pub mime_type: String,
}
impl From<Blob> for EncodedBlob {
fn from(blob: Blob) -> Self {
Self {
data: base64::encode(blob.data.as_ref()),
mime_type: blob.mime_type,
}
}
}
impl From<&Blob> for EncodedBlob {
fn from(blob: &Blob) -> Self {
Self {
data: base64::encode(blob.data.as_ref()),
mime_type: blob.mime_type.clone(),
}
}
}
impl Debug for EncodedBlob {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("EncodedBlob")
.field("mime_type", &self.mime_type)
.field("data_length", &self.data.len())
.field("data", &debug_print_bytes(self.data.as_bytes()))
.finish()
}
}