pw_cast/lib.rs
1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#![no_std]
16
17/// Like [`From`], but supporting target-specific casts.
18///
19/// [`From`] does not support casts which are not valid on all targets (such as
20/// `u32` to `usize`, which is not valid on 16-bit platforms). `CastFrom`, by
21/// contrast, supports all conversions which are valid on a given target. As a
22/// consequence, uses of `CastFrom` may not be portable to all targets.
23///
24/// Like [`From`], `CastFrom` only supports lossless casts.
25pub trait CastFrom<T> {
26 fn cast_from(t: T) -> Self;
27}
28
29/// Like [`Into`], but supporting target-specific casts.
30///
31/// See [`CastFrom`]'s docs for more information.
32///
33/// Like [`Into`], `CastInto` only supports lossless casts.
34pub trait CastInto<T> {
35 fn cast_into(self) -> T;
36}
37
38impl<T, U: CastFrom<T>> CastInto<U> for T {
39 fn cast_into(self) -> U {
40 U::cast_from(self)
41 }
42}
43
44/// Performs a lossless cast.
45///
46/// `cast!` performs the same cast as [`CastFrom::cast_from`] or
47/// [`CastInto::cast_into`], but unlike those methods, it works in a `const`
48/// context.
49#[macro_export]
50macro_rules! cast {
51 ($e:expr) => { $crate::cast!($e => _) };
52 ($e:expr => $t:ty) => {{
53 #[allow(clippy::as_underscore)]
54 if false {
55 // SAFETY: This branch is never taken.
56 #[allow(clippy::macro_metavars_in_unsafe)]
57 unsafe { $crate::__cast($e) }
58 } else {
59 // The preceding call to `__cast` ensures that the source type (the
60 // type of `$e`) can be casted into the destination type (`$t`) via
61 // `CastFrom`, which ensures that this is a lossless cast.
62 $e as $t
63 }
64 }};
65}
66
67/// Attempts to perform a lossless cast.
68///
69/// This macro evaluates to an expression of type `Option<$t>`. It is similar to
70/// [`TryInto`], but it works in a `const` context.
71#[macro_export]
72macro_rules! try_cast {
73 ($e:expr => $t:ty) => {{
74 let min = $crate::cast!(<$t>::MIN);
75 let max = $crate::cast!(<$t>::MAX);
76 // Triggered when `$e` is a literal which trivially satisfies one of
77 // these comparisons.
78 #[allow(unused_comparisons)]
79 // Triggered when invoked with `x + 1` or `y - 1`.
80 #[allow(clippy::int_plus_one)]
81 if $e >= min && $e <= max {
82 #[allow(clippy::cast_possible_truncation)]
83 Some($e as $t)
84 } else {
85 None
86 }
87 }};
88}
89
90// A test to ensure that `cast!` and `try_cast!` work in a const context, and
91// work properly.
92const _: () = {
93 let x: usize = cast!(0u32);
94 assert!(x == 0usize);
95 assert!(cast!(0u32 => usize) == 0usize);
96
97 assert!(try_cast!(0u32 => u16).unwrap() == 0u16);
98 assert!(try_cast!(256u16 => u8).is_none());
99
100 #[allow(clippy::identity_op)]
101 {
102 // Test more complex `$e:expr` fragments.
103 let x: usize = cast!(0u32 + 1);
104 assert!(x == 1usize);
105 assert!(cast!(0u32 + 1 => usize) == 1usize);
106 assert!(try_cast!(0u32 + 1 => u16).unwrap() == 1u16);
107 assert!(try_cast!(255u16 + 1 => u8).is_none());
108 }
109};
110
111/// # Safety
112///
113/// It is UB to call this function.
114#[doc(hidden)]
115pub const unsafe fn __cast<T, U: CastFrom<T>>(_t: T) -> U {
116 unsafe { core::hint::unreachable_unchecked() }
117}
118
119macro_rules! impl_cast_from {
120 ($($src:ty => $dst:ty),* $(,)?) => {
121 $(
122 impl CastFrom<$src> for $dst {
123 #[allow(clippy::cast_lossless, clippy::cast_possible_truncation)]
124 fn cast_from(t: $src) -> $dst {
125 const _: () = assert!(size_of::<$src>() <= size_of::<$dst>());
126
127 // So long as `$src` and `$dst` are numeric primitives, the
128 // preceding assert ensures that this is a lossless cast.
129 t as $dst
130 }
131 }
132 )*
133 };
134}
135
136#[cfg(target_pointer_width = "16")]
137impl_cast_from!(
138 u8 => usize,
139 u8 => u16,
140 bool => usize,
141 u16 => usize,
142 usize => u16,
143 usize => u32,
144 usize => u64,
145);
146
147#[cfg(target_pointer_width = "32")]
148impl_cast_from!(
149 u8 => usize,
150 u8 => u16,
151 bool => usize,
152 u16 => usize,
153 u16 => u32,
154 u32 => usize,
155 u32 => u64,
156 usize => u32,
157 usize => u64,
158);
159
160#[cfg(target_pointer_width = "64")]
161impl_cast_from!(
162 u8 => usize,
163 u8 => u16,
164 bool => usize,
165 u16 => usize,
166 u16 => u32,
167 u32 => usize,
168 u32 => u64,
169 u64 => usize,
170 usize => u64,
171);