@@ -263,6 +263,28 @@ impl Uint128 {
263
263
Self ( self . 0 . saturating_pow ( exp) )
264
264
}
265
265
266
+ /// This is the same as [`Uint128::add`] but const.
267
+ ///
268
+ /// Panics on overflow.
269
+ #[ must_use = "this returns the result of the operation, without modifying the original" ]
270
+ pub const fn panicking_add ( self , other : Self ) -> Self {
271
+ match self . 0 . checked_add ( other. u128 ( ) ) {
272
+ None => panic ! ( "attempt to add with overflow" ) ,
273
+ Some ( sum) => Self ( sum) ,
274
+ }
275
+ }
276
+
277
+ /// This is the same as [`Uint128::sub`] but const.
278
+ ///
279
+ /// Panics on overflow.
280
+ #[ must_use = "this returns the result of the operation, without modifying the original" ]
281
+ pub const fn panicking_sub ( self , other : Self ) -> Self {
282
+ match self . 0 . checked_sub ( other. u128 ( ) ) {
283
+ None => panic ! ( "attempt to subtract with overflow" ) ,
284
+ Some ( diff) => Self ( diff) ,
285
+ }
286
+ }
287
+
266
288
#[ must_use = "this returns the result of the operation, without modifying the original" ]
267
289
pub const fn abs_diff ( self , other : Self ) -> Self {
268
290
Self ( if self . 0 < other. 0 {
@@ -372,11 +394,7 @@ impl Add<Uint128> for Uint128 {
372
394
type Output = Self ;
373
395
374
396
fn add ( self , rhs : Self ) -> Self {
375
- Self (
376
- self . u128 ( )
377
- . checked_add ( rhs. u128 ( ) )
378
- . expect ( "attempt to add with overflow" ) ,
379
- )
397
+ self . panicking_add ( rhs)
380
398
}
381
399
}
382
400
forward_ref_binop ! ( impl Add , add for Uint128 , Uint128 ) ;
@@ -385,11 +403,7 @@ impl Sub<Uint128> for Uint128 {
385
403
type Output = Self ;
386
404
387
405
fn sub ( self , rhs : Self ) -> Self {
388
- Uint128 (
389
- self . u128 ( )
390
- . checked_sub ( rhs. u128 ( ) )
391
- . expect ( "attempt to subtract with overflow" ) ,
392
- )
406
+ self . panicking_sub ( rhs)
393
407
}
394
408
}
395
409
forward_ref_binop ! ( impl Sub , sub for Uint128 , Uint128 ) ;
@@ -1176,6 +1190,21 @@ mod tests {
1176
1190
assert_eq ! ( a, Uint128 :: from( 1u32 ) ) ;
1177
1191
}
1178
1192
1193
+ #[ test]
1194
+ fn uint128_panicking_sub_works ( ) {
1195
+ let a = Uint128 :: new ( 5 ) ;
1196
+ let b = Uint128 :: new ( 3 ) ;
1197
+ assert_eq ! ( a. panicking_sub( b) , Uint128 :: new( 2 ) ) ;
1198
+ }
1199
+
1200
+ #[ test]
1201
+ #[ should_panic( expected = "attempt to subtract with overflow" ) ]
1202
+ fn uint128_panicking_sub_panics_on_overflow ( ) {
1203
+ let a = Uint128 :: ZERO ;
1204
+ let b = Uint128 :: ONE ;
1205
+ let _diff = a. panicking_sub ( b) ;
1206
+ }
1207
+
1179
1208
#[ test]
1180
1209
fn uint128_abs_diff_works ( ) {
1181
1210
let a = Uint128 :: from ( 42u32 ) ;
0 commit comments