builtin: add &u8.free() (fix #23592) (#23598)

This commit is contained in:
Felipe Pena 2025-01-28 18:54:33 -03:00 committed by GitHub
parent 15e3f6258d
commit a05ef999ff
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 19 additions and 2 deletions

View File

@ -1058,6 +1058,12 @@ pub fn (data &u8) vbytes(len int) []u8 {
return unsafe { voidptr(data).vbytes(len) }
}
// free frees the memory allocated
@[unsafe]
pub fn (data &u8) free() {
unsafe { free(data) }
}
@[if !no_bounds_checking ?; inline]
fn panic_on_negative_len(len int) {
if len < 0 {

View File

@ -205,7 +205,7 @@ fn (mut g Gen) autofree_var_call(free_fn_name string, v ast.Var) {
return
}
mut af := strings.new_builder(128)
if v.typ.is_ptr() {
if v.typ.is_ptr() && v.typ.idx() != ast.u8_type_idx {
af.write_string('\t')
if v.typ.share() == .shared_t {
af.write_string(free_fn_name.replace_each(['__shared__', '']))
@ -241,7 +241,7 @@ fn (mut g Gen) autofree_var_call(free_fn_name string, v ast.Var) {
af.writeln('\tif (${c_name(v.name)}.state != 2) {')
af.writeln('\t\t${free_fn_name}((${base_type}*)${c_name(v.name)}.data); // autofreed option var ${g.cur_mod.name} ${g.is_builtin_mod}')
af.writeln('\t}')
} else {
} else if v.typ.idx() != ast.u8_type_idx {
af.writeln('\t${free_fn_name}(&${c_name(v.name)}); // autofreed var ${g.cur_mod.name} ${g.is_builtin_mod}')
}
}

View File

@ -0,0 +1,11 @@
fn test_main() {
unsafe {
mut data := malloc(4)
data[0] = c'f'
data[1] = c'o'
data[2] = c'o'
data[3] = c'\0'
assert data.vstring() == 'foo'
data.free()
}
}