Skip to main content

Color

Enum Color 

Source
#[non_exhaustive]
pub enum Color {
Show 19 variants Reset, Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, DarkGray, LightRed, LightGreen, LightYellow, LightBlue, LightMagenta, LightCyan, LightWhite, Rgb(u8, u8, u8), Indexed(u8),
}
Expand description

Terminal color.

Covers the standard 16 named colors, 256-color palette indices, and 24-bit RGB true color. Use Color::Reset to restore the terminal’s default foreground or background.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Reset

Reset to the terminal’s default color.

§

Black

Standard black (color index 0).

§

Red

Standard red (color index 1).

§

Green

Standard green (color index 2).

§

Yellow

Standard yellow (color index 3).

§

Blue

Standard blue (color index 4).

§

Magenta

Standard magenta (color index 5).

§

Cyan

Standard cyan (color index 6).

§

White

Standard white (color index 7).

§

DarkGray

Bright black / dark gray (color index 8).

§

LightRed

Bright red (color index 9).

§

LightGreen

Bright green (color index 10).

§

LightYellow

Bright yellow (color index 11).

§

LightBlue

Bright blue (color index 12).

§

LightMagenta

Bright magenta (color index 13).

§

LightCyan

Bright cyan (color index 14).

§

LightWhite

Bright white (color index 15).

§

Rgb(u8, u8, u8)

24-bit true color.

§

Indexed(u8)

256-color palette index.

Implementations§

Source§

impl Color

Source

pub fn luminance(self) -> f32

Compute relative luminance using ITU-R BT.709 coefficients.

Returns a value in [0.0, 1.0] where 0 is darkest and 1 is brightest. Use this to determine whether text on a given background should be light or dark.

§Example
use slt::Color;

let dark = Color::Rgb(30, 30, 46);
assert!(dark.luminance() < 0.15);

let light = Color::Rgb(205, 214, 244);
assert!(light.luminance() > 0.6);
Source

pub fn contrast_fg(bg: Color) -> Color

Return a contrasting foreground color for the given background.

Uses the WCAG 2.1 relative luminance threshold (0.179) to decide between white and black text. For theme-aware contrast, prefer using this over hardcoding theme.bg as the foreground.

§Example
use slt::Color;

let bg = Color::Rgb(189, 147, 249); // Dracula purple
let fg = Color::contrast_fg(bg);
// Dracula purple → white (WCAG luminance 0.385 < 0.179 threshold)
Source

pub fn blend(self, other: Color, alpha: f32) -> Color

Blend this color over another with the given alpha.

alpha is in [0.0, 1.0] where 0.0 returns other unchanged and 1.0 returns self unchanged. Both colors are resolved to RGB.

§Example
use slt::Color;

let white = Color::Rgb(255, 255, 255);
let black = Color::Rgb(0, 0, 0);
let gray = white.blend(black, 0.5);
// ≈ Rgb(128, 128, 128)
Source

pub fn lighten(self, amount: f32) -> Color

Lighten this color by the given amount (0.0–1.0).

Blends toward white. amount = 0.0 returns the original color; amount = 1.0 returns white.

Source

pub fn darken(self, amount: f32) -> Color

Darken this color by the given amount (0.0–1.0).

Blends toward black. amount = 0.0 returns the original color; amount = 1.0 returns black.

Source

pub fn contrast_ratio(a: Color, b: Color) -> f32

Compute the WCAG 2.1 contrast ratio between two colors.

Returns a value >= 1.0. A ratio >= 4.5 meets WCAG AA for normal text;

= 3.0 meets AA for large text.

§Example
use slt::Color;

let ratio = Color::contrast_ratio(Color::White, Color::Black);
assert!(ratio > 15.0);
Source

pub fn meets_contrast_aa(fg: Color, bg: Color) -> bool

Returns true if the contrast ratio between two colors meets WCAG AA for normal text (ratio >= 4.5).

Source

pub fn downsampled(self, depth: ColorDepth) -> Color

Downsample this color to fit the given color depth.

  • TrueColor: returns self unchanged.
  • EightBit: converts Rgb to the nearest Indexed color.
  • Basic: converts Rgb and Indexed to the nearest named color.
  • NoColor: returns Color::Reset — emit no ANSI color at all.

Named colors (Red, Green, etc.) and Reset pass through at depths other than NoColor.

Source

pub fn from_hex(s: &str) -> Option<Color>

Parse a hex string (#rgb or #rrggbb) into Color::Rgb.

The leading # is required. Short form #rgb expands each nibble (#abcRgb(0xaa, 0xbb, 0xcc)). Returns None for any malformed input (wrong length, non-hex digits, missing #).

§Example
use slt::Color;

assert_eq!(Color::from_hex("#ff6b6b"), Some(Color::Rgb(255, 107, 107)));
assert_eq!(Color::from_hex("#abc"), Some(Color::Rgb(170, 187, 204)));
assert_eq!(Color::from_hex("ff6b6b"), None); // missing '#'
assert_eq!(Color::from_hex("#xyz"), None); // non-hex
Source

pub fn to_hex(self) -> String

Format an Rgb color as a #rrggbb hex string.

Non-Rgb variants are first resolved to their RGB equivalent via the internal palette, so the result is always a valid #rrggbb token.

§Example
use slt::Color;

assert_eq!(Color::Rgb(255, 107, 107).to_hex(), "#ff6b6b");
Source

pub fn from_hsl(h: f32, s: f32, l: f32) -> Color

Construct an Color::Rgb from HSL components.

h is the hue in degrees (wrapped into 0..360), s is the saturation and l the lightness, both clamped to [0.0, 1.0].

§Example
use slt::Color;

assert_eq!(Color::from_hsl(0.0, 1.0, 0.5), Color::Rgb(255, 0, 0));
assert_eq!(Color::from_hsl(120.0, 1.0, 0.5), Color::Rgb(0, 255, 0));
assert_eq!(Color::from_hsl(240.0, 1.0, 0.5), Color::Rgb(0, 0, 255));
Source

pub fn from_hsv(h: f32, s: f32, v: f32) -> Color

Construct an Color::Rgb from HSV (a.k.a. HSB) components.

h is the hue in degrees (wrapped into 0..360), s is the saturation and v the value/brightness, both clamped to [0.0, 1.0].

§Example
use slt::Color;

assert_eq!(Color::from_hsv(0.0, 1.0, 1.0), Color::Rgb(255, 0, 0));
assert_eq!(Color::from_hsv(120.0, 1.0, 1.0), Color::Rgb(0, 255, 0));
assert_eq!(Color::from_hsv(0.0, 0.0, 1.0), Color::Rgb(255, 255, 255));
Source

pub fn rotate_hue(self, degrees: f32) -> Color

Rotate the hue of this color by degrees around the HSL color wheel.

The color is resolved to RGB, converted to HSL, rotated, and converted back to Color::Rgb. Positive values rotate forward (red → green → blue); negative values rotate backward. The result is always an Rgb color regardless of the input variant — named and indexed colors are first resolved via the internal palette.

§Example
use slt::Color;

// Rotating pure red by 120° lands on pure green.
assert_eq!(Color::Rgb(255, 0, 0).rotate_hue(120.0), Color::Rgb(0, 255, 0));

Trait Implementations§

Source§

impl Clone for Color

Source§

fn clone(&self) -> Color

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Color

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Color

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Color, D::Error>
where D: Deserializer<'de>,

Deserialize from a token string: #rgb/#rrggbb, a named color (case-insensitive), or indexed:N.

Source§

impl From<[u8; 3]> for Color

Source§

fn from([r, g, b]: [u8; 3]) -> Color

Construct an Color::Rgb from an [r, g, b] array.

Source§

impl From<(u8, u8, u8)> for Color

Source§

fn from((r, g, b): (u8, u8, u8)) -> Color

Construct an Color::Rgb from an (r, g, b) tuple.

Source§

impl From<u32> for Color

Source§

fn from(value: u32) -> Color

Construct an Color::Rgb from a packed 0xRRGGBB integer.

The high byte (alpha / 0xAA______) is ignored.

§Example
use slt::Color;

assert_eq!(Color::from(0xff6b6b), Color::Rgb(255, 107, 107));
Source§

impl FromStr for Color

Source§

fn from_str(s: &str) -> Result<Color, ColorParseError>

Parse a color from a string.

Accepts hex (#rgb, #rrggbb, or bare rrggbb / rgb without the leading #) and case-insensitive named colors ("red", "lightblue", "darkgray", "reset", …).

§Errors

Returns ColorParseError when the input matches no known form: ColorParseError::InvalidLength for a hex token of the wrong length, ColorParseError::InvalidHexDigit for non-hex digits in a #-prefixed token, and ColorParseError::Unknown otherwise.

§Example
use slt::Color;

assert_eq!("#ff6b6b".parse::<Color>(), Ok(Color::Rgb(255, 107, 107)));
assert_eq!("ff6b6b".parse::<Color>(), Ok(Color::Rgb(255, 107, 107)));
assert_eq!("#abc".parse::<Color>(), Ok(Color::Rgb(170, 187, 204)));
assert_eq!("cyan".parse::<Color>(), Ok(Color::Cyan));
assert!("nope".parse::<Color>().is_err());
Source§

type Err = ColorParseError

The associated error which can be returned from parsing.
Source§

impl Hash for Color

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Color

Source§

fn eq(&self, other: &Color) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Color

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize as a human-friendly string token (#rrggbb, a named color, or indexed:N) so theme files stay hand-editable and round-trip.

Source§

impl Copy for Color

Source§

impl Eq for Color

Source§

impl StructuralPartialEq for Color

Auto Trait Implementations§

§

impl Freeze for Color

§

impl RefUnwindSafe for Color

§

impl Send for Color

§

impl Sync for Color

§

impl Unpin for Color

§

impl UnsafeUnpin for Color

§

impl UnwindSafe for Color

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,