module

CrImage::Math::Safe

Safe provides overflow-safe arithmetic operations for image processing.

Prevents integer overflow and memory allocation errors by validating dimensions and buffer sizes before operations. Essential for handling untrusted image data and preventing security vulnerabilities.

Features:

  • Dimension validation (max ~2.1 billion pixels per dimension)
  • Buffer size checking (max 2GB)
  • Overflow-safe multiplication
  • Bounds checking for pixel access

Constants

MAX_BUFFER_SIZE = 2147483647_i64

Maximum safe pixel buffer size (2GB limit for safety).

MAX_DIMENSION = 2147483647

Maximum safe image dimension to prevent integer overflow.

Class methods

mul_i32(a : Int32, b : Int32) : Int64

Safely multiplies two Int32 values with overflow checking.

Parameters:

  • a : First operand
  • b : Second operand

Returns: Result as Int64

Raises: MemoryError if result exceeds Int32::MAX

Source
safe_buffer_size(width : Int32, height : Int32, bytes_per_pixel : Int32) : Int64

Safely calculates pixel buffer size with overflow checking.

Validates dimensions and calculates total buffer size needed.

Parameters:

  • width : Image width in pixels
  • height : Image height in pixels
  • bytes_per_pixel : Bytes per pixel

Returns: Total buffer size in bytes

Raises: DimensionError or MemoryError if size exceeds limits

Source
safe_pixel_offset(x : Int32, y : Int32, rect : Rectangle, stride : Int32, bytes_per_pixel : Int32) : Int32

Safely calculates pixel offset with bounds checking.

Validates coordinates are within bounds and calculates buffer offset.

Parameters:

  • x, y : Pixel coordinates
  • rect : Image bounds
  • stride : Row stride in bytes
  • bytes_per_pixel : Bytes per pixel

Returns: Byte offset in pixel buffer

Raises: BoundsError if coordinates out of bounds, MemoryError on overflow

Source
safe_stride(width : Int32, bytes_per_pixel : Int32) : Int32

Safely calculates row stride with overflow checking.

Parameters:

  • width : Image width in pixels
  • bytes_per_pixel : Bytes per pixel (1, 2, 4, or 8)

Returns: Stride in bytes

Raises: DimensionError or MemoryError on overflow

Source
validate_dimensions(width : Int32, height : Int32)

Validates image dimensions before allocation.

Checks that dimensions are non-negative and within safe limits.

Parameters:

  • width : Image width
  • height : Image height

Raises: DimensionError if dimensions are invalid or exceed limits

Source
validate_rectangle(rect : Rectangle)

Validates rectangle dimensions.

Parameters:

  • rect : Rectangle to validate

Raises: DimensionError if rectangle dimensions are invalid

Source