Forked from
Eclipse Projects / aidge / aidge_core
2287 commits behind the upstream repository.
-
Olivier BICHLER authoredOlivier BICHLER authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
Formatting.hpp 2.16 KiB
/********************************************************************************
* Copyright (c) 2023 CEA-List
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
#ifndef AIDGE_FORMATTING_H_
#define AIDGE_FORMATTING_H_
#include <memory>
#include <string>
#include <vector>
namespace Aidge {
// The code snippet below is licensed under CC0 1.0.
template<typename ... Args>
std::string stringFormat(const std::string& format, Args... args) {
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
// Disable security warning on GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
#elif defined(_MSC_VER)
// Disable security warning on MSVC
#pragma warning(push)
#pragma warning(disable : 4774)
#endif
int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
if (size_s <= 0) {
std::printf("Error during formatting.");
std::abort();
}
auto size = static_cast<size_t>(size_s);
std::unique_ptr<char[]> buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic pop
#elif defined(_MSC_VER)
#pragma warning(pop)
#endif
}
/**
* Print any iterable object in a std::string.
*/
template <class T, typename F>
std::string print(const T& vec, const std::string& format, const F& func) {
std::string str = "{";
bool first = true;
for (const auto& val : vec) {
if (!first) {
str += ", ";
}
else {
first = false;
}
str += stringFormat(format, func(val));
}
str += "}";
return str;
}
template <class T>
std::string print(const T& vec, const std::string& format) {
return print(vec, format, [](auto val){ return val; });
}
}
#endif //AIDGE_FORMATTING_H_