mirror of
https://github.com/ratatui-org/ratatui
synced 2025-02-16 22:18:51 +00:00
feat(color): add Color::from_u32 constructor (#785)
Convert a u32 in the format 0x00RRGGBB to a Color. ```rust let white = Color::from_u32(0x00FFFFFF); let black = Color::from_u32(0x00000000); ```
This commit is contained in:
parent
34648941d4
commit
ffd5fc79fc
1 changed files with 21 additions and 0 deletions
|
@ -127,6 +127,18 @@ pub enum Color {
|
|||
Indexed(u8),
|
||||
}
|
||||
|
||||
impl Color {
|
||||
/// Convert a u32 to a Color
|
||||
///
|
||||
/// The u32 should be in the format 0x00RRGGBB.
|
||||
pub const fn from_u32(u: u32) -> Color {
|
||||
let r = (u >> 16) as u8;
|
||||
let g = (u >> 8) as u8;
|
||||
let b = u as u8;
|
||||
Color::Rgb(r, g, b)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de> serde::Deserialize<'de> for Color {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
|
@ -270,6 +282,15 @@ mod tests {
|
|||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn from_u32() {
|
||||
assert_eq!(Color::from_u32(0x000000), Color::Rgb(0, 0, 0));
|
||||
assert_eq!(Color::from_u32(0xFF0000), Color::Rgb(255, 0, 0));
|
||||
assert_eq!(Color::from_u32(0x00FF00), Color::Rgb(0, 255, 0));
|
||||
assert_eq!(Color::from_u32(0x0000FF), Color::Rgb(0, 0, 255));
|
||||
assert_eq!(Color::from_u32(0xFFFFFF), Color::Rgb(255, 255, 255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_rgb_color() {
|
||||
let color: Color = Color::from_str("#FF0000").unwrap();
|
||||
|
|
Loading…
Add table
Reference in a new issue