Functional Weave
Code in Python

charts.color

Hex colours to RGB and back, and sRGB channels to linear light and back, identically in every language.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 31 tests, run in TypeScript, Python and Rust · fewer than the registry now requires. 1.0.1 adds them.parseHex 9 · toHex 5 · srgbToLinear 8 · linearToSrgb 9

What it does

The small kit every colour calculation in `charts.*` starts from: hex text to three 8-bit channels and back (`parseHex`, `toHex`), and each channel to linear light and back (`srgbToLinear`, `linearToSrgb`). A group, because the four only make sense together and `charts.interpolate-color` and `charts.contrast` use them all.

**Hex.** `parseHex` accepts `#rrggbb` and the CSS short form `#rgb` (each digit doubled, so `#f80` is `#ff8800`), in either case. A missing `#`, an alpha channel, `rgb()` syntax or a colour name is an error, not a guess. `toHex` always writes lowercase `#rrggbb`.

The functions

A group: 4 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.

  1. parse_hex (hex: string) -> Rgb
  2. to_hex (rgb: Rgb) -> string
  3. srgb_to_linear (channel: int) -> float
  4. linear_to_srgb (value: float) -> int

The type it declares, generated into your project

@dataclass(frozen=True)
class Rgb:
    """An sRGB colour as three 8-bit channels."""

    #: 0 to 255
    r: int
    #: 0 to 255
    g: int
    #: 0 to 255
    b: int

Once installed, your code imports each one from the group's module.

parse_hex throws on bad input 9 tests

def parse_hex(hex: str) -> Rgb
hexstring"#rrggbb" or "#rgb", either case
returnsRgb

For example

  • parse_hex(#e69f00) → r 230, g 159, b 0 six digits
  • parse_hex(#56B4E9) → r 86, g 180, b 233 upper case
  • parse_hex(#f80) → r 255, g 136, b 0 three digits double each one, as CSS does
from fune.charts.color import parse_hex  # charts.color@^1
impl/python/parse_hex.py · 23 lines · open · raw
from .charts_color_types import Rgb

_HEX = "0123456789abcdef"


def _nibble(ch: str, hex: str) -> int:
    n = _HEX.find(ch.lower())
    if n < 0:
        raise ValueError('"%s" is not a hex colour (#rgb or #rrggbb)' % (hex,))
    return n


def parse_hex(hex: str) -> Rgb:  # noqa: A002 - the manifest names it hex
    """"#rrggbb" or the short "#rgb" (digits doubled, as CSS does), either case."""
    if not isinstance(hex, str) or not hex.startswith("#") or len(hex) not in (4, 7):
        raise ValueError('"%s" is not a hex colour (#rgb or #rrggbb)' % (hex,))
    if len(hex) == 4:
        return Rgb(r=_nibble(hex[1], hex) * 17, g=_nibble(hex[2], hex) * 17, b=_nibble(hex[3], hex) * 17)
    return Rgb(
        r=_nibble(hex[1], hex) * 16 + _nibble(hex[2], hex),
        g=_nibble(hex[3], hex) * 16 + _nibble(hex[4], hex),
        b=_nibble(hex[5], hex) * 16 + _nibble(hex[6], hex),
    )

to_hex throws on bad input 5 tests

def to_hex(rgb: Rgb) -> str
rgbRgb
returnsstringlowercase "#rrggbb"

For example

  • to_hex(r 230, g 159, b 0) → #e69f00 lower case, two digits per channel
  • to_hex(r 1, g 10, b 15) → #010a0f single-digit channels are zero-padded
  • to_hex(r 255, g 255, b 255) → #ffffff white
from fune.charts.color import to_hex  # charts.color@^1
impl/python/to_hex.py · 14 lines · open · raw
from .charts_color_types import Rgb

_HEX = "0123456789abcdef"


def _pair(value: int) -> str:
    if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > 255:
        raise ValueError("rgb channels must be whole numbers from 0 to 255, received %r" % (value,))
    return _HEX[value // 16] + _HEX[value % 16]


def to_hex(rgb: Rgb) -> str:
    """Lowercase "#rrggbb", the form every renderer accepts."""
    return "#" + _pair(rgb.r) + _pair(rgb.g) + _pair(rgb.b)

srgb_to_linear throws on bad input 8 tests

def srgb_to_linear(channel: int) -> float
channelint0 to 255, as stored in a hex colour
returnsfloatlinear light 0 to 1, rounded to 12 decimal places

For example

  • srgb_to_linear(0) → 0 black is 0
  • srgb_to_linear(255) → 1 white is 1
  • srgb_to_linear(1) → 0 the darkest step is on the straight segment: 1/255/12.92
from fune.charts.color import srgb_to_linear  # charts.color@^1
impl/python/srgb_to_linear.py · 12 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from .math_pow import pow  ← from math.pow ^1.0.0 · built alongside by fune
from .math_round_float import round_float  ← from math.round-float ^1.0.0 · built alongside by fune


def srgb_to_linear(channel: int) -> float:
    """The sRGB transfer function (IEC 61966-2-1) undone: an 8-bit channel as
    linear light from 0 to 1, rounded to 12 places."""
    if isinstance(channel, bool) or not isinstance(channel, int) or channel < 0 or channel > 255:
        raise ValueError("channel must be a whole number from 0 to 255, received %r" % (channel,))
    c = channel / 255
    linear = c / 12.92 if c <= 0.04045 else pow((c + 0.055) / 1.055, 2.4)
    return round_float(linear, 12)

linear_to_srgb throws on bad input 9 tests

def linear_to_srgb(value: float) -> int
valuefloatlinear light; below 0 or above 1 is clipped
returnsint0 to 255, rounded half away from zero

For example

  • linear_to_srgb(0.5) → 188 half the light is 188, not 128
  • linear_to_srgb(0.216) → 128 back from 128's linear value
  • linear_to_srgb(0) → 1 back from 1's linear value
from fune.charts.color import linear_to_srgb  # charts.color@^1
impl/python/linear_to_srgb.py · 13 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import math

from .math_pow import pow  ← from math.pow ^1.0.0 · built alongside by fune
from .math_round_float import round_float  ← from math.round-float ^1.0.0 · built alongside by fune


def linear_to_srgb(value: float) -> int:
    """Linear light back to an 8-bit sRGB channel, clipping to 0..1 first."""
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
        raise ValueError("value must be a finite number, received %r" % (value,))
    v = 0.0 if value < 0 else 1.0 if value > 1 else float(value)
    encoded = 12.92 * v if v <= 0.0031308 else 1.055 * pow(v, 1 / 2.4) - 0.055
    return int(round_float(encoded * 255, 0))

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 2 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add charts.color

That builds the whole group. To build only what you call, and whatever it uses inside the group:

fune add charts.color --only parseHex
Download for Python charts.color-1.0.0-python.fune · 12,790 bytes sha256 30f23264859138792663b2cb2d624b681338b601075c4443dac8be43d1ef2066

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./charts.color-1.0.0-python.fune, or fetch it from a terminal with fune pull charts.color@1.0.0:python.

The whole function, every language, is one file too: charts.color-1.0.0.fune, 19,719 bytes, sha256 828b8ee0f7f2de31e8dcab050778b11b0d6c822f5a3360d54d9f6c63110b136e. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before charts.color.parseHex
# fune: before charts.color.toHex
# fune: before charts.color.srgbToLinear
# fune: before charts.color.linearToSrgb

after — your function gets the result and the arguments, and returns the final result.

# fune: after charts.color.parseHex
# fune: after charts.color.toHex
# fune: after charts.color.srgbToLinear
# fune: after charts.color.linearToSrgb

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace math.pow in charts.color
# fune: replace math.round-float in charts.color

step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show charts.color --steps.

# fune: step charts.color.<fn> after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

This version has fewer tests than the registry now requires. It was published before every function had to have 8. 1.0.1 meets it, and a project on ^1.0.0 installs that or newer.

  • toHex has 5 tests; every function needs at least 8. Add 3 more to vectors.json ("fn": "toHex"): the ordinary case, the boundaries (zero, negative, the largest values), the rounding edge and every error it documents
  • linearToSrgb throws (throws yes) but none of its 9 tests expects an error; add an "expectError" vector ("fn": "linearToSrgb") for each error it documents, or declare `throws no` if it cannot throw

parseHex 9 tests

CaseArgumentsExpected
six digits #e69f00 → r 230, g 159, b 0
upper case #56B4E9 → r 86, g 180, b 233
three digits double each one, as CSS does #f80 → r 255, g 136, b 0
black #000000 → r 0, g 0, b 0
white #FFF → r 255, g 255, b 255
a missing # is an error e69f00 → error: is not a hex colour (#rgb or #rrggbb)
a non-hex digit is an error #e69g00 → error: is not a hex colour (#rgb or #rrggbb)
an alpha channel is not accepted #e69f00ff → error: is not a hex colour (#rgb or #rrggbb)
a colour name is an error red → error: is not a hex colour (#rgb or #rrggbb)

toHex 5 tests

CaseArgumentsExpected
lower case, two digits per channel r 230, g 159, b 0 → #e69f00
single-digit channels are zero-padded r 1, g 10, b 15 → #010a0f
white r 255, g 255, b 255 → #ffffff
a channel above 255 is an error r 256, g 0, b 0 → error: rgb channels must be whole numbers from 0 to 255
a negative channel is an error r 0, g -1, b 0 → error: rgb channels must be whole numbers from 0 to 255

srgbToLinear 8 tests

CaseArgumentsExpected
black is 0 0 → 0
white is 1 255 → 1
the darkest step is on the straight segment: 1/255/12.92 1 → 0
10 is the last value on the straight segment 10 → 0.003
11 is the first on the power curve 11 → 0.003
mid grey 128 is only 21.6% of the light, not 50% 128 → 0.216
188 is about half the light 188 → 0.503
above 255 is an error 256 → error: channel must be a whole number from 0 to 255

linearToSrgb 9 tests

CaseArgumentsExpected
half the light is 188, not 128 0.5 → 188
back from 128's linear value 0.216 → 128
back from 1's linear value 0 → 1
the straight segment's end: 12.92 x 0.0031308 x 255 = 10.31 0.003 → 10
on the straight segment 6.59 rounds to 7 0.002 → 7
white 1 → 255
below 0 clips to black -0.1 → 0
above 1 clips to white 1.2 → 255
18% grey 0.18 → 118

More from the author

**Linear light.** A stored channel is gamma-encoded: 128 is only 21.6% of the light of 255, and averaging stored values gives muddy, too-dark mixes. `srgbToLinear` applies the sRGB transfer function of IEC 61966-2-1: c / 12.92 when c = channel / 255 is at most 0.04045, otherwise ((c + 0.055) / 1.055)^2.4. It returns linear light from 0 to 1, rounded to 12 decimal places. `linearToSrgb` inverts it (12.92 v up to 0.0031308, otherwise 1.055 v^(1/2.4) - 0.055), clipping to 0..1 first because a mix computed in another colour space can land a hair out of gamut, and rounds the channel half away from zero. Every 8-bit value survives the round trip.

The powers come from `math.pow`, not `Math.pow` or `**`, so all three languages return the same bits, and the rounding from `math.round-float`.

Sources: IEC 61966-2-1:1999, "Default RGB colour space - sRGB"; W3C, CSS Color Module Level 4, section 10.2 "Predefined sRGB" (the same transfer function) and section 5.2 "The RGB hexadecimal notations".

Files

PathBytes
README.md1,606
impl/python/linear_to_srgb.py573
impl/python/parse_hex.py897
impl/python/srgb_to_linear.py574
impl/python/to_hex.py489
impl/rust/linear_to_srgb.rs685
impl/rust/parse_hex.rs1,298
impl/rust/srgb_to_linear.rs716
impl/rust/to_hex.rs821
impl/typescript/linear_to_srgb.ts620
impl/typescript/parse_hex.ts1,058
impl/typescript/srgb_to_linear.ts673
impl/typescript/to_hex.ts508
vectors.json3,618