refining-core 0.3.0

Core functionality for 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
//! Refinement types.

use core::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    marker::PhantomData,
    mem::transmute,
    ops::Deref,
};

#[cfg(feature = "unsafe-assert")]
use core::hint::assert_unchecked;

use crate::{
    context::NoContext,
    errors::{Error, Recoverable, RecoverableRef},
    predicate::Predicate,
    types::TypeStr,
};

/// Represents refinement types.
#[repr(transparent)]
pub struct Refinement<T: ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized = NoContext> {
    predicate: PhantomData<P>,
    context: PhantomData<C>,
    value: T,
}

impl<T: Clone, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Clone for Refinement<T, P, C> {
    fn clone(&self) -> Self {
        // SAFETY: `clone` does not change the value, so the predicate is still satisfied
        unsafe { Self::unchecked(self.get_ref().clone()) }
    }
}

impl<T: Copy, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Copy for Refinement<T, P, C> {}

impl<T: fmt::Debug + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> fmt::Debug
    for Refinement<T, P, C>
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get_ref().fmt(formatter)
    }
}

impl<T: fmt::Display + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> fmt::Display
    for Refinement<T, P, C>
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get_ref().fmt(formatter)
    }
}

impl<T: PartialEq + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> PartialEq
    for Refinement<T, P, C>
{
    fn eq(&self, other: &Self) -> bool {
        self.get_ref().eq(other.get_ref())
    }
}

impl<T: Eq + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Eq for Refinement<T, P, C> {}

impl<T: PartialOrd + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> PartialOrd
    for Refinement<T, P, C>
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.get_ref().partial_cmp(other.get_ref())
    }
}

impl<T: Ord + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Ord for Refinement<T, P, C> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.get_ref().cmp(other.get_ref())
    }
}

impl<T: Hash + ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Hash for Refinement<T, P, C> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.get_ref().hash(state);
    }
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> AsRef<T> for Refinement<T, P, C> {
    fn as_ref(&self) -> &T {
        self.get_ref()
    }
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Deref for Refinement<T, P, C> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.get_ref()
    }
}

mod sealed {
    pub trait Sealed {}
}

/// Represents recoverable refining results.
pub type RecoverableRefinement<R> =
    Recoverable<R, <R as Refining>::Predicate, <R as Refining>::Context, <R as Refining>::Value>;

/// Represents recoverable reference refining results.
pub type RecoverableRefinementRef<'a, R> = RecoverableRef<
    'a,
    R,
    <R as Refining>::Predicate,
    <R as Refining>::Context,
    <R as Refining>::Value,
>;

/// Refinement methods.
///
/// This sealed trait is used for generics over [`Refinement<T, P, C>`].
pub trait Refining: Deref<Target = Self::Value> + sealed::Sealed {
    /// The refinement value (`T` in [`Refinement<T, P, C>`]).
    type Value: ?Sized;

    /// The refinement predicate (`P` in [`Refinement<T, P, C>`]).
    type Predicate: Predicate<Self::Value> + ?Sized;

    /// The refinement context (`C` in [`Refinement<T, P, C>`]).
    type Context: TypeStr + ?Sized;

    /// Constructs [`Self`] from [`Self::Value`] by reference without checking.
    ///
    /// # Safety
    ///
    /// This method should only be called for references that satisfy [`Self::Predicate`].
    ///
    /// Alternatively, this can be checked using the [`is_fine`] method.
    ///
    /// [`is_fine`]: Self::is_fine
    unsafe fn unchecked_ref(value: &Self::Value) -> &Self;

    /// Constructs [`Self`] from [`Self::Value`] without checking.
    ///
    /// # Safety
    ///
    /// This method should only be called for values that satisfy [`Self::Predicate`].
    ///
    /// Alternatively, this can be checked using the [`is_fine`] method.
    ///
    /// [`is_fine`]: Self::is_fine
    unsafe fn unchecked(value: Self::Value) -> Self
    where
        Self::Value: Sized;

    /// Constructs [`Self`] from default [`Self::Value`] without checking.
    ///
    /// # Safety
    ///
    /// This method should only be called if the default value satisfies [`Self::Predicate`].
    ///
    /// Alternatively, this can be checked using the [`is_fine`] method.
    ///
    /// [`is_fine`]: Self::is_fine
    unsafe fn unchecked_default() -> Self
    where
        Self::Value: Default,
        Self: Sized,
    {
        unsafe { Self::unchecked(Self::Value::default()) }
    }

    /// Checks whether the given [`Self::Value`] satisfies [`Self::Predicate`].
    ///
    /// This is the same as calling [`Self::Predicate::check`] on the value.
    ///
    /// [`Self::Predicate::check`]: Predicate::check
    fn is_fine(value: &Self::Value) -> bool {
        Self::Predicate::check(value)
    }

    /// Returns the contained value reference.
    fn get_ref(&self) -> &Self::Value;

    /// Returns the contained value.
    fn get(self) -> Self::Value
    where
        Self::Value: Sized;

    /// Constructs [`Self`] from [`Self::Value`] by reference.
    ///
    /// # Errors
    ///
    /// Returns [`Error<Self::Value, Self::Predicate, Self::Context>`](Error)
    /// reference in case the reference does not satisfy the predicate.
    fn checked_ref(value: &Self::Value) -> RecoverableRefinementRef<'_, Self>;

    /// Constructs [`Self`] from [`Self::Value`].
    ///
    /// # Errors
    ///
    /// Returns [`Error<Self::Value, Self::Predicate, Self::Context>`](Error)
    /// in case the value does not satisfy the predicate.
    fn checked(value: Self::Value) -> RecoverableRefinement<Self>
    where
        Self::Value: Sized,
        Self: Sized;

    /// Constructs [`Self`] from default [`Self::Value`].
    ///
    /// # Errors
    ///
    /// Returns [`Error<Self::Value, Self::Predicate, Self::Context>`](Error)
    /// in case the default value does not satisfy the predicate.
    fn checked_default() -> RecoverableRefinement<Self>
    where
        Self::Value: Default,
        Self: Sized,
    {
        Self::checked(Self::Value::default())
    }
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Refinement<T, P, C> {
    /// Constructs [`Self`] by reference without checking.
    ///
    /// # Safety
    ///
    /// This method should only be called for references that satisfy `P`,
    /// which can be checked via [`is_fine`].
    ///
    /// [`is_fine`]: Self::is_fine
    pub const unsafe fn unchecked_ref(value: &T) -> &Self {
        // SAFETY: layout of `T` matches `Self` due to `repr(transparent)`, so this is safe
        // moreover, the caller guarantees that `value` satisfies `P`
        unsafe { transmute(value) }
    }

    /// Returns the contained value reference.
    ///
    /// If the `unsafe-assert` feature is enabled, [`assert_unchecked`] is called on the reference
    /// before returning.
    ///
    /// The [`get_ref_no_assert`] method is provided in case the assertion is explicitly not needed.
    ///
    /// [`assert_unchecked`]: core::hint::assert_unchecked
    /// [`get_ref_no_assert`]: Self::get_ref_no_assert
    #[allow(clippy::missing_const_for_fn)] // conditionally const
    pub fn get_ref(&self) -> &T {
        let reference = self.get_ref_no_assert();

        #[cfg(feature = "unsafe-assert")]
        unsafe {
            assert_unchecked(Self::is_fine(reference));
        }

        reference
    }

    /// Returns the contained value.
    pub const fn get_ref_no_assert(&self) -> &T {
        &self.value
    }

    /// Checks whether the provided value satisfies `P`.
    ///
    /// This is the same as calling [`P::check`] on it.
    ///
    /// [`P::check`]: Predicate::check
    pub fn is_fine(value: &T) -> bool {
        P::check(value)
    }

    /// Constructs [`Self`] by reference.
    ///
    /// # Errors
    ///
    /// Returns [`Error<T, P, C>`] in case the reference does not satisfy `P`.
    ///
    /// [`Error<T, P, C>]: Error
    pub fn checked_ref(value: &T) -> RecoverableRef<'_, Self, P, C, T> {
        if Self::is_fine(value) {
            Ok(unsafe { Self::unchecked_ref(value) })
        } else {
            Err(Error::new_ref(value))
        }
    }
}

impl<T, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Refinement<T, P, C> {
    /// Constructs [`Self`] without checking the value.
    ///
    /// # Safety
    ///
    /// This method should only be called for values that satisfy the predicate `P`,
    /// which can be checked using [`is_fine`].
    ///
    /// [`is_fine`]: Self::is_fine
    pub const unsafe fn unchecked(value: T) -> Self {
        Self {
            predicate: PhantomData,
            context: PhantomData,
            value,
        }
    }

    /// Returns the contained value.
    ///
    /// If the `unsafe-assert` feature is enabled, [`assert_unchecked`] is called on the reference
    /// before returning the value.
    ///
    /// The [`get_no_assert`] method is provided in case the assertion is explicitly not needed.
    ///
    /// [`assert_unchecked`]: core::hint::assert_unchecked
    /// [`get_no_assert`]: Self::get_no_assert
    pub fn get(self) -> T {
        let value = self.get_no_assert();

        #[cfg(feature = "unsafe-assert")]
        unsafe {
            assert_unchecked(Self::is_fine(&value));
        }

        value
    }

    /// Returns the contained value.
    pub fn get_no_assert(self) -> T {
        self.value
    }

    /// Constructs [`Self`] from the given value.
    ///
    /// # Errors
    ///
    /// Returns [`Error<T, P, C>`] in case the value does not satisfy `P`.
    ///
    /// [`Error<T, P, C>]: Error
    pub fn checked(value: T) -> Recoverable<Self, P, C, T> {
        if Self::is_fine(&value) {
            Ok(unsafe { Self::unchecked(value) })
        } else {
            Err(Error::new(value))
        }
    }
}

impl<T: Default, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Refinement<T, P, C> {
    /// Constructs [`Self`] from the default value.
    ///
    /// # Safety
    ///
    /// This method should only be called if the default value satisfies `P`,
    /// which can be checked using [`is_fine`].
    ///
    /// [`is_fine`]: Self::is_fine
    pub unsafe fn unchecked_default() -> Self {
        unsafe { Self::unchecked(T::default()) }
    }

    /// Constructs [`Self`] from the default value.
    ///
    /// # Errors
    ///
    /// Returns [`Error<T, P, C>`] in case the default value does not satisfy `P`.
    ///
    /// [`Error<T, P, C>]: Error
    pub fn checked_default() -> Recoverable<Self, P, C, T> {
        Self::checked(T::default())
    }
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> sealed::Sealed
    for Refinement<T, P, C>
{
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, C: TypeStr + ?Sized> Refining for Refinement<T, P, C> {
    type Value = T;
    type Predicate = P;
    type Context = C;

    unsafe fn unchecked_ref(value: &Self::Value) -> &Self {
        unsafe { Self::unchecked_ref(value) }
    }

    unsafe fn unchecked(value: Self::Value) -> Self
    where
        Self::Value: Sized,
    {
        unsafe { Self::unchecked(value) }
    }

    fn is_fine(value: &Self::Value) -> bool {
        Self::is_fine(value)
    }

    fn get_ref(&self) -> &Self::Value {
        self.get_ref()
    }

    fn get(self) -> Self::Value
    where
        Self::Value: Sized,
    {
        self.get()
    }

    fn checked_ref(value: &Self::Value) -> RecoverableRefinementRef<'_, Self> {
        Self::checked_ref(value)
    }

    fn checked(value: Self::Value) -> RecoverableRefinement<Self>
    where
        Self::Value: Sized,
    {
        Self::checked(value)
    }
}

/// Extends any type `T` to allow refining its values with `R` implementing [`Refining<Value = T>`].
pub trait Refine {
    /// Refines the given value with `R` by reference.
    ///
    /// This is the same as calling [`R::checked_ref`] on `Self` reference.
    ///
    /// # Errors
    ///
    /// See [`checked_ref`].
    ///
    /// [`R::checked_ref`]: Refining::checked_ref
    /// [`checked_ref`]: Refining::checked_ref
    fn refine_ref<R: Refining<Value = Self> + ?Sized>(&self) -> RecoverableRefinementRef<'_, R> {
        R::checked_ref(self)
    }

    /// Refines the given value with `R`.
    ///
    /// This is the same as calling [`R::checked`] on `Self` value.
    ///
    /// # Errors
    ///
    /// See [`checked`].
    ///
    /// [`R::checked`]: Refining::checked
    /// [`checked`]: Refining::checked
    fn refine<R: Refining<Value = Self>>(self) -> RecoverableRefinement<R>
    where
        Self: Sized,
    {
        R::checked(self)
    }
}

impl<T: ?Sized> Refine for T {}