use std::{fmt, sync::Arc};
use crate::Value;
#[derive(Clone, PartialEq, Eq)]
pub struct Upload {
filename: Option<Arc<str>>,
content_type: Option<Arc<str>>,
bytes: Arc<[u8]>,
}
impl Upload {
#[must_use]
pub fn new(
filename: impl Into<Arc<str>>,
content_type: impl Into<Arc<str>>,
bytes: impl Into<Arc<[u8]>>,
) -> Self {
Self {
filename: Some(filename.into()),
content_type: Some(content_type.into()),
bytes: bytes.into(),
}
}
#[must_use]
pub fn from_parts(
filename: Option<Arc<str>>,
content_type: Option<Arc<str>>,
bytes: Arc<[u8]>,
) -> Self {
Self {
filename,
content_type,
bytes,
}
}
#[must_use]
pub fn filename(&self) -> Option<&str> {
self.filename.as_deref()
}
#[must_use]
pub fn content_type(&self) -> Option<&str> {
self.content_type.as_deref()
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub fn into_bytes(self) -> Arc<[u8]> {
self.bytes
}
#[must_use]
pub fn len(&self) -> usize {
self.bytes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
impl fmt::Debug for Upload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Upload")
.field("filename", &self.filename)
.field("content_type", &self.content_type)
.field("len", &self.bytes.len())
.finish()
}
}
impl From<Upload> for Value {
fn from(value: Upload) -> Self {
Self::external(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_does_not_print_contents() {
let upload = Upload::new("a.txt", "text/plain", b"top secret".to_vec());
let debug = format!("{upload:?}");
assert!(debug.contains("a.txt"));
assert!(debug.contains("text/plain"));
assert!(!debug.contains("top secret"));
}
#[test]
fn value_round_trips_through_external() {
let upload = Upload::new("a.txt", "text/plain", b"hello".to_vec());
let value = Value::from(upload);
let borrowed = value.as_external::<Upload>().expect("upload");
assert_eq!(borrowed.filename(), Some("a.txt"));
assert_eq!(borrowed.bytes(), b"hello");
}
}