Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding const fn with_a8() to Color #525

Merged
merged 5 commits into from
Jul 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion piet/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,36 @@ impl Color {
Color::from_rgba32_u32((self.as_rgba_u32() & !0xff) | a)
}

/// Change just the red value of a color.
///
/// The `r` value represents red as a `u8` from 0 to 255.
pub const fn with_r8(self, r: u8) -> Color {
Color::from_rgba32_u32((self.as_rgba_u32() & !0xff000000) | (r as u32) << 24)
}

/// Change just the green value of a color.
///
/// The `g` value represents green as a `u8` from 0 to 255.
pub const fn with_g8(self, g: u8) -> Color {
Color::from_rgba32_u32((self.as_rgba_u32() & !0xff0000) | (g as u32) << 16)
}

/// Change just the blue value of a color.
///
/// The `b` value represents blue as a `u8` from 0 to 255.
pub const fn with_b8(self, b: u8) -> Color {
Color::from_rgba32_u32((self.as_rgba_u32() & !0xff00) | (b as u32) << 8)
}

/// Change just the alpha value of a color.
///
/// The `a` value represents alpha as a `u8` from 0 to 255.
pub const fn with_a8(self, a: u8) -> Color {
Color::from_rgba32_u32((self.as_rgba_u32() & !0xff) | a as u32)
}

/// Convert a color value to a 32-bit rgba value.
pub fn as_rgba_u32(self) -> u32 {
pub const fn as_rgba_u32(self) -> u32 {
match self {
Color::Rgba32(rgba) => rgba,
}
Expand Down Expand Up @@ -355,4 +383,14 @@ mod tests {
assert!(Color::from_hex_str("x0f").is_err());
assert!(Color::from_hex_str("#0afa1").is_err());
}

#[test]
fn change_subcolor_values() {
let color = Color::from_rgba32_u32(0x11aa22bb);

assert_eq!(color.with_r8(0xff), Color::from_rgba32_u32(0xffaa22bb));
assert_eq!(color.with_g8(0xff), Color::from_rgba32_u32(0x11ff22bb));
assert_eq!(color.with_b8(0xff), Color::from_rgba32_u32(0x11aaffbb));
assert_eq!(color.with_a8(0xff), Color::from_rgba32_u32(0x11aa22ff));
}
}
Loading