Elliot Chance
Elliot Chance

Reputation: 5746

Is this a compiler trick in Go?

There is a function in the Go language (https://github.com/golang/go/blob/master/src/io/ioutil/ioutil.go#L18-L38). Specifically this branch seems redundant to me:

if int64(int(capacity)) == capacity {
    buf.Grow(int(capacity))
}

capacity is never modified and the function doesn't seem to be recursive. Is this something to trick the compiler?

Upvotes: 1

Views: 101

Answers (2)

Burak Serdar
Burak Serdar

Reputation: 51662

It looks like it is to prevent allocating a very large buffer for architectures smaller than 64 bits. That equivalence check will fail if int is smaller than 64 bits on the architecture and capacity is larger than int limit.

Upvotes: 2

torek
torek

Reputation: 489848

The capacity argument to io.ReadAll has type int64. The argument to *bytes.Buffer's Grow is int. So we have to narrow the input int64 to (perhaps) 32 bits. The result may not be the same value as the original int64 value. If not, we skip the call (though I might argue that we should try to grow the buffer to the maximum int value, or—probably better—just return an error directly).

Upvotes: 5

Related Questions