sophia_iri/
_wrap_macro.rs

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
#[macro_export]
/// This macro is used to create a read-only wrapper around a type T,
/// usually for the purpose of guaranteeing that the wrapped value verifies some condition.
/// This macro takes care of defining all the usual traits for the wrapper type.
///
/// In its most general form, it is used like this:
/// ```
/// # #[macro_use] extern crate sophia_iri;
/// # trait SomeTrait { fn check_some_property(&self) -> bool; }
/// # #[derive(Debug)]
/// # struct SomeError {}
/// wrap! { MyWrapper<T: SomeTrait> :
///     // NB: the trait bound is required, as well as the trailing colon (':').
///
///     // You can include members in the impl of the wrapper type.
///     // At the very least, you must define a `new` constructor,
///     // that will check the appropriate condition on the wrapped value,
///     // and return a `Result`.
///
///     /// The `new` constructor should carry the documentation of the type;
///     /// since the generated documentation for the type will point to it.
///     pub fn new(inner: T) -> Result<Self, SomeError> {
///         if inner.check_some_property() {
///             Ok(Self(inner))
///         } else {
///             Err(SomeError {})
///         }
///     }
/// }
/// ```
///
/// A more specific form is when the trait that T must satisfy
/// is [`std::borrow::Borrow<U>`], in which case more traits
/// can be implemented by the wrapper. This is achieved with
/// the following syntax:
/// ```
/// # #[macro_use] extern crate sophia_iri;
/// # #[derive(Debug)]
/// # struct SomeError {}
/// wrap! { Foo borrowing str :
///     /// As before
///     pub fn new(inner: T) -> Result<Self, String> {
///         if inner.borrow().contains("foo") {
///             Ok(Self(inner))
///         } else {
///             Err(format!("{:?} is not a valid Foo", inner.borrow()))
///         }
///     }
/// }
/// ```
///
/// Two [examples](crate::wrap_macro_examples) are availble,
/// illustrating the members and trait implementation generated by this macro.
///
/// NB: the documentation of the wrapper will point to the documentation of the `new` method.
macro_rules! wrap {
    ($wid:ident<$tid:ident: $bound:path>: $new:item $($item:item)*) => {
        #[derive(Clone, Copy, Debug)]

        #[doc = concat!(
            "See [`",
            stringify!($wid),
            "::new`].",
        )]
        pub struct $wid<$tid: $bound>($tid);

        impl<$tid: $bound> $wid<$tid> {
            $new
            $($item)*

            #[doc = concat!(
                "Construct a `",
                stringify!($wid),
                "<T>` without checking that the inner value is valid. ",
                "If it is not, it may result in undefined behaviour.",
            )]
            #[allow(dead_code)]
            pub fn new_unchecked(inner: $tid) -> Self {
                if cfg!(debug_assertions) {
                    Self::new(inner).unwrap()
                } else {
                    Self(inner)
                }
            }

            /// Returns the wrapped value, consuming `self`.
            #[allow(dead_code)]
            pub fn unwrap(self) -> $tid {
                self.0
            }

            #[doc = concat!(
                "Map a `",
                stringify!($wid),
                "<T>` to a `",
                stringify!($wid),
                "<U>` by applying a function to the wrapped value. ",
                "It does not check that the value returned by the function is valid. ",
                "If it is not, it may result in undefined behaviour.",
            )]
            #[allow(dead_code)]
            pub fn map_unchecked<F, U>(self, f: F) -> $wid<U>
            where
                F: FnOnce(T) -> U,
                U: $bound,
            {
                let inner = self.unwrap();
                let new_inner: U = f(inner);
                $wid(new_inner)
            }
        }

        impl<T: $bound> std::ops::Deref for $wid<T> {
            type Target = T;
            fn deref(&self) -> &T {
                &self.0
            }
        }

        impl<T: $bound> std::convert::AsRef<T> for $wid<T> {
            fn as_ref(&self) -> &T {
                &self.0
            }
        }

        impl<T: $bound> std::borrow::Borrow<T> for $wid<T> {
            fn borrow(&self) -> &T {
                &self.0
            }
        }

        impl<T, U> std::cmp::PartialEq<$wid<T>> for $wid<U>
        where
            T: $bound,
            U: $bound + std::cmp::PartialEq<T>,
        {
            fn eq(&self, rhs: &$wid<T>) -> bool {
                self.0 == rhs.0
            }
        }

        impl<T> std::cmp::Eq for $wid<T>
        where
            T: $bound + std::cmp::Eq,
        {}

        impl<T, U> std::cmp::PartialOrd<$wid<T>> for $wid<U>
        where
            T: $bound,
            U: $bound + std::cmp::PartialOrd<T>,
        {
            fn partial_cmp(&self, rhs: &$wid<T>) -> std::option::Option<std::cmp::Ordering> {
                std::cmp::PartialOrd::partial_cmp(&self.0, &rhs.0)
            }
        }

        impl<T> std::cmp::Ord for $wid<T>
        where
            T: $bound + std::cmp::Eq + std::cmp::Ord,
        {
            fn cmp(&self, rhs: &$wid<T>) -> std::cmp::Ordering {
                std::cmp::Ord::cmp(&self.0, &rhs.0)
            }
        }


        impl<T> std::hash::Hash for $wid<T>
        where
            T: $bound + std::hash::Hash,
        {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.0.hash(state);
            }
        }
    };
    ($wid:ident borrowing $bid:ty: $new:item $($item:item)*) => {
        $crate::wrap!($wid<T: std::borrow::Borrow<$bid>>: $new $($item)*);

        impl<T> $wid<T>
        where
            T: std::borrow::Borrow<$bid>,
        {
            #[doc = concat!(
                "Convert from `&",
                stringify!($wid),
                "<T>` to `",
                stringify!($wid),
                "<&",
                stringify!($bid),
                ">`.",
            )]
            #[allow(dead_code)]
            pub fn as_ref(&self) -> $wid<&$bid> {
                $wid(self.0.borrow())
            }
        }

        impl $wid<&'static $bid> {
            #[doc = concat!(
                "Construct a `",
                stringify!($wid),
                "<&'static ",
                stringify!($bid),
                ">` without checking that the inner value is valid. ",
                "If it is not, it may result in undefined behaviour.",
            )]
            #[allow(dead_code)]
            pub const fn new_unchecked_const(inner: &'static $bid) -> Self {
                $wid(inner)
            }
        }

        impl<T: std::borrow::Borrow<$bid>> std::convert::AsRef<$bid> for $wid<T> {
            fn as_ref(&self) -> &$bid {
                &self.0.borrow()
            }
        }

        impl<T: std::borrow::Borrow<$bid>> std::borrow::Borrow<$bid> for $wid<T> {
            fn borrow(&self) -> &$bid {
                &self.0.borrow()
            }
        }

        impl<T> std::cmp::PartialEq<$bid> for $wid<T>
        where
            T: std::borrow::Borrow<$bid>,
            $bid: std::cmp::PartialEq,
        {
                fn eq(&self, other: &$bid) -> bool {
                    self.0.borrow() == other
                }
        }

        impl<T> std::cmp::PartialEq<$wid<T>> for $bid
        where
            T: std::borrow::Borrow<$bid>,
            $bid: std::cmp::PartialEq,
        {
                fn eq(&self, other: &$wid<T>) -> bool {
                    self == other.0.borrow()
                }
        }

        impl<T> std::cmp::PartialOrd<$bid> for $wid<T>
        where
            T: std::borrow::Borrow<$bid>,
            $bid: std::cmp::PartialOrd,
        {
            fn partial_cmp(&self, other: &$bid) -> std::option::Option<std::cmp::Ordering> {
                self.0.borrow().partial_cmp(other)
            }
        }

        impl<T> std::cmp::PartialOrd<$wid<T>> for $bid
        where
            T: std::borrow::Borrow<$bid>,
            $bid: std::cmp::PartialOrd,
        {
            fn partial_cmp(&self, other: &$wid<T>) -> std::option::Option<std::cmp::Ordering> {
                self.partial_cmp(other.0.borrow())
            }
        }
    };
}

#[cfg(test)]
pub mod test_simple_wrap {
    pub trait Number {
        fn even(&self) -> bool;
    }
    impl Number for i32 {
        fn even(&self) -> bool {
            *self % 2 == 0
        }
    }
    impl Number for isize {
        fn even(&self) -> bool {
            *self % 2 == 0
        }
    }

    wrap! { Even<T: Number>:
        pub fn new(inner: T) -> Result<Self, ()> {
            if inner.even() {
                Ok(Even(inner))
            } else {
                Err(())
            }
        }
    }

    #[test]
    fn constructor_succeeds() {
        assert!(Even::new(42).is_ok());
    }

    #[test]
    fn constructor_fails() {
        assert!(Even::new(43).is_err());
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn unwrap() {
        let even = Even(42);
        let _: isize = even.unwrap();
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn deref() {
        let even = Even(42);
        let _: &isize = &even;
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn as_ref() {
        let even = Even(42);
        let _: &isize = even.as_ref();
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn borrow() {
        use std::borrow::Borrow;
        let even = Even(42);
        let _: &isize = even.borrow();
    }
}

#[cfg(test)]
pub mod test_wrap_borrowing {
    wrap! { Foo borrowing str :
        /// The constructor of Foo
        pub fn new(inner: T) -> Result<Self, ()> {
            if inner.borrow().contains("foo") {
                Ok(Foo(inner))
            } else {
                Err(())
            }
        }

        pub fn as_str(&self) -> &str {
            self.0.borrow()
        }
    }

    #[test]
    fn new_succeeds() {
        assert!(Foo::new("this foo is good").is_ok());
    }

    #[test]
    fn new_fails() {
        assert!(Foo::new("this bar is bad").is_err());
    }

    #[test]
    fn partial_eq() {
        let f1a = Foo::new("foo1".to_string()).unwrap();
        let f1b = Foo::new("foo1").unwrap();
        let f2 = Foo::new("foo2").unwrap();
        assert_eq!(&f1a, "foo1");
        assert_eq!(&f1a, "foo1");
        assert_eq!(&f2, "foo2");
        assert_ne!(&f2, "foo1");
        assert_eq!("foo1", &f1a);
        assert_eq!("foo1", &f1a);
        assert_eq!("foo2", &f2);
        assert_ne!("foo1", &f2);
        assert_eq!(f1a.as_str(), f1b.as_str());
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn new_unchecked() {
        let _: Foo<String> = Foo::new_unchecked("".into());
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn unwrap() {
        let foo = Foo("foo".to_string());
        let _: String = foo.unwrap();
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn deref() {
        let foo = Foo("this foo is good".to_string());
        let _: &String = &foo;
        let _: &str = &foo;
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn as_ref_trait() {
        let foo = Foo("this foo is good".to_string());
        let _: &String = AsRef::as_ref(&foo);
        let _: &str = AsRef::as_ref(&foo);
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn borrow() {
        use std::borrow::Borrow;
        let foo = Foo("this foo is good".to_string());
        let _: &String = foo.borrow();
        let _: &str = foo.borrow();
    }

    // only check that this compiles
    #[allow(dead_code)]
    fn as_ref() {
        let foo = Foo("this foo is good".to_string());
        let _: Foo<&str> = foo.as_ref();
    }
}