lsst.afw  17.0.1-26-ga1fda76f0
GenericMap.h
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 /*
3  * This file is part of afw.
4  *
5  * Developed for the LSST Data Management System.
6  * This product includes software developed by the LSST Project
7  * (https://www.lsst.org).
8  * See the COPYRIGHT file at the top-level directory of this distribution
9  * for details of code ownership.
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <https://www.gnu.org/licenses/>.
23  */
24 
25 #ifndef LSST_AFW_TYPEHANDLING_GENERICMAP_H
26 #define LSST_AFW_TYPEHANDLING_GENERICMAP_H
27 
28 #include <cstdint>
29 #include <functional>
30 #include <ostream>
31 #include <memory>
32 #include <sstream>
33 #include <typeinfo>
34 #include <type_traits>
35 #include <unordered_set>
36 #include <vector>
37 
38 #include "boost/core/demangle.hpp"
39 #include "boost/variant.hpp"
40 
41 #include "lsst/pex/exceptions.h"
44 
45 namespace lsst {
46 namespace afw {
47 namespace typehandling {
48 
61 template <typename K, typename V>
62 class Key final {
63 public:
64  using KeyType = K;
65  using ValueType = V;
66 
78  constexpr Key(K id) : id(id) {}
79 
80  Key(Key const&) = default;
81  Key(Key&&) = default;
82  Key& operator=(Key const&) = delete;
83  Key& operator=(Key&&) = delete;
84 
93  constexpr K const& getId() const noexcept { return id; }
94 
103  constexpr bool operator==(Key<K, V> const& other) const noexcept { return this->id == other.id; }
104 
105  template <typename U>
106  constexpr std::enable_if_t<!std::is_same<U, V>::value, bool> operator==(Key<K, U> const&) const noexcept {
107  return false;
108  }
109 
110  template <typename U>
111  constexpr bool operator!=(Key<K, U> const& other) const noexcept {
112  return !(*this == other);
113  }
114 
130  template <typename U>
131  constexpr bool operator<(Key<K, U> const& other) const noexcept {
132  const std::less<K> comparator;
133  return comparator(this->getId(), other.getId());
134  }
135 
137  std::size_t hash_value() const noexcept { return std::hash<K>()(id); }
138 
139 private:
141  K const id;
142 };
143 
159 // template parameters must be reversed for inference to work correctly
160 template <typename V, typename K>
161 constexpr Key<K, V> makeKey(K const& id) {
162  return Key<K, V>(id);
163 }
164 
183 template <typename K, typename V>
184 std::ostream& operator<<(std::ostream& os, Key<K, V> const& key) {
185  static const std::string typeStr = boost::core::demangle(typeid(V).name());
186  static const std::string constStr = std::is_const<V>::value ? " const" : "";
187  static const std::string volatileStr = std::is_volatile<V>::value ? " volatile" : "";
188  os << key.getId() << "<" << typeStr << constStr << volatileStr << ">";
189  return os;
190 }
191 
192 // Test for smart pointers as "any type with an element_type member"
193 // Second template parameter is a dummy to let us do some metaprogramming
194 template <typename, typename = void>
195 constexpr bool IS_SMART_PTR = false;
196 template <typename T>
197 constexpr bool IS_SMART_PTR<T, std::enable_if_t<std::is_object<typename T::element_type>::value>> = true;
198 
227 // TODO: const keys should be possible in C++17 with std::variant
228 template <typename K>
229 class GenericMap {
230 public:
231  using key_type = K;
234 
235  virtual ~GenericMap() noexcept = default;
236 
254  template <typename T, typename std::enable_if_t<!IS_SMART_PTR<T>, int> = 0>
255  T& at(Key<K, T> const& key) {
256  // Both casts are safe; see Effective C++, Item 3
257  return const_cast<T&>(static_cast<const GenericMap&>(*this).at(key));
258  }
259 
260  // Can't partially specialize method templates, rely on enable_if to avoid duplicates
261  template <typename T,
262  typename std::enable_if_t<
264  T const& at(Key<K, T> const& key) const {
265  static_assert(!std::is_const<T>::value,
266  "Due to implementation constraints, const keys are not supported.");
267  try {
268  auto foo = unsafeLookup(key.getId());
269  return boost::get<T const&>(foo);
270  } catch (boost::bad_get const&) {
271  std::stringstream message;
272  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
274  }
275  }
276 
277  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
278  T const& at(Key<K, T> const& key) const {
279  static_assert(!std::is_const<T>::value,
280  "Due to implementation constraints, const keys are not supported.");
281  try {
282  auto foo = unsafeLookup(key.getId());
283  // Don't use pointer-based get, because it won't work after migrating to std::variant
284  Storable const& value = boost::get<PolymorphicValue const&>(foo);
285  T const* typedPointer = dynamic_cast<T const*>(&value);
286  if (typedPointer != nullptr) {
287  return *typedPointer;
288  } else {
289  std::stringstream message;
290  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
292  }
293  } catch (boost::bad_get const&) {
294  std::stringstream message;
295  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
297  }
298  }
299 
300  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
302  static_assert(!std::is_const<T>::value,
303  "Due to implementation constraints, const keys are not supported.");
304  try {
305  auto foo = unsafeLookup(key.getId());
306  auto pointer = boost::get<std::shared_ptr<Storable> const&>(foo);
307  std::shared_ptr<T> typedPointer = std::dynamic_pointer_cast<T>(pointer);
308  // shared_ptr can be empty without being null. dynamic_pointer_cast
309  // only promises result of failed cast is empty, so test for that
310  if (typedPointer.use_count() > 0) {
311  return typedPointer;
312  } else {
313  std::stringstream message;
314  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
316  }
317  } catch (boost::bad_get const&) {
318  std::stringstream message;
319  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
321  }
322  }
323 
326  virtual size_type size() const noexcept = 0;
328 
330  virtual bool empty() const noexcept = 0;
331 
339  virtual size_type max_size() const noexcept = 0;
340 
354  template <typename T>
355  size_type count(Key<K, T> const& key) const {
356  return contains(key) ? 1 : 0;
357  }
358 
371  virtual bool contains(K const& key) const = 0;
372 
393  // Can't partially specialize method templates, rely on enable_if to avoid duplicates
394  template <typename T,
395  typename std::enable_if_t<
397  bool contains(Key<K, T> const& key) const {
398  // Avoid actually getting and casting an object, if at all possible
399  if (!contains(key.getId())) {
400  return false;
401  }
402 
403  auto foo = unsafeLookup(key.getId());
404  // boost::variant has no equivalent to std::holds_alternative
405  try {
406  boost::get<T const&>(foo);
407  return true;
408  } catch (boost::bad_get const&) {
409  return false;
410  }
411  }
412 
413  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
414  bool contains(Key<K, T> const& key) const {
415  // Avoid actually getting and casting an object, if at all possible
416  if (!contains(key.getId())) {
417  return false;
418  }
419 
420  auto foo = unsafeLookup(key.getId());
421  try {
422  // Don't use pointer-based get, because it won't work after migrating to std::variant
423  Storable const& value = boost::get<PolymorphicValue const&>(foo);
424  auto asT = dynamic_cast<T const*>(&value);
425  return asT != nullptr;
426  } catch (boost::bad_get const&) {
427  return false;
428  }
429  }
430 
431  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
432  bool contains(Key<K, std::shared_ptr<T>> const& key) const {
433  // Avoid actually getting and casting an object, if at all possible
434  if (!contains(key.getId())) {
435  return false;
436  }
437 
438  auto foo = unsafeLookup(key.getId());
439  try {
440  auto pointer = boost::get<std::shared_ptr<Storable> const&>(foo);
441  std::shared_ptr<T> typedPointer = std::dynamic_pointer_cast<T>(pointer);
442  // shared_ptr can be empty without being null. dynamic_pointer_cast
443  // only promises result of failed cast is empty, so test for that
444  return typedPointer.use_count() > 0;
445  } catch (boost::bad_get const&) {
446  return false;
447  }
448  }
449 
463  virtual std::vector<K> keys() const = 0;
464 
479  virtual bool operator==(GenericMap const& other) const {
480  auto keys1 = this->keySet();
481  auto keys2 = other.keySet();
482  if (keys1 != keys2) {
483  return false;
484  }
485  for (K const& key : keys1) {
486  if (this->unsafeLookup(key) != other.unsafeLookup(key)) {
487  return false;
488  }
489  }
490  return true;
491  }
492 
493  bool operator!=(GenericMap const& other) const { return !(*this == other); }
494 
497 private:
498  // Icky TMP, but I can't find another way to get at the template arguments for variant :(
499  // Method has no definition but can't be deleted without breaking definition of StorableType
501  template <typename... Types>
502  static boost::variant<std::decay_t<Types>...> _referenceToType(boost::variant<Types...> const&) noexcept;
504 
505 protected:
511  // may need to use std::reference_wrapper when migrating to std::variant, but it confuses Boost
512  using ValueReference =
513  boost::variant<bool const&, std::int32_t const&, std::int64_t const&, float const&, double const&,
515 
521  // this mouthful is shorter than the equivalent expression with result_of
522  using StorableType = decltype(_referenceToType(std::declval<ValueReference>()));
523 
537  virtual ValueReference unsafeLookup(K key) const = 0;
538 
539 private:
545  std::unordered_set<K> keySet() const {
546  auto rawKeys = keys();
547  return std::unordered_set<K>(rawKeys.begin(), rawKeys.end());
548  }
549 };
550 
561 template <typename K>
562 class MutableGenericMap : public GenericMap<K> {
563 protected:
564  using typename GenericMap<K>::StorableType;
565 
566 public:
567  virtual ~MutableGenericMap() noexcept = default;
568 
574  virtual void clear() noexcept = 0;
575 
594  template <typename T>
595  bool insert(Key<K, T> const& key, T const& value) {
596  if (this->contains(key.getId())) {
597  return false;
598  }
599 
600  return unsafeInsert(key.getId(), StorableType(value));
601  }
602 
618  template <typename T>
619  std::pair<Key<K, T>, bool> insert(K const& key, T const& value) {
620  auto strongKey = makeKey<T>(key);
621  // Construct return value in advance, so that exception from copying/moving Key is atomic
622  auto result = make_pair(strongKey, false);
623  result.second = insert(strongKey, value);
624  return result;
625  }
626 
640  template <typename T>
641  bool erase(Key<K, T> const& key) {
642  if (this->contains(key)) {
643  return unsafeErase(key.getId());
644  } else {
645  return false;
646  }
647  }
648 
649 protected:
662  virtual bool unsafeInsert(K key, StorableType&& value) = 0;
663 
673  virtual bool unsafeErase(K key) = 0;
674 };
675 
676 } // namespace typehandling
677 } // namespace afw
678 } // namespace lsst
679 
680 namespace std {
681 template <typename K, typename V>
682 struct hash<typename lsst::afw::typehandling::Key<K, V>> {
685  size_t operator()(argument_type const& obj) const noexcept { return obj.hash_value(); }
686 };
687 } // namespace std
688 
689 #endif
size_type count(Key< K, T > const &key) const
Return the number of elements mapped to the specified key.
Definition: GenericMap.h:355
bool operator!=(GenericMap const &other) const
Test for map equality.
Definition: GenericMap.h:493
virtual bool operator==(GenericMap const &other) const
Test for map equality.
Definition: GenericMap.h:479
def keys(self)
bool erase(Key< K, T > const &key)
Remove the mapping for a key from this map, if it exists.
Definition: GenericMap.h:641
Container that passes Storable objects by value while preserving type.
std::shared_ptr< T > at(Key< K, std::shared_ptr< T >> const &key) const
Return a reference to the mapped value of the element with key equal to key.
Definition: GenericMap.h:301
T & at(Key< K, T > const &key)
Return a reference to the mapped value of the element with key equal to key.
Definition: GenericMap.h:255
Interface supporting iteration over heterogenous containers.
Definition: Storable.h:61
constexpr Key< K, V > makeKey(K const &id)
Factory function for Key, to enable type parameter inference.
Definition: GenericMap.h:161
size_t operator()(argument_type const &obj) const noexcept
Definition: GenericMap.h:685
STL namespace.
constexpr bool operator==(Key< K, V > const &other) const noexcept
Test for key equality.
Definition: GenericMap.h:103
ItemVariant const * other
Definition: Schema.cc:56
T const & at(Key< K, T > const &key) const
Return a reference to the mapped value of the element with key equal to key.
Definition: GenericMap.h:264
STL class.
Key for type-safe lookup in a GenericMap.
Definition: GenericMap.h:62
bool contains(Key< K, T > const &key) const
Return true if this map contains a mapping for the specified key.
Definition: GenericMap.h:397
boost::variant< bool const &, std::int32_t const &, std::int64_t const &, float const &, double const &, std::string const &, PolymorphicValue const &, std::shared_ptr< Storable > const & > ValueReference
A type-agnostic reference to the value stored inside the map.
Definition: GenericMap.h:514
A base class for image defects.
decltype(_referenceToType(std::declval< ValueReference >())) StorableType
The types that can be stored in a map.
Definition: GenericMap.h:522
virtual ValueReference unsafeLookup(K key) const =0
Return a reference to the mapped value of the element with key equal to key.
Key< U > key
Definition: Schema.cc:281
T str(T... args)
constexpr Key(K id)
Construct a new key.
Definition: GenericMap.h:78
typename lsst::afw::typehandling::Key< K, V > argument_type
Definition: GenericMap.h:683
T dynamic_pointer_cast(T... args)
constexpr bool operator!=(Key< K, U > const &other) const noexcept
Test for key equality.
Definition: GenericMap.h:111
std::unique_ptr< SchemaItem< U > > result
Definition: Schema.cc:195
std::size_t hash_value() const noexcept
Return a hash of this object.
Definition: GenericMap.h:137
#define LSST_EXCEPT(type,...)
STL class.
std::pair< Key< K, T >, bool > insert(K const &key, T const &value)
Insert an element into the map, if the map doesn&#39;t already contain a mapping with a conflicting key...
Definition: GenericMap.h:619
bool contains(Key< K, std::shared_ptr< T >> const &key) const
Return true if this map contains a mapping for the specified key.
Definition: GenericMap.h:432
constexpr bool IS_SMART_PTR
Definition: GenericMap.h:195
bool insert(Key< K, T > const &key, T const &value)
Insert an element into the map, if the map doesn&#39;t already contain a mapping with the same or a confl...
Definition: GenericMap.h:595
Interface for a GenericMap that allows element addition and removal.
Definition: GenericMap.h:562
constexpr K const & getId() const noexcept
Return the identifier of this field.
Definition: GenericMap.h:93
std::ostream * os
Definition: Schema.cc:746
STL class.
Interface for a heterogeneous map.
Definition: GenericMap.h:229
Key & operator=(Key const &)=delete