Решение на CSS Цветове от Ангел Пенчев
Резултати
- 20 точки от тестове
- 1 бонус точка
- 21 точки общо
- 5 успешни тест(а)
- 0 неуспешни тест(а)
Код
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Color {
RGB {
red: u8,
green: u8,
blue: u8,
},
HSV {
hue: u16,
saturation: u8,
value: u8,
},
}
impl Color {
/// Конструира нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
///
/// # Параметри
/// * `red` - стойност за червено от 0 до 255
/// * `green` - стойност за зелено от 0 до 255
/// * `blue` - стойност за синьо от 0 до 255
///
/// # Връща
/// Нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
///
/// # Пример
/// ```
/// use css_colors::Color;
/// let red = Color::new_rgb(255, 0, 0);
/// assert_eq!(red, Color::RGB { red: 255, green: 0, blue: 0 });
/// ```
pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {
Color::RGB { red, green, blue }
}
/// Конструира нова стойност от вариант `HSV` с дадените стойности за оттенък, наситеност и яркост.
///
/// # Параметри
/// * `hue` - стойност за оттенък от 0 до 360
/// * `saturation` - стойност за наситеност от 0 до 100
/// * `value` - стойност за яркост от 0 до 100
///
/// # Връща
/// Нова стойност от вариант `HSV` с дадените стойности.
///
/// # Грешки
/// Ако някоя от стойностите е извън допустимите граници, се връща грешка.
///
/// # Пример
/// ```
/// use css_colors::Color;
/// let red = Color::new_hsv(0, 80, 80);
/// assert_eq!(red, Color::HSV { hue: 0, saturation: 80, value: 80 });
/// ```
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
assert!(hue <= 360, "Hue must be a degree, i.e. hue <= 360");
assert!(saturation <= 100, "Saturation must be a percentage, i.e. saturation <= 100");
assert!(value <= 100, "Value must be <= 100, i.e. value <= 100");
Color::HSV { hue, saturation, value }
}
/// Връща отделните стойности за червено, зелено и синьо на даден `RGB` цвят.
///
/// # Параметри
/// * `color` - стойност от вариант `RGB`
///
/// # Връща
/// Компонентите на цвета, ако той е `RGB`.
///
/// # Грешки
/// Ако стойността не е `RGB`, се връща грешка.
///
/// # Пример
/// ```
/// use css_colors::Color;
/// let red = Color::new_rgb(255, 0, 0);
/// let (red, green, blue) = red.unwrap_rgb();
/// assert_eq!((red, green, blue), (255, 0, 0));
/// ```
pub fn unwrap_rgb(&self) -> (u8, u8, u8) {
match self {
Color::RGB { red, green, blue } => (*red, *green, *blue),
_ => panic!("Color is not RGB!"),
}
}
/// Връща отделните стойности за оттенък, наситеност и яркост на даден `HSV` цвят.
///
/// # Параметри
/// * `color` - стойност от вариант `HSV`
///
/// # Връща
/// Компонентите на цвета, ако той е `HSV`.
///
/// # Грешки
/// Ако стойността не е `HSV`, се връща грешка.
///
/// # Пример
/// ```
/// use css_colors::Color;
/// let red = Color::HSV { hue: 0, saturation: 80, value: 80 };
/// assert_eq!(red.unwrap_hsv(), (0, 80, 80));
/// ```
pub fn unwrap_hsv(&self) -> (u16, u8, u8) {
match self {
Color::HSV { hue, saturation, value } => (*hue, *saturation, *value),
_ => panic!("Color is not HSV!")
}
}
/// Превръща даден цвят като символен низ, според CSS начина на запис на цветове.
///
/// # Параметри
/// * `color` - цвят за преобразуване към символен низ
///
/// # Връща
/// Ако цветът е `RGB`, връща символен низ във формат #rrggbb, с малки букви.
/// Ако цветът е `HSV`, връща символен низ във формат hsv(h,s%,v).
///
/// # Пример
/// ```
/// use css_colors::Color;
/// let color1 = Color::HSV { hue: 0, saturation: 30, value: 50 };
/// assert_eq!(color1.to_string(), "hsv(0,30%,50%)");
///
/// let color2 = Color::RGB { red: 255, green: 0, blue: 0 };
/// assert_eq!(color2.to_string(), "#ff0000");
/// ```
pub fn to_string(&self) -> String {
match self {
Color::RGB { red, green, blue }
=> format!("#{:02x}{:02x}{:02x}", red, green, blue),
Color::HSV { hue, saturation, value }
=> format!("hsv({},{}%,{}%)", hue, saturation, value)
}
}
/// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
///
/// # Параметри
/// * `color` - цвят, който да се инвертира
///
/// # Връща
/// Нов цвят, който представлява инвертирана версия на подадения.
///
/// # Пример
/// ```
/// use css_colors::Color;
/// let color1 = Color::HSV { hue: 180, saturation: 70, value: 70 };
/// assert_eq!(color1.invert(), Color::new_hsv(180, 30, 30));
/// ```
pub fn invert(&self) -> Self {
match self {
Color::RGB { red, green, blue } => Color::RGB {
red: u8::MAX - red,
green: u8::MAX - green,
blue: u8::MAX - blue,
},
Color::HSV { hue, saturation, value } => Color::HSV {
hue: 360 - hue,
saturation: 100 - saturation,
value: 100 - value,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_rgb() {
let color: Color = Color::new_rgb(80, 120, 160);
assert_eq!(color, Color::RGB { red: 80, green: 120, blue: 160 });
}
#[test]
fn test_new_hsv() {
let color: Color = Color::new_hsv(80, 60, 40);
assert_eq!(color, Color::HSV { hue: 80, saturation: 60, value: 40 });
}
#[test]
#[should_panic]
fn test_new_hsv_panic() {
// Should panic because hue is > 360
Color::new_hsv(380, 60, 40);
}
#[test]
fn test_unwrap_rgb() {
let color: Color = Color::new_rgb(80, 120, 160);
assert_eq!(color.unwrap_rgb(), (80, 120, 160));
}
#[test]
fn test_unwrap_hsv() {
let color: Color = Color::new_hsv(80, 60, 40);
assert_eq!(color.unwrap_hsv(), (80, 60, 40));
}
#[test]
fn test_to_string_rgb() {
assert_eq!(Color::new_rgb(0, 0, 0).to_string(), "#000000");
assert_eq!(Color::new_rgb(255, 128, 128).to_string(), "#ff8080");
assert_eq!(Color::new_rgb(128, 255, 128).to_string(), "#80ff80");
assert_eq!(Color::new_rgb(128, 128, 255).to_string(), "#8080ff");
assert_eq!(Color::new_rgb(255, 255, 255).to_string(), "#ffffff");
}
#[test]
fn test_to_string_hsv() {
assert_eq!(Color::new_hsv(0, 0, 0).to_string(), "hsv(0,0%,0%)");
assert_eq!(Color::new_hsv(180, 50, 50).to_string(), "hsv(180,50%,50%)");
assert_eq!(Color::new_hsv(360, 100, 100).to_string(), "hsv(360,100%,100%)");
}
#[test]
fn test_invert_rgb() {
assert_eq!(Color::new_rgb(0, 0, 0).invert(), Color::new_rgb(255, 255, 255));
assert_eq!(Color::new_rgb(255, 128, 128).invert(), Color::new_rgb(0, 127, 127));
assert_eq!(Color::new_rgb(128, 255, 128).invert(), Color::new_rgb(127, 0, 127));
assert_eq!(Color::new_rgb(128, 128, 255).invert(), Color::new_rgb(127, 127, 0));
assert_eq!(Color::new_rgb(255, 255, 255).invert(), Color::new_rgb(0, 0, 0));
}
#[test]
fn test_invert_hsv() {
assert_eq!(Color::new_hsv(0, 0, 0).invert(), Color::new_hsv(360, 100, 100));
assert_eq!(Color::new_hsv(180, 50, 50).invert(), Color::new_hsv(180, 50, 50));
assert_eq!(Color::new_hsv(360, 100, 100).invert(), Color::new_hsv(0, 0, 0));
}
}
Лог от изпълнението
Compiling solution v0.1.0 (/tmp/d20230111-3772066-xlt9bs/solution) Finished test [unoptimized + debuginfo] target(s) in 0.64s 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_new_hsv ... ok test solution_test::test_invert_rgb ... ok test solution_test::test_rgb_display ... ok test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
История (4 версии и 1 коментар)
Ангел качи решение на 20.10.2022 20:31 (преди почти 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 {
- Color::RGB { red, green, blue }
+ todo!()
}
/// Конструира нова стойност от вариант `HSV` с дадените стойности.
///
/// В случай, че hue е над 360 или saturation или value са над 100, очакваме да `panic!`-нете с
/// каквото съобщение си изберете.
///
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
- assert!(hue <= 360, "hue must be <= 360");
- assert!(saturation <= 100, "saturation must be <= 100");
- assert!(value <= 100, "value must be <= 100");
- Color::HSV { hue, saturation, value }
+ todo!()
}
/// Ако `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!("Color is not RGB"),
- }
+ todo!()
}
/// Ако `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!("Color is not HSV"),
- }
+ todo!()
}
/// В случай, че варианта на `self` е `RGB`, очакваме низ със съдържание `#rrggbb`, където
/// червения, зеления и синия компонент са форматирани в шестнадесетична система, и всеки от тях е
/// точно два символа с малки букви (запълнени с нули).
///
/// Ако варианта е `HSV`, очакваме низ `hsv(h,s%,v%)`, където числата са си напечатани в
/// десетичната система, без водещи нули, без интервали след запетаите, вторите две завършващи на
/// `%`.
///
pub fn to_string(&self) -> String {
- match self {
- Color::RGB { red, green, blue } => format!("#{:02x}{:02x}{:02x}", red, green, blue),
- Color::HSV { hue, saturation, value } => format!("hsv({},{}%,{}%)", hue, saturation, value),
- }
+ todo!()
}
+}
- /// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
- ///
- pub fn invert(&self) -> Self {
- match self {
- Color::RGB { red, green, blue } => Color::RGB {
- red: 255 - red,
- green: 255 - green,
- blue: 255 - blue,
- },
- Color::HSV { hue, saturation, value } => Color::HSV {
- hue: 360 - hue,
- saturation: 100 - saturation,
- value: 100 - value,
- },
- }
- }
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn it_works() {}
}
Ангел качи решение на 20.10.2022 23:23 (преди почти 3 години)
+#[derive(PartialEq)]
+#[derive(Debug)]
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 {
- todo!()
+ Color::RGB { red, green, blue }
}
/// Конструира нова стойност от вариант `HSV` с дадените стойности.
///
/// В случай, че hue е над 360 или saturation или value са над 100, очакваме да `panic!`-нете с
/// каквото съобщение си изберете.
///
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
- todo!()
+ assert!(hue <= 360, "hue must be <= 360");
+ assert!(saturation <= 100, "saturation must be <= 100");
+ assert!(value <= 100, "value must be <= 100");
+ Color::HSV { hue, saturation, value }
}
/// Ако `self` е `RGB`, тогава връщате неговите `red`, `green`, `blue` компоненти в този ред.
/// Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_rgb(&self) -> (u8, u8, u8) {
- todo!()
+ match self {
+ Color::RGB { red, green, blue } => (*red, *green, *blue),
+ _ => panic!("Color is not RGB!"),
+ }
}
/// Ако `self` е `HSV`, тогава връщате неговите `hue`, `saturation`, `value` компоненти в този
/// ред. Иначе, `panic!`-вате с каквото съобщение си изберете.
///
pub fn unwrap_hsv(&self) -> (u16, u8, u8) {
- todo!()
+ match self {
+ Color::HSV { hue, saturation, value } => (*hue, *saturation, *value),
+ _ => panic!("Color is not HSV!")
+ }
}
/// В случай, че варианта на `self` е `RGB`, очакваме низ със съдържание `#rrggbb`, където
/// червения, зеления и синия компонент са форматирани в шестнадесетична система, и всеки от тях е
/// точно два символа с малки букви (запълнени с нули).
///
/// Ако варианта е `HSV`, очакваме низ `hsv(h,s%,v%)`, където числата са си напечатани в
/// десетичната система, без водещи нули, без интервали след запетаите, вторите две завършващи на
/// `%`.
///
pub fn to_string(&self) -> String {
- todo!()
+ match self {
+ Color::RGB { red, green, blue } => format!("#{:02x}{:02x}{:02x}", red, green, blue),
+ Color::HSV { hue, saturation, value } => format!("hsv({},{}%,{}%)", hue, saturation, value)
+ }
}
+
+ /// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
+ ///
+ pub fn invert(&self) -> Self {
+ match self {
+ Color::RGB { red, green, blue } => Color::RGB {
+ red: u8::MAX - red,
+ green: u8::MAX - green,
+ blue: u8::MAX - blue,
+ },
+ Color::HSV { hue, saturation, value } => Color::HSV {
+ hue: 360 - hue,
+ saturation: 100 - saturation,
+ value: 100 - value,
+ }
+ }
+ }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
- fn it_works() {}
+ fn test_new_rgb() {
+ let color: Color = Color::new_rgb(80, 120, 160);
+ assert_eq!(color, Color::RGB { red: 80, green: 120, blue: 160 });
+ }
+
+ #[test]
+ fn test_new_hsv() {
+ let color: Color = Color::new_hsv(80, 60, 40);
+ assert_eq!(color, Color::HSV { hue: 80, saturation: 60, value: 40 });
+ }
+
+ #[test]
+ #[should_panic]
+ fn test_new_hsv_panic() {
+ // Should panic because hue is > 360
+ Color::new_hsv(380, 60, 40);
+ }
+
+ #[test]
+ fn test_unwrap_rgb() {
+ let color: Color = Color::new_rgb(80, 60, 40);
+ assert_eq!(color.unwrap_rgb(), (80, 60, 40));
+ }
+
+ #[test]
+ fn test_unwrap_hsv() {
+ let color: Color = Color::new_hsv(80, 60, 40);
+ assert_eq!(color.unwrap_hsv(), (80, 60, 40));
+ }
+
+ #[test]
+ fn test_to_string_rgb() {
+ assert_eq!(Color::new_rgb(0, 0, 0).to_string(), "#000000");
+ assert_eq!(Color::new_rgb(255, 128, 128).to_string(), "#ff8080");
+ assert_eq!(Color::new_rgb(128, 255, 128).to_string(), "#80ff80");
+ assert_eq!(Color::new_rgb(128, 128, 255).to_string(), "#8080ff");
+ assert_eq!(Color::new_rgb(255, 255, 255).to_string(), "#ffffff");
+ }
+
+ #[test]
+ fn test_to_string_hsv() {
+ assert_eq!(Color::new_hsv(0, 0, 0).to_string(), "hsv(0,0%,0%)");
+ assert_eq!(Color::new_hsv(180, 50, 50).to_string(), "hsv(180,50%,50%)");
+ assert_eq!(Color::new_hsv(360, 100, 100).to_string(), "hsv(360,100%,100%)");
+ }
+
+ #[test]
+ fn test_invert_rgb() {
+ assert_eq!(Color::new_rgb(0, 0, 0).invert(), Color::new_rgb(255, 255, 255));
+ assert_eq!(Color::new_rgb(255, 128, 128).invert(), Color::new_rgb(0, 127, 127));
+ assert_eq!(Color::new_rgb(128, 255, 128).invert(), Color::new_rgb(127, 0, 127));
+ assert_eq!(Color::new_rgb(128, 128, 255).invert(), Color::new_rgb(127, 127, 0));
+ assert_eq!(Color::new_rgb(255, 255, 255).invert(), Color::new_rgb(0, 0, 0));
+ }
+
+ #[test]
+ fn test_invert_hsv() {
+ assert_eq!(Color::new_hsv(0, 0, 0).invert(), Color::new_hsv(360, 100, 100));
+ assert_eq!(Color::new_hsv(180, 50, 50).invert(), Color::new_hsv(180, 50, 50));
+ assert_eq!(Color::new_hsv(360, 100, 100).invert(), Color::new_hsv(0, 0, 0));
+ }
}
Ангел качи решение на 21.10.2022 01:04 (преди почти 3 години)
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Color {
RGB {
red: u8,
green: u8,
blue: u8,
},
HSV {
hue: u16,
saturation: u8,
value: u8,
- }
+ },
}
impl Color {
/// Конструира нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
///
+ /// # Параметри
+ /// * `red` - стойност за червено от 0 до 255
+ /// * `green` - стойност за зелено от 0 до 255
+ /// * `blue` - стойност за синьо от 0 до 255
+ ///
+ /// # Връща
+ /// Нова стойност от вариант `RGB` с дадените стойности за червено, зелено и синьо.
+ ///
+ /// # Пример
+ /// ```
+ /// use css_colors::Color;
+ /// let red = Color::new_rgb(255, 0, 0);
+ /// assert_eq!(red, Color::RGB { red: 255, green: 0, blue: 0 });
+ /// ```
pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {
Color::RGB { red, green, blue }
}
- /// Конструира нова стойност от вариант `HSV` с дадените стойности.
+ /// Конструира нова стойност от вариант `HSV` с дадените стойности за оттенък, наситеност и яркост.
///
- /// В случай, че hue е над 360 или saturation или value са над 100, очакваме да `panic!`-нете с
- /// каквото съобщение си изберете.
+ /// # Параметри
+ /// * `hue` - стойност за оттенък от 0 до 360
+ /// * `saturation` - стойност за наситеност от 0 до 100
+ /// * `value` - стойност за яркост от 0 до 100
///
+ /// # Връща
+ /// Нова стойност от вариант `HSV` с дадените стойности.
+ ///
+ /// # Грешки
+ /// Ако някоя от стойностите е извън допустимите граници, се връща грешка.
+ ///
+ /// # Пример
+ /// ```
+ /// use css_colors::Color;
+ /// let red = Color::new_hsv(0, 80, 80);
+ /// assert_eq!(red, Color::HSV { hue: 0, saturation: 80, value: 80 });
+ /// ```
pub fn new_hsv(hue: u16, saturation: u8, value: u8) -> Color {
- assert!(hue <= 360, "hue must be <= 360");
- assert!(saturation <= 100, "saturation must be <= 100");
- assert!(value <= 100, "value must be <= 100");
+ assert!(hue <= 360, "Hue must be a degree, i.e. hue <= 360");
+ assert!(saturation <= 100, "Saturation must be a percentage, i.e. saturation <= 100");
+ assert!(value <= 100, "Value must be <= 100, i.e. value <= 100");
Color::HSV { hue, saturation, value }
}
- /// Ако `self` е `RGB`, тогава връщате неговите `red`, `green`, `blue` компоненти в този ред.
- /// Иначе, `panic!`-вате с каквото съобщение си изберете.
+ /// Връща отделните стойности за червено, зелено и синьо на даден `RGB` цвят.
///
+ /// # Параметри
+ /// * `color` - стойност от вариант `RGB`
+ ///
+ /// # Връща
+ /// Компонентите на цвета, ако той е `RGB`.
+ ///
+ /// # Грешки
+ /// Ако стойността не е `RGB`, се връща грешка.
+ ///
+ /// # Пример
+ /// ```
+ /// use css_colors::Color;
+ /// let red = Color::new_rgb(255, 0, 0);
+ /// let (red, green, blue) = red.unwrap_rgb();
+ /// assert_eq!((red, green, blue), (255, 0, 0));
+ /// ```
pub fn unwrap_rgb(&self) -> (u8, u8, u8) {
match self {
Color::RGB { red, green, blue } => (*red, *green, *blue),
_ => panic!("Color is not RGB!"),
}
}
- /// Ако `self` е `HSV`, тогава връщате неговите `hue`, `saturation`, `value` компоненти в този
- /// ред. Иначе, `panic!`-вате с каквото съобщение си изберете.
+ /// Връща отделните стойности за оттенък, наситеност и яркост на даден `HSV` цвят.
///
+ /// # Параметри
+ /// * `color` - стойност от вариант `HSV`
+ ///
+ /// # Връща
+ /// Компонентите на цвета, ако той е `HSV`.
+ ///
+ /// # Грешки
+ /// Ако стойността не е `HSV`, се връща грешка.
+ ///
+ /// # Пример
+ /// ```
+ /// use css_colors::Color;
+ /// let red = Color::HSV { hue: 0, saturation: 80, value: 80 };
+ /// assert_eq!(red.unwrap_hsv(), (0, 80, 80));
+ /// ```
pub fn unwrap_hsv(&self) -> (u16, u8, u8) {
match self {
Color::HSV { hue, saturation, value } => (*hue, *saturation, *value),
_ => panic!("Color is not HSV!")
}
}
- /// В случай, че варианта на `self` е `RGB`, очакваме низ със съдържание `#rrggbb`, където
- /// червения, зеления и синия компонент са форматирани в шестнадесетична система, и всеки от тях е
- /// точно два символа с малки букви (запълнени с нули).
+ /// Превръща даден цвят като символен низ, според CSS начина на запис на цветове.
///
- /// Ако варианта е `HSV`, очакваме низ `hsv(h,s%,v%)`, където числата са си напечатани в
- /// десетичната система, без водещи нули, без интервали след запетаите, вторите две завършващи на
- /// `%`.
+ /// # Параметри
+ /// * `color` - цвят за преобразуване към символен низ
///
+ /// # Връща
+ /// Ако цветът е `RGB`, връща символен низ във формат #rrggbb, с малки букви.
+ /// Ако цветът е `HSV`, връща символен низ във формат hsv(h,s%,v).
+ ///
+ /// # Пример
+ /// ```
+ /// use css_colors::Color;
+ /// let color1 = Color::HSV { hue: 0, saturation: 30, value: 50 };
+ /// assert_eq!(color1.to_string(), "hsv(0,30%,50%)");
+ ///
+ /// let color2 = Color::RGB { red: 255, green: 0, blue: 0 };
+ /// assert_eq!(color2.to_string(), "#ff0000");
+ /// ```
pub fn to_string(&self) -> String {
match self {
- Color::RGB { red, green, blue } => format!("#{:02x}{:02x}{:02x}", red, green, blue),
- Color::HSV { hue, saturation, value } => format!("hsv({},{}%,{}%)", hue, saturation, value)
+ Color::RGB { red, green, blue }
+ => format!("#{:02x}{:02x}{:02x}", red, green, blue),
+
+ Color::HSV { hue, saturation, value }
+ => format!("hsv({},{}%,{}%)", hue, saturation, value)
}
}
/// Инвертира цвят покомпонентно -- за всяка от стойностите се взема разликата с максимума.
///
+ /// # Параметри
+ /// * `color` - цвят, който да се инвертира
+ ///
+ /// # Връща
+ /// Нов цвят, който представлява инвертирана версия на подадения.
+ ///
+ /// # Пример
+ /// ```
+ /// use css_colors::Color;
+ /// let color1 = Color::HSV { hue: 180, saturation: 70, value: 70 };
+ /// assert_eq!(color1.invert(), Color::new_hsv(180, 30, 30));
+ /// ```
pub fn invert(&self) -> Self {
match self {
Color::RGB { red, green, blue } => Color::RGB {
red: u8::MAX - red,
green: u8::MAX - green,
blue: u8::MAX - blue,
},
Color::HSV { hue, saturation, value } => Color::HSV {
hue: 360 - hue,
saturation: 100 - saturation,
value: 100 - value,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_rgb() {
let color: Color = Color::new_rgb(80, 120, 160);
assert_eq!(color, Color::RGB { red: 80, green: 120, blue: 160 });
}
#[test]
fn test_new_hsv() {
let color: Color = Color::new_hsv(80, 60, 40);
assert_eq!(color, Color::HSV { hue: 80, saturation: 60, value: 40 });
}
#[test]
#[should_panic]
fn test_new_hsv_panic() {
// Should panic because hue is > 360
Color::new_hsv(380, 60, 40);
}
#[test]
fn test_unwrap_rgb() {
- let color: Color = Color::new_rgb(80, 60, 40);
- assert_eq!(color.unwrap_rgb(), (80, 60, 40));
+ let color: Color = Color::new_rgb(80, 120, 160);
+ assert_eq!(color.unwrap_rgb(), (80, 120, 160));
}
#[test]
fn test_unwrap_hsv() {
let color: Color = Color::new_hsv(80, 60, 40);
assert_eq!(color.unwrap_hsv(), (80, 60, 40));
}
#[test]
fn test_to_string_rgb() {
assert_eq!(Color::new_rgb(0, 0, 0).to_string(), "#000000");
assert_eq!(Color::new_rgb(255, 128, 128).to_string(), "#ff8080");
assert_eq!(Color::new_rgb(128, 255, 128).to_string(), "#80ff80");
assert_eq!(Color::new_rgb(128, 128, 255).to_string(), "#8080ff");
assert_eq!(Color::new_rgb(255, 255, 255).to_string(), "#ffffff");
}
#[test]
fn test_to_string_hsv() {
assert_eq!(Color::new_hsv(0, 0, 0).to_string(), "hsv(0,0%,0%)");
assert_eq!(Color::new_hsv(180, 50, 50).to_string(), "hsv(180,50%,50%)");
assert_eq!(Color::new_hsv(360, 100, 100).to_string(), "hsv(360,100%,100%)");
}
#[test]
fn test_invert_rgb() {
assert_eq!(Color::new_rgb(0, 0, 0).invert(), Color::new_rgb(255, 255, 255));
assert_eq!(Color::new_rgb(255, 128, 128).invert(), Color::new_rgb(0, 127, 127));
assert_eq!(Color::new_rgb(128, 255, 128).invert(), Color::new_rgb(127, 0, 127));
assert_eq!(Color::new_rgb(128, 128, 255).invert(), Color::new_rgb(127, 127, 0));
assert_eq!(Color::new_rgb(255, 255, 255).invert(), Color::new_rgb(0, 0, 0));
}
#[test]
fn test_invert_hsv() {
assert_eq!(Color::new_hsv(0, 0, 0).invert(), Color::new_hsv(360, 100, 100));
assert_eq!(Color::new_hsv(180, 50, 50).invert(), Color::new_hsv(180, 50, 50));
assert_eq!(Color::new_hsv(360, 100, 100).invert(), Color::new_hsv(0, 0, 0));
}
}
Давам ти бонус точка за написаните тестове и добрите doc-коментари 👍. Едно нещо, което все пак си изпуснал в тестването, е panic при невалидни value или saturation -- написал си should_panic
тест само за hue, така че ако изпуснеш assert-ите, тестовете ще продължават да си минават.