Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/Firefox/third_party/rust/cssparser/src/   (Firefox Browser Version 136.0.1©)  Datei vom 10.2.2025 mit Größe 12 kB image not shown  

Quelle  color.rs

  Sprache: Rust
 

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */


//! General color-parsing utilities, independent on the specific color storage and parsing
//! implementation.
//!
//! For a more complete css-color implementation take a look at cssparser-color crate, or at
//! Gecko's color module.

// Allow text like <color> in docs.
#![allow(rustdoc::invalid_html_tags)]

/// The opaque alpha value of 1.0.
pub const OPAQUE: f32 = 1.0;

use crate::{BasicParseError, Parser, ToCss, Token};
use std::fmt;

/// Clamp a 0..1 number to a 0..255 range to u8.
///
/// Whilst scaling by 256 and flooring would provide
/// an equal distribution of integers to percentage inputs,
/// this is not what Gecko does so we instead multiply by 255
/// and round (adding 0.5 and flooring is equivalent to rounding)
///
/// Chrome does something similar for the alpha value, but not
/// the rgb values.
///
/// See <https://bugzilla.mozilla.org/show_bug.cgi?id=1340484>
///
/// Clamping to 256 and rounding after would let 1.0 map to 256, and
/// `256.0_f32 as u8` is undefined behavior:
///
/// <https://github.com/rust-lang/rust/issues/10184>
#[inline]
pub fn clamp_unit_f32(val: f32) -> u8 {
    clamp_floor_256_f32(val * 255.)
}

/// Round and clamp a single number to a u8.
#[inline]
pub fn clamp_floor_256_f32(val: f32) -> u8 {
    val.round().clamp(0., 255.) as u8
}

/// Serialize the alpha copmonent of a color according to the specification.
/// <https://drafts.csswg.org/css-color-4/#serializing-alpha-values>
#[inline]
pub fn serialize_color_alpha(
    dest: &mut impl fmt::Write,
    alpha: Option<f32>,
    legacy_syntax: bool,
) -> fmt::Result {
    let alpha = match alpha {
        None => return dest.write_str(" / none"),
        Some(a) => a,
    };

    // If the alpha component is full opaque, don't emit the alpha value in CSS.
    if alpha == OPAQUE {
        return Ok(());
    }

    dest.write_str(if legacy_syntax { ", " } else { " / " })?;

    // Try first with two decimal places, then with three.
    let mut rounded_alpha = (alpha * 100.).round() / 100.;
    if clamp_unit_f32(rounded_alpha) != clamp_unit_f32(alpha) {
        rounded_alpha = (alpha * 1000.).round() / 1000.;
    }

    rounded_alpha.to_css(dest)
}

/// A Predefined color space specified in:
/// <https://drafts.csswg.org/css-color-4/#predefined>
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
pub enum PredefinedColorSpace {
    /// <https://drafts.csswg.org/css-color-4/#predefined-sRGB>
    Srgb,
    /// <https://drafts.csswg.org/css-color-4/#predefined-sRGB-linear>
    SrgbLinear,
    /// <https://drafts.csswg.org/css-color-4/#predefined-display-p3>
    DisplayP3,
    /// <https://drafts.csswg.org/css-color-4/#predefined-a98-rgb>
    A98Rgb,
    /// <https://drafts.csswg.org/css-color-4/#predefined-prophoto-rgb>
    ProphotoRgb,
    /// <https://drafts.csswg.org/css-color-4/#predefined-rec2020>
    Rec2020,
    /// <https://drafts.csswg.org/css-color-4/#predefined-xyz>
    XyzD50,
    /// <https://drafts.csswg.org/css-color-4/#predefined-xyz>
    XyzD65,
}

impl PredefinedColorSpace {
    /// Parse a PredefinedColorSpace from the given input.
    pub fn parse<'i>(input: &mut Parser<'i, '_>) -> Result<Self, BasicParseError<'i>> {
        let location = input.current_source_location();

        let ident = input.expect_ident()?;
        Ok(match_ignore_ascii_case! { ident,
            "srgb" => Self::Srgb,
            "srgb-linear" => Self::SrgbLinear,
            "display-p3" => Self::DisplayP3,
            "a98-rgb" => Self::A98Rgb,
            "prophoto-rgb" => Self::ProphotoRgb,
            "rec2020" => Self::Rec2020,
            "xyz-d50" => Self::XyzD50,
            "xyz" | "xyz-d65" => Self::XyzD65,
            _ => return Err(location.new_basic_unexpected_token_error(Token::Ident(ident.clone()))),
        })
    }
}

impl ToCss for PredefinedColorSpace {
    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
    where
        W: fmt::Write,
    {
        dest.write_str(match self {
            Self::Srgb => "srgb",
            Self::SrgbLinear => "srgb-linear",
            Self::DisplayP3 => "display-p3",
            Self::A98Rgb => "a98-rgb",
            Self::ProphotoRgb => "prophoto-rgb",
            Self::Rec2020 => "rec2020",
            Self::XyzD50 => "xyz-d50",
            Self::XyzD65 => "xyz-d65",
        })
    }
}

/// Parse a color hash, without the leading '#' character.
#[allow(clippy::result_unit_err)]
#[inline]
pub fn parse_hash_color(value: &[u8]) -> Result<(u8, u8, u8, f32), ()> {
    Ok(match value.len() {
        8 => (
            from_hex(value[0])? * 16 + from_hex(value[1])?,
            from_hex(value[2])? * 16 + from_hex(value[3])?,
            from_hex(value[4])? * 16 + from_hex(value[5])?,
            (from_hex(value[6])? * 16 + from_hex(value[7])?) as f32 / 255.0,
        ),
        6 => (
            from_hex(value[0])? * 16 + from_hex(value[1])?,
            from_hex(value[2])? * 16 + from_hex(value[3])?,
            from_hex(value[4])? * 16 + from_hex(value[5])?,
            OPAQUE,
        ),
        4 => (
            from_hex(value[0])? * 17,
            from_hex(value[1])? * 17,
            from_hex(value[2])? * 17,
            (from_hex(value[3])? * 17as f32 / 255.0,
        ),
        3 => (
            from_hex(value[0])? * 17,
            from_hex(value[1])? * 17,
            from_hex(value[2])? * 17,
            OPAQUE,
        ),
        _ => return Err(()),
    })
}

ascii_case_insensitive_phf_map! {
    named_colors -> (u8, u8, u8) = {
        "black" => (000),
        "silver" => (192192192),
        "gray" => (128128128),
        "white" => (255255255),
        "maroon" => (12800),
        "red" => (25500),
        "purple" => (1280128),
        "fuchsia" => (2550255),
        "green" => (01280),
        "lime" => (02550),
        "olive" => (1281280),
        "yellow" => (2552550),
        "navy" => (00128),
        "blue" => (00255),
        "teal" => (0128128),
        "aqua" => (0255255),

        "aliceblue" => (240248255),
        "antiquewhite" => (250235215),
        "aquamarine" => (127255212),
        "azure" => (240255255),
        "beige" => (245245220),
        "bisque" => (255228196),
        "blanchedalmond" => (255235205),
        "blueviolet" => (13843226),
        "brown" => (1654242),
        "burlywood" => (222184135),
        "cadetblue" => (95158160),
        "chartreuse" => (1272550),
        "chocolate" => (21010530),
        "coral" => (25512780),
        "cornflowerblue" => (100149237),
        "cornsilk" => (255248220),
        "crimson" => (2202060),
        "cyan" => (0255255),
        "darkblue" => (00139),
        "darkcyan" => (0139139),
        "darkgoldenrod" => (18413411),
        "darkgray" => (169169169),
        "darkgreen" => (01000),
        "darkgrey" => (169169169),
        "darkkhaki" => (189183107),
        "darkmagenta" => (1390139),
        "darkolivegreen" => (8510747),
        "darkorange" => (2551400),
        "darkorchid" => (15350204),
        "darkred" => (13900),
        "darksalmon" => (233150122),
        "darkseagreen" => (143188143),
        "darkslateblue" => (7261139),
        "darkslategray" => (477979),
        "darkslategrey" => (477979),
        "darkturquoise" => (0206209),
        "darkviolet" => (1480211),
        "deeppink" => (25520147),
        "deepskyblue" => (0191255),
        "dimgray" => (105105105),
        "dimgrey" => (105105105),
        "dodgerblue" => (30144255),
        "firebrick" => (1783434),
        "floralwhite" => (255250240),
        "forestgreen" => (3413934),
        "gainsboro" => (220220220),
        "ghostwhite" => (248248255),
        "gold" => (2552150),
        "goldenrod" => (21816532),
        "greenyellow" => (17325547),
        "grey" => (128128128),
        "honeydew" => (240255240),
        "hotpink" => (255105180),
        "indianred" => (2059292),
        "indigo" => (750130),
        "ivory" => (255255240),
        "khaki" => (240230140),
        "lavender" => (230230250),
        "lavenderblush" => (255240245),
        "lawngreen" => (1242520),
        "lemonchiffon" => (255250205),
        "lightblue" => (173216230),
        "lightcoral" => (240128128),
        "lightcyan" => (224255255),
        "lightgoldenrodyellow" => (250250210),
        "lightgray" => (211211211),
        "lightgreen" => (144238144),
        "lightgrey" => (211211211),
        "lightpink" => (255182193),
        "lightsalmon" => (255160122),
        "lightseagreen" => (32178170),
        "lightskyblue" => (135206250),
        "lightslategray" => (119136153),
        "lightslategrey" => (119136153),
        "lightsteelblue" => (176196222),
        "lightyellow" => (255255224),
        "limegreen" => (5020550),
        "linen" => (250240230),
        "magenta" => (2550255),
        "mediumaquamarine" => (102205170),
        "mediumblue" => (00205),
        "mediumorchid" => (18685211),
        "mediumpurple" => (147112219),
        "mediumseagreen" => (60179113),
        "mediumslateblue" => (123104238),
        "mediumspringgreen" => (0250154),
        "mediumturquoise" => (72209204),
        "mediumvioletred" => (19921133),
        "midnightblue" => (2525112),
        "mintcream" => (245255250),
        "mistyrose" => (255228225),
        "moccasin" => (255228181),
        "navajowhite" => (255222173),
        "oldlace" => (253245230),
        "olivedrab" => (10714235),
        "orange" => (2551650),
        "orangered" => (255690),
        "orchid" => (218112214),
        "palegoldenrod" => (238232170),
        "palegreen" => (152251152),
        "paleturquoise" => (175238238),
        "palevioletred" => (219112147),
        "papayawhip" => (255239213),
        "peachpuff" => (255218185),
        "peru" => (20513363),
        "pink" => (255192203),
        "plum" => (221160221),
        "powderblue" => (176224230),
        "rebeccapurple" => (10251153),
        "rosybrown" => (188143143),
        "royalblue" => (65105225),
        "saddlebrown" => (1396919),
        "salmon" => (250128114),
        "sandybrown" => (24416496),
        "seagreen" => (4613987),
        "seashell" => (255245238),
        "sienna" => (1608245),
        "skyblue" => (135206235),
        "slateblue" => (10690205),
        "slategray" => (112128144),
        "slategrey" => (112128144),
        "snow" => (255250250),
        "springgreen" => (0255127),
        "steelblue" => (70130180),
        "tan" => (210180140),
        "thistle" => (216191216),
        "tomato" => (2559971),
        "turquoise" => (64224208),
        "violet" => (238130238),
        "wheat" => (245222179),
        "whitesmoke" => (245245245),
        "yellowgreen" => (15420550),
    }
}

/// Returns the named color with the given name.
/// <https://drafts.csswg.org/css-color-4/#typedef-named-color>
#[allow(clippy::result_unit_err)]
#[inline]
pub fn parse_named_color(ident: &str) -> Result<(u8, u8, u8), ()> {
    named_colors::get(ident).copied().ok_or(())
}

/// Returns an iterator over all named CSS colors.
/// <https://drafts.csswg.org/css-color-4/#typedef-named-color>
#[inline]
pub fn all_named_colors() -> impl Iterator<Item = (&'static str, (u8, u8, u8))> {
    named_colors::entries().map(|(k, v)| (*k, *v))
}

#[inline]
fn from_hex(c: u8) -> Result<u8, ()> {
    match c {
        b'0'..=b'9' => Ok(c - b'0'),
        b'a'..=b'f' => Ok(c - b'a' + 10),
        b'A'..=b'F' => Ok(c - b'A' + 10),
        _ => Err(()),
    }
}

Messung V0.5 in Prozent
C=88 H=97 G=92

¤ Dauer der Verarbeitung: 0.14 Sekunden  (vorverarbeitet am  2026-06-19) ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

PVS Prover

Isabelle Prover

NIST Cobol Testsuite

Cephes Mathematical Library

Vienna Development Method

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.