swarm_pool 0.2.0

Optimized object pooling system for Rust
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
//! An object pooling system optimized for perfomance.
//! 
//! The pooling system manages object instances of a cutom type,
//! and provides update loops to iterate over them.
//! 
//! In order to create a new swarm pool, you need to define what your `pool object` and `swarm properties` types
//! are going to look like. Your `pool object` must at leas implement the Default and Clone traits 
//! from the standard library. The `swarm properties`, on the other hand, does not depend on any traits.
//! 
//! # Basic swarm setup example
//! ```
//! extern crate swarm_pool;
//! use swarm_pool::Swarm;
//! 
//! // create an object you want to pool
//! #[derive(Default, Clone)]     
//! pub struct MyPoolObject { 
//!     pub name: &'static str,
//!     pub value: usize,               
//! }
//! 
//! // create properties you want to share with pooled objects
//! pub struct MySwarmProperties;
//! 
//! fn main() {
//!     let swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, MySwarmProperties);
//!     assert!(swarm.capacity() == 10);
//! }
//! ```
//! 
//! The swarm is now ready to be used. First of all we need to Spawn new pool instances. In reality all
//! objects in the pool are allready created and are waiting to be used. This means that all objects (
//! from 0 up to, but not including, the maximum capacity) can be accessed through the fetch() methode.
//! The difference between spawned and non-spawned pool objects is that spawned object are included in all
//! of the Swarm pools iterator methodes and non-spawned object are not.
//!
//! # Spawning and looping
//! ```
//! # extern crate swarm_pool;
//! # use swarm_pool::Swarm;

//! # #[derive(Default, Clone)]
//! # pub struct MyPoolObject {      
//! #     pub name: &'static str,     
//! #     pub value: usize,    
//! # }

//! let mut swarm = Swarm::<MyPoolObject, _>::new(10, ());
//! let spawn1 = swarm.spawn().unwrap();
//! let spawn2 = swarm.spawn().unwrap();
//!   
//! assert_eq!(swarm.fetch_ref(&spawn1).value, 0);
//! assert_eq!(swarm.fetch_ref(&spawn2).value, 0);
//!
//! swarm.for_each(|obj| {
//!     obj.value = 42;
//! });
//!
//! assert_eq!(swarm.fetch_ref(&spawn1).value, 42);
//! assert_eq!(swarm.fetch_ref(&spawn2).value, 42);
//! ```
//!
//! The real power of this library is not just looping through a few object instances, it is controlling and cross referencing them.
//! There are 2 powerful methodes that can be used to do so: `Swarm.for_all()` and `Swarm.update()`.
//! Both have their advantages and disadvantages, `for_all` loop is fast (equal to a standard vec for loop) but cannot spawn nor kill
//! pool objects, `update` is easy to use, gives full control, but is slow (less than half the speed).
//!
//! # Cross referencing using for_all & update
//! ```
//! # extern crate swarm_pool;
//! # use swarm_pool::{ Swarm, Spawn };

//! # #[derive(Default, Clone)]
//! # pub struct MyPoolObject {      
//! #     pub name: &'static str,     
//! #     pub value: usize,          
//! # }

//! // change properties to contain references to our spawned pool objects
//! pub struct MySwarmProperties { 
//!     john: Option<Spawn>, 
//!     cristy: Option<Spawn>,
//! }
//!
//! let properties = MySwarmProperties { john: None, cristy: None };
//! 
//! let mut swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, properties);
//! let s_john = swarm.spawn().unwrap();
//! let s_cristy = swarm.spawn().unwrap();
//!
//! swarm.properties.john = Some(s_john.mirror());
//! swarm.properties.cristy = Some(s_cristy.mirror());
//!
//! swarm.fetch(&s_john).name = "John";
//! swarm.fetch(&s_cristy).name = "Cristy";
//!
//! swarm.for_all(|target, pool, properties| {
//!
//!     // john tells critsy to have a value of 2
//!     if pool[*target].name == "John" { 
//!         if let Some(cristy) = &properties.cristy {
//!             pool[cristy.pos()].value = 2; 
//!         }
//!     }
//!     // cristy tells john to have a value of 1
//!     if pool[*target].name == "Cristy" { 
//!         if let Some(john) = &properties.john {
//!             pool[john.pos()].value = 1; 
//!         }
//!     }
//! });
//!
//! assert_eq!(swarm.fetch_ref(&s_john).value, 1);
//! assert_eq!(swarm.fetch_ref(&s_cristy).value, 2);
//!
//! swarm.update(|ctl| {
//!     let name = ctl.target().name;
//!     let cristy = ctl.properties.cristy.as_ref().unwrap().mirror();
//!     let john = ctl.properties.john.as_ref().unwrap().mirror();
//!
//!     // john tells critsy to have a value of 4
//!     if name == "John" { 
//!         ctl.fetch(&cristy).value = 4; 
//!     }
//!     // cristy tells john to have a value of 5
//!     if name == "Cristy" { 
//!         ctl.fetch(&john).value = 5; 
//!     }
//! });
//!
//! assert_eq!(swarm.fetch_ref(&s_john).value, 5);
//! assert_eq!(swarm.fetch_ref(&s_cristy).value, 4);
//! ```
//!
//! There are many more functionalities included in the Swarm and SwarmControl types. 
//! The documentation on the examples above or other functionalities this library provides are more in depth
//! and should be read, for writing them out was a lot of work ;)


#[allow(dead_code)]
mod tests;
pub mod control;
pub mod types;
//pub mod tools;

use control::SwarmControl;
pub use types::*;

/// The actual Swarm pool
pub struct Swarm<ItemType, Properties> {
    pool: Vec<ItemType>,
    spawns: Vec<Spawn>,
    free: Vec<Spawn>,
    len: usize,
    max: usize,
    order: Vec<usize>,
    factories: Vec<Factory<ItemType, Properties>>,

    pub properties: Properties,
}

impl<ItemType: Default + Clone, Properties> Swarm<ItemType, Properties> {

    /// Create a new Swarm object pool
    /// 
    /// The maximum `capacity` of the pool is defined here and cannot be changed aferwards, 
    /// This is the number of instances you can span.
    /// 
    /// You can add custom swarm `properties` for sharing values between spawned
    /// instances while iterating over these spawns.
    /// 
    /// # Example
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::Swarm;
    /// 
    /// // create an object you want to pool
    /// // Swarm uses Copy and therfore only accepts Sized properties!
    /// // This means types such as String and Vec aren't allowed
    /// // The tools module has a few tools that deal with this
    
    /// #[derive(Default, Clone)]     
    /// pub struct MyPoolObject {           
    ///     pub name: &'static str,              
    ///     pub value: usize,               
    /// }
    /// 
    /// // create properties you want to share with pooled objects
    /// pub struct MySwarmProperties;
    /// 
    /// let swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, MySwarmProperties);
    /// assert!(swarm.capacity() == 10);
    /// ```
    pub fn new(capacity: usize, properties: Properties) -> Self {
        let mut spawns = Vec::<Spawn>::with_capacity(capacity);
        let mut order = Vec::<usize>::with_capacity(capacity);

        for i in 0..capacity { 
            let tag = Spawn::new(i);
            spawns.push(tag);
            order.push(i);
        }

        Swarm { 
            pool: vec![ItemType::default(); capacity],
            spawns,
            free: Vec::<Spawn>::with_capacity(capacity),
            len: 0,
            max: capacity,
            order,
            properties,
            factories: Vec::new(),
        }
    }
    /// Create a new spawn for every item in the `items` list and gives
    /// it that value.
    /// 
    /// # Example
    /// ```
    ///     extern crate swarm_pool;
    ///     use swarm_pool::{ Swarm, Spawn };
    /// 
    ///     let mut swarm = Swarm::<u8, _>::new(10, ());
    ///     swarm.populate(&[5, 4, 3, 2, 1]);
    ///     
    ///     assert_eq!(swarm.count(), 5);
    ///     assert_eq!(*swarm.fetch_raw(&0), 5);
    /// ```
    pub fn populate(&mut self, items: &[ItemType]) {
        for item in items {
            if let Some(s) = self.spawn() {
                *self.fetch(&s) = item.clone();
            }
        }
    }
    
    pub(crate) fn control(&mut self) -> SwarmControl<ItemType, Properties> {
        SwarmControl {
            order: &mut self.order,
            pos: 0,
            len: self.len,
            max: &self.max, 
            spawns: &mut self.spawns, 
            free: &mut self.free,

            pool: &mut self.pool, 
            properties: &mut self.properties,
        }
    }

    /// Add methodes as factories to the swarm that can be used to create
    /// pool instances with specific values. The newly spawned instance is
    /// passed through the added methode when using `spawn_type(type_def)`, and can 
    /// be altered by the factory methode.
    /// 
    /// This can be useful for creating pool instances of a different type
    /// 
    /// # Example
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::Swarm;
    /// 
    /// #[derive(Default, Copy, Clone)]
    /// pub struct Minion {
    ///     name: &'static str,
    ///     value: usize,
    /// }
    /// 
    /// type UnitNames = (&'static str, &'static str);
    ///
    /// fn soldier_factory(m: &mut Minion, n: &mut UnitNames) {
    ///     m.name = n.0;
    ///     m.value = 1;
    /// }
    ///
    /// fn truck_factory(m: &mut Minion, n: &mut UnitNames) {
    ///     m.name = n.1;
    ///     m.value = 2;
    /// }
    ///
    /// fn spawn_specific_type_by_factory_definition() {
    ///     let names: UnitNames = ("soldier", "truck");
    ///     let mut swarm = Swarm::<Minion, UnitNames>::new(10, names);
    ///
    ///     swarm.add_factory(0, soldier_factory);
    ///     swarm.add_factory(1, truck_factory);
    /// 
    ///     let soldier = swarm.spawn_type(0).unwrap();
    ///     let truck = swarm.spawn_type(1).unwrap();
    ///
    ///     assert_eq!(swarm.fetch_ref(&soldier).name, "soldier");
    ///     assert_eq!(swarm.fetch_ref(&soldier).value, 1);
    ///     assert_eq!(swarm.fetch_ref(&truck).name, "truck");
    ///     assert_eq!(swarm.fetch_ref(&truck).value, 2);
    /// }
    /// ``` 

    pub fn add_factory(&mut self, type_def: usize, factory_handler: FactoryHandler<ItemType, Properties>) {
        self.factories.push(Factory { type_def, methode: factory_handler })
    }

    /// Create a new pool instance. 
    /// Spawns are pool instances that will be included in the update loops 
    /// provided by Swarm, as long as they are active and not killed yet.
    /// 
    /// Returns None if the pool reached it's maximum capacity and 
    /// therefore could not spawn new instances
    /// 
    /// # Example
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::Swarm;
    /// 
    /// // create an object you want to pool
    /// #[derive(Default, Clone)] 
    /// pub struct MyPoolObject {
    ///     pub name: &'static str,
    ///     pub value: usize,
    /// }
    /// 
    /// // create properties you want to share with pooled objects
    /// pub struct MySwarmProperties;
    /// 
    /// fn main() {
    ///     let mut swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, MySwarmProperties);
    ///     let spawn = swarm.spawn();
    /// 
    ///     assert!(spawn.is_some());
    ///     assert_eq!(swarm.count(), 1);
    /// }
    /// ```
    pub fn spawn(&mut self) -> Option<Spawn> {
        let mut ctl = self.control();
        let result = ctl.spawn();
        self.len = ctl.len;
        result
    }

    /// Create a new pool instance with specific values. The instances values are
    /// set by passing it through a predefined factory. See `add_factory(type_def, methode)`
    /// 
    /// # Example
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::Swarm;
    /// 
    /// #[derive(Default, Copy, Clone)]
    /// pub struct Minion {
    ///     name: &'static str,
    ///     value: usize,
    /// }
    /// 
    /// type UnitNames = (&'static str, &'static str);
    ///
    /// fn soldier_factory(m: &mut Minion, n: &mut UnitNames) {
    ///     m.name = n.0;
    ///     m.value = 1;
    /// }
    ///
    /// fn truck_factory(m: &mut Minion, n: &mut UnitNames) {
    ///     m.name = n.1;
    ///     m.value = 2;
    /// }
    ///
    /// fn spawn_specific_type_by_factory_definition() {
    ///     let names: UnitNames = ("soldier", "truck");
    ///     let mut swarm = Swarm::<Minion, UnitNames>::new(10, names);
    /// 
    ///     swarm.add_factory(0, soldier_factory);
    ///     swarm.add_factory(1, truck_factory);
    ///
    ///     let soldier_1 = swarm.spawn_type(0).unwrap();
    ///     let truck_1 = swarm.spawn_type(1).unwrap();
    ///     let truck_2 = swarm.spawn_type(1).unwrap();
    ///     let soldier_2 = swarm.spawn_type(0).unwrap();
    ///
    ///     assert_eq!(swarm.fetch_ref(&soldier_1).name, "soldier");
    ///     assert_eq!(swarm.fetch_ref(&soldier_2).name, "soldier");
    ///     assert_eq!(swarm.fetch_ref(&truck_1).name, "truck");
    ///     assert_eq!(swarm.fetch_ref(&truck_2).name, "truck");
    /// }
    /// ```
    
    pub fn spawn_type(&mut self, type_def: usize) -> Option<Spawn> {
        let some_spawn = self.spawn().clone();

        if let (Some(factory), Some(spawn)) = (
            self.factories
                .iter_mut()
                .find(|x| x.type_def == type_def),
            some_spawn
        ) {
            (factory.methode)(&mut self.pool[spawn.0.borrow().pos], &mut self.properties);
            Some(spawn.mirror())
        }
        else {
            None
        }
    }

    /// Remove a spawn instance from the swarm pool update loops
    /// 
    /// # Example
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::Swarm;
    /// 
    /// // create an object you want to pool
    /// #[derive(Default, Clone)] 
    /// pub struct MyPoolObject {
    ///     pub name: &'static str,
    ///     pub value: usize,
    /// }
    /// 
    /// // create properties you want to share with pooled objects
    /// pub struct MySwarmProperties;
    /// 
    /// fn main() {
    ///     let mut swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, MySwarmProperties);
    ///     let spawn = swarm.spawn();
    /// 
    ///     assert!(spawn.is_some());
    ///     assert_eq!(swarm.count(), 1);
    /// 
    ///     swarm.kill(&spawn.unwrap());
    ///     assert_eq!(swarm.count(), 0);
    /// }
    /// ```
    pub fn kill(&mut self, target: &Spawn) {
        let mut ctl = self.control();
        let reset_order = target.pos();
        ctl.kill(target);
        self.len = ctl.len;
        self.order[reset_order] = reset_order;
    }

    /// Remove all spawn instances
    pub fn kill_all(&mut self) {
        for spawn in &mut self.spawns {
            spawn.0.borrow_mut().active = false;
        }
        self.len = 0;
    }

    /// Returns a spawn reference object from an object position within the pool
    pub fn fetch_spawn(&self, pos: &ObjectPosition) -> Spawn {
        self.spawns[*pos].mirror()
    }

    /// Returns a mutable reference to an object from the Swarm pool.
    /// The supplied Spawn reference object points out which object to return.
    pub fn fetch(&mut self, spawn: &Spawn) -> &mut ItemType { 
        &mut self.pool[spawn.0.borrow().pos]
    }

    /// Returns a immutable reference to an object from the Swarm pool.
    /// The supplied Spawn reference object points out which object to return.
    pub fn fetch_ref(&self, spawn: &Spawn) -> &ItemType { 
        &self.pool[spawn.0.borrow().pos]
    }

    /// Returns a mutable reference to an object from the Swarm pool.
    /// The supplied object position points out which object to return.
    /// 
    /// NOTE: when killing objects the order of object positions change,
    /// Use fetch() instead of fetch_raw() if you are going to kill spawns 
    /// at any point in your code.
    pub fn fetch_raw(&mut self, pos: &ObjectPosition) -> &mut ItemType { 
        &mut self.pool[*pos]
    }

    /// Returns the number of spawned instances currently availeble
    pub fn count(&self) -> usize { self.len }

    /// Returns the maximum number of instances that can be spawned
    pub fn capacity(&self) -> usize { self.max }
    

    // update iterators

    /// Loops through all spawned instances and returns them via a callback
    /// handler. The callback handler is supplied with a mutable reference of these
    /// instances so that the object data of each looped instance can be changed.
    pub fn enumerate(&mut self, handler: EnumerateHandler<ItemType>) {
        let len = self.len;
        let mut i = 0;

        while &i < &len {
            handler(&i, &mut self.pool[i]);
            i += 1;
        }
    }

    /// Loops through all spawned instances and returns them via a callback
    /// handler. The callback handler is supplied with a mutable reference of these
    /// instances so that the object data of each looped instance can be changed.
    ///
    /// # Example
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::{ Swarm, Spawn };
    ///
    /// // create an object you want to pool
    /// #[derive(Default, Clone)] 
    /// pub struct MyPoolObject {
    ///     pub value: usize,
    /// }
    /// let mut swarm = Swarm::<MyPoolObject, _>::new(10, ());
    /// let spawn1 = swarm.spawn().unwrap();
    /// let spawn2 = swarm.spawn().unwrap();
    ///   
    /// assert_eq!(swarm.fetch_ref(&spawn1).value, 0);
    /// assert_eq!(swarm.fetch_ref(&spawn2).value, 0);
    ///
    /// swarm.for_each(|obj| {
    ///     obj.value = 42;
    /// });
    ///
    /// assert_eq!(swarm.fetch_ref(&spawn1).value, 42);
    /// assert_eq!(swarm.fetch_ref(&spawn2).value, 42);
    /// ```
    pub fn for_each(&mut self, handler: ForEachHandler<ItemType>) {
        let len = self.len;
        let mut i = 0;

        while &i < &len {
            handler(&mut self.pool[i]);
            i += 1;
        }
    }
    
    /// Loops through all spawned instances and returns their object position via a 
    /// callback handler. The callback handler also hands out a mutable reference to
    /// the object pool and the swarm properties object.
    /// 
    /// NOTE: This methode is quite fast (faster than the foreach or update methodes), but
    /// at the cost that is uses object positions. When an object is killed, the order 
    /// of some object positions are changed. Because of that, no tools for spawning nor 
    /// killing are supplied, which makes it impossible to do so within this loop.
    ///
    /// # Examples
    /// ## Basic usecase
    /// ```
    /// extern crate swarm_pool;
    /// use swarm_pool::{ Swarm, Spawn };
    ///
    /// // create an object you want to pool
    /// #[derive(Default, Clone)] 
    /// pub struct MyPoolObject {
    ///     pub name: &'static str,
    ///     pub value: usize,
    /// }
    /// 
    /// let mut swarm = Swarm::<MyPoolObject, _>::new(10, ());
    /// let spawn1 = swarm.spawn().unwrap();
    /// let spawn2 = swarm.spawn().unwrap();
    ///
    /// assert_eq!(swarm.fetch_ref(&spawn1).value, 0);
    /// assert_eq!(swarm.fetch_ref(&spawn2).value, 0);
    ///
    /// swarm.for_all(|target, list, _props| {
    ///     list[*target].value = *target + 1;
    /// });
    ///
    /// assert_eq!(swarm.fetch_ref(&spawn1).value, 1);
    /// assert_eq!(swarm.fetch_ref(&spawn2).value, 2);
    /// ```
    ///
    /// ## Using shared properties
    /// ```
    /// # extern crate swarm_pool;
    /// # use swarm_pool::{ Swarm, Spawn };
    /// # // create an object you want to pool
    /// # #[derive(Default, Clone)] 
    /// # pub struct MyPoolObject { pub name: &'static str, pub value: usize, }
    /// # //
    /// // create properties you want to share with pooled objects
    /// pub struct MySwarmProperties { 
    ///     counter: usize 
    /// }
    /// 
    /// let properties = MySwarmProperties { counter: 0 };
    ///
    /// let mut swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, properties);
    /// let spawn1 = swarm.spawn().unwrap();
    /// let spawn2 = swarm.spawn().unwrap();
    ///
    /// swarm.for_all(|target, list, props| {
    ///     props.counter += 1;
    ///     list[*target].value = props.counter;
    /// });
    ///
    /// assert_eq!(swarm.properties.counter, 2);
    /// assert_eq!(swarm.fetch_ref(&spawn1).value, 1);
    /// assert_eq!(swarm.fetch_ref(&spawn2).value, 2);
    /// ```
    ///
    /// ## Cross referencing between objects
    /// ```
    /// # extern crate swarm_pool;
    /// # use swarm_pool::{ Swarm, Spawn };
    /// # #[derive(Default, Clone)] 
    /// # pub struct MyPoolObject { pub name: &'static str, pub value: usize }
    /// # //
    /// // create properties you want to share with pooled objects
    /// pub struct MySwarmProperties { 
    ///     john: Option<Spawn>, 
    ///     cristy: Option<Spawn>,
    /// }
    ///
    /// let properties = MySwarmProperties { john: None, cristy: None };
    /// 
    /// let mut swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, properties);
    /// let s_john = swarm.spawn().unwrap();
    /// let s_cristy = swarm.spawn().unwrap();
    ///
    /// swarm.properties.john = Some(s_john.mirror());
    /// swarm.properties.cristy = Some(s_cristy.mirror());
    ///
    /// swarm.fetch(&s_john).name = "John";
    /// swarm.fetch(&s_cristy).name = "Cristy";
    ///
    /// swarm.for_all(|target, list, props| {
    ///
    ///     // john tells critsy to have a value of 2
    ///     if list[*target].name == "John" { 
    ///         if let Some(cristy) = &props.cristy {
    ///             list[cristy.pos()].value = 2; 
    ///         }
    ///     }
    ///     // cristy tells john to have a value of 1
    ///     if list[*target].name == "Cristy" { 
    ///         if let Some(john) = &props.john {
    ///             list[john.pos()].value = 1; 
    ///         }
    ///     }
    /// });
    ///
    /// assert_eq!(swarm.fetch_ref(&s_john).value, 1);
    /// assert_eq!(swarm.fetch_ref(&s_cristy).value, 2);
    /// ```
    pub fn for_all(&mut self, handler: ForAllHandler<ItemType, Properties>) {
        let len = self.len;
        let mut i = 0;

        while &i < &len {
            handler(&i, &mut self.pool, &mut self.properties);
            i += 1;
        }
    }

    /// Loops through all spawned instances and returns a `SwarmControl` object via a 
    /// callback handler. The swarm control objects lets you edit the currently updated object
    /// as well as spawning and killing instances.
    /// 
    /// NOTE: This methode is slower then the other loops, but gives you full control over
    /// the swarm.
    /// 
    ///
    /// # Examples
    /// ##  Cross Referencing between objects
    /// ```
    /// # extern crate swarm_pool;
    /// # use swarm_pool::{ Swarm, Spawn };
    /// // create an object you want to pool
    /// #[derive(Default, Clone)] 
    /// pub struct MyPoolObject { 
    ///     pub name: &'static str,
    ///     pub value: usize,
    /// }
    /// 
    /// // create properties you want to share with pooled objects
    /// pub struct MySwarmProperties {
    ///     john: Option<Spawn>,
    ///     cristy: Option<Spawn>,
    /// }
    ///
    /// let properties = MySwarmProperties {
    ///     john: None,
    ///     cristy: None,
    /// };
    /// 
    /// let mut swarm = Swarm::<MyPoolObject, MySwarmProperties>::new(10, properties);
    ///
    /// let s_john = swarm.spawn().unwrap();
    /// let s_cristy = swarm.spawn().unwrap();
    ///
    /// swarm.properties.john = Some(s_john.mirror());
    /// swarm.properties.cristy = Some(s_cristy.mirror());
    ///
    /// swarm.fetch(&s_john).name = "John";
    /// swarm.fetch(&s_cristy).name = "Cristy";
    ///
    /// swarm.update(|ctl| {
    ///     let name = ctl.target().name;
    ///     let cristy = ctl.properties.cristy.as_ref().unwrap().mirror();
    ///     let john = ctl.properties.john.as_ref().unwrap().mirror();
    ///
    ///     // john tells critsy to have a value of 2
    ///     if name == "John" { 
    ///         ctl.fetch(&cristy).value = 2; 
    ///     }
    ///     // cristy tells john to have a value of 1
    ///     if name == "Cristy" { 
    ///         ctl.fetch(&john).value = 1; 
    ///     }
    /// });
    ///
    /// assert_eq!(swarm.fetch_ref(&s_john).value, 1);
    /// assert_eq!(swarm.fetch_ref(&s_cristy).value, 2);
    /// ```
    pub fn update(&mut self, handler: UpdateHandler<ItemType, Properties>) {
        let mut i = 0;
        let len = self.len;
        let mut ctl = self.control();

        while &i < &len {
            ctl.pos = ctl.order[*&i];
            handler(&mut ctl);
            ctl.order[*&i] = i; 
            i += 1;
        }
        self.len = ctl.len;
    }
}