further speed up parsePixels()

This commit is contained in:
Norwin Roosen 2020-02-11 13:34:33 +01:00
parent 15b9cf19da
commit 067bef55f6
1 changed files with 19 additions and 21 deletions

View File

@ -7,8 +7,6 @@ import (
"image/color" "image/color"
"log" "log"
"net" "net"
"net/textproto"
"strconv"
) )
// Flut asynchronously sends the given image to pixelflut server at `address` // Flut asynchronously sends the given image to pixelflut server at `address`
@ -39,44 +37,44 @@ func FetchImage(bounds image.Rectangle, address string, conns int) (img *image.N
// @cleanup: parsePixels calls conn.Close(), as deferring it here would // @cleanup: parsePixels calls conn.Close(), as deferring it here would
// instantly close it // instantly close it
go parsePixels(img, conn) go readPixels(img, conn)
go bombConn(cmds[i], conn) go bombConn(cmds[i], conn)
} }
return img return img
} }
func parsePixels(target *image.NRGBA, conn net.Conn) { func readPixels(target *image.NRGBA, conn net.Conn) {
reader := bufio.NewReader(conn)
tp := textproto.NewReader(reader)
defer conn.Close() defer conn.Close()
reader := bufio.NewReader(conn)
col := make([]byte, 3)
for { for {
// @speed: textproto seems not the fastest, buffer text manually & split at \n ? res, err := reader.ReadSlice('\n')
res, err := tp.ReadLine()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
// parse response ("PX <x> <y> <col>") // parse response ("PX <x> <y> <col>\n")
// @incomplete errorhandling colorStart := len(res) - 7
colorStart := len(res) - 6
xy := res[3:colorStart - 1] xy := res[3:colorStart - 1]
yStart := 0 yStart := 0
for yStart = len(xy) - 1; yStart >= 0; yStart-- { for yStart = len(xy) - 2; yStart >= 0; yStart-- {
if xy[yStart] == ' ' { if xy[yStart] == ' ' {
break break
} }
} }
x, _ := strconv.Atoi(xy[:yStart]) x := asciiToInt(xy[:yStart])
y, _ := strconv.Atoi(xy[yStart+1:]) y := asciiToInt(xy[yStart + 1:])
col, _ := hex.DecodeString(res[colorStart:]) hex.Decode(col, res[colorStart:len(res) - 1])
target.Set(x, y, color.NRGBA{ target.SetNRGBA(x, y, color.NRGBA{ col[0], col[1], col[2], 255 })
uint8(col[0]),
uint8(col[1]),
uint8(col[2]),
255,
})
} }
} }
func asciiToInt(buf []byte) (v int) {
for _, c := range buf {
v = v * 10 + int(c - '0')
}
return v
}