Go:字节.重复检查是否有溢出

  • 本文关键字:是否 溢出 字节 Go go
  • 更新时间 :
  • 英文 :


在 bytes .go 的 Go 字节包行 412 中,有一个条件如下:(https://golang.org/src/bytes/bytes.go?s=10462:10501#L412(

len(b)*count/count != len(b)

这显然应该检查溢出,但我不明白如何。这是否正在检查整数的基础数据类型的某些溢出?还是这是实施中的错误? len(b)*count/count应该始终len(b)...不?

它正在检查溢出。

// bytes.Repeat(make([]byte, 255), int((^uint(0))/255+1)) panics with the test.
// Without the test, it returns a bad result.
b := make([]byte, 255)
count := int((^uint(0))/255 + 1)
fmt.Println("count:", count)    // prints 16843010 on the playground
fmt.Println("len(b):", len(b))  // prints 255
fmt.Println("count * len(b): ", count*len(b))  // prints 254 
fmt.Println("len(b) * count / count != len(b):", len(b)*count/count != len(b)) // prints false

https://play.golang.org/p/3OQ0vB0WC4

最新更新