├── .gitignore
├── .travis.yml
├── Cargo.toml
├── Readme.md
└── src
└── lib.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | Cargo.lock
2 | target
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: rust
2 | matrix:
3 | include:
4 | - rust: nightly
5 | env: TEST_SUITE=suite_nightly
6 | script:
7 | - cargo build --verbose
8 | - cargo test --verbose
9 | - if [ "$TEST_SUITE" = "suite_nightly" ]; then cargo bench --verbose; fi
10 | after_success: |
11 | [ $TRAVIS_BRANCH = master ] &&
12 | [ $TRAVIS_PULL_REQUEST = false ] &&
13 | cargo doc &&
14 | echo "" > target/doc/index.html &&
15 | sudo pip install ghp-import &&
16 | ghp-import -n target/doc &&
17 | git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
18 | env:
19 | global:
20 | secure: oTPbc4GK5XlNcmguB4D7xXQ4W/PDjlbxsN8der0ouCF+2m//01RJL3jXMK6rDjXNm25E214ouzyJStg5iiW+OVck9QhBGpqNKREm4NJFNr1Yk0yOj+5s69a8mrgwId0o6e2nGDewFo0h/RZ+OqokJLABcNyk08tQ1wnDxJZUkANYNO/NwaEvMeVTMIyc2+0afzUgU46kbWDCILPS157CmoJGD3NajEgKK4vmiwfQt8loTmlU45i1nldOpDZX3uOCshyyyC3cVwOUKF2SiC9nd3xm4PceHZ3VRhZkd7IAA2U8KrGEyE+uyZ+9ip7znWExmHDvaz7szQ5knNQgI6M2CExeSTzQk5onWVMgHPS94g63dkI6qBd6NHAA+5TYl4itNY1euDZpcV3sdLCqZ0aXKX3NQ7kUj2CzN5bRaysf3b75wEY7dC0R/ie7hzFNrHI+cnE/MqN0ZkXjORR4YxYIv09V8k3dfNlRRSpU73g3GxsEVOmEjfw2SfTAw38dke+QAe+zMJCnHbeX+fQDa6SSvOi0jT1SzpGduC6/jAtsImf7PnpJVVXZkvv56mCQ6v4xSfD2jObeftpCwjsEoXj884E73jMCKgKuzoaRyE14CjGSpbFoGcO93Pkyh/GeO+0P1IZEA2t0K4RUL/UOetYkazibr4TB2eqdUfCPjBfRVpY=
21 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tangle"
3 | version = "0.4.0"
4 | description = "Future implementation for Rust"
5 | homepage = "https://github.com/thehydroimpulse/tangle"
6 | documentation = "https://github.com/thehydroimpulse/tangle"
7 | repository = "https://github.com/thehydroimpulse/tangle"
8 | keywords = ["future", "promise", "asynchronous"]
9 | license = "MIT"
10 | authors = ["Daniel Fagnan "]
11 |
12 | [dependencies]
13 | lazy_static = "0.1.15"
14 | threadpool = "1.0.0"
15 | num_cpus = "0.2.11"
16 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 | # Tangle
2 |
3 | [](https://travis-ci.org/thehydroimpulse/tangle)
4 |
5 | [Documentation (Master)](http://thehydroimpulse.github.io/tangle)
6 |
7 | Futures implementation in Rust based on Scala's Futures that runs in a thread pool. It allows composable asynchronous concurrency in a way that works nicely with existing Rust constructs.
8 |
9 | ## Getting Started
10 |
11 | Install tangle with Cargo:
12 |
13 | ```toml
14 | [dependencies]
15 | tangle = "0.4.0"
16 | ```
17 |
18 | Add the crate to your project:
19 |
20 | ```rust
21 | extern crate tangle;
22 | ```
23 |
24 | And require the only two types you need from this crate:
25 |
26 | ```rust
27 | use tangle::{Future, Async};
28 | ```
29 |
30 | ## Creating a Future
31 |
32 | **Using Values**
33 |
34 | The first way to create a future is through a unit, or an already resolved value. This will not require any threading and allows you to lift a value into a Future, making it composable.
35 |
36 | ```rust
37 | Future::unit(1);
38 | Future::unit("hello world".to_string());
39 | ```
40 |
41 | Future values must implement the `Send` trait regardless if threading is involved.
42 |
43 | **Using Closures**
44 |
45 | You may also create a Future through the use of a closure. The closure is expected to return the `Async` type which is an asynchronous version of `Result`.
46 |
47 | ```rust
48 | Future::new(move || {
49 | let result = // perform some heavy work here...
50 |
51 | Async::Ok(result);
52 | });
53 | ```
54 |
55 | **Using Channels**
56 |
57 | Channels are essentially the substitute to promises. Usually, promises are used for writing and futures are used for reading; however, Tangle replaces the writing part with Rust channels.
58 |
59 | You may let Tangle create the channel or you may pass the receiver-end yourself, using `::channel` and `::from_channel`, respectively.
60 |
61 | ```rust
62 | let (tx, future) = Future::channel();
63 |
64 | tx.send(123);
65 | ```
66 |
67 | Using an existing channel:
68 |
69 | ```rust
70 | use std::sync::mpsc::channel;
71 |
72 | let (tx, rx) = channel();
73 | let future = Future::from_channel(rx);
74 |
75 | tx.send(123);
76 | ```
77 |
78 | ## Resolving Futures
79 |
80 | The point is to eventually get some sort of value back from the futures. You may either block on the future using the `.recv()` method, or you may chain using `and_then` (flat map) and `map`. The latter methods are all asynchronous and continue running in a thread pool, they also themselves return new futures.
81 |
82 | ### Blocking
83 |
84 | ```rust
85 | let future = Future::unit(123);
86 |
87 | // recv() returns `Result`
88 | assert_eq!(future.recv().unwrap(), 123);
89 | ```
90 |
91 | ### `and_then`
92 |
93 | You need to wrap the value back into an `Async` type.
94 |
95 | ```rust
96 | let future = Future::unit(123);
97 |
98 | future.and_then(move |n| {
99 | Async::Ok(n * 100)
100 | });
101 | ```
102 |
103 | You may also dynamically compose futures using `Async::Continue`.
104 |
105 | ```rust
106 | let future = Future::unit(123);
107 |
108 | future.and_then(move |n| {
109 | // ...
110 | Async::Continue(find_user_id("thehydroimpulse"))
111 | });
112 |
113 | fn find_user_id(name: &str) -> Future {
114 | // ...
115 | return Async::Ok(...);
116 | }
117 | ```
118 |
119 | ### `map`
120 |
121 | ```rust
122 | let future = Future::unit(123);
123 |
124 | future.map(move |n| n * 100);
125 | ```
126 |
127 | ## Error Handling
128 |
129 | TODO: Write documentation.
130 |
131 | ## License
132 |
133 | The MIT License (MIT)
134 | Copyright (c) 2016 Daniel Fagnan
135 |
136 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
137 |
138 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
139 |
140 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
141 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | //! A lightweight futures package inspired by Scala. The goals are to provide
2 | //! a simple interface for creating futures and, most importantly, composing multiple
3 | //! asynchronous actions together. Thus, all futures return `Async` which is
4 | //! an asynchronous equivalent to `Result`, the only difference being that
5 | //! an extra variant `Continue(Future)` allows for composition.
6 |
7 | use std::thread;
8 | use std::sync::mpsc::{Receiver, Sender, channel};
9 | use std::sync::Mutex;
10 | use std::convert;
11 | use std::mem;
12 | use threadpool::ThreadPool;
13 |
14 | pub use Async::Continue;
15 |
16 | #[macro_use]
17 | extern crate lazy_static;
18 | extern crate threadpool;
19 | extern crate num_cpus;
20 |
21 | lazy_static! {
22 | static ref POOL: Mutex = Mutex::new(ThreadPool::new(num_cpus::get()));
23 | }
24 |
25 | /// Asynchronous version of `Result` that allows for future composition. Additional
26 | /// macros are provided to work with both `Async` and `Result`.
27 | #[derive(Debug)]
28 | pub enum Async {
29 | Ok(T),
30 | Err(E),
31 | Continue(Future)
32 | }
33 |
34 | impl Async {
35 | pub fn unwrap(self) -> T {
36 | match self {
37 | Async::Ok(t) => t,
38 | _ => panic!("cannot unwrap `Async` of Err or Continue.")
39 | }
40 | }
41 |
42 | pub fn map U>(self, f: F) -> Async {
43 | match self {
44 | Async::Ok(t) => Async::Ok(f(t)),
45 | Async::Err(e) => Async::Err(e),
46 | Async::Continue(cont) => panic!("Cannot map on `Async::Continue`. Use `map_future` for that.")
47 | }
48 | }
49 |
50 | pub fn map_err U>(self, f: F) -> Async {
51 | match self {
52 | Async::Ok(t) => Async::Ok(t),
53 | Async::Err(e) => Async::Err(f(e)),
54 | Async::Continue(cont) => panic!("Cannot map on `Async::Continue`. Use `map_future` for that.")
55 | }
56 | }
57 |
58 | pub fn is_err(&self) -> bool {
59 | match self {
60 | &Async::Err(_) => true,
61 | _ => false
62 | }
63 | }
64 |
65 | pub fn is_future(&self) -> bool {
66 | match self {
67 | &Async::Continue(_) => true,
68 | _ => false
69 | }
70 | }
71 |
72 | pub fn is_ok(&self) -> bool {
73 | match self {
74 | &Async::Ok(_) => true,
75 | _ => false
76 | }
77 | }
78 | }
79 |
80 | /// ok!(123)
81 | #[macro_export]
82 | macro_rules! ok {
83 | ($expr:expr) => (Async::Ok($expr))
84 | }
85 |
86 | // err!(123)
87 | #[macro_export]
88 | macro_rules! err {
89 | ($expr:expr) => (Async::Err($expr))
90 | }
91 |
92 | /// compose!(future! {
93 | /// err!(123)
94 | /// })
95 | #[macro_export]
96 | macro_rules! compose {
97 | ($expr:expr) => (Async::Err($expr))
98 | }
99 |
100 | #[macro_export]
101 | macro_rules! async {
102 | ($expr:expr) => (match $expr {
103 | Result::Ok(val) => val,
104 | Result::Err(err) => {
105 | use std::convert;
106 | return $crate::Async::Err(convert::From::from(err));
107 | }
108 | })
109 | }
110 |
111 | /// Create a `Future` with a slightly nicer syntax.
112 | ///
113 | /// ```notrust
114 | /// future! {
115 | /// Ok(123)
116 | /// }
117 | /// ```
118 | #[macro_export]
119 | macro_rules! future {
120 | ($x:expr) => {{
121 | Future::new(|| {
122 | $x
123 | })
124 | }}
125 | }
126 |
127 | #[derive(Debug)]
128 | pub enum PromiseState {
129 | Waiting,
130 | Resolved,
131 | Failed
132 | }
133 |
134 | #[derive(Debug)]
135 | pub struct Promise {
136 | chan: Sender>,
137 | rx: Option>>,
138 | state: PromiseState
139 | }
140 |
141 | impl Promise
142 | where T: Send + 'static,
143 | E: Send + 'static
144 | {
145 | /// ```
146 | /// use tangle::{Promise};
147 | /// let mut p = Promise::::new();
148 | ///
149 | /// p.future();
150 | /// ```
151 | pub fn new() -> Promise {
152 | let (tx, rx) = channel::>();
153 |
154 | Promise {
155 | chan: tx,
156 | rx: Some(rx),
157 | state: PromiseState::Waiting
158 | }
159 | }
160 |
161 | pub fn future(&mut self) -> Future {
162 | if let Some(rx) = mem::replace(&mut self.rx, None) {
163 | return Future::::from_async_channel(rx);
164 | } else {
165 | panic!("Unexpected None");
166 | }
167 | }
168 | }
169 |
170 | /// A value that will be resolved sometime into the future, asynchronously. `Future`s use
171 | /// an internal threadpool to handle asynchronous tasks.
172 | #[derive(Debug)]
173 | pub struct Future {
174 | receiver: Receiver>,
175 | read: bool
176 | }
177 |
178 | impl Future
179 | where T: Send + 'static,
180 | E: Send + 'static
181 | {
182 | /// ```
183 | /// use tangle::{Future, Async};
184 | ///
185 | /// Future::new(|| if true { Async::Ok(123) } else { Async::Err("Foobar") });
186 | /// ```
187 | pub fn new(f: F) -> Future
188 | where F: FnOnce() -> Async + Send + 'static
189 | {
190 | let (tx, rx) = channel();
191 |
192 | POOL.lock().unwrap().execute(move || { tx.send(f()); });
193 |
194 | Future:: {
195 | receiver: rx,
196 | read: false
197 | }
198 | }
199 |
200 | pub fn from_async_channel(receiver: Receiver>) -> Future {
201 | Future:: {
202 | receiver: receiver,
203 | read: false
204 | }
205 | }
206 |
207 | pub fn channel() -> (Sender, Future) {
208 | let (ret_tx, ret_rx) = channel();
209 | let (tx, rx) = channel();
210 |
211 | POOL.lock().expect("error acquiring a lock.").execute(move || {
212 | match ret_rx.recv() {
213 | Ok(v) => { tx.send(Async::Ok(v)).expect("error sending on to the channel.") },
214 | Err(err) => { panic!("{:?}", err) }
215 | };
216 | });
217 |
218 | (ret_tx, Future:: {
219 | receiver: rx,
220 | read: false
221 | })
222 | }
223 |
224 | /// Create a new future from the receiving end of a native channel.
225 | ///
226 | /// ```
227 | /// use tangle::{Future, Async};
228 | /// use std::thread;
229 | /// use std::sync::mpsc::channel;
230 | ///
231 | /// let (tx, rx) = channel();
232 | /// Future::::from_channel(rx).and_then(|v| {
233 | /// assert_eq!(v, 1235);
234 | /// Async::Ok(())
235 | /// });
236 | /// tx.send(1235);
237 | /// ```
238 | pub fn from_channel(receiver: Receiver) -> Future {
239 | let (tx, rx) = channel();
240 |
241 | POOL.lock().expect("error acquiring a lock.").execute(move || {
242 | match receiver.recv() {
243 | Ok(v) => { tx.send(Async::Ok(v)).expect("error sending on to the channel.") },
244 | Err(err) => { panic!("{:?}", err) }
245 | };
246 | });
247 |
248 | Future:: {
249 | receiver: rx,
250 | read: false
251 | }
252 | }
253 |
254 | /// ```
255 | /// use tangle::{Future, Async};
256 | ///
257 | /// let f: Future = Future::unit(1);
258 | ///
259 | /// let purchase: Future = f.and_then(|num| Async::Ok(num.to_string()));
260 | ///
261 | /// match purchase.recv() {
262 | /// Ok(val) => assert_eq!(val, "1".to_string()),
263 | /// _ => panic!("unexpected")
264 | /// }
265 | /// ```
266 | pub fn and_then(self, f: F) -> Future
267 | where F: FnOnce(T) -> Async + Send + 'static,
268 | S: Send + 'static
269 | {
270 | let (tx, rx) = channel();
271 |
272 | POOL.lock().expect("error acquiring a lock.").execute(move || {
273 | match self.recv() {
274 | Ok(val) => { tx.send(f(val)); },
275 | Err(err) => { tx.send(Async::Err(err)); }
276 | }
277 | });
278 |
279 | Future:: {
280 | receiver: rx,
281 | read: false
282 | }
283 | }
284 |
285 | /// ```
286 | /// use tangle::{Future, Async};
287 | ///
288 | /// let f: Future = Future::unit(1);
289 | ///
290 | /// let purchase: Future = f.map(|num| num.to_string());
291 | ///
292 | /// match purchase.recv() {
293 | /// Ok(val) => assert_eq!(val, "1".to_string()),
294 | /// _ => panic!("unexpected")
295 | /// }
296 | /// ```
297 | pub fn map(self, f: F) -> Future
298 | where F: FnOnce(T) -> S + Send + 'static,
299 | S: Send + 'static
300 | {
301 | let (tx, rx) = channel();
302 |
303 | POOL.lock().expect("error acquiring a lock.").execute(move || {
304 | match self.recv() {
305 | Ok(val) => { tx.send(Async::Ok(f(val))); },
306 | Err(err) => { tx.send(Async::Err(err)); }
307 | }
308 | });
309 |
310 | Future:: {
311 | receiver: rx,
312 | read: false
313 | }
314 | }
315 |
316 | pub fn recv(self) -> Result {
317 | let val = self.receiver.recv().expect("error trying to wait for channel.");
318 |
319 | match val {
320 | Async::Ok(val) => Ok(val),
321 | Async::Err(err) => Err(err),
322 | Continue(f) => f.recv()
323 | }
324 | }
325 |
326 | /// Wrap a value into a `Future` that completes right away.
327 | ///
328 | /// ## Usage
329 | ///
330 | /// ```
331 | /// use tangle::Future;
332 | ///
333 | /// let _: Future = Future::unit(5);
334 | /// ```
335 | pub fn unit(val: T) -> Future {
336 | let (tx, rx) = channel();
337 |
338 | tx.send(Async::Ok(val));
339 |
340 | Future:: {
341 | receiver: rx,
342 | read: false
343 | }
344 | }
345 |
346 | /// ```
347 | /// use tangle::Future;
348 | ///
349 | /// let _: Future = Future::err("foobar");
350 | /// ```
351 | pub fn err(err: E) -> Future {
352 | let (tx, rx) = channel();
353 |
354 | tx.send(Async::Err(err));
355 |
356 | Future:: {
357 | receiver: rx,
358 | read: false
359 | }
360 | }
361 | }
362 |
363 | #[cfg(test)]
364 | mod tests {
365 | use super::*;
366 | use std::thread;
367 | use std::time::Duration;
368 | use std::sync::mpsc::{channel, Receiver, Sender};
369 |
370 | #[test]
371 | fn async_macro() {
372 | fn foo() -> Async {
373 | let v = Ok(123);
374 | let v = async!(v);
375 | assert_eq!(v, 123);
376 | Async::Ok(v)
377 | }
378 |
379 | foo();
380 | }
381 |
382 | #[test]
383 | fn async_macro_err() {
384 | fn foo() -> Async {
385 | let v = Err(123u32);
386 | let v = async!(v);
387 | Async::Ok(0)
388 | }
389 |
390 | assert!(foo().is_err());
391 | }
392 |
393 | #[test]
394 | fn async_map() {
395 | let val: Async = Async::Ok(123);
396 | match val.map(|x| x * 2) {
397 | Async::Ok(v) => assert_eq!(v, 246),
398 | _ => panic!("Unexpected error.")
399 | }
400 | }
401 |
402 | #[test]
403 | #[should_panic]
404 | fn async_map_fail() {
405 | let val: Async = Async::Continue(future! {
406 | Async::Ok(123)
407 | });
408 |
409 | val.map(|x| x * 2);
410 | }
411 |
412 | #[test]
413 | fn async_map_err() {
414 | let val: Async<(), u32> = Async::Err(1);
415 | match val.map_err(|x| x + 5) {
416 | Async::Err(e) => assert_eq!(e, 6),
417 | _ => panic!("Unexpected error")
418 | }
419 | }
420 |
421 | #[test]
422 | fn create_channel() {
423 | let (tx, future) = Future::::channel();
424 |
425 | tx.send(123);
426 |
427 | match future.recv() {
428 | Ok(v) => assert_eq!(v, 123),
429 | Err(err) => panic!("Unexpected case.")
430 | }
431 | }
432 |
433 | #[test]
434 | fn from_chan1() {
435 | let (tx, rx) = channel();
436 | let f: Future = Future::from_channel(rx);
437 |
438 | let f = f.map(|n| {
439 | assert_eq!(n, 555);
440 | n + 5
441 | }).map(|n| {
442 | assert_eq!(n, 560);
443 | n
444 | });
445 |
446 | // Resolve the future through the sender half of the channel.
447 | tx.send(555);
448 |
449 | assert_eq!(f.recv().unwrap(), 560);
450 | }
451 |
452 | #[test]
453 | fn to_future_macro() {
454 | future! {
455 | if true {
456 | Async::Ok(123)
457 | } else {
458 | Async::Err(5)
459 | }
460 | };
461 | }
462 |
463 | #[test]
464 | fn test_async() {
465 | let f: Future = future! { Async::Ok(5) };
466 |
467 | let next = f.and_then(|n| {
468 | thread::sleep(Duration::from_millis(50));
469 |
470 | Continue(Future::new(move || {
471 | thread::sleep(Duration::from_millis(100));
472 | Async::Ok(n * 100)
473 | }))
474 | });
475 |
476 | match next.recv() {
477 | Ok(n) => assert_eq!(n, 500),
478 | Err(err) => panic!("Unexpected value")
479 | }
480 | }
481 |
482 | #[test]
483 | fn resolve_from_value() {
484 | let val: Future = Future::unit(5);
485 |
486 | match val.recv() {
487 | Ok(n) => assert_eq!(n, 5),
488 | Err(err) => panic!("Unexpected value")
489 | }
490 | }
491 |
492 | #[test]
493 | fn map_promise() {
494 | let count: Future = Future::unit(5);
495 |
496 | let curr: Future = count.and_then(|n| {
497 | Continue(future! {
498 | Async::Ok(100)
499 | })
500 | });
501 |
502 | match curr.recv() {
503 | Ok(n) => assert_eq!(n, 100),
504 | Err(err) => panic!("Unexpected value")
505 | }
506 | }
507 |
508 | // #[test]
509 | // fn promise() {
510 | // let mut m = Promise::new();
511 |
512 | // // Do some calculation...
513 | // m.success(123);
514 |
515 | // m.future().recv()
516 | // }
517 | }
518 |
--------------------------------------------------------------------------------