Skip to content

File hdf5object.h

File List > code_source > templat > include > TempLat > lattice > IO > HDF5 > helpers > hdf5object.h

Go to the documentation of this file

#ifndef TEMPLAT_LATTICE_IO_HDF5_HELPERS_HDF5OBJECT_H
#define TEMPLAT_LATTICE_IO_HDF5_HELPERS_HDF5OBJECT_H

/* This file is part of TempLat, available at https://cosmolattice.github.io/templat .
   Copyright 2021-2026 The TempLat authors, see AUTHORS.md.
   Released under the MIT license, see LICENSE.md. */

// File info: Main contributor(s): Adrien Florio, Year: 2020
#ifdef HAVE_HDF5

#include <string>
#include <vector>
#include "TempLat/lattice/IO/HDF5/helpers/hdf5attribute.h"
#include "TempLat/lattice/IO/HDF5/helpers/hdf5type.h"

namespace TempLat
{

  class HDF5Object
  {
  public:
    /* Put public methods here. These should change very little over time. */
    HDF5Object() : mId(-1) {} // H5I_INVALID_HID, so a default-constructed handle is never a live id

    HDF5Object(const hid_t &id) : mId(id) {}

    HDF5Object(hid_t &&id) : mId(std::move(id)) {}

    operator hid_t &() { return mId; }

    operator const hid_t &() const { return mId; }

    template <typename T> void addAtribute(std::string name, T value) // single value attribute
    {
      const hsize_t dim = 1;
      const auto dataspace_id = H5Screate_simple(1, &dim, nullptr);

      const auto attr_id = H5Acreate2(mId, name.c_str(), HDF5Type<T>().type, dataspace_id, H5P_DEFAULT, H5P_DEFAULT);

      H5Awrite(attr_id, HDF5Type<T>().type, value);
      H5Aclose(attr_id);
      H5Sclose(dataspace_id);
    }

    void addAtribute(std::string name, std::string value) // single value attribute
    {
      addAtribute(name, value.c_str());
    }

    template <typename T> void addAtribute(std::string name, std::vector<T> values) // one-d table of value attribute
    {
      const hsize_t dim = values.size();
      const auto dataspace_id = H5Screate_simple(1, &dim, nullptr);

      const auto attr_id = H5Acreate2(mId, name.c_str(), HDF5Type<T>().type, dataspace_id, H5P_DEFAULT, H5P_DEFAULT);

      H5Awrite(attr_id, HDF5Type<T>().type, values.data());
      H5Aclose(attr_id);
      H5Sclose(dataspace_id);
    }

  private:
    /* Put all member variables and private methods here. These may change arbitrarily. */

  protected:
    hid_t mId;
  };
} // namespace TempLat

#endif

#endif