Dune-Fufem 2.11-git
Loading...
Searching...
No Matches
attributes.hh
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright © DUNE-FUFEM Project contributors, see file AUTHORS.md
2// SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception OR LGPL-3.0-or-later
3
4#ifndef DUNE_FUFEM_HDF5_ATTRIBUTES_HH
5#define DUNE_FUFEM_HDF5_ATTRIBUTES_HH
6
7#include <string>
8
9#if __has_include(<hdf5.h>)
10
11#include <hdf5.h>
12
13#include "file.hh"
14
15namespace HDF5 {
16class Attribute {
17public:
18 Attribute(Grouplike &grouplike, std::string key)
19 : grouplike_(grouplike), key_(key) {}
20
21 bool exists() const { return H5Aexists(grouplike_.c_obj(), key_.c_str()); }
22
23 std::string get() const {
24 hid_t root = H5Gopen(grouplike_.c_obj(), "/", H5P_DEFAULT);
25 hid_t attr = H5Aopen_name(root, key_.c_str());
26
27 hid_t attrtype = H5Aget_type(attr);
28 if (H5Tget_class(attrtype) != H5T_STRING)
30 "Only string attributes are supported");
31
32 if (H5Tis_variable_str(attrtype))
34 "Variable-size attributes are not supported");
35
36 hid_t nativetype = H5Tget_native_type(attrtype, H5T_DIR_ASCEND);
37 std::vector<char> buffer(H5Tget_size(attrtype));
38 if (H5Aread(attr, nativetype, buffer.data()) < 0)
39 DUNE_THROW(Dune::Exception, "Failed to read attribute: " << key_);
40 H5Tclose(nativetype);
41
42 H5Aclose(attr);
43 H5Gclose(root);
44
45 return {buffer.begin(), buffer.end()};
46 }
47
48 void set(std::string value) {
49 hid_t stringtype = H5Tcopy(H5T_C_S1); // A C-style string
50 H5Tset_size(stringtype, value.size());
51 hid_t dataspace = H5Screate(H5S_SCALAR);
52
53 hid_t root = H5Gopen(grouplike_.c_obj(), "/", H5P_DEFAULT);
54 hid_t attr = H5Acreate(root, key_.c_str(), stringtype, dataspace,
55 H5P_DEFAULT, H5P_DEFAULT);
56 H5Awrite(attr, stringtype, value.c_str());
57
58 H5Aclose(attr);
59 H5Gclose(root);
60 H5Sclose(dataspace);
61 H5Tclose(stringtype);
62 }
63
64private:
65 Grouplike &grouplike_;
66 std::string key_;
67};
68}
69
70#else
71 #warning Including the hdf5/attributes.hh but hdf5.h is missing.
72#endif // __has_include(<hdf5.h>)
73
74#endif
static TupleAccessTraits< typenameAtType< N, Tuple >::Type >::NonConstType get(Tuple &t)
bool exists(size_type i, size_type j) const
#define DUNE_THROW(E,...)