| 1 | use core::fmt::{Display, Formatter}; |
| 2 | #[cfg(feature = "std")] |
| 3 | use std::string::{String, ToString}; |
| 4 | |
| 5 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 6 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 7 | /// A 24-bit color value stored as R, G, and B bytes |
| 8 | pub struct Color { |
| 9 | /// Red component |
| 10 | pub r: u8, |
| 11 | /// Green component |
| 12 | pub g: u8, |
| 13 | /// Blue component |
| 14 | pub b: u8, |
| 15 | } |
| 16 | |
| 17 | #[cfg(feature = "std")] |
| 18 | #[deprecated(since = "0.7.0", note = "Use color.to_string() instead")] |
| 19 | impl Color { |
| 20 | /// Returns the html string for this color. |
| 21 | /// |
| 22 | /// ``` |
| 23 | /// use mendeleev::{Element, Color}; |
| 24 | /// |
| 25 | /// let color = Color{r: 0, g: 255, b: 255}; |
| 26 | /// assert_eq!(color.html(), "#00ffff"); |
| 27 | /// let color = Color{r: 48, g: 64, b: 80}; |
| 28 | /// assert_eq!(color.html(), "#304050"); |
| 29 | /// ``` |
| 30 | pub fn html(&self) -> String { |
| 31 | self.to_string() |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | /// Displays the color as an HTML string. |
| 36 | /// |
| 37 | /// ``` |
| 38 | /// use mendeleev::{Element, Color}; |
| 39 | /// |
| 40 | /// let color = Color{r: 0, g: 255, b: 255}; |
| 41 | /// assert_eq!(format!("{}", color), "#00ffff"); |
| 42 | /// let color = Color{r: 48, g: 64, b: 80}; |
| 43 | /// assert_eq!(format!("{}", color), "#304050"); |
| 44 | /// ``` |
| 45 | impl Display for Color { |
| 46 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { |
| 47 | write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | pub(crate) const fn color(r: u8, g: u8, b: u8) -> Option<Color> { |
| 52 | Some(Color { r, g, b }) |
| 53 | } |