| 1 | use core::fmt; |
| 2 | |
| 3 | #[cfg(not(feature = "std"))] |
| 4 | use num_traits::float::Float; |
| 5 | |
| 6 | // Strip prefix ignore case. |
| 7 | pub fn strip_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> { |
| 8 | if prefix.len() > s.len() { |
| 9 | return None; |
| 10 | } |
| 11 | let s_start = &s[..prefix.len()]; |
| 12 | if s_start.eq_ignore_ascii_case(prefix) { |
| 13 | Some(&s[prefix.len()..]) |
| 14 | } else { |
| 15 | None |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | pub(crate) struct AlphaFmt(pub f32); |
| 20 | |
| 21 | impl fmt::Display for AlphaFmt { |
| 22 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 23 | let t = (self.0.clamp(0.0, 1.0) * 100.0 + 0.5) as u8; |
| 24 | if t < 100 { |
| 25 | write!(f, " / {t}%") |
| 26 | } else { |
| 27 | Ok(()) |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | pub(crate) struct FloatFmt(pub f32); |
| 33 | |
| 34 | impl fmt::Display for FloatFmt { |
| 35 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 36 | if self.0.is_nan() { |
| 37 | return write!(f, "none"); |
| 38 | } |
| 39 | |
| 40 | // Round to 3 decimal places first to clear floating point noise |
| 41 | let rounded = (self.0 * 1000.0).round() / 1000.0; |
| 42 | |
| 43 | // Get the 3-digit fractional part as an integer |
| 44 | let fract = (rounded.abs().fract() * 1000.0).round() as u16; |
| 45 | |
| 46 | // Determine precision based on the integer fractional part |
| 47 | let precision = if fract == 0 { |
| 48 | 0 |
| 49 | } else if fract % 10 != 0 { |
| 50 | 3 |
| 51 | } else if fract % 100 != 0 { |
| 52 | 2 |
| 53 | } else { |
| 54 | 1 |
| 55 | }; |
| 56 | |
| 57 | write!(f, "{:.*}", precision, rounded) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[cfg(test)] |
| 62 | mod t { |
| 63 | use super::*; |
| 64 | |
| 65 | #[test] |
| 66 | fn strip_prefix_() { |
| 67 | assert_eq!(strip_prefix("rgb(77)", "rgb"), Some("(77)")); |
| 68 | assert_eq!(strip_prefix("RGB(0,0)", "rgb"), Some("(0,0)")); |
| 69 | assert_eq!(strip_prefix("Hsv()", "HSV"), Some("()")); |
| 70 | |
| 71 | assert_eq!(strip_prefix("", "rgb"), None); |
| 72 | assert_eq!(strip_prefix("10", "rgb"), None); |
| 73 | assert_eq!(strip_prefix("hsv(0,0)", "hsva"), None); |
| 74 | assert_eq!(strip_prefix("hsv", "hsva"), None); |
| 75 | } |
| 76 | } |