yuge optimization of fastreadnum

This commit is contained in:
2026-01-02 01:44:06 +01:00
parent 12fdf93377
commit d6a7179ba5

View File

@@ -1,6 +1,8 @@
#ifndef UTILS_HPP
#define UTILS_HPP
#include <charconv>
#include <cstdint>
#include <filesystem>
#include <format>
@@ -20,15 +22,25 @@ ssize_t readFile(const std::string& path, char* buffer, size_t maxlen);
ssize_t readFile(const char* path, char* buffer, size_t maxlen);
std::string getFirstDir(const std::string_view& path);
template <size_t N>
inline int fastReadNum(const std::string& path, char (&buf)[N]) {
/* reads a number from file REALLY fast */
template <typename T, size_t N>
inline void fastReadNum(const std::string& path, char (&buf)[N], T& result) {
readFile(path, buf, N);
int ret = 0;
std::from_chars(buf, buf + N, ret);
return ret;
std::from_chars(buf, buf + N, result);
}
inline std::string pNum(auto num, uint8_t decs = 0) {
/* reads a number slightly slower and divides it */
template <uint32_t Divider, typename T, size_t N>
inline void fastReadNumDiv(const std::string& path, char (&buf)[N], T& result) {
uint64_t temp{};
fastReadNum(path, buf, temp);
if constexpr (std::is_floating_point_v<T>)
result = temp / static_cast<T>(Divider);
else
result = static_cast<T>(temp / Divider);
}
inline std::string pNum(const auto num, const uint8_t decs = 0) {
return std::format("{:.{}f}", num, decs);
}