Skip to content

Commit e8eb1d8

Browse files
urandom2ianlancetaylor
authored andcommitted
math: add MaxUint, MinInt, MaxInt
Since we have int8 to int64 min max and uint8 to uint64 max constants, we should probably have some for the word size types too. This change also adds tests to validate the correctness of all integer limit values. Fixes #28538 Change-Id: Idd25782e98d16c2abedf39959b7b66e9c4c0c98b Reviewed-on: https://go-review.googlesource.com/c/go/+/247058 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Trust: Robert Griesemer <[email protected]>
1 parent ed5ebd3 commit e8eb1d8

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/math/const.go

+5
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ const (
3737

3838
// Integer limit values.
3939
const (
40+
intSize = 32 << (^uint(0) >> 63) // 32 or 64
41+
42+
MaxInt = 1<<(intSize-1) - 1
43+
MinInt = -1 << (intSize - 1)
4044
MaxInt8 = 1<<7 - 1
4145
MinInt8 = -1 << 7
4246
MaxInt16 = 1<<15 - 1
@@ -45,6 +49,7 @@ const (
4549
MinInt32 = -1 << 31
4650
MaxInt64 = 1<<63 - 1
4751
MinInt64 = -1 << 63
52+
MaxUint = 1<<intSize - 1
4853
MaxUint8 = 1<<8 - 1
4954
MaxUint16 = 1<<16 - 1
5055
MaxUint32 = 1<<32 - 1

src/math/const_test.go

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright 2021 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package math_test
6+
7+
import (
8+
"testing"
9+
10+
. "math"
11+
)
12+
13+
func TestMaxUint(t *testing.T) {
14+
if v := uint(MaxUint); v+1 != 0 {
15+
t.Errorf("MaxUint should wrap around to zero: %d", v+1)
16+
}
17+
if v := uint8(MaxUint8); v+1 != 0 {
18+
t.Errorf("MaxUint8 should wrap around to zero: %d", v+1)
19+
}
20+
if v := uint16(MaxUint16); v+1 != 0 {
21+
t.Errorf("MaxUint16 should wrap around to zero: %d", v+1)
22+
}
23+
if v := uint32(MaxUint32); v+1 != 0 {
24+
t.Errorf("MaxUint32 should wrap around to zero: %d", v+1)
25+
}
26+
if v := uint64(MaxUint64); v+1 != 0 {
27+
t.Errorf("MaxUint64 should wrap around to zero: %d", v+1)
28+
}
29+
}
30+
31+
func TestMaxInt(t *testing.T) {
32+
if v := int(MaxInt); v+1 != MinInt {
33+
t.Errorf("MaxInt should wrap around to MinInt: %d", v+1)
34+
}
35+
if v := int8(MaxInt8); v+1 != MinInt8 {
36+
t.Errorf("MaxInt8 should wrap around to MinInt8: %d", v+1)
37+
}
38+
if v := int16(MaxInt16); v+1 != MinInt16 {
39+
t.Errorf("MaxInt16 should wrap around to MinInt16: %d", v+1)
40+
}
41+
if v := int32(MaxInt32); v+1 != MinInt32 {
42+
t.Errorf("MaxInt32 should wrap around to MinInt32: %d", v+1)
43+
}
44+
if v := int64(MaxInt64); v+1 != MinInt64 {
45+
t.Errorf("MaxInt64 should wrap around to MinInt64: %d", v+1)
46+
}
47+
}

0 commit comments

Comments
 (0)