From 17e8c1d6283518bcae25ca656f148e26ee7d6461 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Tue, 30 Jul 2019 21:27:31 +0200 Subject: [PATCH] map.delete(key) --- vlib/builtin/map.v | 26 ++++++++++++++++++++++++++ vlib/builtin/map_test.v | 6 ++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/vlib/builtin/map.v b/vlib/builtin/map.v index 1ed9f89c98..ea6ab03db4 100644 --- a/vlib/builtin/map.v +++ b/vlib/builtin/map.v @@ -169,6 +169,32 @@ fn (m map) get(key string, out voidptr) bool { return m.root.find(key, out, m.element_size) } +pub fn (n mut Node) delete(key string, element_size int) { + if n.key == key { + C.memset(n.val, 0, element_size) + return + } + else if n.key > key { + if isnil(n.left) { + return + } else { + n.left.delete(key, element_size) + } + } + else { + if isnil(n.right) { + return + } else { + n.right.delete(key, element_size) + } + } +} + +pub fn (m mut map) delete(key string) { + m.root.delete(key, m.element_size) + m.size-- +} + pub fn (m map) exists(key string) bool { panic('map.exists(key) was removed from the language. Use `key in map` instead.') return false diff --git a/vlib/builtin/map_test.v b/vlib/builtin/map_test.v index b4c5edac7d..e493e6d5a2 100644 --- a/vlib/builtin/map_test.v +++ b/vlib/builtin/map_test.v @@ -36,13 +36,15 @@ fn test_map() { assert keys.len == 2 assert keys[0] == 'hi' assert keys[1] == 'hello' + m.delete('hi') + assert m.size == 1 + assert m['hi'] == 0 + //assert m.keys().len == 1 //// mut users := map[string]User{} users['1'] = User{'Peter'} peter := users['1'] assert peter.name == 'Peter' - println(peter.name) - mut a := A{ m: map[string]int{} users: map[string]User{}