restorable: Avoid memory allocating when an entire image is cleared

This commit is contained in:
Hajime Hoshi 2018-10-30 11:08:38 +09:00
parent bb0b8ca83b
commit b2b09ccec0
2 changed files with 29 additions and 3 deletions

View File

@ -169,10 +169,16 @@ func (i *Image) ReplacePixels(pixels []byte, x, y, width, height int) {
}
if x == 0 && y == 0 && width == w && height == h {
if pixels != nil {
if i.basePixels == nil {
i.basePixels = make([]byte, 4*w*h)
}
copy(i.basePixels, pixels)
} else {
// If basePixels is nil, the restored pixels are cleared.
// See restore() implementation.
i.basePixels = nil
}
i.drawImageHistory = nil
i.stale = false
return

View File

@ -97,6 +97,26 @@ func TestRestore(t *testing.T) {
}
}
func TestRestoreWithoutDraw(t *testing.T) {
img0 := NewImage(1024, 1024, false)
defer img0.Dispose()
// If there is no drawing command on img0, img0 is cleared when restored.
ResolveStaleImages()
if err := Restore(); err != nil {
t.Fatal(err)
}
for i := 0; i < 1024*1024; i++ {
want := color.RGBA{0x00, 0x00, 0x00, 0x00}
got := byteSliceToColor(img0.BasePixelsForTesting(), i)
if !sameColors(got, want, 0) {
t.Errorf("got %v, want %v", got, want)
}
}
}
func TestRestoreChain(t *testing.T) {
const num = 10
imgs := []*Image{}