diff options
| author | batsumaru <> | 2026-08-10 19:27:13 +0900 |
|---|---|---|
| committer | batsumaru <> | 2026-08-10 19:27:13 +0900 |
| commit | 8918325808f9e474c473f4e1c1b4e4e73b8187cf (patch) | |
| tree | 74628a2a1a7e28baa303484f968fa9aae9e242ca | |
| parent | 1fe44b8855c0e83c443e8cbaeeedf25fbe342849 (diff) | |
Fixed casting, added fatal error
| -rw-r--r-- | include/fatal_error.h | 16 | ||||
| -rw-r--r-- | src/fixed_point.cpp | 26 |
2 files changed, 32 insertions, 10 deletions
diff --git a/include/fatal_error.h b/include/fatal_error.h new file mode 100644 index 0000000..06e1b88 --- /dev/null +++ b/include/fatal_error.h @@ -0,0 +1,16 @@ +#ifndef FATAL_ERROR_H +#define FATAL_ERROR_H + +#include <format> +#include <cstdlib> +#include <cstdio> + +template <typename... Args> +[[noreturn]] void fatal_error(std::format_string<Args...> fmt, Args&&... args) { + std::string msg = std::format(fmt, std::forward<Args>(args)...); + std::fputs(msg.c_str(), stderr); + std::fputc('\n', stderr); + std::abort(); +} + +#endif diff --git a/src/fixed_point.cpp b/src/fixed_point.cpp index 8b4b937..a39f2bc 100644 --- a/src/fixed_point.cpp +++ b/src/fixed_point.cpp @@ -1,37 +1,43 @@ #include "fixed_point.h" -#include <cstdlib> -#include <cstdio> +#include "fatal_error.h" +#include <limits> fp_t fp_t::operator+(const fp_t& other) const { - return {(std::int32_t)((std::uint32_t)raw + (std::uint32_t)other.raw)}; + return {static_cast<std::int32_t>(static_cast<std::uint32_t>(raw) + static_cast<std::uint32_t>(other.raw))}; } fp_t fp_t::operator-(const fp_t& other) const { - return {(std::int32_t)((std::uint32_t)raw - (std::uint32_t)other.raw)}; + return {static_cast<std::int32_t>(static_cast<std::uint32_t>(raw) - static_cast<std::uint32_t>(other.raw))}; } fp_t fp_t::operator*(const fp_t& other) const { std::int32_t result; std::int64_t temp; - temp = (std::int64_t)raw * (std::int64_t)other.raw; + temp = static_cast<std::int64_t>(raw) * static_cast<std::int64_t>(other.raw); temp += fp_t::K; - result = (std::int32_t)(temp >> fp_t::Q); + result = static_cast<std::int32_t>(temp >> fp_t::Q); return {result}; } fp_t fp_t::operator/(const fp_t& other) const { if (other.raw == 0) { - std::fprintf(stderr, "fp_t: division by zero\n"); - std::abort(); + fatal_error("fp_t: division by zero"); } - std::int64_t temp = (std::int64_t)raw << fp_t::Q; + std::int64_t temp = static_cast<std::int64_t>(raw) << fp_t::Q; if ((temp >= 0 && other.raw >= 0) || (temp < 0 && other.raw < 0)) { temp += (other.raw / 2); } else { temp -= (other.raw / 2); } - return {(std::int32_t)(temp / other.raw)}; + + temp = temp / other.raw; + + if (temp > std::numeric_limits<std::int32_t>::max() || + temp < std::numeric_limits<std::int32_t>::min()) { + fatal_error("fp_t: division overflow (raw={} / raw={})", raw, other.raw); + } + return {static_cast<std::int32_t>(temp)}; } bool fp_t::operator==(const fp_t& other) const { |
