Skip to main content

eclipse_core/
message.rs

1//! OpenAI-compatible chat message types.
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "lowercase")]
7pub enum Role {
8    System,
9    User,
10    Assistant,
11    Tool,
12}
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct FunctionCall {
16    pub name: String,
17    /// JSON-encoded arguments, exactly as the model produced them.
18    pub arguments: String,
19}
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct ToolCall {
23    pub id: String,
24    #[serde(rename = "type", default = "function_kind")]
25    pub kind: String,
26    pub function: FunctionCall,
27}
28
29fn function_kind() -> String {
30    "function".into()
31}
32
33/// One picture attached to a message (`#346`).
34///
35/// The bytes travel *in* the message as a `data:` URL, not as a path. A path is a reference the
36/// model resolves with `read_file` — a tool call the user sees — and a stored session has to be
37/// able to show what was sent without the file still being where it was. The cap and the type
38/// check live where an image enters (`attach`), because this struct is also what a session reads
39/// back from disk and re-checking every row on every load would be a cost for no gain.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct ImagePart {
42    /// What the user called it, for the transcript and the compaction placeholder. Empty when a
43    /// picture arrives without a name.
44    #[serde(default, skip_serializing_if = "String::is_empty")]
45    pub name: String,
46    pub mime: String,
47    /// `data:<mime>;base64,<…>` — the wire's own spelling of a picture, so nothing has to
48    /// reassemble it at request time.
49    pub url: String,
50    /// What a model that can see said about this picture (`#346`), written once.
51    ///
52    /// Kept beside the picture rather than in the prompt: a session replayed a week later must not
53    /// pay for the same description again, and the prompt for a past turn must not change under the
54    /// session that is still talking about it.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub seen: Option<String>,
57}
58
59/// How long a picture's name may be, once it has been cleaned up.
60///
61/// The name is interpolated into the composed block a model reads (`--- attached picture: NAME
62/// (image/png) ---`) and into `label()`, so it is text with a shape, not an arbitrary string: a
63/// newline in it could forge one of those delimiters and a control character could end the line
64/// the compaction log is reading (`#380`).
65const MAX_NAME_CHARS: usize = 100;
66
67/// A name safe to put in a line of text: control characters become spaces, runs of whitespace
68/// collapse, and the result is capped. Empty after all that is `picture`.
69fn picture_name(raw: &str) -> String {
70    let flattened: String = raw
71        .chars()
72        .map(|c| if c.is_control() { ' ' } else { c })
73        .collect();
74    let one = flattened.split_whitespace().collect::<Vec<_>>().join(" ");
75    if one.is_empty() {
76        return "picture".to_string();
77    }
78    one.chars().take(MAX_NAME_CHARS).collect()
79}
80
81/// Base64 to bytes, or `None` for anything that is not base64.
82///
83/// Hand-rolled because this crate carries no decoder, and the check is worth more than the
84/// dependency: the point is to reject a payload that is not a picture *once*, before it is stored
85/// and re-sent on every turn, not to be fast. Padding is optional; `=` anywhere but the end is not.
86fn decode_base64(payload: &str) -> Option<Vec<u8>> {
87    fn value(b: u8) -> Option<u32> {
88        Some(match b {
89            b'A'..=b'Z' => (b - b'A') as u32,
90            b'a'..=b'z' => (b - b'a') as u32 + 26,
91            b'0'..=b'9' => (b - b'0') as u32 + 52,
92            b'+' => 62,
93            b'/' => 63,
94            _ => return None,
95        })
96    }
97    let body = payload.trim_end_matches('=');
98    if body.len() % 4 == 1 {
99        return None;
100    }
101    let mut out = Vec::with_capacity(body.len() / 4 * 3 + 3);
102    let mut acc = 0u32;
103    let mut n = 0;
104    for byte in body.bytes() {
105        acc = (acc << 6) | value(byte)?;
106        n += 1;
107        if n == 4 {
108            out.push((acc >> 16) as u8);
109            out.push((acc >> 8) as u8);
110            out.push(acc as u8);
111            acc = 0;
112            n = 0;
113        }
114    }
115    match n {
116        0 => {}
117        2 => out.push((acc >> 4) as u8),
118        3 => {
119            out.push((acc >> 10) as u8);
120            out.push((acc >> 2) as u8);
121        }
122        _ => return None,
123    }
124    Some(out)
125}
126
127/// Bytes to a `data:` URL — the other half of [`decode_base64`], and the only encoder this build
128/// has. Hand-rolled for the same reason: one picture per attach, not a hot path.
129pub fn data_url(mime: &str, bytes: &[u8]) -> String {
130    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
131    let mut out = String::with_capacity(24 + bytes.len() / 3 * 4 + 4);
132    out.push_str("data:");
133    out.push_str(mime);
134    out.push_str(";base64,");
135    for chunk in bytes.chunks(3) {
136        let b = [
137            chunk[0],
138            chunk.get(1).copied().unwrap_or(0),
139            chunk.get(2).copied().unwrap_or(0),
140        ];
141        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
142        out.push(ALPHABET[(n >> 18) as usize & 0x3F] as char);
143        out.push(ALPHABET[(n >> 12) as usize & 0x3F] as char);
144        out.push(if chunk.len() > 1 {
145            ALPHABET[(n >> 6) as usize & 0x3F] as char
146        } else {
147            '='
148        });
149        out.push(if chunk.len() > 2 {
150            ALPHABET[n as usize & 0x3F] as char
151        } else {
152            '='
153        });
154    }
155    out
156}
157
158/// Whether these bytes begin like the picture the header claims they are.
159fn looks_like_picture(mime: &str, bytes: &[u8]) -> bool {
160    match mime {
161        "image/png" => bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]),
162        "image/jpeg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]),
163        "image/gif" => bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a"),
164        "image/webp" => bytes.len() > 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP",
165        _ => false,
166    }
167}
168
169/// The picture types a message may carry, and how big one may be once decoded.
170///
171/// Every surface that accepts a picture checks this — the dashboard's composer and the gateway's
172/// `image_url` parts alike — because a 40 MB phone photo is a 54 MB data URL that rides in the
173/// request body and in every later request's history, and the symptom months later is "the
174/// dashboard got slow" (`#346`, `#364`).
175pub const PICTURE_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
176/// What one picture may weigh *on the wire*: the request body and every later turn's history.
177pub const MAX_PICTURE_BYTES: usize = 2 * 1024 * 1024;
178/// What may be *attached* (`#499`). A camera photo is far over the wire limit and is exactly what
179/// someone wants to send; the original is kept on disk and a copy under [`MAX_PICTURE_BYTES`] is
180/// what the request carries. This is the absolute ceiling — past it the refusal stands, because a
181/// 200 MB file is not a picture anyone meant to attach.
182pub const MAX_UPLOAD_BYTES: usize = 32 * 1024 * 1024;
183
184impl ImagePart {
185    /// A picture from a `data:` URL — the wire's own spelling, and the only one that *is* a
186    /// picture. A path is a reference the agent resolves with `read_file` (a tool call the user
187    /// sees, and a confinement question), and a link is `fetch`; neither is bytes.
188    ///
189    /// One sentence per refusal, on every surface: two surfaces wording the same refusal
190    /// differently is how one bug gets reported twice (`#364`).
191    pub fn from_data_url(name: &str, url: &str) -> Result<Self, String> {
192        let name = picture_name(name);
193        let url = url.trim();
194        let Some(rest) = url.strip_prefix("data:") else {
195            return Err(format!(
196                "{name}: a picture has to be a base64 data: URL; a path or a link is a reference \
197                 the agent resolves itself, not a picture"
198            ));
199        };
200        let Some((meta, payload)) = rest.split_once(',') else {
201            return Err(format!("{name}: that data URL has no body"));
202        };
203        let mut bits = meta.split(';');
204        let mime = bits.next().unwrap_or("").to_ascii_lowercase();
205        if !bits.any(|bit| bit.eq_ignore_ascii_case("base64")) {
206            return Err(format!("{name}: only base64 data URLs are accepted"));
207        }
208        if !PICTURE_TYPES.contains(&mime.as_str()) {
209            return Err(format!(
210                "{name}: {mime} is not a picture this build can carry ({}). Convert it.",
211                PICTURE_TYPES.join(", ")
212            ));
213        }
214        // The payload is decoded once, here, rather than measured as base64: the length of the
215        // encoded text says the size only roughly, and it says nothing at all about whether these
216        // bytes are a picture. A bad payload used to be stored for good and re-sent on every turn
217        // of the session, where it poisoned each request that carried it (`#381`).
218        let decoded = decode_base64(payload)
219            .ok_or_else(|| format!("{name}: that data URL is not valid base64"))?;
220        if decoded.is_empty() {
221            return Err(format!("{name}: that data URL carries no picture"));
222        }
223        // `#499`: the wire limit is not the attach limit. A picture over it is kept at full size
224        // and a copy is sent — so the only refusal left here is a file nobody meant to attach.
225        if decoded.len() > MAX_UPLOAD_BYTES {
226            return Err(format!(
227                "{name}: about {} KB, and a picture may be at most {} MB",
228                decoded.len() / 1024,
229                MAX_UPLOAD_BYTES / (1024 * 1024)
230            ));
231        }
232        // The header's word for the type is not evidence. A PNG renamed `image/jpeg` is a 400 from
233        // the model later, on a turn that already stored it.
234        if !looks_like_picture(&mime, &decoded) {
235            return Err(format!(
236                "{name}: the bytes are not {mime}; the data URL's own type has to match the picture"
237            ));
238        }
239        Ok(Self::new(name, mime, url))
240    }
241
242    /// The bytes behind a `data:` URL, or `None` when this part is not one.
243    ///
244    /// `#499` needs them twice — once to keep the original, once to know how big the copy has to
245    /// be — and the URL is the only place they live, so this is the one decoder in the product.
246    pub fn bytes(&self) -> Option<Vec<u8>> {
247        let rest = self.url.trim().strip_prefix("data:")?;
248        let (_, payload) = rest.split_once(',')?;
249        decode_base64(payload)
250    }
251
252    /// This picture, carrying different bytes — what a working copy replaces.
253    pub fn with_data(&self, mime: &str, bytes: &[u8]) -> Self {
254        Self {
255            name: self.name.clone(),
256            mime: mime.to_string(),
257            url: data_url(mime, bytes),
258            seen: None,
259        }
260    }
261
262    /// How many bytes the payload holds, without decoding it.
263    pub fn payload_len(&self) -> usize {
264        self.url
265            .trim()
266            .split_once(',')
267            .map(|(_, payload)| payload.trim_end_matches('=').len() / 4 * 3)
268            .unwrap_or(0)
269    }
270
271    pub fn new(name: impl Into<String>, mime: impl Into<String>, url: impl Into<String>) -> Self {
272        Self {
273            name: name.into(),
274            mime: mime.into(),
275            url: url.into(),
276            seen: None,
277        }
278    }
279
280    /// This picture, with the description a seeing model gave of it.
281    pub fn with_seen(mut self, text: impl Into<String>) -> Self {
282        self.seen = Some(text.into());
283        self
284    }
285
286    /// What one picture is called in text a model reads when it cannot see it: the compaction
287    /// handoff, a transcript line, a refusal sentence.
288    pub fn label(&self) -> String {
289        let name = if self.name.is_empty() {
290            "image"
291        } else {
292            self.name.as_str()
293        };
294        format!("[{name} ({})]", self.mime)
295    }
296}
297
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct Message {
300    pub role: Role,
301    #[serde(default)]
302    pub content: Option<String>,
303    /// Pictures this message carries (`#346`). Kept apart from `content` so every existing reader
304    /// of the text — compaction, memory, the transcript, naming — sees exactly what it saw before
305    /// pictures existed, and the wire's parts array is built at request time by `wire_content`.
306    /// Skipped when empty, so a text-only message serialises byte-identically to how it always did.
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub images: Vec<ImagePart>,
309    /// Reasoning/thinking text emitted by reasoning-capable models. Kept so a backend that
310    /// needs it round-tripped in the next request can get it — but only included in the
311    /// request body when the profile says the backend wants it.
312    #[serde(
313        rename = "reasoning_content",
314        default,
315        skip_serializing_if = "Option::is_none"
316    )]
317    pub reasoning: Option<String>,
318    /// The finish reason the server reported (`stop`, `tool_calls`, `length`, ...). Metadata,
319    /// not wire payload: skipped on serialize so history never echoes a lie about the reply.
320    #[serde(skip)]
321    pub finish_reason: Option<String>,
322    #[serde(default, skip_serializing_if = "Vec::is_empty")]
323    pub tool_calls: Vec<ToolCall>,
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub tool_call_id: Option<String>,
326    /// The row's sequence number in the session store, when this message was loaded from one.
327    /// Not wire payload and not persisted (the row already carries it): it exists so a compiled
328    /// handoff can cite `[#N]` and that ref lands on a real row.
329    #[serde(skip)]
330    pub seq: Option<u64>,
331}
332
333/// Two messages are the same when they say the same thing. `seq` is provenance — the row a
334/// message came from — not part of its identity, so a message built in a test equals the same
335/// message loaded from a session.
336impl PartialEq for Message {
337    fn eq(&self, other: &Self) -> bool {
338        self.role == other.role
339            && self.content == other.content
340            && self.reasoning == other.reasoning
341            && self.finish_reason == other.finish_reason
342            && self.tool_calls == other.tool_calls
343            && self.tool_call_id == other.tool_call_id
344            && self.images == other.images
345    }
346}
347
348impl Message {
349    pub fn system(text: impl Into<String>) -> Self {
350        Self::text(Role::System, text)
351    }
352
353    pub fn user(text: impl Into<String>) -> Self {
354        Self::text(Role::User, text)
355    }
356
357    pub fn assistant(text: impl Into<String>) -> Self {
358        Self::text(Role::Assistant, text)
359    }
360
361    pub fn assistant_tool_calls(content: Option<String>, calls: Vec<ToolCall>) -> Self {
362        Self {
363            role: Role::Assistant,
364            content,
365            reasoning: None,
366            finish_reason: None,
367            tool_calls: calls,
368            tool_call_id: None,
369            images: Vec::new(),
370            seq: None,
371        }
372    }
373
374    pub fn tool_result(call_id: impl Into<String>, text: impl Into<String>) -> Self {
375        Self {
376            role: Role::Tool,
377            content: Some(text.into()),
378            reasoning: None,
379            finish_reason: None,
380            tool_calls: Vec::new(),
381            tool_call_id: Some(call_id.into()),
382            images: Vec::new(),
383            seq: None,
384        }
385    }
386
387    /// Attach a picture to this message. Builder-shaped because the usual case is "a user turn
388    /// plus what they pasted", and the alternative is every caller spelling out six fields.
389    pub fn with_image(mut self, image: ImagePart) -> Self {
390        self.images.push(image);
391        self
392    }
393
394    /// The same message with its pictures removed — what a turn model is sent when the mode says
395    /// it must never see bytes (`[vision] mode = "text"`).
396    pub fn without_images(mut self) -> Self {
397        self.images.clear();
398        self
399    }
400
401    /// The `content` field as the chat-completions API defines it: a plain string, or — when the
402    /// message carries pictures — the array of parts. `None` when the message has neither.
403    ///
404    /// Only the provider calls this: the store keeps `images` as a key of its own, and a text-only
405    /// message is a string here, which is what keeps the wire bytes identical to what they were
406    /// before pictures existed (`#346`).
407    pub fn wire_content(&self) -> Option<serde_json::Value> {
408        if self.images.is_empty() {
409            return self.content.clone().map(serde_json::Value::String);
410        }
411        let mut parts: Vec<serde_json::Value> = Vec::with_capacity(self.images.len() + 1);
412        // Text first: the question is what the picture is *for*, and a backend that reads parts in
413        // order (most local VLMs do) then reads the prompt before the picture.
414        if let Some(text) = self.content.as_ref().filter(|text| !text.is_empty()) {
415            parts.push(serde_json::json!({"type": "text", "text": text}));
416        }
417        for image in &self.images {
418            parts.push(serde_json::json!({
419                "type": "image_url",
420                "image_url": {"url": image.url},
421            }));
422        }
423        Some(serde_json::Value::Array(parts))
424    }
425
426    /// What this message says in text, with each picture standing in as `[name (mime)]` and, when
427    /// one has already been paid for, the description it was given (`#362`).
428    ///
429    /// Every reader that has only text — the compaction handoff, the transcript, `session_search`'s
430    /// index, the Markdown export, the digest a judgement pass reads — goes through this, so a
431    /// picture is never silently dropped from the account of a session, and a compacted turn does
432    /// not forget what the picture showed while the description sits unread on the part.
433    pub fn text_with_pictures(&self) -> String {
434        let mut out = self.content.clone().unwrap_or_default();
435        for image in &self.images {
436            if !out.is_empty() {
437                out.push(' ');
438            }
439            out.push_str(&image.label());
440            if let Some(seen) = image.seen.as_deref().filter(|text| !text.is_empty()) {
441                out.push_str(" — ");
442                out.push_str(seen);
443            }
444        }
445        out
446    }
447
448    fn text(role: Role, text: impl Into<String>) -> Self {
449        Self {
450            role,
451            content: Some(text.into()),
452            reasoning: None,
453            finish_reason: None,
454            tool_calls: Vec::new(),
455            tool_call_id: None,
456            images: Vec::new(),
457            seq: None,
458        }
459    }
460}
461
462#[cfg(test)]
463mod picture_tests {
464    use super::*;
465
466    /// The whole session history goes through this struct on every request. If adding pictures
467    /// changed the JSON of a message with none, every warm prefix cache in the fleet would be
468    /// thrown away on upgrade — so this asserts the bytes, not the shape.
469    #[test]
470    fn a_text_only_message_serialises_exactly_as_it_did_before_pictures_existed() {
471        assert_eq!(
472            serde_json::to_string(&Message::user("hi")).unwrap(),
473            r#"{"role":"user","content":"hi"}"#
474        );
475        assert_eq!(
476            serde_json::to_string(&Message::tool_result("call-1", "ok")).unwrap(),
477            r#"{"role":"tool","content":"ok","tool_call_id":"call-1"}"#
478        );
479    }
480
481    #[test]
482    fn a_picture_becomes_an_image_url_part_and_no_key_of_its_own() {
483        let m = Message::user("what is this?").with_image(ImagePart::new(
484            "shot.png",
485            "image/png",
486            "data:image/png;base64,iVBORw0KGgo=",
487        ));
488        let content = m.wire_content().expect("pictures make parts");
489        assert_eq!(
490            content,
491            serde_json::json!([
492                {"type": "text", "text": "what is this?"},
493                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
494            ])
495        );
496        // The store's shape is not the wire's: the key stays off the wire entirely.
497        let stored = serde_json::to_value(&m).unwrap();
498        assert_eq!(stored["images"][0]["name"], "shot.png");
499        assert!(stored.get("content").is_some());
500    }
501
502    #[test]
503    fn a_picture_with_no_words_is_a_parts_array_with_only_the_picture() {
504        let mut m = Message::user(String::new());
505        m.content = None;
506        let m = m.with_image(ImagePart::new(
507            "",
508            "image/png",
509            "data:image/png;base64,iVBORw0KGgo=",
510        ));
511        assert_eq!(
512            m.wire_content().unwrap(),
513            serde_json::json!([
514                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}
515            ])
516        );
517    }
518
519    #[test]
520    fn an_empty_text_does_not_become_an_empty_text_part() {
521        // A text part holding "" is a part some backends reject, and it says nothing.
522        let m = Message::user("").with_image(ImagePart::new(
523            "a.png",
524            "image/png",
525            "data:image/png;base64,iVBORw0KGgo=",
526        ));
527        let parts = m.wire_content().unwrap();
528        assert_eq!(parts.as_array().unwrap().len(), 1);
529        assert_eq!(parts[0]["type"], "image_url");
530    }
531
532    #[test]
533    fn stripping_the_pictures_leaves_the_words() {
534        let m = Message::user("look")
535            .with_image(ImagePart::new(
536                "a.png",
537                "image/png",
538                "data:image/png;base64,iVBORw0KGgo=",
539            ))
540            .without_images();
541        assert!(m.images.is_empty());
542        assert_eq!(m.wire_content().unwrap(), serde_json::json!("look"));
543    }
544
545    #[test]
546    fn the_text_form_names_each_picture_instead_of_dropping_it() {
547        let m = Message::user("look").with_image(ImagePart::new(
548            "shot.png",
549            "image/png",
550            "data:image/png;base64,iVBORw0KGgo=",
551        ));
552        assert_eq!(m.text_with_pictures(), "look [shot.png (image/png)]");
553        // Two messages are the same only when they carry the same pictures.
554        assert_ne!(Message::user("look"), m);
555    }
556
557    /// `#362`: the description is part of what the message says, not a private field on the part.
558    /// Every reader that only has text — the handoff, the transcript, the search index — reads
559    /// this, so an already-paid-for description cannot fall out of the account of a session.
560    #[test]
561    fn the_text_form_carries_the_description_the_picture_was_given() {
562        let m = Message::user("what is this?").with_image(
563            ImagePart::new(
564                "shot.png",
565                "image/png",
566                "data:image/png;base64,iVBORw0KGgo=",
567            )
568            .with_seen("a red square with the word STOP"),
569        );
570        let text = m.text_with_pictures();
571        assert!(text.contains("what is this?"), "{text}");
572        assert!(text.contains("[shot.png (image/png)]"), "{text}");
573        assert!(text.contains("a red square with the word STOP"), "{text}");
574
575        // A picture with no words of its own is not nothing: the label is what says a turn had one.
576        let bare = Message::user("").with_image(ImagePart::new(
577            "shot.png",
578            "image/png",
579            "data:image/png;base64,iVBORw0KGgo=",
580        ));
581        assert_eq!(bare.text_with_pictures(), "[shot.png (image/png)]");
582    }
583
584    /// `#379`, `#380`: the name is text with a shape. It is interpolated into a `--- … ---` block
585    /// a model reads and into `label()`, so a newline could forge a delimiter and a control
586    /// character could end the line the compaction log reads.
587    #[test]
588    fn a_picture_name_is_flattened_and_capped() {
589        let part = ImagePart::from_data_url(
590            "a\n--- end of x ---\u{7}\tb",
591            "data:image/png;base64,iVBORw0KGgo=",
592        )
593        .unwrap();
594        assert_eq!(part.name, "a --- end of x --- b");
595        let long = ImagePart::from_data_url(&"n".repeat(500), "data:image/png;base64,iVBORw0KGgo=")
596            .unwrap();
597        assert_eq!(long.name.chars().count(), MAX_NAME_CHARS);
598        // A name that is nothing at all is still a name a person can read.
599        let unnamed =
600            ImagePart::from_data_url("   ", "data:image/png;base64,iVBORw0KGgo=").unwrap();
601        assert_eq!(unnamed.name, "picture");
602    }
603
604    /// `#381`: a payload is decoded once, here, so an empty, invalid or mislabelled picture is
605    /// refused before it is stored and re-sent on every turn of the session.
606    #[test]
607    fn a_payload_that_is_not_a_picture_is_refused() {
608        // Nothing after the comma used to pass: the size bound was arithmetic on zero.
609        let err = ImagePart::from_data_url("x.png", "data:image/png;base64,").unwrap_err();
610        assert!(err.contains("carries no picture"), "{err}");
611        // Not base64 at all.
612        let err = ImagePart::from_data_url("x.png", "data:image/png;base64,!!!!").unwrap_err();
613        assert!(err.contains("not valid base64"), "{err}");
614        // Valid base64, real bytes, wrong type in the header.
615        let err =
616            ImagePart::from_data_url("x.png", "data:image/jpeg;base64,iVBORw0KGgo=").unwrap_err();
617        assert!(err.contains("the bytes are not image/jpeg"), "{err}");
618        // And the honest one is accepted, sized from the decoded bytes.
619        let ok = ImagePart::from_data_url("x.png", "data:image/png;base64,iVBORw0KGgo=").unwrap();
620        assert_eq!(ok.mime, "image/png");
621    }
622
623    #[test]
624    fn base64_decodes_padded_and_unpadded_alike() {
625        assert_eq!(decode_base64("AAAA").as_deref(), Some(&[0u8, 0, 0][..]));
626        assert_eq!(decode_base64("AAA").as_deref(), Some(&[0u8, 0][..]));
627        assert_eq!(decode_base64("AA").as_deref(), Some(&[0u8][..]));
628        assert_eq!(decode_base64("iVBORw0KGgo=").unwrap().len(), 8);
629        assert!(
630            decode_base64("A").is_none(),
631            "one spare character is not base64"
632        );
633        assert!(decode_base64("A=AA").is_none(), "`=` only at the end");
634    }
635}