1 #include "hdf_id_helper.h"
2 
3 #define THROW(_ex) throw _ex
4 
5 #define THROW_ON_ERROR(code) \
6     if (code < 0) THROW(Exception())
7 
8 namespace ont { namespace hdf5 {
9 
10 static_assert(std::is_same<Id,hid_t>::value, "Mismatched ID types");
11 
claim(Id id)12 IdRef IdRef::claim(Id id)
13 {
14     if (id < 0 || H5Iis_valid(id) <= 0) {
15         THROW(Exception());
16     }
17     return IdRef(id);
18 }
19 
ref(Id id)20 IdRef IdRef::ref(Id id)
21 {
22     assert(id >= 0);
23     THROW_ON_ERROR(H5Iinc_ref(id));
24     return IdRef(id);
25 }
26 
global_ref(Id id)27 IdRef IdRef::global_ref(Id id)
28 {
29     assert(id >= 0);
30 
31     // Increment the index here - never decrementing it.
32     THROW_ON_ERROR(H5Iinc_ref(id));
33     return global(id);
34 }
35 
IdRef(IdRef const & other)36 IdRef::IdRef(IdRef const& other)
37     : m_id(other.m_id)
38     , m_is_global_constant(other.m_is_global_constant)
39 {
40     if (!m_is_global_constant && m_id >= 0) {
41         THROW_ON_ERROR(H5Iinc_ref(m_id));
42     }
43 }
44 
operator =(IdRef const & other)45 IdRef& IdRef::operator=(IdRef const& other)
46 {
47     if (!other.m_is_global_constant && other.m_id >= 0) {
48         THROW_ON_ERROR(H5Iinc_ref(other.m_id));
49     }
50     if (!m_is_global_constant && m_id >= 0) {
51         auto result = H5Idec_ref(m_id);
52         if (result < 0) {
53             // this will be logged by the auto-logging code
54             // (see install_error_function)
55             assert(false);
56         }
57     }
58     m_is_global_constant = other.m_is_global_constant;
59     m_id = other.m_id;
60     return *this;
61 }
62 
~IdRef()63 IdRef::~IdRef()
64 {
65     if (!m_is_global_constant && m_id >= 0) {
66         auto result = H5Idec_ref(m_id);
67         if (result < 0) {
68             // this will be logged by the auto-logging code
69             // (see install_error_function)
70             assert(false);
71         }
72     }
73 }
74 
ref_count() const75 int IdRef::ref_count() const
76 {
77     if (m_id < 0) {
78         return 0;
79     }
80     return H5Iget_ref(m_id);
81 }
82 
83 }}