1use std::path::Path;
4
5use tempfile::NamedTempFile;
6
7use crate::FormError;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum FileStorage {
12 #[default]
14 Memory,
15 TempFile,
17}
18
19#[derive(Debug)]
21pub struct UploadedFile {
22 filename: Option<String>,
23 content_type: Option<String>,
24 payload: FilePayload,
25}
26
27#[derive(Debug)]
28enum FilePayload {
29 Bytes(Vec<u8>),
30 Temp(NamedTempFile),
31}
32
33impl UploadedFile {
34 #[must_use]
36 pub const fn from_bytes(
37 filename: Option<String>,
38 content_type: Option<String>,
39 bytes: Vec<u8>,
40 ) -> Self {
41 Self {
42 filename,
43 content_type,
44 payload: FilePayload::Bytes(bytes),
45 }
46 }
47
48 pub fn from_tempfile(
54 filename: Option<String>,
55 content_type: Option<String>,
56 bytes: &[u8],
57 ) -> Result<Self, FormError> {
58 let mut file = NamedTempFile::new()
59 .map_err(|err| FormError::Upload(format!("failed to create tempfile: {err}")))?;
60 std::io::Write::write_all(&mut file, bytes)
61 .map_err(|err| FormError::Upload(format!("failed to write tempfile: {err}")))?;
62 Ok(Self {
63 filename,
64 content_type,
65 payload: FilePayload::Temp(file),
66 })
67 }
68
69 #[must_use]
71 pub fn filename(&self) -> Option<&str> {
72 self.filename.as_deref()
73 }
74
75 #[must_use]
77 pub fn content_type(&self) -> Option<&str> {
78 self.content_type.as_deref()
79 }
80
81 #[must_use]
83 pub fn len(&self) -> usize {
84 match &self.payload {
85 FilePayload::Bytes(bytes) => bytes.len(),
86 FilePayload::Temp(file) => file
87 .as_file()
88 .metadata()
89 .map_or(0, |meta| usize::try_from(meta.len()).unwrap_or(usize::MAX)),
90 }
91 }
92
93 #[must_use]
95 pub fn is_empty(&self) -> bool {
96 self.len() == 0
97 }
98
99 #[must_use]
101 pub const fn as_bytes(&self) -> Option<&[u8]> {
102 match &self.payload {
103 FilePayload::Bytes(bytes) => Some(bytes.as_slice()),
104 FilePayload::Temp(_) => None,
105 }
106 }
107
108 #[must_use]
110 pub fn path(&self) -> Option<&Path> {
111 match &self.payload {
112 FilePayload::Bytes(_) => None,
113 FilePayload::Temp(file) => Some(file.path()),
114 }
115 }
116
117 pub fn into_bytes(self) -> Result<Vec<u8>, FormError> {
123 match self.payload {
124 FilePayload::Bytes(bytes) => Ok(bytes),
125 FilePayload::Temp(file) => std::fs::read(file.path())
126 .map_err(|err| FormError::Upload(format!("failed to read tempfile: {err}"))),
127 }
128 }
129}