1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#![deny(unsafe_code)]

use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::num::{ParseIntError, TryFromIntError};
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
use std::str::FromStr;

use libc::rlim_t;

/// Unsigned integer type used for limit values.
///
/// The actual type of [`RawRlim`][RawRlim] can be different on different platforms.
///
/// [RawRlim]: type.RawRlim.html
pub type RawRlim = rlim_t;

/// Unsigned integer type used for limit values.
///
/// Arithmetic operations with [`Self`][Rlim] are delegated to the inner [`RawRlim`][RawRlim].
///
/// Arithmetic operation with [`usize`][usize] converts the rhs to [`RawRlim`][RawRlim] and computes the result by two [`RawRlim`][RawRlim] values.
///
/// **Be careful**: The actual type of [`RawRlim`][RawRlim] can be different on different platforms.
///
/// # Panics
///
/// Panics if the usize operand can not be converted to [`RawRlim`][RawRlim].
///
/// Panics in debug mode if arithmetic overflow occurred .
///
/// # Features
/// Enables the feature `serde` to implement `Serialize` and `Deserialize` for Rlim with the attribute `serde(transparent)`.
///
/// [Rlim]: struct.Rlim.html
/// [RawRlim]: type.RawRlim.html
/// [usize]: https://doc.rust-lang.org/std/primitive.usize.html
///
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Rlim(RawRlim);

impl Rlim {
    /// A value of Rlim indicating no limit.
    pub const INFINITY: Self = Self(libc::RLIM_INFINITY);

    #[cfg(any(
        target_os = "fuchsia",
        any(target_os = "openbsd", target_os = "netbsd"),
        target_os = "emscripten",
        target_os = "linux",
        target_env = "uclibc",
    ))]
    /// A value of type Rlim indicating an unrepresentable saved soft limit.
    pub const SAVED_CUR: Self = Self(libc::RLIM_SAVED_CUR);

    #[cfg(any(
        target_os = "fuchsia",
        any(target_os = "openbsd", target_os = "netbsd"),
        target_os = "emscripten",
        target_os = "linux",
        target_env = "uclibc",
    ))]
    /// A value of type Rlim indicating an unrepresentable saved hard limit.
    pub const SAVED_MAX: Self = Self(libc::RLIM_SAVED_MAX);
}

impl Rlim {
    /// Wraps a raw value of limit as Rlim.
    ///
    /// # Example
    /// ```
    /// # use rlimit::Rlim;
    /// // The integer type is inferred by compiler.
    /// const DEFAULT_LIMIT: Rlim = Rlim::from_raw(42);
    /// ```
    #[inline]
    #[must_use]
    pub const fn from_raw(rlim: RawRlim) -> Self {
        Self(rlim)
    }

    /// Returns a raw value of limit.
    #[inline]
    #[must_use]
    pub const fn as_raw(self) -> RawRlim {
        self.0
    }

    /// Converts usize to Rlim
    /// # Panics
    /// Panics if the usize value can not be converted to [`RawRlim`][RawRlim].
    ///
    /// [RawRlim]: type.RawRlim.html
    #[inline]
    #[must_use]
    pub fn from_usize(n: usize) -> Self {
        Self(usize_to_raw(n))
    }

    /// Converts Rlim to usize
    /// # Panics
    /// Panics if the wrapped [`RawRlim`][RawRlim] value can not be converted to usize.
    ///
    /// [RawRlim]: type.RawRlim.html
    #[inline]
    #[must_use]
    pub fn as_usize(self) -> usize {
        raw_to_usize(self.0)
    }
}

impl fmt::Debug for Rlim {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        RawRlim::fmt(&self.0, f)
    }
}

impl fmt::Display for Rlim {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        RawRlim::fmt(&self.0, f)
    }
}

impl FromStr for Rlim {
    type Err = ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(RawRlim::from_str(s)?))
    }
}

impl TryFrom<usize> for Rlim {
    type Error = TryFromIntError;
    fn try_from(n: usize) -> Result<Self, Self::Error> {
        Ok(Self(n.try_into()?))
    }
}

impl TryFrom<Rlim> for usize {
    type Error = TryFromIntError;
    fn try_from(r: Rlim) -> Result<Self, Self::Error> {
        Ok(r.0.try_into()?)
    }
}

#[track_caller]
fn usize_to_raw(n: usize) -> RawRlim {
    match n.try_into() {
        Ok(r) => r,
        Err(e) => panic!(
            "can not convert usize to {}, the number is {}, the error is {}",
            std::any::type_name::<RawRlim>(),
            n,
            e
        ),
    }
}

#[track_caller]
fn raw_to_usize(n: RawRlim) -> usize {
    match n.try_into() {
        Ok(r) => r,
        Err(e) => panic!(
            "can not convert {} to usize, the number is {}, the error is {}",
            std::any::type_name::<RawRlim>(),
            n,
            e
        ),
    }
}

macro_rules! arithmetic_panic {
    ($method:tt, $lhs:expr,$rhs:expr) => {
        panic!(
            "Rlim: arithmetic overflow: method = {}, lhs = {}, rhs = {}, type = {}",
            stringify!($method),
            $lhs,
            $rhs,
            std::any::type_name::<RawRlim>(),
        )
    };
}

macro_rules! impl_arithmetic {
    ($tr:tt, $method:tt,$check:tt) => {
        impl $tr<Rlim> for Rlim {
            type Output = Self;

            #[track_caller]
            fn $method(self, rhs: Self) -> Self::Output {
                if cfg!(debug_assertions) {
                    match self.0.$check(rhs.0) {
                        Some(x) => Self(x),
                        None => arithmetic_panic!($method, self.0, rhs.0),
                    }
                } else {
                    Self(self.0.$method(rhs.0))
                }
            }
        }

        impl $tr<usize> for Rlim {
            type Output = Self;

            #[track_caller]
            fn $method(self, rhs: usize) -> Self::Output {
                let rhs = usize_to_raw(rhs);

                if cfg!(debug_assertions) {
                    match self.0.$check(rhs) {
                        Some(x) => Self(x),
                        None => arithmetic_panic!($method, self.0, rhs),
                    }
                } else {
                    Self(self.0.$method(rhs))
                }
            }
        }
    };
}

macro_rules! impl_arithmetic_assign{
    ($tr:tt, $method:tt,$op:tt) => {
        impl $tr<Rlim> for Rlim {
            #[track_caller]
            fn $method(&mut self, rhs: Self) {
                *self = *self $op rhs;
            }
        }

        impl $tr<usize> for Rlim {
            #[track_caller]
            fn $method(&mut self, rhs: usize) {
                *self = *self $op rhs;
            }
        }
    }
}

macro_rules! delegate_arithmetic{
    {@checked $($check:tt,)+} => {
        impl Rlim{
            $(
                /// Checked integer arithmetic. Returns None if overflow occurred.
                pub fn $check(self, rhs: Self) -> Option<Self>{
                    self.0.$check(rhs.0).map(Self)
                }
            )+
        }
    };

    {@wrapping $($wrap:tt,)+} => {
        impl Rlim{
            $(
                /// Wrapping (modular) arithmetic. Wraps around at the boundary of the inner [`RawRlim`][RawRlim].
                ///
                /// [RawRlim]: type.RawRlim.html
                #[must_use]
                #[allow(clippy::missing_const_for_fn)] // FIXME: `core::num::<impl u64>::wrapping_div` is not yet stable as a const fn
                pub fn $wrap(self, rhs: Self) -> Self{
                    Self(self.0.$wrap(rhs.0))
                }
            )+
        }
    }
}

impl_arithmetic!(Add, add, checked_add);
impl_arithmetic!(Sub, sub, checked_sub);
impl_arithmetic!(Mul, mul, checked_mul);
impl_arithmetic!(Div, div, checked_div);

impl_arithmetic_assign!(AddAssign, add_assign, +);
impl_arithmetic_assign!(SubAssign, sub_assign, -);
impl_arithmetic_assign!(MulAssign, mul_assign, *);
impl_arithmetic_assign!(DivAssign, div_assign, /);

delegate_arithmetic! {@checked
    checked_add,
    checked_sub,
    checked_mul,
    checked_div,
}

delegate_arithmetic! {@wrapping
    wrapping_add,
    wrapping_sub,
    wrapping_mul,
    wrapping_div,
}