moonshine-tag 0.5.0

Cheap, fast, mostly unique identifiers designed for Bevy
Documentation
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
#![allow(deprecated)] // TODO: Remove
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

pub mod prelude {
    //! Prelude module to import the most essential types and traits.

    pub use crate::{tag_filter, tags, Tag, TagFilter, TagPlugin, Tags};

    pub use crate::{ComponentTags, WithTags};
}

mod filter;

pub extern crate inventory;

use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

use bevy_app::{App, Plugin};
use bevy_ecs::lifecycle::HookContext;
use bevy_ecs::prelude::*;
use bevy_ecs::world::DeferredWorld;
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::prelude::*;
use itertools::Itertools;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};

use moonshine_util::prelude::*;

pub use self::filter::*;

/// A [`Plugin`] required to register tag related types for reflection.
pub struct TagPlugin;

impl Plugin for TagPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<TagNames>()
            .register_type::<Tag>()
            .register_type::<Tags>()
            .register_type::<HashSet<Tag>>()
            .register_type_data::<HashSet<Tag>, ReflectSerialize>()
            .register_type_data::<HashSet<Tag>, ReflectDeserialize>()
            .register_type::<TagFilter>()
            .register_type::<Box<TagFilter>>()
            .register_type_data::<Box<TagFilter>, ReflectSerialize>()
            .register_type_data::<Box<TagFilter>, ReflectDeserialize>();
    }
}

/// Macro used to define new tags.
///
/// See [`Tag`] for more information.
#[macro_export]
macro_rules! tags {
    ($(#[$meta:meta])* $v:vis $name:ident $(,)?) => {
        $(#[$meta])*
        $v const $name: $crate::Tag = $crate::Tag::new(stringify!($name));
        $crate::inventory::submit! {
            $crate::TagMeta { tag: $name, name: stringify!($name) }
        }
    };

    ($(#[$meta:meta])* $v0:vis $n0:ident, $($v:vis $n:ident),* $(,)?) => {
        $(#[$meta])*
        $v0 const $n0: $crate::Tag = $crate::Tag::new(stringify!($n0));
        $crate::inventory::submit! {
            $crate::TagMeta { tag: $n0, name: stringify!($n0) }
        }
        $crate::tags!($(#[$meta])* $($v $n),*);
    };
}

/// A generic, cheap, and mostly unique identifier.
///
///
/// # Usage
///
/// A tag is a hashed representation of some string key. Two tags are equal if their hash values are equal.
///
/// Tags are defined to be very cheap to create, copy, and compare. However, they do not guarantee uniqueness.
/// In most application domains, the chance of tag collision within a single subsystem is very low.
///
/// Internally, tags are hashed using a 64-bit [FNV-1a](https://softwareengineering.stackexchange.com/a/145633) algorithm.
///
/// # Example
/// ```rust
/// use moonshine_tag::prelude::*;
///
/// tags! { A, pub B };
///
/// assert_eq!(A, A);
/// assert_ne!(A, B);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Reflect)]
#[cfg_attr(not(feature = "pretty-serde"), derive(Serialize, Deserialize))]
#[reflect(Hash, PartialEq)]
pub struct Tag(u64);

impl Tag {
    /// Creates a new tag from a string key.
    ///
    /// # Example
    /// ```rust
    /// use moonshine_tag::prelude::*;
    ///
    /// tags! { A };
    ///
    /// assert_eq!(Tag::new("A"), A);
    /// ```
    pub const fn new(source: &str) -> Self {
        Self::from_hash(const_fnv1a_hash::fnv1a_hash_str_64(source))
    }

    /// Creates a new tag from a hash value.
    pub const fn from_hash(hash: u64) -> Self {
        Self(hash)
    }

    /// Returns the hash value of this tag.
    pub const fn hash(&self) -> u64 {
        self.0
    }

    /// Returns a human-friendly representation of this tag's hash.
    ///
    /// This is a [base31](https://github.com/kmanley/base31)-encoded string representation of the tag's hash value.
    ///
    /// This is, on average, faster than [`resolve_name`](Tag::resolve_name) for human-friendly identification.
    pub fn pretty_hash(&self) -> String {
        base31::encode(self.0)
    }

    /// Returns `true` if this tag matches the given [`TagFilter`].
    pub fn matches(&self, filter: &TagFilter) -> bool {
        use TagFilter::*;
        match filter {
            Equal(a) => a.iter().exactly_one().is_ok_and(|tag| tag == *self),
            AllOf(a) => a.is_empty() || a.iter().exactly_one().is_ok_and(|tag| tag == *self),
            AnyOf(a) => a.contains(*self),
            And(a, b) => self.matches(a) && self.matches(b),
            Or(a, b) => self.matches(a) || self.matches(b),
            Not(a) => !self.matches(a),
        }
    }

    /// Resolves the name of this tag if it has been defined using the `tags!` macro.
    ///
    /// Note that this function is very slow and should not be used in performance-critical code.
    /// It performs a linear search over all registered tags to find a match and it is mainly designed for debugging and editor purposes.
    ///
    /// If performance is a concern, consider using [`pretty_hash`](Tag::pretty_hash) or cache the result of this function.
    /// See [`iter_names`](Tag::iter_names) for an iterator over all registered tag names.
    ///
    /// Tags must be defined using the [`tags!`] macro to be registered.
    pub fn resolve_name(&self) -> Option<&'static str> {
        TagMeta::iter()
            .find(|meta| meta.tag == *self)
            .map(|meta| meta.name)
    }

    /// Returns the name of this tag if it has been defined using the `tags!` macro.
    /// Otherwise, it returns the [`pretty_hash`](Tag::pretty_hash) as a fallback.
    ///
    /// Use this when you just want to display the most human-friendly format of the tag and
    /// do not care for handling any errors due to unregistered tags.
    ///
    /// See:
    /// - [`Tag::resolve_name`]
    /// - [`Tag::pretty_hash`]
    pub fn pretty_name(&self) -> Cow<'static, str> {
        self.resolve_name()
            .map(|name| name.into())
            .unwrap_or_else(|| self.pretty_hash().into())
    }

    /// Returns an iterator over all registered tag names.
    ///
    /// Tags must be defined using the [`tags!`] macro to be registered.
    pub fn iter_names() -> impl Iterator<Item = &'static str> {
        TagMeta::iter().map(|meta| meta.name)
    }
}

impl fmt::Debug for Tag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Tag({})", self.0)
    }
}

impl Hash for Tag {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(self.0)
    }
}

impl FromWorld for Tag {
    fn from_world(_: &mut World) -> Self {
        Self(u64::MAX)
    }
}

impl IntoIterator for Tag {
    type Item = Tag;

    type IntoIter = std::iter::Once<Tag>;

    fn into_iter(self) -> Self::IntoIter {
        std::iter::once(self)
    }
}

#[cfg(feature = "pretty-serde")]
impl Serialize for Tag {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if let Some(name) = TagNames::global().get_cached(*self) {
            serializer.serialize_str(&name)
        } else {
            serializer.serialize_u64(self.0)
        }
    }
}

#[cfg(feature = "pretty-serde")]
impl<'de> Deserialize<'de> for Tag {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_any(TagVisitor)
    }
}

#[cfg(feature = "pretty-serde")]
struct TagVisitor;

#[cfg(feature = "pretty-serde")]
impl<'de> serde::de::Visitor<'de> for TagVisitor {
    type Value = Tag;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "string or numeric hash")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Tag::new(v))
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Tag::new(&v))
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Tag::from_hash(v))
    }
}

/// The metadata associated with a [`Tag`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Reflect)]
pub struct TagMeta {
    /// The tag itself.
    pub tag: Tag,
    /// The name of the tag.
    pub name: &'static str,
}

impl TagMeta {
    /// Iterates over all registered tag metadata.
    pub fn iter() -> impl Iterator<Item = &'static TagMeta> {
        inventory::iter::<TagMeta>()
    }
}

inventory::collect!(TagMeta);

/// A [`Resource`] which may be used to cache [`Tag`] names.
///
/// # Usage
///
/// When managing tags, it is often required to represent a [`Tag`] in a human-friendly way.
/// While [`Tag::pretty_name`] exists, it is not cheap to use because it requires a linear search
/// over all registered tags.
///
/// This is fine for small projects, but this method does not scale well as the numebr of tags increases.
///
/// One solution around this problem is to cache the tag names.
#[derive(Resource, Default)]
pub struct TagNames(HashMap<Tag, Cow<'static, str>>);

impl TagNames {
    /// Creates a new [`TagNames`] and preloads it with all existing tag names.
    ///
    /// The cost of this function increases linearly relative to the number of tags in your project.
    /// This function is useful if you are willing to spend the initial cost of caching all tag names to
    /// ensure no cache misses during lookup.
    ///
    /// # Example
    /// ```rust
    /// use bevy::prelude::*;
    /// use moonshine_tag::{prelude::*, TagNames};
    ///
    /// let mut app = App::new();
    ///
    /// app.add_plugins((MinimalPlugins, TagPlugin));
    /// app.insert_resource(TagNames::generate());
    /// ```
    pub fn generate() -> Self {
        let mut inner = HashMap::new();
        for &TagMeta { tag, name } in TagMeta::iter() {
            inner.insert(tag, name.into());
        }

        Self(inner)
    }

    /// Returns a global instance of [`TagNames`].
    ///
    /// This global instance is lazily initialized and internally calls [`generate`](TagNames::generate)
    /// on first execution which can be expensive depending on the number of registered tags.
    pub fn global() -> &'static Self {
        static GLOBAL: Lazy<TagNames> = Lazy::new(TagNames::generate);
        &GLOBAL
    }

    /// Returns the name of the given [`Tag`] and stores a copy of it to speed up future calls.
    pub fn get(&mut self, tag: Tag) -> Cow<'static, str> {
        self.0
            .entry(tag)
            .or_insert_with(|| tag.pretty_name())
            .clone()
    }

    /// Returns the name of the given [`Tag`] if it exists in the cache.
    pub fn get_cached(&self, tag: Tag) -> Option<Cow<'static, str>> {
        self.0.get(&tag).cloned()
    }

    /// Iterates over all [`Tag`]/name pairs saved in this cache.
    pub fn iter(&self) -> impl Iterator<Item = (&Tag, &Cow<'static, str>)> {
        self.0.iter()
    }
}

/// A collection of tags.
///
/// # Examples
///
/// ```rust
/// use moonshine_tag::prelude::*;
///
/// tags! { A, B };
///
/// let tags: Tags = [A, B].into();
///
/// assert_eq!(tags, [B, A]);
/// ```
///
/// You may use this type on its own, or as a [`Component`]:
///
/// ```rust
/// use bevy::prelude::*;
/// use moonshine_tag::prelude::*;
///
/// tags! { A, B };
///
/// let mut world = World::new();
/// let entity = world.spawn(Tags::from([A, B])).id();
/// assert_eq!(world.get::<Tags>(entity).unwrap(), [A, B]);
/// ```
#[derive(Component, Default, Debug, Clone, PartialEq, Eq, Reflect)]
#[cfg_attr(not(feature = "pretty-serde"), derive(Serialize, Deserialize))]
#[reflect(Component)]
pub struct Tags(HashSet<Tag>);

impl Tags {
    /// A static empty set of [`Tags`].
    ///
    /// # Usage
    ///
    /// This is convenient for cases when the absence of `Tags` implies "no tags", for example:
    ///
    /// ```
    /// use bevy::prelude::*;
    /// use moonshine_tag::prelude::*;
    ///
    /// let mut world = World::new();
    ///
    /// // Spawn an entity with no tags:
    /// let entity = world.spawn_empty().id();
    ///
    /// // Get tags, or just use the global empty set.
    /// let tags = world.get::<Tags>(entity).unwrap_or(Tags::empty());
    ///
    /// assert!(tags.is_empty());
    /// ```
    pub fn static_empty() -> &'static Tags {
        static EMPTY: Lazy<Tags> = Lazy::new(Tags::new);
        &EMPTY
    }

    #[doc(hidden)]
    #[deprecated(since = "0.3.0", note = "use `static_empty` instead")]
    pub fn empty() -> &'static Tags {
        Self::static_empty()
    }

    /// Creates a new empty set of tags.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of tags in this set.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if this set is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns `true` if this set contains the given tag.
    pub fn contains(&self, tag: Tag) -> bool {
        self.0.contains(&tag)
    }

    /// Inserts a tag into this set.
    pub fn insert(&mut self, tag: Tag) -> bool {
        self.0.insert(tag)
    }

    /// Removes a tag from this set.
    pub fn remove(&mut self, tag: Tag) -> bool {
        self.0.remove(&tag)
    }

    /// See [`HashSet::retain`].
    pub fn retain(&mut self, f: impl FnMut(&Tag) -> bool) {
        self.0.retain(f)
    }

    /// Returns an iterator over the tags in this set.
    pub fn iter(&self) -> impl Iterator<Item = Tag> + '_ {
        self.0.iter().copied()
    }

    /// Returns the union of this and another set of tags.
    #[must_use]
    pub fn union(mut self, other: impl Into<Tags>) -> Self {
        self.extend(other.into());
        self
    }

    /// Adds all tags from another set to this one.
    pub fn extend(&mut self, other: impl Into<Tags>) {
        self.0.extend(other.into());
    }

    /// Returns `true` if this set has no tags in common with another set.
    pub fn is_disjoint(&self, tags: &Tags) -> bool {
        self.0.is_disjoint(&tags.0)
    }

    /// Returns `true` if the tags in this set are all present in another set.
    pub fn is_subset(&self, tags: &Tags) -> bool {
        self.0.is_subset(&tags.0)
    }

    /// Returns `true` if the tags in another set are all present in this set.
    pub fn is_superset(&self, tags: &Tags) -> bool {
        self.0.is_superset(&tags.0)
    }

    /// Returns `true` if this set matches the given filter.
    pub fn matches(&self, filter: &TagFilter) -> bool {
        use TagFilter::*;
        match filter {
            Equal(a) => a == self,
            AllOf(a) => a.is_subset(self),
            AnyOf(a) => !a.is_disjoint(self),
            And(a, b) => self.matches(a) && self.matches(b),
            Or(a, b) => self.matches(a) || self.matches(b),
            Not(a) => !self.matches(a),
        }
    }

    /// Returns a string representation of this set of tags.
    ///
    /// Note that this function is slow and should not be used in performance-critical code.
    /// It is mainly designed for debugging and editor purposes.
    pub fn to_pretty_string(&self) -> String {
        self.0
            .iter()
            .map(|tag| {
                tag.resolve_name()
                    .map(|name| name.to_string())
                    .unwrap_or_else(|| tag.pretty_hash())
            })
            .join(", ")
    }
}

impl From<Tag> for Tags {
    fn from(tag: Tag) -> Self {
        let mut tags = Tags::new();
        tags.insert(tag);
        tags
    }
}

impl FromIterator<Tag> for Tags {
    fn from_iter<T: IntoIterator<Item = Tag>>(iter: T) -> Self {
        Self(HashSet::from_iter(iter))
    }
}

impl<const N: usize> From<[Tag; N]> for Tags {
    fn from(tags: [Tag; N]) -> Self {
        Tags::from_iter(tags)
    }
}

impl<const N: usize> PartialEq<[Tag; N]> for Tags {
    fn eq(&self, other: &[Tag; N]) -> bool {
        self.0.len() == N && other.iter().all(|tag| self.0.contains(tag))
    }
}

impl<const N: usize> PartialEq<[Tag; N]> for &Tags {
    fn eq(&self, other: &[Tag; N]) -> bool {
        self.0.len() == N && other.iter().all(|tag| self.0.contains(tag))
    }
}

impl<const N: usize> PartialEq<Tags> for [Tag; N] {
    fn eq(&self, other: &Tags) -> bool {
        other == self
    }
}

impl MergeComponent for Tags {
    fn merge(&mut self, other: Self) {
        self.0.extend(other);
    }
}

impl IntoIterator for Tags {
    type Item = Tag;
    type IntoIter = bevy_platform::collections::hash_set::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

#[cfg(feature = "pretty-serde")]
impl Serialize for Tags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeSeq;
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for tag in self.iter() {
            seq.serialize_element(&tag)?;
        }
        seq.end()
    }
}

#[cfg(feature = "pretty-serde")]
impl<'de> Deserialize<'de> for Tags {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_any(TagsVisitor)
    }
}

#[cfg(feature = "pretty-serde")]
struct TagsVisitor;

#[cfg(feature = "pretty-serde")]
impl<'de> serde::de::Visitor<'de> for TagsVisitor {
    type Value = Tags;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "string or numeric hash")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Tag::new(v).into())
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Tag::new(&v).into())
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Tag::from_hash(v).into())
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let mut tags = Tags::new();
        while let Ok(Some(tag)) = seq.next_element::<Tag>() {
            tags.insert(tag);
        }
        Ok(tags)
    }
}

/// A [`Component`] which merges a set of tags into single [`Tags`] component.
///
/// # Usage
///
/// This is useful for adding tags to entities which may or may not have a `Tags` component
/// already without replacing the existing tags, especially when spawning bundles.
///
/// This implementation takes advantage of the unique type signature of Rust lambda functions
/// to avoid conflicts when used in bundles. While more flexible, this usage is not possible
/// as component requirements. For that, see [`ComponentTags`].
///
/// # Examples
/// ```
/// use bevy::prelude::*;
/// use moonshine_tag::prelude::*;
/// use moonshine_util::prelude::*;
///
/// tags! { A, B, C };
///
/// let mut world = World::new();
/// let entity = world.spawn((
///     Merge::<Tags>::with(|| [A, B].into()),
///     Merge::<Tags>::with(|| [B, C].into()),
/// ));
/// assert_eq!(entity.get::<Tags>().unwrap(), [A, B, C]);
/// ```
#[derive(Component)]
#[component(storage = "SparseSet")]
#[component(on_add = Self::on_add)]
#[deprecated(since = "0.3.0", note = "use `AddWith` from `moonshine-util` instead")]
pub struct WithTags<I: IntoIterator<Item = Tag>, F: FnOnce() -> I>(pub F)
where
    F: 'static + Send + Sync,
    I: 'static + Send + Sync;

impl<I: IntoIterator<Item = Tag>, F: FnOnce() -> I> WithTags<I, F>
where
    F: 'static + Send + Sync,
    I: 'static + Send + Sync,
{
    fn on_add(mut world: DeferredWorld, ctx: HookContext) {
        let entity = ctx.entity;
        world.commands().queue(move |world: &mut World| {
            let mut entity = world.entity_mut(entity);
            let this = entity.take::<Self>().unwrap();
            let new_tags = Tags::from_iter(this.0());
            if let Some(mut tags) = entity.get_mut::<Tags>() {
                tags.extend(new_tags);
            } else {
                entity.insert(new_tags);
            }
        });
    }
}

/// A [`Component`] which merges a set of tags into single [`Tags`] component.
///
/// # Usage
///
/// This is similar to [`WithTags`], except that it may be used as a component requirement.
///
/// Note that `T` can be anything. By convention, it is best to use `Self` to avoid requirement conflicts.
///
/// # Examples
/// ```
/// use bevy::prelude::*;
/// use moonshine_tag::prelude::*;
/// use moonshine_util::prelude::*;
///
/// tags! { A, B, C };
///
/// #[derive(Component)]
/// #[require(MergeFrom<Self, Tags> = Tags::from(A))]
/// struct Foo;
///
/// #[derive(Component)]
/// #[require(MergeFrom<Self, Tags> = Tags::from([B, C]))]
/// struct Bar;
///
/// let mut world = World::new();
/// let entity = world.spawn((Foo, Bar));
/// assert_eq!(entity.get::<Tags>().unwrap(), [A, B, C]);
/// ```
#[derive(Component)]
#[component(storage = "SparseSet")]
#[component(on_add = Self::on_add)]
#[deprecated(since = "0.3.0", note = "use `AddFrom` from `moonshine-util` instead")]
pub struct ComponentTags<T: Component>(Tags, PhantomData<T>);

impl<T: Component> ComponentTags<T> {
    fn on_add(mut world: DeferredWorld, ctx: HookContext) {
        let entity = ctx.entity;
        world.commands().queue(move |world: &mut World| {
            let mut entity = world.entity_mut(entity);
            let ComponentTags(new_tags, ..) = entity.take::<Self>().unwrap();
            if let Some(mut tags) = entity.get_mut::<Tags>() {
                tags.extend(new_tags);
            } else {
                entity.insert(new_tags);
            }
        });
    }
}

impl<T: Component, I: Into<Tags>> From<I> for ComponentTags<T> {
    fn from(tags: I) -> Self {
        Self(tags.into(), PhantomData)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    tags!(A, B, C);

    #[test]
    fn match_eq() {
        assert_eq!(A, A);
        assert_ne!(A, B);
    }

    pub fn matches(tags: impl Into<Tags>, filter: &TagFilter) -> bool {
        tags.into().matches(filter)
    }

    #[test]
    fn match_empty() {
        assert!(matches([], &tag_filter!([])));
        assert!(matches([], &tag_filter!([..])));
        assert!(matches([], &tag_filter!([..] | [])));
        assert!(matches([], &tag_filter!([..] & [])));

        assert!(!matches([], &tag_filter!(![])));
        assert!(!matches([], &tag_filter!([A])));
        assert!(!matches([], &tag_filter!([A, ..])));
        assert!(!matches([], &tag_filter!([A, B])));
        assert!(!matches([], &tag_filter!([A | B])));
    }

    #[test]
    fn match_tag() {
        assert!(matches(A, &tag_filter!([..])));
        assert!(matches(A, &tag_filter!([..] | [])));
        assert!(matches(A, &tag_filter!(![])));
        assert!(matches(A, &tag_filter!([A])));
        assert!(matches(A, &tag_filter!([A | B])));
        assert!(matches(A, &tag_filter!([B | A])));
        assert!(matches(A, &tag_filter!(![B])));
        assert!(matches(A, &tag_filter!([A, ..])));
        assert!(matches(A, &tag_filter!([A, ..] | [B])));

        assert!(A.matches(&tag_filter!([..])));
        assert!(A.matches(&tag_filter!([..] | [])));
        assert!(A.matches(&tag_filter!(![])));
        assert!(A.matches(&tag_filter!([A])));
        assert!(A.matches(&tag_filter!([A | B])));
        assert!(A.matches(&tag_filter!([B | A])));
        assert!(A.matches(&tag_filter!(![B])));
        assert!(A.matches(&tag_filter!([A, ..])));
        assert!(A.matches(&tag_filter!([A, ..] | [B])));

        assert!(!matches(A, &tag_filter!([])));
        assert!(!matches(A, &tag_filter!(![A])));
        assert!(!matches(A, &tag_filter!([B])));
        assert!(!matches(A, &tag_filter!([A, B, ..])));
        assert!(!matches(A, &tag_filter!([B, A, ..])));
        assert!(!matches(A, &tag_filter!([B | C])));
        assert!(!matches(A, &tag_filter!([B, C, ..])));

        assert!(!A.matches(&tag_filter!([])));
        assert!(!A.matches(&tag_filter!(![A])));
        assert!(!A.matches(&tag_filter!([B])));
        assert!(!A.matches(&tag_filter!([A, B, ..])));
        assert!(!A.matches(&tag_filter!([B, A, ..])));
        assert!(!A.matches(&tag_filter!([B | C])));
        assert!(!A.matches(&tag_filter!([B, C, ..])));
    }

    #[test]
    fn match_tags() {
        assert!(matches([A, B], &tag_filter!([..])));
        assert!(matches([A, B], &tag_filter!([..] | [])));
        assert!(matches([A, B], &tag_filter!(![])));
        assert!(matches([A, B], &tag_filter!([A, B])));
        assert!(matches([A, B], &tag_filter!([B, A])));
        assert!(matches([A, B], &tag_filter!([A, ..])));
        assert!(matches([A, B], &tag_filter!([A, B, ..])));
        assert!(matches([A, B], &tag_filter!([A, B, ..] | [B, C])));

        assert!(!matches([A, B], &tag_filter!([])));
        assert!(!matches([A, B], &tag_filter!([A])));
        assert!(!matches([A, B], &tag_filter!([A, B, C])));
        assert!(!matches([A, B], &tag_filter!(![A, B])));
        assert!(!matches([A, B], &tag_filter!([A, C])));
        assert!(!matches([A, B], &tag_filter!([A, C, ..])));
        assert!(!matches([A, B], &tag_filter!([A, B, C, ..])));
        assert!(!matches([A, B], &tag_filter!([A, C, ..] | [B, C])));
        assert!(!matches([A, B], &tag_filter!([C, ..])));
    }

    #[test]
    fn with_tags() {
        let mut world = World::new();
        let entity = world
            .spawn((WithTags(|| [A]), WithTags(|| [A, B]), WithTags(|| [B, C])))
            .id();
        world.flush();
        assert_eq!(
            world.get::<Tags>(entity).unwrap_or(Tags::static_empty()),
            [A, B, C]
        );
    }

    #[test]
    fn with_tags_existing() {
        let mut world = World::new();
        let entity = world
            .spawn((Tags::from(A), WithTags(|| [A, B]), WithTags(|| [B, C])))
            .id();
        world.flush();
        assert_eq!(
            world.get::<Tags>(entity).unwrap_or(Tags::static_empty()),
            [A, B, C]
        );
    }

    #[test]
    fn tags_macro_usage() {
        tags! {
            pub N00,
        }
        tags! {
            pub N01,
            N02,
        }
        tags! {
            pub N03,
            pub N04,
        }
        tags! {
            #[allow(non_upper_case_globals)]
            pub n05,
        }
        tags! {
            #[allow(non_upper_case_globals)]
            n06,
        }
        tags! {
            #[allow(non_upper_case_globals)] // Meta applies to all entries
            n07,
            n08,
        }
        tags! {
            #[allow(non_upper_case_globals)]
            pub n09,
            n10,
        }
    }

    #[cfg(feature = "pretty-serde")]
    #[test]
    fn test_pretty_serde() {
        let ux = tag_filter![A, B, ..];
        let sx = "AllOf([\"A\",\"B\"])";

        let s = ron::to_string(&ux).unwrap();
        assert_eq!(s, sx);

        let u: TagFilter = ron::from_str(&s).unwrap();
        assert_eq!(u, ux);
    }
}