英文:
Go: bytes.Repeat check for overflow
问题
在Go语言的bytes包的bytes.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)...是吗?
英文:
In Go's bytes package line 412 of bytes.go, there is a condition that goes as follows: (https://golang.org/src/bytes/bytes.go?s=10462:10501#L412)
len(b)*count/count != len(b)
This should apparently check for overflow but I don't understand how. Is this checking for some overflow of the underlying data type for integer? Or is this an error in implementation? len(b)*count/count should always be len(b)...no?
答案1
得分: 0
这是一个检查溢出的代码示例。在测试中,使用bytes.Repeat(make([]byte, 255), int((^uint(0))/255+1))会导致程序崩溃。如果没有测试,它会返回错误的结果。
代码中,首先创建了一个长度为255的字节切片b。然后计算了一个名为count的变量,其值为int((^uint(0))/255 + 1)。
在输出部分,打印了count的值(在playground上打印的结果为16843010),打印了b的长度(打印结果为255),打印了count乘以len(b)的结果(打印结果为254),以及判断len(b)*count/count != len(b)的结果(打印结果为false)。
你可以在这个链接中查看完整的代码和运行结果:https://play.golang.org/p/3OQ0vB0WC4
英文:
// 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论