Skip to content

Commit 260d29b

Browse files
authored
builtin: add .hex() methods to the rune and char types too (#25635)
1 parent 26359d6 commit 260d29b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

vlib/builtin/hex_test.v

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
fn test_hex_methods_on_u8() {
2+
assert u8(1).hex() == '01'
3+
assert u8(` `).hex() == '20'
4+
assert u8(255).hex() == 'ff'
5+
}
6+
7+
fn test_hex_methods_on_byte() {
8+
assert byte(1).hex() == '01'
9+
assert byte(` `).hex() == '20'
10+
assert byte(255).hex() == 'ff'
11+
}
12+
13+
fn test_hex_methods_on_char() {
14+
assert char(1).hex() == '01'
15+
assert char(` `).hex() == '20'
16+
assert char(255).hex() == 'ff'
17+
}
18+
19+
fn test_hex_method_on_runes() {
20+
assert ` `.hex() == '20'
21+
assert `喂`.hex() == '5582'
22+
// latin:
23+
assert `A`.hex() == '41'
24+
assert `Z`.hex() == '5a'
25+
// cyrillic:
26+
assert `Д`.hex() == '414'
27+
assert `Я`.hex() == '42f'
28+
// emojies:
29+
assert `💣`.hex() == '1f4a3'
30+
}

vlib/builtin/int.v

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,22 @@ pub fn (nn u8) hex() string {
340340
return u64_to_hex(nn, 2)
341341
}
342342

343+
// hex returns a hexadecimal representation of `c` (as an 8 bit unsigned number).
344+
// The output is zero padded for values below 16.
345+
// Example: assert char(`A`).hex() == '41'
346+
// Example: assert char(`Z`).hex() == '5a'
347+
// Example: assert char(` `).hex() == '20'
348+
pub fn (c char) hex() string {
349+
return u8(c).hex()
350+
}
351+
352+
// hex returns a hexadecimal representation of the rune `r` (as a 32 bit unsigned number).
353+
// Example: assert `A`.hex() == '41'
354+
// Example: assert `💣`.hex() == '1f4a3'
355+
pub fn (r rune) hex() string {
356+
return u32(r).hex()
357+
}
358+
343359
// hex returns the value of the `i8` as a hexadecimal `string`.
344360
// Note that the output is zero padded for values below 16.
345361
// Example: assert i8(8).hex() == '08'

0 commit comments

Comments
 (0)