Skip to content

Commit

Permalink
Improve docs and test for to_int_unchecked
Browse files Browse the repository at this point in the history
  • Loading branch information
danakj committed Dec 3, 2023
1 parent a803cb3 commit 51ed5a4
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
18 changes: 13 additions & 5 deletions sus/num/__private/float_methods.inc
Original file line number Diff line number Diff line change
Expand Up @@ -936,12 +936,20 @@ sus_pure inline _self to_degrees() const& noexcept {
sus_pure inline _self to_radians() const& noexcept {
return primitive_value * (consts::PI.primitive_value / _primitive{180});
}
/// Rounds toward zero and converts to any primitive integer type, assuming
/// that the value is finite and fits in that type.
template <Integer I>
sus_pure constexpr inline I to_int_unchecked(

/// Rounds toward zero and converts to any [safe integer type]($sus::num)
/// assuming that the value is finite and fits in that type.
///
/// # Safety
/// To avoid Undefined Behaviour, the value must:
/// * Not be `NaN`.
/// * Not be infinite.
/// * Be representable in the return type `Int`, after truncating off its
/// fractional part.
template <Integer Int>
sus_pure constexpr inline Int to_int_unchecked(
::sus::marker::UnsafeFnMarker) const& noexcept {
return static_cast<decltype(I::primitive_value)>(primitive_value);
return static_cast<decltype(Int::primitive_value)>(primitive_value);
}

/// Raw transmutation from `##_unsigned##`.
Expand Down
3 changes: 3 additions & 0 deletions sus/num/f32_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1007,10 +1007,13 @@ TEST(f32, ToRadians) {

TEST(f32, ToIntUnchecked) {
auto a = (198.054321_f32).to_int_unchecked<u8>(unsafe_fn);
static_assert(std::same_as<decltype(a), u8>);
EXPECT_EQ(a, 198_u8);
auto b = (198.054321_f32).to_int_unchecked<u32>(unsafe_fn);
static_assert(std::same_as<decltype(b), u32>);
EXPECT_EQ(b, 198_u32);
auto c = (-108.054321_f32).to_int_unchecked<i8>(unsafe_fn);
static_assert(std::same_as<decltype(c), i8>);
EXPECT_EQ(c, -108_i8);
}

Expand Down
3 changes: 3 additions & 0 deletions sus/num/f64_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1015,10 +1015,13 @@ TEST(f64, ToRadians) {

TEST(f64, ToIntUnchecked) {
auto a = (198.054321_f64).to_int_unchecked<u8>(unsafe_fn);
static_assert(std::same_as<decltype(a), u8>);
EXPECT_EQ(a, 198_u8);
auto b = (198.054321_f64).to_int_unchecked<u32>(unsafe_fn);
static_assert(std::same_as<decltype(b), u32>);
EXPECT_EQ(b, 198_u32);
auto c = (-108.054321_f64).to_int_unchecked<i8>(unsafe_fn);
static_assert(std::same_as<decltype(c), i8>);
EXPECT_EQ(c, -108_i8);
}

Expand Down

0 comments on commit 51ed5a4

Please sign in to comment.