mangadex_api_schema_rust/
v5.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
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
pub mod api_client;
pub mod at_home_server;
pub mod auth_tokens;
pub mod author;
pub mod chapter;
pub mod check_token_response;
pub mod check_username_available;
pub mod cover;
pub mod custom_list;
pub mod error;
mod exports_types;
pub mod forum_thread;
pub mod is_following_response;
pub mod legacy_id_mapping;
pub mod login_response;
pub mod manga;
pub mod manga_aggregate;
pub mod manga_links;
pub mod manga_read_markers;
pub mod manga_reading_status;
pub mod manga_reading_statuses;
pub mod manga_relation;
pub mod oauth;
pub mod ratings;
pub mod refresh_token_response;
pub mod report;
pub mod scanlation_group;
pub mod settings_template;
pub mod statistics;
pub mod tag;
pub mod upload_required_approval;
pub mod upload_session;
pub mod upload_session_file;
pub mod user;
pub mod user_history;
pub mod user_report;
pub mod user_settings;

pub use self::exports_types::*;
use std::collections::HashMap;

use mangadex_api_types as types;
use serde::Deserialize;
use uuid::Uuid;

use types::{
    Language, MangaDexDateTime, MangaRelation, RelationshipType, ResponseType, ResultType,
};

use crate::FromResponse;
pub(crate) use crate::{ApiObject, ApiObjectNoRelationships};
use types::error::RelationshipConversionError;

// TODO: Find a way to reduce the boilerplate for this.
// `struct-variant` (https://docs.rs/struct-variant) is a potential candidate for this.
#[derive(Debug, Deserialize, Clone)]
#[allow(clippy::large_enum_variant)]
#[serde(untagged)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "specta", derive(specta::Type))]
pub enum RelatedAttributes {
    /// Manga resource.
    Manga(MangaAttributes),
    /// Chapter resource.
    Chapter(ChapterAttributes),
    /// A Cover Art for a manga.
    ///
    /// On manga resources, only one cover art resource relation is returned,
    /// marking the primary cover if there are more than one. By default, this will be the latest
    /// volume's cover art. To see all the covers for a given manga, use the cover search endpoint.
    CoverArt(CoverAttributes),
    /// Author resource.
    Author(AuthorAttributes),
    /// ScanlationGroup resource.
    ScanlationGroup(ScanlationGroupAttributes),
    /// Tag resource.
    Tag(TagAttributes),
    /// User resource.
    User(UserAttributes),
    /// CustomList resource.
    CustomList(CustomListAttributes),
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<MangaAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if value.type_ != RelationshipType::Manga {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::Manga,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::Manga(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::Manga,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::Manga,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<ChapterAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if value.type_ != RelationshipType::Chapter {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::Chapter,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::Chapter(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::Chapter,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::Chapter,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<CoverAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if value.type_ != RelationshipType::CoverArt {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::CoverArt,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::CoverArt(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::CustomList,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::CoverArt,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<AuthorAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if !(value.type_ == RelationshipType::Author || value.type_ == RelationshipType::Artist) {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::Author,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::Author(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::Author,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::Author,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<ScanlationGroupAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if value.type_ != RelationshipType::ScanlationGroup {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::ScanlationGroup,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::ScanlationGroup(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::ScanlationGroup,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::ScanlationGroup,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<TagAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if value.type_ != RelationshipType::Tag {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::Tag,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::Tag(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::Tag,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::Tag,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<UserAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if !(value.type_ == RelationshipType::User
            || value.type_ == RelationshipType::Member
            || value.type_ == RelationshipType::Leader)
        {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::User,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::User(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::User,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::User,
            ))
        }
    }
}

impl TryFrom<Relationship> for ApiObjectNoRelationships<CustomListAttributes> {
    type Error = RelationshipConversionError;

    fn try_from(value: Relationship) -> Result<Self, Self::Error> {
        if value.type_ != RelationshipType::CustomList {
            return Err(RelationshipConversionError::InvalidInputRelationshipType {
                input: RelationshipType::CustomList,
                inner: value.type_,
            });
        }
        if let Some(RelatedAttributes::CustomList(attributes)) = value.attributes {
            Ok(Self {
                id: value.id,
                type_: RelationshipType::CustomList,
                attributes,
            })
        } else {
            Err(RelationshipConversionError::AttributesNotFound(
                RelationshipType::CustomList,
            ))
        }
    }
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "specta", derive(specta::Type))]
pub struct Relationship {
    pub id: Uuid,
    #[serde(rename = "type")]
    pub type_: RelationshipType,
    /// Related Manga type.
    ///
    /// <https://api.mangadex.org/docs/static-data/#manga-related-enum>
    ///
    /// This is only present for a Manga entity and a Manga relationship.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub related: Option<MangaRelation>,
    /// Contains object attributes for the type.
    ///
    /// Present if [Reference Expansion](https://api.mangadex.org/docs/reference-expansion/) is applied.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub attributes: Option<RelatedAttributes>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "specta", derive(specta::Type))]
pub struct Results<T> {
    #[serde(default)]
    pub result: ResultType,
    pub response: ResponseType,
    pub data: Vec<T>,
    pub limit: u32,
    pub offset: u32,
    pub total: u32,
}

impl<T> FromResponse for Results<T> {
    type Response = Self;
    fn from_response(res: Self::Response) -> Self {
        res
    }
}

pub type LocalizedString = HashMap<Language, String>;

/// Originally a Deserializer helper to handle JSON array or object types.
///
/// MangaDex currently returns an empty array when the localized string field isn't present.
///
/// The Serializer was added in 0.2.0 for pratical and necessities reason
pub(crate) mod localizedstring_array_or_map {
    use std::collections::HashMap;

    use super::LocalizedString;
    use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
    #[cfg(feature = "serialize")]
    use serde::ser::{Serialize, Serializer};

    pub fn deserialize<'de, D>(deserializer: D) -> Result<LocalizedString, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct V;

        impl<'de> Visitor<'de> for V {
            type Value = LocalizedString;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("array or object")
            }

            fn visit_seq<A>(self, mut _seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                Ok(HashMap::new())
            }

            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let de = serde::de::value::MapAccessDeserializer::new(map);
                let helper = LocalizedString::deserialize(de)?;
                Ok(helper)
            }
        }

        deserializer.deserialize_any(V)
    }
    #[cfg(feature = "serialize")]
    pub fn serialize<S>(to_use: &LocalizedString, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        to_use.serialize(serializer)
    }
}

/// Originally a Deserializer helper to handle JSON array or object types.
///
/// MangaDex sometimes returns an array instead of a JSON object for the volume aggregate field.
///
/// The Serializer was added in 0.2.0 for pratical and necessities reason
pub(crate) mod volume_aggregate_array_or_map {
    use super::manga_aggregate::VolumeAggregate;
    use serde::de::{Deserializer, MapAccess, SeqAccess, Visitor};
    #[cfg(feature = "serialize")]
    use serde::ser::Serializer;
    #[cfg(feature = "serialize")]
    use serde::Serialize;
    use std::collections::BTreeMap;
    #[cfg(feature = "serialize")]
    use std::collections::HashMap;

    type VolumeAggregateCollection = Vec<VolumeAggregate>;

    const PAD_WIDTH: usize = 5;

    pub fn deserialize<'de, D>(deserializer: D) -> Result<VolumeAggregateCollection, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct V;

        impl<'de> Visitor<'de> for V {
            type Value = VolumeAggregateCollection;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("array or object")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut volumes = Vec::new();

                while let Some(volume) = seq.next_element::<VolumeAggregate>()? {
                    volumes.push(volume);
                }

                Ok(volumes)
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                // Temporary collection to sort the results because serde doesn't seem to iterate
                // through the map in the order they appear.
                let mut sorting_map = BTreeMap::new();

                while let Some((volume_number, volume)) =
                    map.next_entry::<String, VolumeAggregate>()?
                {
                    let volume_number = if volume_number.contains('.') {
                        match volume_number.parse::<f64>() {
                            Ok(_) => {
                                //
                                let (i, f) = volume_number.split_once('.').unwrap();
                                let i = i.parse::<i32>().unwrap();
                                // Pad the whole number part so that it is sorted correctly with the
                                // other keys.
                                format!("{i:0PAD_WIDTH$}.{f}")
                            }
                            Err(_) => volume_number,
                        }
                    } else {
                        match volume_number.parse::<i32>() {
                            Ok(n) => format!("{n:0PAD_WIDTH$}"),
                            Err(_) => volume_number,
                        }
                    };
                    sorting_map.insert(volume_number, volume);
                }

                Ok(sorting_map.values().cloned().collect())
            }
        }

        deserializer.deserialize_any(V)
    }
    #[cfg(feature = "serialize")]
    #[allow(dead_code)]
    pub fn serialize<S>(
        to_use: &VolumeAggregateCollection,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use super::manga_aggregate::VolumeAggregateSer;

        let mut volumes: HashMap<String, VolumeAggregateSer> = HashMap::new();
        for volume in to_use {
            volumes.insert(volume.volume.clone(), Into::into(volume.clone()));
        }
        volumes.serialize(serializer)
    }
}

/// Originally a Deserializer helper to handle JSON array or object types.
///
/// MangaDex sometimes returns an array instead of a JSON object for the chapter aggregate field.
///
/// The Serializer was added in 0.2.0 for pratical and necessities reason
pub(crate) mod chapter_aggregate_array_or_map {
    use serde::de::{Deserializer, MapAccess, SeqAccess, Visitor};
    #[cfg(feature = "serialize")]
    use serde::ser::Serializer;
    #[cfg(feature = "serialize")]
    use serde::Serialize;
    use std::collections::BTreeMap;

    use super::manga_aggregate::ChapterAggregate;

    const PAD_WIDTH: usize = 5;

    type ChapterAggregateCollection = Vec<ChapterAggregate>;

    pub fn deserialize<'de, D>(deserializer: D) -> Result<ChapterAggregateCollection, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct V;

        impl<'de> Visitor<'de> for V {
            type Value = ChapterAggregateCollection;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("array or object")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut chapters = Vec::new();

                while let Some(chapter) = seq.next_element::<ChapterAggregate>()? {
                    chapters.push(chapter);
                }

                Ok(chapters)
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                // Temporary collection to sort the results because serde doesn't seem to iterate
                // through the map in the order they appear.
                let mut sorting_map = BTreeMap::new();

                while let Some((chapter_number, chapter)) =
                    map.next_entry::<String, ChapterAggregate>()?
                {
                    let chapter_number = if chapter_number.contains('.') {
                        match chapter_number.parse::<f64>() {
                            Ok(_) => {
                                //
                                let (i, f) = chapter_number.split_once('.').unwrap();
                                let i = i.parse::<i32>().unwrap();
                                // Pad the whole number part so that it is sorted correctly with the
                                // other keys.
                                format!("{i:0PAD_WIDTH$}.{f}")
                            }
                            Err(_) => chapter_number,
                        }
                    } else {
                        match chapter_number.parse::<i32>() {
                            Ok(n) => format!("{n:0PAD_WIDTH$}"),
                            Err(_) => chapter_number,
                        }
                    };
                    sorting_map.insert(chapter_number, chapter);
                }

                Ok(sorting_map.values().cloned().collect())
            }
        }

        deserializer.deserialize_any(V)
    }
    #[cfg(feature = "serialize")]
    pub fn serialize<S>(
        to_use: &ChapterAggregateCollection,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use std::collections::HashMap;

        let mut chapters: HashMap<String, ChapterAggregate> = HashMap::new();
        for chapter in to_use {
            chapters.insert(chapter.chapter.clone(), chapter.clone());
        }
        chapters.serialize(serializer)
    }
}

/// Originally a Deserializer helper to handle JSON array or object types.
///
/// MangaDex sometimes returns an array instead of a JSON object for the `links` field for `MangaAttributes`.
///
/// The Serializer was added in 0.2.0 for pratical and necessities reason
pub(crate) mod manga_links_array_or_struct {
    use crate::v5::MangaLinks;
    use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
    #[cfg(feature = "serialize")]
    use serde::ser::Serializer;
    #[cfg(feature = "serialize")]
    use serde::Serialize;

    /// Deserialize a `MangaLinks` from a JSON value or none.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<MangaLinks>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OptionMangaLinksVisitor;

        impl<'de> Visitor<'de> for OptionMangaLinksVisitor {
            type Value = Option<MangaLinks>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("some or none")
            }

            /// Deserialize a `MangaLinks` from none.
            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(None)
            }

            /// Deserialize a `MangaLinks` from a JSON value.
            fn visit_some<D>(self, d: D) -> Result<Self::Value, D::Error>
            where
                D: Deserializer<'de>,
            {
                let manga_links = d.deserialize_any(MangaLinksVisitor)?;

                let manga_links = if manga_links.has_no_links() {
                    None
                } else {
                    Some(manga_links)
                };

                Ok(manga_links)
            }

            /// Deserialize a `MangaLinks` from none (`null`).
            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(None)
            }
        }

        struct MangaLinksVisitor;

        impl<'de> Visitor<'de> for MangaLinksVisitor {
            type Value = MangaLinks;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("array or map")
            }

            /// Deserialize a `MangaLinks` from a sequence (array).
            fn visit_seq<A>(self, mut _seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                Ok(Self::Value::default())
            }

            /// Deserialize a `MangaLinks` from a map (JSON object).
            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                // `MapAccessDeserializer` is a wrapper that turns a `MapAccess`
                // into a `Deserializer`, allowing it to be used as the input to T's
                // `Deserialize` implementation. T then deserializes itself using
                // the entries from the map visitor.
                Deserialize::deserialize(serde::de::value::MapAccessDeserializer::new(map))
            }
        }

        deserializer.deserialize_option(OptionMangaLinksVisitor)
    }
    #[cfg(feature = "serialize")]
    pub fn serialize<S>(to_use: &Option<MangaLinks>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match to_use {
            None => serializer.serialize_none(),
            Some(data) => data.serialize(serializer),
        }
    }
}

/// Originally a Deserializer for an array of languages, discarding elements that are `null`.
///
/// The Serializer was added in 0.2.0 for pratical and necessities reason
pub(crate) mod language_array_or_skip_null {
    use mangadex_api_types::Language;
    use serde::de::{Deserializer, SeqAccess, Visitor};
    #[cfg(feature = "serialize")]
    use serde::ser::Serializer;
    #[cfg(feature = "serialize")]
    use serde::Serialize;
    /// Deserialize a `Vec<Language>` from an array of JSON values.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Language>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct V;

        impl<'de> Visitor<'de> for V {
            type Value = Vec<Language>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a sequence of languages")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut languages = Vec::new();

                // Skip over invalid or `null` languages.
                while let Some(language) = seq.next_element::<Option<Language>>()? {
                    // `language` will be `None` if an element value is `null` from JSON.
                    if let Some(language) = language {
                        languages.push(language);
                    }
                }

                Ok(languages)
            }
        }

        deserializer.deserialize_seq(V)
    }
    #[cfg(feature = "serialize")]
    pub fn serialize<S>(to_use: &Vec<Language>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        to_use.serialize(serializer)
    }
}

pub fn mangadex_datetime_serialize<S>(
    datetime: &MangaDexDateTime,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(datetime.to_string().as_str())
}

pub fn mangadex_datetime_serialize_option<S>(
    datetime: &Option<MangaDexDateTime>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    if let Some(d) = datetime {
        serializer.serialize_str(d.to_string().as_str())
    } else {
        serializer.serialize_none()
    }
}

#[cfg(test)]
mod test {
    use serde::{Deserialize, Serialize};

    use mangadex_api_types::MangaDexDateTime;

    #[derive(Serialize, Deserialize, Default)]
    struct TestStruct {
        #[serde(serialize_with = "crate::v5::mangadex_datetime_serialize")]
        date: MangaDexDateTime,
    }

    #[tokio::test]
    async fn mangadex_datetime_serialize_test() {
        let test: TestStruct = Default::default();
        println!("{}", serde_json::to_string_pretty(&test).unwrap());
    }
}