Implement map key exists in mgp (#1336)

This commit is contained in:
Matija Pintarić 2023-10-23 15:29:41 +02:00 committed by GitHub
parent aec4c3dd2b
commit 97ed912ab6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 31 additions and 0 deletions

View File

@ -355,6 +355,8 @@ inline size_t map_size(mgp_map *map) { return MgInvoke<size_t>(mgp_map_size, map
inline mgp_value *map_at(mgp_map *map, const char *key) { return MgInvoke<mgp_value *>(mgp_map_at, map, key); }
inline bool key_exists(mgp_map *map, const char *key) { return MgInvoke<int>(mgp_key_exists, map, key); }
inline const char *map_item_key(mgp_map_item *item) { return MgInvoke<const char *>(mgp_map_item_key, item); }
inline mgp_value *map_item_value(mgp_map_item *item) { return MgInvoke<mgp_value *>(mgp_map_item_value, item); }

View File

@ -482,6 +482,9 @@ enum mgp_error mgp_map_size(struct mgp_map *map, size_t *result);
/// Result is NULL if no mapping exists.
enum mgp_error mgp_map_at(struct mgp_map *map, const char *key, struct mgp_value **result);
/// Returns true if key in map.
enum mgp_error mgp_key_exists(struct mgp_map *map, const char *key, int *result);
/// An item in the mgp_map.
struct mgp_map_item;

View File

@ -630,6 +630,9 @@ class Map {
/// @brief Returns the value at the given `key`.
Value const At(std::string_view key) const;
/// @brief Returns true if the given `key` exists.
bool KeyExists(std::string_view key) const;
class Iterator {
public:
friend class Map;
@ -2573,6 +2576,8 @@ inline const Value Map::At(std::string_view key) const {
return Value();
}
inline bool Map::KeyExists(std::string_view key) const { return mgp::key_exists(ptr_, key.data()); }
inline Map::Iterator::Iterator(mgp_map_items_iterator *map_items_iterator) : map_items_iterator_(map_items_iterator) {
if (map_items_iterator_ == nullptr) return;
if (mgp::map_items_iterator_get(map_items_iterator_) == nullptr) {

View File

@ -1096,6 +1096,18 @@ mgp_error mgp_map_at(mgp_map *map, const char *key, mgp_value **result) {
result);
}
mgp_error mgp_key_exists(mgp_map *map, const char *key, int *result) {
return WrapExceptions(
[&map, &key]() -> int {
auto found_it = map->items.find(key);
if (found_it == map->items.end()) {
return 0;
};
return 1;
},
result);
}
mgp_error mgp_map_item_key(mgp_map_item *item, const char **result) {
return WrapExceptions([&item] { return item->key; }, result);
}

View File

@ -758,3 +758,12 @@ TYPED_TEST(CppApiTestFixture, TestInAndOutDegrees) {
ASSERT_EQ(node_2.OutDegree(), 0);
ASSERT_EQ(node_3.OutDegree(), 0);
}
TYPED_TEST(CppApiTestFixture, TestMapKeyExist) {
mgp::Map map = mgp::Map();
map.Insert("key", mgp::Value("string"));
ASSERT_EQ(true, map.KeyExists("key"));
ASSERT_EQ(false, map.KeyExists("no_existo"));
map.Insert("null_key", mgp::Value());
ASSERT_EQ(true, map.KeyExists("null_key"));
}