makepad_live_tokenizer/
vec4_ext.rs1
2use makepad_math::Vec4;
3use crate::colorhex;
4
5pub trait Vec4Ext{
6 fn from_hex_str(hex: &str) -> Result<Vec4, ()> {Self::from_hex_bytes(hex.as_bytes())}
7 fn from_hex_bytes(bytes: &[u8]) -> Result<Vec4, ()>;
8 fn append_hex_to_string(&self, out:&mut String);
9 fn color(value: &str) -> Vec4;
10}
11
12impl Vec4Ext for Vec4{
13 fn append_hex_to_string(&self, out:&mut String) {
14 fn int_to_hex(d: u8) -> char {
15 if d >= 10 {
16 return (d + 55) as char;
17 }
18 (d + 48) as char
19 }
20
21 let r = (self.x * 255.0) as u8;
22 let g = (self.y * 255.0) as u8;
23 let b = (self.z * 255.0) as u8;
24 out.push(int_to_hex((r >> 4) & 0xf));
25 out.push(int_to_hex((r) & 0xf));
26 out.push(int_to_hex((g >> 4) & 0xf));
27 out.push(int_to_hex((g) & 0xf));
28 out.push(int_to_hex((b >> 4) & 0xf));
29 out.push(int_to_hex((b) & 0xf));
30 }
31
32 fn color(value: &str) -> Vec4 {
33 if let Ok(val) = Self::from_hex_str(value) {
34 val
35 }
36 else {
37 Vec4 {x: 1.0, y: 0.0, z: 1.0, w: 1.0}
38 }
39 }
40
41 fn from_hex_bytes(bytes: &[u8]) -> Result<Vec4, ()> {
42 let color = if bytes.len()>2 && bytes[0] == b'#' {
43 colorhex::hex_bytes_to_u32(&bytes[1..])?
44 }
45 else {
46 colorhex::hex_bytes_to_u32(bytes)?
47 };
48 Ok(Vec4 {
49 x: (((color >> 24)&0xff) as f32) / 255.0,
50 y: (((color >> 16)&0xff) as f32) / 255.0,
51 z: (((color >> 8)&0xff) as f32) / 255.0,
52 w: ((color&0xff) as f32) / 255.0,
53 })
54 }
55}