-
Notifications
You must be signed in to change notification settings - Fork 5
Open
Description
A function to get maximum possible output buffer size would be useful. Common usecase would be pre-allocating destination buffer.
libjpeg-turbo has implemented the function as:
/* TurboJPEG 1.0+ */
DLLEXPORT unsigned long TJBUFSIZE(int width, int height)
{
static const char FUNCTION_NAME[] = "TJBUFSIZE";
unsigned long long retval = 0;
if (width < 1 || height < 1)
THROWG("Invalid argument", (unsigned long)-1);
/* This allows for rare corner cases in which a JPEG image can actually be
larger than the uncompressed input (we wouldn't mention it if it hadn't
happened before.) */
retval = PAD(width, 16) * PAD(height, 16) * 6ULL + 2048ULL;
if (retval > (unsigned long long)((unsigned long)-1))
THROWG("Image is too large", (unsigned long)-1);
bailout:
return (unsigned long)retval;
}
If I were to translate it into Rust, I would write:
fn max_buffer_size(width: u16, height: u16) -> Option<usize> {
let padded_w = (width as usize).checked_next_multiple_of(16)?;
let padded_h = (height as usize).checked_next_multiple_of(16)?;
padded_w.checked_mul(padded_h)?.checked_mul(6)?.checked_add(2048)
}
Note that first two checked_next_multiple_of
can be replaced with normal next_multiple_of
assuming 32-bit usize
.
Metadata
Metadata
Assignees
Labels
No labels