builtin: add 0 terminators for strings returned by .to_lower, .to_upper, utf32_to_str_no_malloc/2

pull/9306/head
Delyan Angelov 2021-03-14 18:21:45 +02:00
parent b6d089b605
commit d65ad68e77
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
4 changed files with 17 additions and 14 deletions

View File

@ -266,6 +266,7 @@ pub fn (n int) hex1() string {
len := if n >= 0 { n.str().len + 3 } else { 11 }
hex := malloc(len) // 0x + \n
count := C.sprintf((hex), '0x%x', n)
hex[count] = 0
return tos(hex, count)
}
*/
@ -282,10 +283,7 @@ fn u64_to_hex(nn u64, len byte) string {
buf[i] = x
n = n >> 4
}
return string{
str: unsafe { memdup(buf, len + 1) }
len: len
}
return unsafe { tos(memdup(buf, len + 1), len) }
}
// u64_to_hex_no_leading_zeros converts the number `nn` to hexadecimal `string`.
@ -305,10 +303,7 @@ fn u64_to_hex_no_leading_zeros(nn u64, len byte) string {
}
}
res_len := len - i
return string{
str: unsafe { memdup(&buf[i], res_len + 1) }
len: res_len
}
return unsafe { tos(memdup(&buf[i], res_len + 1), res_len) }
}
// hex returns the value of the `byte` as a hexadecimal `string`.

View File

@ -49,8 +49,10 @@ pub fn (b []byte) bytestr() string {
// TODO copy pasted from builder.v
fn bytes2string(b []byte) string {
mut copy := b.clone()
copy << `\0`
res := unsafe { tos(copy.data, copy.len-1) }
return res
unsafe {
buf := malloc(b.len + 1)
C.memcpy(buf, b.data, b.len)
buf[b.len] = 0
return tos(buf, b.len)
}
}

View File

@ -877,6 +877,7 @@ pub fn (s string) to_lower() string {
for i in 0 .. s.len {
b[i] = byte(C.tolower(s.str[i]))
}
b[s.len] = 0
return tos(b, s.len)
}
}
@ -900,6 +901,7 @@ pub fn (s string) to_upper() string {
for i in 0 .. s.len {
b[i] = byte(C.toupper(s.str[i]))
}
b[s.len] = 0
return tos(b, s.len)
}
}

View File

@ -25,17 +25,20 @@ pub fn utf32_to_str_no_malloc(code u32, buf voidptr) string {
if icode <= 127 {
// 0x7F
buffer[0] = byte(icode)
buffer[1] = 0
res = tos(buffer, 1)
} else if icode <= 2047 {
// 0x7FF
buffer[0] = 192 | byte(icode >> 6) // 0xC0 - 110xxxxx
buffer[1] = 128 | byte(icode & 63) // 0x80 - 0x3F - 10xxxxxx
buffer[2] = 0
res = tos(buffer, 2)
} else if icode <= 65535 {
// 0xFFFF
buffer[0] = 224 | byte(icode >> 12) // 0xE0 - 1110xxxx
buffer[1] = 128 | (byte(icode >> 6) & 63) // 0x80 - 0x3F - 10xxxxxx
buffer[2] = 128 | byte(icode & 63) // 0x80 - 0x3F - 10xxxxxx
buffer[3] = 0
res = tos(buffer, 3)
}
// 0x10FFFF
@ -44,6 +47,7 @@ pub fn utf32_to_str_no_malloc(code u32, buf voidptr) string {
buffer[1] = 128 | (byte(icode >> 12) & 63) // 0x80 - 0x3F - 10xxxxxx
buffer[2] = 128 | (byte(icode >> 6) & 63) // 0x80 - 0x3F - 10xxxxxx
buffer[3] = 128 | byte(icode & 63) // 0x80 - 0x3F - 10xxxxxx
buffer[4] = 0
res = tos(buffer, 4)
}
}