builtin: optimize hex() (#11261)

pull/11269/head
penguindark 2021-08-22 10:10:24 +02:00 committed by GitHub
parent 2f6b2dd189
commit fde934cd93
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 10 deletions

View File

@ -256,13 +256,12 @@ pub fn (b bool) str() string {
[direct_array_access; inline]
fn u64_to_hex(nn u64, len byte) string {
mut n := nn
mut buf := [256]byte{}
mut buf := [17]byte{}
buf[len] = 0
mut i := 0
for i = len - 1; i >= 0; i-- {
d := byte(n & 0xF)
x := if d < 10 { d + `0` } else { d + 87 }
buf[i] = x
buf[i] = if d < 10 { d + `0` } else { d + 87 }
n = n >> 4
}
return unsafe { tos(memdup(&buf[0], len + 1), len) }
@ -272,13 +271,12 @@ fn u64_to_hex(nn u64, len byte) string {
[direct_array_access; inline]
fn u64_to_hex_no_leading_zeros(nn u64, len byte) string {
mut n := nn
mut buf := [256]byte{}
mut buf := [17]byte{}
buf[len] = 0
mut i := 0
for i = len - 1; i >= 0; i-- {
d := byte(n & 0xF)
x := if d < 10 { d + `0` } else { d + 87 }
buf[i] = x
buf[i] = if d < 10 { d + `0` } else { d + 87 }
n = n >> 4
if n == 0 {
break
@ -306,7 +304,11 @@ pub fn (nn byte) hex() string {
// Example: assert i8(10).hex() == '0a'
// Example: assert i8(15).hex() == '0f'
pub fn (nn i8) hex() string {
return byte(nn).hex()
if nn == 0 {
return '00'
}
return u64_to_hex(u64(nn), 2)
//return byte(nn).hex()
}
// hex returns the value of the `u16` as a hexadecimal `string`.

View File

@ -23,8 +23,6 @@ fn test_str_methods() {
assert int(-2147483648).str() == '-2147483648'
assert i64(1).str() == '1'
assert i64(-1).str() == '-1'
// assert byte(1).str() == '1'
// assert byte(-1).str() == '255'
assert u16(1).str() == '1'
assert u16(-1).str() == '65535'
assert u32(1).str() == '1'
@ -33,6 +31,8 @@ fn test_str_methods() {
assert u64(-1).str() == '18446744073709551615'
assert voidptr(-1).str() == 'ffffffffffffffff'
assert voidptr(1).str() == '1'
assert (&byte(-1)).str() == 'ffffffffffffffff'
assert (&byte(1)).str() == '1'
assert byteptr(-1).str() == 'ffffffffffffffff'
assert byteptr(1).str() == '1'
}
@ -105,6 +105,18 @@ fn test_hex() {
assert b.hex() == '4d2'
b1 := -1
assert b1.hex() == 'ffffffff'
// unsigned tests
assert u8(12).hex() == '0c'
assert u8(255).hex() == 'ff'
assert u16(65535).hex() == 'ffff'
assert u32(-1).hex() == 'ffffffff'
assert u64(-1).hex() == 'ffffffffffffffff'
// signed tests
assert i8(-1).hex() == 'ff'
assert i8(12).hex() == '0c'
assert i16(32767).hex() == '7fff'
assert int(2147483647).hex() == '7fffffff'
assert i64(9223372036854775807).hex() == '7fffffffffffffff'
}
fn test_bin() {
@ -168,7 +180,6 @@ fn test_num_separator() {
// f32 or f64
assert 312_2.55 == 3122.55
assert 312_2.55 == 3122.55
}
fn test_int_decl() {