azalea_block/
range.rs

1use std::{
2    collections::{HashSet, hash_set},
3    ops::{Add, RangeInclusive},
4    sync::LazyLock,
5};
6
7use azalea_registry::{builtin::BlockKind, tags::RegistryTag};
8
9use crate::{BlockState, block_state::BlockStateIntegerRepr};
10
11#[derive(Clone, Debug)]
12pub struct BlockStates {
13    pub set: HashSet<BlockState>,
14}
15
16impl From<RangeInclusive<BlockStateIntegerRepr>> for BlockStates {
17    fn from(range: RangeInclusive<BlockStateIntegerRepr>) -> Self {
18        let mut set = HashSet::with_capacity((range.end() - range.start() + 1) as usize);
19        for id in range {
20            set.insert(BlockState::try_from(id).unwrap_or_default());
21        }
22        Self { set }
23    }
24}
25
26impl IntoIterator for BlockStates {
27    type Item = BlockState;
28    type IntoIter = hash_set::IntoIter<BlockState>;
29
30    fn into_iter(self) -> Self::IntoIter {
31        self.set.into_iter()
32    }
33}
34
35impl BlockStates {
36    pub fn contains(&self, state: &BlockState) -> bool {
37        self.set.contains(state)
38    }
39}
40
41impl Add for BlockStates {
42    type Output = Self;
43
44    fn add(self, rhs: Self) -> Self::Output {
45        Self {
46            set: self.set.union(&rhs.set).copied().collect(),
47        }
48    }
49}
50
51impl From<HashSet<BlockKind>> for BlockStates {
52    fn from(set: HashSet<BlockKind>) -> Self {
53        Self::from(&set)
54    }
55}
56
57impl From<&HashSet<BlockKind>> for BlockStates {
58    fn from(set: &HashSet<BlockKind>) -> Self {
59        let mut block_states = HashSet::with_capacity(set.len());
60        for &block in set {
61            block_states.extend(BlockStates::from(block));
62        }
63        Self { set: block_states }
64    }
65}
66
67impl From<&[BlockKind]> for BlockStates {
68    fn from(arr: &[BlockKind]) -> Self {
69        let mut block_states = HashSet::with_capacity(arr.len());
70        for &block in arr {
71            block_states.extend(BlockStates::from(block));
72        }
73        Self { set: block_states }
74    }
75}
76impl<const N: usize> From<[BlockKind; N]> for BlockStates {
77    fn from(arr: [BlockKind; N]) -> Self {
78        Self::from(&arr[..])
79    }
80}
81impl From<&RegistryTag<BlockKind>> for BlockStates {
82    fn from(tag: &RegistryTag<BlockKind>) -> Self {
83        Self::from(&**tag)
84    }
85}
86// allows users to do like `BlockStates::from(&tags::blocks::LOGS)` instead of
87// `BlockStates::from(&&tags::blocks::LOGS)`
88impl From<&LazyLock<RegistryTag<BlockKind>>> for BlockStates {
89    fn from(tag: &LazyLock<RegistryTag<BlockKind>>) -> Self {
90        Self::from(&**tag)
91    }
92}