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
//! Fast column-major serialization
//!
//! Stores each archetype in a block where each type of component is laid out
//! contiguously. Preferred for data that will be read/written programmatically. Efficient, compact,
//! and highly compressible, but difficult to read or edit by hand.
//!
//! This module builds on the public archetype-related APIs and [`World::spawn_column_batch_at()`],
//! and is somewhat opinionated. For some applications, a custom approach may be preferable.
//!
//! In terms of the serde data model, we treat a [`World`] as a sequence of archetypes, where each
//! archetype is a 4-tuple of an entity count `n`, component count `k`, a `k`-tuple of
//! user-controlled component IDs, and a `k+1`-tuple of `n`-tuples of components, such that the
//! first `n`-tuple contains `Entity` values and the remainder each contain components of the type
//! identified by the corresponding component ID.

use crate::alloc::vec::Vec;
use core::{any::type_name, cell::RefCell, fmt, marker::PhantomData};

use serde::{
    de::{self, DeserializeSeed, SeqAccess, Unexpected, Visitor},
    ser::{SerializeSeq, SerializeTuple},
    Deserialize, Deserializer, Serialize, Serializer,
};

use crate::{
    Archetype, ColumnBatch, ColumnBatchBuilder, ColumnBatchType, Component, Entity, World,
};

/// Implements serialization of archetypes
///
/// `serialize_component_ids` and `serialize_components` must serialize exactly the number of
/// elements indicated by `component_count` or return `Err`.
///
/// Data external to the [`World`] can be exposed during serialization by storing references inside
/// the struct implementing this trait.
///
/// # Example
///
/// ```
/// # use serde::{Serialize, Deserialize};
/// # #[derive(Serialize)]
/// # struct Position([f32; 3]);
/// # #[derive(Serialize)]
/// # struct Velocity([f32; 3]);
/// use std::any::TypeId;
/// use hecs::{*, serialize::column::*};
///
/// #[derive(Serialize, Deserialize)]
/// enum ComponentId { Position, Velocity }
///
/// struct Context;
///
/// impl SerializeContext for Context {
///     fn component_count(&self, archetype: &Archetype) -> usize {
///         archetype.component_types()
///             .filter(|&t| t == TypeId::of::<Position>() || t == TypeId::of::<Velocity>())
///             .count()
///     }
///
///     fn serialize_component_ids<S: serde::ser::SerializeTuple>(
///         &mut self,
///         archetype: &Archetype,
///         mut out: S,
///     ) -> Result<S::Ok, S::Error> {
///         try_serialize_id::<Position, _, _>(archetype, &ComponentId::Position, &mut out)?;
///         try_serialize_id::<Velocity, _, _>(archetype, &ComponentId::Velocity, &mut out)?;
///         out.end()
///     }
///
///     fn serialize_components<S: serde::ser::SerializeTuple>(
///         &mut self,
///         archetype: &Archetype,
///         mut out: S,
///     ) -> Result<S::Ok, S::Error> {
///         try_serialize::<Position, _>(archetype, &mut out)?;
///         try_serialize::<Velocity, _>(archetype, &mut out)?;
///         out.end()
///     }
/// }
/// ```
// Serializing the ID tuple separately from component data allows the deserializer to allocate the
// entire output archetype up front, rather than having to allocate storage for each component type
// after processing the previous one and copy into an archetype at the end.
pub trait SerializeContext {
    /// Number of entries that [`serialize_component_ids`](Self::serialize_component_ids) and
    /// [`serialize_components`](Self::serialize_components) will produce for `archetype`
    fn component_count(&self, archetype: &Archetype) -> usize;

    /// Serialize the IDs of the components from `archetype` that will be serialized
    // We use a wrapper here rather than exposing the serde type directly because it's a huge pain
    // to determine how many IDs were written otherwise, and we need that to set the component data
    // tuple length correctly.
    fn serialize_component_ids<S: SerializeTuple>(
        &mut self,
        archetype: &Archetype,
        out: S,
    ) -> Result<S::Ok, S::Error>;

    /// Serialize component data from `archetype` into `out`
    ///
    /// For each component ID written by `serialize_component_ids`, this method must write a tuple
    /// containing one value for each entity, e.g. using [`try_serialize`], in the same order. Each
    /// tuple's length must exactly match the number of entities in `archetype`, and there must be
    /// exactly the same number of tuples as there were IDs.
    fn serialize_components<S: SerializeTuple>(
        &mut self,
        archetype: &Archetype,
        out: S,
    ) -> Result<S::Ok, S::Error>;
}

/// If `archetype` has `T` components, serialize `id` into `S`
pub fn try_serialize_id<T, I, S>(archetype: &Archetype, id: &I, out: &mut S) -> Result<(), S::Error>
where
    T: Component,
    I: Serialize + ?Sized,
    S: SerializeTuple,
{
    if archetype.has::<T>() {
        out.serialize_element(id)?;
    }
    Ok(())
}

/// If `archetype` has `T` components, serialize them into `out`
///
/// Useful for implementing [`SerializeContext::serialize_components()`].
pub fn try_serialize<T, S>(archetype: &Archetype, out: &mut S) -> Result<(), S::Error>
where
    T: Component + Serialize,
    S: SerializeTuple,
{
    if let Some(xs) = archetype.get::<&T>() {
        serialize_collection(&*xs, out)?;
    }
    Ok(())
}

/// Serialize components from `collection` into a single element of `out`
fn serialize_collection<I, S>(collection: I, out: &mut S) -> Result<(), S::Error>
where
    I: IntoIterator,
    I::IntoIter: ExactSizeIterator,
    I::Item: Serialize,
    S: SerializeTuple,
{
    struct SerializeColumn<I>(RefCell<I>);

    impl<I> Serialize for SerializeColumn<I>
    where
        I: ExactSizeIterator,
        I::Item: Serialize,
    {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut iter = self.0.borrow_mut();
            let mut tuple = serializer.serialize_tuple(iter.len())?;
            for x in &mut *iter {
                tuple.serialize_element(&x)?;
            }
            tuple.end()
        }
    }

    out.serialize_element(&SerializeColumn(RefCell::new(collection.into_iter())))
}

/// Serialize a [`World`] through a [`SerializeContext`] to a [`Serializer`]
pub fn serialize<C, S>(world: &World, context: &mut C, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    C: SerializeContext,
{
    struct SerializeArchetype<'a, C> {
        world: &'a World,
        archetype: &'a Archetype,
        ctx: RefCell<&'a mut C>,
    }

    impl<C> Serialize for SerializeArchetype<'_, C>
    where
        C: SerializeContext,
    {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let ctx = &mut *self.ctx.borrow_mut();
            let mut tuple = serializer.serialize_tuple(4)?;
            tuple.serialize_element(&self.archetype.len())?;
            let components = ctx.component_count(self.archetype);
            tuple.serialize_element(&(components as u32))?;
            let helper = SerializeComponentIds::<'_, C> {
                archetype: self.archetype,
                ctx: RefCell::new(ctx),
                components,
            };
            tuple.serialize_element(&helper)?;
            tuple.serialize_element(&SerializeComponents::<'_, C> {
                world: self.world,
                archetype: self.archetype,
                ctx: RefCell::new(ctx),
                components,
            })?;
            tuple.end()
        }
    }

    struct SerializeComponentIds<'a, C> {
        archetype: &'a Archetype,
        ctx: RefCell<&'a mut C>,
        components: usize,
    }

    impl<C> Serialize for SerializeComponentIds<'_, C>
    where
        C: SerializeContext,
    {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let tuple = serializer.serialize_tuple(self.components)?;
            self.ctx
                .borrow_mut()
                .serialize_component_ids(self.archetype, tuple)
        }
    }

    struct SerializeComponents<'a, C> {
        world: &'a World,
        archetype: &'a Archetype,
        ctx: RefCell<&'a mut C>,
        components: usize,
    }

    impl<C> Serialize for SerializeComponents<'_, C>
    where
        C: SerializeContext,
    {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let ctx = &mut *self.ctx.borrow_mut();
            let mut tuple = serializer.serialize_tuple(self.components + 1)?;

            // Serialize entity IDs
            tuple.serialize_element(&SerializeEntities {
                world: self.world,
                ids: self.archetype.ids(),
            })?;

            // Serialize component data
            ctx.serialize_components(self.archetype, tuple)
        }
    }

    struct SerializeEntities<'a> {
        world: &'a World,
        ids: &'a [u32],
    }

    impl Serialize for SerializeEntities<'_> {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut tuple = serializer.serialize_tuple(self.ids.len())?;
            for &id in self.ids {
                let entity = unsafe { self.world.find_entity_from_id(id) };
                tuple.serialize_element(&entity)?;
            }
            tuple.end()
        }
    }

    let mut seq =
        serializer.serialize_seq(Some(world.archetypes().filter(|x| !x.is_empty()).count()))?;
    for archetype in world.archetypes().filter(|x| !x.is_empty()) {
        seq.serialize_element(&SerializeArchetype {
            world,
            archetype,
            ctx: RefCell::new(context),
        })?;
    }
    seq.end()
}

/// Implements deserialization of archetypes
///
/// # Example
///
/// ```
/// # use serde::{Serialize, Deserialize};
/// # #[derive(Deserialize)]
/// # struct Position([f32; 3]);
/// # #[derive(Deserialize)]
/// # struct Velocity([f32; 3]);
/// use hecs::{*, serialize::column::*};
///
/// #[derive(Serialize, Deserialize)]
/// enum ComponentId { Position, Velocity }
///
/// // Could include references to external state for use by serialization methods
/// struct Context {
///     /// Components of the archetype currently being deserialized
///     components: Vec<ComponentId>,
/// }
///
/// impl DeserializeContext for Context {
///     fn deserialize_component_ids<'de, A>(
///         &mut self,
///         mut seq: A,
///     ) -> Result<ColumnBatchType, A::Error>
///     where
///         A: serde::de::SeqAccess<'de>,
///     {
///         self.components.clear(); // Discard data from the previous archetype
///         let mut batch = ColumnBatchType::new();
///         while let Some(id) = seq.next_element()? {
///             match id {
///                 ComponentId::Position => {
///                     batch.add::<Position>();
///                 }
///                 ComponentId::Velocity => {
///                     batch.add::<Velocity>();
///                 }
///             }
///             self.components.push(id);
///         }
///         Ok(batch)
///     }
///
///     fn deserialize_components<'de, A>(
///         &mut self,
///         entity_count: u32,
///         mut seq: A,
///         batch: &mut ColumnBatchBuilder,
///     ) -> Result<(), A::Error>
///     where
///         A: serde::de::SeqAccess<'de>,
///     {
///         // Decode component data in the order that the component IDs appeared
///         for component in &self.components {
///             match *component {
///                 ComponentId::Position => {
///                     deserialize_column::<Position, _>(entity_count, &mut seq, batch)?;
///                 }
///                 ComponentId::Velocity => {
///                     deserialize_column::<Velocity, _>(entity_count, &mut seq, batch)?;
///                 }
///             }
///         }
///         Ok(())
///     }
/// }
pub trait DeserializeContext {
    /// Deserialize a set of component IDs
    ///
    /// Implementers should usually store the deserialized component IDs in `self` to guide the
    /// following `deserialize_components` call.
    fn deserialize_component_ids<'de, A>(&mut self, seq: A) -> Result<ColumnBatchType, A::Error>
    where
        A: SeqAccess<'de>;

    /// Deserialize all component data for an archetype
    ///
    /// `seq` is a sequence of tuples directly corresponding to the IDs read in
    /// `deserialize_component_ids`, each containing `entity_count` elements.
    fn deserialize_components<'de, A>(
        &mut self,
        entity_count: u32,
        seq: A,
        batch: &mut ColumnBatchBuilder,
    ) -> Result<(), A::Error>
    where
        A: SeqAccess<'de>;
}

/// Deserialize a column of `entity_count` `T`s from `seq` into `out`
pub fn deserialize_column<'de, T, A>(
    entity_count: u32,
    seq: &mut A,
    out: &mut ColumnBatchBuilder,
) -> Result<(), A::Error>
where
    T: Component + Deserialize<'de>,
    A: SeqAccess<'de>,
{
    seq.next_element_seed(DeserializeColumn::<T>::new(entity_count, out))?
        .ok_or_else(|| {
            de::Error::invalid_value(
                Unexpected::Other("end of components"),
                &"a column of components",
            )
        })
}

/// Deserializer for a single component type, for use in [`DeserializeContext::deserialize_components()`]
struct DeserializeColumn<'a, T> {
    entity_count: u32,
    out: &'a mut ColumnBatchBuilder,
    marker: PhantomData<fn() -> T>,
}

impl<'de, 'a, T> DeserializeColumn<'a, T>
where
    T: Component + Deserialize<'de>,
{
    /// Construct a deserializer for `entity_count` `T` components, writing into `batch`
    pub fn new(entity_count: u32, batch: &'a mut ColumnBatchBuilder) -> Self {
        Self {
            entity_count,
            out: batch,
            marker: PhantomData,
        }
    }
}

impl<'de, 'a, T> DeserializeSeed<'de> for DeserializeColumn<'a, T>
where
    T: Component + Deserialize<'de>,
{
    type Value = ();

    fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_tuple(
            self.entity_count as usize,
            ColumnVisitor::<T> {
                entity_count: self.entity_count,
                out: self.out,
                marker: PhantomData,
            },
        )
    }
}

struct ColumnVisitor<'a, T> {
    entity_count: u32,
    out: &'a mut ColumnBatchBuilder,
    marker: PhantomData<fn() -> T>,
}

impl<'de, 'a, T> Visitor<'de> for ColumnVisitor<'a, T>
where
    T: Component + Deserialize<'de>,
{
    type Value = ();

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "a set of {} {} values",
            self.entity_count,
            type_name::<T>()
        )
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut out = self.out.writer::<T>().expect("unexpected component type");
        while let Some(component) = seq.next_element()? {
            if out.push(component).is_err() {
                return Err(de::Error::invalid_value(
                    Unexpected::Other("extra component"),
                    &self,
                ));
            }
        }
        if out.fill() < self.entity_count {
            return Err(de::Error::invalid_length(out.fill() as usize, &self));
        }
        Ok(())
    }
}

/// Deserialize a [`World`] with a [`DeserializeContext`] and a [`Deserializer`]
pub fn deserialize<'de, C, D>(context: &mut C, deserializer: D) -> Result<World, D::Error>
where
    C: DeserializeContext,
    D: Deserializer<'de>,
{
    deserializer.deserialize_seq(WorldVisitor(context))
}

struct WorldVisitor<'a, C>(&'a mut C);

impl<'de, 'a, C> Visitor<'de> for WorldVisitor<'a, C>
where
    C: DeserializeContext,
{
    type Value = World;

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

    fn visit_seq<A>(self, mut seq: A) -> Result<World, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut world = World::new();
        let mut entities = Vec::new();
        while let Some(bundle) =
            seq.next_element_seed(DeserializeArchetype(self.0, &mut entities))?
        {
            world.spawn_column_batch_at(&entities, bundle);
            entities.clear();
        }
        Ok(world)
    }
}

struct DeserializeArchetype<'a, C>(&'a mut C, &'a mut Vec<Entity>);

impl<'de, 'a, C> DeserializeSeed<'de> for DeserializeArchetype<'a, C>
where
    C: DeserializeContext,
{
    type Value = ColumnBatch;

    fn deserialize<D>(self, deserializer: D) -> Result<ColumnBatch, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_tuple(4, ArchetypeVisitor(self.0, self.1))
    }
}

struct ArchetypeVisitor<'a, C>(&'a mut C, &'a mut Vec<Entity>);

impl<'de, 'a, C> Visitor<'de> for ArchetypeVisitor<'a, C>
where
    C: DeserializeContext,
{
    type Value = ColumnBatch;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a 4-tuple of an entity count, a component count, a component ID list, and a component value list")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<ColumnBatch, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let entity_count = seq
            .next_element::<u32>()?
            .ok_or_else(|| de::Error::invalid_length(0, &self))?;
        let component_count = seq
            .next_element::<u32>()?
            .ok_or_else(|| de::Error::invalid_length(1, &self))?;
        self.1.reserve(entity_count as usize);
        let ty = seq
            .next_element_seed(DeserializeComponentIds(self.0, component_count))?
            .ok_or_else(|| de::Error::invalid_length(2, &self))?;
        let mut batch = ty.into_batch(entity_count);
        seq.next_element_seed(DeserializeComponents {
            ctx: self.0,
            entity_count,
            component_count,
            entities: self.1,
            out: &mut batch,
        })?
        .ok_or_else(|| de::Error::invalid_length(3, &self))?;
        batch.build().map_err(|_| {
            de::Error::invalid_value(
                Unexpected::Other("incomplete archetype"),
                &"a complete archetype",
            )
        })
    }
}

struct DeserializeComponentIds<'a, C>(&'a mut C, u32);

impl<'de, 'a, C> DeserializeSeed<'de> for DeserializeComponentIds<'a, C>
where
    C: DeserializeContext,
{
    type Value = ColumnBatchType;

    fn deserialize<D>(self, deserializer: D) -> Result<ColumnBatchType, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_tuple(self.1 as usize, ComponentIdVisitor(self.0, self.1))
    }
}

struct ComponentIdVisitor<'a, C>(&'a mut C, u32);

impl<'de, 'a, C> Visitor<'de> for ComponentIdVisitor<'a, C>
where
    C: DeserializeContext,
{
    type Value = ColumnBatchType;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "a set of {} component IDs", self.1)
    }

    fn visit_seq<A>(self, seq: A) -> Result<ColumnBatchType, A::Error>
    where
        A: SeqAccess<'de>,
    {
        self.0.deserialize_component_ids(seq)
    }
}

struct DeserializeComponents<'a, C> {
    ctx: &'a mut C,
    component_count: u32,
    entity_count: u32,
    entities: &'a mut Vec<Entity>,
    out: &'a mut ColumnBatchBuilder,
}

impl<'de, 'a, C> DeserializeSeed<'de> for DeserializeComponents<'a, C>
where
    C: DeserializeContext,
{
    type Value = ();

    fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_tuple(
            self.component_count as usize + 1,
            ComponentsVisitor {
                ctx: self.ctx,
                entity_count: self.entity_count,
                entities: self.entities,
                out: self.out,
            },
        )
    }
}

struct ComponentsVisitor<'a, C> {
    ctx: &'a mut C,
    entity_count: u32,
    entities: &'a mut Vec<Entity>,
    out: &'a mut ColumnBatchBuilder,
}

impl<'de, 'a, C> Visitor<'de> for ComponentsVisitor<'a, C>
where
    C: DeserializeContext,
{
    type Value = ();

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "a set of {} components", self.entity_count)
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
    where
        A: SeqAccess<'de>,
    {
        seq.next_element_seed(DeserializeEntities {
            count: self.entity_count,
            out: self.entities,
        })?;
        self.ctx
            .deserialize_components(self.entity_count, seq, self.out)
    }
}

struct DeserializeEntities<'a> {
    count: u32,
    out: &'a mut Vec<Entity>,
}

impl<'de, 'a> DeserializeSeed<'de> for DeserializeEntities<'a> {
    type Value = ();

    fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_tuple(
            self.count as usize,
            EntitiesVisitor {
                count: self.count,
                out: self.out,
            },
        )
    }
}

struct EntitiesVisitor<'a> {
    count: u32,
    out: &'a mut Vec<Entity>,
}

impl<'de, 'a> Visitor<'de> for EntitiesVisitor<'a> {
    type Value = ();

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a list of {} entity IDs", self.count)
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut n = 0;
        while let Some(id) = seq.next_element()? {
            self.out.push(id);
            n += 1;
        }
        if n != self.count {
            return Err(de::Error::invalid_length(n as usize, &self));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::alloc::vec::Vec;
    use core::fmt;

    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::*;

    #[derive(Serialize, Deserialize, PartialEq, Debug, Copy, Clone)]
    struct Position([f32; 3]);
    #[derive(Serialize, Deserialize, PartialEq, Debug, Copy, Clone)]
    struct Velocity([f32; 3]);

    #[derive(Default)]
    struct Context {
        components: Vec<ComponentId>,
    }
    #[derive(Serialize, Deserialize)]
    enum ComponentId {
        Position,
        Velocity,
    }

    #[derive(Serialize, Deserialize)]
    /// Bodge into serde_test's very strict interface
    struct SerWorld(#[serde(with = "helpers")] World);

    impl PartialEq for SerWorld {
        fn eq(&self, other: &Self) -> bool {
            fn same_components<T: Component + PartialEq>(x: &EntityRef, y: &EntityRef) -> bool {
                x.get::<&T>().as_ref().map(|x| &**x) == y.get::<&T>().as_ref().map(|x| &**x)
            }

            for (x, y) in self.0.iter().zip(other.0.iter()) {
                if x.entity() != y.entity()
                    || !same_components::<Position>(&x, &y)
                    || !same_components::<Velocity>(&x, &y)
                {
                    return false;
                }
            }
            true
        }
    }

    impl fmt::Debug for SerWorld {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_map()
                .entries(self.0.iter().map(|e| {
                    (
                        e.entity(),
                        (
                            e.get::<&Position>().map(|x| *x),
                            e.get::<&Velocity>().map(|x| *x),
                        ),
                    )
                }))
                .finish()
        }
    }

    mod helpers {
        use super::*;
        pub fn serialize<S: Serializer>(x: &World, s: S) -> Result<S::Ok, S::Error> {
            crate::serialize::column::serialize(
                x,
                &mut Context {
                    components: Vec::new(),
                },
                s,
            )
        }
        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<World, D::Error> {
            crate::serialize::column::deserialize(
                &mut Context {
                    components: Vec::new(),
                },
                d,
            )
        }
    }

    impl DeserializeContext for Context {
        fn deserialize_component_ids<'de, A>(
            &mut self,
            mut seq: A,
        ) -> Result<ColumnBatchType, A::Error>
        where
            A: SeqAccess<'de>,
        {
            self.components.clear();
            let mut batch = ColumnBatchType::new();
            while let Some(id) = seq.next_element()? {
                match id {
                    ComponentId::Position => {
                        batch.add::<Position>();
                    }
                    ComponentId::Velocity => {
                        batch.add::<Velocity>();
                    }
                }
                self.components.push(id);
            }
            Ok(batch)
        }

        fn deserialize_components<'de, A>(
            &mut self,
            entity_count: u32,
            mut seq: A,
            batch: &mut ColumnBatchBuilder,
        ) -> Result<(), A::Error>
        where
            A: SeqAccess<'de>,
        {
            for component in &self.components {
                match *component {
                    ComponentId::Position => {
                        deserialize_column::<Position, _>(entity_count, &mut seq, batch)?;
                    }
                    ComponentId::Velocity => {
                        deserialize_column::<Velocity, _>(entity_count, &mut seq, batch)?;
                    }
                }
            }
            Ok(())
        }
    }

    impl SerializeContext for Context {
        fn component_count(&self, archetype: &Archetype) -> usize {
            archetype.component_types().len()
        }

        fn serialize_component_ids<S: SerializeTuple>(
            &mut self,
            archetype: &Archetype,
            mut out: S,
        ) -> Result<S::Ok, S::Error> {
            try_serialize_id::<Position, _, _>(archetype, &ComponentId::Position, &mut out)?;
            try_serialize_id::<Velocity, _, _>(archetype, &ComponentId::Velocity, &mut out)?;
            out.end()
        }

        fn serialize_components<S: SerializeTuple>(
            &mut self,
            archetype: &Archetype,
            mut out: S,
        ) -> Result<S::Ok, S::Error> {
            try_serialize::<Position, _>(archetype, &mut out)?;
            try_serialize::<Velocity, _>(archetype, &mut out)?;
            out.end()
        }
    }

    #[test]
    #[rustfmt::skip]
    fn roundtrip() {
        use serde_test::{Token, assert_tokens};

        let mut world = World::new();
        let p0 = Position([0.0, 0.0, 0.0]);
        let v0 = Velocity([1.0, 1.0, 1.0]);
        let p1 = Position([2.0, 2.0, 2.0]);
        let e0 = world.spawn((p0, v0));
        let e1 = world.spawn((p1,));
        let e2 = world.spawn(());

        assert_tokens(&SerWorld(world), &[
            Token::NewtypeStruct { name: "SerWorld" },
            Token::Seq { len: Some(3) },

            Token::Tuple { len: 4 },
            Token::U32(1),
            Token::U32(0),
            Token::Tuple { len: 0 },
            Token::TupleEnd,
            Token::Tuple { len: 1 },
            Token::Tuple { len: 1 },
            Token::U64(e2.to_bits().into()),
            Token::TupleEnd,
            Token::TupleEnd,
            Token::TupleEnd,

            Token::Tuple { len: 4 },
            Token::U32(1),
            Token::U32(2),
            Token::Tuple { len: 2 },
            Token::UnitVariant { name: "ComponentId", variant: "Position" },
            Token::UnitVariant { name: "ComponentId", variant: "Velocity" },
            Token::TupleEnd,
            Token::Tuple { len: 3 },
            Token::Tuple { len: 1 },
            Token::U64(e0.to_bits().into()),
            Token::TupleEnd,
            Token::Tuple { len: 1 },
            Token::NewtypeStruct { name: "Position" },
            Token::Tuple { len: 3 },
            Token::F32(0.0),
            Token::F32(0.0),
            Token::F32(0.0),
            Token::TupleEnd,
            Token::TupleEnd,
            Token::Tuple { len: 1 },
            Token::NewtypeStruct { name: "Velocity" },
            Token::Tuple { len: 3 },
            Token::F32(1.0),
            Token::F32(1.0),
            Token::F32(1.0),
            Token::TupleEnd,
            Token::TupleEnd,
            Token::TupleEnd,
            Token::TupleEnd,

            Token::Tuple { len: 4 },
            Token::U32(1),
            Token::U32(1),
            Token::Tuple { len: 1 },
            Token::UnitVariant { name: "ComponentId", variant: "Position" },
            Token::TupleEnd,
            Token::Tuple { len: 2 },
            Token::Tuple { len: 1 },
            Token::U64(e1.to_bits().into()),
            Token::TupleEnd,
            Token::Tuple { len: 1 },
            Token::NewtypeStruct { name: "Position" },
            Token::Tuple { len: 3 },
            Token::F32(2.0),
            Token::F32(2.0),
            Token::F32(2.0),
            Token::TupleEnd,
            Token::TupleEnd,
            Token::TupleEnd,
            Token::TupleEnd,

            Token::SeqEnd,
        ])
    }
}