Skip to content

Function to get maximum output buffer size #11

@jsonmona

Description

@jsonmona

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions