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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
use crate::{Form, Json, Query};
use indexmap::IndexMap;
pub use rweb_openapi::v3_0::*;
use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, HashMap, HashSet, LinkedList, VecDeque},
    convert::Infallible,
    sync::Arc,
};
use warp::{Rejection, Reply};

pub type Responses = IndexMap<Cow<'static, str>, Response>;

#[derive(Debug)]
pub struct ComponentDescriptor {
    components: IndexMap<Cow<'static, str>, Schema>,
}
impl ComponentDescriptor {
    pub(crate) fn new() -> Self {
        Self {
            components: IndexMap::new(),
        }
    }
    /// Get a reference to the component named `name`, if such exists.
    pub fn get_component(&self, name: &str) -> Option<&Schema> {
        self.components.get(name)
    }
    /// Get a reference to the schema of a type.
    ///
    /// If `schema` is inline, it itself is returned,
    /// otherwise the component is looked up by name and its schema is returned.
    ///
    /// # Panics
    /// Panics if `schema` refers to a non-existing component.
    pub fn get_unpack<'a>(&'a self, schema: &'a ComponentOrInlineSchema) -> &'a Schema {
        match schema {
            ComponentOrInlineSchema::Component { name } => self.get_component(name).unwrap(),
            ComponentOrInlineSchema::Inline(s) => s,
        }
    }
    /// Describes a component, iff it isn't already described.
    ///
    /// # Parameters
    /// - `name`: name of the component
    /// - `desc`: descriptor function
    ///
    /// # Returns
    /// Reference to the component
    ///
    /// # Circular references
    /// To avoid infinite recursion on circular references,
    /// a blanket schema is stored under component name first,
    /// then the component is described and the schema replaced.
    ///
    /// Note that this _may_ cause invalid spec generation if
    /// somewhere in such loop there are types that rely on
    /// cloned modification of the schema of underlying component.
    pub fn describe_component(
        &mut self,
        name: &str,
        desc: impl FnOnce(&mut ComponentDescriptor) -> Schema,
    ) -> ComponentOrInlineSchema {
        if !self.components.contains_key(name) {
            self.components
                .insert(Cow::Owned(name.to_string()), Default::default());
            self.components[name] = desc(self);
        }
        ComponentOrInlineSchema::Component {
            name: Cow::Owned(name.to_string()),
        }
    }
    /// Finalizes the descriptor and packages up all components.
    pub(crate) fn build(self) -> IndexMap<Cow<'static, str>, ObjectOrReference<Schema>> {
        self.components
            .into_iter()
            .map(|(k, v)| (k, ObjectOrReference::Object(v)))
            .collect()
    }
}

/// This can be derived by `#[derive(Schema)]`.
///
/// # `#[derive(Schema)]`
///
/// It implements [Entity] for the struct or enum. Note that it's recommended to
/// use `derive(Schema)` even when you are not using openapi, as it is noop when
/// cargo feature openapi is disabled.
///
/// ## Overriding description
///
/// ```rust
/// use rweb::*;
///
/// /// private documentation, for example
/// #[derive(Debug, Default, Schema)]
/// // #[schema(description = "This is output!!")]
/// pub struct Output {
///     /// By default, doc comments become description
///     data: String,
///     /// Another private info like implementation detail.
///     #[schema(description = "field")]
///     field_example: String,
/// }
/// ```
///
/// ## Component
///
/// ```rust
/// use rweb::*;
/// use serde::{Serialize, Deserialize};
///
/// // This item is stored at #/components/schema/Item
/// #[derive(Debug, Serialize, Deserialize, Schema)]
/// #[schema(component = "Item")]
/// struct ComponentTestReq {
///     data: String,
/// }
/// ```
///
/// ## Example value
///
/// `#[schema(example = $path)]` is supported. If `$path` is a literal, it's
/// automatically converted into json value. Otherwise, you should provide an
/// expression to get example value.
///
///
/// ```rust
/// use rweb::*;
/// use serde::{Serialize, Deserialize};
///
/// // This item is stored at #/components/schema/Item
/// #[derive(Debug, Serialize, Deserialize, Schema)]
/// struct ExampleTest {
///     #[schema(example = "10")]
///     data: usize,
///     #[schema(example = "\"Example for string values must be escaped like this\"")]
///     s: String,
///     #[schema(example = "complex_example()")]
///     complex: String,
/// }
///
/// fn complex_example() -> serde_json::Value {
///     serde_json::Value::String(String::from("this is example!"))
/// }
/// ```
pub trait Entity {
    /// String uniquely identifying this type, respecting component naming pattern.
    ///
    /// If this type is a component, this is the component's name.
    ///
    /// Even if this type is not a component, this is necessary for assembling names of generic components
    /// parameterized on underlying types.
    ///
    /// # Returns
    /// Name of this type, respecting `^[a-zA-Z0-9\.\-_]+$` regex.
    ///
    /// # Panics
    /// Panic if you decide that this type must not be used for generic parameterization of components.
    fn type_name() -> Cow<'static, str>;

    /// Describe this entity, and the components it (may) requires.
    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema;
}

/// This should be implemented only for types that know how it should be
/// encoded.
pub trait ResponseEntity: Entity {
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses;
}

/// Implements entity by another entity
macro_rules! delegate_entity {
    // full paths (with `::`) not supported
    ( $T:tt $(< $( $tlt:tt $(< $( $tltt:tt ),+ >)? ),+ >)? => $D:tt $(< $( $plt:tt $(< $( $pltt:tt ),+ >)? ),+ >)? ) => {
        impl Entity for $T $(< $( $tlt $(< $( $tltt ),+ >)? ),+ >)? {
            fn type_name() -> Cow<'static, str> {
                <$D $(< $( $plt $(< $( $pltt ),+ >)? ),+ >)? as Entity>::type_name()
            }
            fn describe(d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
                <$D $(< $( $plt $(< $( $pltt ),+ >)? ),+ >)? as Entity>::describe(d)
            }
        }
    };
    // Doesn't work with `?Sized` :(
    ( < $( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+ > $T:tt $(< $( $tlt:tt $(< $( $tltt:tt ),+ >)? ),+ >)? => $D:tt $(< $( $plt:tt $(< $( $pltt:tt ),+ >)? ),+ >)? ) => {
        impl < $( $lt $( : $clt $(+ $dlt )* )? ),+ > Entity for $T $(< $( $tlt $(< $( $tltt ),+ >)? ),+ >)? {
            fn type_name() -> Cow<'static, str> {
                <$D $(< $( $plt $(< $( $pltt ),+ >)? ),+ >)? as Entity>::type_name()
            }
            fn describe(d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
                <$D $(< $( $plt $(< $( $pltt ),+ >)? ),+ >)? as Entity>::describe(d)
            }
        }
    };
}

impl Entity for () {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("unit")
    }
    /// Returns empty schema
    #[inline]
    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::Object),
            nullable: Some(true),
            ..Default::default()
        })
    }
}

macro_rules! integer {
    ($T:ty) => {
        impl Entity for $T {
            fn type_name() -> Cow<'static, str> {
                if <$T>::MIN == 0 {
                    Cow::Borrowed("uinteger")
                } else {
                    Cow::Borrowed("integer")
                }
            }
            #[inline]
            fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
                ComponentOrInlineSchema::Inline(Schema {
                    schema_type: Some(Type::Integer),
                    minimum: if <$T>::MIN == 0 {
                        Some(serde_json::json!(0))
                    } else {
                        None
                    },
                    ..Default::default()
                })
            }
        }

    };

    (
        $(
            $T:ty
        ),*
    ) => {
        $(
            integer!($T);
        )*
    };
}

integer!(u8, u16, u32, u64, u128, usize);
integer!(i8, i16, i32, i64, i128, isize);
// TODO: non-zero types

macro_rules! number {
    ($T:ty) => {
        impl Entity for $T {
            fn type_name() -> Cow<'static, str> {
                Cow::Borrowed("number")
            }
            #[inline]
            fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
                ComponentOrInlineSchema::Inline(Schema {
                    schema_type: Some(Type::Number),
                    ..Default::default()
                })
            }
        }
    };
}

number!(f32);
number!(f64);

impl Entity for bool {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("bool")
    }
    #[inline]
    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::Boolean),
            ..Default::default()
        })
    }
}

impl Entity for char {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("char")
    }
    #[inline]
    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::String),
            ..Default::default()
        })
    }
}

impl Entity for str {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("string")
    }
    #[inline]
    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::String),
            ..Default::default()
        })
    }
}

impl ResponseEntity for str {
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        String::describe_responses(comp_d)
    }
}

impl<T> Entity for Box<T>
where
    T: ?Sized + Entity,
{
    fn type_name() -> Cow<'static, str> {
        T::type_name()
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        T::describe(comp_d)
    }
}

impl<T> ResponseEntity for Box<T>
where
    T: ?Sized + ResponseEntity,
{
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        T::describe_responses(comp_d)
    }
}

impl<T> Entity for Arc<T>
where
    T: ?Sized + Entity,
{
    fn type_name() -> Cow<'static, str> {
        T::type_name()
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        T::describe(comp_d)
    }
}

impl<T> ResponseEntity for Arc<T>
where
    T: ?Sized + ResponseEntity,
{
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        T::describe_responses(comp_d)
    }
}

impl<'a, T> Entity for &'a T
where
    T: ?Sized + Entity,
{
    fn type_name() -> Cow<'static, str> {
        T::type_name()
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        T::describe(comp_d)
    }
}

impl<'a, T> ResponseEntity for &'a T
where
    T: ?Sized + ResponseEntity,
{
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        T::describe_responses(comp_d)
    }
}

impl<T: Entity> Entity for HashMap<String, T> {
    fn type_name() -> Cow<'static, str> {
        Cow::Owned(format!("Map-string_{}-", T::type_name()))
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::Object),
            additional_properties: Some(Box::new(T::describe(comp_d))),
            ..Default::default()
        })
    }
}

impl<T: Entity> Entity for [T] {
    fn type_name() -> Cow<'static, str> {
        Cow::Owned(format!("{}_List", T::type_name()))
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::Array),
            items: Some(Box::new(T::describe(comp_d))),
            ..Default::default()
        })
    }
}

impl<T: Entity, const N: usize> Entity for [T; N] {
    fn type_name() -> Cow<'static, str> {
        Cow::Owned(format!("{}_Array_{}", T::type_name(), N))
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::Array),
            items: Some(Box::new(T::describe(comp_d))),
            min_items: Some(N),
            max_items: Some(N),
            ..Default::default()
        })
    }
}

impl<T: Entity> Entity for BTreeSet<T> {
    fn type_name() -> Cow<'static, str> {
        Cow::Owned(format!("{}_Set", T::type_name()))
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::Array),
            items: Some(Box::new(T::describe(comp_d))),
            unique_items: Some(true),
            ..Default::default()
        })
    }
}

impl<T> Entity for Option<T>
where
    T: Entity,
{
    fn type_name() -> Cow<'static, str> {
        Cow::Owned(format!("{}_Opt", T::type_name()))
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        let desc = T::describe(comp_d);
        let schema = comp_d.get_unpack(&desc);
        if schema.nullable == Some(true) {
            desc
        } else {
            let mut schema = schema.clone();
            schema.nullable = Some(true);
            match desc {
                ComponentOrInlineSchema::Component { .. } => {
                    comp_d.describe_component(&Self::type_name(), |_| schema)
                }
                ComponentOrInlineSchema::Inline(_) => ComponentOrInlineSchema::Inline(schema),
            }
        }
    }
}

impl<T> ResponseEntity for Option<T>
where
    T: ResponseEntity,
{
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        T::describe_responses(comp_d)
            .into_iter()
            .map(|(k, r)| {
                (
                    k,
                    Response {
                        content: r
                            .content
                            .into_iter()
                            .map(|(k, v)| {
                                (
                                    k,
                                    MediaType {
                                        schema: v.schema.map(|desc| {
                                            let schema = comp_d.get_unpack(&desc);
                                            if schema.nullable == Some(true) {
                                                desc
                                            } else {
                                                let mut schema = schema.clone();
                                                schema.nullable = Some(true);
                                                match desc {
                                                    ComponentOrInlineSchema::Component { name } => {
                                                        comp_d.describe_component(
                                                            &format!("{}_Opt", name),
                                                            |_| schema,
                                                        )
                                                    }
                                                    ComponentOrInlineSchema::Inline(_) => {
                                                        ComponentOrInlineSchema::Inline(schema)
                                                    }
                                                }
                                            }
                                        }),
                                        ..v
                                    },
                                )
                            })
                            .collect(),
                        ..r
                    },
                )
            })
            .collect()
    }
}

delegate_entity!(String => str);

impl ResponseEntity for String {
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        let mut content = IndexMap::new();
        content.insert(
            Cow::Borrowed("text/plain"),
            MediaType {
                schema: Some(Self::describe(comp_d)),
                examples: None,
                encoding: Default::default(),
            },
        );

        let mut map = IndexMap::new();
        map.insert(
            Cow::Borrowed("200"),
            Response {
                content,
                ..Default::default()
            },
        );
        map
    }
}

impl<T, E> Entity for Result<T, E>
where
    T: Entity,
    E: Entity,
{
    fn type_name() -> Cow<'static, str> {
        Cow::Owned(format!("Result-{}_{}-", T::type_name(), E::type_name()))
    }

    fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            one_of: vec![
                ComponentOrInlineSchema::Inline(Schema {
                    schema_type: Some(Type::Object),
                    properties: indexmap::indexmap! {
                        Cow::Borrowed("Ok") => T::describe(comp_d),
                    },
                    required: vec![Cow::Borrowed("Ok")],
                    ..Default::default()
                }),
                ComponentOrInlineSchema::Inline(Schema {
                    schema_type: Some(Type::Object),
                    properties: indexmap::indexmap! {
                        Cow::Borrowed("Err") => E::describe(comp_d),
                    },
                    required: vec![Cow::Borrowed("Err")],
                    ..Default::default()
                }),
            ],
            ..Default::default()
        })
    }
}

impl<T, E> ResponseEntity for Result<T, E>
where
    T: ResponseEntity,
    E: ResponseEntity,
{
    fn describe_responses(
        comp_d: &mut ComponentDescriptor,
    ) -> IndexMap<Cow<'static, str>, Response> {
        let mut map = T::describe_responses(comp_d);
        map.extend(E::describe_responses(comp_d));
        map
    }
}

delegate_entity!(<V: Entity, S> HashSet<V, S> => BTreeSet<V>);

delegate_entity!(<T: Entity> Vec<T> => [T]);
delegate_entity!(<T: Entity> LinkedList<T> => [T]);
delegate_entity!(<T: Entity> VecDeque<T> => [T]);

delegate_entity!(<T: Entity> (T, T) => [T; 2]);
delegate_entity!(<T: Entity> (T, T, T) => [T; 3]);
delegate_entity!(<T: Entity> (T, T, T, T) => [T; 4]);
delegate_entity!(<T: Entity> (T, T, T, T, T) => [T; 5]);

delegate_entity!(<T: Entity> HashMap<Arc<String>, T> => HashMap<String, T>);
delegate_entity!(<T: Entity> HashMap<Cow<'_, String>, T> => HashMap<String, T>);

delegate_entity!(<T: Entity> BTreeMap<String, T> => HashMap<String, T>);
delegate_entity!(<T: Entity> BTreeMap<Arc<String>, T> => BTreeMap<String, T>);
delegate_entity!(<T: Entity> BTreeMap<Cow<'_, String>, T> => BTreeMap<String, T>);

delegate_entity!(<T: Entity> IndexMap<String, T> => HashMap<String, T>);
delegate_entity!(<T: Entity> IndexMap<Arc<String>, T> => IndexMap<String, T>);
delegate_entity!(<T: Entity> IndexMap<Cow<'_, String>, T> => IndexMap<String, T>);

delegate_entity!(Infallible => ());

impl ResponseEntity for Infallible {
    #[inline]
    fn describe_responses(_: &mut ComponentDescriptor) -> Responses {
        Default::default()
    }
}

delegate_entity!(<T: Entity> Json<T> => T);

impl<T> ResponseEntity for Json<T>
where
    T: Entity,
{
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        let schema = Self::describe(comp_d);
        let mut content = IndexMap::new();
        content.insert(
            Cow::Borrowed("application/json"),
            MediaType {
                schema: Some(schema),
                examples: None,
                encoding: Default::default(),
            },
        );
        let mut map = Responses::new();

        map.insert(
            Cow::Borrowed("200"),
            Response {
                content,
                ..Default::default()
            },
        );

        map
    }
}

type SerdeJsonValue = serde_json::Value;
delegate_entity!(SerdeJsonValue => ());

impl ResponseEntity for serde_json::Value {
    fn describe_responses(comp_d: &mut ComponentDescriptor) -> Responses {
        let schema = Self::describe(comp_d);
        let mut content = IndexMap::new();
        content.insert(
            Cow::Borrowed("application/json"),
            MediaType {
                schema: Some(schema),
                examples: None,
                encoding: Default::default(),
            },
        );
        let mut map = Responses::new();

        map.insert(
            Cow::Borrowed("200"),
            Response {
                content,
                ..Default::default()
            },
        );

        map
    }
}

delegate_entity!(<T: Entity> Query<T> => T);
delegate_entity!(<T: Entity> Form<T> => T);

delegate_entity!(Rejection => ());

impl ResponseEntity for Rejection {
    fn describe_responses(_: &mut ComponentDescriptor) -> Responses {
        Default::default()
    }
}

type HttpError = http::Error;
delegate_entity!(HttpError => ());

impl ResponseEntity for http::Error {
    fn describe_responses(_: &mut ComponentDescriptor) -> Responses {
        Default::default()
    }
}

type DynReply = dyn Reply;
delegate_entity!(DynReply => ());

impl ResponseEntity for dyn Reply {
    fn describe_responses(_: &mut ComponentDescriptor) -> Responses {
        Default::default()
    }
}

impl Entity for std::net::Ipv4Addr {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("ipv4")
    }

    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::String),
            format: Self::type_name(),
            ..Default::default()
        })
    }
}

impl Entity for std::net::Ipv6Addr {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("ipv6")
    }

    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::String),
            format: Self::type_name(),
            ..Default::default()
        })
    }
}

#[cfg(feature = "uuid")]
impl Entity for uuid::Uuid {
    fn type_name() -> Cow<'static, str> {
        Cow::Borrowed("uuid")
    }

    fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
        ComponentOrInlineSchema::Inline(Schema {
            schema_type: Some(Type::String),
            format: Self::type_name(),
            ..Default::default()
        })
    }
}

#[cfg(feature = "enumset")]
mod enumsetrepr {
    use super::*;
    use enumset::*;
    use serde::*;

    #[derive(Deserialize, Clone)]
    #[serde(untagged)]
    enum EnumSetRepr {
        BitFlags(u64),
        List(Vec<String>),
    }
    impl EnumSetRepr {
        fn detect<T: EnumSetType>() -> Self {
            serde_json::from_value(serde_json::to_value(EnumSet::<T>::new()).unwrap()).unwrap()
        }
    }

    // A `EnumSet<T>` can be serialized as either some number, or list of strings
    // depending on the presence of `#[enumset(serialize_as_list)]` attr.

    impl<T: EnumSetType + Entity> Entity for EnumSet<T> {
        fn type_name() -> Cow<'static, str> {
            Cow::Owned(format!("{}_EnumSet", T::type_name()))
        }

        fn describe(comp_d: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
            let t = T::describe(comp_d);
            let s = comp_d.get_unpack(&t);
            ComponentOrInlineSchema::Inline(match EnumSetRepr::detect::<T>() {
                EnumSetRepr::BitFlags(_) => Schema {
                    schema_type: Some(Type::Integer),
                    description: s.description.clone(),
                    ..Default::default()
                },
                EnumSetRepr::List(_) => Schema {
                    schema_type: Some(Type::Array),
                    items: Some(Box::new(t)),
                    ..Default::default()
                },
            })
        }
    }
}

#[cfg(feature = "chrono")]
mod chrono_impls {
    use chrono::*;

    use super::*;

    impl Entity for NaiveDateTime {
        fn type_name() -> Cow<'static, str> {
            Cow::Borrowed("date-time")
        }

        fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
            ComponentOrInlineSchema::Inline(Schema {
                schema_type: Some(Type::String),
                format: Self::type_name(),
                ..Default::default()
            })
        }
    }

    delegate_entity!(<T: TimeZone> DateTime<T> => NaiveDateTime);

    impl Entity for chrono::NaiveDate {
        fn type_name() -> Cow<'static, str> {
            Cow::Borrowed("date")
        }

        fn describe(_: &mut ComponentDescriptor) -> ComponentOrInlineSchema {
            ComponentOrInlineSchema::Inline(Schema {
                schema_type: Some(Type::String),
                format: Self::type_name(),
                ..Default::default()
            })
        }
    }

    delegate_entity!(<T: TimeZone> Date<T> => NaiveDate);
}