Async Entity Component System based on the ideas of specs (https://github.com/amethyst/specs)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
1.9 KiB

  1. use crate::{
  2. core::{Collector, Executor},
  3. Consumer, Folder, ParallelIterator,
  4. };
  5. use super::noop::NoOpReducer;
  6. pub struct ForEach<I, F> {
  7. iterator: I,
  8. operation: F,
  9. }
  10. impl<I, F> ForEach<I, F> {
  11. pub fn new(iterator: I, operation: F) -> Self {
  12. Self {
  13. iterator,
  14. operation,
  15. }
  16. }
  17. }
  18. impl<I, F> Collector for ForEach<I, F>
  19. where
  20. I: ParallelIterator,
  21. F: Fn(I::Item) + Sync + Send + Copy,
  22. {
  23. type Iterator = I;
  24. type Consumer = ForEachConsumer<F>;
  25. fn exec_with<E>(self, executor: E) -> E::Result
  26. where
  27. E: Executor<Self::Iterator, Self::Consumer>,
  28. {
  29. let iterator = self.iterator;
  30. let operation = self.operation;
  31. let consumer = ForEachConsumer { operation };
  32. iterator.drive(executor, consumer)
  33. }
  34. }
  35. pub struct ForEachConsumer<F> {
  36. operation: F,
  37. }
  38. impl<F, T> Consumer<T> for ForEachConsumer<F>
  39. where
  40. F: Fn(T) + Sync + Send + Copy,
  41. {
  42. type Folder = ForEachConsumer<F>;
  43. type Reducer = NoOpReducer;
  44. type Result = ();
  45. fn split_off_left(&self) -> (Self, NoOpReducer) {
  46. (
  47. ForEachConsumer {
  48. operation: self.operation,
  49. },
  50. NoOpReducer,
  51. )
  52. }
  53. fn into_folder(self) -> Self {
  54. self
  55. }
  56. }
  57. impl<F, T> Folder<T> for ForEachConsumer<F>
  58. where
  59. F: Fn(T) + Sync + Send + Copy,
  60. {
  61. type Result = ();
  62. fn consume(self, item: T) -> Self {
  63. (self.operation)(item);
  64. self
  65. }
  66. fn consume_iter<I>(self, iter: I) -> Self
  67. where
  68. I: IntoIterator<Item = T>,
  69. {
  70. iter.into_iter().for_each(self.operation);
  71. self
  72. }
  73. fn complete(self) {}
  74. }
  75. #[cfg(test)]
  76. mod tests {
  77. use super::*;
  78. use crate::*;
  79. #[test]
  80. fn test_for_each() {
  81. (0..10usize)
  82. .into_par_iter()
  83. .for_each(&|j| {
  84. println!("{}", j);
  85. })
  86. .exec();
  87. }
  88. }