diff --git a/lang/interval/interval.go b/lang/interval/interval.go new file mode 100644 index 00000000..41d8ac26 --- /dev/null +++ b/lang/interval/interval.go @@ -0,0 +1,515 @@ +// Copyright 2018 The Wuffs Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package interval provides interval arithmetic on big integers. Big means +// arbitrary-precision, as per the standard math/big package. +// +// For example, if x is in the interval [3, 6] and y is in the interval [10, +// 15] then x+y is in the interval [13, 21]. +// +// Such intervals may have infinite bounds. For example, if x is in the +// interval [3, +∞) and y is in the interval [-4, -2], then x*y is in the +// interval (-∞, -6]. +// +// As a motivating example, if a compiler knows that the integer-typed +// variables i and j are in the intervals [0, 255] and [0, 3], and that the +// array a has 1024 elements, then it can prove that the array-index expression +// a[4*i + j] is memory-safe without needing a at-runtime bounds check. +// +// This package depends only on the standard math/big package. +package interval + +import ( + "math/big" +) + +func bigIntMul(i *big.Int, j *big.Int) *big.Int { return big.NewInt(0).Mul(i, j) } +func bigIntQuo(i *big.Int, j *big.Int) *big.Int { return big.NewInt(0).Quo(i, j) } + +func bigIntLsh(i *big.Int, j *big.Int) *big.Int { + if j.IsUint64() { + if u := j.Uint64(); u <= 0xFFFFFFFF { + return big.NewInt(0).Lsh(i, uint(u)) + } + } + + // Fallback code path, copy-pasted to interval_test.go. + k := big.NewInt(2) + k.Exp(k, j, nil) + k.Mul(i, k) + return k +} + +func bigIntRsh(i *big.Int, j *big.Int) *big.Int { + if j.IsUint64() { + if u := j.Uint64(); u <= 0xFFFFFFFF { + return big.NewInt(0).Rsh(i, uint(u)) + } + } + + // Fallback code path, copy-pasted to interval_test.go. + k := big.NewInt(2) + k.Exp(k, j, nil) + k.Div(i, k) // This is explicitly Div, not Quo. + return k +} + +// biggerInt is either a non-nil *big.Int or ±∞. +type biggerInt struct { + // extra being less than or greater than 0 means that the biggerInt is -∞ + // or +∞ respectively. extra being zero means that the biggerInt is i, + // which should be a non-nil pointer. + extra int32 + i *big.Int +} + +type biggerIntPair [2]biggerInt + +// newBiggerIntPair returns a pair of biggerInt values, the first being +∞ +// and the second being -∞. +func newBiggerIntPair() biggerIntPair { return biggerIntPair{{extra: +1}, {extra: -1}} } + +// lowerMin sets x[0] to min(x[0], y). +func (x *biggerIntPair) lowerMin(y biggerInt) { + if x[0].extra > 0 || y.extra < 0 || + (x[0].extra == 0 && y.extra == 0 && x[0].i.Cmp(y.i) > 0) { + x[0] = y + } +} + +// raiseMax sets x[1] to max(x[1], y). +func (x *biggerIntPair) raiseMax(y biggerInt) { + if x[1].extra < 0 || y.extra > 0 || + (x[1].extra == 0 && y.extra == 0 && x[1].i.Cmp(y.i) < 0) { + x[1] = y + } +} + +func (x *biggerIntPair) toInt() Int { + if x[0].extra > 0 || x[1].extra < 0 { + return empty() + } + return Int{x[0].i, x[1].i} +} + +func (x *biggerIntPair) fromInt(y Int) { + if y[0] != nil { + x[0] = biggerInt{i: big.NewInt(0).Set(y[0])} + } else { + x[0] = biggerInt{extra: -1} + } + if y[1] != nil { + x[1] = biggerInt{i: big.NewInt(0).Set(y[1])} + } else { + x[1] = biggerInt{extra: +1} + } +} + +// Int is an integer interval. The array elements are the minimum and maximum +// values, inclusive (if non-nil) on both ends. A nil element means unbounded: +// negative or positive infinity. +// +// The zero value (zero in the Go sense, not in the integer sense) is a valid, +// infinitely sized interval, unbounded at both ends. +// +// A subtle point is that an interval's minimum or maximum can be infinite, but +// if an integer value i is known to be within such an interval, i's possible +// values are arbitrarily large but not infinite. Specifically, 0*i is +// unambiguously always equal to 0. +// +// It is also valid for the first element to be greater than the second +// element. This represents an empty interval. There is more than one +// representation of an empty interval. +type Int [2]*big.Int + +// String returns a string representation of x. +func (x Int) String() string { + if x.Empty() { + return "" + } + buf := []byte(nil) + if x[0] == nil { + buf = append(buf, "(-∞, "...) + } else { + buf = append(buf, '[') + buf = x[0].Append(buf, 10) + buf = append(buf, ", "...) + } + if x[1] == nil { + buf = append(buf, "+∞)"...) + } else { + buf = x[1].Append(buf, 10) + buf = append(buf, ']') + } + return string(buf) +} + +// empty returns an empty Int: one that contains no elements. +func empty() Int { + return Int{big.NewInt(+1), big.NewInt(-1)} +} + +// ContainsNegative returns whether x contains at least one negative value. +func (x Int) ContainsNegative() bool { + if x[0] == nil { + return true + } + if x[0].Sign() >= 0 { + return false + } + return x[1] == nil || x[0].Cmp(x[1]) <= 0 +} + +// ContainsPositive returns whether x contains at least one positive value. +func (x Int) ContainsPositive() bool { + if x[1] == nil { + return true + } + if x[1].Sign() <= 0 { + return false + } + return x[0] == nil || x[0].Cmp(x[1]) <= 0 +} + +// ContainsZero returns whether x contains zero. +func (x Int) ContainsZero() bool { + return (x[0] == nil || x[0].Sign() <= 0) && + (x[1] == nil || x[1].Sign() >= 0) +} + +// Eq returns whether x equals y. +func (x Int) Eq(y Int) bool { + if xe, ye := x.Empty(), y.Empty(); xe || ye { + return xe == ye + } + if x0, y0 := x[0] != nil, y[0] != nil; x0 != y0 { + return false + } else if x0 && x[0].Cmp(y[0]) != 0 { + return false + } + if x1, y1 := x[1] != nil, y[1] != nil; x1 != y1 { + return false + } else if x1 && x[1].Cmp(y[1]) != 0 { + return false + } + return true +} + +// Empty returns whether x is empty. +func (x Int) Empty() bool { + return x[0] != nil && x[1] != nil && x[0].Cmp(x[1]) > 0 +} + +// justZero returns whether x is the [0, 0] interval, containing exactly one +// element: the integer zero. +func (x Int) justZero() bool { + return x[0] != nil && x[1] != nil && x[0].Sign() == 0 && x[1].Sign() == 0 +} + +// split splits x into negative, zero and positive sub-intervals. The Int +// values returned may be empty, which means that x does not contain any +// negative or positive elements. +func (x Int) split() (neg Int, pos Int, negEmpty bool, hasZero bool, posEmpty bool) { + if x[0] != nil && x[0].Sign() > 0 { + return empty(), x, true, false, x.Empty() + } + if x[1] != nil && x[1].Sign() < 0 { + return x, empty(), x.Empty(), false, true + } + + neg[0] = x[0] + neg[1] = big.NewInt(-1) + if x[1] != nil && x[1].Cmp(neg[1]) < 0 { + neg[1] = x[1] + } + + pos[0] = big.NewInt(+1) + if x[0] != nil && x[0].Cmp(pos[0]) > 0 { + pos[0] = x[0] + } + pos[1] = x[1] + + return neg, pos, neg.Empty(), x.ContainsZero(), pos.Empty() +} + +// Add returns z = x + y. +func (x Int) Add(y Int) (z Int) { + if x.Empty() || y.Empty() { + return empty() + } + if x[0] != nil && y[0] != nil { + z[0] = big.NewInt(0).Add(x[0], y[0]) + } + if x[1] != nil && y[1] != nil { + z[1] = big.NewInt(0).Add(x[1], y[1]) + } + return z +} + +// Sub returns z = x - y. +func (x Int) Sub(y Int) (z Int) { + if x.Empty() || y.Empty() { + return empty() + } + if x[0] != nil && y[1] != nil && (x[1] != nil || y[0] != nil) { + z[0] = big.NewInt(0).Sub(x[0], y[1]) + } + if x[1] != nil && y[0] != nil && (x[0] != nil || y[1] != nil) { + z[1] = big.NewInt(0).Sub(x[1], y[0]) + } + return z +} + +// Mul returns z = x * y. +func (x Int) Mul(y Int) (z Int) { + return x.mulLsh(y, false) +} + +// Lsh returns z = x << y. +// +// ok is false (and z will be Int{nil, nil}) if x is non-empty and y contains +// at least one negative value, as it's invalid to shift by a negative number. +// Otherwise, ok is true. +func (x Int) Lsh(y Int) (z Int, ok bool) { + if !x.Empty() && y.ContainsNegative() { + return Int{}, false + } + return x.mulLsh(y, true), true +} + +func (x Int) mulLsh(y Int, shift bool) (z Int) { + if x.Empty() || y.Empty() { + return empty() + } + if x.justZero() || (!shift && y.justZero()) { + return Int{big.NewInt(0), big.NewInt(0)} + } + + combine := bigIntMul + if shift { + combine = bigIntLsh + } + + ret := newBiggerIntPair() + + // Split x and y into negative, zero and positive parts. + negX, posX, negXEmpty, zeroX, posXEmpty := x.split() + negY, posY, negYEmpty, zeroY, posYEmpty := y.split() + + if zeroY && shift { + ret.fromInt(x) + } else if (zeroY && !shift) || zeroX { + ret[0] = biggerInt{i: big.NewInt(0)} + ret[1] = biggerInt{i: big.NewInt(0)} + } + + if !negXEmpty { + if !negYEmpty { + // x is negative and y is negative, so x op y is positive. + // + // If op is << instead of * then we have previously checked that y + // is non-negative, so this should be unreachable. + ret.lowerMin(biggerInt{i: combine(negX[1], negY[1])}) + if negX[0] == nil || negY[0] == nil { + ret.raiseMax(biggerInt{extra: +1}) + } else { + ret.raiseMax(biggerInt{i: combine(negX[0], negY[0])}) + } + } + + if !posYEmpty { + // x is negative and y is positive, so x op y is negative. + if negX[0] == nil || posY[1] == nil { + ret.lowerMin(biggerInt{extra: -1}) + } else { + ret.lowerMin(biggerInt{i: combine(negX[0], posY[1])}) + } + ret.raiseMax(biggerInt{i: combine(negX[1], posY[0])}) + } + } + + if !posXEmpty { + if !negYEmpty { + // x is positive and y is negative, so x op y is negative. + // + // If op is << instead of * then we have previously checked that y + // is non-negative, so this should be unreachable. + if posX[1] == nil || negY[0] == nil { + ret.lowerMin(biggerInt{extra: -1}) + } else { + ret.lowerMin(biggerInt{i: combine(posX[1], negY[0])}) + } + ret.raiseMax(biggerInt{i: combine(posX[0], negY[1])}) + } + + if !posYEmpty { + // x is positive and y is positive, so x op y is positive. + ret.lowerMin(biggerInt{i: combine(posX[0], posY[0])}) + if posX[1] == nil || posY[1] == nil { + ret.raiseMax(biggerInt{extra: +1}) + } else { + ret.raiseMax(biggerInt{i: combine(posX[1], posY[1])}) + } + } + } + + return ret.toInt() +} + +// Quo returns z = x / y. Like the big.Int.Quo method (and unlike the +// big.Int.Div method), it truncates towards zero. +// +// ok is false (and z will be Int{nil, nil}) if x is non-empty and y contains +// zero, as it's invalid to divide by zero. Otherwise, ok is true. +func (x Int) Quo(y Int) (z Int, ok bool) { + if x.Empty() || y.Empty() { + return empty(), true + } + if y.ContainsZero() { + return Int{}, false + } + if x.justZero() { + return Int{big.NewInt(0), big.NewInt(0)}, true + } + + ret := newBiggerIntPair() + + // Split x and y into negative, zero and positive parts. + negX, posX, negXEmpty, zeroX, posXEmpty := x.split() + negY, posY, negYEmpty, _, posYEmpty := y.split() + + if zeroX { + ret[0] = biggerInt{i: big.NewInt(0)} + ret[1] = biggerInt{i: big.NewInt(0)} + } + + if !negXEmpty { + if !negYEmpty { + // x is negative and y is negative, so x / y is non-negative. + if negX[0] == nil { + ret.raiseMax(biggerInt{extra: +1}) + } else { + ret.raiseMax(biggerInt{i: bigIntQuo(negX[0], negY[1])}) + } + if negY[0] == nil { + ret.lowerMin(biggerInt{i: big.NewInt(0)}) + } else { + ret.lowerMin(biggerInt{i: bigIntQuo(negX[1], negY[0])}) + } + } + + if !posYEmpty { + // x is negative and y is positive, so x / y is non-positive. + if negX[0] == nil { + ret.lowerMin(biggerInt{extra: -1}) + } else { + ret.lowerMin(biggerInt{i: bigIntQuo(negX[0], posY[0])}) + } + if posY[1] == nil { + ret.raiseMax(biggerInt{i: big.NewInt(0)}) + } else { + ret.raiseMax(biggerInt{i: bigIntQuo(negX[1], posY[1])}) + } + } + } + + if !posXEmpty { + if !negYEmpty { + // x is positive and y is negative, so x / y is non-positive. + if posX[1] == nil { + ret.lowerMin(biggerInt{extra: -1}) + } else { + ret.lowerMin(biggerInt{i: bigIntQuo(posX[1], negY[1])}) + } + if negY[0] == nil { + ret.raiseMax(biggerInt{i: big.NewInt(0)}) + } else { + ret.raiseMax(biggerInt{i: bigIntQuo(posX[0], negY[0])}) + } + } + + if !posYEmpty { + // x is positive and y is positive, so x / y is non-negative. + if posX[1] == nil { + ret.raiseMax(biggerInt{extra: +1}) + } else { + ret.raiseMax(biggerInt{i: bigIntQuo(posX[1], posY[0])}) + } + if posY[1] == nil { + ret.lowerMin(biggerInt{i: big.NewInt(0)}) + } else { + ret.lowerMin(biggerInt{i: bigIntQuo(posX[0], posY[1])}) + } + } + } + + return ret.toInt(), true +} + +// Rsh returns z = x >> y. +// +// ok is false (and z will be Int{nil, nil}) if x is non-empty and y contains +// at least one negative value, as it's invalid to shift by a negative number. +// Otherwise, ok is true. +func (x Int) Rsh(y Int) (z Int, ok bool) { + if x.Empty() || y.Empty() { + return empty(), true + } + if y.ContainsNegative() { + return Int{}, false + } + if x.justZero() { + return Int{big.NewInt(0), big.NewInt(0)}, true + } + + ret := newBiggerIntPair() + + // Split x and y into negative and zero-or-positive parts. + negX, posX, negXEmpty, zeroX, posXEmpty := x.split() + + if zeroX { + ret[0] = biggerInt{i: big.NewInt(0)} + ret[1] = biggerInt{i: big.NewInt(0)} + } + + if !negXEmpty { + // x is negative and y is positive, so x >> y is non-positive. + if negX[0] == nil { + ret.lowerMin(biggerInt{extra: -1}) + } else { + ret.lowerMin(biggerInt{i: bigIntRsh(negX[0], y[0])}) + } + if y[1] == nil { + ret.raiseMax(biggerInt{i: big.NewInt(-1)}) + } else { + ret.raiseMax(biggerInt{i: bigIntRsh(negX[1], y[1])}) + } + } + + if !posXEmpty { + // x is positive and y is positive, so x >> y is non-negative. + if y[1] == nil { + ret.lowerMin(biggerInt{i: big.NewInt(0)}) + } else { + ret.lowerMin(biggerInt{i: bigIntRsh(posX[0], y[1])}) + } + if posX[1] == nil { + ret.raiseMax(biggerInt{extra: +1}) + } else { + ret.raiseMax(biggerInt{i: bigIntRsh(posX[1], y[0])}) + } + } + + return ret.toInt(), true +} diff --git a/lang/interval/interval_test.go b/lang/interval/interval_test.go new file mode 100644 index 00000000..02f11e57 --- /dev/null +++ b/lang/interval/interval_test.go @@ -0,0 +1,699 @@ +// Copyright 2018 The Wuffs Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package interval + +import ( + "fmt" + "math/big" + "math/rand" + "sort" + "strconv" + "strings" + "testing" +) + +// TestMotivatingExample tests the "motivating example" given in the package +// doc comment. +func TestMotivatingExample(tt *testing.T) { + i := Int{big.NewInt(0), big.NewInt(255)} + j := Int{big.NewInt(0), big.NewInt(3)} + four := Int{big.NewInt(4), big.NewInt(4)} + got := four.Mul(i).Add(j) + want := Int{big.NewInt(0), big.NewInt(1023)} + if !got.Eq(want) { + tt.Fatalf("got %v, want %v", got, want) + } +} + +func TestBigIntShifts(tt *testing.T) { + // These alternative implementations always take the fallback code path of + // bigIntLsh and bigIntRsh. This test checks that those fallback paths give + // the same results as *big.Int's Lsh and Rsh methods. There are fallback + // and non-fallback code paths in interval.go because those *big.Int + // methods aren't applicable if j's value doesn't fit in a uint. + + alternativeBigIntLsh := func(i *big.Int, j *big.Int) *big.Int { + // Fallback code path, copy-pasted from interval.go. + k := big.NewInt(2) + k.Exp(k, j, nil) + k.Mul(i, k) + return k + } + + alternativeBigIntRsh := func(i *big.Int, j *big.Int) *big.Int { + // Fallback code path, copy-pasted from interval.go. + k := big.NewInt(2) + k.Exp(k, j, nil) + k.Div(i, k) // This is explicitly Div, not Quo. + return k + } + + xs := []*big.Int{ + big.NewInt(-9), + big.NewInt(-8), + big.NewInt(-7), + + big.NewInt(-2), + big.NewInt(-1), + big.NewInt(+0), + big.NewInt(+1), + big.NewInt(+2), + + big.NewInt(+7), + big.NewInt(+8), + big.NewInt(+9), + } + + ys := []*big.Int{ + big.NewInt(+0), + big.NewInt(+1), + big.NewInt(+2), + big.NewInt(+3), + big.NewInt(+4), + } + + for _, x := range xs { + for _, y := range ys { + { + got := bigIntLsh(x, y) + want := alternativeBigIntLsh(x, y) + if got.Cmp(want) != 0 { + tt.Errorf("%v << %v: got %v, want %v", x, y, got, want) + } + } + + { + got := bigIntRsh(x, y) + want := alternativeBigIntRsh(x, y) + if got.Cmp(want) != 0 { + tt.Errorf("%v >> %v: got %v, want %v", x, y, got, want) + } + } + } + } +} + +func trimLeadingSpaces(s string) string { + for ; len(s) > 0 && s[0] == ' '; s = s[1:] { + } + return s +} + +func trimTrailingSpaces(s string) string { + for ; len(s) > 0 && s[len(s)-1] == ' '; s = s[:len(s)-1] { + } + return s +} + +func parseInt(s string) (x *big.Int, remaining string, err error) { + s = trimLeadingSpaces(s) + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c == ')' || c == ',' || c == ']' { + break + } + } + s, remaining = trimTrailingSpaces(s[:i]), s[i:] + switch s { + case "-∞", "+∞": + // No-op. + default: + n, err := strconv.Atoi(s) + if err != nil { + return nil, "", fmt.Errorf("parseInt(%q): %v", s, err) + } + x = big.NewInt(int64(n)) + } + return x, remaining, nil +} + +// parseInterval parses a string like "[-3, +4] etcetera", returning the +// interval itself and the remaining string " etcetera". +// +// It also parses infinite (unbounded) intervals like "[0, +∞)". The brackets +// here are square brackets (to ease the parsing algorithm) even though, in +// mathematical interval notation, parentheses would be more traditional. +// +// It also parses the special syntax "[...empty..]" for an empty interval (one +// that contains no elements). +func parseInterval(s string) (x Int, remaining string, err error) { + const emptySyntax = "[...empty..]" + s = trimLeadingSpaces(s) + if strings.HasPrefix(s, emptySyntax) { + s = s[len(emptySyntax):] + return Int{big.NewInt(+1), big.NewInt(-1)}, s, nil + } + + if s[0] != '(' && s[0] != '[' { + return Int{}, "", fmt.Errorf("expected '(' or '['") + } + s = s[1:] + x0, s, err := parseInt(s) + if err != nil { + return Int{}, "", err + } + if s[0] != ',' { + return Int{}, "", fmt.Errorf("expected ','") + } + s = s[1:] + x1, s, err := parseInt(s) + if err != nil { + return Int{}, "", err + } + if s[0] != ')' && s[0] != ']' { + return Int{}, "", fmt.Errorf("expected ')' or ']'") + } + s = s[1:] + if x0 != nil && x1 != nil && x0.Cmp(x1) > 0 { + return Int{}, "", fmt.Errorf("invalid empty interval") + } + return Int{x0, x1}, s, nil +} + +func TestContainsEtc(tt *testing.T) { + testCases := []struct { + s string + cn uint32 + cz uint32 + cp uint32 + }{ + {"", 0, 0, 0}, + {"", 0, 0, 0}, + {"", 0, 0, 0}, + {"", 0, 0, 0}, + {"", 0, 0, 0}, + + {"(-∞, -1]", 1, 0, 0}, + {"(-∞, 0]", 1, 1, 0}, + {"(-∞, +1]", 1, 1, 1}, + {"(-∞, +∞)", 1, 1, 1}, + + {"[-1, -1]", 1, 0, 0}, + {"[-1, 0]", 1, 1, 0}, + {"[-1, +1]", 1, 1, 1}, + {"[-1, +∞)", 1, 1, 1}, + + {"[ 0, 0]", 0, 1, 0}, + {"[ 0, +1]", 0, 1, 1}, + {"[ 0, +∞)", 0, 1, 1}, + + {"[+1, +1]", 0, 0, 1}, + {"[+1, +∞)", 0, 0, 1}, + } + + // eqTestCases is appended to throughout the "range testCases" loop, but it + // always contains exactly one empty Int. + eqTestCases := []Int{ + empty(), + } + + for _, tc := range testCases { + x := Int{} + switch tc.s { + case "": + x = Int{big.NewInt(-1), big.NewInt(-2)} + case "": + x = Int{big.NewInt(00), big.NewInt(-2)} + case "": + x = Int{big.NewInt(+2), big.NewInt(-2)} + case "": + x = Int{big.NewInt(+2), big.NewInt(00)} + case "": + x = Int{big.NewInt(+2), big.NewInt(+1)} + default: + err := error(nil) + x, _, err = parseInterval(tc.s) + if err != nil { + tt.Errorf("%s: %v", tc.s, err) + continue + } + } + + if got, want := x.ContainsNegative(), tc.cn != 0; got != want { + tt.Errorf("%s.ContainsNegative(): got %t, want %t", tc.s, got, want) + } + if got, want := x.ContainsZero(), tc.cz != 0; got != want { + tt.Errorf("%s.ContainsZero(): got %t, want %t", tc.s, got, want) + } + if got, want := x.ContainsPositive(), tc.cp != 0; got != want { + tt.Errorf("%s.ContainsPositive(): got %t, want %t", tc.s, got, want) + } + + if got, want := x.Empty(), strings.Contains(tc.s, "empty"); got != want { + tt.Errorf("%s.Empty(): got %t, want %t", tc.s, got, want) + } else if !got { + eqTestCases = append(eqTestCases, x) + } else if !x.Eq(empty()) { + tt.Errorf("%v eq %v: got %t, want %t", x, empty(), got, want) + } + + if got, want := x.justZero(), tc.s == "[ 0, 0]"; got != want { + tt.Errorf("%s.justZero(): got %t, want %t", tc.s, got, want) + } + } + + for i, x := range eqTestCases { + for j, y := range eqTestCases { + got := x.Eq(y) + want := i == j + if got != want { + tt.Errorf("%v eq %v: got %t, want %t", x, y, got, want) + } + } + } + + for _, x := range eqTestCases { + neg, pos, negEmpty, hasZero, posEmpty := x.split() + if got, want := neg.Empty(), negEmpty; got != want { + tt.Errorf("%v: neg.Empty() == %t, negEmpty == %t", x, got, want) + } + if got, want := !x.ContainsNegative(), negEmpty; got != want { + tt.Errorf("%v: !x.ContainsNegative() == %t, negEmpty == %t", x, got, want) + } + if got, want := x.ContainsZero(), hasZero; got != want { + tt.Errorf("%v: x.ContainsZero() == %t, hasZero == %t", x, got, want) + } + if got, want := !x.ContainsPositive(), posEmpty; got != want { + tt.Errorf("%v: !x.ContainsPositive() == %t, posEmpty == %t", x, got, want) + } + if got, want := pos.Empty(), posEmpty; got != want { + tt.Errorf("%v: pos.Empty() == %t, posEmpty == %t", x, got, want) + } + } +} + +func testBruteForceAgrees(x Int, y Int, opKey string) error { + brute, bruteOK := bruteForce(x, y, opKey) + got, gotOK := intOperators[opKey](x, y) + if !got.Eq(brute) || gotOK != bruteOK { + return fmt.Errorf("got %v, %t, brute force gave %v, %t", got, gotOK, brute, bruteOK) + } + return nil +} + +func TestBruteForceAgreesSystematically(tt *testing.T) { + ints := []*big.Int{ + big.NewInt(-7), + big.NewInt(-6), + big.NewInt(-5), + big.NewInt(-4), + big.NewInt(-3), + big.NewInt(-2), + big.NewInt(-1), + big.NewInt(+0), + big.NewInt(+1), + big.NewInt(+2), + big.NewInt(+3), + big.NewInt(+4), + big.NewInt(+5), + big.NewInt(+6), + big.NewInt(+7), + nil, + } + + for _, opKey := range intOperatorsKeys { + + for _, x0 := range ints { + for _, x1 := range ints { + x := Int{x0, x1} + + for _, y0 := range ints { + for _, y1 := range ints { + y := Int{y0, y1} + + if err := testBruteForceAgrees(x, y, opKey); err != nil { + tt.Fatalf("%v %s %v: %v", x, opKey, y, err) + } + } + } + } + } + } +} + +func TestBruteForceAgreesRandomly(tt *testing.T) { + gen := func(rng *rand.Rand) *big.Int { + r := rng.Intn(2*riRadius+2) - (riRadius + 1) + if r == -(riRadius + 1) { + return nil + } + return big.NewInt(int64(r)) + } + + rng := rand.New(rand.NewSource(0)) + for _, opKey := range intOperatorsKeys { + for i := 0; i < 10000; i++ { + x := Int{gen(rng), gen(rng)} + y := Int{gen(rng), gen(rng)} + if err := testBruteForceAgrees(x, y, opKey); err != nil { + tt.Fatalf("%v %s %v: %v", x, opKey, y, err) + } + } + } +} + +func testOp(tt *testing.T, testCases ...string) { + for _, tc := range testCases { + if err := testOp1(tc); err != nil { + tt.Errorf("%q: %v", tc, err) + } + } +} + +func testOp1(s string) error { + x, s, err := parseInterval(s) + if err != nil { + return err + } + s = trimLeadingSpaces(s) + + i := 0 + for ; i < len(s) && s[i] != ' '; i++ { + } + opKey, s := s[:i], s[i:] + + y, s, err := parseInterval(s) + if err != nil { + return err + } + s = trimLeadingSpaces(s) + if !strings.HasPrefix(s, "==") { + return fmt.Errorf(`expected "=="`) + } + s = s[2:] + s = trimLeadingSpaces(s) + want, wantOK := Int{}, false + if s == "invalid" { + s = "" + } else { + wantOK = true + want, s, err = parseInterval(s) + if err != nil { + return err + } + s = trimLeadingSpaces(s) + if s != "" { + return fmt.Errorf("trailing specification %q", s) + } + } + + if err := testBruteForceAgrees(x, y, opKey); err != nil { + return err + } + + got, gotOK := intOperators[opKey](x, y) + if !got.Eq(want) || gotOK != wantOK { + return fmt.Errorf("package code: got %v, %t, want %v, %t", got, gotOK, want, wantOK) + } + return nil +} + +var intOperators = map[string]func(Int, Int) (Int, bool){ + "+": func(x Int, y Int) (z Int, ok bool) { return x.Add(y), true }, + "-": func(x Int, y Int) (z Int, ok bool) { return x.Sub(y), true }, + "*": func(x Int, y Int) (z Int, ok bool) { return x.Mul(y), true }, + "/": Int.Quo, + "<<": Int.Lsh, + ">>": Int.Rsh, +} + +var intOperatorsKeys []string + +func init() { + for k := range intOperators { + intOperatorsKeys = append(intOperatorsKeys, k) + } + sort.Strings(intOperatorsKeys) +} + +func TestOpAdd(tt *testing.T) { + testOp(tt, + "[ 3, 3] + [ -5, -5] == [ -2, -2]", + "[ 3, 3] + [ 0, 0] == [ 3, 3]", + "[ 0, 0] + [ -7, 7] == [ -7, 7]", + "[ 0, 2] + [ 0, 5] == [ 0, 7]", + "[ 3, 6] + [ 10, 15] == [ 13, 21]", + "[ 3, +∞) + [ -4, -2] == [ -1, +∞)", + "[ 3, +∞) + [ 10, 15] == [ 13, +∞)", + "[ 3, +∞) + ( -∞, 15] == ( -∞, +∞)", + "[ 3, 6] + ( -∞, 15] == ( -∞, 21]", + "[ 3, 6] + ( -∞, +∞) == ( -∞, +∞)", + "( -∞, +∞) + ( -∞, +∞) == ( -∞, +∞)", + "( -∞, +∞) + [ 1, 2] == ( -∞, +∞)", + "( -∞, +∞) + [ 0, 0] == ( -∞, +∞)", + "[ 3, 6] + [...empty..] == [...empty..]", + "[...empty..] + [ 10, 15] == [...empty..]", + "[...empty..] + [...empty..] == [...empty..]", + "( -∞, +∞) + [...empty..] == [...empty..]", + ) +} + +func TestOpSub(tt *testing.T) { + testOp(tt, + "[ 3, 3] - [ -5, -5] == [ 8, 8]", + "[ 3, 3] - [ 0, 0] == [ 3, 3]", + "[ 0, 0] - [ -7, 7] == [ -7, 7]", + "[ 0, 2] - [ 0, 5] == [ -5, 2]", + "[ 3, 6] - [ 10, 15] == [ -12, -4]", + "[ 3, +∞) - [ -4, -2] == [ 5, +∞)", + "[ 3, +∞) - [ 10, 15] == [ -12, +∞)", + "[ 3, +∞) - ( -∞, 15] == ( -∞, +∞)", + "[ 3, 6] - ( -∞, 15] == [ -12, +∞)", + "[ 3, 6] - ( -∞, +∞) == ( -∞, +∞)", + "( -∞, +∞) - ( -∞, +∞) == ( -∞, +∞)", + "( -∞, +∞) - [ 1, 2] == ( -∞, +∞)", + "( -∞, +∞) - [ 0, 0] == ( -∞, +∞)", + "[ 3, 6] - [...empty..] == [...empty..]", + "[...empty..] - [ 10, 15] == [...empty..]", + "[...empty..] - [...empty..] == [...empty..]", + "( -∞, +∞) - [...empty..] == [...empty..]", + ) +} + +func TestOpMul(tt *testing.T) { + testOp(tt, + "[ 3, 3] * [ -5, -5] == [ -15, -15]", + "[ 3, 3] * [ 0, 0] == [ 0, 0]", + "[ 0, 0] * [ -7, 7] == [ 0, 0]", + "[ 0, 2] * [ 0, 5] == [ 0, 10]", + "[ 3, 6] * [ 10, 15] == [ 30, 90]", + "[ 3, +∞) * [ -4, -2] == ( -∞, -6]", + "[ 3, +∞) * [ 10, 15] == [ 30, +∞)", + "[ 3, +∞) * ( -∞, 15] == ( -∞, +∞)", + "[ 3, 6] * ( -∞, 15] == ( -∞, 90]", + "[ 3, 6] * ( -∞, +∞) == ( -∞, +∞)", + "( -∞, +∞) * ( -∞, +∞) == ( -∞, +∞)", + "( -∞, +∞) * [ 1, 2] == ( -∞, +∞)", + "( -∞, +∞) * [ 0, 0] == [ 0, 0]", + "[ 3, 6] * [...empty..] == [...empty..]", + "[...empty..] * [ 10, 15] == [...empty..]", + "[...empty..] * [...empty..] == [...empty..]", + "( -∞, +∞) * [...empty..] == [...empty..]", + + "[ -3, -1] * [ -11, -10] == [ 10, 33]", + "[ -3, 0] * [ -11, -10] == [ 0, 33]", + "[ -3, 1] * [ -11, -10] == [ -11, 33]", + "[ -3, 4] * [ -11, -10] == [ -44, 33]", + "[ -1, 4] * [ -11, -10] == [ -44, 11]", + "[ 0, 4] * [ -11, -10] == [ -44, 0]", + "[ 1, 4] * [ -11, -10] == [ -44, -10]", + + "[ -3, -1] * [ -6, 2] == [ -6, 18]", + "[ -3, 0] * [ -6, 2] == [ -6, 18]", + "[ -3, 1] * [ -6, 2] == [ -6, 18]", + "[ -3, 4] * [ -6, 2] == [ -24, 18]", + "[ -1, 4] * [ -6, 2] == [ -24, 8]", + "[ 0, 4] * [ -6, 2] == [ -24, 8]", + "[ 1, 4] * [ -6, 2] == [ -24, 8]", + + "[ -3, -1] * [ 0, 3] == [ -9, 0]", + "[ -3, 0] * [ 0, 3] == [ -9, 0]", + "[ -3, 1] * [ 0, 3] == [ -9, 3]", + "[ -3, 4] * [ 0, 3] == [ -9, 12]", + "[ -1, 4] * [ 0, 3] == [ -3, 12]", + "[ 0, 4] * [ 0, 3] == [ 0, 12]", + "[ 1, 4] * [ 0, 3] == [ 0, 12]", + + "[ -3, -1] * [ 2, 3] == [ -9, -2]", + "[ -3, 0] * [ 2, 3] == [ -9, 0]", + "[ -3, 1] * [ 2, 3] == [ -9, 3]", + "[ -3, 4] * [ 2, 3] == [ -9, 12]", + "[ -1, 4] * [ 2, 3] == [ -3, 12]", + "[ 0, 4] * [ 2, 3] == [ 0, 12]", + "[ 1, 4] * [ 2, 3] == [ 2, 12]", + + "[ -9, +∞) * [ 2, +∞) == ( -∞, +∞)", + "[ -1, +∞) * [ 2, +∞) == ( -∞, +∞)", + "[ 0, +∞) * [ 2, +∞) == [ 0, +∞)", + "[ 1, +∞) * [ 2, +∞) == [ 2, +∞)", + "[ 7, +∞) * [ 2, +∞) == [ 14, +∞)", + "[ -1, 1] * ( -∞, +∞) == ( -∞, +∞)", + "[ 0, 0] * ( -∞, +∞) == [ 0, 0]", + "[ 1, 1] * ( -∞, +∞) == ( -∞, +∞)", + ) +} + +func TestOpQuo(tt *testing.T) { + testOp(tt, + "[ 3, 3] / [ -5, -5] == [ 0, 0]", + "[ 3, 3] / [ 0, 0] == invalid", + "[ 0, 0] / [ -7, 7] == invalid", + "[ 0, 2] / [ 0, 5] == invalid", + "[ 3, 6] / [ 10, 15] == [ 0, 0]", + "[ 3, +∞) / [ -4, -2] == ( -∞, 0]", + "[ 3, +∞) / [ 10, 15] == [ 0, +∞)", + "[ 3, +∞) / ( -∞, 15] == invalid", + "[ 3, 6] / ( -∞, 15] == invalid", + "[ 3, 6] / ( -∞, +∞) == invalid", + "( -∞, +∞) / ( -∞, +∞) == invalid", + "( -∞, +∞) / [ 1, 2] == ( -∞, +∞)", + "( -∞, +∞) / [ 0, 0] == invalid", + "[ 3, 6] / [...empty..] == [...empty..]", + "[...empty..] / [ 10, 15] == [...empty..]", + "[...empty..] / [...empty..] == [...empty..]", + "( -∞, +∞) / [...empty..] == [...empty..]", + + "[ 1, 4] / [ -11, -10] == [ 0, 0]", + + "[ 1, 4] / [ -6, 2] == invalid", + + "[ -3, -1] / [ 1, 3] == [ -3, 0]", + "[ -3, 0] / [ 1, 3] == [ -3, 0]", + "[ -3, 1] / [ 1, 3] == [ -3, 1]", + "[ -3, 4] / [ 1, 3] == [ -3, 4]", + "[ -1, 4] / [ 1, 3] == [ -1, 4]", + "[ 0, 4] / [ 1, 3] == [ 0, 4]", + "[ 1, 4] / [ 1, 3] == [ 0, 4]", + + "[ -3, -1] / [ 2, 3] == [ -1, 0]", + "[ -3, 0] / [ 2, 3] == [ -1, 0]", + "[ -3, 1] / [ 2, 3] == [ -1, 0]", + "[ -3, 4] / [ 2, 3] == [ -1, 2]", + "[ -1, 4] / [ 2, 3] == [ 0, 2]", + "[ 0, 4] / [ 2, 3] == [ 0, 2]", + "[ 1, 4] / [ 2, 3] == [ 0, 2]", + + "[ -9, +∞) / [ 2, +∞) == [ -4, +∞)", + "[ -1, +∞) / [ 2, +∞) == [ 0, +∞)", + "[ 0, +∞) / [ 2, +∞) == [ 0, +∞)", + "[ 1, +∞) / [ 2, +∞) == [ 0, +∞)", + "[ 7, +∞) / [ 2, +∞) == [ 0, +∞)", + "[ -1, 1] / ( -∞, +∞) == invalid", + "[ 0, 0] / ( -∞, +∞) == invalid", + "[ 1, 1] / ( -∞, +∞) == invalid", + ) +} + +func TestOpLsh(tt *testing.T) { + testOp(tt, + "[ 3, 3] << [ -5, -5] == invalid", + "[ 3, 3] << [ 0, 0] == [ 3, 3]", + "[ 0, 0] << [ -7, 7] == invalid", + "[ 0, 2] << [ 0, 5] == [ 0, 64]", + "[ 3, 6] << [ 10, 15] == [3072, 196608]", + "[ 3, +∞) << [ -4, -2] == invalid", + "[ 3, +∞) << [ 10, 15] == [3072, +∞)", + "[ 3, +∞) << ( -∞, 15] == invalid", + "[ 3, 6] << ( -∞, 15] == invalid", + "[ 3, 6] << ( -∞, +∞) == invalid", + "( -∞, +∞) << ( -∞, +∞) == invalid", + "( -∞, +∞) << [ 1, 2] == ( -∞, +∞)", + "( -∞, +∞) << [ 0, 0] == ( -∞, +∞)", + "[ 3, 6] << [...empty..] == [...empty..]", + "[...empty..] << [ 10, 15] == [...empty..]", + "[...empty..] << [...empty..] == [...empty..]", + "( -∞, +∞) << [...empty..] == [...empty..]", + + "[ 1, 4] << [ -11, -10] == invalid", + + "[ 1, 4] << [ -6, 2] == invalid", + + "[ -3, -1] << [ 0, 3] == [ -24, -1]", + "[ -3, 0] << [ 0, 3] == [ -24, 0]", + "[ -3, 1] << [ 0, 3] == [ -24, 8]", + "[ -3, 4] << [ 0, 3] == [ -24, 32]", + "[ -1, 4] << [ 0, 3] == [ -8, 32]", + "[ 0, 4] << [ 0, 3] == [ 0, 32]", + "[ 1, 4] << [ 0, 3] == [ 1, 32]", + + "[ -3, -1] << [ 2, 3] == [ -24, -4]", + "[ -3, 0] << [ 2, 3] == [ -24, 0]", + "[ -3, 1] << [ 2, 3] == [ -24, 8]", + "[ -3, 4] << [ 2, 3] == [ -24, 32]", + "[ -1, 4] << [ 2, 3] == [ -8, 32]", + "[ 0, 4] << [ 2, 3] == [ 0, 32]", + "[ 1, 4] << [ 2, 3] == [ 4, 32]", + + "[ -9, +∞) << [ 2, +∞) == ( -∞, +∞)", + "[ -1, +∞) << [ 2, +∞) == ( -∞, +∞)", + "[ 0, +∞) << [ 2, +∞) == [ 0, +∞)", + "[ 1, +∞) << [ 2, +∞) == [ 4, +∞)", + "[ 7, +∞) << [ 2, +∞) == [ 28, +∞)", + "[ -1, 1] << ( -∞, +∞) == invalid", + "[ 0, 0] << ( -∞, +∞) == invalid", + "[ 1, 1] << ( -∞, +∞) == invalid", + ) +} + +func TestOpRsh(tt *testing.T) { + testOp(tt, + "[ 3, 3] >> [ -5, -5] == invalid", + "[ 3, 3] >> [ 0, 0] == [ 3, 3]", + "[ 0, 0] >> [ -7, 7] == invalid", + "[ 0, 2] >> [ 0, 5] == [ 0, 2]", + "[ 3, 6] >> [ 10, 15] == [ 0, 0]", + "[ 3, +∞) >> [ -4, -2] == invalid", + "[ 3, +∞) >> [ 10, 15] == [ 0, +∞)", + "[ 3, +∞) >> ( -∞, 15] == invalid", + "[ 3, 6] >> ( -∞, 15] == invalid", + "[ 3, 6] >> ( -∞, +∞) == invalid", + "( -∞, +∞) >> ( -∞, +∞) == invalid", + "( -∞, +∞) >> [ 1, 2] == ( -∞, +∞)", + "( -∞, +∞) >> [ 0, 0] == ( -∞, +∞)", + "[ 3, 6] >> [...empty..] == [...empty..]", + "[...empty..] >> [ 10, 15] == [...empty..]", + "[...empty..] >> [...empty..] == [...empty..]", + "( -∞, +∞) >> [...empty..] == [...empty..]", + + "[ 1, 4] >> [ -11, -10] == invalid", + + "[ 1, 4] >> [ -6, 2] == invalid", + + "[ -3, -1] >> [ 0, 3] == [ -3, -1]", + "[ -3, 0] >> [ 0, 3] == [ -3, 0]", + "[ -3, 1] >> [ 0, 3] == [ -3, 1]", + "[ -3, 4] >> [ 0, 3] == [ -3, 4]", + "[ -1, 4] >> [ 0, 3] == [ -1, 4]", + "[ 0, 4] >> [ 0, 3] == [ 0, 4]", + "[ 1, 4] >> [ 0, 3] == [ 0, 4]", + + "[ -3, -1] >> [ 1, 3] == [ -2, -1]", + "[ -3, 0] >> [ 1, 3] == [ -2, 0]", + "[ -3, 1] >> [ 1, 3] == [ -2, 0]", + "[ -3, 4] >> [ 1, 3] == [ -2, 2]", + "[ -1, 4] >> [ 1, 3] == [ -1, 2]", + "[ 0, 4] >> [ 1, 3] == [ 0, 2]", + "[ 1, 4] >> [ 1, 3] == [ 0, 2]", + + "[ -9, +∞) >> [ 2, +∞) == [ -3, +∞)", + "[ -1, +∞) >> [ 2, +∞) == [ -1, +∞)", + "[ 0, +∞) >> [ 2, +∞) == [ 0, +∞)", + "[ 1, +∞) >> [ 2, +∞) == [ 0, +∞)", + "[ 7, +∞) >> [ 2, +∞) == [ 0, +∞)", + "[ -1, 1] >> ( -∞, +∞) == invalid", + "[ 0, 0] >> ( -∞, +∞) == invalid", + "[ 1, 1] >> ( -∞, +∞) == invalid", + ) +} diff --git a/lang/interval/radial_test.go b/lang/interval/radial_test.go new file mode 100644 index 00000000..7e8c9be5 --- /dev/null +++ b/lang/interval/radial_test.go @@ -0,0 +1,380 @@ +// Copyright 2018 The Wuffs Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package interval + +// This file provides "radial numbers", which partition the infinite set +// ℤ∪{NaN} into a finite number of boxes. The source set ℤ∪{NaN} is the set of +// integers, ℤ, augmented with a "Not a Number" element to represent the result +// of computations such as a division by zero or a shift by a negative integer. +// NaN-ness is viral: if x or y is NaN then (x op y) is also NaN, for any +// binary operator op. +// +// Specifically, there are (2*R + 4) boxes, for some non-negative integer +// radius R, and all but two of them contain exactly one element. There are +// (2*R + 1) single-element boxes for "small" integers: those whose absolute +// values are less than or equal to R. There is another single-element box for +// NaN. The two remaining boxes hold "large" integers: those that are less than +// -R and those that are greater than +R. +// +// A rough analogy for a radial number is a primitive counting system: one, +// two, three, many. +// +// This file defines two concrete "radial number" types: +// - radialInput has a radius R of 15. +// - radialOutput has a radius R of 16 << 16 (which equals 1048576). +// +// If x and y are "small" radialInput values or one of the two "smallest large" +// radialInput values, i.e. x and y are in the range [-16, +16], then (x op y) +// will always be a "small" radialOutput value, for the common binary +// operators: add, subtract, multiply, divide, left-shift, right-shift. +// +// Both of these radialInput and radialOutput types are encoded as an int32: +// - math.MinInt32 (which equals -1 << 31) encodes a NaN. +// - "small" numbers (within the interval [-R, +R]) encode themselves. +// - any other negative int32 encodes "less than -R". +// - any other positive int32 encodes "greater than +R". +// +// For example, radialInput(20) and radialInput(30) represent the same box: +// integers greater than +15. +// +// Binary operators take two radialInput values and produce a pair of +// radialOutput values: either a [min, max] interval, or [NaN, NaN]. For +// example, adding the "-3" box to the "greater than +15" box would produce the +// radialOutPair ["13", "greater than +16 << 16"], or in more conventional +// notation, the half-open interval [13, +∞). +// +// These radial number types are not exported by package interval, as the +// radius values (15 and 16 << 16) are somewhat arbitrary and not so generally +// useful. They are only used for brute force testing in interval_test.go. When +// tests in that other file use radial numbers (via calling the bruteForce +// function), the test cases are constructed so that every non-nil member of an +// interval.Int maps to a "small" radialInput, and asSmallRadialInput will +// panic if that doesn't hold. +// +// These types exist in order to simplify calculations. The general problem of +// calculating bounds for (x * y), given intervals for x and y, becomes +// complicated if e.g. x's possible values include both positive and negative +// numbers. In comparison, a radial number's box is either a single value, or +// if multiple values, those values all have the same sign. Computation on +// "small" radial numbers can use Go's built-in operators (+, -, etc) instead +// of the clumsier *big.Int API. +// +// The radial number methods like Add and Mul also have a simpler API than the +// corresponding *big.Int methods, since the radial number methods don't +// allocate memory or therefore need a destination argument. + +import ( + "math/big" +) + +const ( + radialNaN = -1 << 31 + + riRadius = 15 + roRadius = 16 << 16 + + roLargeNeg = -(16<<16 + 1) + roLargePos = +(16<<16 + 1) +) + +type ( + radialInput int32 + radialOutput int32 + radialOutPair [2]radialOutput +) + +func (x radialInput) canonicalize() radialOutput { + o := radialOutput(x) + if o != radialNaN { + // No-op. + } else if o < -riRadius { + return -riRadius - 1 + } else if o > +riRadius { + return +riRadius + 1 + } + return o +} + +func (x radialOutput) bigInt() *big.Int { + if x < -roRadius || +roRadius < x { + return nil + } + return big.NewInt(int64(x)) +} + +func asSmallRadialInput(x *big.Int, defaultIfXIsNil radialInput) radialInput { + if x == nil { + return defaultIfXIsNil + } + if !x.IsInt64() { + panic("asSmallRadialInput passed too large a value") + } + i := x.Int64() + if i < -riRadius || +riRadius < i { + panic("asSmallRadialInput passed too large a value") + } + return radialInput(i) +} + +func enumerate(x Int) (min radialInput, max radialInput) { + if x.Empty() { + return +1, -1 + } + return asSmallRadialInput(x[0], -riRadius-1), asSmallRadialInput(x[1], +riRadius+1) +} + +func (x radialInput) Add(y radialInput) radialOutPair { + if x == radialNaN || y == radialNaN { + return radialOutPair{radialNaN, radialNaN} + } + ox := x.canonicalize() + oy := y.canonicalize() + + switch { + case ox < -riRadius: + if oy > +riRadius { + return radialOutPair{roLargeNeg, roLargePos} + } + return radialOutPair{roLargeNeg, ox + oy} + case ox > +riRadius: + if oy < -riRadius { + return radialOutPair{roLargeNeg, roLargePos} + } + return radialOutPair{ox + oy, roLargePos} + default: + switch { + case oy < -riRadius: + return radialOutPair{roLargeNeg, ox + oy} + case oy > +riRadius: + return radialOutPair{ox + oy, roLargePos} + default: + return radialOutPair{ox + oy, ox + oy} + } + } +} + +func (x radialInput) Sub(y radialInput) radialOutPair { + if x == radialNaN || y == radialNaN { + return radialOutPair{radialNaN, radialNaN} + } + ox := x.canonicalize() + oy := y.canonicalize() + + switch { + case ox < -riRadius: + switch { + case oy < -riRadius, oy > +riRadius: + return radialOutPair{roLargeNeg, roLargePos} + default: + return radialOutPair{roLargeNeg, ox - oy} + } + case ox > +riRadius: + switch { + case oy < -riRadius, oy > +riRadius: + return radialOutPair{roLargeNeg, roLargePos} + default: + return radialOutPair{ox - oy, roLargePos} + } + default: + switch { + case oy < -riRadius: + return radialOutPair{ox - oy, roLargePos} + case oy > +riRadius: + return radialOutPair{roLargeNeg, ox - oy} + default: + return radialOutPair{ox - oy, ox - oy} + } + } +} + +func (x radialInput) Mul(y radialInput) radialOutPair { + if x == radialNaN || y == radialNaN { + return radialOutPair{radialNaN, radialNaN} + } + ox := x.canonicalize() + oy := y.canonicalize() + + switch { + case ox < -riRadius: + if oy < 0 { + return radialOutPair{ox * oy, roLargePos} + } else if oy > 0 { + return radialOutPair{roLargeNeg, ox * oy} + } + return radialOutPair{0, 0} + case ox > +riRadius: + if oy < 0 { + return radialOutPair{roLargeNeg, ox * oy} + } else if oy > 0 { + return radialOutPair{ox * oy, roLargePos} + } + return radialOutPair{0, 0} + default: + switch { + case oy < -riRadius: + if ox < 0 { + return radialOutPair{ox * oy, roLargePos} + } else if ox > 0 { + return radialOutPair{roLargeNeg, ox * oy} + } + return radialOutPair{0, 0} + case oy > +riRadius: + if ox < 0 { + return radialOutPair{roLargeNeg, ox * oy} + } else if ox > 0 { + return radialOutPair{ox * oy, roLargePos} + } + return radialOutPair{0, 0} + default: + return radialOutPair{ox * oy, ox * oy} + } + } +} + +func (x radialInput) Lsh(y radialInput) radialOutPair { + if x == radialNaN || y == radialNaN || y < 0 { + return radialOutPair{radialNaN, radialNaN} + } + ox := x.canonicalize() + oy := uint32(y.canonicalize()) + + switch { + case ox < -riRadius: + return radialOutPair{roLargeNeg, ox << oy} + case ox > +riRadius: + return radialOutPair{ox << oy, roLargePos} + default: + if oy <= +riRadius { + return radialOutPair{ox << oy, ox << oy} + } else if ox < 0 { + return radialOutPair{roLargeNeg, ox << oy} + } else if ox > 0 { + return radialOutPair{ox << oy, roLargePos} + } + return radialOutPair{0, 0} + } +} + +func (x radialInput) Quo(y radialInput) radialOutPair { + if x == radialNaN || y == radialNaN || y == 0 { + return radialOutPair{radialNaN, radialNaN} + } + ox := x.canonicalize() + oy := y.canonicalize() + + switch { + case ox < -riRadius: + switch { + case oy < -riRadius: + return radialOutPair{0, roLargePos} + case oy > +riRadius: + return radialOutPair{roLargeNeg, 0} + default: + if oy < 0 { + return radialOutPair{ox / oy, roLargePos} + } + return radialOutPair{roLargeNeg, ox / oy} + } + case ox > +riRadius: + switch { + case oy < -riRadius: + return radialOutPair{roLargeNeg, 0} + case oy > +riRadius: + return radialOutPair{0, roLargePos} + default: + if oy < 0 { + return radialOutPair{roLargeNeg, ox / oy} + } + return radialOutPair{ox / oy, roLargePos} + } + default: + switch { + case oy < -riRadius, oy > +riRadius: + return radialOutPair{0, 0} + default: + return radialOutPair{ox / oy, ox / oy} + } + } +} + +func (x radialInput) Rsh(y radialInput) radialOutPair { + if x == radialNaN || y == radialNaN || y < 0 { + return radialOutPair{radialNaN, radialNaN} + } + ox := x.canonicalize() + oy := uint32(y.canonicalize()) + + switch { + case ox < -riRadius: + if oy > +riRadius { + return radialOutPair{roLargeNeg, -1} + } + return radialOutPair{roLargeNeg, ox >> oy} + case ox > +riRadius: + if oy > +riRadius { + return radialOutPair{0, roLargePos} + } + return radialOutPair{ox >> oy, roLargePos} + default: + if oy <= +riRadius { + return radialOutPair{ox >> oy, ox >> oy} + } else if ox < 0 { + return radialOutPair{-1, -1} + } + return radialOutPair{0, 0} + } +} + +var riOperators = map[string]func(radialInput, radialInput) radialOutPair{ + "+": radialInput.Add, + "-": radialInput.Sub, + "*": radialInput.Mul, + "/": radialInput.Quo, + "<<": radialInput.Lsh, + ">>": radialInput.Rsh, +} + +func bruteForce(x Int, y Int, opKey string) (z Int, ok bool) { + op := riOperators[opKey] + iMin, iMax := enumerate(x) + jMin, jMax := enumerate(y) + result := radialOutPair{} + first := true + + for i := iMin; i <= iMax; i++ { + for j := jMin; j <= jMax; j++ { + k := op(i, j) + if k[0] == radialNaN || k[1] == radialNaN { + return Int{}, false + } + if first { + result = k + first = false + continue + } + if result[0] > k[0] { + result[0] = k[0] + } + if result[1] < k[1] { + result[1] = k[1] + } + } + } + + if first { + return empty(), true + } + return Int{result[0].bigInt(), result[1].bigInt()}, true +}