On Tue, Dec 31, 2019 at 9:58 AM <jvm...@gmail.com> wrote:
>
> So I looked at the implementation of ReadAll, and found this interesting 
> little nugget:
>
> if int64(int(capacity)) == capacity {
>     34   buf.Grow(int(capacity))
>     35   }
>
>
> To see it in context: https://golang.org/src/io/ioutil/ioutil.go?s=807:875#L18
>
> Can anybody decipher what the point of the cast to `int` and then back to 
> `int64` is? My best guess is it's guarding against integer overflow on a 
> 32-bit arch, but it seems like there would be a more straightforward way to 
> do that.. ?

The Go standard library keeps file sizes as int64, and ioutil.ReadFile
wants to pass that size to readAll, so readAll takes the capacity as
an int64.  However, in Go, the type int is the size of an object that
can be stored in memory, and on a 32-bit system this is of course a
32-bit type.  Since a bytes.Buffer lives in memory, its size is type
int.  To save time we want to grow the buffer to be large enough to
hold the expected file size.  But of course converting a value like
0x200000000 to a 32-bit int will give us zero, and we don't want to
grow the buffer to size 0.  So we only grow the buffer if we can
represent the capacity in type int.  And it's very easy to test
whether an int64 value fits in type int by writing int64(int(x)) == x.
So that is what the code does.

I think you are asking whether there is a more straightforward way to
check whether an int64 value fits in an int, but I can't think of what
that might be.  This approach seems straightforward to me: if you
convert to int and then back to int64, do you still have the same
value?  (Although this isn't the most important criterion here, this
approach does have the advantage of compiling away on a system where
int is 64 bits.)

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcXq8TXgFrQ4JreZwZbXiRobFwaBC4%2BkKSFo6GNYCeHptw%40mail.gmail.com.

Reply via email to