1 | // Copyright 2015-2016 Brian Smith. |
2 | // |
3 | // Permission to use, copy, modify, and/or distribute this software for any |
4 | // purpose with or without fee is hereby granted, provided that the above |
5 | // copyright notice and this permission notice appear in all copies. |
6 | // |
7 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES |
8 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
9 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY |
10 | // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
11 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION |
12 | // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN |
13 | // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
14 | |
15 | //! Polyfills for functionality that will (hopefully) be added to Rust's |
16 | //! standard library soon. |
17 | |
18 | #[cfg (any(target_pointer_width = "32" , target_pointer_width = "64" ))] |
19 | #[inline (always)] |
20 | pub const fn u64_from_usize(x: usize) -> u64 { |
21 | x as u64 |
22 | } |
23 | |
24 | #[cfg (any(target_pointer_width = "32" , target_pointer_width = "64" ))] |
25 | pub fn usize_from_u32(x: u32) -> usize { |
26 | x as usize |
27 | } |
28 | |
29 | #[cfg (all(target_arch = "aarch64" , target_pointer_width = "64" ))] |
30 | #[allow (clippy::cast_possible_truncation)] |
31 | pub fn usize_from_u64(x: u64) -> usize { |
32 | x as usize |
33 | } |
34 | |
35 | /// const-capable `x.try_into().unwrap_or(usize::MAX)` |
36 | #[allow (clippy::cast_possible_truncation)] |
37 | #[inline (always)] |
38 | pub const fn usize_from_u64_saturated(x: u64) -> usize { |
39 | const USIZE_MAX: u64 = u64_from_usize(usize::MAX); |
40 | if x < USIZE_MAX { |
41 | x as usize |
42 | } else { |
43 | usize::MAX |
44 | } |
45 | } |
46 | |
47 | mod array_flat_map; |
48 | mod array_flatten; |
49 | mod array_split_map; |
50 | |
51 | #[cfg (feature = "alloc" )] |
52 | mod leading_zeros_skipped; |
53 | |
54 | #[cfg (test)] |
55 | mod test; |
56 | |
57 | mod unwrap_const; |
58 | |
59 | pub use self::{ |
60 | array_flat_map::ArrayFlatMap, array_flatten::ArrayFlatten, array_split_map::ArraySplitMap, |
61 | unwrap_const::unwrap_const, |
62 | }; |
63 | |
64 | #[cfg (feature = "alloc" )] |
65 | pub use leading_zeros_skipped::LeadingZerosStripped; |
66 | |
67 | #[cfg (test)] |
68 | mod tests { |
69 | use super::*; |
70 | #[test ] |
71 | fn test_usize_from_u64_saturated() { |
72 | const USIZE_MAX: u64 = u64_from_usize(usize::MAX); |
73 | assert_eq!(usize_from_u64_saturated(u64::MIN), usize::MIN); |
74 | assert_eq!(usize_from_u64_saturated(USIZE_MAX), usize::MAX); |
75 | assert_eq!(usize_from_u64_saturated(USIZE_MAX - 1), usize::MAX - 1); |
76 | |
77 | #[cfg (not(target_pointer_width = "64" ))] |
78 | { |
79 | assert_eq!(usize_from_u64_saturated(USIZE_MAX + 1), usize::MAX); |
80 | } |
81 | } |
82 | } |
83 | |