Skip to content

Commit 51ed5a4

Browse files
committed
Improve docs and test for to_int_unchecked
1 parent a803cb3 commit 51ed5a4

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

sus/num/__private/float_methods.inc

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -936,12 +936,20 @@ sus_pure inline _self to_degrees() const& noexcept {
936936
sus_pure inline _self to_radians() const& noexcept {
937937
return primitive_value * (consts::PI.primitive_value / _primitive{180});
938938
}
939-
/// Rounds toward zero and converts to any primitive integer type, assuming
940-
/// that the value is finite and fits in that type.
941-
template <Integer I>
942-
sus_pure constexpr inline I to_int_unchecked(
939+
940+
/// Rounds toward zero and converts to any [safe integer type]($sus::num)
941+
/// assuming that the value is finite and fits in that type.
942+
///
943+
/// # Safety
944+
/// To avoid Undefined Behaviour, the value must:
945+
/// * Not be `NaN`.
946+
/// * Not be infinite.
947+
/// * Be representable in the return type `Int`, after truncating off its
948+
/// fractional part.
949+
template <Integer Int>
950+
sus_pure constexpr inline Int to_int_unchecked(
943951
::sus::marker::UnsafeFnMarker) const& noexcept {
944-
return static_cast<decltype(I::primitive_value)>(primitive_value);
952+
return static_cast<decltype(Int::primitive_value)>(primitive_value);
945953
}
946954

947955
/// Raw transmutation from `##_unsigned##`.

sus/num/f32_unittest.cc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1007,10 +1007,13 @@ TEST(f32, ToRadians) {
10071007

10081008
TEST(f32, ToIntUnchecked) {
10091009
auto a = (198.054321_f32).to_int_unchecked<u8>(unsafe_fn);
1010+
static_assert(std::same_as<decltype(a), u8>);
10101011
EXPECT_EQ(a, 198_u8);
10111012
auto b = (198.054321_f32).to_int_unchecked<u32>(unsafe_fn);
1013+
static_assert(std::same_as<decltype(b), u32>);
10121014
EXPECT_EQ(b, 198_u32);
10131015
auto c = (-108.054321_f32).to_int_unchecked<i8>(unsafe_fn);
1016+
static_assert(std::same_as<decltype(c), i8>);
10141017
EXPECT_EQ(c, -108_i8);
10151018
}
10161019

sus/num/f64_unittest.cc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,10 +1015,13 @@ TEST(f64, ToRadians) {
10151015

10161016
TEST(f64, ToIntUnchecked) {
10171017
auto a = (198.054321_f64).to_int_unchecked<u8>(unsafe_fn);
1018+
static_assert(std::same_as<decltype(a), u8>);
10181019
EXPECT_EQ(a, 198_u8);
10191020
auto b = (198.054321_f64).to_int_unchecked<u32>(unsafe_fn);
1021+
static_assert(std::same_as<decltype(b), u32>);
10201022
EXPECT_EQ(b, 198_u32);
10211023
auto c = (-108.054321_f64).to_int_unchecked<i8>(unsafe_fn);
1024+
static_assert(std::same_as<decltype(c), i8>);
10221025
EXPECT_EQ(c, -108_i8);
10231026
}
10241027

0 commit comments

Comments
 (0)