lsst.afw  18.1.0-18-gf57f4888d+1
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 <algorithm>
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: correctly handling const vs. non-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 
258  template <typename T, typename std::enable_if_t<!IS_SMART_PTR<T>, int> = 0>
259  T& at(Key<K, T> const& key) {
260  // Both casts are safe; see Effective C++, Item 3
261  return const_cast<T&>(static_cast<const GenericMap&>(*this).at(key));
262  }
263 
264  template <typename T, typename std::enable_if_t<!IS_SMART_PTR<T>, int> = 0>
265  T const& at(Key<K, T> const& key) const {
266  // Delegate to private methods to hide further special-casing of T
267  return _at(key);
268  }
269 
270  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
272  // Delegate to private methods to hide further special-casing of T
273  return _at(key);
274  }
275 
278  virtual size_type size() const noexcept = 0;
280 
282  virtual bool empty() const noexcept = 0;
283 
291  virtual size_type max_size() const noexcept = 0;
292 
306  template <typename T>
307  size_type count(Key<K, T> const& key) const {
308  return contains(key) ? 1 : 0;
309  }
310 
323  virtual bool contains(K const& key) const = 0;
324 
343  template <typename T>
344  bool contains(Key<K, T> const& key) const {
345  // Delegate to private methods to hide special-casing of T
346  return _contains(key);
347  }
348 
363  virtual std::vector<K> const& keys() const noexcept = 0;
364 
379  virtual bool operator==(GenericMap const& other) const noexcept {
380  auto keys1 = this->keys();
381  auto keys2 = other.keys();
382  if (!std::is_permutation(keys1.begin(), keys1.end(), keys2.begin(), keys2.end())) {
383  return false;
384  }
385  for (K const& key : keys1) {
386  if (this->unsafeLookup(key) != other.unsafeLookup(key)) {
387  return false;
388  }
389  }
390  return true;
391  }
392 
393  bool operator!=(GenericMap const& other) const { return !(*this == other); }
394 
456  template <class Visitor>
457  auto apply(Visitor&& visitor) const {
458  // Delegate to private methods to hide special-casing of Visitor
459  return _apply(visitor);
460  }
461 
478  template <class Visitor>
479  auto apply(Visitor&& visitor) {
480  // Delegate to private methods to hide special-casing of Visitor
481  return _apply(visitor);
482  }
483 
484 private:
485  // Transformations between value/reference/ref-to-const versions of internal variant type, to let
486  // the set of value types supported by GenericMap be defined only once
487  // Icky TMP, but I can't find another way to get at the template arguments for variant :(
488  // Methods have no definition but can't be deleted without breaking type definitions below
489 
491  // may need to use std::reference_wrapper when migrating to std::variant, but it confuses Boost
492  template <typename... Types>
493  static boost::variant<std::add_lvalue_reference_t<Types>...> _typeToRef(
494  boost::variant<Types...> const&) noexcept;
495  template <typename... Types>
496  static boost::variant<std::add_lvalue_reference_t<std::add_const_t<Types>>...> _typeToConstRef(
497  boost::variant<Types...> const&) noexcept;
499 
500 protected:
506  // Use int, long, long long instead of int32_t, int64_t because C++ doesn't
507  // consider signed integers of the same length but different names equivalent
508  using StorableType = boost::variant<bool, int, long, long long, float, double, std::string,
510 
517  // this mouthful is shorter than the equivalent expression with result_of
518  using ConstValueReference = decltype(_typeToConstRef(std::declval<StorableType>()));
519  using ValueReference = decltype(_typeToRef(std::declval<StorableType>()));
520 
538  virtual ConstValueReference unsafeLookup(K key) const = 0;
539 
541  ConstValueReference constRef = static_cast<const GenericMap&>(*this).unsafeLookup(key);
542  auto removeConst = [](auto const& value) -> ValueReference {
543  using NonConstRef = std::add_lvalue_reference_t<
544  std::remove_const_t<std::remove_reference_t<decltype(value)>>>;
545  // This cast is safe; see Effective C++, Item 3
546  return const_cast<NonConstRef>(value);
547  };
548  return boost::apply_visitor(removeConst, constRef);
549  }
550 
553 private:
554  // Neither Storable nor shared_ptr<Storable>
555  template <typename T,
556  typename std::enable_if_t<
558  T const& _at(Key<K, T> const& key) const {
559  static_assert(!std::is_const<T>::value,
560  "Due to implementation constraints, const keys are not supported.");
561  try {
562  auto foo = unsafeLookup(key.getId());
563  return boost::get<T const&>(foo);
564  } catch (boost::bad_get const&) {
565  std::stringstream message;
566  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
568  }
569  }
570 
571  // Storable and its subclasses
572  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
573  T const& _at(Key<K, T> const& key) const {
574  static_assert(!std::is_const<T>::value,
575  "Due to implementation constraints, const keys are not supported.");
576  try {
577  auto foo = unsafeLookup(key.getId());
578  // Don't use pointer-based get, because it won't work after migrating to std::variant
579  Storable const& value = boost::get<PolymorphicValue const&>(foo);
580  T const* typedPointer = dynamic_cast<T const*>(&value);
581  if (typedPointer != nullptr) {
582  return *typedPointer;
583  } else {
584  std::stringstream message;
585  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
587  }
588  } catch (boost::bad_get const&) {
589  std::stringstream message;
590  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
592  }
593  }
594 
595  // shared_ptr<Storable>
596  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
597  std::shared_ptr<T> _at(Key<K, std::shared_ptr<T>> const& key) const {
598  static_assert(std::is_const<T>::value,
599  "Due to implementation constraints, pointers to non-const are not supported.");
600  try {
601  auto foo = unsafeLookup(key.getId());
602  auto pointer = boost::get<std::shared_ptr<Storable const> const&>(foo);
603  if (pointer == nullptr) { // dynamic_cast not helpful
604  return nullptr;
605  }
606 
607  std::shared_ptr<T> typedPointer = std::dynamic_pointer_cast<T>(pointer);
608  // shared_ptr can be empty without being null. dynamic_pointer_cast
609  // only promises result of failed cast is empty, so test for that
610  if (typedPointer.use_count() > 0) {
611  return typedPointer;
612  } else {
613  std::stringstream message;
614  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
616  }
617  } catch (boost::bad_get const&) {
618  std::stringstream message;
619  message << "Key " << key << " not found, but a key labeled " << key.getId() << " is present.";
621  }
622  }
623 
624  // Neither Storable nor shared_ptr<Storable>
625  template <typename T,
626  typename std::enable_if_t<
628  bool _contains(Key<K, T> const& key) const {
629  // Avoid actually getting and casting an object, if at all possible
630  if (!contains(key.getId())) {
631  return false;
632  }
633 
634  auto foo = unsafeLookup(key.getId());
635  // boost::variant has no equivalent to std::holds_alternative
636  try {
637  boost::get<T const&>(foo);
638  return true;
639  } catch (boost::bad_get const&) {
640  return false;
641  }
642  }
643 
644  // Storable and its subclasses
645  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
646  bool _contains(Key<K, T> const& key) const {
647  // Avoid actually getting and casting an object, if at all possible
648  if (!contains(key.getId())) {
649  return false;
650  }
651 
652  auto foo = unsafeLookup(key.getId());
653  try {
654  // Don't use pointer-based get, because it won't work after migrating to std::variant
655  Storable const& value = boost::get<PolymorphicValue const&>(foo);
656  auto asT = dynamic_cast<T const*>(&value);
657  return asT != nullptr;
658  } catch (boost::bad_get const&) {
659  return false;
660  }
661  }
662 
663  // shared_ptr<Storable>
664  template <typename T, typename std::enable_if_t<std::is_base_of<Storable, T>::value, int> = 0>
665  bool _contains(Key<K, std::shared_ptr<T>> const& key) const {
666  static_assert(std::is_const<T>::value,
667  "Due to implementation constraints, pointers to non-const are not supported.");
668  // Avoid actually getting and casting an object, if at all possible
669  if (!contains(key.getId())) {
670  return false;
671  }
672 
673  auto foo = unsafeLookup(key.getId());
674  try {
675  auto pointer = boost::get<std::shared_ptr<Storable const> const&>(foo);
676  if (pointer == nullptr) { // Can't confirm type with dynamic_cast
677  return true;
678  }
679  std::shared_ptr<T> typedPointer = std::dynamic_pointer_cast<T>(pointer);
680  // shared_ptr can be empty without being null. dynamic_pointer_cast
681  // only promises result of failed cast is empty, so test for that
682  return typedPointer.use_count() > 0;
683  } catch (boost::bad_get const&) {
684  return false;
685  }
686  }
687 
688  // Type alias to properly handle Visitor output
689  // Assume that each operator() has the same return type; variant will enforce it
691  template <class Visitor>
692  using _VisitorResult = std::result_of_t<Visitor && (K&&, bool&)>;
694 
695  // No return value, const GenericMap
696  template <class Visitor, typename std::enable_if_t<std::is_void<_VisitorResult<Visitor>>::value, int> = 0>
697  void _apply(Visitor&& visitor) const {
698  for (K const& key : keys()) {
699  boost::variant<K> varKey = key;
700  boost::apply_visitor(visitor, varKey, unsafeLookup(key));
701  }
702  }
703 
704  // Return value, const GenericMap
705  template <class Visitor,
706  typename std::enable_if_t<!std::is_void<_VisitorResult<Visitor>>::value, int> = 0>
707  auto _apply(Visitor&& visitor) const {
709  results.reserve(size());
710 
711  for (K const& key : keys()) {
712  boost::variant<K> varKey = key;
713  results.emplace_back(boost::apply_visitor(visitor, varKey, unsafeLookup(key)));
714  }
715  return results;
716  }
717 
718  // No return value, non-const GenericMap
719  template <class Visitor, typename std::enable_if_t<std::is_void<_VisitorResult<Visitor>>::value, int> = 0>
720  void _apply(Visitor&& visitor) {
721  for (K const& key : keys()) {
722  boost::variant<K> varKey = key;
723  // Boost gets confused if we pass it a temporary variant
724  ValueReference ref = unsafeLookup(key);
725  boost::apply_visitor(visitor, varKey, ref);
726  }
727  }
728 
729  // Return value, non-const GenericMap
730  template <class Visitor,
731  typename std::enable_if_t<!std::is_void<_VisitorResult<Visitor>>::value, int> = 0>
732  auto _apply(Visitor&& visitor) {
734  results.reserve(size());
735 
736  for (K const& key : keys()) {
737  boost::variant<K> varKey = key;
738  // Boost gets confused if we pass it a temporary variant
739  ValueReference ref = unsafeLookup(key);
740  results.emplace_back(boost::apply_visitor(visitor, varKey, ref));
741  }
742  return results;
743  }
744 };
745 
756 template <typename K>
757 class MutableGenericMap : public GenericMap<K> {
758 protected:
759  using typename GenericMap<K>::StorableType;
760 
761 public:
762  virtual ~MutableGenericMap() noexcept = default;
763 
769  virtual void clear() noexcept = 0;
770 
789  template <typename T>
790  bool insert(Key<K, T> const& key, T const& value) {
791  if (this->contains(key.getId())) {
792  return false;
793  }
794 
795  return unsafeInsert(key.getId(), StorableType(value));
796  }
797 
813  template <typename T>
814  std::pair<Key<K, T>, bool> insert(K const& key, T const& value) {
815  auto strongKey = makeKey<T>(key);
816  // Construct return value in advance, so that exception from copying/moving Key is atomic
817  auto result = make_pair(strongKey, false);
818  result.second = insert(strongKey, value);
819  return result;
820  }
821 
835  template <typename T>
836  bool erase(Key<K, T> const& key) {
837  if (this->contains(key)) {
838  return unsafeErase(key.getId());
839  } else {
840  return false;
841  }
842  }
843 
844 protected:
857  virtual bool unsafeInsert(K key, StorableType&& value) = 0;
858 
868  virtual bool unsafeErase(K key) = 0;
869 };
870 
871 } // namespace typehandling
872 } // namespace afw
873 } // namespace lsst
874 
875 namespace std {
876 template <typename K, typename V>
877 struct hash<typename lsst::afw::typehandling::Key<K, V>> {
880  size_t operator()(argument_type const& obj) const noexcept { return obj.hash_value(); }
881 };
882 } // namespace std
883 
884 #endif
T is_permutation(T... args)
auto apply(Visitor &&visitor)
Apply a modifying operation to each key-value pair in the map.
Definition: GenericMap.h:479
boost::variant< bool, int, long, long long, float, double, std::string, PolymorphicValue, std::shared_ptr< Storable const > > StorableType
The types that can be stored in a map.
Definition: GenericMap.h:509
size_type count(Key< K, T > const &key) const
Return the number of elements mapped to the specified key.
Definition: GenericMap.h:307
bool operator!=(GenericMap const &other) const
Test for map equality.
Definition: GenericMap.h:393
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:836
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:271
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:259
Interface supporting iteration over heterogenous containers.
Definition: Storable.h:56
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:880
decltype(_typeToConstRef(std::declval< StorableType >())) ConstValueReference
A type-agnostic reference to the value stored inside the map.
Definition: GenericMap.h:518
STL namespace.
constexpr bool operator==(Key< K, V > const &other) const noexcept
Test for key equality.
Definition: GenericMap.h:103
bool contains(Key< K, T > const &key) const
Return true if this map contains a mapping for the specified key.
Definition: GenericMap.h:344
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:265
STL class.
Key for type-safe lookup in a GenericMap.
Definition: GenericMap.h:62
virtual ConstValueReference unsafeLookup(K key) const =0
Return a reference to the mapped value of the element with key equal to key.
A base class for image defects.
Key< U > key
Definition: Schema.cc:281
auto apply(Visitor &&visitor) const
Apply an operation to each key-value pair in the map.
Definition: GenericMap.h:457
T str(T... args)
constexpr Key(K id)
Construct a new key.
Definition: GenericMap.h:78
ValueReference unsafeLookup(K key)
Return a reference to the mapped value of the element with key equal to key.
Definition: GenericMap.h:540
typename lsst::afw::typehandling::Key< K, V > argument_type
Definition: GenericMap.h:878
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,...)
virtual bool operator==(GenericMap const &other) const noexcept
Test for map equality.
Definition: GenericMap.h:379
decltype(_typeToRef(std::declval< StorableType >())) ValueReference
A type-agnostic reference to the value stored inside the map.
Definition: GenericMap.h:519
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:814
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:790
Interface for a GenericMap that allows element addition and removal.
Definition: GenericMap.h:757
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
T reserve(T... args)
T emplace_back(T... args)