color - A library for color interface in V


 

Hello again, this afternoon I decided to write a library for color interface in V! As I stated in my previous post, I very much like V and think it has great potential. 


Since in this project I knew it would be used a library, I had to make some changes to the struct and function definitions, namely making them public. Below are the definitions of the structs.

pub struct RGB{
pub:
r int
g int
b int
}
pub struct CMYK {
pub:
c int
m int
y int
k int
}

pub struct HEX {
pub:
data string
}

As you can see, I made the choice to store the hexadecimal values as strings, which would make it easier to work with later on. However, the inital function accepts int or strings, to allow for operability with existing code.


Once done with this, I knew that we would need at least 6 functions, to switch between the following:

  • RGB to CMYK
  • RGB to hex
  • CMYK to RGB
  • CMYK to hex
  • hex to RGB
  • hex to CMYK

And these functions were by and large easy to implement, though the two hex and CMYK functions used the RGB ones in the function, to ensure we followed DRY (don't repeat yourself).  

One difficult part was sorting out RGB to CMYK and vice versa. This was because CMYK and RGB use 100 and 255 maximums respectively, which complicated matters and made approximation needed. Once the algorithm itself was done, I needed to deal with edge cases and integer overflows, since we were using V's int type, a 32-bit integer. Once the edge cases were dealt with, the tool was finished!


Here is a list of all the methods:

fn rgb(r int, g int, b int) RGB
 
fn (r RGB) cmyk() CMYK
fn (r RGB) hex() HEX
 

fn hex_s(s string) HEX
fn hex(i int) HEX

fn (h HEX) rgb() RGB
fn (h HEX) cmyk() CMYK
 
fn (h HEX) int() int
 
fn cmyk(c int, m int, y int, k int) CMYK

fn (bits CMYK) rgb() RGB
fn (bits CMYK) hex() HEX

Comments

Popular posts from this blog

Upcoming Guest Opinions Post!

Why I use the V language

color gets updated!