refinement-types 0.3.0

Refinement types.
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Predicates based on length.

use core::{fmt, marker::PhantomData};

#[cfg(feature = "diagnostics")]
use miette::Diagnostic;

use thiserror::Error;

use crate::{
    core::Predicate,
    logic::{And, Not},
};

/// Represents types that have length defined for their values.
pub trait HasLength {
    /// Returns the value length.
    fn length(&self) -> usize;
}

/// Represents errors that occur when the provided value has
/// length greater than or equal to some bound.
#[derive(Debug, Error)]
#[error("received value with length >= {other}")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(length::lt), help("make sure the length is less than {other}"))
)]
pub struct LessError {
    /// The length against which the check was performed (the `N`).
    pub other: usize,
}

impl LessError {
    /// Constructs [`Self`].
    pub const fn new(other: usize) -> Self {
        Self { other }
    }
}

/// Checks whether the given value has length less than `N`.
pub struct Less<const N: usize> {
    private: PhantomData<()>,
}

impl<const N: usize, T: HasLength + ?Sized> Predicate<T> for Less<N> {
    type Error = LessError;

    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() < N {
            Ok(())
        } else {
            Err(Self::Error::new(N))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "value with length < {N}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::lt<{N}>")
    }
}

/// Represents errors that occur when the provided value has
/// length greater than some bound.
#[derive(Debug, Error)]
#[error("received value with length > {other}")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(
        code(length::le),
        help("make sure the length is less than or equal to {other}")
    )
)]
pub struct LessOrEqualError {
    /// The length against which the check was performed (the `N`).
    pub other: usize,
}

impl LessOrEqualError {
    /// Constructs [`Self`].
    pub const fn new(other: usize) -> Self {
        Self { other }
    }
}

/// Checks whether the given value has length less than or equal to `N`.
pub struct LessOrEqual<const N: usize> {
    private: PhantomData<()>,
}

impl<const N: usize, T: HasLength + ?Sized> Predicate<T> for LessOrEqual<N> {
    type Error = LessOrEqualError;

    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() <= N {
            Ok(())
        } else {
            Err(Self::Error::new(N))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "value with length <= {N}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::le<{N}>")
    }
}

/// Represents errors that occur when the provided value has
/// length less than or equal to some bound.
#[derive(Debug, Error)]
#[error("received value with length <= {other}")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(length::gt), help("make sure the length is greater than {other}"))
)]
pub struct GreaterError {
    /// The length against which the check was performed (the `N`).
    pub other: usize,
}

impl GreaterError {
    /// Constructs [`Self`].
    pub const fn new(other: usize) -> Self {
        Self { other }
    }
}

/// Checks whether the given value has length greater than `N`.
pub struct Greater<const N: usize> {
    private: PhantomData<()>,
}

impl<const N: usize, T: HasLength + ?Sized> Predicate<T> for Greater<N> {
    type Error = GreaterError;

    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() > N {
            Ok(())
        } else {
            Err(Self::Error::new(N))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "value with length > {N}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::gt<{N}>")
    }
}

/// Represents errors that occur when the provided value has
/// length less than some bound.
#[derive(Debug, Error)]
#[error("received value with length < {other}")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(
        code(length::ge),
        help("make sure the length is greater than or equal to {other}")
    )
)]
pub struct GreaterOrEqualError {
    /// The length against which the check was performed (the `N`).
    pub other: usize,
}

impl GreaterOrEqualError {
    /// Constructs [`Self`].
    pub const fn new(other: usize) -> Self {
        Self { other }
    }
}

/// Checks whether the given value has length greater than or equal to `N`.
pub struct GreaterOrEqual<const N: usize> {
    private: PhantomData<()>,
}

impl<const N: usize, T: HasLength + ?Sized> Predicate<T> for GreaterOrEqual<N> {
    type Error = GreaterOrEqualError;

    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() >= N {
            Ok(())
        } else {
            Err(Self::Error::new(N))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "value with length >= {N}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::ge<{N}>")
    }
}

/// Represents errors that occur when the provided value has
/// length not equal to some bound.
#[derive(Debug, Error)]
#[error("received value with length != {other}")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(length::eq), help("make sure the length is equal to {other}"))
)]
pub struct EqualError {
    /// The length against which the check was performed (the `N`).
    pub other: usize,
}

impl EqualError {
    /// Constructs [`Self`].
    pub const fn new(other: usize) -> Self {
        Self { other }
    }
}

/// Checks whether the given value has length equal to `N`.
pub struct Equal<const N: usize> {
    private: PhantomData<()>,
}

impl<const N: usize, T: HasLength + ?Sized> Predicate<T> for Equal<N> {
    type Error = EqualError;

    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() == N {
            Ok(())
        } else {
            Err(Self::Error::new(N))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "value with length == {N}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::eq<{N}>")
    }
}

/// Represents errors that occur when the provided value has
/// length equal to some bound.
#[derive(Debug, Error)]
#[error("received value with length == {other}")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(length::ne), help("make sure the length is not equal to {other}"))
)]
pub struct NotEqualError {
    /// The length against which the check was performed (the `N`).
    pub other: usize,
}

impl NotEqualError {
    /// Constructs [`Self`].
    pub const fn new(other: usize) -> Self {
        Self { other }
    }
}

/// Checks whether the given value has length not equal to `N`.
pub struct NotEqual<const N: usize> {
    private: PhantomData<()>,
}

impl<const N: usize, T: HasLength + ?Sized> Predicate<T> for NotEqual<N> {
    type Error = NotEqualError;

    #[allow(clippy::if_not_else)]
    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() != N {
            Ok(())
        } else {
            Err(Self::Error::new(N))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "value with length != {N}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::ne<{N}>")
    }
}

/// Represents `(M, N)` intervals.
pub type Open<const M: usize, const N: usize> = And<Greater<M>, Less<N>>;

/// Represents `[M, N)` intervals.
pub type ClosedOpen<const M: usize, const N: usize> = And<GreaterOrEqual<M>, Less<N>>;

/// Represents `(M, N]` intervals.
pub type OpenClosed<const M: usize, const N: usize> = And<Greater<M>, LessOrEqual<N>>;

/// Represents `[M, N]` intervals.
pub type Closed<const M: usize, const N: usize> = And<GreaterOrEqual<M>, LessOrEqual<N>>;

/// Checks whether the given value has zero length.
pub type Zero = Equal<0>;

/// Checks whether the given value has non-zero length.
pub type NonZero = NotEqual<0>;

/// Represents errors when the provided value has
/// length divided by [`divisor`] not equal to [`modulo`].
///
/// [`divisor`]: Self::divisor
/// [`modulo`]: Self::modulo
#[derive(Debug, Error)]
#[error("received value % {divisor} != {modulo}")]
pub struct ModuloError {
    /// The divisor that the value length should be divided by (the `D`).
    pub divisor: usize,
    /// The expected modulo of the length division (the `M`).
    pub modulo: usize,
}

impl ModuloError {
    /// Constructs [`Self`].
    pub const fn new(divisor: usize, modulo: usize) -> Self {
        Self { divisor, modulo }
    }
}

/// Checks whether the given value length divided by `D` has modulo `M`.
pub struct Modulo<const D: usize, const M: usize> {
    private: PhantomData<()>,
}

impl<const D: usize, const M: usize, T: HasLength + ?Sized> Predicate<T> for Modulo<D, M> {
    type Error = ModuloError;

    fn check(value: &T) -> Result<(), Self::Error> {
        if value.length() % D == M {
            Ok(())
        } else {
            Err(Self::Error::new(D, M))
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length % {D} == {M}")
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "length::mod<{D}, {M}>")
    }
}

/// Checks whether the given value length is divisible by `D`.
pub type Divisible<const D: usize> = Modulo<D, 0>;

/// Checks whether the given value length is even.
pub type Even = Divisible<2>;

/// Checks whether the given value length is odd.
pub type Odd = Not<Even>;

// core

impl HasLength for str {
    fn length(&self) -> usize {
        self.len()
    }
}

impl<T> HasLength for [T] {
    fn length(&self) -> usize {
        self.len()
    }
}

impl<T: HasLength + ?Sized> HasLength for &T {
    fn length(&self) -> usize {
        T::length(self)
    }
}

// prelude imports

#[cfg(feature = "alloc")]
use alloc::{boxed::Box, string::String, vec::Vec};

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T: HasLength + ?Sized> HasLength for Box<T> {
    fn length(&self) -> usize {
        T::length(self)
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl HasLength for String {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> HasLength for Vec<T> {
    fn length(&self) -> usize {
        self.len()
    }
}

// clone-on-write

#[cfg(feature = "alloc")]
use alloc::borrow::{Cow, ToOwned};

#[cfg(all(not(feature = "alloc"), feature = "std"))]
use std::borrow::{Cow, ToOwned};

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T: ToOwned + HasLength + ?Sized> HasLength for Cow<'_, T> {
    fn length(&self) -> usize {
        T::length(self)
    }
}

// pointers

#[cfg(feature = "alloc")]
use alloc::rc::Rc;

#[cfg(all(not(feature = "alloc"), feature = "std"))]
use std::rc::Rc;

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T: HasLength + ?Sized> HasLength for Rc<T> {
    fn length(&self) -> usize {
        T::length(self)
    }
}

#[cfg(feature = "alloc")]
use alloc::sync::Arc;

#[cfg(all(not(feature = "alloc"), feature = "std"))]
use std::sync::Arc;

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T: HasLength + ?Sized> HasLength for Arc<T> {
    fn length(&self) -> usize {
        T::length(self)
    }
}

// shared collections

#[cfg(feature = "alloc")]
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};

#[cfg(all(not(feature = "alloc"), feature = "std"))]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};

#[cfg(any(feature = "alloc", feature = "std"))]
impl<K, V> HasLength for BTreeMap<K, V> {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> HasLength for BTreeSet<T> {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> HasLength for BinaryHeap<T> {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> HasLength for LinkedList<T> {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<T> HasLength for VecDeque<T> {
    fn length(&self) -> usize {
        self.len()
    }
}

// collections

#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};

#[cfg(feature = "std")]
impl<K, V, S> HasLength for HashMap<K, V, S> {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(feature = "std")]
impl<T, S> HasLength for HashSet<T, S> {
    fn length(&self) -> usize {
        self.len()
    }
}

// OS strings

#[cfg(feature = "std")]
use std::ffi::{OsStr, OsString};

#[cfg(feature = "std")]
impl HasLength for OsStr {
    fn length(&self) -> usize {
        self.len()
    }
}

#[cfg(feature = "std")]
impl HasLength for OsString {
    fn length(&self) -> usize {
        self.len()
    }
}

// paths (via underlying strings)

#[cfg(feature = "std")]
use std::path::{Path, PathBuf};

#[cfg(feature = "std")]
impl HasLength for Path {
    fn length(&self) -> usize {
        self.as_os_str().length()
    }
}

#[cfg(feature = "std")]
impl HasLength for PathBuf {
    fn length(&self) -> usize {
        self.as_os_str().length()
    }
}