Skip to main content

objectiveai_sdk/agent/completions/message/
file_content.rs

1/// Extractable file content from a media type.
2///
3/// `content` is the raw payload (e.g. base64-encoded data).
4/// `extension` is the file extension to use (e.g. `"png"`, `"wav"`).
5pub struct FileContent<'s> {
6    pub content: &'s str,
7    pub extension: &'s str,
8}
9
10impl FileContent<'_> {
11    /// Decodes the base64 content into raw bytes.
12    pub fn decode(&self) -> std::io::Result<Vec<u8>> {
13        use base64::Engine;
14        base64::engine::general_purpose::STANDARD
15            .decode(self.content)
16            .map_err(|e| {
17                std::io::Error::new(std::io::ErrorKind::InvalidData, e)
18            })
19    }
20
21    /// Writes the decoded content to `path` with the extension appended.
22    ///
23    /// Parent directories are created if they don't exist.
24    pub fn write(&self, path: &std::path::Path) -> std::io::Result<()> {
25        let path = path.with_extension(self.extension);
26        if let Some(parent) = path.parent() {
27            std::fs::create_dir_all(parent)?;
28        }
29        std::fs::write(&path, self.decode()?)
30    }
31}
32
33/// Maps a full MIME type to a file extension using `mime2ext`.
34///
35/// Falls back to `"bin"` if the MIME type is not recognized.
36pub(crate) fn mime_to_ext(mime: &str) -> &str {
37    mime2ext::mime2ext(mime).unwrap_or("bin")
38}