Skip to main content

Color

Enum Color 

Source
#[non_exhaustive]
pub enum Color { Default, Ansi(AnsiColor), Indexed(u8), Rgb { r: u8, g: u8, b: u8, }, }
Expand description

Represents a color in the terminal grid.

§Examples

use retroglyph_core::color::Color;

let named = Color::GREEN;
let rgb = Color::Rgb { r: 255, g: 0, b: 0 };
let indexed = Color::Indexed(42);
assert_ne!(named, rgb);
assert_ne!(rgb, indexed);

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.
§

Default

Backend’s default foreground/background color.

This tells the rendering backend to use the terminal’s configured default colors (e.g., the user’s background color preference).

§

Ansi(AnsiColor)

One of the 16 standard ANSI colors.

Use these to respect the user’s terminal theme.

§

Indexed(u8)

256-color palette index.

§

Rgb

24-bit RGB color.

Use this for exact color matching regardless of terminal settings.

Fields

§r: u8

Red channel.

§g: u8

Green channel.

§b: u8

Blue channel.

Implementations§

Source§

impl Color

Source

pub const BLACK: Self

Standard Black (ANSI).

Source

pub const RED: Self

Standard Red (ANSI).

Source

pub const GREEN: Self

Standard Green (ANSI).

Source

pub const YELLOW: Self

Standard Yellow (ANSI).

Source

pub const BLUE: Self

Standard Blue (ANSI).

Source

pub const MAGENTA: Self

Standard Magenta (ANSI).

Source

pub const CYAN: Self

Standard Cyan (ANSI).

Source

pub const WHITE: Self

Standard White (ANSI).

Source

pub const BRIGHT_BLACK: Self

Bright Black / dark grey (ANSI).

Source

pub const BRIGHT_RED: Self

Bright Red (ANSI).

Source

pub const BRIGHT_GREEN: Self

Bright Green (ANSI).

Source

pub const BRIGHT_YELLOW: Self

Bright Yellow (ANSI).

Source

pub const BRIGHT_BLUE: Self

Bright Blue (ANSI).

Source

pub const BRIGHT_MAGENTA: Self

Bright Magenta (ANSI).

Source

pub const BRIGHT_CYAN: Self

Bright Cyan (ANSI).

Source

pub const BRIGHT_WHITE: Self

Bright White (ANSI).

Source

pub const fn resolve_rgb(self, default: (u8, u8, u8)) -> (u8, u8, u8)

Resolves this color to a concrete 24-bit (r, g, b) triple, substituting default for Color::Default.

This is the canonical color-to-RGB resolution every graphical backend shares, so that a glyph drawn through the CPU rasterizer (retroglyph-software) and the GPU atlas (retroglyph-gl) comes out the same pixel color:

  • Rgb passes through unchanged.
  • Ansi resolves through AnsiColor::to_rgb (the one canonical ANSI palette).
  • Indexed resolves through the 256-color palette (16 ANSI + 6×6×6 cube
    • grayscale ramp).
  • Default (and any future non-exhaustive variant this crate can’t yet resolve) returns default, which the caller picks per channel (foreground vs background).

Terminal backends do not use this: they emit ANSI/indexed colors as-is and let the terminal apply the user’s theme. It exists specifically for pixel/GPU backends that must produce real RGB.

Source

pub fn to_srgb(self) -> Option<Srgb>

Converts an Rgb variant to gem::space::Srgb.

Returns None for non-RGB variants (Default, Ansi, Indexed).

Source

pub fn from_srgb(srgb: Srgb) -> Self

Constructs an Rgb variant from a gem::space::Srgb color.

Channels are clamped to [0.0, 1.0] and rounded to the nearest u8 (ties away from zero), via gem::rgb::Rgb888’s own Srgb conversion, the same round-to-nearest rule every other integer channel operation in this crate follows (see tests/rounding_conformance.rs).

Source

pub fn lerp(a: Self, b: Self, t: f32) -> Self

Linearly interpolates between two colors, always returning a concrete Rgb result.

Both inputs are resolved to (r, g, b) via Color::resolve_rgb before blending, so non-Rgb variants (Ansi, Indexed) contribute their real color rather than being skipped. Color::Default has no intrinsic RGB value, so it falls back to (0, 0, 0) when it appears as a and (255, 255, 255) when it appears as b.

Source

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

Lightens a color by amount (0.0 = no change, 1.0 = white).

Non-Rgb variants are resolved to (r, g, b) via Color::resolve_rgb before the transform is applied, rather than being returned unchanged. Color::Default has no intrinsic RGB value, so it resolves to (0, 0, 0).

Source

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

Darkens a color by amount (0.0 = no change, 1.0 = black).

Non-Rgb variants are resolved to (r, g, b) via Color::resolve_rgb before the transform is applied, rather than being returned unchanged. Color::Default has no intrinsic RGB value, so it resolves to (0, 0, 0).

Source

pub fn saturate(self, amount: f32) -> Self

Increases saturation of a color by amount (0.0–1.0).

Non-Rgb variants are resolved to (r, g, b) via Color::resolve_rgb before the transform is applied, rather than being returned unchanged. Color::Default has no intrinsic RGB value, so it resolves to (0, 0, 0).

Source

pub fn desaturate(self, amount: f32) -> Self

Decreases saturation of a color by amount (0.0–1.0).

Non-Rgb variants are resolved to (r, g, b) via Color::resolve_rgb before the transform is applied, rather than being returned unchanged. Color::Default has no intrinsic RGB value, so it resolves to (0, 0, 0).

Source

pub fn complement(self) -> Self

Returns the complementary color (hue shifted by 180 degrees).

Non-Rgb variants are resolved to (r, g, b) via Color::resolve_rgb before the transform is applied, rather than being returned unchanged. Color::Default has no intrinsic RGB value, so it resolves to (0, 0, 0).

Source

pub fn to_indexed(self) -> Self

Quantizes an RGB color to the nearest entry in the standard 256-color palette, by perceptual (Oklab) distance.

Equivalent to to_indexed_with(Quantize::Perceptual); see there for the full contract and for the euclidean alternative.

§Examples
use retroglyph_core::color::Color;

let black = Color::Rgb { r: 0, g: 0, b: 0 };
assert_eq!(black.to_indexed(), Color::Indexed(0));

// Non-RGB colors pass through unchanged.
assert_eq!(Color::Default.to_indexed(), Color::Default);

Backends that render to terminals without full RGB support can call this method to downgrade colors before emitting them; retroglyph-core never downgrades colors on its own. See Color::to_ansi to quantize to the smaller 16-color ANSI palette.

Source

pub fn to_indexed_with(self, metric: Quantize) -> Self

Quantizes an RGB color to the nearest entry in the standard 256-color palette, under metric.

  • Color::Rgb inputs are converted to the nearest 256-color palette index (0–255), searching the 16 ANSI colors (0–15), the 6×6×6 color cube (16–231), and the grayscale ramp (232–255).
  • Color::Default, Color::Ansi, and Color::Indexed are returned unchanged: this method only downgrades Rgb colors.
  • Ties (multiple equidistant palette entries) are resolved by preferring the lower index.
§Examples
use retroglyph_core::color::{Color, Quantize};

let salmon = Color::Rgb { r: 250, g: 128, b: 114 };
assert_eq!(salmon.to_indexed_with(Quantize::Perceptual), Color::Indexed(210));
assert_eq!(salmon.to_indexed_with(Quantize::Euclidean), Color::Indexed(209));
Source

pub fn to_ansi(self) -> Self

Quantizes an RGB color to the nearest of the 16 standard ANSI palette colors, by perceptual (Oklab) distance.

Equivalent to to_ansi_with(Quantize::Perceptual); see there for the full contract and for the euclidean alternative.

§Examples
use retroglyph_core::color::{AnsiColor, Color};

let pure_red = Color::Rgb { r: 255, g: 0, b: 0 };
assert_eq!(pure_red.to_ansi(), Color::Ansi(AnsiColor::BrightRed));

// Non-RGB colors pass through unchanged.
assert_eq!(Color::Default.to_ansi(), Color::Default);

Use this method when rendering to terminals limited to 16 colors, or when a caller otherwise needs to reduce color depth. See Color::to_indexed to quantize to the larger 256-color palette instead.

Source

pub fn to_ansi_with(self, metric: Quantize) -> Self

Quantizes an RGB color to the nearest of the 16 standard ANSI palette colors, under metric.

  • Color::Rgb inputs are converted to the nearest of the 16 standard ANSI colors.
  • Color::Default, Color::Ansi, and Color::Indexed are returned unchanged: this method only downgrades Rgb colors.
  • Ties (multiple equidistant palette entries) are resolved by preferring the lower ANSI index.
§Examples
use retroglyph_core::color::{AnsiColor, Color, Quantize};

// Euclidean RGB distance over-weights green, so this reddish brown lands on yellow.
let chocolate = Color::Rgb { r: 210, g: 105, b: 30 };
assert_eq!(chocolate.to_ansi_with(Quantize::Perceptual), Color::Ansi(AnsiColor::BrightRed));
assert_eq!(chocolate.to_ansi_with(Quantize::Euclidean), Color::Ansi(AnsiColor::Yellow));
Source§

impl Color

Source

pub fn from_named(name: &str) -> Option<Self>

Looks up a CSS named color by name (case-insensitive).

Supports all 147 CSS Color Module Level 4 named colors. Returns None for unrecognized names.

§Examples
use retroglyph_core::color::Color;

let gold = Color::from_named("gold");
assert_eq!(gold, Some(Color::Rgb { r: 255, g: 215, b: 0 }));

assert_eq!(Color::from_named("not-a-color"), None);
Source

pub fn from_hex(hex: &str) -> Option<Self>

Parses a CSS hex color string into an Rgb variant.

Accepts #rgb and #rrggbb formats (case-insensitive). Returns None for invalid input.

§Examples
use retroglyph_core::color::Color;

let c = Color::from_hex("#ff8000")?;
assert_eq!(c, Color::Rgb { r: 255, g: 128, b: 0 });

assert_eq!(Color::from_hex("not-color"), None);

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 Default for Color

Source§

fn default() -> Color

Returns the “default value” for a type. Read more
Source§

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

Available on crate feature serde only.
Source§

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

Deserializes through FromStr, so every string Display can produce, plus every alias FromStr additionally accepts (e.g. "BrightRed", "#f80"), round-trips.

Source§

impl Display for Color

Source§

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

Writes the string form FromStr parses back and, with the serde feature, Serialize writes: "default", an ANSI name like "bright-red", a palette index like "42", or #rrggbb hex.

§Examples
use retroglyph_core::color::{AnsiColor, Color};

assert_eq!(Color::Default.to_string(), "default");
assert_eq!(Color::Ansi(AnsiColor::BrightRed).to_string(), "bright-red");
assert_eq!(Color::Indexed(42).to_string(), "42");
assert_eq!(Color::Rgb { r: 255, g: 128, b: 0 }.to_string(), "#ff8000");
Source§

impl FromStr for Color

Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses the string form written by Display.

Hyphens, underscores, and spaces are ignored and matching is case-insensitive, so "BrightRed", "bright red", and "bright-red" all parse the same as the canonical "bright-red" that Display writes. "reset" is accepted as a synonym for "default". Accepts #rgb in addition to the #rrggbb Display writes.

§Examples
use retroglyph_core::color::{AnsiColor, Color};

assert_eq!("default".parse(), Ok(Color::Default));
assert_eq!("reset".parse(), Ok(Color::Default));
assert_eq!("bright-red".parse(), Ok(Color::Ansi(AnsiColor::BrightRed)));
assert_eq!("Bright Red".parse(), Ok(Color::Ansi(AnsiColor::BrightRed)));
assert_eq!("42".parse(), Ok(Color::Indexed(42)));
assert_eq!("#ff8000".parse(), Ok(Color::Rgb { r: 255, g: 128, b: 0 }));
assert_eq!("#f80".parse(), Ok(Color::Rgb { r: 255, g: 136, b: 0 }));
assert!("not-a-color".parse::<Color>().is_err());
Source§

type Err = ParseColorError

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,

Serializes through the Display round trip, e.g. "bright-red" or "#ff8000", rather than deriving a structural form: a hand-edited TOML/JSON theme file stays legible and isn’t coupled to this (#[non_exhaustive]) enum’s variant shape.

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<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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.
§

impl<C> WithAlpha for C
where C: Copy,

§

fn with_alpha_first<A>(self, alpha: A) -> AlphaFirst<A, Self>

Wraps self with alpha, storing alpha before the color in memory (see [AlphaFirst]).
§

fn with_alpha_last<A>(self, alpha: A) -> AlphaLast<A, Self>

Wraps self with alpha, storing alpha after the color in memory (see [AlphaLast]).
Source§

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