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

cgen: array_init_with_default

This commit is contained in:
yuyi 2020-05-16 21:21:37 +08:00 committed by GitHub
parent 5767576deb
commit 9b6ee8e77d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 3 deletions

View File

@ -27,6 +27,22 @@ fn __new_array(mylen int, cap int, elm_size int) array {
return arr
}
fn __new_array_with_default(mylen int, cap int, elm_size int, val voidptr) array {
cap_ := if cap < mylen { mylen } else { cap }
arr := array{
len: mylen
cap: cap_
element_size: elm_size
data: vcalloc(cap_ * elm_size)
}
if val != 0 {
for i in 0..arr.len {
C.memcpy(charptr(arr.data) + i*elm_size, val, elm_size)
}
}
return arr
}
// Private function, used by V (`nums := [1, 2, 3]`)
fn new_array_from_c_array(len, cap, elm_size int, c_array voidptr) array {
cap_ := if cap < len { len } else { cap }

View File

@ -977,6 +977,12 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
ast.ArrayInit {
is_fixed_array_init = it.is_fixed
has_val = it.has_val
if it.has_default {
elem_type_str := g.typ(it.elem_type)
g.write('$elem_type_str ${elem_type_str}_val_t = ')
g.expr(it.default_expr)
g.writeln(';')
}
}
else {}
}
@ -1239,7 +1245,7 @@ fn (mut g Gen) expr(node ast.Expr) {
g.write("'$it.val'")
}
ast.ConcatExpr {
g.concat_expr(it)
g.concat_expr(it)
}
ast.EnumVal {
// g.write('${it.mod}${it.enum_name}_$it.val')
@ -3842,7 +3848,7 @@ fn (mut g Gen) array_init(it ast.ArrayInit) {
// elem_sym := g.table.get_type_symbol(it.elem_type)
elem_type_str := g.typ(it.elem_type)
if it.exprs.len == 0 {
g.write('__new_array(')
g.write('__new_array_with_default(')
if it.has_len {
g.expr(it.len_expr)
g.write(', ')
@ -3855,7 +3861,12 @@ fn (mut g Gen) array_init(it ast.ArrayInit) {
} else {
g.write('0, ')
}
g.write('sizeof($elem_type_str))')
g.write('sizeof($elem_type_str), ')
if it.has_default {
g.write('&${elem_type_str}_val_t)')
} else {
g.write('0)')
}
return
}
len := it.exprs.len

View File

@ -14,3 +14,11 @@ fn test_array_init() {
d << 'bbb'
'$d, $d.len, $d.cap' == "['aaa', 'bbb'], 2, 3"
}
fn test_array_init_with_default() {
a := []int{len: 4, init: 2}
assert '$a' == '[2, 2, 2, 2]'
b := []string{len: 3, init: 'abc'}
assert '$b' == "['abc', 'abc', 'abc']"
}