Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub fn checkedInt(comptime I: type, comptime Hook: type) type {
- return struct {
- int: I,
- hook: Hook,
- const Self = @This();
- fn init(h: Hook) Self {
- if (comptime hasMember(Hook, "default")) {
- return Self { .int = Hook.default(), .hook = h};
- }
- else {
- return Self { .int = undefined, .hook = h};
- }
- }
- fn opUnary(self: *Self, comptime op: []const u8) void {
- if (comptime hasMember(Hook, "opUnary")) {
- self.hook.opUnary(&self.int);
- }
- if (comptime hasMember(Hook, "onOverflow")) {
- if (comptime mem.eql(u8, op, "++")) {
- if (self.int == std.math.maxInt(I)) {
- self.int = self.hook.onOverflow(I, "++", self.int);
- } else {
- self.int += 1;
- }
- }
- if (comptime mem.eql(u8, op, "--")) {
- if (self.int == std.math.minInt(I)) {
- self.int = self.hook.onOverflow(I, "--", self.int);
- } else {
- self.int -= 1;
- }
- }
- } else {
- if (comptime mem.eql(u8, op, "++")) {
- self.int += 1;
- }
- if (comptime mem.eql(u8, op, "--")) {
- self.int -= 1;
- }
- }
- }
- };
- }
- const Overflow = struct {
- const Self = @This();
- pub fn default() comptime_int {
- return 1;
- }
- pub fn onOverflow(self: *Self, comptime I: type, comptime op: [] const u8, number: I) I {
- std.debug.warn("tried to calculate `" ++ op ++ "` on integer {}", number);
- return 0;
- }
- };
- test "test hook" {
- var int = checkedInt(u32, Overflow).init(Overflow {});
- int.opUnary("--");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement