Source file src/internal/runtime/math/math.go
1 // Copyright 2018 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 6 7 import "internal/goarch" 8 9 const ( 10 MaxUint16 = ^uint16(0) 11 MaxUint32 = ^uint32(0) 12 MaxUint64 = ^uint64(0) 13 MaxUintptr = ^uintptr(0) 14 15 MaxInt64 = int64(MaxUint64 >> 1) 16 ) 17 18 // MulUintptr returns a * b and whether the multiplication overflowed. 19 // On supported platforms this is an intrinsic lowered by the compiler. 20 func MulUintptr(a, b uintptr) (uintptr, bool) { 21 if a|b < 1<<(4*goarch.PtrSize) || a == 0 { 22 return a * b, false 23 } 24 overflow := b > MaxUintptr/a 25 return a * b, overflow 26 } 27 28 // Add64 returns the sum with carry of x, y and carry: sum = x + y + carry. 29 // The carry input must be 0 or 1; otherwise the behavior is undefined. 30 // The carryOut output is guaranteed to be 0 or 1. 31 // 32 // This function's execution time does not depend on the inputs. 33 // On supported platforms this is an intrinsic lowered by the compiler. 34 func Add64(x, y, carry uint64) (sum, carryOut uint64) { 35 sum = x + y + carry 36 // The sum will overflow if both top bits are set (x & y) or if one of them 37 // is (x | y), and a carry from the lower place happened. If such a carry 38 // happens, the top bit will be 1 + 0 + 1 = 0 (&^ sum). 39 carryOut = ((x & y) | ((x | y) &^ sum)) >> 63 40 return 41 } 42