|
1 | 1 | use crate::num::traits::{
|
2 |
| - BitSize, Bounded, CheckedAdd, CheckedMul, CheckedSub, OverflowingAdd, OverflowingMul, |
| 2 | + BitSize, Bounded, CheckedAdd, CheckedMul, CheckedSub, DivRem, OverflowingAdd, OverflowingMul, |
3 | 3 | OverflowingSub, Pow, SaturatingAdd, SaturatingMul, SaturatingSub, WrappingAdd, WrappingMul,
|
4 | 4 | WrappingSub,
|
5 | 5 | };
|
| 6 | +#[feature("generic-divrem")] |
| 7 | +use crate::traits::DivRem as DivRemLegacy; |
| 8 | +use crate::zeroable::NonZero; |
6 | 9 |
|
7 | 10 |
|
8 | 11 | #[test]
|
@@ -467,3 +470,57 @@ fn test_pow() {
|
467 | 470 | assert_eq!(2.pow(9), 0b1000000000);
|
468 | 471 | assert_eq!(2.pow(10), 0b10000000000);
|
469 | 472 | }
|
| 473 | + |
| 474 | + |
| 475 | +// Bridge-driven generic division: u32 / u32 |
| 476 | +#[test] |
| 477 | +fn test_divrem_generic_u32() { |
| 478 | + let lhs: u32 = 27; |
| 479 | + let rhs: NonZero<u32> = 4_u32.try_into().unwrap(); |
| 480 | + |
| 481 | + let (q, r) = DivRem::<u32, u32>::div_rem(lhs, rhs); |
| 482 | + |
| 483 | + assert_eq!(q, 6); |
| 484 | + assert_eq!(r, 3); |
| 485 | +} |
| 486 | + |
| 487 | + |
| 488 | +// Legacy API still works |
| 489 | +#[test] |
| 490 | +fn test_divrem_legacy_u32() { |
| 491 | + let lhs: u32 = 27; |
| 492 | + let rhs: NonZero<u32> = 4_u32.try_into().unwrap(); |
| 493 | + |
| 494 | + let (q, r) = DivRemLegacy::<u32>::div_rem(lhs, rhs); |
| 495 | + |
| 496 | + assert_eq!(q, 6); |
| 497 | + assert_eq!(r, 3); |
| 498 | +} |
| 499 | + |
| 500 | +#[test] |
| 501 | +fn test_divrem_u256_by_u128() { |
| 502 | + // Heterogeneous example: u256 / u128. |
| 503 | + // We supply a one-off impl in the test so corelib proper remains minimal. |
| 504 | + |
| 505 | + let lhs: u256 = 20; |
| 506 | + let rhs: NonZero<u128> = 6_u128.try_into().unwrap(); |
| 507 | + |
| 508 | + let (q, r) = DivRem::<u256, u128>::div_rem(lhs, rhs); |
| 509 | + assert_eq!(q, 3_u256); |
| 510 | + assert_eq!(r, 2_u128); |
| 511 | +} |
| 512 | + |
| 513 | +// Local impl so the test can call DivRem<u256,u128>. |
| 514 | +impl U256ByU128DivRem of DivRem<u256, u128> { |
| 515 | + type Quotient = u256; |
| 516 | + type Remainder = u128; |
| 517 | + |
| 518 | + fn div_rem(lhs: u256, rhs: NonZero<u128>) -> (u256, u128) { |
| 519 | + // Reuse the old symmetric trait on (u256,u256). |
| 520 | + let rhs_u128: u128 = rhs.into(); |
| 521 | + let rhs_u256: u256 = rhs_u128.into(); |
| 522 | + let rhs_u256_nz: NonZero<u256> = rhs_u256.try_into().unwrap(); |
| 523 | + let (q, r_u256) = DivRemLegacy::<u256>::div_rem(lhs, rhs_u256_nz); |
| 524 | + (q, r_u256.try_into().unwrap()) |
| 525 | + } |
| 526 | +} |
0 commit comments