From f2badf403e946d3fd88ee85b9912bdde28d2a158 Mon Sep 17 00:00:00 2001 From: Lee ByeongJun Date: Fri, 3 Jan 2025 23:01:27 +0900 Subject: [PATCH] overflow checker (#456) --- _deploy/p/gnoswap/uint256/arithmetic.gno | 4 ++ _deploy/p/gnoswap/uint256/arithmetic_test.gno | 43 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/_deploy/p/gnoswap/uint256/arithmetic.gno b/_deploy/p/gnoswap/uint256/arithmetic.gno index c3e2ed837..a10436f8e 100644 --- a/_deploy/p/gnoswap/uint256/arithmetic.gno +++ b/_deploy/p/gnoswap/uint256/arithmetic.gno @@ -416,6 +416,10 @@ func (z *Uint) isBitSet(n uint) bool { return (z.arr[n/64] & (1 << (n % 64))) != 0 } +func (z *Uint) IsOverflow() bool { + return z.isBitSet(255) +} + // addTo computes x += y. // Requires len(x) >= len(y). func addTo(x, y []uint64) uint64 { diff --git a/_deploy/p/gnoswap/uint256/arithmetic_test.gno b/_deploy/p/gnoswap/uint256/arithmetic_test.gno index 9f45a5077..09d83eb18 100644 --- a/_deploy/p/gnoswap/uint256/arithmetic_test.gno +++ b/_deploy/p/gnoswap/uint256/arithmetic_test.gno @@ -6,6 +6,49 @@ type binOp2Test struct { x, y, want string } +func TestIsOverflow(t *testing.T) { + tests := []struct { + name string + input *Uint + expected bool + }{ + { + name: "Number greater than max value", + input: &Uint{arr: [4]uint64{ + ^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0), + }}, + expected: true, + }, + { + name: "Max value", + input: &Uint{arr: [4]uint64{ + ^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0) >> 1, + }}, + expected: false, + }, + { + name: "0", + input: &Uint{arr: [4]uint64{0, 0, 0, 0}}, + expected: false, + }, + { + name: "Only 255th bit set", + input: &Uint{arr: [4]uint64{ + 0, 0, 0, uint64(1) << 63, + }}, + expected: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.input.IsOverflow(); got != tt.expected { + t.Errorf("IsOverflow() = %v, expected %v", got, tt.expected) + } + }) + } +} + func TestAdd(t *testing.T) { tests := []binOp2Test{ {"0", "1", "1"},