//! QuickDraw PICT R5G5B5 `PixMap`s.

use crate::{bin::{check_data, u16b}, err::*, image::{*, pict::{pm, rle}}};

/// Reads a R5G5B5 `PixMap`.
pub fn read(mut im: Image8,
            b: &[u8],
            hdr: pm::head::Header) -> ResultS<Image8>
{
	let mut p = 0;

	if hdr.pitch < 8 || hdr.pack_t == pm::head::PackType::None {
		// uncompressed R5G5B5
		for _ in 0..im.h() {
			for _ in 0..im.w() {
				let cr = u16b(&b[p..]);

				im.cr.push(r5g5b5_to_rgb8(cr));
				p += 2;
			}
		}

		Ok(im)
	} else if hdr.rle {
		// RLE compressed R5G5B5
		for _ in 0..im.h() {
			let (d, pp) = rle::read::<u16>(&b[p..], hdr.pitch)?;

			check_data(&d, im.w())?;

			p += pp;

			for &cr in &d {
				im.cr.push(r5g5b5_to_rgb8(cr));
			}
		}

		Ok(im)
	} else {
		bail!("invalid configuration")
	}
}

// EOF
