zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

subo.zig (1742B) - Raw


      1 //! subo - subtract overflow
      2 //! * return a-%b.
      3 //! * return if a-b overflows => 1 else => 0
      4 //! - suboXi4_generic as default
      5 
      6 const std = @import("std");
      7 const builtin = @import("builtin");
      8 const common = @import("common.zig");
      9 
     10 pub const panic = common.panic;
     11 
     12 comptime {
     13     @export(&__subosi4, .{ .name = "__subosi4", .linkage = common.linkage, .visibility = common.visibility });
     14     @export(&__subodi4, .{ .name = "__subodi4", .linkage = common.linkage, .visibility = common.visibility });
     15     @export(&__suboti4, .{ .name = "__suboti4", .linkage = common.linkage, .visibility = common.visibility });
     16 }
     17 
     18 pub fn __subosi4(a: i32, b: i32, overflow: *c_int) callconv(.c) i32 {
     19     return suboXi4_generic(i32, a, b, overflow);
     20 }
     21 pub fn __subodi4(a: i64, b: i64, overflow: *c_int) callconv(.c) i64 {
     22     return suboXi4_generic(i64, a, b, overflow);
     23 }
     24 pub fn __suboti4(a: i128, b: i128, overflow: *c_int) callconv(.c) i128 {
     25     return suboXi4_generic(i128, a, b, overflow);
     26 }
     27 
     28 inline fn suboXi4_generic(comptime ST: type, a: ST, b: ST, overflow: *c_int) ST {
     29     overflow.* = 0;
     30     const sum: ST = a -% b;
     31     // Hackers Delight: section Overflow Detection, subsection Signed Add/Subtract
     32     // Let sum = a -% b == a - b - carry == wraparound subtraction.
     33     // Overflow in a-b-carry occurs, iff a and b have opposite signs
     34     // and the sign of a-b-carry is opposite of a (or equivalently same as b).
     35     // Faster routine: res = (a ^ b) & (sum ^ a)
     36     // Slower routine: res = (sum^a) & ~(sum^b)
     37     // Overflow occurred, iff (res < 0)
     38     if (((a ^ b) & (sum ^ a)) < 0)
     39         overflow.* = 1;
     40     return sum;
     41 }
     42 
     43 test {
     44     _ = @import("subosi4_test.zig");
     45     _ = @import("subodi4_test.zig");
     46     _ = @import("suboti4_test.zig");
     47 }