Thread: custom type for storing a HTML color

custom type for storing a HTML color

From
"Justin Dearing"
Date:
Hello, I currently store html color codes in that database with the
following DOMAIN:

CREATE DOMAIN html_color AS char(7) CHECK (VALUE ~ '^#[A-Fa-f0-9]{6}$');

Has anyone created a custom type that has additional functionality (eg
format the input or output to other formats, retrieve red, green or
blue values as 0-255 integers, etc. This is good enough for my uses at
the moment, but has anyone invented a better wheel than mine?

Re: custom type for storing a HTML color

From
Kevin Hunter
Date:
On 27 Mar 2007 05:10p -0400, Justin Dearing wrote:
> Hello, I currently store html color codes in that database with the
> following DOMAIN:
>
> CREATE DOMAIN html_color AS char(7) CHECK (VALUE ~ '^#[A-Fa-f0-9]{6}$');
>
> Has anyone created a custom type that has additional functionality (eg
> format the input or output to other formats, retrieve red, green or
> blue values as 0-255 integers, etc. This is good enough for my uses at
> the moment, but has anyone invented a better wheel than mine?

I have no idea of your specific environment/application, but it seems to
me that CHAR(7) is a waste of (at least) 3 bytes per row (or 4 bytes,
since you're not worrying about an alpha channel with HTML).

In essence, an HTML color is composed of 3 bytes, 8 bits each for red,
green, and blue.  If the capitalization of the [A-F] characters isn't
important, you could simply store the binary equivalent and convert it
to the hexadecimal equivalent when you need it.  This would then
alleviate the need for the constraint as it's simply a number.  (Well,
move the check to the next layer, I suppose.)

For instance: #aab329 could be stored as

   a a        b 3        2 9
1010 1010  1011 0011  0010 1001

the binary number (10101010 10110011 00101001)_2 = (11,176,985)_10, or
basically a number that can be stored in 3 bytes.

That being said, I /am/ curious if someone has created a better wheel?
Besides, I don't even know what a DOMAIN is!

/me scurries off to find out about DOMAINs

Kevin