Created
February 8, 2024 15:26
-
-
Save fancellu/de2a286fa8ab738565a2ed392da05b34 to your computer and use it in GitHub Desktop.
Rust conversion of hex rgb strings to their components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use crate::RGBError::WrongLength; | |
use std::num::ParseIntError; | |
use std::str::FromStr; | |
#[derive(Debug)] | |
struct RGB { | |
red: u8, | |
green: u8, | |
blue: u8, | |
} | |
#[derive(Debug)] | |
enum RGBError { | |
WrongDigits, | |
WrongLength, | |
} | |
impl From<ParseIntError> for RGBError { | |
fn from(_: ParseIntError) -> Self { | |
RGBError::WrongDigits | |
} | |
} | |
impl FromStr for RGB { | |
type Err = RGBError; | |
fn from_str(s: &str) -> Result<Self, Self::Err> { | |
let ignore_hash = s.strip_prefix('#').unwrap_or(s); | |
if ignore_hash.len() != 6 { | |
return Err(WrongLength); | |
} | |
let hex_byte = u32::from_str_radix(ignore_hash, 16)?; | |
let red: u8 = (hex_byte >> 16) as u8; | |
let green: u8 = (hex_byte >> 8) as u8; | |
let blue: u8 = hex_byte as u8; | |
Ok(RGB { red, green, blue }) | |
} | |
} | |
fn main() { | |
// Directly | |
let rgb = RGB::from_str("FFFFFF").unwrap(); | |
println!("Red: {}, Green: {}, Blue: {}", rgb.red, rgb.green, rgb.blue); | |
// Via parse | |
let rgb: RGB = ("#010203").parse().unwrap(); | |
println!("Red: {}, Green: {}, Blue: {}", rgb.red, rgb.green, rgb.blue); | |
let rgb = RGB::from_str("toolong"); | |
println!("{:?}", rgb); | |
let rgb = RGB::from_str("01020z"); | |
println!("{:?}", rgb); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
Red: 255, Green: 255, Blue: 255
Red: 1, Green: 2, Blue: 3
Err(WrongLength)
Err(WrongDigits)