std.overflow
Functionality
The overflow package provides handling capabilities for integer arithmetic overflow.
In integer arithmetic, overflow occurs when the result of an operation exceeds the maximum value or falls below the minimum value of its type. By default, an exception is thrown when overflow occurs.
The overflow package offers four overflow handling strategies and defines corresponding interfaces, as listed below:
| Strategy | Interface | Description |
|---|---|---|
| Return Option | CheckedOp | Returns None when integer arithmetic overflow occurs. |
| Saturation | SaturatingOp | Returns MAX value when result exceeds target type's MAX; returns MIN value when result is below target type's MIN. |
| Throw Exception | ThrowingOp | Throws an exception when integer arithmetic overflow occurs. |
| Wrapping | WrappingOp | Truncates higher bits beyond target type's bit width when overflow occurs. |
The overflow package provides implementations of these interfaces for all integer types through extensions. Users can implement overflow interfaces for other types in the same manner.
API List
Interfaces
| Interface Name | Functionality |
|---|---|
| CarryingOp | Provides interface for returning whether truncation occurred in integer operations along with the result. |
| CarryingPow | Provides power operation interface using wrapping strategy. |
| CheckedOp | Returns None when integer arithmetic overflow occurs. |
| CheckedPow | Provides power operation interface returning Option strategy. |
| SaturatingOp | Performs saturation when integer arithmetic overflow occurs. |
| SaturatingPow | Provides power operation interface with saturation strategy. |
| ThrowingOp | Throws an exception when integer arithmetic overflow occurs. |
| ThrowingPow | Provides power operation interface using exception-throwing strategy. |
| WrappingOp | Truncates higher bits beyond target type's bit width when overflow occurs. |
| WrappingPow | Provides power operation interface using wrapping strategy. |
Exception Classes
| Class Name | Functionality |
|---|---|
| OvershiftException | Exception thrown when shift count exceeds operand bit width in shift operations. |
| UndershiftException | Exception thrown when shift count is less than 0 in shift operations. |