go-text / render

Rendering capabilities for go-text based typesetting
Other
10 stars 2 forks source link

Fix out-of-bounds bug for tiny bitmap rendering #18

Closed diamondburned closed 6 months ago

diamondburned commented 6 months ago

Previously, when rendering a tiny black-and-white bitmap font such as turquoise-hexagon/cherry or lucy/tewi-font, the code would panic with an out of bounds error:

panic: runtime error: index out of range [4] with length 4

goroutine 1 [running]:
github.com/go-text/render.(*Renderer).drawBitmap(0xc0001aa1a0, {0x0, 0x0, 0x33, 0x0, 0x133, 0x0, 0x0, 0x0, 0x0, ...}, ...)
    /home/diamond/.go/pkg/mod/github.com/go-text/render@v0.1.0/bitmap.go:30 +0x725
github.com/go-text/render.(*Renderer).DrawShapedRunAt(0xc0001aa1a0, {0x10ca, 0x200, {0xc000024a80, 0xe, 0xe}, {0x19a, 0xffffff99, 0x0}, {0x0, ...}, ...}, ...)
    /home/diamond/.go/pkg/mod/github.com/go-text/render@v0.1.0/render.go:108 +0x3cf
github.com/go-text/render.(*Renderer).DrawString(0xc0001aa1a0, {0xc00019be90?, 0xe?}, {0x6cc4a0, 0xc0000b6280}, 0x676c01?)
    /home/diamond/.go/pkg/mod/github.com/go-text/render@v0.1.0/render.go:65 +0xe5
main.main()
    /home/diamond/Scripts/pi-oled-playground/main.go:78 +0x3ab

This commit fixes the issue by rewriting the loop that draws bitmap pixels to the image canvas.

Previously, this loop tries to be fast by unrolling it to draw 8 pixels per iteration, but this was causing the panic to occur. Rather than figuring out more checks to safe-guard this loop, I rewrote it to use a simplier copy loop.

A test case for turquoise-hexagon/cherry was added to ensure that the code works as expected in the future. The new test case draws a "Hello, world!" string onto the top of the out.png image.