xvc-ecs 0.7.0

Entity-Component System for Xvc
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
//! A component store for ephemeral operations based on [HashMap].
//! Unlike [XvcStore], it doesn't require `T` to be serializable.
//! It's supposed to be used operations that don't require final result to be recorded to disk.
use super::*;
use crate::error::{Error, Result};
use crate::{Storable, XvcStore};
use log::debug;
use rayon::iter::{FromParallelIterator, ParallelIterator};

use std::collections::hash_map::IterMut;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::convert::From;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::{FromIterator, Iterator};
use std::sync::{Arc, RwLock};

use super::vstore::VStore;

use std::ops::{Deref, DerefMut};

/// This is a HashMap for more random access and less restrictions, no support for serialization
#[derive(Debug, Clone)]
pub struct HStore<T> {
    /// The wrapped map for the store
    pub map: HashMap<XvcEntity, T>,
}

/// A shared version of [HStore] for use in multithreaded environments.
pub type SharedHStore<T> = Arc<RwLock<HStore<T>>>;

impl<T> Deref for HStore<T> {
    type Target = HashMap<XvcEntity, T>;

    fn deref(&self) -> &Self::Target {
        &self.map
    }
}

impl<T> DerefMut for HStore<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.map
    }
}

impl<T> From<HashMap<XvcEntity, T>> for HStore<T> {
    fn from(map: HashMap<XvcEntity, T>) -> Self {
        Self { map }
    }
}

impl<T> FromIterator<(XvcEntity, T)> for HStore<T> {
    fn from_iter<I: IntoIterator<Item = (XvcEntity, T)>>(iter: I) -> Self {
        Self {
            map: HashMap::<XvcEntity, T>::from_iter(iter),
        }
    }
}

impl<T> FromParallelIterator<(XvcEntity, T)> for HStore<T>
where
    T: Send,
{
    fn from_par_iter<I>(par_iter: I) -> Self
    where
        I: rayon::iter::IntoParallelIterator<Item = (XvcEntity, T)>,
    {
        let par_iter = par_iter.into_par_iter();
        let map: HashMap<XvcEntity, T> = par_iter.collect();
        Self { map }
    }
}

impl<T> HStore<T>
where
    T: Storable,
{
    /// Convert to [VStore]
    pub fn to_vstore(&self) -> Result<VStore<T>> {
        let mut store = VStore::new();
        for (k, v) in self.map.iter() {
            store.insert(*k, v.clone());
        }
        Ok(store)
    }

    /// Returns the inner map's iter_mut
    pub fn iter_mut(&mut self) -> IterMut<'_, XvcEntity, T> {
        self.map.iter_mut()
    }

    /// Return a mutable value for `entity`
    pub fn get_mut(&mut self, entity: &XvcEntity) -> Option<&mut T> {
        self.map.get_mut(entity)
    }

    /// This is used to create a store from actual values where the entity may
    /// or may not already be in the store.
    pub fn from_storable<I>(
        values: I,
        store: &XvcStore<T>,
        generator: &XvcEntityGenerator,
    ) -> HStore<T>
    where
        I: IntoIterator<Item = T>,
    {
        let mut hstore = HStore::<T>::new();
        for value in values {
            let key = match store.entity_by_value(&value) {
                Some(e) => e,
                None => generator.next_element(),
            };
            hstore.map.insert(key, value.clone());
        }
        hstore
    }
}

impl<T> Default for HStore<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Storable> From<&XvcStore<T>> for HStore<T> {
    fn from(store: &XvcStore<T>) -> Self {
        let map = HashMap::from_iter(store.iter().map(|(k, v)| (*k, v.clone())));
        Self { map }
    }
}

impl<T> HStore<T> {
    /// Create an empty HStore.
    ///
    /// Calls inner map's [HashMap::new].
    pub fn new() -> HStore<T> {
        HStore {
            map: HashMap::<XvcEntity, T>::new(),
        }
    }

    /// Creates an empty HStore.
    ///
    /// Creates an inner map with the given `capacity`.
    pub fn with_capacity(capacity: usize) -> HStore<T> {
        HStore {
            map: HashMap::<XvcEntity, T>::with_capacity(capacity),
        }
    }

    /// Creates values from `func` and gets new entities from `generator` to create new records.
    pub fn from_func<F>(generator: &XvcEntityGenerator, func: F) -> Result<HStore<T>>
    where
        F: Fn() -> Result<Option<T>>,
    {
        let mut hstore = HStore::<T>::new();
        loop {
            let value = match func() {
                Ok(Some(v)) => v,
                Ok(None) => break,
                Err(err) => return Err(err),
            };
            let key = generator.next_element();
            hstore.map.insert(key, value);
        }
        Ok(hstore)
    }

    /// Return the number of elements in this HStore
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Return true if there are no elements in this HStore
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Calls the inner map's insert
    pub fn insert(&mut self, entity: XvcEntity, value: T) -> Option<T> {
        self.map.insert(entity, value)
    }

    /// Returns a [HashSet] of values.
    pub fn to_hset(&self) -> HashSet<T>
    where
        T: std::fmt::Debug + Eq + Hash + Clone,
    {
        let mut set = HashSet::<T>::with_capacity(self.len());
        for (e, v) in self.iter() {
            if !set.insert(v.clone()) {
                debug!("Duplicate value in store: ({:?}, {:?})", e, v);
            }
        }
        set
    }

    /// Returns a [BTreeSet] of values.
    pub fn to_bset(&self) -> BTreeSet<T>
    where
        T: std::fmt::Debug + Ord + Clone,
    {
        let mut set = BTreeSet::<T>::new();
        for (e, v) in self.iter() {
            if !set.insert(v.clone()) {
                debug!("Duplicate value in store: ({:?}, {:?})", e, &v);
            }
        }
        set
    }

    /// Returns a map from values to entities.
    ///
    /// Skips if there are duplicate values in the map.
    pub fn inverted_hmap(&self) -> HashMap<T, XvcEntity>
    where
        T: std::fmt::Debug + Eq + Hash + Clone,
    {
        let mut imap = HashMap::<T, XvcEntity>::with_capacity(self.len());
        for (e, v) in self.iter() {
            let ires = imap.insert(v.clone(), *e);
            if ires.is_some() {
                debug!("Duplicate value in store: ({:?}, {:?})", e, v);
            }
        }
        imap
    }

    /// Returns a map from values to entities.
    ///
    /// Skips if there are duplicate values in the map.
    pub fn inverted_bmap(&self) -> BTreeMap<T, XvcEntity>
    where
        T: std::fmt::Debug + Ord + Clone,
    {
        let mut imap = BTreeMap::<T, XvcEntity>::new();
        for (e, v) in self.map.iter() {
            let ires = imap.insert(v.clone(), *e);
            if ires.is_some() {
                debug!("Duplicate value in store: ({:?}, {:?})", e, v);
            }
        }
        imap
    }

    /// Performs a left join with [XvcEntity] keys.
    ///
    /// The returned store contains `(T, Option<U>)` values that correspond to the identical
    /// `XvcEntity` values.
    ///
    /// ## Example
    ///
    /// If this store has
    ///
    /// `{10: "John Doe", 12: "George Mason", 19: "Ali Canfield"}`,
    /// and the `other` store contains
    /// `{10: "Carpenter", 17: "Developer", 19: "Artist" }`
    ///
    /// `left_join` will return
    ///
    /// `{10: ("John Doe", Some("Carpenter")), 12: ("George Mason", None), 19: ("Ali Canfield",
    /// Some("Artist")}`
    ///
    /// Note that, it may be more convenient to keep this relationship in a [crate::R11Store]
    /// if your stores don't use filtering
    pub fn left_join<U>(&self, other: HStore<U>) -> HStore<(T, Option<U>)>
    where
        T: Storable,
        U: Storable,
    {
        let mut joined = HStore::<(T, Option<U>)>::new();
        for (entity, value) in self.map.iter() {
            joined.insert(*entity, (value.clone(), other.get(entity).cloned()));
        }

        joined
    }

    /// Performs a full join with [XvcEntity] keys.
    ///
    /// The returned store contains `(Option<T>, Option<U>)` values that correspond to the
    /// identical `XvcEntity` values.
    ///
    /// Note that, it may be more convenient to keep this relationship in a [crate::R11Store]
    /// if your stores don't use filtering
    ///
    /// ```rust
    ///
    /// use xvc_ecs::{XvcEntity, HStore};
    ///
    /// let mut store1 = HStore::<String>::new();
    /// store1.insert(10u128.into(), "John Doe".into());
    /// store1.insert(12u128.into(), "George Mason".into());
    /// store1.insert(19u128.into(), "Ali Canfield".into());
    ///
    /// let mut store2 = HStore::<String>::new();
    /// store2.insert(10u128.into(), "Carpenter".into());
    /// store2.insert(17u128.into(), "Developer".into());
    /// store2.insert(15u128.into(), "Plumber".into());
    /// store2.insert(19u128.into(), "Artist".into());
    ///
    /// let result = store1.full_join(store2);
    ///
    /// assert_eq!(result.len(), 5);
    /// assert_eq!(result[&10u128.into()], (Some("John Doe".into()), Some("Carpenter".into())));
    /// assert_eq!(result[&12u128.into()], (Some("George Mason".into()), None));
    /// assert_eq!(result[&15u128.into()], (None, Some("Plumber".into())));
    /// assert_eq!(result[&17u128.into()], (None, Some("Developer".into())));
    /// assert_eq!(result[&19u128.into()], (Some("Ali Canfield".into()), Some("Artist".into())));
    /// ```
    pub fn full_join<U>(&self, other: HStore<U>) -> HStore<(Option<T>, Option<U>)>
    where
        T: Storable,
        U: Storable,
    {
        let all_keys = self.keys().chain(other.keys()).collect::<HashSet<_>>();
        let mut joined = HStore::<(Option<T>, Option<U>)>::new();
        for entity in all_keys.into_iter() {
            joined.insert(
                *entity,
                (self.get(entity).cloned(), other.get(entity).cloned()),
            );
        }

        joined
    }

    /// Performs a join with [XvcEntity] keys.
    ///
    /// The returned store contains `(T, U)` values that correspond to the
    /// identical `XvcEntity` values for values that exist in both stores.
    ///
    /// ## Example
    ///
    /// If this store has
    ///
    /// `{10: "John Doe", 12: "George Mason", 19: "Ali Canfield"}`,
    /// and the `other` store contains
    /// `{10: "Carpenter", 17: "Developer", 15: "Plumber",  19: "Artist" }`
    ///
    /// `join` will return
    ///
    /// `{10: ("John Doe", "Carpenter"),
    ///   19: ("Ali Canfield", "Artist")}`
    ///
    /// Note that, it may be more convenient to keep this relationship in a [crate::R11Store]
    /// if your stores don't use filtering
    /// ```rust
    ///
    /// use xvc_ecs::{XvcEntity, HStore};
    ///
    /// let mut store1 = HStore::<String>::new();
    /// store1.insert(10u128.into(), "John Doe".into());
    /// store1.insert(12u128.into(), "George Mason".into());
    /// store1.insert(19u128.into(), "Ali Canfield".into());
    ///
    /// let mut store2 = HStore::<String>::new();
    /// store2.insert(10u128.into(), "Carpenter".into());
    /// store2.insert(17u128.into(), "Developer".into());
    /// store2.insert(15u128.into(), "Plumber".into());
    /// store2.insert(19u128.into(), "Artist".into());
    ///
    /// let result = store1.join(store2);
    ///
    /// assert_eq!(result.len(), 2);
    /// assert_eq!(result[&10u128.into()], ("John Doe".into(), "Carpenter".into()));
    /// assert_eq!(result[&19u128.into()], ("Ali Canfield".into(), "Artist".into()));
    pub fn join<U>(&self, other: HStore<U>) -> HStore<(T, U)>
    where
        T: Storable,
        U: Storable,
    {
        let mut joined = HStore::<(T, U)>::new();
        self.map.iter().for_each(|(entity, value)| {
            if let Some(other_value) = other.get(entity) {
                joined.insert(*entity, (value.clone(), other_value.clone()));
            }
        });

        joined
    }

    /// returns a subset of the store defined by iterator of XvcEntity
    pub fn subset<I>(&self, keys: I) -> Result<HStore<T>>
    where
        I: Iterator<Item = XvcEntity>,
        T: Clone,
    {
        let mut map = HashMap::<XvcEntity, T>::with_capacity(self.len());
        for e in keys {
            if let Some(v) = self.get(&e) {
                map.insert(e, v.clone());
            } else {
                Error::CannotFindKeyInStore { key: e.to_string() }.warn();
            }
        }
        Ok(Self { map })
    }
    /// Creates a new map by calling the `predicate` with each value.
    ///
    /// `predicate` must be a function or closure that returns `bool`.
    ///
    /// It doesn't clone the values.
    pub fn filter<F>(&self, predicate: F) -> HStore<&T>
    where
        F: Fn(&XvcEntity, &T) -> bool,
    {
        let mut m = HashMap::<XvcEntity, &T>::new();
        for (e, v) in self.map.iter() {
            if predicate(e, v) {
                m.insert(*e, v);
            }
        }

        HStore::from(m)
    }

    /// Returns the first element of the map.
    pub fn first(&self) -> Option<(&XvcEntity, &T)> {
        self.map.iter().next()
    }
}

impl<T: Clone> HStore<&T> {
    /// Returns a new map by cloning the values.
    pub fn cloned(&self) -> HStore<T> {
        let mut map = HashMap::<XvcEntity, T>::with_capacity(self.len());
        for (e, v) in self.iter() {
            map.insert(*e, (*v).clone());
        }
        HStore::from(map)
    }
}

impl<T> IntoIterator for HStore<T> {
    type Item = (XvcEntity, T);
    type IntoIter = std::collections::hash_map::IntoIter<XvcEntity, T>;

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

impl<T: PartialEq> HStore<T> {
    /// Returns the entities for a `value`.
    ///
    /// There may be more than one entity for a given value, hence it returns a `Vec`.
    /// It uses internal reverse index for fast lookup.
    pub fn entities_for(&self, value: &T) -> Option<Vec<XvcEntity>>
    where
        T: PartialEq,
    {
        let entity_vec: Vec<XvcEntity> = self
            .map
            .iter()
            .filter_map(|(k, v)| if *v == *value { Some(*k) } else { None })
            .collect();
        if entity_vec.is_empty() {
            None
        } else {
            Some(entity_vec)
        }
    }

    /// Returns the first entity matched with [Self::entities_for]
    pub fn entity_by_value(&self, value: &T) -> Option<XvcEntity> {
        match self.entities_for(value) {
            Some(vec_e) => vec_e.first().copied(),
            None => None,
        }
    }
}

impl<T> From<(XvcEntity, T)> for HStore<T> {
    fn from((e, v): (XvcEntity, T)) -> Self {
        let mut store = HStore::<T>::new();
        store.insert(e, v);
        store
    }
}