libSplash
H5IdWrapper.hpp
1 
23 #ifndef H5ID_WRAPPER_HPP
24 #define H5ID_WRAPPER_HPP
25 
26 #include "splash/core/splashMacros.hpp"
27 
28 #include <hdf5.h>
29 
30 
31 namespace splash
32 {
33  namespace policies
34  {
35  template<typename T>
36  struct NoCopy
37  {
38  static T copy(const T&)
39  {
40  // Make it depend on template parameter
41  SPLASH_UNUSED static char copyNotAllowed[sizeof(T) ? -1 : 0];
42  }
43 
44  static bool release(const T&)
45  {
46  return true;
47  }
48  };
49 
50  template<typename T>
51  struct RefCounted
52  {
53  RefCounted(): refCt_(new unsigned)
54  {
55  *refCt_ = 1;
56  }
57 
58  T copy(const T& obj)
59  {
60  ++*refCt_;
61  return obj;
62  }
63 
64  bool release(const T&)
65  {
66  if(!--*refCt_)
67  {
68  delete refCt_;
69  refCt_ = NULL;
70  return true;
71  }
72  return false;
73  }
74 
75  friend void swap(RefCounted& lhs, RefCounted& rhs)
76  {
77  std::swap(lhs.refCt_, rhs.refCt_);
78  }
79  private:
80  unsigned* refCt_;
81  };
82  }
83 
89  template<H5_DLL herr_t (*T_CloseMethod)(hid_t), template<class> class T_DestructionPolicy>
90  struct H5IdWrapper: public T_DestructionPolicy<hid_t>
91  {
92  typedef T_DestructionPolicy<hid_t> DestructionPolicy;
93 
94  H5IdWrapper(): id_(-1){}
95  explicit H5IdWrapper(hid_t id): id_(id){}
96  H5IdWrapper(const H5IdWrapper& rhs): DestructionPolicy(rhs)
97  {
98  id_ = DestructionPolicy::copy(rhs.id_);
99  }
100 
101  H5IdWrapper& operator=(const H5IdWrapper& rhs)
102  {
103  H5IdWrapper tmp(rhs);
104  swap(*this, tmp);
105  return *this;
106  }
107 
108  ~H5IdWrapper()
109  {
110  if(DestructionPolicy::release(id_))
111  {
112  if(id_ >= 0)
113  T_CloseMethod(id_);
114  }
115  }
116 
118  void close()
119  {
120  reset(-1);
121  }
122 
124  void reset(hid_t id)
125  {
126  H5IdWrapper tmp(id);
127  swap(*this, tmp);
128  }
129 
132  hid_t release()
133  {
134  hid_t id = id_;
135  id_ = -1;
136  return id;
137  }
138 
139  operator hid_t() const { return id_; }
140  operator bool() const { return id_ >= 0; }
141 
142  friend void swap(H5IdWrapper& lhs, H5IdWrapper& rhs)
143  {
144  std::swap(lhs.id_, rhs.id_);
145  std::swap(static_cast<DestructionPolicy&>(lhs), static_cast<DestructionPolicy&>(rhs));
146  }
147 
148  private:
149  hid_t id_;
150  };
151 
164 
165  template<H5_DLL herr_t (*T_CloseMethod)(hid_t), template<class> class T_DestructionPolicy>
167  {
168  return static_cast<hid_t>(lhs) == static_cast<hid_t>(rhs);
169  }
170  template<H5_DLL herr_t (*T_CloseMethod)(hid_t), template<class> class T_DestructionPolicy>
172  {
173  return !(lhs == rhs);
174  }
175 }
176 
177 #endif /* H5ID_WRAPPER_HPP */
H5IdWrapper< H5Oclose, policies::NoCopy > H5ObjectId
void reset(hid_t id)
H5IdWrapper< H5Tclose, policies::NoCopy > H5TypeId
H5IdWrapper< H5Sclose, policies::NoCopy > H5DataspaceId
H5IdWrapper< H5Aclose, policies::NoCopy > H5AttributeId