dvcompute_branch/simulation/stream/
ops.rs

1// Copyright (c) 2020-2022  David Sorokin <davsor@mail.ru>, based in Yoshkar-Ola, Russia
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7use crate::simulation::stream::*;
8
9use dvcompute_utils::grc::Grc;
10
11/// It represents the source of `Stream` computations.
12#[must_use = "computations are lazy and do nothing unless to be run"]
13#[derive(Clone)]
14pub struct StreamFn<T> where T: 'static {
15    gen: Grc<Box<dyn Fn() -> Stream<T>>>
16}
17
18impl<T> StreamFn<T> {
19
20    /// Create a new source of computations.
21    #[inline]
22    pub fn new<F>(f: F) -> Self
23        where F: Fn() -> Stream<T> + 'static
24    {
25        StreamFn {
26            gen: Grc::new(Box::new(move || { f() }))
27        }
28    }
29
30    /// Get the next computation.
31    #[inline]
32    pub fn next(&self) -> Stream<T> {
33        (self.gen)()
34    }
35
36    /// Return the prefix of the stream of the specified length.
37    pub fn take(&self, n: isize) -> Self
38        where T: Clone + 'static
39    {
40        let gen = self.gen.clone();
41        StreamFn {
42            gen: Grc::new(Box::new(move || { gen().take(n) }))
43        }
44    }
45
46    /// Return the suffix of the stream after the specified first elements.
47    pub fn drop(&self, n: isize) -> Self
48        where T: Clone + 'static
49    {
50        let gen = self.gen.clone();
51        StreamFn {
52            gen: Grc::new(Box::new(move || { gen().take(n) }))
53        }
54    }
55}