1pub(crate) trait ForceAdd: Sized {
2fn force_add(self, rhs: Self) -> Self;
3}
45impl ForceAdd for u8 {
6fn force_add(self, rhs: Self) -> Self {
7self.checked_add(rhs).unwrap_or_else(die)
8 }
9}
1011impl ForceAdd for i32 {
12fn force_add(self, rhs: Self) -> Self {
13self.checked_add(rhs).unwrap_or_else(die)
14 }
15}
1617impl ForceAdd for u32 {
18fn force_add(self, rhs: Self) -> Self {
19self.checked_add(rhs).unwrap_or_else(die)
20 }
21}
2223impl ForceAdd for u64 {
24fn force_add(self, rhs: Self) -> Self {
25self.checked_add(rhs).unwrap_or_else(die)
26 }
27}
2829impl ForceAdd for usize {
30fn force_add(self, rhs: Self) -> Self {
31self.checked_add(rhs).unwrap_or_else(die)
32 }
33}
3435pub(crate) trait ForceMul: Sized {
36fn force_mul(self, rhs: Self) -> Self;
37}
3839impl ForceMul for i32 {
40fn force_mul(self, rhs: Self) -> Self {
41self.checked_mul(rhs).unwrap_or_else(die)
42 }
43}
4445impl ForceMul for i64 {
46fn force_mul(self, rhs: Self) -> Self {
47self.checked_mul(rhs).unwrap_or_else(die)
48 }
49}
5051impl ForceMul for u64 {
52fn force_mul(self, rhs: Self) -> Self {
53self.checked_mul(rhs).unwrap_or_else(die)
54 }
55}
5657pub(crate) trait ForceInto {
58fn force_into<U>(self) -> U
59where
60Self: TryInto<U>;
61}
6263impl<T> ForceInto for T {
64fn force_into<U>(self) -> U
65where
66Self: TryInto<U>,
67 {
68 <Self as TryInto<U>>::try_into(self)
69 .ok()
70 .unwrap_or_else(die)
71 }
72}
7374// Deterministically abort on arithmetic overflow, instead of wrapping and
75// continuing with invalid behavior.
76//
77// This is impossible or nearly impossible to hit as the arithmetic computations
78// in libyaml are all related to either:
79//
80// - small integer processing (ascii, hex digits)
81// - allocation sizing
82//
83// and the only allocations in libyaml are for fixed-sized objects and
84// geometrically growing buffers with a growth factor of 2. So in order for an
85// allocation computation to overflow usize, the previous allocation for that
86// container must have been filled to a size of usize::MAX/2, which is an
87// allocation that would have failed in the allocator. But we check for this to
88// be pedantic and to find out if it ever does happen.
89//
90// No-std abort is implemented using a double panic. On most platforms the
91// current mechanism for this is for core::intrinsics::abort to invoke an
92// invalid instruction. On Unix, the process will probably terminate with a
93// signal like SIGABRT, SIGILL, SIGTRAP, SIGSEGV or SIGBUS. The precise
94// behaviour is not guaranteed and not stable, but is safe.
95#[cold]
96pub(crate) fn die<T>() -> T {
97struct PanicAgain;
9899impl Drop for PanicAgain {
100fn drop(&mut self) {
101panic!("arithmetic overflow");
102 }
103 }
104105fn do_die() -> ! {
106let _panic_again = PanicAgain;
107panic!("arithmetic overflow");
108 }
109110 do_die();
111}