Micro-optimisation

This commit is contained in:
Kovid Goyal 2025-12-30 13:40:49 +05:30
parent 2aed1c9c06
commit a4d88beddb
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
2 changed files with 19 additions and 21 deletions

34
kitty/rgb.py generated
View file

@ -455,30 +455,28 @@ def to_color(raw: str, validate: bool = False) -> Color | None:
if raw.startswith('#'):
# For hex colors, only strip comments after whitespace
# e.g., "#ff0000 # comment" -> "#ff0000"
parts = raw.split()
if len(parts) > 1:
raw = parts[0] # Keep only the hex color part
raw = raw.partition(' ')[0]
else:
# For non-hex colors, strip everything after #
raw = raw.split('#')[0].strip()
raw = raw.partition('#')[0]
x = raw.strip().lower()
ans = color_names.get(x)
if ans is not None:
if ans := color_names.get(x):
return ans
val: Color | None = None
with suppress(Exception):
if raw.startswith('#'):
val = parse_sharp(raw[1:])
elif x.startswith('oklch('):
val = parse_oklch(x[6:])
elif x.startswith('lab('):
val = parse_lab(x[4:])
else:
k, sep, v = raw.partition(':')
if k == 'rgb':
val = parse_rgb(v)
elif k == 'rgbi':
val = parse_rgbi(v)
match raw[0]:
case '#':
val = parse_sharp(raw[1:])
case 'o':
val = parse_oklch(x[6:])
case 'l':
val = parse_lab(x[4:])
case 'r':
k, _, v = raw.partition(':')
if k == 'rgb':
val = parse_rgb(v)
elif k == 'rgbi':
val = parse_rgbi(v)
if val is None and validate:
raise ValueError(f'Invalid color name: {raw!r}')
return val

View file

@ -105,9 +105,9 @@ func oklchToSrgbGamutMap(l, c, h float64) (float64, float64, float64) {
}
// Constants from CSS Color Module Level 4
const jnd = 0.02 // Just Noticeable Difference threshold
const jnd = 0.02 // Just Noticeable Difference threshold
const minConvergence = 0.0001 // Binary search precision
const epsilon = 0.00001 // Small value for floating point comparisons
const epsilon = 0.00001 // Small value for floating point comparisons
// Edge cases: pure black or white
if l <= 0.0 {
@ -271,7 +271,7 @@ func parseOklch(spec string) (RGBA, error) {
// Clamp to reasonable ranges
l = math.Max(0.0, math.Min(1.0, l))
c = math.Max(0.0, c) // Chroma is unbounded
h = math.Mod(h, 360) // Wrap hue to 0-360
h = math.Mod(h, 360) // Wrap hue to 0-360
if h < 0 {
h += 360
}