pub struct HexColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}
Expand description

An RGBA color.

See the module documentation for details.

Fields

r: u8

The red component of the color.

g: u8

The green component of the color.

b: u8

The blue component of the color.

a: u8

The alpha component of the color (0 is transparent, 255 is opaque).

Implementations

The minimum possible value. RGBA is (0, 0, 0, 0).

The maximum possible value. RGBA is (255, 255, 255, 255).

Solid black. RGBA is (0, 0, 0, 255).

Solid blue. RGBA is (0, 0, 255, 255).

Completely transparent. RGBA is (0, 0, 0, 0).

Solid cyan. RGBA is (0, 255, 255, 255).

Solid gray; American spelling of grey. RGBA is (128, 128, 128, 255).

Solid green. RGBA is (0, 0, 255, 255).

Solid grey; British spelling of gray. RGBA is (128, 128, 128, 255).

Solid magenta. RGBA is (255, 0, 255, 255).

Solid red. RGBA is (255, 0, 0, 255).

Solid white. RGBA is (255, 255, 255, 255).

Solid yellow. RGBA is (255, 255, 0, 255).

Constructs a new RGBA value.

For creating just an RGB value instead, use HexColor::rgb.

Examples
use hex_color::HexColor;

let red = HexColor::rgba(255, 0, 0, 255);
let translucent_red = HexColor::rgba(255, 0, 0, 128);

Constructs a new RGB value. (The alpha channel defaults to u8::MAX.)

For creating an RGBA value instead, use HexColor::rgba.

Examples
use hex_color::HexColor;

let aqua = HexColor::rgb(0, 255, 255);

Constructs a new achromatic RGB value. (The alpha channel defaults to u8::MAX.)

Examples
use hex_color::HexColor;

assert_eq!(HexColor::achromatic(128), HexColor::rgb(128, 128, 128));

Note: There is no “achromatic_alpha” constructor or similar method. Instead, it’s advised to chain HexColor::achromatic with HexColor::with_a:

use hex_color::HexColor;

let transparent_dark_gray = HexColor::achromatic(64).with_a(128);
assert_eq!(transparent_dark_gray, HexColor::rgba(64, 64, 64, 128));
Available on crate features rand and std only.

Constructs a new random RGB value through the rand crate.

To generate a random RGBA value, use HexColor::random_rgba instead.

Examples
use hex_color::HexColor;

println!("{}", HexColor::random_rgb());
Available on crate features rand and std only.

Constructs a new random RGBA value through the rand crate.

To generate a random RGB value, use HexColor::random_rgb instead.

Examples
use hex_color::HexColor;

println!("{:#}", HexColor::random_rgba());

Parses an RGB(A) hex code.

All parsing is case-insensitive. There are currently four parseable formats:

  • #RGB
  • #RRGGBB
  • #RGBA
  • #RRGGBBAA

To parse only a hexadecimal triplet, use parse_rgb. Otherwise, to parse only a hexadecimal quadruplet, use parse_rgba.

Errors
  • Empty when the input is empty.
  • InvalidFormat when the input is a malformed length or lacks a leading #. If you suspect there might be whitespace in the input, consider calling str::trim first.
  • InvalidDigit when the format seems correct but one of the characters is an invalid hexadecimal digit.
Examples
use hex_color::HexColor;

let red = HexColor::parse("#F00")?;
assert_eq!(red, HexColor::rgb(0xFF, 0x00, 0x00));

let plum = HexColor::parse("#DDA0DD")?;
assert_eq!(plum, HexColor::rgb(0xDD, 0xA0, 0xDD));

let opaque_cyan = HexColor::parse("#0FFF")?;
assert_eq!(opaque_cyan, HexColor::rgba(0x00, 0xFF, 0xFF, 0xFF));

let translucent_azure = HexColor::parse("#F0FFFF80")?;
assert_eq!(translucent_azure, HexColor::rgba(0xF0, 0xFF, 0xFF, 0x80));

Parses an RGB hex code.

All parsing is case-insensitive. There are currently two parseable formats:

  • #RGB
  • #RRGGBB

To parse only a hexadecimal quadruplet, use parse_rgba. Otherwise, to parse both hexadecimal triplets and quadruplets, use parse.

Errors
  • Empty when the input is empty.
  • InvalidFormat when the input is a malformed length or lacks a leading #. If you suspect there might be whitespace in the input, consider calling str::trim first.
  • InvalidDigit when the format seems correct but one of the characters is an invalid hexadecimal digit.

Note: a valid RGBA input will return an InvalidFormat. Use parse_rgba or parse instead if that behavior is not desired.

Examples
use hex_color::HexColor;

let yellow = HexColor::parse_rgb("#FF0")?;
assert_eq!(yellow, HexColor::rgb(0xFF, 0xFF, 0x00));

let hot_pink = HexColor::parse_rgb("#FF69B4")?;
assert_eq!(hot_pink, HexColor::rgb(0xFF, 0x69, 0xB4));

Parses an RGBA hex code.

All parsing is case-insensitive. There are currently two parseable formats:

  • #RGBA
  • #RRGGBBAA

To parse only a hexadecimal triplet, use parse_rgb. Otherwise, to parse both hexadecimal triplets and quadruplets, use parse.

Errors
  • Empty when the input is empty.
  • InvalidFormat when the input is a malformed length or lacks a leading #. If you suspect there might be whitespace in the input, consider calling str::trim first.
  • InvalidDigit when the format seems correct but one of the characters is an invalid hexadecimal digit.

Note: a valid RGB input (without an alpha value) will return an InvalidFormat. Use parse_rgb or parse instead if that behavior is not desired.

Examples
use hex_color::HexColor;

let transparent = HexColor::parse_rgba("#FFFF")?;
assert_eq!(transparent, HexColor::rgba(0xFF, 0xFF, 0xFF, 0xFF));

let translucent_gold = HexColor::parse_rgba("#FFD70080")?;
assert_eq!(translucent_gold, HexColor::rgba(0xFF, 0xD7, 0x00, 0x80));

Converts any u32 in the range 0x0000_0000..=0x00FF_FFFF to an RGB value.

To convert any u32 to an RGBA value, use from_u32 instead.

Panics

Panics if debug_assertions are enabled and the given value exceeds 0x00FF_FFFF.

Examples
use hex_color::HexColor;

let pale_green = HexColor::from_u24(0x98FB98);
assert_eq!(pale_green, HexColor::rgb(0x98, 0xFB, 0x98));

Converts any u32 to an RGBA value.

For converting a u32 in the range of 0x0000_0000..=0x00FF_FFFF to an RGB value, use from_u24 instead.

Examples
use hex_color::HexColor;

let navajo_white = HexColor::from_u32(0xFFDEADFF);
assert_eq!(navajo_white, HexColor::rgba(0xFF, 0xDE, 0xAD, 0xFF));

let translucent_violet = HexColor::from_u32(0xEE82EE80);
assert_eq!(translucent_violet, HexColor::rgba(0xEE, 0x82, 0xEE, 0x80));

Converts a HexColor into a u32 in the range 0x000000..=0xFFFFFF, discarding any possibly significant alpha value.

To convert this HexColor into a u32 containing the alpha value as well, use to_u32.

Examples
use hex_color::HexColor;

let misty_rose = HexColor::rgb(0xFF, 0xE4, 0xE1);
assert_eq!(misty_rose.to_u24(), 0xFFE4E1);

// Again, note that the alpha value is lost in this conversion:
let translucent_navy = HexColor::rgba(0x00, 0x00, 0x80, 0x80);
assert_eq!(translucent_navy.to_u24(), 0x000080);

Converts a HexColor into a u32.

To convert the HexColor into a u32 with only the red, green, and blue channels packed, use to_u24.

Examples
use hex_color::HexColor;

let sea_shell = HexColor::rgb(0xFF, 0xF5, 0xEE);
assert_eq!(sea_shell.to_u32(), 0xFFF5EEFF);

// Unlike `to_u24` the alpha value is preserved
let translucent_navy = HexColor::rgba(0x00, 0x00, 0x80, 0x80);
assert_eq!(translucent_navy.to_u32(), 0x00008080);

Converts a HexColor into [r, g, b, a].

Examples
use hex_color::HexColor;

let color = HexColor::from_u32(0x89AB_CDEF);
assert_eq!(color.to_be_bytes(), [0x89, 0xAB, 0xCD, 0xEF]);

Converts a HexColor into [a, b, g, r].

Examples
use hex_color::HexColor;

let color = HexColor::from_u32(0x89AB_CDEF);
assert_eq!(color.to_le_bytes(), [0xEF, 0xCD, 0xAB, 0x89]);

Constructs a new HexColor derived from self with the red component of r.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::MIN.with_r(255), HexColor::rgba(255, 0, 0, 0));

Constructs a new HexColor derived from self with the green component of g.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::MIN.with_g(255), HexColor::rgba(0, 255, 0, 0));

Constructs a new HexColor derived from self with the blue component of b.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::MIN.with_b(255), HexColor::rgba(0, 0, 255, 0));

Constructs a new HexColor derived from self with the alpha component of a.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::MIN.with_a(255), HexColor::rgba(0, 0, 0, 255));

Deconstructs a HexColor into a tuple of its components: (r, g, b, a).

This primarily helps in cleaner deconstruction of HexColor instances, especially if the variable bindings aren’t the same as the struct's fields.

Examples

Basic usage:

use hex_color::HexColor;

let slate_blue = HexColor::from_u24(0x6A5ACD);
let (red, green, blue, alpha) = slate_blue.split();

For contrast, here’s what it would look like otherwise; it’s not terrible, but en masse, it’s subjectively annoying:

use hex_color::HexColor;

let slate_blue = HexColor::from_u24(0x6A5ACD);
let HexColor {
    r: red,
    g: green,
    b: blue,
    a: alpha,
} = slate_blue;

Adds two colors together.

Each component is added separately. The alpha component is ignored entirely, always returning an RGB color (where alpha is the default u8::MAX).

Panics

Panics if any overflow occurs.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::BLUE.add(HexColor::GREEN), HexColor::CYAN);
assert_eq!(HexColor::RED.add(HexColor::BLUE), HexColor::MAGENTA);
assert_eq!(HexColor::GREEN.add(HexColor::RED), HexColor::YELLOW);

Checked color addition. Computes self + rhs, returning None if overflow occurred.

Examples
use hex_color::HexColor;

let almost_white = HexColor::achromatic(254);
let one = HexColor::achromatic(1);

assert_eq!(almost_white.checked_add(one), Some(HexColor::WHITE));
assert_eq!(HexColor::WHITE.checked_add(one), None);

Calculates self + rhs.

Returns a tuple of the addition along with a boolean indicating whether any arithmetic overflow would occur. If an overflow would have occurred, then the wrapped value is returned.

Examples
use hex_color::HexColor;

let almost_white = HexColor::achromatic(254);
let one = HexColor::achromatic(1);

assert_eq!(
    almost_white.overflowing_add(one),
    (HexColor::WHITE, false),
);
assert_eq!(
    HexColor::WHITE.overflowing_add(one),
    (HexColor::BLACK, true),
);

Saturating color addition. Computes self + rhs, saturating at the numeric bounds instead of overflowing.

Examples
use hex_color::HexColor;

// Even though the green component should exceed 255, it saturates at
// 255 instead:
assert_eq!(
    HexColor::YELLOW.saturating_add(HexColor::CYAN),
    HexColor::WHITE,
);

Wrapping (modular) addition. Computes self + rhs, wrapping around the boundary of u8.

Examples
use hex_color::HexColor;

let almost_white = HexColor::achromatic(254);
let one = HexColor::achromatic(1);

assert_eq!(almost_white.wrapping_add(one), HexColor::WHITE);
assert_eq!(HexColor::WHITE.wrapping_add(one), HexColor::BLACK);

Subtracts one color from another.

Each component is subtracted separately. The alpha component is ignored entirely, always returning an RGB color (where alpha is the default u8::MAX).

Panics

Panics if any overflow occurs.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::MAGENTA.sub(HexColor::BLUE), HexColor::RED);
assert_eq!(HexColor::YELLOW.sub(HexColor::RED), HexColor::GREEN);
assert_eq!(HexColor::CYAN.sub(HexColor::GREEN), HexColor::BLUE);

Subtracts n from the HexColor’s red, green, and blue components.

Panics

Panics if overflow occurs.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::WHITE.sub_scalar(255), HexColor::BLACK);

Checked color subtraction. Computes self - rhs, returning None if overflow occurred.

Examples
use hex_color::HexColor;

let almost_black = HexColor::achromatic(1);
let one = HexColor::achromatic(1);

assert_eq!(almost_black.checked_sub(one), Some(HexColor::BLACK));
assert_eq!(HexColor::BLACK.checked_sub(one), None);

Calculates self - rhs.

Returns a tuple of the subtraction along with a boolean indicating whether any arithmetic overflow would occur. If an overflow would have occurred, then the wrapped value is returned.

Examples
use hex_color::HexColor;

let almost_black = HexColor::achromatic(1);
let one = HexColor::achromatic(1);

assert_eq!(
    almost_black.overflowing_sub(one),
    (HexColor::BLACK, false),
);
assert_eq!(
    HexColor::BLACK.overflowing_sub(one),
    (HexColor::WHITE, true),
);

Saturating color subtraction. Computes self - rhs, saturating at the numeric bounds instead of overflowing.

Examples
use hex_color::HexColor;

// Even though the red component should overflow, it saturates at 0
// instead:
assert_eq!(
    HexColor::CYAN.saturating_sub(HexColor::YELLOW),
    HexColor::BLUE,
);

Wrapping (modular) subtraction. Computes self - rhs, wrapping around the boundary of u8.

Examples
use hex_color::HexColor;

let almost_black = HexColor::achromatic(1);
let one = HexColor::achromatic(1);

assert_eq!(almost_black.wrapping_sub(one), HexColor::BLACK);
assert_eq!(HexColor::BLACK.wrapping_sub(one), HexColor::WHITE);

Multiplies two colors together.

Each component is multiplied separately. The alpha component is ignored entirely, always returning an RGB color (where alpha is the default u8::MAX).

Panics

Panics if any overflow occurs.

Examples
use hex_color::HexColor;

let a = HexColor::rgb(1, 2, 3);
let b = HexColor::rgb(4, 5, 6);

assert_eq!(a.mul(b), HexColor::rgb(4, 10, 18));

Checked color multiplication. Computes self * rhs, returning None if overflow occurred.

Examples
use hex_color::HexColor;

assert_eq!(
    HexColor::achromatic(5).checked_mul(HexColor::achromatic(2)),
    Some(HexColor::achromatic(10)),
);
assert_eq!(
    HexColor::MAX.checked_mul(HexColor::achromatic(2)),
    None,
);

Calculates self * rhs.

Returns a tuple of the multiplication along with a boolean indicating whether any arithmetic overflow would occur. If an overflow would have occurred, then the wrapped value is returned.

Examples
use hex_color::HexColor;

assert_eq!(
    HexColor::achromatic(5).overflowing_mul(HexColor::achromatic(2)),
    (HexColor::achromatic(10), false),
);
assert_eq!(
    HexColor::achromatic(200).overflowing_mul(HexColor::achromatic(2)),
    (HexColor::achromatic(144), true),
);

Saturating color multiplication. Computes self * rhs, saturating at the numeric bounds instead of overflowing.

Examples
use hex_color::HexColor;

assert_eq!(
    HexColor::achromatic(5).saturating_mul(HexColor::achromatic(2)),
    HexColor::achromatic(10),
);
assert_eq!(
    HexColor::achromatic(200).saturating_mul(HexColor::achromatic(2)),
    HexColor::achromatic(255),
);

Wrapping (modular) multiplication. Computes self * rhs, wrapping around at the boundary of the type.

Examples
use hex_color::HexColor;

assert_eq!(
    HexColor::achromatic(5).wrapping_mul(HexColor::achromatic(2)),
    HexColor::achromatic(10),
);
assert_eq!(
    HexColor::achromatic(200).wrapping_mul(HexColor::achromatic(2)),
    HexColor::achromatic(144),
);

Divides one color with another.

Each component is divided separately. The alpha component is ignored entirely, always returning an RGB color (where alpha is the default u8::MAX).

Panics

Panics if any component is divided by zero.

Examples
use hex_color::HexColor;

let a = HexColor::rgb(128, 64, 32);
let b = HexColor::rgb(2, 4, 8);

assert_eq!(a.div(b), HexColor::rgb(64, 16, 4));

Checked color division. Computes self / rhs, returning None if any component of rhs is zero.

Examples
use hex_color::HexColor;

assert_eq!(
    HexColor::achromatic(128).checked_div(HexColor::achromatic(2)),
    Some(HexColor::achromatic(64)),
);
assert_eq!(
    HexColor::WHITE.checked_div(HexColor::achromatic(0)),
    None,
);

Linearly inverts the HexColor.

Examples
use hex_color::HexColor;

assert_eq!(HexColor::RED.invert(), HexColor::CYAN);

Trait Implementations

The resulting type after applying the + operator.

Performs the + operation. Read more

Performs the += operation. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

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

Deserializes a HexColor from a string using the same rules as HexColor::parse.

To strictly deserialize either an RGB or RGBA value from a string, use rgb::deserialize or rgba::deserialize respectively.

Examples
use hex_color::HexColor;
use serde::Deserialize;
use serde_json::json;

#[derive(Debug, PartialEq, Deserialize)]
struct Color {
    name: String,
    value: HexColor,
}

let saddle_brown = json!({
    "name": "Saddle Brown",
    "value": "#8B4513",
});
assert_eq!(
    serde_json::from_value::<Color>(saddle_brown)?,
    Color {
        name: String::from("Saddle Brown"),
        value: HexColor::rgb(139, 69, 19),
    },
);

let transparent_cyan = json!({
    "name": "Transparent Cyan",
    "value": "#00FFFF80",
});
assert_eq!(
    serde_json::from_value::<Color>(transparent_cyan)?,
    Color {
        name: String::from("Transparent Cyan"),
        value: HexColor::rgba(0, 255, 255, 128),
    },
);

Display the HexColor as a hexadecimal value.

Examples
use hex_color::HexColor;

let rgba = HexColor::rgba(16, 32, 48, 64);

// By default it displays only a typical uppercase hexadecimal triplet
// even if the alpha is not fully opaque:
assert_eq!(format!("{rgba}"), "#102030");

// To display the alpha component, too, use the alternate flag:
assert_eq!(format!("{rgba:#}"), "#10203040");

Generate a random value of T, using rng as the source of randomness.

Create an iterator that generates random values of T, using rng as the source of randomness. Read more

Create a distribution of values of ‘S’ by mapping the output of Self through the closure F Read more

The resulting type after applying the / operator.

Performs the / operation. Read more

Performs the /= operation. Read more

Constructs a new u32 from a HexColor via HexColor::to_u32.

Constructs a new HexColor from a u32 via HexColor::from_u32.

Semantically identical to HexColor::parse. For more information, refer to that function’s documentation.

The associated error which can be returned from parsing.

Feeds this value into the given Hasher. Read more

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

The resulting type after applying the * operator.

Performs the * operation. Read more

Performs the *= operation. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Serializes the HexColor as a string.

By default, HexColor values get serialized in the form of #RRGGBB strings when the alpha value is set to u8::MAX, or completely opaque. However, if any transparency exists, they are serialized in the form of #RRGGBBAA strings.

To strictly enforce getting serialized as an RGB or RGBA string, use rgb::serialize or rgba::serialize respectively. In fact, using either of these options is highly suggested for more normalized results.

Examples
use hex_color::HexColor;
use serde::Serialize;
use serde_json::json;

#[derive(Serialize)]
struct Color {
    name: &'static str,
    value: HexColor,
}

let orange = Color {
    name: "Orange",
    value: HexColor::rgb(255, 165, 0),
};
assert_eq!(
    serde_json::to_value(orange)?,
    json!({
        "name": "Orange",
        "value": "#FFA500",
    }),
);

let transparent_navy = Color {
    name: "Transparent Navy",
    value: HexColor::rgba(0, 0, 128, 128),
};
assert_eq!(
    serde_json::to_value(transparent_navy)?,
    json!({
        "name": "Transparent Navy",
        "value": "#00008080",
    }),
);

The resulting type after applying the - operator.

Performs the - operation. Read more

Performs the -= operation. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.

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

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

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.