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| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
17    }
18
19    /// Writes the decoded content to `path` with the extension appended.
20    ///
21    /// Parent directories are created if they don't exist.
22    pub fn write(&self, path: &std::path::Path) -> std::io::Result<()> {
23        let path = path.with_extension(self.extension);
24        if let Some(parent) = path.parent() {
25            std::fs::create_dir_all(parent)?;
26        }
27        std::fs::write(&path, self.decode()?)
28    }
29}
30
31/// Parses a data URL, returning `(full_mime, base64_payload)`.
32///
33/// Expects the format `data:{type}/{subtype};base64,{payload}`.
34/// Returns `None` if the URL is not a valid base64 data URL.
35pub(crate) fn parse_data_url(url: &str) -> Option<(&str, &str)> {
36    let rest = url.strip_prefix("data:")?;
37    let (mime, payload) = rest.split_once(";base64,")?;
38    Some((mime, payload))
39}
40
41/// Maps a full MIME type to a file extension using `mime2ext`.
42///
43/// Falls back to `"bin"` if the MIME type is not recognized.
44pub(crate) fn mime_to_ext(mime: &str) -> &str {
45    mime2ext::mime2ext(mime).unwrap_or("bin")
46}