Seastar
High performance C++ framework for concurrent servers
indirect.hh
1 /*
2  * This file is open source software, licensed to you under the terms
3  * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4  * distributed with this work for additional information regarding copyright
5  * ownership. You may not use this file except in compliance with the License.
6  *
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing,
12  * software distributed under the License is distributed on an
13  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14  * KIND, either express or implied. See the License for the
15  * specific language governing permissions and limitations
16  * under the License.
17  */
18 /*
19  * Copyright (C) 2016 ScyllaDB
20  */
21 
22 #pragma once
23 
24 #include <memory>
25 
26 namespace seastar {
27 
28 // This header defines functors for comparing and hashing pointers by pointed-to values instead of pointer addresses.
29 //
30 // Examples:
31 //
32 // std::multiset<shared_ptr<sstring>, indirect_less<shared_ptr<sstring>>> _multiset;
33 //
34 // std::unordered_map<shared_ptr<sstring>, bool,
35 // indirect_hash<shared_ptr<sstring>>, indirect_equal_to<shared_ptr<sstring>>> _unordered_map;
36 //
37 
38 template<typename Pointer, typename Equal = std::equal_to<typename std::pointer_traits<Pointer>::element_type>>
40  Equal _eq;
41  indirect_equal_to(Equal eq = Equal()) : _eq(std::move(eq)) {}
42  bool operator()(const Pointer& i1, const Pointer& i2) const {
43  if (bool(i1) ^ bool(i2)) {
44  return false;
45  }
46  return !i1 || _eq(*i1, *i2);
47  }
48 };
49 
50 template<typename Pointer, typename Less = std::less<typename std::pointer_traits<Pointer>::element_type>>
51 struct indirect_less {
52  Less _cmp;
53  indirect_less(Less cmp = Less()) : _cmp(std::move(cmp)) {}
54  bool operator()(const Pointer& i1, const Pointer& i2) const {
55  if (i1 && i2) {
56  return _cmp(*i1, *i2);
57  }
58  return !i1 && i2;
59  }
60 };
61 
62 template<typename Pointer, typename Hash = std::hash<typename std::pointer_traits<Pointer>::element_type>>
63 struct indirect_hash {
64  Hash _h;
65  indirect_hash(Hash h = Hash()) : _h(std::move(h)) {}
66  size_t operator()(const Pointer& p) const {
67  if (p) {
68  return _h(*p);
69  }
70  return 0;
71  }
72 };
73 
74 }
Seastar API namespace.
Definition: abort_on_ebadf.hh:24
Definition: indirect.hh:39
Definition: indirect.hh:63
Definition: indirect.hh:51