mirror of
https://github.com/golang/go
synced 2024-11-07 01:46:15 -07:00
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 <iant@golang.org> TryBot-Result: Go Bot <gobot@golang.org> Reviewed-by: Ian Lance Taylor <iant@golang.org> Trust: Robert Griesemer <gri@golang.org>
This commit is contained in:
parent
ed5ebd32b3
commit
e8eb1d8269
@ -37,6 +37,10 @@ const (
|
||||
|
||||
// Integer limit values.
|
||||
const (
|
||||
intSize = 32 << (^uint(0) >> 63) // 32 or 64
|
||||
|
||||
MaxInt = 1<<(intSize-1) - 1
|
||||
MinInt = -1 << (intSize - 1)
|
||||
MaxInt8 = 1<<7 - 1
|
||||
MinInt8 = -1 << 7
|
||||
MaxInt16 = 1<<15 - 1
|
||||
@ -45,6 +49,7 @@ const (
|
||||
MinInt32 = -1 << 31
|
||||
MaxInt64 = 1<<63 - 1
|
||||
MinInt64 = -1 << 63
|
||||
MaxUint = 1<<intSize - 1
|
||||
MaxUint8 = 1<<8 - 1
|
||||
MaxUint16 = 1<<16 - 1
|
||||
MaxUint32 = 1<<32 - 1
|
||||
|
47
src/math/const_test.go
Normal file
47
src/math/const_test.go
Normal file
@ -0,0 +1,47 @@
|
||||
// Copyright 2021 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package math_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "math"
|
||||
)
|
||||
|
||||
func TestMaxUint(t *testing.T) {
|
||||
if v := uint(MaxUint); v+1 != 0 {
|
||||
t.Errorf("MaxUint should wrap around to zero: %d", v+1)
|
||||
}
|
||||
if v := uint8(MaxUint8); v+1 != 0 {
|
||||
t.Errorf("MaxUint8 should wrap around to zero: %d", v+1)
|
||||
}
|
||||
if v := uint16(MaxUint16); v+1 != 0 {
|
||||
t.Errorf("MaxUint16 should wrap around to zero: %d", v+1)
|
||||
}
|
||||
if v := uint32(MaxUint32); v+1 != 0 {
|
||||
t.Errorf("MaxUint32 should wrap around to zero: %d", v+1)
|
||||
}
|
||||
if v := uint64(MaxUint64); v+1 != 0 {
|
||||
t.Errorf("MaxUint64 should wrap around to zero: %d", v+1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxInt(t *testing.T) {
|
||||
if v := int(MaxInt); v+1 != MinInt {
|
||||
t.Errorf("MaxInt should wrap around to MinInt: %d", v+1)
|
||||
}
|
||||
if v := int8(MaxInt8); v+1 != MinInt8 {
|
||||
t.Errorf("MaxInt8 should wrap around to MinInt8: %d", v+1)
|
||||
}
|
||||
if v := int16(MaxInt16); v+1 != MinInt16 {
|
||||
t.Errorf("MaxInt16 should wrap around to MinInt16: %d", v+1)
|
||||
}
|
||||
if v := int32(MaxInt32); v+1 != MinInt32 {
|
||||
t.Errorf("MaxInt32 should wrap around to MinInt32: %d", v+1)
|
||||
}
|
||||
if v := int64(MaxInt64); v+1 != MinInt64 {
|
||||
t.Errorf("MaxInt64 should wrap around to MinInt64: %d", v+1)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user