Skip to content

Commit

Permalink
Add fast-path for SetRGBA/SetNRGBA interfaces, use Set as fallback.
Browse files Browse the repository at this point in the history
  • Loading branch information
bbrks committed Sep 5, 2020
1 parent 9fa9a88 commit e2f229d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
28 changes: 22 additions & 6 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ func Decode(hash string, width, height int, punch int) (image.Image, error) {
return newImg, nil
}

type drawImageNRGBA interface {
SetNRGBA(x, y int, c color.NRGBA)
}

type drawImageRGBA interface {
SetRGBA(x, y int, c color.RGBA)
}

// DecodeDraw decodes the given hash into the given image.
func DecodeDraw(dst draw.Image, hash string, punch float64) error {
numX, numY, err := Components(hash)
Expand Down Expand Up @@ -85,12 +93,20 @@ func DecodeDraw(dst draw.Image, hash string, punch float64) error {
}
}

dst.Set(x, y, color.NRGBA{
R: uint8(linearTosRGB(r)),
G: uint8(linearTosRGB(g)),
B: uint8(linearTosRGB(b)),
A: 255,
})
sR := uint8(linearTosRGB(r))
sG := uint8(linearTosRGB(g))
sB := uint8(linearTosRGB(b))
sA := uint8(255)

// interface smuggle
switch d := dst.(type) {
case drawImageNRGBA:
d.SetNRGBA(x, y, color.NRGBA{sR, sG, sB, sA})
case drawImageRGBA:
d.SetRGBA(x, y, color.RGBA{sR, sG, sB, sA})
default:
d.Set(x, y, color.NRGBA{sR, sG, sB, sA})
}
}
}

Expand Down
16 changes: 16 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,19 @@ func BenchmarkDecode(b *testing.B) {
})
}
}

func BenchmarkDecodeDraw(b *testing.B) {
for _, test := range testFixtures {
// skip tests without hashes
if test.hash == "" {
continue
}

b.Run(test.hash, func(b *testing.B) {
for i := 0; i < b.N; i++ {
dst := image.NewRGBA(image.Rect(0, 0, 32, 32))
_ = blurhash.DecodeDraw(dst, test.hash, 1)
}
})
}
}

0 comments on commit e2f229d

Please sign in to comment.