tonhowtf/omniget · error

cor inválida

Error message

cor inválida: {raw}

What it means

Raised by the `byte` closure inside `parse_hex_color` when a 2-character hex slice cannot be parsed as a base-16 u8. It fires while decoding 6- or 8-digit hex color components in the img_bg tool's background color option.

Solutions

  1. Provide a valid hex color string: exactly 3, 6, or 8 hex digits ([0-9a-fA-F]) after an optional '#'.
  2. Sanitize the value at the UI/config layer with a regex like ^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$ before calling.
  3. Use a color picker component that emits well-formed hex values instead of free text.

Example fix

// before
let bg = parse_hex_color("#GG2255")?; // panics into: cor inválida: #GG2255
// after
let raw = "#GG2255";
let valid = regex::Regex::new(r"^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$").unwrap();
if !valid.is_match(raw) { eprintln!("use um hex válido, ex: #FF00AA"); return Ok(()); }
let bg = parse_hex_color(raw)?;
Defensive patterns

Strategy: validation

Validate before calling

fn is_valid_hex6(s: &str) -> bool {
    let s = s.trim().trim_start_matches('#');
    s.len() == 6 && s.chars().all(|c| c.is_ascii_hexdigit())
}

Type guard

fn is_hex_color(raw: &str) -> bool {
    let s = raw.trim().trim_start_matches('#');
    matches!(s.len(), 3 | 6 | 8) && s.chars().all(|c| c.is_ascii_hexdigit())
}

Try / catch

match parse_hex_color(raw) {
    Ok(Some(color)) => apply(color),
    Ok(None) => {}, // empty means "keep default"
    Err(e) => eprintln!("use hex como #RRGGBB: {e}"),
}

Prevention

When it happens

Trigger: Calling `parse_hex_color` with a string whose length is 6 or 8 (after trimming '#' and whitespace) but containing non-hex characters, e.g. "#GGHHII" or "12345z8".

Common situations: Typo in a config value for the background color; pasted color with stray letters or the '0x' prefix; lowercase/uppercase confusion is fine but accidental characters like 'O' instead of '0' are not.

Understand the failure class

Background: "Invalid ... format", "must be in format X", "does not look like a ..." — invalid argument format errors across CLI tools and libraries — this error's family across 17 libraries.

Related errors


AI-assisted analysis of tonhowtf/omniget@8600b91f42 (2026-09-12). Data as JSON: /api/errors/2d17176ce229f7c5. Report an issue: GitHub.

Appendix: source

Thrown at src-tauri/omniget-core/src/core/tools/img_bg.rs:146

#[derive(Debug, Clone, Serialize)]
pub struct BgResult {
    pub model: String,
    pub items: Vec<BgItem>,
    pub done: usize,
    pub failed: usize,
}

// ── Peças puras (testadas sem modelo nem runtime) ──────────────────────

/// `#RGB`, `#RRGGBB` ou `#RRGGBBAA`. Vazio devolve `None` (= transparente).
pub fn parse_hex_color(raw: &str) -> anyhow::Result<Option<Rgba<u8>>> {
    let s = raw.trim().trim_start_matches('#');
    if s.is_empty() {
        return Ok(None);
    }
    let byte = |i: usize| -> anyhow::Result<u8> {
        u8::from_str_radix(&s[i..i + 2], 16).map_err(|_| anyhow!("cor inválida: {raw}"))
    };
    let px = match s.len() {
        3 => {
            let mut v = [0u8; 3];
            for (i, c) in s.chars().enumerate() {
                let d = c
                    .to_digit(16)
                    .ok_or_else(|| anyhow!("cor inválida: {raw}"))? as u8;
                v[i] = d * 17;
            }
            Rgba([v[0], v[1], v[2], 255])
        }
        6 => Rgba([byte(0)?, byte(2)?, byte(4)?, 255]),
        8 => Rgba([byte(0)?, byte(2)?, byte(4)?, byte(6)?]),
        _ => return Err(anyhow!("cor inválida: {raw}")),
    };
    Ok(Some(px))
}

View on GitHub (pinned to 8600b91f42)