1//! Copy the sign over from another number.
2
3use super::{F32, SIGN_MASK};
4
5impl F32 {
6 /// Returns a number composed of the magnitude of `self` and the sign of
7 /// `sign`.
8 pub fn copysign(self, sign: Self) -> Self {
9 let source_bits: u32 = sign.to_bits();
10 let source_sign: u32 = source_bits & SIGN_MASK;
11 let signless_destination_bits: u32 = self.to_bits() & !SIGN_MASK;
12 Self::from_bits(signless_destination_bits | source_sign)
13 }
14}
15
16#[cfg(test)]
17mod tests {
18 use super::F32;
19
20 #[test]
21 fn sanity_check() {
22 assert_eq!(F32(1.0).copysign(F32(-1.0)).0, -1.0);
23 assert_eq!(F32(-1.0).copysign(F32(1.0)).0, 1.0);
24 assert_eq!(F32(1.0).copysign(F32(1.0)).0, 1.0);
25 assert_eq!(F32(-1.0).copysign(F32(-1.0)).0, -1.0);
26
27 let large_float = F32(100_000_000.13425345345);
28 assert_eq!(large_float.copysign(-large_float), -large_float);
29 assert_eq!((-large_float).copysign(large_float), large_float);
30 assert_eq!(large_float.copysign(large_float), large_float);
31 assert_eq!((-large_float).copysign(-large_float), -large_float);
32 }
33}
34