Skip to content

Commit

Permalink
image: use three-index slice for NewYCbCr.
Browse files Browse the repository at this point in the history
This ensures that changing an image.YCbCr's Y values can't change its
chroma values, even after re-slicing up to capacity.

Change-Id: Icb626561522e336a3220e10f456c95330ae7db9e
Reviewed-on: https://go-review.googlesource.com/2209
Reviewed-by: Rob Pike <[email protected]>
  • Loading branch information
nigeltao authored and robpike committed Jan 5, 2015
1 parent 43ce5c0 commit 0b52392
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/image/ycbcr.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,14 @@ func NewYCbCr(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *YCbCr {
cw = w
ch = h
}
b := make([]byte, w*h+2*cw*ch)
i0 := w*h + 0*cw*ch
i1 := w*h + 1*cw*ch
i2 := w*h + 2*cw*ch
b := make([]byte, i2)
return &YCbCr{
Y: b[:w*h],
Cb: b[w*h+0*cw*ch : w*h+1*cw*ch],
Cr: b[w*h+1*cw*ch : w*h+2*cw*ch],
Y: b[:i0:i0],
Cb: b[i0:i1:i1],
Cr: b[i1:i2:i2],
SubsampleRatio: subsampleRatio,
YStride: w,
CStride: cw,
Expand Down
24 changes: 24 additions & 0 deletions src/image/ycbcr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,27 @@ func testYCbCr(t *testing.T, r Rectangle, subsampleRatio YCbCrSubsampleRatio, de
}
}
}

func TestYCbCrSlicesDontOverlap(t *testing.T) {
m := NewYCbCr(Rect(0, 0, 8, 8), YCbCrSubsampleRatio420)
names := []string{"Y", "Cb", "Cr"}
slices := [][]byte{
m.Y[:cap(m.Y)],
m.Cb[:cap(m.Cb)],
m.Cr[:cap(m.Cr)],
}
for i, slice := range slices {
want := uint8(10 + i)
for j := range slice {
slice[j] = want
}
}
for i, slice := range slices {
want := uint8(10 + i)
for j, got := range slice {
if got != want {
t.Fatalf("m.%s[%d]: got %d, want %d", names[i], j, got, want)
}
}
}
}

0 comments on commit 0b52392

Please sign in to comment.