lib/alloc/phase/src/capacity/arithmetic.zig
daab053ee43316e1809a84551d573ddd1e5bf3d2
1 const std = @import("std");
2
3 /// Computes the checked sum of two integer values of type `T`. It delegates to
4 /// the `@addWithOverflow` builtin, returning `error.CapacityOverflow` if
5 /// arithmetic overflow or carry occurs. The function imposes no domain-specific
6 /// maximum bounds or byte limit policies, leaving application limits to owner
7 /// capacity derivation. On success, it returns the sum as a value of type `T`.
8 pub inline fn add(comptime T: type, lhs: T, rhs: T) error{CapacityOverflow}!T {
9 const result = @addWithOverflow(lhs, rhs);
10 if (result[1] != 0) return error.CapacityOverflow;
11 return result[0];
12 }
13
14 /// Computes the checked product of two integer values of type `T`. It delegates
15 /// to the `@mulWithOverflow` builtin, returning `error.CapacityOverflow` if
16 /// arithmetic overflow occurs. The function enforces no external range policies
17 /// or domain limits beyond the representation limits of type `T`. On success,
18 /// it returns the product as a value of type `T`.
19 pub inline fn mul(comptime T: type, lhs: T, rhs: T) error{CapacityOverflow}!T {
20 const result = @mulWithOverflow(lhs, rhs);
21 if (result[1] != 0) return error.CapacityOverflow;
22 return result[0];
23 }
24
25 test "checked capacity arithmetic returns values for two integer types" {
26 try std.testing.expectEqual(@as(u8, 7), try add(u8, 3, 4));
27 try std.testing.expectEqual(@as(usize, 12), try mul(usize, 3, 4));
28 }
29
30 test "checked capacity arithmetic reports overflow" {
31 try std.testing.expectError(error.CapacityOverflow, add(u8, std.math.maxInt(u8), 1));
32 try std.testing.expectError(
33 error.CapacityOverflow,
34 mul(usize, std.math.maxInt(usize), 2),
35 );
36 }