Решение на CSS Цветове от Теодор Кирилов

Обратно към всички решения

Към профила на Теодор Кирилов

Резултати

  • 20 точки от тестове
  • 0 бонус точки
  • 20 точки общо
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)

Код

pub enum Color {
RGB {
red: u8,
green: u8,
blue: u8
},
HSV {
hue: u16,
saturation: u8,
value: u8,
}
}
impl Color {
/// Конструира нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {
let rgb=Color::RGB{ red:red, green:green, blue:blue };
rgb
}
/// Конструира нова стойност от вариант `HSV` с дадените стойности.
///
/// В случай, че hue е над 360 или saturation или value са над 100, очакваме да `panic!`-нете с
/// каквото съобщение си изберете.
///
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
//Тук декларираме 3 константи, обозначаващи максималните стойности, които може да са hue, saturation и value,
//за да избегнем магически числа при проверката. Все пак са лоша практика :)
const MAX_HUE_VALUE: u16 =360;
const MAX_SATURATION_VALUE: u8=100;
const MAX_VALUE_VALUE: u8=100;
if hue > MAX_HUE_VALUE || saturation > MAX_SATURATION_VALUE || value > MAX_VALUE_VALUE {
panic!("Invalid value for hue or saturation or value! Max value for hue is 360, for saturation and value is 100");
}
else {
let hsv: Color=Color::HSV{ hue:hue, saturation:saturation, value:value };
hsv
}
}
}
impl Color {
/// Ако `self` е `RGB`, тогава връщате неговите `red`, `green`, `blue` компоненти в този ред.
/// Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_rgb(&self) -> (u8, u8, u8) {
match self{
Color::RGB{red, green, blue}=>(*red,*green,*blue),
_ =>panic!("Expected RGB, not HSV!"),
}
}
/// Ако `self` е `HSV`, тогава връщате неговите `hue`, `saturation`, `value` компоненти в този
/// ред. Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_hsv(&self) -> (u16, u8, u8) {
match self{
Color::HSV { hue, saturation, value } => (*hue,*saturation,*value),
_ => panic!("Expected HSV! "),
}
}
}
impl Color {
/// В случай, че варианта на `self` е `RGB`, очакваме низ със съдържание `#rrggbb`, където
/// червения, зеления и синия компонент са форматирани в шестнадесетична система, и всеки от тях е
/// точно два символа с малки букви (запълнени с нули).
///
/// Ако варианта е `HSV`, очакваме низ `hsv(h,s%,v%)`, където числата са си напечатани в
/// десетичната система, без водещи нули, без интервали след запетаите, вторите две завършващи на
/// `%`.
///
pub fn to_string(&self) -> String {
match self{
Color::RGB{red,green, blue} => {
let mut rgb_string = String::from("#");
rgb_string.push_str(&decimal_to_hex(*red as u16));
rgb_string.push_str(&decimal_to_hex(*green as u16));
rgb_string.push_str(&decimal_to_hex(*blue as u16));
rgb_string
}
Color::HSV { hue, saturation, value } => {
let mut hsv_string = String::from("hsv(");
hsv_string.push_str(&hue.to_string());
hsv_string.push_str(",");
hsv_string.push_str(&saturation.to_string());
hsv_string.push_str("%,");
hsv_string.push_str(&value.to_string());
hsv_string.push_str("%)");
hsv_string
}
}
}
}
impl Color {
/// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
pub fn invert(&self) -> Self {
const MAX_HUE_VALUE: u16 =360;
const MAX_SATURATION_VALUE: u8=100;
const MAX_VALUE_VALUE: u8=100;
const MAX_RGB_VALUE: u8 =255;
match self{
Color::HSV { hue, saturation, value } => {
let inverted_hue=MAX_HUE_VALUE-hue;
let inverted_saturation=MAX_SATURATION_VALUE-saturation;
let inverted_value=MAX_VALUE_VALUE-value;
let inverted_hsv: Color=Color::HSV{ hue:inverted_hue, saturation:inverted_saturation, value:inverted_value };
inverted_hsv
}
Color::RGB { red, green, blue } => {
let inverted_red=MAX_RGB_VALUE-red;
let inverted_greed=MAX_RGB_VALUE-green;
let inverted_blue=MAX_RGB_VALUE-blue;
let inverted_rgb:Color=Color::RGB { red:inverted_red, green: inverted_greed, blue: inverted_blue };
inverted_rgb
}
}
}
}
//Функция която да превръща число от десетична в шестнайсетична бройна система и го връща във фромата #xx
//(демек е пригудена да работи за new_rgb() функцията)
pub fn decimal_to_hex(number:u16) -> String
{
let mut result=String::from("");
if number== 0{
result.push_str("00");
return result
}
let mut temp:u16;
let mut num=number;
let mut counter=0; //Малко нагласена поправка за проблема, когато числото се преобразува до едноцифрено/еднобуквано в hex и трябва да добавим водеща нула, за да запазим формата.
while num!=0
{
temp=num%16;
counter=counter+1;
match temp{
0|1|2|3|4|5|6|7|8|9 => {
result.push_str(&temp.to_string());
}
10 => result.push_str("a"),
11 => result.push_str("b"),
12 => result.push_str("c"),
13 => result.push_str("d"),
14 => result.push_str("e"),
15 => result.push_str("f"),
_ => panic!("Something went wrong"),

Има и по-прост начин да форматираш шестнадесетични числа -- можеш да видиш моето решение примерно. Не е проблем да си напишеш собствено решение, разбира се.

}
num=num/16;
}
//прилагане на фалшивата поправка :Д
//добавяма тази нула, за да можем да запазим формата #00, примерно когато числото е 1 да е 01, а не само 1
//също така добавянето на тази "0" е след добавянето на самото число, защото при обръщането на числото в правилният ред ще застане на грешно място
if counter==1{
result.push_str("0");
}
//обръщаме разултата, за да е правилно изписано числото в шестнайсетична бройна система.
result.chars().rev().collect::<String>()
}
//tests the unwrap_rgb() and unwrap_hsv functions
#[test]
fn my_test1() {
let color1 = Color::new_rgb(10, 20, 30);
assert_eq!(color1.unwrap_rgb().0, 10);
assert_eq!(color1.unwrap_rgb().1, 20);
assert_eq!(color1.unwrap_rgb().2, 30);
let color2 = Color::new_rgb(255, 1, 0);
assert_eq!(color2.unwrap_rgb(), (255,1,0));
let color3 = Color::new_hsv(5, 10, 15);
assert_eq!(color3.unwrap_hsv().0, 5);
assert_eq!(color3.unwrap_hsv().1, 10);
assert_eq!(color3.unwrap_hsv().2, 15);
let color4 = Color::new_hsv(360, 100, 100);
assert_eq!(color4.unwrap_hsv(),(360,100,100));
}
//testing if it panics when we exceed the maximum value for hue, saturation or value
#[test]
#[should_panic]
fn my_test2_1() {
let _color1 = Color::new_hsv(5, 10, 101);
}
#[test]
#[should_panic]
fn my_test2_2() {
let _color1 = Color::new_hsv(361, 10, 1);
}
#[test]
#[should_panic]
fn my_test2_3() {
let _color1 = Color::new_hsv(44, 101, 1);
}
//testing the to_strong function for HSV
#[test]
fn my_test3() {
let color1 = Color::new_hsv(0, 0, 0);
assert_eq!(color1.to_string(), "hsv(0,0%,0%)");
let color2 = Color::new_hsv(360, 100, 100);
assert_eq!(color2.to_string(), "hsv(360,100%,100%)");
let color3 = Color::new_hsv(0, 10, 100);
assert_eq!(color3.to_string(), "hsv(0,10%,100%)");
let color4 = Color::new_hsv(1, 1, 1);
assert_eq!(color4.to_string(), "hsv(1,1%,1%)");
}
//testing the to_string() function for RGB
#[test]
fn my_test4() {
let color1 = Color::new_rgb(255, 1, 255);
assert_eq!(&color1.to_string()[0..7], "#ff01ff");
let color2 = Color::new_rgb(16, 16, 16);
assert_eq!(&color2.to_string()[0..7], "#101010");
let color3 = Color::new_rgb(1, 0, 16);
assert_eq!(&color3.to_string()[0..7], "#010010");
let color4 = Color::new_rgb(0, 0, 0);
assert_eq!(&color4.to_string()[0..7], "#000000");
let color5 = Color::new_rgb(11, 1, 1);
assert_eq!(&color5.to_string()[0..7], "#0b0101");
let color6 = Color::new_rgb(123, 5, 255);
assert_eq!(&color6.to_string()[0..7], "#7b05ff");
}
//testing the invert() function for RGB
#[test]
fn my_test5(){
let color1 = Color::new_rgb(0, 0, 0);
assert_eq!(color1.invert().unwrap_rgb(), (255,255,255));
let color2 = Color::new_rgb(255, 255, 255);
assert_eq!(color2.invert().unwrap_rgb(), (0,0,0));
let color3 = Color::new_rgb(127, 1, 254);
assert_eq!(color3.invert().unwrap_rgb(), (128,254,1));
}
//testing the invert() funtion for HSV
#[test]
fn my_test6(){
let color1 = Color::new_hsv(0, 0, 0);
assert_eq!(color1.invert().unwrap_hsv(), (360,100,100));
let color2 = Color::new_hsv(360, 100, 100);
assert_eq!(color2.invert().unwrap_hsv(), (0,0,0));
let color3 = Color::new_hsv(180, 50, 50);
assert_eq!(color3.invert().unwrap_hsv(), (180,50,50));
}

Лог от изпълнението

Compiling solution v0.1.0 (/tmp/d20230111-3772066-87afg3/solution)
    Finished test [unoptimized + debuginfo] target(s) in 0.74s
     Running tests/solution_test.rs (target/debug/deps/solution_test-0edbea2040daef01)

running 5 tests
test solution_test::test_invert_hsv ... ok
test solution_test::test_hsv_display ... ok
test solution_test::test_invert_rgb ... ok
test solution_test::test_rgb_display ... ok
test solution_test::test_new_hsv ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

История (3 версии и 3 коментара)

Теодор качи първо решение на 26.10.2022 22:35 (преди почти 3 години)

Теодор качи решение на 27.10.2022 12:22 (преди почти 3 години)

pub enum Color {
RGB {
red: u8,
green: u8,
blue: u8
},
HSV {
hue: u16,
saturation: u8,
value: u8,
}
}
impl Color {
/// Конструира нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {
let rgb=Color::RGB{ red:red, green:green, blue:blue };
rgb
}
/// Конструира нова стойност от вариант `HSV` с дадените стойности.
///
/// В случай, че hue е над 360 или saturation или value са над 100, очакваме да `panic!`-нете с
/// каквото съобщение си изберете.
///
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
//Тук декларираме 3 константи, обозначаващи максималните стойности, които може да са hue, saturation и value,
//за да избегнем магически числа при проверката. Все пак са лоша практика :)
const MAX_HUE_VALUE: u16 =360;
const MAX_SATURATION_VALUE: u8=100;
const MAX_VALUE_VALUE: u8=100;
if hue > MAX_HUE_VALUE || saturation > MAX_SATURATION_VALUE || value > MAX_VALUE_VALUE {
panic!("Invalid value for hue or saturation or value! Max value for hue is 360, for saturation and value is 100");
}
else {
let hsv: Color=Color::HSV{ hue:hue, saturation:saturation, value:value };
hsv
}
}
}
impl Color {
/// Ако `self` е `RGB`, тогава връщате неговите `red`, `green`, `blue` компоненти в този ред.
/// Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_rgb(&self) -> (u8, u8, u8) {
match self{
Color::RGB{red, green, blue}=>(*red,*green,*blue),
_ =>panic!("Expected RGB, not HSV!"),
}
}
/// Ако `self` е `HSV`, тогава връщате неговите `hue`, `saturation`, `value` компоненти в този
/// ред. Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_hsv(&self) -> (u16, u8, u8) {
match self{
Color::HSV { hue, saturation, value } => (*hue,*saturation,*value),
_ => panic!("Expected HSV! "),
}
}
}
impl Color {
/// В случай, че варианта на `self` е `RGB`, очакваме низ със съдържание `#rrggbb`, където
/// червения, зеления и синия компонент са форматирани в шестнадесетична система, и всеки от тях е
/// точно два символа с малки букви (запълнени с нули).
///
/// Ако варианта е `HSV`, очакваме низ `hsv(h,s%,v%)`, където числата са си напечатани в
/// десетичната система, без водещи нули, без интервали след запетаите, вторите две завършващи на
/// `%`.
///
pub fn to_string(&self) -> String {
match self{
Color::RGB{red,green, blue} => {
let mut rgb_string = String::from("#");
rgb_string.push_str(&decimal_to_hex(*red as u16));
rgb_string.push_str(&decimal_to_hex(*green as u16));
rgb_string.push_str(&decimal_to_hex(*blue as u16));
rgb_string
}
Color::HSV { hue, saturation, value } => {
let mut hsv_string = String::from("hsv(");
hsv_string.push_str(&hue.to_string());
hsv_string.push_str(",");
hsv_string.push_str(&saturation.to_string());
hsv_string.push_str("%,");
hsv_string.push_str(&value.to_string());
hsv_string.push_str("%)");
hsv_string
}
}
}
}
impl Color {
/// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
pub fn invert(&self) -> Self {
const MAX_HUE_VALUE: u16 =360;
const MAX_SATURATION_VALUE: u8=100;
const MAX_VALUE_VALUE: u8=100;
const MAX_RGB_VALUE: u8 =255;
match self{
Color::HSV { hue, saturation, value } => {
let inverted_hue=MAX_HUE_VALUE-hue;
let inverted_saturation=MAX_SATURATION_VALUE-saturation;
let inverted_value=MAX_VALUE_VALUE-value;
let inverted_hsv: Color=Color::HSV{ hue:inverted_hue, saturation:inverted_saturation, value:inverted_value };
inverted_hsv
}
Color::RGB { red, green, blue } => {
let inverted_red=MAX_RGB_VALUE-red;
let inverted_greed=MAX_RGB_VALUE-green;
let inverted_blue=MAX_RGB_VALUE-blue;
let inverted_rgb:Color=Color::RGB { red:inverted_red, green: inverted_greed, blue: inverted_blue };
inverted_rgb
}
}
}
}
//Функция която да превръща число от десетична в шестнайсетична бройна система и го връща във фромата #xx
//(демек е пригудена да работи за new_rgb() функцията)
pub fn decimal_to_hex(number:u16) -> String
{
let mut result=String::from("");
if number== 0{
result.push_str("00");
return result
}
let mut temp:u16;
let mut num=number;
let mut counter=0; //Малко нагласена поправка за проблема, когато числото се преобразува до едноцифрено/еднобуквано в hex и трябва да добавим водеща нула, за да запазим формата.
while num!=0
{
temp=num%16;
counter=counter+1;
match temp{
0|1|2|3|4|5|6|7|8|9 => {
result.push_str(&temp.to_string());
}
10 => result.push_str("a"),
11 => result.push_str("b"),
12 => result.push_str("c"),
13 => result.push_str("d"),
14 => result.push_str("e"),
15 => result.push_str("f"),
_ => panic!("Something went wrong"),
}
num=num/16;
}
//прилагане на фалшивата поправка :Д
//добавяма тази нула, за да можем да запазим формата #00, примерно когато числото е 1 да е 01, а не само 1
//също така добавянето на тази "0" е след добавянето на самото число, защото при обръщането на числото в правилният ред ще застане на грешно място
if counter==1{
result.push_str("0");
}
//обръщаме разултата, за да е правилно изписано числото в шестнайсетична бройна система.
result.chars().rev().collect::<String>()
+}
+
+//tests the unwrap_rgb() and unwrap_hsv functions
+#[test]
+fn my_test1() {
+ let color1 = Color::new_rgb(10, 20, 30);
+ assert_eq!(color1.unwrap_rgb().0, 10);
+ assert_eq!(color1.unwrap_rgb().1, 20);
+ assert_eq!(color1.unwrap_rgb().2, 30);
+
+ let color2 = Color::new_rgb(255, 1, 0);
+ assert_eq!(color2.unwrap_rgb(), (255,1,0));
+
+
+ let color3 = Color::new_hsv(5, 10, 15);
+ assert_eq!(color3.unwrap_hsv().0, 5);
+ assert_eq!(color3.unwrap_hsv().1, 10);
+ assert_eq!(color3.unwrap_hsv().2, 15);
+
+ let color4 = Color::new_hsv(360, 100, 100);
+ assert_eq!(color4.unwrap_hsv(),(360,100,100));
+
+}
+
+//testing if it panics when we exceed the maximum value for hue, saturation or value
+#[test]
+#[should_panic]
+fn my_test2_1() {
+
+ let _color1 = Color::new_hsv(5, 10, 101);
+}
+#[test]
+#[should_panic]
+fn my_test2_2() {
+
+ let _color1 = Color::new_hsv(361, 10, 1);
+}
+#[test]
+#[should_panic]
+fn my_test2_3() {
+
+ let _color1 = Color::new_hsv(44, 101, 1);
+}
+
+//testing the to_strong function for HSV
+#[test]
+fn my_test3() {
+
+ let color1 = Color::new_hsv(0, 0, 0);
+ assert_eq!(color1.to_string(), "hsv(0,0%,0%)");
+
+ let color2 = Color::new_hsv(360, 100, 100);
+ assert_eq!(color2.to_string(), "hsv(360,100%,100%)");
+
+ let color3 = Color::new_hsv(0, 10, 100);
+ assert_eq!(color3.to_string(), "hsv(0,10%,100%)");
+
+ let color4 = Color::new_hsv(1, 1, 1);
+ assert_eq!(color4.to_string(), "hsv(1,1%,1%)");
+}
+
+//testing the to_string() function for RGB
+#[test]
+fn my_test4() {
+
+ let color1 = Color::new_rgb(255, 1, 255);
+ assert_eq!(&color1.to_string()[0..7], "#ff01ff");
+
+ let color2 = Color::new_rgb(16, 16, 16);
+ assert_eq!(&color2.to_string()[0..7], "#101010");
+
+ let color3 = Color::new_rgb(1, 0, 16);
+ assert_eq!(&color3.to_string()[0..7], "#010010");
+
+ let color4 = Color::new_rgb(0, 0, 0);
+ assert_eq!(&color4.to_string()[0..7], "#000000");
+
+ let color5 = Color::new_rgb(11, 1, 1);
+ assert_eq!(&color5.to_string()[0..7], "#0b0101");
+
+ let color5 = Color::new_rgb(123, 5, 255);
+ assert_eq!(&color5.to_string()[0..7], "#7b05ff");
+}
+
+//testing the invert() function for RGB
+#[test]
+fn my_test5(){
+
+ let color1 = Color::new_rgb(0, 0, 0);
+ assert_eq!(color1.invert().unwrap_rgb(), (255,255,255));
+
+ let color2 = Color::new_rgb(255, 255, 255);
+ assert_eq!(color2.invert().unwrap_rgb(), (0,0,0));
+
+ let color3 = Color::new_rgb(127, 1, 254);
+ assert_eq!(color3.invert().unwrap_rgb(), (128,254,1));
+
+}
+
+//testing the invert() funtion for HSV
+#[test]
+fn my_test6(){
+
+ let color1 = Color::new_hsv(0, 0, 0);
+ assert_eq!(color1.invert().unwrap_hsv(), (360,100,100));
+
+ let color2 = Color::new_hsv(360, 100, 100);
+ assert_eq!(color2.invert().unwrap_hsv(), (0,0,0));
+
+ let color3 = Color::new_hsv(180, 50, 50);
+ assert_eq!(color3.invert().unwrap_hsv(), (180,50,50));
}

Теодор качи решение на 27.10.2022 12:25 (преди почти 3 години)

pub enum Color {
RGB {
red: u8,
green: u8,
blue: u8
},
HSV {
hue: u16,
saturation: u8,
value: u8,
}
}
impl Color {
/// Конструира нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {
let rgb=Color::RGB{ red:red, green:green, blue:blue };
rgb
}
/// Конструира нова стойност от вариант `HSV` с дадените стойности.
///
/// В случай, че hue е над 360 или saturation или value са над 100, очакваме да `panic!`-нете с
/// каквото съобщение си изберете.
///
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
//Тук декларираме 3 константи, обозначаващи максималните стойности, които може да са hue, saturation и value,
//за да избегнем магически числа при проверката. Все пак са лоша практика :)
const MAX_HUE_VALUE: u16 =360;
const MAX_SATURATION_VALUE: u8=100;
const MAX_VALUE_VALUE: u8=100;
if hue > MAX_HUE_VALUE || saturation > MAX_SATURATION_VALUE || value > MAX_VALUE_VALUE {
panic!("Invalid value for hue or saturation or value! Max value for hue is 360, for saturation and value is 100");
}
else {
let hsv: Color=Color::HSV{ hue:hue, saturation:saturation, value:value };
hsv
}
}
}
impl Color {
/// Ако `self` е `RGB`, тогава връщате неговите `red`, `green`, `blue` компоненти в този ред.
/// Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_rgb(&self) -> (u8, u8, u8) {
match self{
Color::RGB{red, green, blue}=>(*red,*green,*blue),
_ =>panic!("Expected RGB, not HSV!"),
}
}
/// Ако `self` е `HSV`, тогава връщате неговите `hue`, `saturation`, `value` компоненти в този
/// ред. Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_hsv(&self) -> (u16, u8, u8) {
match self{
Color::HSV { hue, saturation, value } => (*hue,*saturation,*value),
_ => panic!("Expected HSV! "),
}
}
}
impl Color {
/// В случай, че варианта на `self` е `RGB`, очакваме низ със съдържание `#rrggbb`, където
/// червения, зеления и синия компонент са форматирани в шестнадесетична система, и всеки от тях е
/// точно два символа с малки букви (запълнени с нули).
///
/// Ако варианта е `HSV`, очакваме низ `hsv(h,s%,v%)`, където числата са си напечатани в
/// десетичната система, без водещи нули, без интервали след запетаите, вторите две завършващи на
/// `%`.
///
pub fn to_string(&self) -> String {
match self{
Color::RGB{red,green, blue} => {
let mut rgb_string = String::from("#");
rgb_string.push_str(&decimal_to_hex(*red as u16));
rgb_string.push_str(&decimal_to_hex(*green as u16));
rgb_string.push_str(&decimal_to_hex(*blue as u16));
rgb_string
}
Color::HSV { hue, saturation, value } => {
let mut hsv_string = String::from("hsv(");
hsv_string.push_str(&hue.to_string());
hsv_string.push_str(",");
hsv_string.push_str(&saturation.to_string());
hsv_string.push_str("%,");
hsv_string.push_str(&value.to_string());
hsv_string.push_str("%)");
hsv_string
}
}
}
}
impl Color {
/// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
pub fn invert(&self) -> Self {
const MAX_HUE_VALUE: u16 =360;
const MAX_SATURATION_VALUE: u8=100;
const MAX_VALUE_VALUE: u8=100;
const MAX_RGB_VALUE: u8 =255;
match self{
Color::HSV { hue, saturation, value } => {
let inverted_hue=MAX_HUE_VALUE-hue;
let inverted_saturation=MAX_SATURATION_VALUE-saturation;
let inverted_value=MAX_VALUE_VALUE-value;
let inverted_hsv: Color=Color::HSV{ hue:inverted_hue, saturation:inverted_saturation, value:inverted_value };
inverted_hsv
}
Color::RGB { red, green, blue } => {
let inverted_red=MAX_RGB_VALUE-red;
let inverted_greed=MAX_RGB_VALUE-green;
let inverted_blue=MAX_RGB_VALUE-blue;
let inverted_rgb:Color=Color::RGB { red:inverted_red, green: inverted_greed, blue: inverted_blue };
inverted_rgb
}
}
}
}
//Функция която да превръща число от десетична в шестнайсетична бройна система и го връща във фромата #xx
//(демек е пригудена да работи за new_rgb() функцията)
pub fn decimal_to_hex(number:u16) -> String
{
let mut result=String::from("");
if number== 0{
result.push_str("00");
return result
}
let mut temp:u16;
let mut num=number;
let mut counter=0; //Малко нагласена поправка за проблема, когато числото се преобразува до едноцифрено/еднобуквано в hex и трябва да добавим водеща нула, за да запазим формата.
while num!=0
{
temp=num%16;
counter=counter+1;
match temp{
0|1|2|3|4|5|6|7|8|9 => {
result.push_str(&temp.to_string());
}
10 => result.push_str("a"),
11 => result.push_str("b"),
12 => result.push_str("c"),
13 => result.push_str("d"),
14 => result.push_str("e"),
15 => result.push_str("f"),
_ => panic!("Something went wrong"),

Има и по-прост начин да форматираш шестнадесетични числа -- можеш да видиш моето решение примерно. Не е проблем да си напишеш собствено решение, разбира се.

}
num=num/16;
}
//прилагане на фалшивата поправка :Д
//добавяма тази нула, за да можем да запазим формата #00, примерно когато числото е 1 да е 01, а не само 1
//също така добавянето на тази "0" е след добавянето на самото число, защото при обръщането на числото в правилният ред ще застане на грешно място
if counter==1{
result.push_str("0");
}
//обръщаме разултата, за да е правилно изписано числото в шестнайсетична бройна система.
result.chars().rev().collect::<String>()
}
//tests the unwrap_rgb() and unwrap_hsv functions
#[test]
fn my_test1() {
let color1 = Color::new_rgb(10, 20, 30);
assert_eq!(color1.unwrap_rgb().0, 10);
assert_eq!(color1.unwrap_rgb().1, 20);
assert_eq!(color1.unwrap_rgb().2, 30);
let color2 = Color::new_rgb(255, 1, 0);
assert_eq!(color2.unwrap_rgb(), (255,1,0));
let color3 = Color::new_hsv(5, 10, 15);
assert_eq!(color3.unwrap_hsv().0, 5);
assert_eq!(color3.unwrap_hsv().1, 10);
assert_eq!(color3.unwrap_hsv().2, 15);
let color4 = Color::new_hsv(360, 100, 100);
assert_eq!(color4.unwrap_hsv(),(360,100,100));
}
//testing if it panics when we exceed the maximum value for hue, saturation or value
#[test]
#[should_panic]
fn my_test2_1() {
let _color1 = Color::new_hsv(5, 10, 101);
}
#[test]
#[should_panic]
fn my_test2_2() {
let _color1 = Color::new_hsv(361, 10, 1);
}
#[test]
#[should_panic]
fn my_test2_3() {
let _color1 = Color::new_hsv(44, 101, 1);
}
//testing the to_strong function for HSV
#[test]
fn my_test3() {
let color1 = Color::new_hsv(0, 0, 0);
assert_eq!(color1.to_string(), "hsv(0,0%,0%)");
let color2 = Color::new_hsv(360, 100, 100);
assert_eq!(color2.to_string(), "hsv(360,100%,100%)");
let color3 = Color::new_hsv(0, 10, 100);
assert_eq!(color3.to_string(), "hsv(0,10%,100%)");
let color4 = Color::new_hsv(1, 1, 1);
assert_eq!(color4.to_string(), "hsv(1,1%,1%)");
}
//testing the to_string() function for RGB
#[test]
fn my_test4() {
let color1 = Color::new_rgb(255, 1, 255);
assert_eq!(&color1.to_string()[0..7], "#ff01ff");
let color2 = Color::new_rgb(16, 16, 16);
assert_eq!(&color2.to_string()[0..7], "#101010");
let color3 = Color::new_rgb(1, 0, 16);
assert_eq!(&color3.to_string()[0..7], "#010010");
let color4 = Color::new_rgb(0, 0, 0);
assert_eq!(&color4.to_string()[0..7], "#000000");
let color5 = Color::new_rgb(11, 1, 1);
assert_eq!(&color5.to_string()[0..7], "#0b0101");
- let color5 = Color::new_rgb(123, 5, 255);
- assert_eq!(&color5.to_string()[0..7], "#7b05ff");
+ let color6 = Color::new_rgb(123, 5, 255);
+ assert_eq!(&color6.to_string()[0..7], "#7b05ff");
}
//testing the invert() function for RGB
#[test]
fn my_test5(){
let color1 = Color::new_rgb(0, 0, 0);
assert_eq!(color1.invert().unwrap_rgb(), (255,255,255));
let color2 = Color::new_rgb(255, 255, 255);
assert_eq!(color2.invert().unwrap_rgb(), (0,0,0));
let color3 = Color::new_rgb(127, 1, 254);
assert_eq!(color3.invert().unwrap_rgb(), (128,254,1));
}
//testing the invert() funtion for HSV
#[test]
fn my_test6(){
let color1 = Color::new_hsv(0, 0, 0);
assert_eq!(color1.invert().unwrap_hsv(), (360,100,100));
let color2 = Color::new_hsv(360, 100, 100);
assert_eq!(color2.invert().unwrap_hsv(), (0,0,0));
let color3 = Color::new_hsv(180, 50, 50);
assert_eq!(color3.invert().unwrap_hsv(), (180,50,50));
}

Погледнах си решението и видях, че във функцията pub fn decimal_to_hex(number:u16) -> String , трябва да е u8 не u16 и също тогава няма нужда да се конвертират от u8 към u16 red, green, blue в тази част от кода(ред 87-89):

rgb_string.push_str(&decimal_to_hex(*red as u16));

rgb_string.push_str(&decimal_to_hex(*green as u16));

rgb_string.push_str(&decimal_to_hex(*blue as u16));

а ще стане:

rgb_string.push_str(&decimal_to_hex(*red));

rgb_string.push_str(&decimal_to_hex(*green));

rgb_string.push_str(&decimal_to_hex(*blue));

Малко ми се е преплело мисленето когато съм я писал заради това, че на HSV hue e u16 :D

Да, конвертиране не ти трябва. Иначе един проблем на кода е, че стилово си доста неконсистентен. Тук-таме има интервали около =, тук таме няма, индентацията понякога мърда напред-назад. Ако ти е трудно да поддържаш консистентност при редактиране, едно решение може да е да си ползваш rustfmt инструмента да ти подрежда кода автоматично.

Обмислях дали да ти дам бонус точка за тестовете -- покрил си трите възможни паники при конструиране на HSV, също и няколко смислени случая за форматиране. Но едно нещо, което си изпуснал, са тестове за паника на unwrap_ методите. Другото, което не ми харесва на тях е, че нямат смислени имена -- не е нужно да бъдат перфектно описателни, но примерно my_test6 е доста неудобно име. Ако гръмне тест на име test_invert_hsv може доста лесно да се сетиш каква логика тества, за разлика от my_test6.

Все пак оценявам усилието, може би за следващото домашно :).