Home Software Engineering Methods to do RGB To Hex Conversion in Rust

Methods to do RGB To Hex Conversion in Rust

0
Methods to do RGB To Hex Conversion in Rust

[ad_1]

The problem

The rgb perform is incomplete. Full it in order that passing in RGB decimal values will lead to a hexadecimal illustration being returned. Legitimate decimal values for RGB are 0 – 255. Any values that fall out of that vary have to be rounded to the closest legitimate worth.

Notice: Your reply ought to at all times be 6 characters lengthy, the shorthand with 3 won’t work right here.

The next are examples of anticipated output values:

problem.rgb(255, 255, 255) -- returns FFFFFF
problem.rgb(255, 255, 300) -- returns FFFFFF
problem.rgb(0, 0, 0) -- returns 000000
problem.rgb(148, 0, 211) -- returns 9400D3

The answer in Rust

Possibility 1:

fn rgb(r: i32, g: i32, b: i32) -> String {
    format!(
        "{:02X}{:02X}{:02X}",
        r.clamp(0, 255),
        g.clamp(0, 255),
        b.clamp(0, 255)
    ) 
}

Possibility 2:

fn rgb(r: i32, g: i32, b: i32) -> String {
  format!("{0:02X}{1:02X}{2:02X}", r.min(255).max(0), g.min(255).max(0), b.min(255).max(0))
}

Possibility 3:

fn rgb(r: i32, g: i32, b: i32) -> String {
    let r = r.min(255).max(0);
    let g = g.min(255).max(0);
    let b = b.min(255).max(0);
    format!("{:02X}{:02X}{:02X}", r, g, b)
}

Check instances to validate our resolution

extern crate rand;
use self::rand::Rng;

fn remedy(r: i32, g: i32, b: i32) -> String {
    let clamp = |x: i32| -> i32 { if x < 0 { 0 } else { if x > 255 { 255 } else { x } } };
    format!("{:02X}{:02X}{:02X}", clamp(r), clamp(g), clamp(b))
}
macro_rules! examine {
  ( $obtained : expr, $anticipated : expr ) => {
    if $obtained != $anticipated { panic!("Obtained: {}nExpected: {}n", $obtained, $anticipated); }
  };
}

#[cfg(test)]
mod assessments {
    use self::tremendous::*;

    #[test]
    fn basic_tests() {
        examine!(rgb(0, 0, 0), "000000");
        examine!(rgb(1, 2, 3), "010203");
        examine!(rgb(255, 255, 255), "FFFFFF");
        examine!(rgb(254, 253, 252), "FEFDFC");
        examine!(rgb(-20, 275, 125), "00FF7D");
    }
    
    #[test]
    fn random_tests() {
        for _ in 0..50 {
            let r = rand::thread_rng().gen_range(-32..288);
            let g = rand::thread_rng().gen_range(-32..288);
            let b = rand::thread_rng().gen_range(-32..288);
            examine!(rgb(r, g, b), remedy(r, g, b));
        }
    }
}

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here