fibonnaci_stream/lib.rs
1//! A lazily evaluated [futures stream](https://docs.rs/futures/*/futures/stream/trait.Stream.html)
2//! of Fibonnaci numbers.
3//!
4//! ## Usage
5//!
6//! ```rust,ignore
7//! extern crate fibonnaci_stream;
8//!
9//! use fibonnaci_stream::{FibError, Stream};
10//!
11//! fn main () {
12//! let mut stream = FibStream::new();
13//! stream.poll().and_then(|val| {
14//! assert_eq!(val, Async::Ready(Some(1)));
15//!
16//! stream.poll().and_then(|val| {
17//! assert_eq!(val, Async::Ready(Some(2)));
18//! Ok(())
19//! });
20//!
21//! Ok(())
22//! });
23//! }
24//! ```
25
26extern crate futures;
27
28pub use futures::Stream;
29use futures::{Async, Future, Poll};
30use std::error::Error;
31
32/// A lazily evaluated [futures stream] of Fibonnaci numbers.
33///
34/// ## Example
35/// ```rust
36/// extern crate fibonnaci_stream;
37/// extern crate futures;
38///
39/// use futures::{Async, Stream}; // Stream must be in scope here for trait to work
40/// use fibonnaci_stream::Stream as FibStream;
41///
42/// fn main () {
43/// let mut stream = FibStream::new();
44/// stream.poll().and_then(|val| {
45/// assert_eq!(val, Async::Ready(Some(1)));
46/// stream.poll().and_then(|val| {
47/// assert_eq!(val, Async::Ready(Some(2)));
48/// Ok(())
49/// });
50/// Ok(())
51/// });
52/// }
53/// ```
54/// [futures stream]: (https://docs.rs/futures/*/futures/stream/trait.Stream.html)
55#[derive(Debug)]
56pub struct FibStream {
57 prev: u64,
58 num: u64,
59}
60
61impl FibStream {
62 /// Creates a new Fibonnaci stream.
63 ///
64 /// This method initializes the stream to start at 1 and continues the
65 /// sequence from there.
66 pub fn new() -> FibStream {
67 FibStream { prev: 0, num: 1 }
68 }
69}
70
71impl Stream for FibStream {
72 type Item = u64;
73 type Error = Box<Error>;
74
75 fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
76 let res = self.prev + self.num;
77 self.prev = self.num;
78 self.num = res;
79 Ok(Async::Ready(Some(res)))
80 }
81}
82
83impl Future for FibStream {
84 type Item = u64;
85 type Error = Box<Error>;
86
87 fn poll(&mut self) -> Result<Async<u64>, Box<Error>> {
88 let res = self.prev + self.num;
89 self.prev = self.num;
90 self.num = res;
91 Ok(Async::Ready(res))
92 }
93}