//! QuickDraw PICT color lookup tables.

use crate::{err::*, image::*};

/// Read a `ColorTable` structure.
pub fn read(b: &[u8]) -> ResultS<(Vec<Color8>, usize)>
{
	read_data! {
		endian: BIG, buf: b, size: 8, start: 0, data {
			let dev = u16[4];
			let num = u16[6] usize;
		}
	}

	let dev = dev & 0x8000 != 0;
	let num = num + 1;

	let mut p = 8;
	let mut clut = vec![Color8::new(0, 0, 0); num];

	for i in 0..num {
		read_data! {
			endian: BIG, buf: b, size: 8, start: p, data {
				let n = u16[0] usize;
				let r = u8[2];
				let g = u8[4];
				let b = u8[6];
			}
		}

		// with device mapping, we ignore the index entirely
		let n = if dev {i} else {n};

		*ok!(clut.get_mut(n), "invalid index")? = Color8::new(r, g, b);

		p += 8;
	}

	Ok((clut, p))
}

// EOF
