From 2e29e09b1b19ba54068357e35a34f7ba197fb835 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Mon, 23 Mar 2020 20:02:09 +0100 Subject: [PATCH] cgen: fix map_get: use zero value if the key was not found --- vlib/builtin/map.v | 19 +++++++++++++++++++ vlib/v/gen/cgen.v | 8 ++++++++ 2 files changed, 27 insertions(+) diff --git a/vlib/builtin/map.v b/vlib/builtin/map.v index 35a9a71cec..7f48547e43 100644 --- a/vlib/builtin/map.v +++ b/vlib/builtin/map.v @@ -345,6 +345,25 @@ fn (m map) get2(key string) voidptr { return voidptr(0) } +fn (m map) get3(key string, zero voidptr) voidptr { + mut index,mut meta := m.key_to_index(key) + index,meta = meta_less(m.metas, index, meta) + for meta == m.metas[index] { + kv_index := m.metas[index + 1] + if key == m.key_values.data[kv_index].key { + out := malloc(m.value_bytes) + C.memcpy(out, m.key_values.data[kv_index].value, m.value_bytes) + return out + } + index += 2 + meta += probe_inc + } + out := malloc(m.value_bytes) + C.memcpy(out, zero, m.value_bytes) + return out + //return voidptr(0) +} + fn (m map) exists(key string) bool { if m.value_bytes == 0 { return false diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index f955c61539..e5c81deeac 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -1430,11 +1430,19 @@ fn (g mut Gen) index_expr(node ast.IndexExpr) { g.write(', &($elem_type_str[]) { ') } else { + /* g.write('(*($elem_type_str*)map_get2(') g.expr(node.left) g.write(', ') g.expr(node.index) g.write('))') + */ + zero := g.type_default(info.value_type) + g.write('(*($elem_type_str*)map_get3(') + g.expr(node.left) + g.write(', ') + g.expr(node.index) + g.write(', &($elem_type_str[]){ $zero }))') } } else if sym.kind == .string && !table.type_is_ptr(node.container_type) {