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
Maximum safe pixel buffer size (2GB limit for safety).
Maximum safe image dimension to prevent integer overflow.
Class methods
Safely multiplies two Int32 values with overflow checking.
Parameters:
a: First operandb: Second operand
Returns: Result as Int64
Raises: MemoryError if result exceeds Int32::MAX
Safely calculates pixel buffer size with overflow checking.
Validates dimensions and calculates total buffer size needed.
Parameters:
width: Image width in pixelsheight: Image height in pixelsbytes_per_pixel: Bytes per pixel
Returns: Total buffer size in bytes
Raises: DimensionError or MemoryError if size exceeds limits
Safely calculates pixel offset with bounds checking.
Validates coordinates are within bounds and calculates buffer offset.
Parameters:
x, y: Pixel coordinatesrect: Image boundsstride: Row stride in bytesbytes_per_pixel: Bytes per pixel
Returns: Byte offset in pixel buffer
Raises: BoundsError if coordinates out of bounds, MemoryError on overflow
Safely calculates row stride with overflow checking.
Parameters:
width: Image width in pixelsbytes_per_pixel: Bytes per pixel (1, 2, 4, or 8)
Returns: Stride in bytes
Raises: DimensionError or MemoryError on overflow
Validates image dimensions before allocation.
Checks that dimensions are non-negative and within safe limits.
Parameters:
width: Image widthheight: Image height
Raises: DimensionError if dimensions are invalid or exceed limits
Validates rectangle dimensions.
Parameters:
rect: Rectangle to validate
Raises: DimensionError if rectangle dimensions are invalid