perf: avoid unnecessary allocations in base64 encoding of IIP (#1639)

This commit is contained in:
三咲雅 · Misaki Masa 2024-09-15 00:39:38 +08:00 committed by GitHub
parent 0acf5c288e
commit 49639aa34c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,4 +1,4 @@
use std::{io::Write, path::Path};
use std::{fmt::Write, io::Write as ioWrite, path::Path};
use anyhow::Result;
use base64::{engine::{general_purpose::STANDARD, Config}, Engine};
@ -48,20 +48,22 @@ impl Iip {
JpegEncoder::new_with_quality(&mut b, PREVIEW.image_quality).encode_image(&img)?;
};
let len = base64::encoded_len(b.len(), STANDARD.config().encode_padding());
let mut buf = Vec::with_capacity(200 + len.unwrap_or(1 << 16));
let mut buf = String::with_capacity(
200 + base64::encoded_len(b.len(), STANDARD.config().encode_padding()).unwrap_or(0),
);
write!(
buf,
"{}]1337;File=inline=1;size={};width={}px;height={}px;doNotMoveCursor=1:{}\x07{}",
"{}]1337;File=inline=1;size={};width={}px;height={}px;doNotMoveCursor=1:",
START,
b.len(),
w,
h,
STANDARD.encode(b),
CLOSE
)?;
Ok(buf)
STANDARD.encode_string(b, &mut buf);
write!(buf, "\x07{}", CLOSE)?;
Ok(buf.into_bytes())
})
.await?
}