@@ -127,19 +127,22 @@ impl TryFrom<&'_ str> for Rgba {
127
127
128
128
let ( r, g, b, a) = match hex. len ( ) {
129
129
RGB | RGBA => {
130
- // There's likely a better way to handle 3 and 4-value hex codes without
131
- // needing to use `.repeat` and incur additional allocations.
132
- // What we probably want to do is parse the single hex digit and then perform
133
- // bit-shifting to "duplicate" the digit.
134
- let r = u8:: from_str_radix ( & hex[ 0 ..1 ] . repeat ( 2 ) , 16 ) ?;
135
- let g = u8:: from_str_radix ( & hex[ 1 ..2 ] . repeat ( 2 ) , 16 ) ?;
136
- let b = u8:: from_str_radix ( & hex[ 2 ..3 ] . repeat ( 2 ) , 16 ) ?;
130
+ let r = u8:: from_str_radix ( & hex[ 0 ..1 ] , 16 ) ?;
131
+ let g = u8:: from_str_radix ( & hex[ 1 ..2 ] , 16 ) ?;
132
+ let b = u8:: from_str_radix ( & hex[ 2 ..3 ] , 16 ) ?;
137
133
let a = if hex. len ( ) == RGBA {
138
- u8:: from_str_radix ( & hex[ 3 ..4 ] . repeat ( 2 ) , 16 ) ?
134
+ u8:: from_str_radix ( & hex[ 3 ..4 ] , 16 ) ?
139
135
} else {
140
- 0xff
136
+ 0xf
141
137
} ;
142
- ( r, g, b, a)
138
+
139
+ /// Duplicates a given hex digit.
140
+ /// E.g., `0xf` -> `0xff`.
141
+ const fn duplicate ( value : u8 ) -> u8 {
142
+ value << 4 | value
143
+ }
144
+
145
+ ( duplicate ( r) , duplicate ( g) , duplicate ( b) , duplicate ( a) )
143
146
}
144
147
RRGGBB | RRGGBBAA => {
145
148
let r = u8:: from_str_radix ( & hex[ 0 ..2 ] , 16 ) ?;
0 commit comments