update png crc handling

This commit is contained in:
Ryan Oldenburg 2022-06-11 16:10:52 -05:00
parent 7ed8ec507e
commit 97ba8c745f

View file

@ -21,8 +21,8 @@ type
template failInvalid() = template failInvalid() =
raise newException(PixieError, "Invalid PNG buffer, unable to load") raise newException(PixieError, "Invalid PNG buffer, unable to load")
# template failCRC() = template failCRC() =
# raise newException(PixieError, "CRC check failed") raise newException(PixieError, "CRC check failed")
when defined(release): when defined(release):
{.push checks: off.} {.push checks: off.}
@ -400,8 +400,9 @@ proc decodePng*(data: pointer, len: int): Png {.raises: [PixieError].} =
prevChunkType = "IHDR" prevChunkType = "IHDR"
inc(pos, 13) inc(pos, 13)
# if crc32(data[pos - 17 ..< pos]) != read32be(data, pos): let headerCrc = crc32(data[pos - 17].addr, 17)
# failCRC() if headerCrc != data.readUint32(pos).swap():
failCRC()
inc(pos, 4) # CRC inc(pos, 4) # CRC
while true: while true:
@ -462,8 +463,9 @@ proc decodePng*(data: pointer, len: int): Png {.raises: [PixieError].} =
inc(pos, chunkLen) inc(pos, chunkLen)
# if crc32(data[pos - chunkLen - 4 ..< pos]) != read32be(data, pos): let chunkCrc = crc32(data[pos - chunkLen - 4].addr, chunkLen + 4)
# failCRC() if chunkCrc != data.readUint32(pos).swap():
failCRC()
inc(pos, 4) # CRC inc(pos, 4) # CRC
prevChunkType = chunkType prevChunkType = chunkType
@ -523,7 +525,7 @@ proc encodePng*(
result.add(0.char) result.add(0.char)
result.add(0.char) result.add(0.char)
result.add(0.char) result.add(0.char)
result.addUint32(crc32(result[result.len - 17 ..< result.len]).swap()) result.addUint32(crc32(result[result.len - 17].addr, 17).swap())
# Add IDAT # Add IDAT
# Add room for 1 byte before each row for the filter type. # Add room for 1 byte before each row for the filter type.
@ -556,14 +558,15 @@ proc encodePng*(
result.addUint32(compressed.len.uint32.swap()) result.addUint32(compressed.len.uint32.swap())
result.add("IDAT") result.add("IDAT")
result.add(compressed) result.add(compressed)
result.addUint32( result.addUint32(crc32(
crc32(result[result.len - compressed.len - 4 ..< result.len]).swap() result[result.len - compressed.len - 4].addr,
) compressed.len + 4
).swap())
# Add IEND # Add IEND
result.addUint32(0) result.addUint32(0)
result.add("IEND") result.add("IEND")
result.addUint32(crc32(result[result.len - 4 ..< result.len]).swap()) result.addUint32(crc32(result[result.len - 4].addr, 4).swap())
proc encodePng*(png: Png): string {.raises: [PixieError].} = proc encodePng*(png: Png): string {.raises: [PixieError].} =
encodePng(png.width, png.height, 4, png.data[0].addr, png.data.len * 4) encodePng(png.width, png.height, 4, png.data[0].addr, png.data.len * 4)