2 * Copyright 2016 gRPC authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef GRPC_CORE_LIB_SLICE_SLICE_WEAK_HASH_TABLE_H
18 #define GRPC_CORE_LIB_SLICE_SLICE_WEAK_HASH_TABLE_H
20 #include <grpc/support/port_platform.h>
22 #include "src/core/lib/gprpp/memory.h"
23 #include "src/core/lib/gprpp/ref_counted.h"
24 #include "src/core/lib/gprpp/ref_counted_ptr.h"
25 #include "src/core/lib/slice/slice_internal.h"
27 /// Weak hash table implementation.
29 /// This entries in this table are weak: an entry may be removed at any time due
30 /// to a number of reasons: memory pressure, hash collisions, etc.
32 /// The keys are \a grpc_slice objects. The values are of arbitrary type.
34 /// This class is thread unsafe. It's the caller's responsibility to ensure
35 /// proper locking when accessing its methods.
39 template <typename T, size_t Size>
40 class SliceWeakHashTable : public RefCounted<SliceWeakHashTable<T, Size>> {
42 /// Creates a new table of at most \a size entries.
43 static RefCountedPtr<SliceWeakHashTable> Create() {
44 return MakeRefCounted<SliceWeakHashTable<T, Size>>();
47 /// Add a mapping from \a key to \a value, taking ownership of \a key. This
48 /// operation will always succeed. It may discard older entries.
49 void Add(const grpc_slice& key, T value) {
50 const size_t idx = grpc_slice_hash_internal(key) % Size;
51 entries_[idx].Set(key, std::move(value));
55 /// Returns the value from the table associated with / \a key or null if not
57 const T* Get(const grpc_slice& key) const {
58 const size_t idx = grpc_slice_hash_internal(key) % Size;
59 const auto& entry = entries_[idx];
60 return grpc_slice_eq(entry.key(), key) ? entry.value() : nullptr;
64 GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_NEW
65 GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE
67 SliceWeakHashTable() = default;
68 ~SliceWeakHashTable() = default;
70 /// The type of the table "rows".
75 if (is_set_) grpc_slice_unref_internal(key_);
77 const grpc_slice& key() const { return key_; }
79 /// Return the entry's value, or null if unset.
80 const T* value() const {
81 if (!is_set_) return nullptr;
85 /// Set the \a key and \a value (which is moved) for the entry.
86 void Set(const grpc_slice& key, T&& value) {
87 if (is_set_) grpc_slice_unref_internal(key_);
89 value_ = std::move(value);
102 } // namespace grpc_core
104 #endif /* GRPC_CORE_LIB_SLICE_SLICE_WEAK_HASH_TABLE_H */