On 2/22/20, Bruno Albuquerque <
b...@gmail.com> wrote:
>
https://play.golang.org/p/Y7ICg7t4_nd
>
> ...
>
> Unfortunately, I could not find an incantation that would remove the bound
> checks.
The code from that
play.golang.org link is:
----
func NRGBA(rgbData []byte) []byte {
nrgbaData := make([]byte, len(rgbData)+(len(rgbData)/3))
offset := 0
for i := 0; i < len(rgbData); i = i + 3 {
nrgbaData[i+0+offset] = rgbData[i]
nrgbaData[i+1+offset] = rgbData[i+1]
nrgbaData[i+2+offset] = rgbData[i+2]
nrgbaData[i+3+offset] = 255
offset++
}
return nrgbaData
}
----
Well, the compiler cannot remove the bounds checks because that
function isn't actually bounds-safe, right? For example, if I call
that func with an rgbData slice such that len(rgbData) == 1, then:
nrgbaData is make'd with length (1 + (1/3)), which is 1.
offset is 0.
The loop over i runs 1 time (at i := 0, which satisfies i < 1).
But inside the loop, this line of code:
nrgbaData[i+1+offset] = rgbData[i+1]
is:
nrgbaData[1] = rgbData[1]
which is two bounds violations. As discussed above, both nrgbaData and
rgbData have length 1.
For the broader point, if you're trying to optimize pixel format
conversions, you might find
https://github.com/golang/exp/tree/master/shiny/driver/internal/swizzle
educational.