fixed/
impl_bytemuck.rs

1// Copyright © 2018–2025 Trevor Spiteri
2
3// This library is free software: you can redistribute it and/or
4// modify it under the terms of either
5//
6//   * the Apache License, Version 2.0 or
7//   * the MIT License
8//
9// at your option.
10//
11// You should have recieved copies of the Apache License and the MIT
12// License along with the library. If not, see
13// <https://www.apache.org/licenses/LICENSE-2.0> and
14// <https://opensource.org/licenses/MIT>.
15
16use crate::types::extra::{LeEqU8, LeEqU16, LeEqU32, LeEqU64, LeEqU128};
17use crate::{
18    FixedI8, FixedI16, FixedI32, FixedI64, FixedI128, FixedU8, FixedU16, FixedU32, FixedU64,
19    FixedU128, Unwrapped, Wrapping,
20};
21use bytemuck::{Contiguous, Pod, TransparentWrapper, Zeroable};
22
23macro_rules! unsafe_impl_traits {
24    ($Fixed:ident, $LeEqU:ident, $Inner:ident) => {
25        unsafe impl<Frac> Zeroable for $Fixed<Frac> {}
26        unsafe impl<Frac: 'static> Pod for $Fixed<Frac> {}
27        unsafe impl<Frac: 'static> Contiguous for $Fixed<Frac> {
28            type Int = $Inner;
29            const MAX_VALUE: $Inner = $Inner::MAX;
30            const MIN_VALUE: $Inner = $Inner::MIN;
31        }
32        unsafe impl<Frac> TransparentWrapper<$Inner> for $Fixed<Frac> {}
33
34        unsafe impl<Frac: $LeEqU> Zeroable for Wrapping<$Fixed<Frac>> {}
35        unsafe impl<Frac: $LeEqU> Pod for Wrapping<$Fixed<Frac>> {}
36        unsafe impl<Frac: $LeEqU> Contiguous for Wrapping<$Fixed<Frac>> {
37            type Int = $Inner;
38            const MAX_VALUE: $Inner = $Inner::MAX;
39            const MIN_VALUE: $Inner = $Inner::MIN;
40        }
41        unsafe impl<Frac: $LeEqU> TransparentWrapper<$Fixed<Frac>> for Wrapping<$Fixed<Frac>> {}
42
43        unsafe impl<Frac: $LeEqU> Zeroable for Unwrapped<$Fixed<Frac>> {}
44        unsafe impl<Frac: $LeEqU> Pod for Unwrapped<$Fixed<Frac>> {}
45        unsafe impl<Frac: $LeEqU> Contiguous for Unwrapped<$Fixed<Frac>> {
46            type Int = $Inner;
47            const MAX_VALUE: $Inner = $Inner::MAX;
48            const MIN_VALUE: $Inner = $Inner::MIN;
49        }
50        unsafe impl<Frac: $LeEqU> TransparentWrapper<$Fixed<Frac>> for Unwrapped<$Fixed<Frac>> {}
51    };
52}
53
54// SAFETY: all fixed-point numbers are repr(transparent) over primitive integer
55// types which are both Pod and Zeroable, and Wrapping and Unwrapped are both
56// repr(transparent) over fixed-point numbers.
57unsafe_impl_traits! { FixedI8, LeEqU8, i8 }
58unsafe_impl_traits! { FixedI16, LeEqU16, i16 }
59unsafe_impl_traits! { FixedI32, LeEqU32, i32 }
60unsafe_impl_traits! { FixedI64, LeEqU64, i64 }
61unsafe_impl_traits! { FixedI128, LeEqU128, i128 }
62unsafe_impl_traits! { FixedU8, LeEqU8, u8 }
63unsafe_impl_traits! { FixedU16, LeEqU16, u16 }
64unsafe_impl_traits! { FixedU32, LeEqU32, u32 }
65unsafe_impl_traits! { FixedU64, LeEqU64, u64 }
66unsafe_impl_traits! { FixedU128, LeEqU128, u128 }