proptest/arbitrary/_core/
non_zero.rs

1//-
2// Copyright 2018 The proptest developers
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use core::convert::TryFrom;
11#[cfg(not(target_arch = "wasm32"))]
12use core::num::{NonZeroI128, NonZeroU128};
13use core::num::{
14    NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU16,
15    NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
16};
17
18use crate::arbitrary::{any, Arbitrary, StrategyFor};
19use crate::strategy::{FilterMap, Strategy};
20
21macro_rules! non_zero_impl {
22    ($nz:ty, $prim:ty) => {
23        impl Arbitrary for $nz {
24            type Parameters = ();
25            type Strategy =
26                FilterMap<StrategyFor<$prim>, fn($prim) -> Option<Self>>;
27
28            fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
29                any::<$prim>().prop_filter_map("must be non zero", |i| {
30                    Self::try_from(i).ok()
31                })
32            }
33        }
34    };
35}
36
37non_zero_impl!(NonZeroU8, u8);
38non_zero_impl!(NonZeroU16, u16);
39non_zero_impl!(NonZeroU32, u32);
40non_zero_impl!(NonZeroU64, u64);
41#[cfg(not(target_arch = "wasm32"))]
42non_zero_impl!(NonZeroU128, u128);
43non_zero_impl!(NonZeroUsize, usize);
44
45non_zero_impl!(NonZeroI8, i8);
46non_zero_impl!(NonZeroI16, i16);
47non_zero_impl!(NonZeroI32, i32);
48non_zero_impl!(NonZeroI64, i64);
49#[cfg(not(target_arch = "wasm32"))]
50non_zero_impl!(NonZeroI128, i128);
51non_zero_impl!(NonZeroIsize, isize);
52
53#[cfg(test)]
54mod test {
55    no_panic_test!(
56        u8 => core::num::NonZeroU8,
57        u16 => core::num::NonZeroU16,
58        u32 => core::num::NonZeroU32,
59        u64 => core::num::NonZeroU64,
60        usize => core::num::NonZeroUsize,
61        i8 => core::num::NonZeroI8,
62        i16 => core::num::NonZeroI16,
63        i32 => core::num::NonZeroI32,
64        i64 => core::num::NonZeroI64,
65        isize => core::num::NonZeroIsize
66    );
67    #[cfg(not(target_arch = "wasm32"))]
68    no_panic_test!(
69        u128 => core::num::NonZeroU128,
70        i128 => core::num::NonZeroI128
71    );
72}