1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Implementation of [`Bounded`], a wrapper around integer types limiting the number of bits 4 //! usable for value representation. 5 6 use core::{ 7 cmp, 8 fmt, 9 ops::{ 10 self, 11 Deref, // 12 }, //, 13 }; 14 15 use kernel::{ 16 num::Integer, 17 prelude::*, // 18 }; 19 20 /// Evaluates to `true` if `$value` can be represented using at most `$n` bits in a `$type`. 21 /// 22 /// `expr` must be of type `type`, or the result will be incorrect. 23 /// 24 /// Can be used in const context. 25 macro_rules! fits_within { 26 ($value:expr, $type:ty, $n:expr) => {{ 27 let shift: u32 = <$type>::BITS - $n; 28 29 // `value` fits within `$n` bits if shifting it left by the number of unused bits, then 30 // right by the same number, doesn't change it. 31 // 32 // This method has the benefit of working for both unsigned and signed values. 33 ($value << shift) >> shift == $value 34 }}; 35 } 36 37 /// Returns `true` if `value` can be represented with at most `N` bits in a `T`. 38 #[inline(always)] 39 fn fits_within<T: Integer>(value: T, num_bits: u32) -> bool { 40 fits_within!(value, T, num_bits) 41 } 42 43 /// An integer value that requires only the `N` least significant bits of the wrapped type to be 44 /// encoded. 45 /// 46 /// This limits the number of usable bits in the wrapped integer type, and thus the stored value to 47 /// a narrower range, which provides guarantees that can be useful when working within e.g. 48 /// bitfields. 49 /// 50 /// # Invariants 51 /// 52 /// - `N` is greater than `0`. 53 /// - `N` is less than or equal to `T::BITS`. 54 /// - Stored values can be represented with at most `N` bits. 55 /// 56 /// # Examples 57 /// 58 /// The preferred way to create values is through constants and the [`Bounded::new`] family of 59 /// constructors, as they trigger a build error if the type invariants cannot be upheld. 60 /// 61 /// ``` 62 /// use kernel::num::Bounded; 63 /// 64 /// // An unsigned 8-bit integer, of which only the 4 LSBs are used. 65 /// // The value `15` is statically validated to fit that constraint at build time. 66 /// let v = Bounded::<u8, 4>::new::<15>(); 67 /// assert_eq!(v.get(), 15); 68 /// 69 /// // Same using signed values. 70 /// let v = Bounded::<i8, 4>::new::<-8>(); 71 /// assert_eq!(v.get(), -8); 72 /// 73 /// // This doesn't build: a `u8` is smaller than the requested 9 bits. 74 /// // let _ = Bounded::<u8, 9>::new::<10>(); 75 /// 76 /// // This also doesn't build: the requested value doesn't fit within 4 signed bits. 77 /// // let _ = Bounded::<i8, 4>::new::<8>(); 78 /// ``` 79 /// 80 /// Values can also be validated at runtime with [`Bounded::try_new`]. 81 /// 82 /// ``` 83 /// use kernel::num::Bounded; 84 /// 85 /// // This succeeds because `15` can be represented with 4 unsigned bits. 86 /// assert!(Bounded::<u8, 4>::try_new(15).is_some()); 87 /// 88 /// // This fails because `16` cannot be represented with 4 unsigned bits. 89 /// assert!(Bounded::<u8, 4>::try_new(16).is_none()); 90 /// ``` 91 /// 92 /// Non-constant expressions can be validated at build-time thanks to compiler optimizations. This 93 /// should be used with caution, on simple expressions only. 94 /// 95 /// ``` 96 /// use kernel::num::Bounded; 97 /// # fn some_number() -> u32 { 0xffffffff } 98 /// 99 /// // Here the compiler can infer from the mask that the type invariants are not violated, even 100 /// // though the value returned by `some_number` is not statically known. 101 /// let v = Bounded::<u32, 4>::from_expr(some_number() & 0xf); 102 /// ``` 103 /// 104 /// Comparison and arithmetic operations are supported on [`Bounded`]s with a compatible backing 105 /// type, regardless of their number of valid bits. 106 /// 107 /// ``` 108 /// use kernel::num::Bounded; 109 /// 110 /// let v1 = Bounded::<u32, 8>::new::<4>(); 111 /// let v2 = Bounded::<u32, 4>::new::<15>(); 112 /// 113 /// assert!(v1 != v2); 114 /// assert!(v1 < v2); 115 /// assert_eq!(v1 + v2, 19); 116 /// assert_eq!(v2 % v1, 3); 117 /// ``` 118 /// 119 /// These operations are also supported between a [`Bounded`] and its backing type. 120 /// 121 /// ``` 122 /// use kernel::num::Bounded; 123 /// 124 /// let v = Bounded::<u8, 4>::new::<15>(); 125 /// 126 /// assert!(v == 15); 127 /// assert!(v > 12); 128 /// assert_eq!(v + 5, 20); 129 /// assert_eq!(v / 3, 5); 130 /// ``` 131 /// 132 /// A change of backing types is possible using [`Bounded::cast`], and the number of valid bits can 133 /// be extended or reduced with [`Bounded::extend`] and [`Bounded::try_shrink`]. 134 /// 135 /// ``` 136 /// use kernel::num::Bounded; 137 /// 138 /// let v = Bounded::<u32, 12>::new::<127>(); 139 /// 140 /// // Changes backing type from `u32` to `u16`. 141 /// let _: Bounded<u16, 12> = v.cast(); 142 /// 143 /// // This does not build, as `u8` is smaller than 12 bits. 144 /// // let _: Bounded<u8, 12> = v.cast(); 145 /// 146 /// // We can safely extend the number of bits... 147 /// let _ = v.extend::<15>(); 148 /// 149 /// // ... to the limits of the backing type. This doesn't build as a `u32` cannot contain 33 bits. 150 /// // let _ = v.extend::<33>(); 151 /// 152 /// // Reducing the number of bits is validated at runtime. This works because `127` can be 153 /// // represented with 8 bits. 154 /// assert!(v.try_shrink::<8>().is_some()); 155 /// 156 /// // ... but not with 6, so this fails. 157 /// assert!(v.try_shrink::<6>().is_none()); 158 /// ``` 159 /// 160 /// Infallible conversions from a primitive integer to a large-enough [`Bounded`] are supported. 161 /// 162 /// ``` 163 /// use kernel::num::Bounded; 164 /// 165 /// // This unsigned `Bounded` has 8 bits, so it can represent any `u8`. 166 /// let v = Bounded::<u32, 8>::from(128u8); 167 /// assert_eq!(v.get(), 128); 168 /// 169 /// // This signed `Bounded` has 8 bits, so it can represent any `i8`. 170 /// let v = Bounded::<i32, 8>::from(-128i8); 171 /// assert_eq!(v.get(), -128); 172 /// 173 /// // This doesn't build, as this 6-bit `Bounded` does not have enough capacity to represent a 174 /// // `u8` (regardless of the passed value). 175 /// // let _ = Bounded::<u32, 6>::from(10u8); 176 /// 177 /// // Booleans can be converted into single-bit `Bounded`s. 178 /// 179 /// let v = Bounded::<u64, 1>::from(false); 180 /// assert_eq!(v.get(), 0); 181 /// 182 /// let v = Bounded::<u64, 1>::from(true); 183 /// assert_eq!(v.get(), 1); 184 /// ``` 185 /// 186 /// Infallible conversions from a [`Bounded`] to a primitive integer are also supported, and 187 /// dependent on the number of bits used for value representation, not on the backing type. 188 /// 189 /// ``` 190 /// use kernel::num::Bounded; 191 /// 192 /// // Even though its backing type is `u32`, this `Bounded` only uses 6 bits and thus can safely 193 /// // be converted to a `u8`. 194 /// let v = Bounded::<u32, 6>::new::<63>(); 195 /// assert_eq!(u8::from(v), 63); 196 /// 197 /// // Same using signed values. 198 /// let v = Bounded::<i32, 8>::new::<-128>(); 199 /// assert_eq!(i8::from(v), -128); 200 /// 201 /// // This however does not build, as 10 bits won't fit into a `u8` (regardless of the actually 202 /// // contained value). 203 /// let _v = Bounded::<u32, 10>::new::<10>(); 204 /// // assert_eq!(u8::from(_v), 10); 205 /// 206 /// // Single-bit `Bounded`s can be converted into a boolean. 207 /// let v = Bounded::<u8, 1>::new::<1>(); 208 /// assert_eq!(bool::from(v), true); 209 /// 210 /// let v = Bounded::<u8, 1>::new::<0>(); 211 /// assert_eq!(bool::from(v), false); 212 /// ``` 213 /// 214 /// Fallible conversions from any primitive integer to any [`Bounded`] are also supported using the 215 /// [`TryIntoBounded`] trait. 216 /// 217 /// ``` 218 /// use kernel::num::{Bounded, TryIntoBounded}; 219 /// 220 /// // Succeeds because `128` fits into 8 bits. 221 /// let v: Option<Bounded<u16, 8>> = 128u32.try_into_bounded(); 222 /// assert_eq!(v.as_deref().copied(), Some(128)); 223 /// 224 /// // Fails because `128` doesn't fit into 6 bits. 225 /// let v: Option<Bounded<u16, 6>> = 128u32.try_into_bounded(); 226 /// assert_eq!(v, None); 227 /// ``` 228 #[repr(transparent)] 229 #[derive(Clone, Copy, Debug, Default, Hash)] 230 pub struct Bounded<T: Integer, const N: u32>(T); 231 232 /// Validating the value as a const expression cannot be done as a regular method, as the 233 /// arithmetic operations we rely on to check the bounds are not const. Thus, implement 234 /// [`Bounded::new`] using a macro. 235 macro_rules! impl_const_new { 236 ($($type:ty)*) => { 237 $( 238 impl<const N: u32> Bounded<$type, N> { 239 /// Creates a [`Bounded`] for the constant `VALUE`. 240 /// 241 /// Fails at build time if `VALUE` cannot be represented with `N` bits. 242 /// 243 /// This method should be preferred to [`Self::from_expr`] whenever possible. 244 /// 245 /// # Examples 246 /// 247 /// ``` 248 /// use kernel::num::Bounded; 249 /// 250 #[doc = ::core::concat!( 251 "let v = Bounded::<", 252 ::core::stringify!($type), 253 ", 4>::new::<7>();")] 254 /// assert_eq!(v.get(), 7); 255 /// ``` 256 pub const fn new<const VALUE: $type>() -> Self { 257 // Statically assert that `VALUE` fits within the set number of bits. 258 const { 259 assert!(fits_within!(VALUE, $type, N)); 260 } 261 262 // SAFETY: `fits_within` confirmed that `VALUE` can be represented within 263 // `N` bits. 264 unsafe { Self::__new(VALUE) } 265 } 266 } 267 )* 268 }; 269 } 270 271 impl_const_new!( 272 u8 u16 u32 u64 usize 273 i8 i16 i32 i64 isize 274 ); 275 276 impl<T, const N: u32> Bounded<T, N> 277 where 278 T: Integer, 279 { 280 /// Private constructor enforcing the type invariants. 281 /// 282 /// All instances of [`Bounded`] must be created through this method as it enforces most of the 283 /// type invariants. 284 /// 285 /// The caller remains responsible for checking, either statically or dynamically, that `value` 286 /// can be represented as a `T` using at most `N` bits. 287 /// 288 /// # Safety 289 /// 290 /// The caller must ensure that `value` can be represented within `N` bits. 291 const unsafe fn __new(value: T) -> Self { 292 // Enforce the type invariants. 293 const { 294 // `N` cannot be zero. 295 assert!(N != 0); 296 // The backing type is at least as large as `N` bits. 297 assert!(N <= T::BITS); 298 } 299 300 Self(value) 301 } 302 303 /// Attempts to turn `value` into a `Bounded` using `N` bits. 304 /// 305 /// Returns [`None`] if `value` doesn't fit within `N` bits. 306 /// 307 /// # Examples 308 /// 309 /// ``` 310 /// use kernel::num::Bounded; 311 /// 312 /// let v = Bounded::<u8, 1>::try_new(1); 313 /// assert_eq!(v.as_deref().copied(), Some(1)); 314 /// 315 /// let v = Bounded::<i8, 4>::try_new(-2); 316 /// assert_eq!(v.as_deref().copied(), Some(-2)); 317 /// 318 /// // `0x1ff` doesn't fit into 8 unsigned bits. 319 /// let v = Bounded::<u32, 8>::try_new(0x1ff); 320 /// assert_eq!(v, None); 321 /// 322 /// // The range of values representable with 4 bits is `[-8..=7]`. The following tests these 323 /// // limits. 324 /// let v = Bounded::<i8, 4>::try_new(-8); 325 /// assert_eq!(v.map(Bounded::get), Some(-8)); 326 /// let v = Bounded::<i8, 4>::try_new(-9); 327 /// assert_eq!(v, None); 328 /// let v = Bounded::<i8, 4>::try_new(7); 329 /// assert_eq!(v.map(Bounded::get), Some(7)); 330 /// let v = Bounded::<i8, 4>::try_new(8); 331 /// assert_eq!(v, None); 332 /// ``` 333 pub fn try_new(value: T) -> Option<Self> { 334 fits_within(value, N).then(|| { 335 // SAFETY: `fits_within` confirmed that `value` can be represented within `N` bits. 336 unsafe { Self::__new(value) } 337 }) 338 } 339 340 /// Checks that `expr` is valid for this type at compile-time and build a new value. 341 /// 342 /// This relies on [`build_assert!`] and guaranteed optimization to perform validation at 343 /// compile-time. If `expr` cannot be proved to be within the requested bounds at compile-time, 344 /// use the fallible [`Self::try_new`] instead. 345 /// 346 /// Limit this to simple, easily provable expressions, and prefer one of the [`Self::new`] 347 /// constructors whenever possible as they statically validate the value instead of relying on 348 /// compiler optimizations. 349 /// 350 /// # Examples 351 /// 352 /// ``` 353 /// use kernel::num::Bounded; 354 /// # fn some_number() -> u32 { 0xffffffff } 355 /// 356 /// // Some undefined number. 357 /// let v: u32 = some_number(); 358 /// 359 /// // Triggers a build error as `v` cannot be asserted to fit within 4 bits... 360 /// // let _ = Bounded::<u32, 4>::from_expr(v); 361 /// 362 /// // ... but this works as the compiler can assert the range from the mask. 363 /// let _ = Bounded::<u32, 4>::from_expr(v & 0xf); 364 /// 365 /// // These expressions are simple enough to be proven correct, but since they are static the 366 /// // `new` constructor should be preferred. 367 /// assert_eq!(Bounded::<u8, 1>::from_expr(1).get(), 1); 368 /// assert_eq!(Bounded::<u16, 8>::from_expr(0xff).get(), 0xff); 369 /// ``` 370 #[inline(always)] 371 pub fn from_expr(expr: T) -> Self { 372 crate::build_assert!( 373 fits_within(expr, N), 374 "Requested value larger than maximal representable value." 375 ); 376 377 // SAFETY: `fits_within` confirmed that `expr` can be represented within `N` bits. 378 unsafe { Self::__new(expr) } 379 } 380 381 /// Returns the wrapped value as the backing type. 382 /// 383 /// # Examples 384 /// 385 /// ``` 386 /// use kernel::num::Bounded; 387 /// 388 /// let v = Bounded::<u32, 4>::new::<7>(); 389 /// assert_eq!(v.get(), 7u32); 390 /// ``` 391 pub fn get(self) -> T { 392 *self.deref() 393 } 394 395 /// Increases the number of bits usable for `self`. 396 /// 397 /// This operation cannot fail. 398 /// 399 /// # Examples 400 /// 401 /// ``` 402 /// use kernel::num::Bounded; 403 /// 404 /// let v = Bounded::<u32, 4>::new::<7>(); 405 /// let larger_v = v.extend::<12>(); 406 /// // The contained values are equal even though `larger_v` has a bigger capacity. 407 /// assert_eq!(larger_v, v); 408 /// ``` 409 pub const fn extend<const M: u32>(self) -> Bounded<T, M> { 410 const { 411 assert!( 412 M >= N, 413 "Requested number of bits is less than the current representation." 414 ); 415 } 416 417 // SAFETY: The value did fit within `N` bits, so it will all the more fit within 418 // the larger `M` bits. 419 unsafe { Bounded::__new(self.0) } 420 } 421 422 /// Attempts to shrink the number of bits usable for `self`. 423 /// 424 /// Returns [`None`] if the value of `self` cannot be represented within `M` bits. 425 /// 426 /// # Examples 427 /// 428 /// ``` 429 /// use kernel::num::Bounded; 430 /// 431 /// let v = Bounded::<u32, 12>::new::<7>(); 432 /// 433 /// // `7` can be represented using 3 unsigned bits... 434 /// let smaller_v = v.try_shrink::<3>(); 435 /// assert_eq!(smaller_v.as_deref().copied(), Some(7)); 436 /// 437 /// // ... but doesn't fit within `2` bits. 438 /// assert_eq!(v.try_shrink::<2>(), None); 439 /// ``` 440 pub fn try_shrink<const M: u32>(self) -> Option<Bounded<T, M>> { 441 Bounded::<T, M>::try_new(self.get()) 442 } 443 444 /// Casts `self` into a [`Bounded`] backed by a different storage type, but using the same 445 /// number of valid bits. 446 /// 447 /// Both `T` and `U` must be of same signedness, and `U` must be at least as large as 448 /// `N` bits, or a build error will occur. 449 /// 450 /// # Examples 451 /// 452 /// ``` 453 /// use kernel::num::Bounded; 454 /// 455 /// let v = Bounded::<u32, 12>::new::<127>(); 456 /// 457 /// let u16_v: Bounded<u16, 12> = v.cast(); 458 /// assert_eq!(u16_v.get(), 127); 459 /// 460 /// // This won't build: a `u8` is smaller than the required 12 bits. 461 /// // let _: Bounded<u8, 12> = v.cast(); 462 /// ``` 463 pub fn cast<U>(self) -> Bounded<U, N> 464 where 465 U: TryFrom<T> + Integer, 466 T: Integer, 467 U: Integer<Signedness = T::Signedness>, 468 { 469 // SAFETY: The converted value is represented using `N` bits, `U` can contain `N` bits, and 470 // `U` and `T` have the same sign, hence this conversion cannot fail. 471 let value = unsafe { U::try_from(self.get()).unwrap_unchecked() }; 472 473 // SAFETY: Although the backing type has changed, the value is still represented within 474 // `N` bits, and with the same signedness. 475 unsafe { Bounded::__new(value) } 476 } 477 } 478 479 impl<T, const N: u32> Deref for Bounded<T, N> 480 where 481 T: Integer, 482 { 483 type Target = T; 484 485 fn deref(&self) -> &Self::Target { 486 // Enforce the invariant to inform the compiler of the bounds of the value. 487 if !fits_within(self.0, N) { 488 // SAFETY: Per the `Bounded` invariants, `fits_within` can never return `false` on the 489 // value of a valid instance. 490 unsafe { core::hint::unreachable_unchecked() } 491 } 492 493 &self.0 494 } 495 } 496 497 /// Trait similar to [`TryInto`] but for [`Bounded`], to avoid conflicting implementations. 498 /// 499 /// # Examples 500 /// 501 /// ``` 502 /// use kernel::num::{Bounded, TryIntoBounded}; 503 /// 504 /// // Succeeds because `128` fits into 8 bits. 505 /// let v: Option<Bounded<u16, 8>> = 128u32.try_into_bounded(); 506 /// assert_eq!(v.as_deref().copied(), Some(128)); 507 /// 508 /// // Fails because `128` doesn't fit into 6 bits. 509 /// let v: Option<Bounded<u16, 6>> = 128u32.try_into_bounded(); 510 /// assert_eq!(v, None); 511 /// ``` 512 pub trait TryIntoBounded<T: Integer, const N: u32> { 513 /// Attempts to convert `self` into a [`Bounded`] using `N` bits. 514 /// 515 /// Returns [`None`] if `self` does not fit into the target type. 516 fn try_into_bounded(self) -> Option<Bounded<T, N>>; 517 } 518 519 /// Any integer value can be attempted to be converted into a [`Bounded`] of any size. 520 impl<T, U, const N: u32> TryIntoBounded<T, N> for U 521 where 522 T: Integer, 523 U: TryInto<T>, 524 { 525 fn try_into_bounded(self) -> Option<Bounded<T, N>> { 526 self.try_into().ok().and_then(Bounded::try_new) 527 } 528 } 529 530 // Comparisons between `Bounded`s. 531 532 impl<T, U, const N: u32, const M: u32> PartialEq<Bounded<U, M>> for Bounded<T, N> 533 where 534 T: Integer, 535 U: Integer, 536 T: PartialEq<U>, 537 { 538 fn eq(&self, other: &Bounded<U, M>) -> bool { 539 self.get() == other.get() 540 } 541 } 542 543 impl<T, const N: u32> Eq for Bounded<T, N> where T: Integer {} 544 545 impl<T, U, const N: u32, const M: u32> PartialOrd<Bounded<U, M>> for Bounded<T, N> 546 where 547 T: Integer, 548 U: Integer, 549 T: PartialOrd<U>, 550 { 551 fn partial_cmp(&self, other: &Bounded<U, M>) -> Option<cmp::Ordering> { 552 self.get().partial_cmp(&other.get()) 553 } 554 } 555 556 impl<T, const N: u32> Ord for Bounded<T, N> 557 where 558 T: Integer, 559 T: Ord, 560 { 561 fn cmp(&self, other: &Self) -> cmp::Ordering { 562 self.get().cmp(&other.get()) 563 } 564 } 565 566 // Comparisons between a `Bounded` and its backing type. 567 568 impl<T, const N: u32> PartialEq<T> for Bounded<T, N> 569 where 570 T: Integer, 571 T: PartialEq, 572 { 573 fn eq(&self, other: &T) -> bool { 574 self.get() == *other 575 } 576 } 577 578 impl<T, const N: u32> PartialOrd<T> for Bounded<T, N> 579 where 580 T: Integer, 581 T: PartialOrd, 582 { 583 fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> { 584 self.get().partial_cmp(other) 585 } 586 } 587 588 // Implementations of `core::ops` for two `Bounded` with the same backing type. 589 590 impl<T, const N: u32, const M: u32> ops::Add<Bounded<T, M>> for Bounded<T, N> 591 where 592 T: Integer, 593 T: ops::Add<Output = T>, 594 { 595 type Output = T; 596 597 fn add(self, rhs: Bounded<T, M>) -> Self::Output { 598 self.get() + rhs.get() 599 } 600 } 601 602 impl<T, const N: u32, const M: u32> ops::BitAnd<Bounded<T, M>> for Bounded<T, N> 603 where 604 T: Integer, 605 T: ops::BitAnd<Output = T>, 606 { 607 type Output = T; 608 609 fn bitand(self, rhs: Bounded<T, M>) -> Self::Output { 610 self.get() & rhs.get() 611 } 612 } 613 614 impl<T, const N: u32, const M: u32> ops::BitOr<Bounded<T, M>> for Bounded<T, N> 615 where 616 T: Integer, 617 T: ops::BitOr<Output = T>, 618 { 619 type Output = T; 620 621 fn bitor(self, rhs: Bounded<T, M>) -> Self::Output { 622 self.get() | rhs.get() 623 } 624 } 625 626 impl<T, const N: u32, const M: u32> ops::BitXor<Bounded<T, M>> for Bounded<T, N> 627 where 628 T: Integer, 629 T: ops::BitXor<Output = T>, 630 { 631 type Output = T; 632 633 fn bitxor(self, rhs: Bounded<T, M>) -> Self::Output { 634 self.get() ^ rhs.get() 635 } 636 } 637 638 impl<T, const N: u32, const M: u32> ops::Div<Bounded<T, M>> for Bounded<T, N> 639 where 640 T: Integer, 641 T: ops::Div<Output = T>, 642 { 643 type Output = T; 644 645 fn div(self, rhs: Bounded<T, M>) -> Self::Output { 646 self.get() / rhs.get() 647 } 648 } 649 650 impl<T, const N: u32, const M: u32> ops::Mul<Bounded<T, M>> for Bounded<T, N> 651 where 652 T: Integer, 653 T: ops::Mul<Output = T>, 654 { 655 type Output = T; 656 657 fn mul(self, rhs: Bounded<T, M>) -> Self::Output { 658 self.get() * rhs.get() 659 } 660 } 661 662 impl<T, const N: u32, const M: u32> ops::Rem<Bounded<T, M>> for Bounded<T, N> 663 where 664 T: Integer, 665 T: ops::Rem<Output = T>, 666 { 667 type Output = T; 668 669 fn rem(self, rhs: Bounded<T, M>) -> Self::Output { 670 self.get() % rhs.get() 671 } 672 } 673 674 impl<T, const N: u32, const M: u32> ops::Sub<Bounded<T, M>> for Bounded<T, N> 675 where 676 T: Integer, 677 T: ops::Sub<Output = T>, 678 { 679 type Output = T; 680 681 fn sub(self, rhs: Bounded<T, M>) -> Self::Output { 682 self.get() - rhs.get() 683 } 684 } 685 686 // Implementations of `core::ops` between a `Bounded` and its backing type. 687 688 impl<T, const N: u32> ops::Add<T> for Bounded<T, N> 689 where 690 T: Integer, 691 T: ops::Add<Output = T>, 692 { 693 type Output = T; 694 695 fn add(self, rhs: T) -> Self::Output { 696 self.get() + rhs 697 } 698 } 699 700 impl<T, const N: u32> ops::BitAnd<T> for Bounded<T, N> 701 where 702 T: Integer, 703 T: ops::BitAnd<Output = T>, 704 { 705 type Output = T; 706 707 fn bitand(self, rhs: T) -> Self::Output { 708 self.get() & rhs 709 } 710 } 711 712 impl<T, const N: u32> ops::BitOr<T> for Bounded<T, N> 713 where 714 T: Integer, 715 T: ops::BitOr<Output = T>, 716 { 717 type Output = T; 718 719 fn bitor(self, rhs: T) -> Self::Output { 720 self.get() | rhs 721 } 722 } 723 724 impl<T, const N: u32> ops::BitXor<T> for Bounded<T, N> 725 where 726 T: Integer, 727 T: ops::BitXor<Output = T>, 728 { 729 type Output = T; 730 731 fn bitxor(self, rhs: T) -> Self::Output { 732 self.get() ^ rhs 733 } 734 } 735 736 impl<T, const N: u32> ops::Div<T> for Bounded<T, N> 737 where 738 T: Integer, 739 T: ops::Div<Output = T>, 740 { 741 type Output = T; 742 743 fn div(self, rhs: T) -> Self::Output { 744 self.get() / rhs 745 } 746 } 747 748 impl<T, const N: u32> ops::Mul<T> for Bounded<T, N> 749 where 750 T: Integer, 751 T: ops::Mul<Output = T>, 752 { 753 type Output = T; 754 755 fn mul(self, rhs: T) -> Self::Output { 756 self.get() * rhs 757 } 758 } 759 760 impl<T, const N: u32> ops::Neg for Bounded<T, N> 761 where 762 T: Integer, 763 T: ops::Neg<Output = T>, 764 { 765 type Output = T; 766 767 fn neg(self) -> Self::Output { 768 -self.get() 769 } 770 } 771 772 impl<T, const N: u32> ops::Not for Bounded<T, N> 773 where 774 T: Integer, 775 T: ops::Not<Output = T>, 776 { 777 type Output = T; 778 779 fn not(self) -> Self::Output { 780 !self.get() 781 } 782 } 783 784 impl<T, const N: u32> ops::Rem<T> for Bounded<T, N> 785 where 786 T: Integer, 787 T: ops::Rem<Output = T>, 788 { 789 type Output = T; 790 791 fn rem(self, rhs: T) -> Self::Output { 792 self.get() % rhs 793 } 794 } 795 796 impl<T, const N: u32> ops::Sub<T> for Bounded<T, N> 797 where 798 T: Integer, 799 T: ops::Sub<Output = T>, 800 { 801 type Output = T; 802 803 fn sub(self, rhs: T) -> Self::Output { 804 self.get() - rhs 805 } 806 } 807 808 // Proxy implementations of `core::fmt`. 809 810 impl<T, const N: u32> fmt::Display for Bounded<T, N> 811 where 812 T: Integer, 813 T: fmt::Display, 814 { 815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 816 self.get().fmt(f) 817 } 818 } 819 820 impl<T, const N: u32> fmt::Binary for Bounded<T, N> 821 where 822 T: Integer, 823 T: fmt::Binary, 824 { 825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 826 self.get().fmt(f) 827 } 828 } 829 830 impl<T, const N: u32> fmt::LowerExp for Bounded<T, N> 831 where 832 T: Integer, 833 T: fmt::LowerExp, 834 { 835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 836 self.get().fmt(f) 837 } 838 } 839 840 impl<T, const N: u32> fmt::LowerHex for Bounded<T, N> 841 where 842 T: Integer, 843 T: fmt::LowerHex, 844 { 845 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 846 self.get().fmt(f) 847 } 848 } 849 850 impl<T, const N: u32> fmt::Octal for Bounded<T, N> 851 where 852 T: Integer, 853 T: fmt::Octal, 854 { 855 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 856 self.get().fmt(f) 857 } 858 } 859 860 impl<T, const N: u32> fmt::UpperExp for Bounded<T, N> 861 where 862 T: Integer, 863 T: fmt::UpperExp, 864 { 865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 866 self.get().fmt(f) 867 } 868 } 869 870 impl<T, const N: u32> fmt::UpperHex for Bounded<T, N> 871 where 872 T: Integer, 873 T: fmt::UpperHex, 874 { 875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 876 self.get().fmt(f) 877 } 878 } 879 880 /// Implements `$trait` for all [`Bounded`] types represented using `$num_bits`. 881 /// 882 /// This is used to declare size properties as traits that we can constrain against in impl blocks. 883 macro_rules! impl_size_rule { 884 ($trait:ty, $($num_bits:literal)*) => { 885 $( 886 impl<T> $trait for Bounded<T, $num_bits> where T: Integer {} 887 )* 888 }; 889 } 890 891 /// Local trait expressing the fact that a given [`Bounded`] has at least `N` bits used for value 892 /// representation. 893 trait AtLeastXBits<const N: usize> {} 894 895 /// Implementations for infallibly converting a primitive type into a [`Bounded`] that can contain 896 /// it. 897 /// 898 /// Put into their own module for readability, and to avoid cluttering the rustdoc of the parent 899 /// module. 900 mod atleast_impls { 901 use super::*; 902 903 // Number of bits at least as large as 64. 904 impl_size_rule!(AtLeastXBits<64>, 64); 905 906 // Anything 64 bits or more is also larger than 32. 907 impl<T> AtLeastXBits<32> for T where T: AtLeastXBits<64> {} 908 // Other numbers of bits at least as large as 32. 909 impl_size_rule!(AtLeastXBits<32>, 910 32 33 34 35 36 37 38 39 911 40 41 42 43 44 45 46 47 912 48 49 50 51 52 53 54 55 913 56 57 58 59 60 61 62 63 914 ); 915 916 // Anything 32 bits or more is also larger than 16. 917 impl<T> AtLeastXBits<16> for T where T: AtLeastXBits<32> {} 918 // Other numbers of bits at least as large as 16. 919 impl_size_rule!(AtLeastXBits<16>, 920 16 17 18 19 20 21 22 23 921 24 25 26 27 28 29 30 31 922 ); 923 924 // Anything 16 bits or more is also larger than 8. 925 impl<T> AtLeastXBits<8> for T where T: AtLeastXBits<16> {} 926 // Other numbers of bits at least as large as 8. 927 impl_size_rule!(AtLeastXBits<8>, 8 9 10 11 12 13 14 15); 928 } 929 930 /// Generates `From` implementations from a primitive type into a [`Bounded`] with 931 /// enough bits to store any value of that type. 932 /// 933 /// Note: The only reason for having this macro is that if we pass `$type` as a generic 934 /// parameter, we cannot use it in the const context of [`AtLeastXBits`]'s generic parameter. This 935 /// can be fixed once the `generic_const_exprs` feature is usable, and this macro replaced by a 936 /// regular `impl` block. 937 macro_rules! impl_from_primitive { 938 ($($type:ty)*) => { 939 $( 940 #[doc = ::core::concat!( 941 "Conversion from a [`", 942 ::core::stringify!($type), 943 "`] into a [`Bounded`] of same signedness with enough bits to store it.")] 944 impl<T, const N: u32> From<$type> for Bounded<T, N> 945 where 946 $type: Integer, 947 T: Integer<Signedness = <$type as Integer>::Signedness> + From<$type>, 948 Self: AtLeastXBits<{ <$type as Integer>::BITS as usize }>, 949 { 950 fn from(value: $type) -> Self { 951 // SAFETY: The trait bound on `Self` guarantees that `N` bits is 952 // enough to hold any value of the source type. 953 unsafe { Self::__new(T::from(value)) } 954 } 955 } 956 )* 957 } 958 } 959 960 impl_from_primitive!( 961 u8 u16 u32 u64 usize 962 i8 i16 i32 i64 isize 963 ); 964 965 /// Local trait expressing the fact that a given [`Bounded`] fits into a primitive type of `N` bits, 966 /// provided they have the same signedness. 967 trait FitsInXBits<const N: usize> {} 968 969 /// Implementations for infallibly converting a [`Bounded`] into a primitive type that can contain 970 /// it. 971 /// 972 /// Put into their own module for readability, and to avoid cluttering the rustdoc of the parent 973 /// module. 974 mod fits_impls { 975 use super::*; 976 977 // Number of bits that fit into a 8-bits primitive. 978 impl_size_rule!(FitsInXBits<8>, 1 2 3 4 5 6 7 8); 979 980 // Anything that fits into 8 bits also fits into 16. 981 impl<T> FitsInXBits<16> for T where T: FitsInXBits<8> {} 982 // Other number of bits that fit into a 16-bits primitive. 983 impl_size_rule!(FitsInXBits<16>, 9 10 11 12 13 14 15 16); 984 985 // Anything that fits into 16 bits also fits into 32. 986 impl<T> FitsInXBits<32> for T where T: FitsInXBits<16> {} 987 // Other number of bits that fit into a 32-bits primitive. 988 impl_size_rule!(FitsInXBits<32>, 989 17 18 19 20 21 22 23 24 990 25 26 27 28 29 30 31 32 991 ); 992 993 // Anything that fits into 32 bits also fits into 64. 994 impl<T> FitsInXBits<64> for T where T: FitsInXBits<32> {} 995 // Other number of bits that fit into a 64-bits primitive. 996 impl_size_rule!(FitsInXBits<64>, 997 33 34 35 36 37 38 39 40 998 41 42 43 44 45 46 47 48 999 49 50 51 52 53 54 55 56 1000 57 58 59 60 61 62 63 64 1001 ); 1002 } 1003 1004 /// Generates [`From`] implementations from a [`Bounded`] into a primitive type that is 1005 /// guaranteed to contain it. 1006 /// 1007 /// Note: The only reason for having this macro is that if we pass `$type` as a generic 1008 /// parameter, we cannot use it in the const context of `AtLeastXBits`'s generic parameter. This 1009 /// can be fixed once the `generic_const_exprs` feature is usable, and this macro replaced by a 1010 /// regular `impl` block. 1011 macro_rules! impl_into_primitive { 1012 ($($type:ty)*) => { 1013 $( 1014 #[doc = ::core::concat!( 1015 "Conversion from a [`Bounded`] with no more bits than a [`", 1016 ::core::stringify!($type), 1017 "`] and of same signedness into [`", 1018 ::core::stringify!($type), 1019 "`]")] 1020 impl<T, const N: u32> From<Bounded<T, N>> for $type 1021 where 1022 $type: Integer + TryFrom<T>, 1023 T: Integer<Signedness = <$type as Integer>::Signedness>, 1024 Bounded<T, N>: FitsInXBits<{ <$type as Integer>::BITS as usize }>, 1025 { 1026 fn from(value: Bounded<T, N>) -> $type { 1027 // SAFETY: The trait bound on `Bounded` ensures that any value it holds (which 1028 // is constrained to `N` bits) can fit into the destination type, so this 1029 // conversion cannot fail. 1030 unsafe { <$type>::try_from(value.get()).unwrap_unchecked() } 1031 } 1032 } 1033 )* 1034 } 1035 } 1036 1037 impl_into_primitive!( 1038 u8 u16 u32 u64 usize 1039 i8 i16 i32 i64 isize 1040 ); 1041 1042 // Single-bit `Bounded`s can be converted from/to a boolean. 1043 1044 impl<T> From<Bounded<T, 1>> for bool 1045 where 1046 T: Integer + Zeroable, 1047 { 1048 fn from(value: Bounded<T, 1>) -> Self { 1049 value.get() != Zeroable::zeroed() 1050 } 1051 } 1052 1053 impl<T, const N: u32> From<bool> for Bounded<T, N> 1054 where 1055 T: Integer + From<bool>, 1056 { 1057 fn from(value: bool) -> Self { 1058 // SAFETY: A boolean can be represented using a single bit, and thus fits within any 1059 // integer type for any `N` > 0. 1060 unsafe { Self::__new(T::from(value)) } 1061 } 1062 } 1063