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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

//! Module containing all of macro definitions for `async-coap-uri`.

pub use super::{impl_uri_buf_traits, impl_uri_traits};
pub use super::{rel_ref, uri, uri_ref};
pub use super::{rel_ref_format, uri_format, uri_ref_format};

// Internal macros.
#[doc(hidden)]
pub use super::{_impl_uri_buf_traits_base, _impl_uri_traits, _impl_uri_traits_base};

#[doc(hidden)]
#[macro_export]
macro_rules! _uri_const {
    ( $S:expr, $C:ty ) => {{
        const __CONST_S: &'static str = $S;
        // We do this weird casting thing here to make sure that we
        // don't end up using unstable features, while still allowing
        // these macros to be used to assign constants.
        unsafe {
            union Slices<'a> {
                str: &'a str,
                uri: &'a $C,
            }
            Slices { str: __CONST_S }.uri
        }
    }};
}

/// Creates a `&'static UriRef` from a string literal.
///
/// Accepts only string constants and literals. The given string *MUST* be well-formed.
///
/// Examples:
///
/// ```
/// # use async_coap_uri::prelude::*;
/// let x = uri_ref!("a/b/c?q=foobar#frag");
/// assert_eq!(x.scheme(),None);
/// assert_eq!(x.raw_authority(),None);
/// assert_eq!(x.raw_path(),"a/b/c");
/// assert_eq!(x.raw_query(),Some("q=foobar"));
/// assert_eq!(x.raw_fragment(),Some("frag"));
/// ```
///
/// ```
/// # use async_coap_uri::prelude::*;
/// let x = uri_ref!("http://example.com");
/// assert_eq!(x.scheme(),Some("http"));
/// assert_eq!(x.raw_authority(),Some("example.com"));
/// assert_eq!(x.raw_path(),"");
/// assert_eq!(x.raw_query(),None);
/// assert_eq!(x.raw_fragment(),None);
/// ```
///
/// Checks for correctness are performed at compile time:
///
/// ```compile_fail
/// # use async_coap_uri::prelude::*;
/// // This will not compile.
/// let x = uri_ref!("%00 invalid %ff");
/// ```
///
#[macro_export]
macro_rules! uri_ref {
    ( unsafe $S:expr ) => {{
        // We don't do any correctness checks when $S is preceded by `unsafe`.
        $crate::_uri_const!($S, $crate::UriRef)
    }};
    ( $S:expr ) => {{
        assert_uri_ref_literal!($S);
        $crate::_uri_const!($S, $crate::UriRef)
    }};
    ( ) => {
        $crate::uri_ref!("")
    };
}

/// Creates a `&'static RelRef` from a string literal.
///
/// Accepts only string constants and literals. The given string *MUST* be well-formed.
///
/// Example:
///
/// ```
/// # use async_coap_uri::prelude::*;
/// let x = rel_ref!("a/b/c?q=foobar#frag");
/// assert_eq!(x.raw_path(),"a/b/c");
/// assert_eq!(x.raw_query(),Some("q=foobar"));
/// assert_eq!(x.raw_fragment(),Some("frag"));
/// ```
///
/// Checks for correctness are performed at compile time:
///
/// ```compile_fail
/// # use async_coap_uri::prelude::*;
/// // This will not compile.
/// let x = rel_ref!("%00 invalid %ff");
/// ```
///
/// Degenerate cases (strings that could be confused with URIs if parsed as URI-Refs)
/// will also not compile:
///
/// ```compile_fail
/// # use async_coap_uri::prelude::*;
/// // This will not compile because `//a/b/c` is
/// // a degenerate relative reference.
/// let x = rel_ref!("//a/b/c");
/// ```
///
/// ```compile_fail
/// # use async_coap_uri::prelude::*;
/// // This will not compile because `g:a:b:c` is
/// // a degenerate relative reference.
/// let x = rel_ref!("g:a:b:c");
/// ```
///
/// Both of those cases can be made to compile by adjusting them to no longer be degenerate:
///
/// ```
/// # use async_coap_uri::prelude::*;
/// let b = rel_ref!("/.//a/b/c"); // Prepending "/."
/// let a = rel_ref!("./g:a:b:c"); // Prepending "./"
/// let a = rel_ref!("g%3Aa:b:c"); // Convert first colon to "%3A"
/// ```
///
/// At runtime, `UriRef::from_str("g:a:b:c")` is allowed since in some circumstances it cannot
/// be avoided, but there is usually no good reason to have a degenerate `RelRef` literal.
/// In the rare case where such a thing is warranted (unit tests, for example), you can disable
/// compile-time verification by prepending the keyword `unsafe` to the string:
///
/// ```
/// # use async_coap_uri::prelude::*;
/// // Both of these will compile because the `unsafe` keyword
/// // disables the compile-time validity checks:
/// assert!(rel_ref!(unsafe "//a/b/c").is_degenerate());
/// assert!(rel_ref!(unsafe "g:a:b:c").is_degenerate());
/// ```
#[macro_export]
macro_rules! rel_ref {
    ( unsafe $S:expr ) => {{
        // We don't do any correctness checks when $S is preceded by `unsafe`.
        $crate::_uri_const!($S, $crate::RelRef)
    }};
    ( $S:expr ) => {{
        assert_rel_ref_literal!($S);
        $crate::_uri_const!($S, $crate::RelRef)
    }};
    ( ) => {
        $crate::rel_ref!("")
    };
}

/// Creates a `&'static Uri` from a string literal.
///
/// Accepts only string constants and literals. The given string *MUST* be well-formed.
///
/// Example:
///
/// ```
/// # use async_coap_uri::prelude::*;
/// let x = uri!("http://example.com");
/// assert_eq!(x.scheme(),Some("http"));
/// assert_eq!(x.raw_authority(),Some("example.com"));
/// ```
///
/// Checks for correctness are performed at compile time:
///
/// ```compile_fail
/// # use async_coap_uri::prelude::*;
/// // This will not compile.
/// let x = uri!("%00 invalid %ff");
/// ```
///
/// Passing something that is a valid URI-Reference but not a valid URI (i.e.: Missing scheme)
/// will also not compile:
///
/// ```compile_fail
/// # use async_coap_uri::prelude::*;
/// // This will not compile because "a/b/c" isn't a valid URI.
/// let x = uri!("a/b/c");
/// ```
///
#[macro_export]
macro_rules! uri {
    ( unsafe $S:expr ) => {{
        // We don't do any correctness checks when $S is preceded by `unsafe`.
        $crate::_uri_const!($S, $crate::Uri)
    }};
    ( $S:expr ) => {{
        assert_uri_literal!($S);
        $crate::_uri_const!($S, $crate::Uri)
    }};
    ( ) => {
        $crate::uri!("")
    };
}

/// Creates a `Option<UriRefBuf>` from the given string format and arguments.
///
/// The resulting string is checked at runtime to ensure it is well-formed.
#[cfg(feature = "std")]
#[macro_export]
macro_rules! uri_ref_format {
    ($($arg:tt)*) => ($crate::UriRefBuf::from_string(format!($($arg)*)))
}

/// Creates a `Option<UriBuf>` from the given string format and arguments.
///
/// The resulting string is checked at runtime to ensure it is well-formed.
#[cfg(feature = "std")]
#[macro_export]
macro_rules! uri_format {
    ($($arg:tt)*) => ($crate::UriBuf::from_string(format!($($arg)*)))
}

/// Creates a `Option<RelRefBuf>` from the given string format and arguments.
///
/// The resulting string is checked at runtime to ensure it is well-formed.
#[cfg(feature = "std")]
#[macro_export]
macro_rules! rel_ref_format {
    ($($arg:tt)*) => ($crate::RelRefBuf::from_string(format!($($arg)*)))
}

#[doc(hidden)]
#[macro_export]
macro_rules! _impl_uri_traits {
    ( $C:ty ) => {
        impl<T: AsRef<str> + ?Sized> core::cmp::PartialEq<T> for $C {
            fn eq(&self, other: &T) -> bool {
                core::cmp::PartialEq::eq(self.as_str(), other.as_ref())
            }
        }

        impl<T: AsRef<str> + ?Sized> core::cmp::PartialOrd<T> for $C {
            fn partial_cmp(&self, other: &T) -> Option<::std::cmp::Ordering> {
                core::cmp::PartialOrd::partial_cmp(self.as_str(), other.as_ref())
            }
        }

        impl core::cmp::Ord for $C {
            fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
                core::cmp::Ord::cmp(self.as_str(), other.as_str())
            }
        }

        impl std::fmt::Debug for $C {
            fn fmt(
                &self,
                f: &mut std::fmt::Formatter<'_>,
            ) -> std::result::Result<(), std::fmt::Error> {
                f.write_str(concat!(stringify!($C), "<"))?;
                std::fmt::Display::fmt(self.as_str(), f)?;
                f.write_str(">")
            }
        }
        impl AsRef<str> for $C {
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }
        impl AsRef<$C> for $C {
            fn as_ref(&self) -> &$C {
                &self
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! _impl_uri_traits_base {
    ( $C:ty ) => {
        _impl_uri_traits!($C);

        impl core::convert::From<&$C> for std::string::String {
            fn from(x: &$C) -> Self {
                String::from(&x.0)
            }
        }

        impl core::convert::From<&$C> for $crate::UriRefBuf {
            fn from(x: &$C) -> Self {
                unsafe { $crate::UriRefBuf::from_string_unchecked(String::from(&x.0)) }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_uri_traits {
    ( $C:ty ) => {
        _impl_uri_traits_base!($C);

        impl $crate::AnyUriRef for $C {
            fn components(&self) -> UriRawComponents<'_> {
                self.0.components()
            }

            fn write_to<W: core::fmt::Write + ?Sized>(
                &self,
                write: &mut W,
            ) -> Result<(), core::fmt::Error> {
                self.0.write_to(write)
            }

            fn is_empty(&self) -> bool {
                self.0.is_empty()
            }

            fn uri_type(&self) -> $crate::UriType {
                self.0.uri_type()
            }

            fn to_uri_ref_buf(&self) -> $crate::UriRefBuf {
                self.0.to_uri_ref_buf()
            }

            fn write_resolved<W: core::fmt::Write + ?Sized, D: $crate::AnyUriRef + ?Sized>(
                &self,
                dest: &D,
                output: &mut W,
            ) -> Result<(), $crate::ResolveError> {
                self.0.write_resolved(dest, output)
            }

            fn resolved<W: $crate::AnyUriRef + ?Sized>(
                &self,
                dest: &W,
            ) -> Result<$crate::UriRefBuf, $crate::ResolveError> {
                self.0.resolved(dest)
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! _impl_uri_buf_traits_base {
    ( $C:ty , $B:ty ) => {
        _impl_uri_traits!($C);

        impl core::convert::From<$C> for std::string::String {
            fn from(x: $C) -> Self {
                String::from(x.0)
            }
        }

        impl core::convert::From<&$C> for $C {
            fn from(x: &$C) -> Self {
                x.clone()
            }
        }

        impl std::borrow::ToOwned for $B {
            type Owned = $C;

            fn to_owned(&self) -> Self::Owned {
                unsafe { <$C>::from_string_unchecked(self.to_string()) }
            }
        }

        impl core::borrow::Borrow<$B> for $C {
            fn borrow(&self) -> &$B {
                unsafe { <$B>::from_str_unchecked(self.as_str()) }
            }
        }

        impl $crate::AnyUriRef for $C {
            fn components(&self) -> UriRawComponents<'_> {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.components()
            }

            fn write_to<W: core::fmt::Write + ?Sized>(
                &self,
                write: &mut W,
            ) -> Result<(), core::fmt::Error> {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.write_to(write)
            }

            fn is_empty(&self) -> bool {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.is_empty()
            }

            fn uri_type(&self) -> $crate::UriType {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.uri_type()
            }

            fn to_uri_ref_buf(&self) -> $crate::UriRefBuf {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.to_uri_ref_buf()
            }

            fn write_resolved<W: core::fmt::Write + ?Sized, D: $crate::AnyUriRef + ?Sized>(
                &self,
                dest: &D,
                output: &mut W,
            ) -> Result<(), $crate::ResolveError> {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.write_resolved(dest, output)
            }

            fn resolved<W: $crate::AnyUriRef + ?Sized>(
                &self,
                dest: &W,
            ) -> Result<$crate::UriRefBuf, $crate::ResolveError> {
                use core::borrow::Borrow;
                let b: &$B = self.borrow();
                b.resolved(dest)
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_uri_buf_traits {
    ( $C:ty , $B:ty) => {
        _impl_uri_buf_traits_base!($C, $B);

        impl AsRef<std::string::String> for $C {
            fn as_ref(&self) -> &std::string::String {
                AsRef::<std::string::String>::as_ref(&self.0)
            }
        }

        impl AsRef<$crate::UriRefBuf> for $C {
            fn as_ref(&self) -> &$crate::UriRefBuf {
                AsRef::<$crate::UriRefBuf>::as_ref(&self.0)
            }
        }

        impl core::convert::From<$C> for $crate::UriRefBuf {
            fn from(x: $C) -> Self {
                x.0.into()
            }
        }
    };
}