699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
|
# File 'lib/tessel.rb', line 699
def decode(bytes, max_pixels: 16384 * 16384)
bytes = String(bytes).b
magic = bytes.byteslice(0, 2)
raise DecodeError, "invalid PPM" unless %w[P3 P6].include?(magic)
cursor = 2
token = lambda do
loop do
cursor += 1 while cursor < bytes.bytesize && bytes.getbyte(cursor).chr.match?(/\s/)
if bytes.getbyte(cursor) == 35
cursor += 1
cursor += 1 while cursor < bytes.bytesize && bytes.getbyte(cursor) != 10
else
break
end
end
start = cursor
cursor += 1 while cursor < bytes.bytesize && !bytes.getbyte(cursor).chr.match?(/\s/)
value = bytes.byteslice(start, cursor - start)
raise DecodeError, "truncated PPM" if value.nil? || value.empty?
raise DecodeError, "invalid PPM number" unless value.match?(/\A\d+\z/)
value.to_i
end
width, height, max = 3.times.map { token.call }
raise DecodeError, "invalid PPM dimensions" unless width.positive? && height.positive? && max.between?(1, 65_535)
raise LimitError, "image exceeds pixel limit" if width * height > max_pixels
raise DecodeError, "truncated PPM header" if cursor >= bytes.bytesize
cursor += bytes.byteslice(cursor, 2) == "\r\n" ? 2 : 1
values = if magic == "P6"
body = bytes.byteslice(cursor..)
expected = width * height * 3 * (max < 256 ? 1 : 2)
raise DecodeError, "invalid PPM pixel data length" unless body.bytesize == expected
max < 256 ? body.bytes : body.unpack("n*")
else
cursor -= 1
samples = Array.new(width * height * 3) { token.call }
tail = bytes.byteslice(cursor..)
raise DecodeError, "extra PPM samples" unless tail.match?(/\A(?:\s+|\#[^\n]*(?:\n|\z))*\z/)
samples
end
raise DecodeError, "PPM sample exceeds maximum" if values.any? { |value| value > max }
if max != 255
values.map! { |value| (value * 255.0 / max).round }
end
rgba = values.each_slice(3).flat_map { |r, g, b| [r, g, b, 255] }.pack("C*")
Image.from_rgba(width, height, rgba)
rescue StandardError => e
raise e if e.is_a?(DecodeError) || e.is_a?(LimitError)
raise DecodeError, "invalid PPM: #{e.message}"
end
|