OpenPFC  0.1.4
Phase Field Crystal simulation framework
Loading...
Searching...
No Matches
utils.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 VTT Technical Research Centre of Finland Ltd
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
34#ifndef PFC_UTILS_HPP
35#define PFC_UTILS_HPP
36
37#include <memory>
38#include <mpi.h>
39#include <sstream>
40#include <stdexcept>
41#include <string>
42#include <vector>
43
44namespace pfc {
45namespace utils {
46
47// Overload for no format arguments - just return the string as-is
48inline std::string string_format(const std::string &str) { return str; }
49
50template <typename... Args>
51inline std::string string_format(const std::string &format, Args... args) {
52 size_t size =
53 snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
54 if (size <= 0) {
55 throw std::runtime_error("Error during formatting.");
56 }
57 std::unique_ptr<char[]> buf(new char[size]);
58 snprintf(buf.get(), size, format.c_str(), args...);
59 return std::string(buf.get(),
60 buf.get() + size - 1); // We don't want the '\0' inside
61}
62
63inline std::string format_with_number(const std::string &filename, int increment) {
64 if (filename.find('%') != std::string::npos) {
65 return utils::string_format(filename, increment);
66 } else {
67 return filename;
68 }
69}
70
71template <typename T> size_t sizeof_vec(std::vector<T> &V) {
72 return V.size() * sizeof(T);
73}
74
75} // namespace utils
76
77namespace mpi {
78
79inline int get_comm_rank(MPI_Comm comm) {
80 int rank;
81 MPI_Comm_rank(comm, &rank);
82 return rank;
83}
84
85inline int get_comm_size(MPI_Comm comm) {
86 int size;
87 MPI_Comm_size(comm, &size);
88 return size;
89}
90
91} // namespace mpi
92
93} // namespace pfc
94
95#endif