Skip to content

Commit ab1471b

Browse files
authored
Calculate buffer capacity when converting an attachment to base64 (#3320)
Fixes #3091. Avoids a potentially large reallocation when pushing the encoded data into the buffer.
1 parent 1ea2df6 commit ab1471b

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/builder/create_attachment.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,18 @@ impl CreateAttachment {
9595
/// places.
9696
#[must_use]
9797
pub fn to_base64(&self) -> String {
98-
let mut encoded = {
99-
use base64::Engine;
100-
base64::prelude::BASE64_STANDARD.encode(&self.data)
101-
};
102-
encoded.insert_str(0, "data:image/png;base64,");
98+
use base64::engine::{Config, Engine};
99+
100+
const PREFIX: &str = "data:image/png;base64,";
101+
102+
let engine = base64::prelude::BASE64_STANDARD;
103+
let encoded_size = base64::encoded_len(self.data.len(), engine.config().encode_padding())
104+
.and_then(|len| len.checked_add(PREFIX.len()))
105+
.expect("buffer capacity overflow");
106+
107+
let mut encoded = String::with_capacity(encoded_size);
108+
encoded.push_str(PREFIX);
109+
engine.encode_string(&self.data, &mut encoded);
103110
encoded
104111
}
105112

0 commit comments

Comments
 (0)