From 5f9af3f5941074db49849d02bf6e178b2079f08b Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 4 Mar 2021 18:39:39 +0800 Subject: [PATCH] cgen: fix for_in array of fixed_array (fix #9098) (#9099) --- vlib/v/gen/c/cgen.v | 4 +++ .../for_in_containers_of_fixed_array_test.v | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 vlib/v/tests/for_in_containers_of_fixed_array_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 75dc9f2386..8138fe306b 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1385,6 +1385,10 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) { g.write('\t') g.write_fn_ptr_decl(val_sym.info as table.FnType, c_name(node.val_var)) g.writeln(' = ((voidptr*)$tmp${op_field}data)[$i];') + } else if val_sym.kind == .array_fixed && !node.val_is_mut { + right := '(($styp*)$tmp${op_field}data)[$i]' + g.writeln('\t$styp ${c_name(node.val_var)};') + g.writeln('\tmemcpy(*($styp*)${c_name(node.val_var)}, (byte*)$right, sizeof($styp));') } else { // If val is mutable (pointer behind the scenes), we need to generate // `int* val = ((int*)arr.data) + i;` diff --git a/vlib/v/tests/for_in_containers_of_fixed_array_test.v b/vlib/v/tests/for_in_containers_of_fixed_array_test.v new file mode 100644 index 0000000000..6c04b84fa8 --- /dev/null +++ b/vlib/v/tests/for_in_containers_of_fixed_array_test.v @@ -0,0 +1,25 @@ +fn test_for_in_containers_of_fixed_array() { + mut rets := []string{} + arr := [][2]int{len: 3} + + for pair in arr { + println(pair) + rets << '$pair' + } + assert rets[0] == '[0, 0]' + assert rets[1] == '[0, 0]' + assert rets[2] == '[0, 0]' +} + +fn test_for_mut_in_containers_of_fixed_array() { + mut rets := []string{} + mut arr := [][2]int{len: 3} + + for mut pair in arr { + println(pair) + rets << '$pair' + } + assert rets[0] == '[0, 0]' + assert rets[1] == '[0, 0]' + assert rets[2] == '[0, 0]' +}