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
//! All error types.

use crate::entity_id::EntityId;
use crate::info::TypeInfo;
use crate::scheduler::Label;
use crate::storage::StorageId;
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt::{Debug, Display, Formatter};
#[cfg(feature = "std")]
use std::error::Error;

/// AtomicRefCell's borrow error.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Borrow {
    /// The Storage was borrowed when an exclusive borrow occurred.
    Unique,
    /// The Storage was borrowed exclusively when a shared borrow occurred.
    Shared,
    /// The Storage of a `!Send` component was accessed from an other thread.
    WrongThread,
    /// The Storage of a `!Sync` component was accessed from multiple threads at the same time.
    MultipleThreads,
}

#[cfg(feature = "std")]
impl Error for Borrow {}

impl Debug for Borrow {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            Borrow::Unique => f.write_str("Cannot mutably borrow while already borrowed."),
            Borrow::Shared => {
                f.write_str("Cannot immutably borrow while already mutably borrowed.")
            }
            Borrow::WrongThread => {
                f.write_str("Can't access from another thread because it's !Send and !Sync.")
            }
            Borrow::MultipleThreads => f.write_str(
                "Can't access from multiple threads at the same time because it's !Sync.",
            ),
        }
    }
}

impl Display for Borrow {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error related to acquiring a storage.
pub enum GetStorage {
    #[allow(missing_docs)]
    AllStoragesBorrow(Borrow),
    #[allow(missing_docs)]
    StorageBorrow {
        name: Option<&'static str>,
        id: StorageId,
        borrow: Borrow,
    },
    #[allow(missing_docs)]
    Entities(Borrow),
    #[allow(missing_docs)]
    MissingStorage {
        name: Option<&'static str>,
        id: StorageId,
    },
    /// Error returned by a custom view.
    #[cfg(feature = "std")]
    Custom(Box<dyn Error + Send + Sync>),
    /// Error returned by a custom view.
    #[cfg(not(feature = "std"))]
    Custom(Box<dyn core::any::Any + Send>),
}

impl GetStorage {
    #[cfg(feature = "std")]
    #[allow(missing_docs)]
    pub fn from_custom<E: Into<Box<dyn Error + Send + Sync>>>(error: E) -> GetStorage {
        GetStorage::Custom(error.into())
    }
    #[cfg(not(feature = "std"))]
    #[allow(missing_docs)]
    pub fn from_custom<E: core::any::Any + Send>(error: E) -> GetStorage {
        GetStorage::Custom(Box::new(error))
    }
}

impl PartialEq for GetStorage {
    fn eq(&self, other: &GetStorage) -> bool {
        match (self, other) {
            (GetStorage::AllStoragesBorrow(l_borrow), GetStorage::AllStoragesBorrow(r_borrow)) => {
                l_borrow == r_borrow
            }
            (
                GetStorage::StorageBorrow {
                    name: l_name,
                    id: l_id,
                    borrow: l_borrow,
                },
                GetStorage::StorageBorrow {
                    name: r_name,
                    id: r_id,
                    borrow: r_borrow,
                },
            ) => l_name == r_name && l_id == r_id && l_borrow == r_borrow,
            (GetStorage::Entities(l_borrow), GetStorage::Entities(r_borrow)) => {
                l_borrow == r_borrow
            }
            (
                GetStorage::MissingStorage {
                    name: l_name,
                    id: l_id,
                },
                GetStorage::MissingStorage {
                    name: r_name,
                    id: r_id,
                },
            ) => l_name == r_name && l_id == r_id,
            _ => false,
        }
    }
}

#[cfg(feature = "std")]
impl Error for GetStorage {}

impl Debug for GetStorage {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            GetStorage::AllStoragesBorrow(borrow) => match borrow {
                Borrow::Unique => f.write_str("Cannot mutably borrow AllStorages while it's already borrowed (AllStorages is borrowed to access any storage)."),
                Borrow::Shared => {
                    f.write_str("Cannot immutably borrow AllStorages while it's already mutably borrowed.")
                },
                _ => unreachable!(),
            },
            GetStorage::StorageBorrow {name, id, borrow} => if let Some(name) = name {
                match borrow {
                    Borrow::Unique => f.write_fmt(format_args!("Cannot mutably borrow {} storage while it's already borrowed.", name)),
                    Borrow::Shared => {
                        f.write_fmt(format_args!("Cannot immutably borrow {} storage while it's already mutably borrowed.", name))
                    },
                    Borrow::MultipleThreads => f.write_fmt(format_args!("Cannot borrow {} storage from multiple thread at the same time because it's !Sync.", name)),
                    Borrow::WrongThread => f.write_fmt(format_args!("Cannot borrow {} storage from other thread than the one it was created in because it's !Send and !Sync.", name)),
                }
            } else {
                match borrow {
                    Borrow::Unique => f.write_fmt(format_args!("Cannot mutably borrow {:?} storage while it's already borrowed.", id)),
                    Borrow::Shared => {
                        f.write_fmt(format_args!("Cannot immutably borrow {:?} storage while it's already mutably borrowed.", id))
                    },
                    Borrow::MultipleThreads => f.write_fmt(format_args!("Cannot borrow {:?} storage from multiple thread at the same time because it's !Sync.", id)),
                    Borrow::WrongThread => f.write_fmt(format_args!("Cannot borrow {:?} storage from other thread than the one it was created in because it's !Send and !Sync.", id)),
                }
            }
            GetStorage::Entities(borrow) => match borrow {
                Borrow::Unique => f.write_str("Cannot mutably borrow Entities storage while it's already borrowed."),
                Borrow::Shared => {
                    f.write_str("Cannot immutably borrow Entities storage while it's already mutably borrowed.")
                },
                _ => unreachable!(),
            },
            GetStorage::MissingStorage { name, id } => if let Some(name) = name {
                f.write_fmt(format_args!("{} storage was not found in the World. You can register unique storage with: world.add_unique(your_unique);", name))
            } else {
                f.write_fmt(format_args!("{:?} storage was not found in the World. You can register unique storage with: world.add_unique(your_unique);", id))
            }
            GetStorage::Custom(err) => {
                f.write_fmt(format_args!("Storage borrow failed with a custom error, {:?}.", err))
            }
        }
    }
}

impl Display for GetStorage {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error related to adding an entity.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum NewEntity {
    /// Another add_storage operation is in progress.
    AllStoragesBorrow(Borrow),
    /// Entities is already borrowed.
    Entities(Borrow),
}

#[cfg(feature = "std")]
impl Error for NewEntity {}

impl Debug for NewEntity {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            NewEntity::AllStoragesBorrow(borrow) => match borrow {
                Borrow::Unique => f.write_str("Cannot mutably borrow all storages while it's already borrowed (this include component storage)."),
                Borrow::Shared => {
                    f.write_str("Cannot immutably borrow all storages while it's already mutably borrowed.")
                },
                _ => unreachable!(),
            },
            NewEntity::Entities(borrow) => match borrow {
                Borrow::Unique => f.write_str("Cannot mutably borrow entities while it's already borrowed."),
                _ => unreachable!(),
            },
        }
    }
}

impl Display for NewEntity {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Returned by [`AllStorages::add_component`] and [`World::add_component`] when trying to add components to an entity that is not alive.
///
/// [`AllStorages::add_component`]: crate::all_storages::AllStorages::add_component()
/// [`World::add_component`]: crate::world::World::add_component()
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AddComponent {
    #[allow(missing_docs)]
    EntityIsNotAlive,
}

#[cfg(feature = "std")]
impl Error for AddComponent {}

impl Debug for AddComponent {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            AddComponent::EntityIsNotAlive => {
                f.write_str("Entity has to be alive to add component to it.")
            }
        }
    }
}

impl Display for AddComponent {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error type returned by [`Workload::add_to_world`].
///
/// [`Workload::add_to_world`]: crate::Workload::add_to_world()
#[derive(Clone, Eq)]
pub enum AddWorkload {
    /// A workload with the same name already exists.
    AlreadyExists,
    /// The `Scheduler` is already borrowed.
    Borrow,
    /// This workload cannot be created.
    ImpossibleRequirements(ImpossibleRequirements),
    /// A system declared some requirements that are not met.
    MissingInWorkload(Box<dyn Label>, Vec<Box<dyn Label>>),
    /// A system declared some requirements that are not met.
    MissingBefore(Box<dyn Label>, Vec<Box<dyn Label>>),
    /// A system declared some requirements that are not met.
    MissingAfter(Box<dyn Label>, Vec<Box<dyn Label>>),
}

// For some reason this trait can't be derived with Box<dyn Label>
impl PartialEq for AddWorkload {
    fn eq(&self, other: &AddWorkload) -> bool {
        match (self, other) {
            (AddWorkload::ImpossibleRequirements(l0), AddWorkload::ImpossibleRequirements(r0)) => {
                l0 == r0
            }
            (AddWorkload::MissingInWorkload(l0, l1), AddWorkload::MissingInWorkload(r0, r1)) => {
                l0 == r0 && l1 == r1
            }
            (AddWorkload::MissingBefore(l0, l1), AddWorkload::MissingBefore(r0, r1)) => {
                l0 == r0 && l1 == r1
            }
            (AddWorkload::MissingAfter(l0, l1), AddWorkload::MissingAfter(r0, r1)) => {
                l0 == r0 && l1 == r1
            }
            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
        }
    }
}

#[cfg(feature = "std")]
impl Error for AddWorkload {}

impl Debug for AddWorkload {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            AddWorkload::AlreadyExists => f.write_str("A workload with this name already exists."),
            AddWorkload::Borrow => {
                f.write_str("Cannot mutably borrow the scheduler while it's already borrowed.")
            }
            AddWorkload::ImpossibleRequirements(err) => Debug::fmt(err, f),
            AddWorkload::MissingInWorkload(system_name, missing_in_workload) => {
                f.write_fmt(format_args!(
                    "System({:?}) is missing some systems in workload: {:?}",
                    system_name, missing_in_workload
                ))
            }
            AddWorkload::MissingBefore(system_name, missing_before) => f.write_fmt(format_args!(
                "System({:?}) is missing some systems before: {:?}",
                system_name, missing_before
            )),
            AddWorkload::MissingAfter(system_name, missing_after) => f.write_fmt(format_args!(
                "System({:?}) is missing some systems after: {:?}",
                system_name, missing_after
            )),
        }
    }
}

impl Display for AddWorkload {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Trying to set the default workload to a non existent one will result in this error.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SetDefaultWorkload {
    /// The `Scheduler` is already borrowed.
    Borrow,
    /// The workload does not exists.
    MissingWorkload,
}

#[cfg(feature = "std")]
impl Error for SetDefaultWorkload {}

impl Debug for SetDefaultWorkload {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            SetDefaultWorkload::Borrow => {
                f.write_str("Cannot mutably borrow scheduler while it's already borrowed.")
            }
            SetDefaultWorkload::MissingWorkload => {
                f.write_str("No workload with this name exists.")
            }
        }
    }
}

impl Display for SetDefaultWorkload {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error returned by [`run_default`] and [`run_workload`].  
/// The error can be a storage error, problem with the scheduler's borrowing, a non existent workload or a custom error.
///
/// [`run_default`]: crate::World#method::run_default()
/// [`run_workload`]: crate::World#method::run_workload()
pub enum RunWorkload {
    /// The `Scheduler` is exclusively borrowed.
    Scheduler,
    /// Error while running a system.
    Run((Box<dyn Label>, Run)),
    /// Workload is not present in the world.
    MissingWorkload,
}

impl RunWorkload {
    /// Helper function to get back a custom error.
    #[cfg(feature = "std")]
    pub fn custom_error(self) -> Option<Box<dyn Error + Send + Sync>> {
        match self {
            RunWorkload::Run((_, Run::Custom(error))) => Some(error),
            _ => None,
        }
    }
    /// Helper function to get back a custom error.
    #[cfg(not(feature = "std"))]
    pub fn custom_error(self) -> Option<Box<dyn core::any::Any + Send>> {
        match self {
            RunWorkload::Run((_, Run::Custom(error))) => Some(error),
            _ => None,
        }
    }
}

#[cfg(feature = "std")]
impl Error for RunWorkload {}

impl Debug for RunWorkload {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            RunWorkload::Scheduler => {
                f.write_str("Cannot borrow the scheduler while it's already mutably borrowed.")
            }
            RunWorkload::MissingWorkload => f.write_str("No workload with this name exists. You first need to add the workload using `World::add_workload`."),
            RunWorkload::Run((system_name, run)) => {
                f.write_fmt(format_args!("System {:?} failed: {:?}", system_name, run))
            }
        }
    }
}

impl Display for RunWorkload {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error returned by [`World::run`] and [`AllStorages::run`].  
/// Can refer to an invalid storage borrow or a custom error.
///
/// [`World::run`]: crate::World::run()
/// [`AllStorages::run`]: crate::AllStorages::run()
pub enum Run {
    /// Failed to borrow one of the storage.
    GetStorage(GetStorage),
    /// Error returned by the system.
    #[cfg(feature = "std")]
    Custom(Box<dyn Error + Send + Sync>),
    /// Error returned by the system.
    #[cfg(not(feature = "std"))]
    Custom(Box<dyn core::any::Any + Send>),
}

impl From<GetStorage> for Run {
    fn from(get_storage: GetStorage) -> Run {
        Run::GetStorage(get_storage)
    }
}

impl Run {
    #[cfg(feature = "std")]
    #[allow(missing_docs)]
    pub fn from_custom<E: Into<Box<dyn Error + Send + Sync>>>(error: E) -> Run {
        Run::Custom(error.into())
    }
    #[cfg(not(feature = "std"))]
    #[allow(missing_docs)]
    pub fn from_custom<E: core::any::Any + Send>(error: E) -> Run {
        Run::Custom(Box::new(error))
    }
}

impl PartialEq for Run {
    fn eq(&self, other: &Run) -> bool {
        match (self, other) {
            (Run::GetStorage(l_get_storage), Run::GetStorage(r_get_storage)) => {
                l_get_storage == r_get_storage
            }
            _ => false,
        }
    }
}

#[cfg(feature = "std")]
impl Error for Run {}

impl Debug for Run {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            Run::GetStorage(get_storage) => Debug::fmt(&get_storage, f),
            Run::Custom(err) => {
                f.write_fmt(format_args!("run failed with a custom error, {:?}.", err))
            }
        }
    }
}

impl Display for Run {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Returned by [`get`] when an entity does not have a component in the requested storage(s).
///
/// [`get`]: crate::Get
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct MissingComponent {
    /// `EntityId` of the component.
    pub id: EntityId,
    /// Name of the component.
    pub name: &'static str,
}

#[cfg(feature = "std")]
impl Error for MissingComponent {}

impl Debug for MissingComponent {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        f.write_fmt(format_args!(
            "{:?} does not have a {} component.",
            self.id, self.name
        ))
    }
}

impl Display for MissingComponent {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Returned when trying to add an invalid system to a workload.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum InvalidSystem {
    /// `AllStorages` borrowed alongside another storage.
    AllStorages,
    /// Multiple views of the same storage including an exclusive one.
    MultipleViews,
    /// Multiple exclusive views for the same storage.
    MultipleViewsMut,
    /// System returning `Workload`
    WorkloadUsedAsSystem(&'static str),
}

#[cfg(feature = "std")]
impl Error for InvalidSystem {}

impl Debug for InvalidSystem {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            InvalidSystem::AllStorages => f.write_str("A system borrowing both AllStorages and a storage can't run. You can borrow the storage inside the system with AllStorages::borrow or AllStorages::run instead."),
            InvalidSystem::MultipleViews => f.write_str("Multiple views of the same storage including an exclusive borrow, consider removing the shared borrow."),
            InvalidSystem::MultipleViewsMut => f.write_str("Multiple exclusive views of the same storage, consider removing one."),
            InvalidSystem::WorkloadUsedAsSystem(system_name) => f.write_fmt(format_args!("Workload used as a system, you should call it `{}()`.", system_name)),
        }
    }
}

impl Display for InvalidSystem {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error returned by [`World::remove_unique`] and [`AllStorages::remove_unique`].
///
/// [`World::remove_unique`]: crate::World::remove_unique()
/// [`AllStorages::remove_unique`]: crate::AllStorages::remove_unique()
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum UniqueRemove {
    /// `AllStorages` was already borrowed.
    AllStorages,
    /// No unique storage of this type exist.
    MissingUnique(&'static str),
    /// The unique storage is already borrowed.
    StorageBorrow((&'static str, Borrow)),
}

#[cfg(feature = "std")]
impl Error for UniqueRemove {}

impl Debug for UniqueRemove {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            UniqueRemove::AllStorages => f.write_str("Cannot borrow AllStorages while it's already exclusively borrowed."),
            UniqueRemove::MissingUnique(name) => f.write_fmt(format_args!("No unique storage exists for {}.\n", name)),
            UniqueRemove::StorageBorrow((name, borrow)) => match borrow {
                Borrow::Unique => f.write_fmt(format_args!("Cannot mutably borrow {} storage while it's already borrowed.", name)),
                Borrow::WrongThread => f.write_fmt(format_args!("Cannot borrow {} storage from other thread than the one it was created in because it's !Send and !Sync.", name)),
                _ => unreachable!()
            }
        }
    }
}

impl Display for UniqueRemove {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error returned by [`apply`] and [`apply_mut`].
///
/// [`apply`]: crate::ViewMut::apply()
/// [`apply_mut`]: crate::ViewMut::apply_mut()
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Apply {
    #[allow(missing_docs)]
    IdenticalIds,
    /// Entity that doesn't have the required component.
    MissingComponent(EntityId),
}

#[cfg(feature = "std")]
impl Error for Apply {}

impl Debug for Apply {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            Apply::IdenticalIds => f.write_str("Cannot use apply with identical components."),
            Apply::MissingComponent(id) => f.write_fmt(format_args!(
                "Entity {:?} does not have any component in this storage.",
                id
            )),
        }
    }
}

impl Display for Apply {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Error returned by [`are_all_uniques_present_in_world`].
///
/// [`are_all_uniques_present_in_world`]: crate::Workload::are_all_uniques_present_in_world()
#[derive(Clone, Eq)]
pub enum UniquePresence {
    #[allow(missing_docs)]
    Workload(Box<dyn Label>),
    #[allow(missing_docs)]
    Unique(TypeInfo),
    #[allow(missing_docs)]
    AllStorages,
    #[allow(missing_docs)]
    Scheduler,
}

// For some reason this trait can't be derived with Box<dyn Label>
impl PartialEq for UniquePresence {
    fn eq(&self, other: &UniquePresence) -> bool {
        match (self, other) {
            (UniquePresence::Workload(l0), UniquePresence::Workload(r0)) => l0 == r0,
            (UniquePresence::Unique(l0), UniquePresence::Unique(r0)) => l0 == r0,
            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
        }
    }
}

#[cfg(feature = "std")]
impl Error for UniquePresence {}

impl Debug for UniquePresence {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            UniquePresence::Workload(workload) => f.write_fmt(format_args!(
                "{:?} workload is not present in the World.",
                workload
            )),
            UniquePresence::Unique(type_info) => f.write_fmt(format_args!(
                "{} unique storage is not present in the World",
                type_info.name
            )),
            UniquePresence::AllStorages => f.write_str(
                "Cannot immutably borrow AllStorages while it is already mutably borrowed.",
            ),
            UniquePresence::Scheduler => f.write_str(
                "Cannot immutably borrow the Scheduler while it is already mutably borrowed.",
            ),
        }
    }
}

impl Display for UniquePresence {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Returned when trying to create views for custom storages.
pub enum CustomStorageView {
    #[allow(missing_docs)]
    GetStorage(GetStorage),
    #[allow(missing_docs)]
    WrongType(Cow<'static, str>),
}

impl From<GetStorage> for CustomStorageView {
    fn from(get_storage: GetStorage) -> CustomStorageView {
        CustomStorageView::GetStorage(get_storage)
    }
}

#[cfg(feature = "std")]
impl Error for CustomStorageView {}

impl Debug for CustomStorageView {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            CustomStorageView::GetStorage(get_storage) => Debug::fmt(get_storage, f),
            CustomStorageView::WrongType(name) => f.write_fmt(format_args!(
                "Cannot convert, custom storage is of type: {:?}",
                name
            )),
        }
    }
}

impl Display for CustomStorageView {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}

/// Returned when requirements for a workload make it impossible to build a valid workload.
#[derive(Clone, Eq)]
pub enum ImpossibleRequirements {
    #[allow(missing_docs)]
    BeforeAndAfter(Box<dyn Label>, Box<dyn Label>),
    #[allow(missing_docs)]
    ImpossibleConstraints(Box<dyn Label>, Vec<Box<dyn Label>>, Vec<Box<dyn Label>>),
}

impl PartialEq for ImpossibleRequirements {
    fn eq(&self, other: &ImpossibleRequirements) -> bool {
        match (self, other) {
            (
                ImpossibleRequirements::BeforeAndAfter(system, conflict),
                ImpossibleRequirements::BeforeAndAfter(other_system, other_conflict),
            ) => system == other_system && conflict == other_conflict,
            (
                ImpossibleRequirements::ImpossibleConstraints(workload1, before1, after1),
                ImpossibleRequirements::ImpossibleConstraints(workload2, before2, after2),
            ) => workload1 == workload2 && before1 == before2 && after1 == after2,
            _ => false,
        }
    }
}

#[cfg(feature = "std")]
impl Error for ImpossibleRequirements {}

impl Debug for ImpossibleRequirements {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            ImpossibleRequirements::BeforeAndAfter(system, other_system) => {
                f.write_fmt(format_args!(
                    "System({:?}) needs to be both before and after {:?}",
                    system, other_system
                ))
            }
            ImpossibleRequirements::ImpossibleConstraints(system, before, after) => {
                f.write_fmt(format_args!("System({:?}) cannot be placed.", system))?;
                f.write_str("\n")?;
                f.write_fmt(format_args!("Before: {:?}", before))?;
                f.write_str("\n")?;
                f.write_fmt(format_args!("After: {:?}", after))
            }
        }
    }
}

impl Display for ImpossibleRequirements {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        Debug::fmt(self, f)
    }
}