From 9b6ee8e77d1ecef09f8c10ca74b2d23171ad01c2 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 16 May 2020 21:21:37 +0800 Subject: [PATCH] cgen: array_init_with_default --- vlib/builtin/array.v | 16 ++++++++++++++++ vlib/v/gen/cgen.v | 17 ++++++++++++++--- vlib/v/tests/array_init_test.v | 8 ++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index d83da8d1ce..969fa38bc3 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -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 } diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index ccf87e0434..3875bb1d5b 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -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 diff --git a/vlib/v/tests/array_init_test.v b/vlib/v/tests/array_init_test.v index 9f4d3a0eac..07d3f196ea 100644 --- a/vlib/v/tests/array_init_test.v +++ b/vlib/v/tests/array_init_test.v @@ -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']" +}