Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion include/hyprutils/string/Numeric.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
#include <charconv>
#include <concepts>

#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 200000
#include <string>
#include <cstdlib>
#include <cerrno>
#endif

namespace Hyprutils::String {

enum eNumericParseResult : uint8_t {
Expand Down Expand Up @@ -40,6 +46,47 @@ namespace Hyprutils::String {
}
}

#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 200000
// libc++ < 20 does not implement std::from_chars for floating point types
if constexpr (std::floating_point<T>) {
std::string_view ts = sv;
if (ts.starts_with('+') || ts.starts_with('-'))
ts.remove_prefix(1);
if (ts.size() >= 2 && ts[0] == '0' && (ts[1] == 'x' || ts[1] == 'X'))
return std::unexpected(NUMERIC_PARSE_GARBAGE);

std::string s{sv};
char* endptr = nullptr;
errno = 0;

if constexpr (std::same_as<T, float>)
value = std::strtof(s.c_str(), &endptr);
else if constexpr (std::same_as<T, double>)
value = std::strtod(s.c_str(), &endptr);
else
value = std::strtold(s.c_str(), &endptr);

if (endptr == s.c_str())
return std::unexpected(NUMERIC_PARSE_BAD);
if (errno == ERANGE)
return std::unexpected(NUMERIC_PARSE_OUT_OF_RANGE);
if (endptr != s.c_str() + s.size())
return std::unexpected(NUMERIC_PARSE_GARBAGE);

return value;
} else {
const auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value);

if (ec == std::errc::invalid_argument)
return std::unexpected(NUMERIC_PARSE_BAD);
if (ec == std::errc::result_out_of_range)
return std::unexpected(NUMERIC_PARSE_OUT_OF_RANGE);
if (ptr != sv.data() + sv.size())
return std::unexpected(NUMERIC_PARSE_GARBAGE);

return value;
}
#else
const auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value);

if (ec == std::errc::invalid_argument)
Expand All @@ -50,5 +97,6 @@ namespace Hyprutils::String {
return std::unexpected(NUMERIC_PARSE_GARBAGE);

return value;
#endif
}
};
};
3 changes: 3 additions & 0 deletions tests/os/Process.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

#include <gtest/gtest.h>

#include <sys/types.h>
#include <signal.h>

using namespace Hyprutils::OS;

TEST(OS, process) {
Expand Down
Loading