From a91bd5a5bb036e1b426e04e5d533c6496254fe49 Mon Sep 17 00:00:00 2001 From: CC Date: Thu, 12 May 2022 00:43:01 -0600 Subject: [PATCH] builtin: add a map.clear() method (#14373) --- vlib/builtin/map.v | 8 ++++++++ vlib/builtin/map_test.v | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/vlib/builtin/map.v b/vlib/builtin/map.v index faed595665..622ccdffd7 100644 --- a/vlib/builtin/map.v +++ b/vlib/builtin/map.v @@ -294,6 +294,14 @@ pub fn (mut m map) move() map { return r } +// clear clears the map without deallocating the allocated data. +// It does it by setting the map length to `0` +// Example: a.clear() // `a.len` and `a.key_values.len` is now 0 +pub fn (mut m map) clear() { + m.len = 0 + m.key_values.len = 0 +} + [inline] fn (m &map) key_to_index(pkey voidptr) (u32, u32) { hash := m.hash_fn(pkey) diff --git a/vlib/builtin/map_test.v b/vlib/builtin/map_test.v index 672efc3b09..4ed7a09860 100644 --- a/vlib/builtin/map_test.v +++ b/vlib/builtin/map_test.v @@ -245,6 +245,14 @@ fn test_mut_arg() { assert a == 10 } +fn test_clear() { + mut m := map[string]int{} + m['one'] = 1 + m['two'] = 2 + m.clear() + assert m.len == 0 +} + fn test_delete() { mut m := map[string]int{} m['one'] = 1