Fair enough. This would never happen in practice but the compiler has no way to know. Would adding an explicit len() check before the loop help the compiler in any way (can not test right now)?
Concerning Swizzle: Although what I am doing is technically a color space conversion, going from RGB to (N)RGBA (as the alpha channel is always 255, it can be converted to non-normalized and normalized RGBA de same way), the actual conversion is just adding the alpha channel (or an extra byte every 3 bytes). I guess one can do this in a pretty fast way without having to resort to assembly. On Sat, Feb 22, 2020 at 3:36 AM Nigel Tao <nigel...@golang.org> wrote: > 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. > -- 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/CAEd86TyrS%3DofozkDRLrfV8pL3FU9%3D0qZ9DNQcrW1yNynDQpaqw%40mail.gmail.com.