Ogeon / palette

A Rust library for linear color calculations and conversion
Apache License 2.0
748 stars 60 forks source link

Add `saturating_add`/`saturating_sub` to integer colors #322

Closed Finomnis closed 1 year ago

Finomnis commented 1 year ago

Description

Add two functions that make it easier to blend color:

Motivation

The behavior of Add/AddAssign is equal to that of integers - they can overflow, which creates a panic in debug mode.

Like this:

use palette::Srgb;

fn main() {
    let color1 = Srgb::<u8>::new(200, 20, 20);
    let color2 = Srgb::<u8>::new(100, 10, 10);

    let color_sum = color1 + color2;
    println!("{:?}", color_sum);
}
thread 'main' panicked at 'attempt to add with overflow', /rustc/9eb3afe9ebe9c7d2b84b71002d44f4a0edac95e0\library\core\src\ops\arith.rs:110:1

So the feature I would find useful, which does exist for integers, is saturating_add/saturating_sub. This would make it much easier to blend integer colors.

use palette::Srgb;

fn main() {
    let color1 = Srgb::<u8>::new(200, 20, 20);
    let color2 = Srgb::<u8>::new(100, 10, 10);

    let color_sum = color1.saturating_add(color2);

    // Desired output: Srgb{255,30,30}
    println!("{:?}", color_sum);
}