Advertisement
Guest User

Untitled

a guest
Feb 28th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. pub fn checkedInt(comptime I: type, comptime Hook: type) type {
  2.    
  3.     return struct {
  4.         int: I,
  5.         hook: Hook,
  6.  
  7.         const Self = @This();
  8.        
  9.         fn init(h: Hook) Self {
  10.             if (comptime hasMember(Hook, "default")) {
  11.                 return Self { .int = Hook.default(), .hook = h};
  12.             }
  13.             else {
  14.                 return Self { .int = undefined, .hook = h};
  15.             }
  16.         }
  17.  
  18.         fn opUnary(self: *Self, comptime op: []const u8) void {
  19.             if (comptime hasMember(Hook, "opUnary")) {
  20.                 self.hook.opUnary(&self.int);
  21.             }
  22.  
  23.             if (comptime hasMember(Hook, "onOverflow")) {
  24.                 if (comptime mem.eql(u8, op, "++")) {
  25.                     if (self.int == std.math.maxInt(I)) {
  26.                         self.int = self.hook.onOverflow(I, "++", self.int);
  27.                     } else {
  28.                         self.int += 1;
  29.                     }
  30.                 }
  31.  
  32.                 if (comptime mem.eql(u8, op, "--")) {
  33.                     if (self.int == std.math.minInt(I)) {
  34.                         self.int = self.hook.onOverflow(I, "--", self.int);
  35.                     } else {
  36.                         self.int -= 1;
  37.                     }
  38.                 }
  39.             } else {
  40.                 if (comptime mem.eql(u8, op, "++")) {
  41.                     self.int += 1;
  42.                 }
  43.                 if (comptime mem.eql(u8, op, "--")) {
  44.                     self.int -= 1;
  45.                 }
  46.             }
  47.         }
  48.     };
  49. }
  50.  
  51. const Overflow = struct {
  52.     const Self = @This();
  53.    
  54.     pub fn default() comptime_int {
  55.         return 1;
  56.     }
  57.  
  58.     pub fn onOverflow(self: *Self, comptime I: type, comptime op: [] const u8, number: I) I {
  59.         std.debug.warn("tried to calculate `" ++ op ++ "` on integer {}", number);
  60.         return 0;
  61.     }
  62. };
  63.  
  64. test "test hook" {
  65.     var int = checkedInt(u32, Overflow).init(Overflow {});
  66.     int.opUnary("--");
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement