clapi 0.1.2

A framework for create command-line applications
Documentation
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#![allow(clippy::manual_unwrap_or)]
use std::collections::Bound;
use std::fmt::{Display, Formatter};
use std::ops::{
    Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, Sub,
};

/**
Represents the number of values an argument takes.
*/
#[derive(Debug, Default, Copy, Clone, Hash, Eq, PartialEq)]
pub struct ArgCount {
    min: Option<usize>,
    max: Option<usize>,
}

impl ArgCount {
    /// Constructs a new `ArgCount` with the given min and max.
    /// It takes `Option<usize>` where `Some(usize)` is bounded and `None` is unbounded.
    ///
    /// # Example
    /// ```
    /// use clapi::ArgCount;
    ///
    /// // This goes from 2 to the usize::MAX
    /// let unbounded_max = ArgCount::new(Some(2), None);
    /// assert_eq!(unbounded_max.min_or_default(), 2);
    /// assert_eq!(unbounded_max.max_or_default(), usize::MAX);
    ///
    /// // This goes from usize::MIN to 12
    /// let unbounded_min = ArgCount::new(None, Some(12));
    /// assert_eq!(unbounded_min.min_or_default(), usize::MIN);
    /// assert_eq!(unbounded_min.max_or_default(), 12);
    ///
    /// // This goes from 5 to 10
    /// let bounded = ArgCount::new(Some(5), Some(10));
    /// assert_eq!(bounded.min_or_default(), 5);
    /// assert_eq!(bounded.max_or_default(), 10);
    /// ```
    ///
    /// # Panics
    /// If min > max.
    #[inline]
    pub fn new(min: Option<usize>, max: Option<usize>) -> Self {
        if let (Some(min), Some(max)) = (min, max) {
            assert!(min <= max, "min cannot be greater than max");
            unsafe { Self::new_unchecked(Some(min), Some(max)) }
        } else {
            unsafe { Self::new_unchecked(min, max) }
        }
    }

    /// Constructs a new `ArgCount` with a know `min` and `max`
    ///
    /// # Example
    /// ```
    /// use clapi::ArgCount;
    ///
    /// let count = ArgCount::new_bounded(2, 10);
    /// assert_eq!(count.min_or_default(), 2);
    /// assert_eq!(count.max_or_default(), 10);
    /// ```
    ///
    /// # Panics
    /// If min > max
    #[inline]
    pub fn new_bounded(min: usize, max: usize) -> Self {
        Self::new(Some(min), Some(max))
    }

    #[inline(always)]
    const unsafe fn new_unchecked(min: Option<usize>, max: Option<usize>) -> Self {
        ArgCount { min, max }
    }

    /// Constructs a new `ArgCount` for not values.
    #[inline]
    pub const fn zero() -> Self {
        unsafe { Self::new_unchecked(Some(0), Some(0)) }
    }

    /// Constructs a new `ArgCount` for exactly 1 values.
    #[inline]
    pub const fn one() -> Self {
        unsafe { Self::new_unchecked(Some(1), Some(1)) }
    }

    /// Constructs a new `ArgCount` for any number of values.
    #[inline]
    pub const fn any() -> Self {
        unsafe { Self::new_unchecked(None, None) }
    }

    /// Constructs a new `ArgCount` for the specified number of values.
    #[inline]
    pub const fn exactly(count: usize) -> Self {
        unsafe { Self::new_unchecked(Some(count), Some(count)) }
    }

    /// Constructs a new `ArgCount` for more than the specified number of values.
    #[inline]
    pub fn more_than(min: usize) -> Self {
        unsafe { Self::new_unchecked(Some(min), None) }
    }

    /// Constructs a new `ArgCount` for less than the specified number of values.
    #[inline]
    pub fn less_than(max: usize) -> Self {
        unsafe { Self::new_unchecked(None, Some(max)) }
    }

    /// Returns the min number of values if bounded or `usize::MIN` if unbounded.
    #[inline]
    pub const fn min_or_default(&self) -> usize {
        match self.min {
            Some(n) => n,
            None => usize::MIN,
        }
    }

    /// Returns the max number of values if bounded or `usize::MAX` if unbounded.
    #[inline]
    pub const fn max_or_default(&self) -> usize {
        match self.max {
            Some(n) => n,
            None => usize::MAX,
        }
    }

    /// Returns the `min` number of values or `None` if unbounded.
    #[inline]
    pub const fn min(&self) -> Option<usize> {
        self.min
    }

    /// Returns the `max` number of values of `None` if unbounded.
    #[inline]
    pub const fn max(&self) -> Option<usize> {
        self.max
    }

    /// Returns a copy of this `ArgCount` with the given `min`.
    #[inline]
    pub fn with_min(&self, min: usize) -> Self {
        Self::new(Some(min), self.max)
    }

    /// Returns a copy of this `ArgCount` with the given `max`.
    #[inline]
    pub fn with_max(&self, max: usize) -> Self {
        Self::new(self.min, Some(max))
    }

    /// Returns `true` if this takes the provided number of values.
    #[inline]
    pub const fn takes(&self, count: usize) -> bool {
        count >= self.min_or_default() && count <= self.max_or_default()
    }

    /// Returns `true` if this takes values.
    #[inline]
    pub const fn takes_values(&self) -> bool {
        self.max_or_default() != 0
    }

    /// Returns `true` if this takes an exact number of values.
    #[inline]
    pub const fn is_exact(&self) -> bool {
        self.min_or_default() == self.max_or_default()
    }

    /// Returns `true` if this takes exactly the specified number of values.
    #[inline]
    pub const fn takes_exactly(&self, count: usize) -> bool {
        self.min_or_default() == count && self.max_or_default() == count
    }
}

impl Display for ArgCount {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.is_exact() {
            return if self.takes_exactly(0) {
                write!(f, "no values")
            } else if self.takes_exactly(1) {
                write!(f, "1 value")
            } else {
                write!(f, "{} values", self.min_or_default())
            };
        }

        match (self.min, self.max) {
            (Some(min), Some(max)) => write!(f, "{} to {} values", min, max),
            (Some(min), None) => write!(f, "{} or more values", min),
            (None, Some(max)) => write!(f, "{} or less values", max),
            (None, None) => write!(f, "any number of values"),
        }
    }
}

impl From<ArgCount> for RangeInclusive<usize> {
    fn from(arg_count: ArgCount) -> Self {
        arg_count.min_or_default()..=arg_count.max_or_default()
    }
}

impl From<RangeFull> for ArgCount {
    fn from(_: RangeFull) -> Self {
        ArgCount::any()
    }
}

impl RangeBounds<usize> for ArgCount {
    fn start_bound(&self) -> Bound<&usize> {
        match self.min {
            Some(ref n) => Bound::Included(n),
            None => Bound::Unbounded,
        }
    }

    fn end_bound(&self) -> Bound<&usize> {
        match self.max {
            Some(ref n) => Bound::Included(n),
            None => Bound::Unbounded,
        }
    }
}

macro_rules! impl_value_count_from_unsigned_int {
    ($($target:ident),*) => {
        $(
            impl From<$target> for ArgCount {
                fn from(value: $target) -> Self {
                    ArgCount::exactly(value as usize)
                }
            }

            impl From<RangeInclusive<$target>> for ArgCount {
                fn from(value: RangeInclusive<$target>) -> Self {
                    let start = *value.start();
                    let end = *value.end();
                    ArgCount::new_bounded(start as usize, end as usize)
                }
            }

            impl From<Range<$target>> for ArgCount {
                fn from(value: Range<$target>) -> Self {
                    let start = value.start;
                    let end = value.end.sub(1);
                    ArgCount::new_bounded(start as usize, end as usize)
                }
            }

            impl From<RangeFrom<$target>> for ArgCount {
                fn from(value: RangeFrom<$target>) -> Self {
                    let start = value.start;
                    ArgCount::more_than(start as usize)
                }
            }

            impl From<RangeTo<$target>> for ArgCount {
                fn from(value: RangeTo<$target>) -> Self {
                    let end = value.end.sub(1);
                    ArgCount::less_than(end as usize)
                }
            }

            impl From<RangeToInclusive<$target>> for ArgCount {
                fn from(value: RangeToInclusive<$target>) -> Self {
                    let end = value.end;
                    ArgCount::less_than(end as usize)
                }
            }
        )*
    };
}

macro_rules! impl_value_count_from_signed_int {
    ($($target:ident),*) => {
        $(
            impl From<$target> for ArgCount {
                fn from(value: $target) -> Self {
                    assert!(value >= 0, "value count cannot be negative: {}", value);
                    ArgCount::exactly(value as usize)
                }
            }

            impl From<RangeInclusive<$target>> for ArgCount {
                fn from(value: RangeInclusive<$target>) -> Self {
                    let start = *value.start();
                    let end = *value.end();

                    assert!(start >= 0, "start cannot be negative");
                    assert!(end >= 0, "end cannot be negative");
                    ArgCount::new_bounded(start as usize, end as usize)
                }
            }

            impl From<Range<$target>> for ArgCount {
                fn from(value: Range<$target>) -> Self {
                    let start = value.start;
                    let end = value.end.sub(1);

                    assert!(start >= 0, "start cannot be negative");
                    assert!(end >= 0, "end cannot be negative");
                    ArgCount::new_bounded(start as usize, end as usize)
                }
            }

            impl From<RangeFrom<$target>> for ArgCount {
                fn from(value: RangeFrom<$target>) -> Self {
                    let start = value.start;
                    assert!(start >= 0, "start cannot be negative");
                    ArgCount::more_than(start as usize)
                }
            }

            impl From<RangeTo<$target>> for ArgCount {
                fn from(value: RangeTo<$target>) -> Self {
                    let end = value.end.sub(1);
                    assert!(end >= 0, "end cannot be negative");
                    ArgCount::less_than(end as usize)
                }
            }

            impl From<RangeToInclusive<$target>> for ArgCount {
                fn from(value: RangeToInclusive<$target>) -> Self {
                    let end = value.end;
                    assert!(end >= 0, "end cannot be negative");
                    ArgCount::less_than(end as usize)
                }
            }
        )*
    };
}

impl_value_count_from_unsigned_int! { u8, u16, u32, u64, u128, usize }

impl_value_count_from_signed_int! { i8, i16, i32, i64, i128, isize }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn value_count_test() {
        let arg_count = ArgCount::new(Some(2), Some(5));
        assert_eq!(arg_count.min_or_default(), 2);
        assert_eq!(arg_count.max_or_default(), 5);
        assert!(arg_count.takes_values());
        assert!(arg_count.takes(2));
        assert!(arg_count.takes(3));
        assert!(arg_count.takes(4));
        assert!(arg_count.takes(5));
    }

    #[test]
    fn into_value_count_test() {
        fn assert_into<A: Into<ArgCount>>(value: A, expected_min: usize, expected_max: usize) {
            let arg_count = value.into();
            let type_name = std::any::type_name::<A>();
            assert_eq!(
                arg_count.min_or_default(),
                expected_min,
                "min value - type: `{}`",
                type_name
            );
            assert_eq!(
                arg_count.max_or_default(),
                expected_max,
                "max value - type: `{}`",
                type_name
            );
        }

        assert_into(2, 2, 2);
        assert_into(.., 0, usize::max_value());
        assert_into(10.., 10, usize::max_value());
        assert_into(..20, 0, 19);
        assert_into(..=20, 0, 20);
        assert_into(1..10, 1, 9);
        assert_into(1..=10, 1, 10);

        assert_into(0..1, 0, 0);
    }

    #[test]
    #[should_panic(expected = "value count cannot be negative")]
    fn into_value_count_panic_test1() {
        let _: ArgCount = (-1_i32).into();
    }

    #[test]
    #[should_panic]
    fn into_value_count_panic_test2() {
        let _: ArgCount = (1..1).into();
    }

    #[test]
    #[should_panic]
    fn into_value_count_panic_test3() {
        let _: ArgCount = (0..-2).into();
    }

    #[test]
    fn none_test() {
        let arg_count = ArgCount::zero();
        assert!(!arg_count.takes_values());
        assert!(arg_count.is_exact());
        assert_eq!(arg_count.min_or_default(), 0);
        assert_eq!(arg_count.max_or_default(), 0);
    }

    #[test]
    fn one_test() {
        let arg_count = ArgCount::one();
        assert!(arg_count.takes_values());
        assert!(arg_count.is_exact());
        assert_eq!(arg_count.min_or_default(), 1);
        assert_eq!(arg_count.max_or_default(), 1);
    }

    #[test]
    fn any_test() {
        let arg_count = ArgCount::any();
        assert!(arg_count.takes_values());
        assert!(!arg_count.is_exact());
        assert_eq!(arg_count.min_or_default(), 0);
        assert_eq!(arg_count.max_or_default(), usize::max_value());
    }

    #[test]
    fn exactly_test() {
        let arg_count = ArgCount::exactly(2);
        assert!(arg_count.takes_exactly(2));
        assert_eq!(arg_count.min_or_default(), 2);
        assert_eq!(arg_count.max_or_default(), 2);
    }

    #[test]
    fn more_than_test() {
        let arg_count = ArgCount::more_than(1);
        assert!(!arg_count.takes_exactly(1));
        assert_eq!(arg_count.min_or_default(), 1);
        assert_eq!(arg_count.max_or_default(), usize::max_value());
    }

    #[test]
    fn less_than_test() {
        let arg_count = ArgCount::less_than(5);
        assert!(!arg_count.takes_exactly(5));
        assert_eq!(arg_count.min_or_default(), 0);
        assert_eq!(arg_count.max_or_default(), 5);
    }

    #[test]
    fn contains_test() {
        let arg_count = ArgCount::new(Some(0), Some(3));
        assert!(arg_count.takes(0));
        assert!(arg_count.takes(1));
        assert!(arg_count.takes(2));
        assert!(arg_count.takes(3));
    }

    #[test]
    fn display_test() {
        assert_eq!(ArgCount::zero().to_string(), "no values");
        assert_eq!(ArgCount::new(Some(0), Some(2)).to_string(), "0 to 2 values");
        assert_eq!(ArgCount::exactly(1).to_string(), "1 value");
        assert_eq!(ArgCount::more_than(2).to_string(), "2 or more values");
        assert_eq!(ArgCount::less_than(10).to_string(), "10 or less values");
        assert_eq!(ArgCount::any().to_string(), "any number of values");
    }
}