Refactors Folly map test cases to use cdsstress library
[folly.git] / folly / stress-test / map_test.h
1 #ifndef _FOLLY_MAP_TEST_H
2 #define _FOLLY_MAP_TEST_H
3
4 #include <folly/concurrency/ConcurrentHashMap.h>
5 #include <folly/AtomicHashMap.h>
6 #include <folly/AtomicUnorderedMap.h>
7
8 #include <cds_test/stress_test.h>
9 #include <cds_test/stress_test_util.h>
10
11 #include <algorithm>
12 #include <iostream>
13 #include <memory>
14 #include <random>
15 #include <thread>
16
17 namespace folly_test {
18
19 typedef folly::ConcurrentHashMap<size_t, size_t> ConcurrentHashMap;
20 typedef folly::AtomicHashMap<size_t, size_t> AtomicHashMap;
21 typedef folly::AtomicUnorderedInsertMap64<size_t, size_t>
22     AtomicUnorderedInsertMap;
23
24 // AtomicUnorderedInsertMap
25 template <typename Key, typename Value>
26 bool map_insert(AtomicUnorderedInsertMap* map, Key key, Value value) {
27   auto iter = map->find(key);
28   if (iter == map->cend() || iter->second != value) {
29     // Insert/update the <key,value> pair
30     map->emplace(key, value);
31     return true;
32   } else {
33     return false;
34   }
35 }
36
37 // AtomicHashMap
38 template <typename Key, typename Value>
39 bool map_insert(AtomicHashMap* map, Key key, Value value) {
40   auto iter = map->find(key);
41   if (iter == map->end() || iter->second != value) {
42     // Insert/update the <key,value> pair
43     map->insert({key, value});
44     return true;
45   } else {
46     return false;
47   }
48 }
49
50 // ConcurrentHashMap
51 template <typename Key, typename Value>
52 bool map_insert(ConcurrentHashMap * map, Key key, Value value) {
53   auto iter = map->find(key);
54   if (iter == map->cend() || iter->second != value) {
55     // Insert/update the <key,value> pair
56     map->insert({key, value});
57     return true;
58   } else {
59     return false;
60   }
61 }
62
63 template <typename Map, typename Key>
64 bool map_find(const Map* map, Key key) {
65   return map->find(key) != map->cend();
66 }
67
68 // Specialization for AtomicHashMap
69 template <typename Key>
70 bool map_find(const AtomicHashMap* map, Key key) {
71   return map->find(key) != map->end();
72 }
73
74 // Doesn't erase for AtomicUnorderedInsertMap & AtomicHashMap, but returns
75 // whether the key exists in the map.
76 template <typename Map, typename Key>
77 bool map_delete(Map* map, Key key) {
78   return map_find(map, key);
79 }
80
81 // Specialization for ConcurrentHashMap
82 template <typename Key>
83 bool map_delete(ConcurrentHashMap* map, Key key) {
84   if (map_find(map, key)) {
85     map->erase(key);
86     return true;
87   } else {
88     return false;
89   }
90 }
91
92 } // namespace folly_test
93
94 #endif