Skip to content

Commit

Permalink
helpers: fix race condition and simplify New
Browse files Browse the repository at this point in the history
  • Loading branch information
disintegration committed May 8, 2018
1 parent bbec8e4 commit bbcee2f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 28 deletions.
30 changes: 7 additions & 23 deletions helpers.go
@@ -1,6 +1,7 @@
package imaging

import (
"bytes"
"errors"
"image"
"image/color"
Expand Down Expand Up @@ -244,33 +245,16 @@ func New(width, height int, fillColor color.Color) *image.NRGBA {
return &image.NRGBA{}
}

dst := image.NewNRGBA(image.Rect(0, 0, width, height))
c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)

if c.R == 0 && c.G == 0 && c.B == 0 && c.A == 0 {
return dst
if (c == color.NRGBA{0, 0, 0, 0}) {
return image.NewNRGBA(image.Rect(0, 0, width, height))
}

// Fill the first row.
i := 0
for x := 0; x < width; x++ {
dst.Pix[i+0] = c.R
dst.Pix[i+1] = c.G
dst.Pix[i+2] = c.B
dst.Pix[i+3] = c.A
i += 4
return &image.NRGBA{
Pix: bytes.Repeat([]byte{c.R, c.G, c.B, c.A}, width*height),
Stride: 4 * width,
Rect: image.Rect(0, 0, width, height),
}

// Copy the first row to other rows.
size := width * 4
parallel(1, height, func(ys <-chan int) {
for y := range ys {
i = y * dst.Stride
copy(dst.Pix[i:i+size], dst.Pix[0:size])
}
})

return dst
}

// Clone returns a copy of the given image.
Expand Down
17 changes: 12 additions & 5 deletions helpers_test.go
Expand Up @@ -181,23 +181,23 @@ func TestNew(t *testing.T) {
dstPix []uint8
}{
{
"New 1x1 black",
"New 1x1 transparent",
1, 1,
color.NRGBA{0, 0, 0, 0},
color.Transparent,
image.Rect(0, 0, 1, 1),
[]uint8{0x00, 0x00, 0x00, 0x00},
},
{
"New 1x2 red",
1, 2,
color.NRGBA{255, 0, 0, 255},
color.RGBA{255, 0, 0, 255},
image.Rect(0, 0, 1, 2),
[]uint8{0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff},
},
{
"New 2x1 white",
2, 1,
color.NRGBA{255, 255, 255, 255},
color.White,
image.Rect(0, 0, 2, 1),
[]uint8{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
},
Expand All @@ -215,10 +215,17 @@ func TestNew(t *testing.T) {
{
"New 0x0 white",
0, 0,
color.NRGBA{255, 255, 255, 255},
color.White,
image.Rect(0, 0, 0, 0),
nil,
},
{
"New 800x600 custom",
800, 600,
color.NRGBA{1, 2, 3, 4},
image.Rect(0, 0, 800, 600),
bytes.Repeat([]byte{1, 2, 3, 4}, 800*600),
},
}

for _, tc := range testCases {
Expand Down

0 comments on commit bbcee2f

Please sign in to comment.