RMF
handle.h
Go to the documentation of this file.
1 /**
2  * \file RMF/HDF5/handle.h
3  * \brief Handle read/write of Model data from/to files.
4  *
5  * Copyright 2007-2022 IMP Inventors. All rights reserved.
6  *
7  */
8 
9 #ifndef RMF_HDF5__HANDLE_H
10 #define RMF_HDF5__HANDLE_H
11 
12 #include "RMF/config.h"
13 #include "infrastructure_macros.h"
14 #include "RMF/exceptions.h"
15 #include <hdf5.h>
16 #include <algorithm>
17 #include <vector>
18 #include <exception>
19 
20 #include <limits>
21 #include <boost/utility.hpp>
22 
23 #ifdef SWIG
24 typedef int hid_t;
25 #endif
26 
27 RMF_ENABLE_WARNINGS
28 namespace RMF {
29 namespace HDF5 {
30 
31 #ifndef SWIG
32 //! The signature for the HDF5 close functions
33 typedef herr_t (*HDF5CloseFunction)(hid_t);
34 
35 //! Make sure an HDF5 handle is released
36 /** CloseFunction should be an appropriate close function
37  for the handle type, e.g. H5Aclose. Handle is not available
38  in python.
39  */
40 class RMFEXPORT Handle : public boost::noncopyable {
41  hid_t h_;
43 
44  public:
45  Handle(hid_t h, HDF5CloseFunction f, std::string operation) : h_(h), f_(f) {
46  if (h_ < 0) {
47  RMF_THROW(
48  Message(std::string("Invalid handle returned from ") + operation),
49  IOException);
50  }
51  }
52  Handle() : h_(-1), f_(nullptr) {}
53  hid_t get_hid() const {
54  RMF_USAGE_CHECK(h_ >= 0, "Uninitialized handle used.");
55  return h_;
56  }
57  operator hid_t() const { return h_; }
58  bool get_is_open() const { return h_ != -1; }
59  void open(hid_t h, HDF5CloseFunction f) {
60  if (get_is_open()) {
61  close();
62  }
63  h_ = h;
64  RMF_USAGE_CHECK(h_ >= 0, "Invalid handle returned");
65  f_ = f;
66  }
67  void close() {
68  if (h_ != -1) {
69  RMF_HDF5_CALL(f_(h_));
70  }
71  h_ = -1;
72  }
73 // Older clang does not like exception specification in combination
74 // with std::shared_ptr
75 #if defined(__clang__) && __clang_major__ <= 7
76  ~Handle() {
77 #else
78  ~Handle() noexcept(false) {
79 #endif
80  if (h_ != -1) {
81  RMF_HDF5_CALL(f_(h_));
82  }
83  }
84 };
85 
86 //! Share an HDF5 handle
87 class RMFEXPORT SharedHandle : public Handle {
88  public:
89  SharedHandle(hid_t h, HDF5CloseFunction f, std::string operation)
90  : Handle(h, f, operation) {}
91 };
92 
93 #endif // SWIG
94 
95 } /* namespace HDF5 */
96 } /* namespace RMF */
97 
98 RMF_DISABLE_WARNINGS
99 
100 #endif /* RMF_HDF5__HANDLE_H */
Various general useful macros for IMP.
Make sure an HDF5 handle is released.
Definition: handle.h:40
Share an HDF5 handle.
Definition: handle.h:87
Declarations of the various exception types.
herr_t(* HDF5CloseFunction)(hid_t)
The signature for the HDF5 close functions.
Definition: handle.h:33
#define RMF_HDF5_CALL(v)
Include all non-deprecated headers in RMF.HDF5.