From a388b3be843783297b04171b05ba33faa85eb687 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 8 Dec 2024 09:38:49 -0300 Subject: [PATCH] cgen: fixed for in loop with generic fixed array (fix #23075) (#23101) --- vlib/v/gen/c/for.v | 11 ++++++++++- vlib/v/tests/arrays_closure_fixed_array_test.v | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/arrays_closure_fixed_array_test.v diff --git a/vlib/v/gen/c/for.v b/vlib/v/gen/c/for.v index 31a8bfe3a..b5fd5a026 100644 --- a/vlib/v/gen/c/for.v +++ b/vlib/v/gen/c/for.v @@ -267,6 +267,8 @@ fn (mut g Gen) for_in_stmt(node_ ast.ForInStmt) { g.writeln('\t${styp} ${c_name(node.val_var)};') g.writeln('\tmemcpy(*(${styp}*)${c_name(node.val_var)}, (byte*)${right}, sizeof(${styp}));') } else { + needs_memcpy := !node.val_type.is_ptr() + && g.table.final_sym(node.val_type).kind == .array_fixed // If val is mutable (pointer behind the scenes), we need to generate // `int* val = ((int*)arr.data) + i;` // instead of @@ -276,10 +278,17 @@ fn (mut g Gen) for_in_stmt(node_ ast.ForInStmt) { '((${styp}*)${opt_expr}${op_field}data)[${i}]' } else if node.val_is_mut || node.val_is_ref { '((${styp})${cond_var}${op_field}data) + ${i}' + } else if val_sym.kind == .array_fixed { + '((${styp}*)${cond_var}${op_field}data)[${i}]' } else { '((${styp}*)${cond_var}${op_field}data)[${i}]' } - g.writeln('\t${styp} ${c_name(node.val_var)} = ${right};') + if !needs_memcpy { + g.writeln('\t${styp} ${c_name(node.val_var)} = ${right};') + } else { + g.writeln('\t${styp} ${c_name(node.val_var)} = {0};') + g.writeln('\tmemcpy(${c_name(node.val_var)}, ${right}, sizeof(${styp}));') + } } } } else if node.kind == .array_fixed { diff --git a/vlib/v/tests/arrays_closure_fixed_array_test.v b/vlib/v/tests/arrays_closure_fixed_array_test.v new file mode 100644 index 000000000..6496086d6 --- /dev/null +++ b/vlib/v/tests/arrays_closure_fixed_array_test.v @@ -0,0 +1,17 @@ +import arrays + +fn test_main() { + mut rules := [][2]int{} + rules << [1, 2]! + rules << [2, 3]! + + common_rule := [1, 2]! + assert arrays.index_of_first(rules, fn [common_rule] (idx int, rule [2]int) bool { + return rule == common_rule + }) == 0 + + common_rule2 := [2, 3]! + assert arrays.index_of_first(rules, fn [common_rule2] (idx int, rule [2]int) bool { + return rule == common_rule2 + }) == 1 +} -- 2.39.5