Created
October 4, 2023 15:44
-
-
Save run-dlang/0cd7a573364c37b490ae7a8e2aed8c59 to your computer and use it in GitHub Desktop.
Code shared from run.dlang.io.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std; | |
struct Color | |
{ | |
/// Color red value | |
ubyte r; | |
/// Color green value | |
ubyte g; | |
/// Color blue value | |
ubyte b; | |
/// Color alpha value | |
ubyte a; | |
} | |
Color parseColor(string input) | |
{ | |
ubyte defaultAlpha = 255; | |
auto hexPattern = regex(`^#([0-9a-fA-F]{3,8})$`); | |
auto rgbPattern = regex(`^rgb\((\d+),\s*(\d+),\s*(\d+)\)$`); | |
auto rgbaPattern = regex(`^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d*(?:\.\d+)?)\)$`); | |
if (matchFirst(input, hexPattern)) | |
{ | |
auto hexMatch = matchFirst(input, hexPattern); | |
uint hexValue = to!uint(hexMatch[1], 16); | |
switch (hexMatch[1].length) | |
{ | |
case 3: | |
return Color( | |
(hexValue >> 8 & 0xF) | (hexValue >> 4 & 0xF0), | |
(hexValue >> 4 & 0xF) | (hexValue & 0xF0), | |
(hexValue & 0xF) | (hexValue << 4 & 0xF0), | |
defaultAlpha | |
); | |
case 6: | |
return Color( | |
(hexValue >> 16) & 0xFF, | |
(hexValue >> 8) & 0xFF, | |
hexValue & 0xFF, | |
defaultAlpha | |
); | |
case 8: | |
return Color( | |
(hexValue >> 24) & 0xFF, | |
(hexValue >> 16) & 0xFF, | |
(hexValue >> 8) & 0xFF, | |
hexValue & 0xFF | |
); | |
default: | |
throw new Exception("Invalid hex color format"); | |
} | |
} | |
else if (matchFirst(input, rgbPattern)) | |
{ | |
auto rgbMatch = matchFirst(input, rgbPattern); | |
return Color(to!ubyte(rgbMatch[1]), | |
to!ubyte(rgbMatch[2]), | |
to!ubyte(rgbMatch[3]), | |
defaultAlpha); | |
} | |
else if (matchFirst(input, rgbaPattern)) | |
{ | |
auto rgbaMatch = matchFirst(input, rgbaPattern); | |
return Color(to!ubyte(rgbaMatch[1]), | |
to!ubyte(rgbaMatch[2]), | |
to!ubyte(rgbaMatch[3]), | |
to!ubyte(round(to!float(rgbaMatch[4]) * 255))); | |
} | |
else | |
{ | |
throw new Exception("Invalid color format"); | |
} | |
} | |
unittest | |
{ | |
// Hex | |
assert(parseColor("#F00") == Color(255, 0, 0, 255)); | |
assert(parseColor("#FF0000") == Color(255, 0, 0, 255)); | |
assert(parseColor("#FF000080") == Color(255, 0, 0, 128)); | |
// RGB | |
assert(parseColor("rgb(255, 0, 0)") == Color(255, 0, 0, 255)); | |
// RGBA | |
assert(parseColor("rgba(255, 0, 0, 0.5)") == Color(255, 0, 0, 128)); | |
} | |
void main() { | |
writeln(parseColor("rgb(255, 0, 0)")); | |
writeln(Color(255, 0, 0, 255)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment