Skip to content

File ndloop.h

File List > code_source > templat > include > TempLat > util > ndloop.h

Go to the documentation of this file

#ifndef TEMPLAT_UTIL_NDLOOP_H
#define TEMPLAT_UTIL_NDLOOP_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): Franz R. Sattler, Year: 2025

#include <array>
#include <cstddef>
#include <tuple>
#include <utility>

namespace TempLat
{
  template <size_t NDim, typename View, typename Functor>
    requires requires(View v, int i) {
      requires(NDim > 0);
      v.size();
      v.extent(i);
    }
  void NDLoop(const View &view, const Functor &functor)
  {
    std::array<ptrdiff_t, NDim> extents;
    for (size_t i = 0; i < NDim; ++i)
      extents[i] = view.extent(i);

    std::array<ptrdiff_t, NDim> idx;
    for (size_t i = 0; i < NDim; ++i)
      idx[i] = 0;

    while (true) {
      std::apply(functor, idx);
      ptrdiff_t dim = (ptrdiff_t)NDim - 1;
      while (dim < (ptrdiff_t)NDim) {
        idx[dim]++;
        if (idx[dim] < extents[dim]) {
          break;
        } else {
          idx[dim] = 0;
          if (dim == 0) return;
          dim--;
        }
      }
    }
  }
} // namespace TempLat

#endif