//! Functions for blending together sRGB colors. These functions use the
//! conversion functions in [`convert`][crate::convert], but do not support
//! transparent backgrounds.

use crate::convert::{srgb8_to_rgb12, rgb12_to_srgb8_unchecked};

#[inline]
pub fn blend_srgb8_channel(bg: u8, fg: u8, alpha: u8) -> u8 {
	let bg_portion = srgb8_to_rgb12(bg) as u32 * (255 - alpha as u32);
	let fg_portion = srgb8_to_rgb12(fg) as u32 * alpha as u32;
	let rgb12 = ((bg_portion + fg_portion) / 255) as u16;

	// SAFETY: as the average of two 12-bit values, rgb12 cannot be over 4095
	unsafe { rgb12_to_srgb8_unchecked(rgb12) }
}

#[inline]
pub fn blend_srgb8(bg: (u8, u8, u8), fg: (u8, u8, u8), alpha: u8) -> (u8, u8, u8) {
	match alpha {
		0 => bg,
		255 => fg,

		_ => (
			blend_srgb8_channel(bg.0, fg.0, alpha),
			blend_srgb8_channel(bg.1, fg.1, alpha),
			blend_srgb8_channel(bg.2, fg.2, alpha)
		)
	}
}
