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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
use crate::langs::Language;
use crate::{genres::*, langs::*};
#[cfg(feature = "chrono")]
use chrono::{serde::ts_seconds, DateTime, Utc};
use itoa;
use serde::de::{MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{borrow::Cow, fmt, num::NonZeroU32};

/// A (de)serializable group information site.
#[derive(
	Debug, Deserialize, Serialize, Clone, PartialEq, PartialOrd, Eq, Ord,
)]
pub struct Group<'a> {
	pub id: u32,
	pub name: Cow<'a, str>,
	pub website: Option<Cow<'a, str>>,
}
impl<'a> From<(String, (&'a str, Option<&'a str>))> for Group<'a> {
	fn from(g: (String, (&'a str, Option<&'a str>))) -> Self {
		let website = (g.1).1.map(|s| Cow::Owned(s.to_owned()));
		Group {
			id: g.0.parse().unwrap_or_default(),
			name: Cow::Owned((g.1).0.to_owned()),
			website,
		}
	}
}
/// A wrapper around group IDs
#[derive(
	Serialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash,
)]
pub struct GroupID(u32);
/// A list of groups
///
/// Has significant space wastage if using ephemerally. Reuse wherever possible.
#[derive(Default, PartialEq)]
pub struct Groups(Vec<Option<(String, Option<String>)>>);
impl<'a> Extend<Group<'a>> for Groups {
	fn extend<T: IntoIterator<Item = Group<'a>>>(&mut self, iter: T) {
		for grp in iter {
			self.add_group(grp);
		}
	}
}
impl<'a> Extend<(String, (&'a str, Option<&'a str>))> for Groups {
	fn extend<T: IntoIterator<Item = (String, (&'a str, Option<&'a str>))>>(
		&mut self,
		iter: T,
	) {
		self.extend(iter.into_iter().map(Group::from));
	}
}
/// Used with serde to (de)serialize a groups sequence/array.
pub mod groups_seq {
	use super::{Groups, GroupsSeqDeserializer};
	use serde::{Deserializer, Serializer};
	/// Deserializes a group sequence
	pub fn deserialize<'de, D: Deserializer<'de>>(
		d: D,
	) -> Result<Groups, D::Error> {
		let seq = d.deserialize_seq(GroupsSeqDeserializer)?;
		let mut groups = Groups::default();
		groups.extend(seq);
		Ok(groups)
	}
	/// Serializes a group sequence
	pub fn serialize<S: Serializer>(
		groups: &Groups,
		s: S,
	) -> Result<S::Ok, S::Error> {
		s.collect_seq(groups.compact_seq())
	}
}

/// Used with serde to (de)serialize a groups map/object.
pub mod groups_map {
	use super::{Groups, GroupsMapDeserializer};
	use serde::{Deserializer, Serializer};
	/// Deserializes a group map
	pub fn deserialize<'de, D: Deserializer<'de>>(
		d: D,
	) -> Result<Groups, D::Error> {
		let map = d.deserialize_map(GroupsMapDeserializer)?;
		let mut groups = Groups::default();
		groups.extend(map);
		Ok(groups)
	}
	/// Serializes a group map
	pub fn serialize<S: Serializer>(
		groups: &Groups,
		s: S,
	) -> Result<S::Ok, S::Error> {
		s.collect_map(groups.compact_map())
	}
}
/// Marker struct
struct GroupsSeqDeserializer;
impl<'de> Visitor<'de> for GroupsSeqDeserializer {
	/// The output value.
	type Value = GroupsSeq<'de>;
	/// Explains that we're getting a sequence of groups.
	fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		fmt.write_str(
			"sequence of groups (eg [{id: 1, name: \"Unknown\", website: null}])",
		)
	}
	/// The consumer for a sequence of groups.
	fn visit_seq<A: SeqAccess<'de>>(
		self,
		mut seq: A,
	) -> Result<Self::Value, A::Error> {
		let mut slf = GroupsSeq::default();
		while let Some(value) = seq.next_element()? {
			slf.0.push(value);
		}
		Ok(slf)
	}
}
/// Marker struct
struct GroupsMapDeserializer;
impl<'de> Visitor<'de> for GroupsMapDeserializer {
	/// The output value.
	type Value = GroupsMap<'de>;
	/// Explains that we're getting a known sequence of id-groupinfo pairs.
	fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		fmt.write_str(
			"id-keyed map of group name-website pairs (eg {1: [\"Unknown\", null]})",
		)
	}
	/// The consumer for a map of groups.
	fn visit_map<A: MapAccess<'de>>(
		self,
		mut map: A,
	) -> Result<Self::Value, A::Error> {
		let mut map_groups = GroupsMap::default();
		while let Some(entry) = map.next_entry()? {
			map_groups.0.push(entry);
		}
		Ok(map_groups)
	}
}
impl fmt::Debug for Groups {
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		fmt.debug_set().entries(self.compact_seq()).finish()
	}
}
impl From<u32> for GroupID {
	fn from(group: u32) -> Self {
		GroupID(group)
	}
}
impl<'a> Group<'a> {
	/// Sets a groups website
	pub fn group_website(mut self, website: String) -> Self {
		self.website = Some(website.into());
		self
	}
	/// Adds a group to a given list of groups
	pub fn add_to_groups(self, groups: &mut Groups) {
		groups.add_group(self);
	}
}
impl GroupID {
	/// Attaches a group name to a group ID
	pub fn group_name<'a>(self, name: String) -> Group<'a> {
		Group {
			id: self.0,
			name: name.into(),
			website: None,
		}
	}
	/// Attaches a group name and website to a group ID
	pub fn group_name_and_website<'a>(
		self,
		name: String,
		website: String,
	) -> Group<'a> {
		Group {
			id: self.0,
			name: name.into(),
			website: Some(website.into()),
		}
	}
}
impl From<&GroupID> for usize {
	fn from(v: &GroupID) -> usize {
		v.0 as usize
	}
}

/// (de)serializable unordered set of groups
#[derive(Debug, Default, Serialize, Deserialize)]
#[repr(transparent)]
pub struct GroupsSeq<'a>(Vec<Group<'a>>);
impl<'a> GroupsSeq<'a> {
	pub fn len(&self) -> u32 {
		self.0.len() as u32
	}
	pub fn is_empty(&self) -> bool {
		self.0.is_empty()
	}
}
impl<'a> From<GroupsSeq<'a>> for Groups {
	fn from(csg: GroupsSeq<'a>) -> Self {
		let mut grps = Groups::default();
		grps.extend(csg);
		grps
	}
}
impl<'a> IntoIterator for GroupsSeq<'a> {
	type Item = Group<'a>;
	type IntoIter = std::vec::IntoIter<Self::Item>;
	fn into_iter(self) -> Self::IntoIter {
		self.0.into_iter()
	}
}

/// (de)serializable unordered map of groups
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct GroupsMap<'a>(Vec<(String, (&'a str, Option<&'a str>))>);
impl<'a> GroupsMap<'a> {
	pub fn len(&self) -> u32 {
		self.0.len() as u32
	}
	pub fn is_empty(&self) -> bool {
		self.0.is_empty()
	}
}
impl<'a> From<GroupsMap<'a>> for Groups {
	fn from(cmg: GroupsMap<'a>) -> Self {
		let mut grps = Groups::default();
		grps.extend(cmg);
		grps
	}
}
impl<'a> Serialize for GroupsMap<'a> {
	/// Serializes as a map/object
	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
		serializer.collect_map(self.0.iter().map(|(s, n)| (s.as_str(), n)))
	}
}
impl<'de> Deserialize<'de> for GroupsMap<'de> {
	/// Deserializes from a map/object
	fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
		d.deserialize_map(GroupsMapDeserializer)
	}
}
impl<'a> IntoIterator for GroupsMap<'a> {
	type Item = (String, (&'a str, Option<&'a str>));
	type IntoIter = std::vec::IntoIter<Self::Item>;
	fn into_iter(self) -> Self::IntoIter {
		self.0.into_iter()
	}
}
impl Groups {
	/// Produces a new list of groups
	pub fn new() -> Self {
		Groups(vec![None; 10_000])
	}
	// Produces a compacted sequence of groups
	pub fn compact_seq(&self) -> GroupsSeq {
		GroupsSeq(
			self
				.0
				.iter()
				.zip(0..)
				.skip(1)
				.filter_map(|(ok, id)| {
					ok.as_ref().map(|g| Group {
						id,
						name: Cow::Borrowed(&g.0),
						website: g.1.as_ref().map(|s| s.into()),
					})
				})
				.collect(),
		)
	}
	/// Produces a compacted map of groups
	pub fn compact_map(&self) -> GroupsMap {
		GroupsMap(
			self
				.0
				.iter()
				.zip(0..)
				.skip(1)
				.filter_map(|(ok, id)| {
					ok.as_ref().map(|g| {
						(
							id.to_string(),
							(g.0.as_str(), g.1.as_ref().map(|w| w.as_str())),
						)
					})
				})
				.collect(),
		)
	}
	/// Filters a list of chapters to the list of group ids
	fn filter_to_groups(&self, chs: &[Chapter]) -> Vec<bool> {
		let mut ids: Vec<bool> = vec![true];
		let mut ext = |n| {
			if ids.len() < n {
				let m = (ids.len()..=n).map(|_| false);
				ids.extend(m);
			}
			ids[n] = true;
		};
		for Chapter { groups, .. } in chs {
			let [a, b, c] = groups;
			ext(a.into());
			ext(b.into());
			ext(c.into());
		}
		ids
	}
	/// Produces a compact sequence of groups given a list of chapters
	pub fn compact_seq_with_ch(&self, chs: &[Chapter]) -> GroupsSeq {
		let ids = self.filter_to_groups(chs);
		GroupsSeq(
			ids
				.into_iter()
				.zip(0..)
				.skip(1)
				.filter_map(|(b, id)| {
					if b && id < self.len() {
						let grp = unsafe { self.0.get_unchecked(id as usize) }.as_ref();
						grp.map(|g| Group {
							id,
							name: Cow::Borrowed(&g.0),
							website: g.1.as_ref().map(|s| s.into()),
						})
					} else {
						None
					}
				})
				.collect(),
		)
	}
	/// Produces a compact map of groups given a list of chapters
	pub fn compact_map_with_ch(&self, chs: &[Chapter]) -> GroupsMap {
		let ids = self.filter_to_groups(chs);
		GroupsMap(
			ids
				.into_iter()
				.zip(0..)
				.skip(1)
				.filter_map(|(b, id)| {
					if b && id < self.len() {
						let g = unsafe { self.0.get_unchecked(id as usize) }.as_ref()?;
						Some((
							id.to_string(),
							(g.0.as_str(), g.1.as_ref().map(|w| w.as_str())),
						))
					} else {
						None
					}
				})
				.collect(),
		)
	}
	pub fn len(&self) -> u32 {
		self.0.len() as u32
	}
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}
	pub fn group_id(u: u32) -> GroupID {
		GroupID(u)
	}
	fn add_group(&mut self, mut grp: Group) {
		if self.len() < grp.id {
			self.0.extend((self.len()..=grp.id).map(|_| None));
		}
		let entry = unsafe { self.0.get_unchecked_mut(grp.id as usize) };
		if let Some(mut ent) = entry.as_mut() {
			if ent.1.is_none() {
				ent.1 = grp.website.take().map(|s| s.into());
			}
		} else {
			let Group { name, website, .. } = grp;
			*entry = Some((name.into(), website.map(|s| s.into())));
		}
	}
	fn populate_groups_from(&mut self, ch: &crate::manga_api::Chapter) {
		if !self.has(ch.group_id) {
			GroupID(ch.group_id)
				.group_name(ch.group_name.chars().collect())
				.add_to_groups(self);
		}
		if let Some(group_name_2) = &ch.group_name_2 {
			if !self.has(ch.group_id_2) {
				GroupID(ch.group_id_2)
					.group_name(group_name_2.chars().collect())
					.add_to_groups(self);
			}
		}
		if let Some(group_name_3) = &ch.group_name_3 {
			if !self.has(ch.group_id_3) {
				GroupID(ch.group_id_3)
					.group_name(group_name_3.chars().collect())
					.add_to_groups(self);
			}
		}
	}
	pub fn has(&self, gid: u32) -> bool {
		if self.len() < gid {
			false
		} else {
			unsafe { self.0.get_unchecked(gid as usize) }.is_some()
		}
	}
	pub fn populate_website_from(&mut self, ch: &crate::chapter_api::Delayed) {
		let id = ch.groups.group_id;
		if self.len() < id {
			self.0.extend((self.len()..=id).map(|_| None));
		}
		let group = unsafe { self.0.get_unchecked_mut(id as usize) };
		if let Some(grp) = group.as_mut() {
			let _ = grp
				.1
				.get_or_insert_with(|| ch.group_website.chars().collect());
		}
	}
	pub fn get(&self, id: u32) -> Option<Group> {
		if self.len() < id {
			None
		} else {
			unsafe { self.0.get_unchecked(id as usize) }
				.as_ref()
				.map(|g| Group {
					id,
					name: Cow::Borrowed(&g.0),
					website: g.1.as_ref().map(|s| s.into()),
				})
		}
	}
}

/// Manga data from a top level
#[derive(Default, Serialize, Clone, Debug)]
pub struct MangaData {
	pub title: String,
	pub status: crate::manga_api::Status,
	pub genres: GenreSet,
	pub desc: String,
	pub authors: Vec<String>,
	pub artists: Vec<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	pub last_chapter: Option<ChapterNumber>,
	pub lang: Language,
	pub hentai: bool,
	pub links: Links,
	pub chapters: Vec<Chapter>,
	#[serde(skip)]
	ch_langs: Vec<(u32, Language)>,
}

impl MangaData {
	pub fn from_manga(
		crate::manga_api::Data {
			manga,
			chapters: ch,
		}: crate::manga_api::Data,
		grps: &mut Groups,
	) -> Self {
		let comma_split = |v: &str| {
			let s = v.trim();
			if s.is_empty() {
				None
			} else {
				Some(s.to_owned())
			}
		};
		let (chapters, ch_langs) = if ch.is_empty() {
			(vec![], vec![])
		} else {
			let mut chs: Vec<(ChapterNumber, Chapter)> = Vec::with_capacity(ch.len());
			let ch_sortable = ch.into_iter().map(|(id, ch)| {
				let chn = ch.chapter.parse().unwrap_or_default();
				grps.populate_groups_from(&ch);
				(chn, (id, ch).into())
			});
			chs.extend(ch_sortable);
			chs.sort_unstable_by(chapter_sort);
			chs.into_iter().fold(
				(vec![], vec![]),
				|(mut ch_l, mut ch_n), (chn, ch)| {
					ch_n.push((chn.as_u32(), ch.lang));
					ch_l.push(ch);
					(ch_l, ch_n)
				},
			)
		};
		let last_chapter = if let Ok(ch) = manga.last_chapter.parse() {
			if ch == ChapterNumber::Empty || ch == ChapterNumber::Simple(0) {
				None
			} else {
				Some(ch)
			}
		} else {
			None
		};
		MangaData {
			title: manga.title,
			status: manga.status,
			desc: manga.description,
			genres: manga.genres.into(),
			authors: manga.author.split(',').filter_map(comma_split).collect(),
			artists: manga.artist.split(',').filter_map(comma_split).collect(),
			lang: manga.lang,
			hentai: manga.hentai.into(),
			links: manga.links.map_or_else(Default::default, |ln| ln.into()),
			last_chapter,
			chapters,
			ch_langs,
		}
	}
	pub fn filter_chap_by_langs<L: Into<LanguageSet>>(
		&self,
		l: L,
	) -> Vec<&Chapter> {
		let langs = l.into();
		self
			.chapters
			.iter()
			.filter(|ch| langs.has(ch.lang))
			.collect()
	}
	//pub fn filter_chap_by_groups<G: Into<Vec<u32>>>(&self, g: G) -> Vec<&Chapter> {
	//	let groups = g.into();
	//	self.chapters.iter().zip(&self.ch_langs).fold(
	//		(None, vec![]),
	//		|(mut prev, mut curr)| {

	//		}
	//	).1
	//}
	// Efficient finding of holes
	// pub fn holes<L: Into<LanguageSet>>(&self, l: L) -> Vec<Hole> {
	// 	let langs = l.into();
	// 	self.ch_langs
	// 	.iter()
	// 	.filter(|v: &&(ChapterNumber, Language)| langs.has(v.1))
	// 	.fold((vec![], 0, 0), |(mut hls, prev, current), (chn, _)| {
	// 		let ch = chn.as_u32();
	// 		match ch.cmp(&current) {
	// 			Less => {
	// 				panic!("{}; {}", current, ch);
	// 			},
	// 			Equal => if current == 0 && ch == 0 {
	// 				(hls, 0, 0)
	// 			} else {
	// 				(hls, prev, ch)
	// 			},
	// 			Greater => {
	// 				hls.push(prev..ch);
	// 				println!("{}, {}", current, ch);
	// 				if ch - current > 1 {
	// 					hls.push(prev..ch);
	// 				}
	// 				(hls, ch, ch)
	// 			}
	// 		}
	// 	})
	// 	.0
	// }
}
/// Hole loader
pub type Hole = std::ops::Range<u32>;

#[derive(Default, Serialize, Clone, Debug, PartialEq)]
pub struct Links {
	#[serde(skip_serializing_if = "Option::is_none")]
	/// Bookwalker (prefix: https://bookwalker.jp/)
	pub book_walker: Option<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// MangaUpdates ID (prefix: https://www.mangaupdates.com/series.html?id=)
	pub manga_updates: Option<NonZeroU32>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// NovelUpdates slug (prefix: https://www.novelupdates.com/series/, postfix: /)
	pub novel_updates: Option<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// Amazon URL
	pub amazon: Option<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// CDJapan URL
	pub cd_japan: Option<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// EbookJapan URL
	pub ebook_japan: Option<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// MyAnimeList ID (prefix: https://myanimelist.net/manga/)
	pub my_anime_list: Option<NonZeroU32>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// Raw URL
	pub raw: Option<String>,
	#[serde(skip_serializing_if = "Option::is_none")]
	/// Official English URL
	pub english_translation: Option<String>,
}

impl From<crate::manga_api::Links> for Links {
	fn from(ln: crate::manga_api::Links) -> Self {
		let manga_updates: u32 = if let Some(n) = ln.manga_updates {
			n.parse().unwrap_or_default()
		} else {
			0
		};
		let my_anime_list: u32 = if let Some(n) = ln.my_anime_list {
			n.parse().unwrap_or_default()
		} else {
			0
		};
		Links {
			manga_updates: NonZeroU32::new(manga_updates),
			my_anime_list: NonZeroU32::new(my_anime_list),
			book_walker: ln.book_walker,
			novel_updates: ln.novel_updates,
			amazon: ln.amazon,
			cd_japan: ln.cd_japan,
			ebook_japan: ln.ebook_japan,
			raw: ln.raw,
			english_translation: ln.english_translation,
		}
	}
}

#[derive(Debug, PartialEq, Clone)]
pub enum ChapterNumber {
	/// literally nothing
	Empty,
	/// up to 8 chars in the chapter field
	Simple(u32),
	/// 6.1 and 1.6 are wholly supported
	Dual(u32, u32),
	/// a range
	Range(u32, u32),
	/// grr
	FuckYou(u32, String),
	/// when you type something like "two" because you're such a fucking arsehole
	SuperFuckYou(String),
}
impl ChapterNumber {
	pub fn as_u32(&self) -> u32 {
		use ChapterNumber::*;
		match self {
			Simple(n) => *n,
			Dual(n, _) => *n,
			Range(n, _) => *n,
			FuckYou(n, _) => *n,
			_ => 0,
		}
	}
}
impl Serialize for ChapterNumber {
	fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
		use ChapterNumber::*;
		match self {
			Empty => s.serialize_none(),
			Simple(n) => s.serialize_u32(*n),
			Dual(a, b) => {
				let mut buf = [0u8; 8];
				let a_off = itoa::write(&mut buf[..], *a).unwrap();
				buf[a_off] = b'.';
				let b_off = itoa::write(&mut buf[(a_off + 1)..], *b).unwrap();
				let len = a_off + b_off + 1;
				let st = unsafe { std::str::from_utf8_unchecked(&buf[..len]) };
				let flt = st.parse().unwrap();
				s.serialize_f64(flt)
			}
			Range(a, b) => {
				let mut buf = [0u8; 8];
				let a_off = itoa::write(&mut buf[..], *a).unwrap();
				buf[a_off] = b'-';
				let b_off = itoa::write(&mut buf[(a_off + 1)..], *b).unwrap();
				let len = a_off + b_off + 1;
				let st = unsafe { std::str::from_utf8_unchecked(&buf[..len]) };
				s.serialize_str(st)
			}
			FuckYou(n, st) => {
				let mut buf = Vec::with_capacity(8);
				let l = itoa::write(&mut buf, *n).unwrap();
				buf[l] = b'.';
				buf.extend_from_slice(&st.as_bytes());
				s.serialize_str(unsafe { std::str::from_utf8_unchecked(&buf) })
			}
			SuperFuckYou(st) => s.serialize_str(&st),
		}
	}
}
impl Default for ChapterNumber {
	fn default() -> Self {
		ChapterNumber::Empty
	}
}
use std::cmp::Ordering::{self, Equal, Greater, Less};
impl std::str::FromStr for ChapterNumber {
	type Err = std::convert::Infallible;
	/// simplified alg to remove chapter excess data.
	fn from_str(s: &str) -> Result<ChapterNumber, Self::Err> {
		use ChapterNumber::*;
		let s = s.trim();
		if s.is_empty() {
			return Ok(Empty);
		}
		let mmkay = |v: &str| {
			let v = v.trim();
			if v.is_empty() {
				None
			} else {
				Some(v.to_owned())
			}
		};
		let mut alt = s.splitn(2, '.');
		let a = alt.next().and_then(mmkay);
		let b = alt.next().and_then(mmkay);

		if let (Some(a_n), None) = (a, b) {
			if let Ok(mhm) = a_n.parse() {
				return Ok(Simple(mhm));
			}
		}
		let mut alt = s.splitn(2, '.');
		let a = alt.next().and_then(mmkay);
		let b = alt.next().and_then(mmkay);

		if let (Some(a_n), Some(b_n)) = (a, b) {
			if let Ok(mhm) = a_n.parse() {
				return if let Ok(owo) = b_n.parse() {
					Ok(Dual(mhm, owo))
				} else {
					Ok(FuckYou(mhm, b_n.to_owned()))
				};
			}
		}
		let mut alt = s.splitn(2, '-');
		let a = alt.next().and_then(mmkay);
		let b = alt
			.next()
			.and_then(mmkay)
			.map(|v: String| v.trim_start_matches('-').to_owned());

		if let (Some(a_r), Some(b_r)) = (a, b) {
			if let Ok(mhm) = a_r.parse() {
				return if let Ok(owo) = b_r.parse() {
					Ok(Range(mhm, owo))
				} else {
					Ok(FuckYou(mhm, b_r.to_owned()))
				};
			}
		}

		Ok(SuperFuckYou(s.to_owned()))
	}
}
impl PartialOrd for ChapterNumber {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		use ChapterNumber::*;
		match (self, other) {
			(Empty, Empty) => Some(Equal),
			(Empty, _) => Some(Less),
			(_, Empty) => Some(Greater),
			(Simple(a), Simple(b)) => a.partial_cmp(b),
			(Dual(a, b), Dual(c, d)) => a
				.partial_cmp(c)
				.map(|k| if k == Equal { b.cmp(d) } else { k }),
			(Range(a, b), Range(c, d)) => a
				.partial_cmp(c)
				.map(|k| if k == Equal { b.cmp(d) } else { k }),
			(FuckYou(a, b), FuckYou(c, d)) => a
				.partial_cmp(c)
				.map(|k| if k == Equal { b.cmp(d) } else { k }),
			(Simple(a), Dual(b, c)) => Some(match a.cmp(b) {
				Equal => c.cmp(&0),
				d => d,
			}),
			(Simple(a), Range(b, c)) => Some(match a.cmp(b) {
				Equal => c.cmp(a),
				d => d,
			}),
			(Range(b, c), Simple(a)) => Some(match b.cmp(a) {
				Equal => a.cmp(c),
				d => d,
			}),
			(Dual(a, b), Simple(c)) => Some(match a.cmp(c) {
				Equal => 0.cmp(b),
				d => d,
			}),
			(Dual(a, b), FuckYou(c, _)) => a
				.partial_cmp(c)
				.map(|k| if k == Equal { b.cmp(&0) } else { k }),
			(Dual(a, _), Range(b, c)) => Some(match a.cmp(b) {
				Equal => c.cmp(a),
				d => d,
			}),
			(Range(b, c), Dual(a, _)) => Some(match b.cmp(a) {
				Equal => a.cmp(c),
				d => d,
			}),
			(FuckYou(a, _), Dual(b, c)) => a
				.partial_cmp(b)
				.map(|k| if k == Equal { 0.cmp(c) } else { k }),
			(FuckYou(a, _), Range(b, c)) => a
				.partial_cmp(b)
				.map(|k| if k == Equal { 0.cmp(c) } else { k }),
			(Range(b, c), FuckYou(a, _)) => b
				.partial_cmp(a)
				.map(|k| if k == Equal { c.cmp(&0) } else { k }),
			(FuckYou(a, _), Simple(b)) => a.partial_cmp(b),
			(Simple(a), FuckYou(b, _)) => a.partial_cmp(b),
			(SuperFuckYou(a), SuperFuckYou(b)) => a.partial_cmp(b),
			(SuperFuckYou(_), _) => Some(Less),
			(_, SuperFuckYou(_)) => Some(Greater),
		}
	}
}

#[derive(Serialize, Clone, Debug)]
pub struct Chapter {
	pub vol: Option<u32>,
	pub chapter: Option<String>,
	pub title: Option<String>,
	pub groups: [GroupID; 3],
	pub id: u32,
	pub lang: Language,
	#[cfg(feature = "chrono")]
	#[serde(with = "ts_seconds", default = "Utc::now")]
	pub timestamp: DateTime<Utc>,
	#[cfg(not(feature = "chrono"))]
	pub timestamp: u64,
}
/// Absolute sorting of chapters through direct comparison; aiming to match the sorting of mangadex's title sort.
fn chapter_sort(
	(a_chn, a): &(ChapterNumber, Chapter),
	(b_chn, b): &(ChapterNumber, Chapter),
) -> Ordering {
	macro_rules! cmp {
		($a:expr, $b:expr) => {
			let cmp = $a.cmp(&$b);
			if cmp != Equal {
				return cmp;
				}
		};
	}
	match (a.vol, b.vol) {
		(Some(a_v), Some(b_v)) => {
			cmp!(a_v, b_v);
		}
		(Some(_), None) => return Less,
		(None, Some(_)) => return Greater,
		_ => {}
	}
	match a_chn.partial_cmp(&b_chn) {
		None | Some(Equal) => {}
		Some(c) => {
			return c;
		}
	}
	// md doesn't consider titles at all
	// cmp!(a.title, b.title);
	cmp!(a.groups, b.groups);
	cmp!(a.lang, b.lang);
	a.id.cmp(&b.id)
}

fn from_gids(a: u32, b: u32, c: u32) -> [GroupID; 3] {
	[GroupID(a), GroupID(b), GroupID(c)]
}
impl From<(String, crate::manga_api::Chapter)> for Chapter {
	fn from((id, ch): (String, crate::manga_api::Chapter)) -> Self {
		Chapter {
			vol: ch.volume.trim().parse().ok(),
			chapter: if ch.chapter.is_empty() {
				None
			} else {
				Some(ch.chapter)
			},
			lang: ch.lang,
			title: if ch.title.is_empty() {
				None
			} else {
				Some(ch.title)
			},
			groups: from_gids(ch.group_id, ch.group_id_2, ch.group_id_3),
			id: id.parse().unwrap_or_default(),
			timestamp: ch.timestamp,
		}
	}
}

#[cfg(test)]
pub mod test {
	use super::*;
	use crate::manga_api::Manga;
	use crate::test_data::*;
	use serde_json::{from_str, to_string_pretty};
	use std::mem::size_of as sizeof;
	#[test]
	fn size_of_group() {
		println!(
			"\
			 Group: {}; \
			 Option<Group>: {}; \
			 String: {}; \
			 Option<String>: {}; \
			 Option<Box<Group>>: {}; \
			 &Group: {}; \
			 Groups: {}; \
			 (usize, String, String): {}; \
			 MangaData: {}\
			 ",
			sizeof::<Group>(),              // 48 on 64 bit; 24 on 32 bit
			sizeof::<Option<Group>>(),      // as above
			sizeof::<String>(),             // 24 on 64 bit; 12 on 32 bit
			sizeof::<Option<String>>(),     // same as above
			sizeof::<Option<Box<Group>>>(), // 8 on 64 bit, 4 on 32 bit
			sizeof::<&Group>(),             // same as above
			sizeof::<Groups>(),             // 24 on 64 bit; 12 on 32 bit
			sizeof::<(usize, String, String)>(),
			sizeof::<MangaData>()
		);
	}
	/// consumes manga and processes it as a full set of information
	fn reformats_manga(groups: &mut Groups) -> R {
		for mng in &TEST_MANGA_ALL_TESTS {
			if let Some(mn) = from_str::<Manga>(mng)?.ok() {
				let manga = MangaData::from_manga(mn, groups);
				eprintln!("{:?}", manga);
				eprintln!("{}", to_string_pretty(&manga)?);
			}
		}
		eprintln!("{:?}", groups);
		Ok(())
	}
	/// processes manga using no allocation of groups
	#[test]
	fn reformats_manga_with_default_groups() -> R {
		reformats_manga(&mut Groups::default())
	}
	/// processes manga using full allocation of groups
	#[test]
	fn reformats_manga_with_full_groups() -> R {
		reformats_manga(&mut Groups::new())
	}
	/// processes manga, then consumes groups
	#[test]
	fn groups_listing() -> R {
		let mut groups = Groups::default();
		use std::collections::HashMap;
		let mut mangas: HashMap<&str, MangaData> = HashMap::with_capacity(8);
		for mng in &TEST_MANGA_ALL_TESTS {
			if let Some(mn) = from_str::<Manga>(mng)?.ok() {
				let manga: MangaData = MangaData::from_manga(mn, &mut groups);
				assert!(mangas.insert(mng, manga).is_none());
			}
		}
		let no_groups =
			groups.compact_seq_with_ch(&mangas[TEST_MANGA_NO_META_OR_CH].chapters);
		assert!(no_groups.is_empty());
		eprintln!("{:?}", no_groups);
		let includes_zeen =
			groups.compact_seq_with_ch(&mangas[TEST_MANGA_OK].chapters);
		let zeen = Group {
			id: 2491,
			name: "zeen3 typesetting".into(),
			website: None,
		};
		assert!(includes_zeen.0.contains(&zeen));
		let zeeno = groups.get(2491).unwrap();
		assert_eq!(zeeno, zeen);
		eprintln!("{:?}", includes_zeen);
		let json = to_string_pretty(&groups.compact_seq())?;
		eprintln!("{}", json);
		let regroups_seq: GroupsSeq = from_str(&json)?;
		eprintln!("{:?}", regroups_seq);
		let mut regroups: Groups = Groups::default();
		regroups.extend(regroups_seq);
		let json = to_string_pretty(&regroups.compact_map())?;
		eprintln!("{}", json);
		let regroups_map: GroupsMap = from_str(&json)?;
		eprintln!("{:?}", regroups_map);
		let regroups: Groups = Groups::from(regroups_map);
		eprintln!("{:?}", regroups);
		assert_eq!(regroups, groups);
		Ok(())
	}
	// #[test]
	// fn holes_test() -> R {
	// 	let mut grps = Groups::default();
	// 	let mng = from_str::<Manga>(TEST_MANGA_OK)?.ok().unwrap();
	// 	let test = MangaData::from_manga(mng, &mut grps);
	// 	let hole_list = test.holes(1);
	// 	eprintln!("{:?}", hole_list);
	// 	Ok(())
	// }
}