Skip to main content

speedy2d/
numeric.rs

1/*
2 *  Copyright 2021 QuantumBadger
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 *  you may not use this file except in compliance with the License.
6 *  You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *  Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 */
16
17/// A trait defined for primitives which have a zero value.
18pub trait PrimitiveZero
19{
20    /// The number zero.
21    const ZERO: Self;
22}
23
24impl PrimitiveZero for i8
25{
26    const ZERO: Self = 0;
27}
28impl PrimitiveZero for i16
29{
30    const ZERO: Self = 0;
31}
32impl PrimitiveZero for i32
33{
34    const ZERO: Self = 0;
35}
36impl PrimitiveZero for i64
37{
38    const ZERO: Self = 0;
39}
40impl PrimitiveZero for i128
41{
42    const ZERO: Self = 0;
43}
44impl PrimitiveZero for isize
45{
46    const ZERO: Self = 0;
47}
48
49impl PrimitiveZero for u8
50{
51    const ZERO: Self = 0;
52}
53impl PrimitiveZero for u16
54{
55    const ZERO: Self = 0;
56}
57impl PrimitiveZero for u32
58{
59    const ZERO: Self = 0;
60}
61impl PrimitiveZero for u64
62{
63    const ZERO: Self = 0;
64}
65impl PrimitiveZero for u128
66{
67    const ZERO: Self = 0;
68}
69impl PrimitiveZero for usize
70{
71    const ZERO: Self = 0;
72}
73
74impl PrimitiveZero for f32
75{
76    const ZERO: Self = 0.0;
77}
78impl PrimitiveZero for f64
79{
80    const ZERO: Self = 0.0;
81}
82
83/// Types implementing this trait can be rounded to the nearest integer value.
84/// In the case of vectors or other types containing multiple elements, each
85/// element will be individually rounded.
86pub trait RoundFloat
87{
88    /// Round this value to the nearest integer. In the case of vectors or other
89    /// types containing multiple elements, each element will be
90    /// individually rounded.
91    fn round(&self) -> Self;
92}
93
94impl RoundFloat for f32
95{
96    #[inline]
97    fn round(&self) -> Self
98    {
99        f32::round(*self)
100    }
101}
102
103impl RoundFloat for f64
104{
105    #[inline]
106    fn round(&self) -> Self
107    {
108        f64::round(*self)
109    }
110}
111
112pub(crate) fn min<T: PartialOrd + Copy>(a: T, b: T) -> T
113{
114    if a < b {
115        a
116    } else {
117        b
118    }
119}
120
121pub(crate) fn max<T: PartialOrd + Copy>(a: T, b: T) -> T
122{
123    if a > b {
124        a
125    } else {
126        b
127    }
128}