From 80bd2974b48064cfe402967e6c3dda769e87efe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20Kr=C3=BCger?= <45282134+UweKrueger@users.noreply.github.com> Date: Fri, 16 Apr 2021 13:49:14 +0200 Subject: [PATCH] cgen: fix iteration over `shared` map (#9763) --- vlib/v/gen/c/cgen.v | 5 ++- vlib/v/tests/shared_map_test.v | 73 ++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index f6c605355d..e59af677e5 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1538,7 +1538,10 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) { g.expr(node.cond) g.writeln(';') } - arw_or_pt := if node.cond_type.is_ptr() { '->' } else { '.' } + mut arw_or_pt := if node.cond_type.is_ptr() { '->' } else { '.' } + if node.cond_type.has_flag(.shared_f) { + arw_or_pt = '->val.' + } idx := g.new_tmp_var() map_len := g.new_tmp_var() g.empty_line = true diff --git a/vlib/v/tests/shared_map_test.v b/vlib/v/tests/shared_map_test.v index 97d59ee6a5..d9b71c39e2 100644 --- a/vlib/v/tests/shared_map_test.v +++ b/vlib/v/tests/shared_map_test.v @@ -82,3 +82,76 @@ fn new_map() map[string]f64 { } return m } + +fn test_shared_array_iteration() { + shared a := [12.75, -0.125, 17] + mut n0 := 0 + mut n1 := 0 + mut n2 := 0 + rlock a { + for i, val in a { + match i { + 1 { + assert val == -0.125 + n1++ + // check for order, too: + assert n0 == 1 + } + 0 { + assert val == 12.75 + n0++ + } + 2 { + assert val == 17.0 + n2++ + assert n1 == 1 + } + else { + // this should not happen + assert false + } + } + } + } + // make sure we have iterated over each of the 3 keys exactly once + assert n0 == 1 + assert n1 == 1 + assert n2 == 1 +} + +fn test_shared_map_iteration() { + shared m := map{ + 'qwe': 12.75 + 'rtz': -0.125 + 'k': 17 + } + mut n0 := 0 + mut n1 := 0 + mut n2 := 0 + rlock m { + for k, val in m { + match k { + 'rtz' { + assert val == -0.125 + n0++ + } + 'qwe' { + assert val == 12.75 + n1++ + } + 'k' { + assert val == 17.0 + n2++ + } + else { + // this should not happen + assert false + } + } + } + } + // make sure we have iterated over each of the 3 keys exactly once + assert n0 == 1 + assert n1 == 1 + assert n2 == 1 +}