1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

strings: cleanup unsafe casts in some of strings.Builder ops (#13819)

This commit is contained in:
Delyan Angelov 2022-03-25 00:07:15 +02:00 committed by GitHub
parent 5b492e26dd
commit d6c40865f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -103,11 +103,20 @@ pub fn (mut b Builder) go_back(n int) {
b.trim(b.len - n) b.trim(b.len - n)
} }
[inline]
fn (b &Builder) spart(start_pos int, n int) string {
unsafe {
mut x := malloc_noscan(n + 1)
vmemcpy(x, &byte(b.data) + start_pos, n)
x[n] = 0
return tos(x, n)
}
}
// cut_last cuts the last `n` bytes from the buffer and returns them // cut_last cuts the last `n` bytes from the buffer and returns them
pub fn (mut b Builder) cut_last(n int) string { pub fn (mut b Builder) cut_last(n int) string {
cut_pos := b.len - n cut_pos := b.len - n
x := unsafe { (*&[]byte(b))[cut_pos..] } res := b.spart(cut_pos, n)
res := x.bytestr()
b.trim(cut_pos) b.trim(cut_pos)
return res return res
} }
@ -147,8 +156,7 @@ pub fn (b &Builder) last_n(n int) string {
if n > b.len { if n > b.len {
return '' return ''
} }
x := unsafe { (*&[]byte(b))[b.len - n..] } return b.spart(b.len - n, n)
return x.bytestr()
} }
// after(6) returns 'world' // after(6) returns 'world'
@ -157,8 +165,7 @@ pub fn (b &Builder) after(n int) string {
if n >= b.len { if n >= b.len {
return '' return ''
} }
x := unsafe { (*&[]byte(b))[n..] } return b.spart(n, b.len - n)
return x.bytestr()
} }
// str returns a copy of all of the accumulated buffer content. // str returns a copy of all of the accumulated buffer content.