Skip to content

Commit d433835

Browse files
authored
cgen: fix map of fixed array value in if guard (fix #24488) (#24496)
1 parent bc06620 commit d433835

File tree

3 files changed

+44
-4
lines changed

3 files changed

+44
-4
lines changed

vlib/v/gen/c/if.v

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -343,9 +343,16 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
343343
} else {
344344
branch.cond.vars[0].name
345345
}
346-
g.write('\t${base_type} ${cond_var_name} = ')
347-
g.expr(branch.cond.expr)
348-
g.writeln(';')
346+
if g.table.sym(branch.cond.expr_type).kind == .array_fixed {
347+
g.writeln('\t${base_type} ${cond_var_name} = {0};')
348+
g.write('\tmemcpy((${base_type}*)${cond_var_name}, &')
349+
g.expr(branch.cond.expr)
350+
g.writeln(', sizeof(${base_type}));')
351+
} else {
352+
g.write('\t${base_type} ${cond_var_name} = ')
353+
g.expr(branch.cond.expr)
354+
g.writeln(';')
355+
}
349356
} else {
350357
mut is_auto_heap := false
351358
if branch.stmts.len > 0 {

vlib/v/gen/c/index.v

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,11 @@ fn (mut g Gen) index_of_map(node ast.IndexExpr, sym ast.TypeSymbol) {
546546
opt_val_type := g.styp(val_type.set_flag(.option))
547547
g.writeln('${opt_val_type} ${tmp_opt} = {0};')
548548
g.writeln('if (${tmp_opt_ptr}) {')
549-
g.writeln('\t*((${val_type_str}*)&${tmp_opt}.data) = *((${val_type_str}*)${tmp_opt_ptr});')
549+
if val_sym.kind == .array_fixed {
550+
g.writeln('\tmemcpy((${val_type_str}*)${tmp_opt}.data, (${val_type_str}*)${tmp_opt_ptr}, sizeof(${val_type_str}));')
551+
} else {
552+
g.writeln('\t*((${val_type_str}*)&${tmp_opt}.data) = *((${val_type_str}*)${tmp_opt_ptr});')
553+
}
550554
g.writeln('} else {')
551555
g.writeln('\t${tmp_opt}.state = 2; ${tmp_opt}.err = _v_error(_SLIT("map key does not exist"));')
552556
g.writeln('}')
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
struct Serials {
2+
a u8
3+
b u8
4+
c u8
5+
pub mut:
6+
ids map[u8][3]u8
7+
}
8+
9+
pub fn (mut s Serials) id(id u8) {
10+
if _ := s.ids[id] {
11+
} else {
12+
s3 := u8(s.c + s.ids.len)
13+
s.ids[id] = [s.a, s.a, s3]!
14+
}
15+
}
16+
17+
fn test_map_fixed_array_if_guard() {
18+
mut s := Serials{
19+
a: 1
20+
b: 2
21+
}
22+
s.id(u8(3))
23+
println(s)
24+
assert s.ids[3] == [u8(1), 1, 0]!
25+
26+
s.id(u8(4))
27+
println(s)
28+
assert s.ids[4] == [u8(1), 1, 1]!
29+
}

0 commit comments

Comments
 (0)