├── .gitignore ├── tests └── sceptic.rs ├── .travis.yml ├── Cargo.toml ├── LICENSE-MIT ├── README.md ├── LICENSE-APACHE ├── examples └── website_loader.rs └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tests/sceptic.rs: -------------------------------------------------------------------------------- 1 | include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs")); -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: 3 | directories: 4 | - $HOME/.cargo 5 | rust: 6 | - stable 7 | - beta 8 | - nightly 9 | os: 10 | - linux 11 | - osx 12 | branches: 13 | only: 14 | - master 15 | - auto 16 | script: 17 | - cargo build -v --features strict 18 | - cargo test -v --features strict 19 | - cargo doc -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "flow" 3 | version = "0.0.0" 4 | authors = ["Erik Hedvall "] 5 | license = "MIT OR Apache-2.0" 6 | 7 | build = "build.rs" 8 | 9 | [dependencies] 10 | parking_lot = "0.2" 11 | mopa = "0.2" 12 | owning_ref = "0.2" 13 | 14 | [dev-dependencies] 15 | lazy_static = "0.2" 16 | cursive = "0.3.2" 17 | hyper = "0.9" 18 | threadpool = "1" 19 | skeptic = "0.5" 20 | 21 | [build-dependencies] 22 | skeptic = "0.5" 23 | 24 | [features] 25 | strict = [] 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Erik Hedvall 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Flow 2 | 3 | An application architecture library, inspired by [Facebook's Flux][flux], 4 | where data flows in only one direction (although circular, with shortcuts): 5 | from controllers, to the dispatcher, to stores, to listeners, and back to the 6 | controllers. This makes it easy to safely keep and mutate shared state, 7 | without causing inconsistencies or a complete meltdown. 8 | 9 | [flux]: https://facebook.github.io/flux/ 10 | 11 | ## Getting started 12 | 13 | Flow is currently not on crates.io, so you'll have to use it through Git, for 14 | now: 15 | 16 | ```toml 17 | [dependencies.flow] 18 | git = "https://github.com/Ogeon/flow" 19 | rev = "feedbee" #Replace with an actual revision hash 20 | ``` 21 | 22 | It's recommended to lock it at a revision to minimize the risk of updating to 23 | an incompatible version. 24 | 25 | Using it in your application is then quite simple: 26 | 27 | ```rust 28 | extern crate flow; 29 | 30 | use flow::{ 31 | Dispatcher, 32 | DispatchContext, 33 | Store, 34 | }; 35 | 36 | struct NumberStore { 37 | the_number: f64, 38 | } 39 | 40 | impl Store for NumberStore { 41 | type Payload = NumberChange; 42 | type Event = NumberOp; 43 | 44 | fn handle(&mut self, _: DispatchContext, payload: &NumberChange) -> Option { 45 | match payload.op { 46 | NumberOp::Add => self.the_number += payload.amount, 47 | NumberOp::Sub => self.the_number -= payload.amount, 48 | } 49 | 50 | //Tell the listeners what happened 51 | Some(payload.op) 52 | } 53 | } 54 | 55 | #[derive(Clone, Copy)] 56 | enum NumberOp { 57 | Add, 58 | Sub, 59 | } 60 | 61 | struct NumberChange { 62 | amount: f64, 63 | op: NumberOp, 64 | } 65 | 66 | fn main() { 67 | let mut dispatcher = Dispatcher::new(); 68 | 69 | //Add our store to the dispatcher 70 | dispatcher.register_store(NumberStore { 71 | the_number: 0.0, 72 | }); 73 | 74 | //Listen for events from the store 75 | dispatcher.listen(|_: DispatchContext, store: &NumberStore, event: &NumberOp| { 76 | match *event { 77 | NumberOp::Add => println!("the number was increased to {}", store.the_number), 78 | NumberOp::Sub => println!("the number was decreased to {}", store.the_number), 79 | } 80 | }); 81 | 82 | //Manipulate the store and watch the listener print the results 83 | dispatcher.dispatch(NumberChange { 84 | amount: 3.14, 85 | op: NumberOp::Add, 86 | }); 87 | dispatcher.dispatch(NumberChange { 88 | amount: 10.0, 89 | op: NumberOp::Sub, 90 | }); 91 | } 92 | ``` 93 | 94 | The dispatcher may also be stored globally, for example using `lazy_static`, 95 | by putting it inside an `RwLock`. Take a look in the `examples` directory for 96 | more real-world like examples. 97 | 98 | ## Compared to the real thing? 99 | 100 | The main difference, apart from this not being a literal clone, is that this 101 | is Rust and not JavaScript. Rust is much more strict and parallel execution is 102 | to be expected. This has lead to a number of API restrictions, as well: 103 | 104 | * Stores and listeners has to be `Send` and `'static`, and stores has to be `Sync` as well, to allow both safe global access and registering multiple store types in a single dispatcher. 105 | * Payloads and events are only accessible behind immutable references, to allow multiple stores and listeners to use them. They are, instead, owned by the dispatcher. 106 | * Mixins aren't as easy to create in Rust as in JavaScript (sort of possible through macros, but still...), so stores in Flow has to be accessed through the dispatcher instead of as global singletons. The caveat is that stores may be unknown to the dispatcher. 107 | * Dispatching requires exclusive access to make sure that multiple dispatches doesn't happen simultaneously. This is to simplify the interaction between stores, as well as listeners. 108 | 109 | This may feel very strict if you are used to the do-whatever-you-want 110 | mentality that may come with JavaScript, but keep in mind that many 111 | JavaScript values may be seen as being wrapped in `Rc>`, 112 | `Arc>` or `Arc>`. Doing this in your Rust code will loosen 113 | some of these restrictions, but also come with its own downsides. 114 | 115 | Something this library does, that may be seen as an improvement, is that it 116 | enforces the idea of a one-directional data flow through the type system. 117 | Stores may only be mutated by dispatching payloads, unless there's some 118 | internal mutability in place, and dynamic type checking is kept at a minimum 119 | (it's practically almost negligible). Both payloads and events can be 120 | exhaustively matched, meaning that it's harder to send something that nobody 121 | listens for... among other things. 122 | 123 | All in all, it has its good parts and bad parts, but much due to Rust being 124 | Rust, and most of it can be dealt with. 125 | 126 | ## License 127 | 128 | Licensed under either of 129 | 130 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 131 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 132 | 133 | at your option. 134 | 135 | ### Contribution 136 | 137 | Unless you explicitly state otherwise, any contribution intentionally submitted 138 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 139 | additional terms or conditions. 140 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /examples/website_loader.rs: -------------------------------------------------------------------------------- 1 | extern crate flow; 2 | #[macro_use] 3 | extern crate lazy_static; 4 | #[macro_use] 5 | extern crate cursive; 6 | extern crate hyper; 7 | extern crate threadpool; 8 | 9 | use std::sync::{Arc, Mutex, RwLock}; 10 | use std::sync::atomic::{AtomicUsize, Ordering}; 11 | use std::sync::mpsc::Sender; 12 | use std::collections::BTreeMap; 13 | use std::any::Any; 14 | 15 | use flow::{ 16 | Dispatcher, 17 | DispatchContext, 18 | Store, 19 | Listener, 20 | ListenerHandle, 21 | }; 22 | 23 | 24 | use cursive::{Cursive, With}; 25 | 26 | use cursive::view::{ 27 | ViewWrapper, 28 | Identifiable, 29 | Selector, 30 | Finder, 31 | }; 32 | use cursive::views::{ 33 | LinearLayout, 34 | TextView, 35 | ListView, 36 | EditView, 37 | BoxView, 38 | Button, 39 | Dialog, 40 | IdView, 41 | }; 42 | 43 | use hyper::Client; 44 | 45 | use threadpool::ThreadPool; 46 | 47 | lazy_static! { 48 | static ref SITES: GlobalDispatcher = GlobalDispatcher::new(); 49 | } 50 | 51 | //A combination of dispatcher and task pool 52 | struct GlobalDispatcher { 53 | dispatcher: RwLock>, 54 | client: Arc, 55 | pool: Mutex, 56 | id_counter: AtomicUsize, 57 | } 58 | 59 | impl GlobalDispatcher { 60 | fn new() -> GlobalDispatcher { 61 | let mut dispatcher = Dispatcher::new(); 62 | dispatcher.register_store(Sites::new()); 63 | 64 | GlobalDispatcher { 65 | dispatcher: RwLock::new(dispatcher), 66 | client: Arc::new(Client::new()), 67 | pool: Mutex::new(ThreadPool::new(4)), 68 | id_counter: AtomicUsize::new(0), 69 | } 70 | } 71 | 72 | fn listen, L: Listener>(&self, listener: L) -> Option> { 73 | self.dispatcher.write().unwrap().listen(listener) 74 | } 75 | 76 | fn unlisten>(&self, handle: ListenerHandle) { 77 | self.dispatcher.write().unwrap().unlisten(handle); 78 | } 79 | 80 | fn dispatch(&self, payload: SiteAction) { 81 | self.dispatcher.write().unwrap().dispatch(payload); 82 | } 83 | 84 | //Load a site and notify the dispatcher when done 85 | fn load_site(&self, url: String) { 86 | let id = self.id_counter.fetch_add(1, Ordering::SeqCst); 87 | 88 | //Notify the dispatcher that a new URL has been added 89 | self.dispatch(SiteAction::Load(id, url.clone())); 90 | 91 | //Request the site and report back 92 | let client = self.client.clone(); 93 | self.pool.lock().unwrap().execute(move || match client.get(&*url).send() { 94 | Ok(response) => if response.status.is_success() { 95 | SITES.done_loading(id); 96 | } else { 97 | SITES.loading_failed(id, response.status.to_string()); 98 | }, 99 | Err(e) => SITES.loading_failed(id, e.to_string()), 100 | }); 101 | } 102 | 103 | //A site was successfully loaded 104 | fn done_loading(&self, id: usize) { 105 | self.dispatch(SiteAction::DoneLoading(id)); 106 | } 107 | 108 | //A site could not be loaded 109 | fn loading_failed(&self, id: usize, error: String) { 110 | self.dispatch(SiteAction::LoadingFailed(id, error)); 111 | } 112 | 113 | //Remove a site from the store 114 | fn remove_site(&self, id: usize) { 115 | self.dispatch(SiteAction::Remove(id)); 116 | } 117 | } 118 | 119 | //Command payloads for the site store 120 | enum SiteAction { 121 | Load(usize, String), 122 | DoneLoading(usize), 123 | LoadingFailed(usize, String), 124 | Remove(usize), 125 | } 126 | 127 | //A store for site status 128 | struct Sites { 129 | sites: BTreeMap, 130 | } 131 | 132 | impl Sites { 133 | fn new() -> Sites { 134 | Sites { 135 | sites: BTreeMap::new(), 136 | } 137 | } 138 | } 139 | 140 | impl Store for Sites { 141 | type Payload = SiteAction; 142 | 143 | type Event = (); 144 | 145 | fn handle(&mut self, _context: DispatchContext, payload: &SiteAction) -> Option<()> { 146 | match *payload { 147 | SiteAction::Load(id, ref url) => { 148 | self.sites.insert(id, Site { 149 | url: url.clone(), 150 | status: Status::Loading, 151 | }); 152 | Some(()) 153 | }, 154 | SiteAction::DoneLoading(id) => if let Some(site) = self.sites.get_mut(&id) { 155 | site.status = Status::Done; 156 | Some(()) 157 | } else { 158 | None 159 | }, 160 | SiteAction::LoadingFailed(id, ref error) => if let Some(site) = self.sites.get_mut(&id) { 161 | site.status = Status::Error(error.clone()); 162 | Some(()) 163 | } else { 164 | None 165 | }, 166 | SiteAction::Remove(id) => { 167 | self.sites.remove(&id); 168 | Some(()) 169 | }, 170 | } 171 | } 172 | } 173 | 174 | #[derive(Clone)] 175 | struct Site { 176 | url: String, 177 | status: Status, 178 | } 179 | 180 | #[derive(Clone)] 181 | enum Status { 182 | Loading, 183 | Done, 184 | Error(String), 185 | } 186 | 187 | fn main() { 188 | let mut ui = Cursive::new(); 189 | 190 | //Get a sender for events 191 | let events = ui.cb_sink().clone(); 192 | 193 | //Build the UI 194 | ui.add_layer( 195 | Dialog::around( 196 | BoxView::with_full_screen(LinearLayout::vertical() 197 | .child(BoxView::with_full_height(SiteList::new("site_list", events.clone()))) 198 | .child(StatusBar::new("site_status", events.clone())) 199 | .child(LinearLayout::horizontal() 200 | .child(TextView::new("Add site: ")) 201 | .child(BoxView::with_full_width(EditView::new() 202 | .content("https://") 203 | .on_submit(load_site) 204 | .with_id("url_input") 205 | )) 206 | ) 207 | ) 208 | ) 209 | .title("Sites") 210 | .button("Quit", |ui| ui.quit()) 211 | ); 212 | 213 | //The UI doesn't always update, so this is a workaround 214 | ui.set_fps(60); 215 | 216 | ui.run(); 217 | } 218 | 219 | //Load a site and reset the text field 220 | fn load_site(ui: &mut Cursive, url: &str) { 221 | SITES.load_site(url.into()); 222 | if let Some(url_input) = ui.find_id::("url_input") { 223 | url_input.set_content("https://"); 224 | } 225 | } 226 | 227 | 228 | 229 | //A list view that shows a list of requested sites, their status and allows 230 | //them to be removed. 231 | struct SiteList { 232 | view: IdView, 233 | handle: ListenerHandle, 234 | } 235 | 236 | impl SiteList { 237 | fn new(id: &str, events: Sender>) -> SiteList { 238 | let view = ListView::new().with_id(id); 239 | 240 | //Set up a listener for updates 241 | let id = String::from(id); 242 | let handle = SITES.listen(move |_: DispatchContext, store: &Sites, _event: &()| { 243 | let sites = store.sites.clone(); 244 | let id = id.clone(); 245 | 246 | //Send an event to the UI that updates the list 247 | events.send(Box::new(move |ui: &mut Cursive| { 248 | if let Some(site_list) = ui.find_id::(&id) { 249 | //Update the list by replacing it 250 | site_list.clear(); 251 | 252 | for (&id, site) in &sites { 253 | //Get site status string and error message 254 | let (status, error) = match site.status { 255 | Status::Loading => ("Loading... ", None), 256 | Status::Done => ("Done ", None), 257 | Status::Error(ref e) => ("Error! ", Some(e.clone())), 258 | }; 259 | 260 | site_list.add_child(&site.url, LinearLayout::horizontal() 261 | .child(BoxView::with_fixed_height(1, TextView::new(status)).squishable()) 262 | .with(move |layout| if let Some(error) = error { 263 | layout.add_child(Button::new("Show error", move |ui| { 264 | ui.add_layer(Dialog::info(&*error).title("Error!")); 265 | })) 266 | }) 267 | .child(Button::new("Remove", move |_| SITES.remove_site(id))) 268 | ); 269 | } 270 | } 271 | })).unwrap() 272 | }).expect("Sites hasn't been registered in the dispatcher"); 273 | 274 | SiteList { 275 | view: view, 276 | handle: handle, 277 | } 278 | } 279 | } 280 | 281 | //This view is just a transparent wrapper. 282 | impl ViewWrapper for SiteList { 283 | wrap_impl!(self.view: IdView); 284 | } 285 | 286 | //Stop listening for events when dropped 287 | impl Drop for SiteList { 288 | fn drop(&mut self) { 289 | SITES.unlisten(self.handle); 290 | } 291 | } 292 | 293 | 294 | 295 | //Shows some site statistics 296 | struct StatusBar { 297 | view: LinearLayout, 298 | handle: ListenerHandle, 299 | id: String, 300 | } 301 | 302 | impl StatusBar { 303 | fn new(id: &str, events: Sender>) -> StatusBar { 304 | let view = LinearLayout::horizontal() 305 | .child(TextView::new("Total: 0 ").with_id("total")) 306 | .child(TextView::new("Pending: 0 ").with_id("pending")) 307 | .child(TextView::new("Successful: 0 ").with_id("successful")) 308 | .child(TextView::new("Failed: 0 ").with_id("failed")); 309 | 310 | let id_owned = String::from(id); 311 | let handle = SITES.listen(move |_: DispatchContext, store: &Sites, _event: &()| { 312 | let mut successful = 0; 313 | let mut failed = 0; 314 | let mut pending = 0; 315 | 316 | for (_, site) in &store.sites { 317 | match site.status { 318 | Status::Loading => pending += 1, 319 | Status::Done => successful += 1, 320 | Status::Error(_) => failed += 1, 321 | } 322 | } 323 | 324 | let id = id_owned.clone(); 325 | events.send(Box::new(move |ui: &mut Cursive| { 326 | if let Some(layout) = ui.find_id::(&id) { 327 | if let Some(text) = layout.find_id::("total") { 328 | text.set_content(format!("Total: {} ", successful + failed + pending)); 329 | } 330 | if let Some(text) = layout.find_id::("pending") { 331 | text.set_content(format!("Pending: {} ", pending)); 332 | } 333 | if let Some(text) = layout.find_id::("successful") { 334 | text.set_content(format!("Successful: {} ", successful)); 335 | } 336 | if let Some(text) = layout.find_id::("failed") { 337 | text.set_content(format!("Failed: {} ", failed)); 338 | } 339 | } 340 | })).unwrap(); 341 | }).expect("Sites hasn't been registered in the dispatcher"); 342 | 343 | StatusBar { 344 | view: view, 345 | handle: handle, 346 | id: id.into(), 347 | } 348 | } 349 | } 350 | 351 | impl ViewWrapper for StatusBar { 352 | wrap_impl!(self.view: LinearLayout); 353 | 354 | //Isolate the content of this view, by making any internal view 355 | //unreachable from the outside, unless it's through our root view. 356 | fn wrap_find_any(&mut self, selector: &Selector) -> Option<&mut Any> { 357 | match *selector { 358 | Selector::Id(id) if id == &self.id => Some(&mut self.view), 359 | _ => None 360 | } 361 | } 362 | } 363 | 364 | impl Drop for StatusBar { 365 | fn drop(&mut self) { 366 | SITES.unlisten(self.handle); 367 | } 368 | } 369 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! An application architecture library, inspired by [Facebook's Flux][flux], 2 | //! where data flows in only one direction (although circular, with 3 | //! shortcuts): from controllers, to the dispatcher, to stores, to listeners, 4 | //! and back to the controllers. This makes it easy to safely keep and mutate 5 | //! shared state, without causing inconsistencies or a complete meltdown. 6 | //! 7 | //! The [dispatcher] is single threaded, but it can easily be put behind an 8 | //! `RwLock` and shared globally. There's nothing stopping you from keeping 9 | //! multiple dispatchers around, for disjoint parts of an application, but 10 | //! there shouldn't be a need for that unless it's very busy. It's likely 11 | //! better to just keep the payload processing routines light. 12 | //! 13 | //! A [store] is meant to represent a particular domain of the application 14 | //! state, such as to-do items or users, and may depend on other stores. They 15 | //! are singletons, which means that there will only be one "user store", but 16 | //! they may instead contain multiple sets or collections, such as "admin 17 | //! users" and "regular users". It's completely dependent on how the 18 | //! application works. 19 | //! 20 | //! The only way a store may be mutated is through a payload dispatch. The 21 | //! payload is sent to every store, where it may be processed, and the store 22 | //! can then choose to notify [listeners] that it has been updated. These 23 | //! listeners will then get immutable access to the store, which can be used 24 | //! to relay information to other parts of the application, such as user 25 | //! interface controllers. 26 | //! 27 | //! That's the general structure and lifecycle. 28 | //! 29 | //! [flux]: https://facebook.github.io/flux/ 30 | //! [dispatcher]: struct.Dispatcher.html 31 | //! [store]: trait.Store.html 32 | //! [listeners]: trait.Listener.html 33 | 34 | #![cfg_attr(feature = "strict", deny(missing_docs))] 35 | #![cfg_attr(feature = "strict", deny(warnings))] 36 | 37 | extern crate parking_lot; 38 | #[macro_use] 39 | extern crate mopa; 40 | extern crate owning_ref; 41 | 42 | use std::collections::{HashMap, VecDeque}; 43 | use std::any::{TypeId, Any}; 44 | use std::marker::PhantomData; 45 | use std::fmt; 46 | use std::ops::Deref; 47 | 48 | use parking_lot::{RwLock, RwLockReadGuard, Mutex}; 49 | use owning_ref::StableAddress; 50 | 51 | pub use owning_ref::OwningRef; 52 | 53 | ///A reference to a store. 54 | pub type Ref<'a, S> = OwningRef, S>; 55 | 56 | ///A read guard for a store. Note that dereferencing performs a hidden 57 | ///downcast. 58 | pub struct Guard<'a, S: Store> { 59 | guard: RwLockReadGuard<'a, Box>>, 60 | ty: PhantomData<&'a S>, 61 | } 62 | 63 | impl<'a, S: Store> Guard<'a, S> { 64 | fn new(guard: RwLockReadGuard<'a, Box>>) -> Guard<'a, S> { 65 | Guard { 66 | guard: guard, 67 | ty: PhantomData, 68 | } 69 | } 70 | } 71 | 72 | impl<'a, S: Store> Deref for Guard<'a, S> { 73 | type Target = S; 74 | 75 | fn deref(&self) -> &S { 76 | &self.guard.downcast_ref::>().expect("a store reference pointed to a store of the wrong type").store 77 | } 78 | } 79 | 80 | unsafe impl<'a, S: Store> StableAddress for Guard<'a, S> {} 81 | 82 | /// The dispatcher sends payloads to stores and notifies listeners. 83 | pub struct Dispatcher

{ 84 | index: HashMap> 85 | } 86 | 87 | impl

Dispatcher

{ 88 | /// Create a new dispatcher that handles the payload type `P`. 89 | pub fn new() -> Dispatcher

{ 90 | Dispatcher { 91 | index: HashMap::new(), 92 | } 93 | } 94 | 95 | /// Register a store in the dispatcher. Stores are singletons, so any 96 | /// previously registered store of the same type will be replaced. 97 | pub fn register_store>(&mut self, store: S) { 98 | self.index.insert(TypeId::of::(), RegisteredStore { 99 | store: RwLock::new(Box::new(StoreContainerImpl::new(store))), 100 | listeners: Mutex::new(Box::new(ListenerContainerImpl::::new())), 101 | }); 102 | } 103 | 104 | /// Get an immutable reference to a store if it's registered. 105 | pub fn get_store>(&self) -> Option> { 106 | self.index.get(&TypeId::of::()) 107 | .map(|s| OwningRef::new(Guard::new(s.store.read()))) 108 | } 109 | 110 | /// Listen for notifications from a store. The returned handle can be used 111 | /// to unregister the listener. 112 | pub fn listen, F: Listener>(&mut self, listener: F) -> Option> { 113 | self.index.get_mut(&TypeId::of::()) 114 | .and_then(|entry| entry 115 | .listeners.get_mut() 116 | .downcast_mut::>() 117 | .map(|listeners| listeners.listen(listener)) 118 | ) 119 | .map(|id| ListenerHandle::new(id)) 120 | } 121 | 122 | /// Stop listening for notifications from a store. 123 | pub fn unlisten>(&mut self, token: ListenerHandle) { 124 | if let Some(entry) = self.index.get_mut(&TypeId::of::()) { 125 | entry 126 | .listeners 127 | .get_mut() 128 | .downcast_mut::>() 129 | .map(|listeners| listeners.unlisten(token.id)); 130 | } 131 | } 132 | 133 | /// Dispatch a payload to the registered stores, and notify their listeners. 134 | pub fn dispatch(&mut self, payload: P) { 135 | let mut deferred = VecDeque::new(); 136 | deferred.push_back(payload); 137 | 138 | while let Some(payload) = deferred.pop_front() { 139 | let pending: Vec<_> = self.index.iter_mut().map(|(&id, entry)| { 140 | entry.store.get_mut().begin_dispatch(); 141 | id 142 | }).collect(); 143 | 144 | for id in pending { 145 | if let Some(entry) = self.index.get(&id) { 146 | let mut store = entry.store.write(); 147 | let mut context = DispatchContext { 148 | payload: &payload, 149 | index: &self.index, 150 | deferred: &mut deferred 151 | }; 152 | 153 | store.handle(context.reborrow(), &payload, &mut **entry.listeners.lock()); 154 | } 155 | } 156 | } 157 | } 158 | } 159 | 160 | impl

GenericDispatcher for Dispatcher

{ 161 | type Payload = P; 162 | 163 | fn get_store<'a, S: Store>(&'a mut self) -> Option> { 164 | (*self).get_store() 165 | } 166 | 167 | fn dispatch(&mut self, payload: P) { 168 | (*self).dispatch(payload); 169 | } 170 | } 171 | 172 | struct RegisteredStore

{ 173 | store: RwLock>>, 174 | listeners: Mutex>, 175 | } 176 | 177 | trait StoreContainer

: mopa::Any + Send + Sync { 178 | fn begin_dispatch(&mut self); 179 | 180 | fn handle(&mut self, context: DispatchContext

, payload: &P, listeners: &mut ListenerContainer); 181 | } 182 | 183 | //Borrowed from mopa until it supports generics 184 | impl

StoreContainer

{ 185 | /// Returns true if the boxed type is the same as `T` 186 | #[inline] 187 | pub fn is>(&self) -> bool { 188 | TypeId::of::() == mopa::Any::get_type_id(self) 189 | } 190 | 191 | /// Returns some reference to the boxed value if it is of type `T`, or 192 | /// `None` if it isn't. 193 | #[inline] 194 | pub fn downcast_ref>(&self) -> Option<&T> { 195 | if self.is::() { 196 | unsafe { 197 | Option::Some(self.downcast_ref_unchecked()) 198 | } 199 | } else { 200 | Option::None 201 | } 202 | } 203 | 204 | /// Returns a reference to the boxed value, blindly assuming it to be of type `T`. 205 | /// If you are not *absolutely certain* of `T`, you *must not* call this. 206 | #[inline] 207 | pub unsafe fn downcast_ref_unchecked>(&self) -> &T { 208 | &*(self as *const Self as *const T) 209 | } 210 | } 211 | 212 | struct StoreContainerImpl { 213 | store: S, 214 | done: bool, 215 | } 216 | 217 | impl StoreContainerImpl { 218 | fn new(store: S) -> StoreContainerImpl { 219 | StoreContainerImpl { 220 | store: store, 221 | done: true, 222 | } 223 | } 224 | } 225 | 226 | impl StoreContainer for StoreContainerImpl { 227 | fn begin_dispatch(&mut self) { 228 | self.done = false; 229 | } 230 | 231 | fn handle(&mut self, mut context: DispatchContext, payload: &S::Payload, listeners: &mut ListenerContainer) { 232 | if !self.done { 233 | let event = self.store.handle(context.reborrow(), payload); 234 | self.done = true; 235 | if let Some(ref event) = event { 236 | listeners.downcast_mut::>().unwrap().notify_listeners(context, &self.store, event); 237 | } 238 | } 239 | } 240 | } 241 | 242 | trait ListenerContainer: mopa::Any + Send { } 243 | 244 | //Borrowed from mopa until it supports generics 245 | impl ListenerContainer { 246 | /// Returns true if the boxed type is the same as `T` 247 | #[inline] 248 | pub fn is(&self) -> bool { 249 | TypeId::of::() == mopa::Any::get_type_id(self) 250 | } 251 | 252 | /// Returns some mutable reference to the boxed value if it is of type `T`, or 253 | /// `None` if it isn't. 254 | #[inline] 255 | pub fn downcast_mut(&mut self) -> Option<&mut T> { 256 | if self.is::() { 257 | unsafe { 258 | Option::Some(self.downcast_mut_unchecked()) 259 | } 260 | } else { 261 | Option::None 262 | } 263 | } 264 | 265 | /// Returns a mutable reference to the boxed value, blindly assuming it to be of type `T`. 266 | /// If you are not *absolutely certain* of `T`, you *must not* call this. 267 | #[inline] 268 | pub unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { 269 | &mut *(self as *mut Self as *mut T) 270 | } 271 | } 272 | 273 | struct ListenerContainerImpl { 274 | listeners: HashMap>>, 275 | listener_id_counter: usize, 276 | } 277 | 278 | impl ListenerContainerImpl { 279 | fn new() -> ListenerContainerImpl { 280 | ListenerContainerImpl { 281 | listeners: HashMap::new(), 282 | listener_id_counter: 0, 283 | } 284 | } 285 | 286 | fn listen>(&mut self, listener: F) -> usize { 287 | let id = self.listener_id_counter; 288 | self.listener_id_counter += 1; 289 | 290 | self.listeners.insert(id, Box::new(listener)); 291 | id 292 | } 293 | 294 | fn unlisten(&mut self, id: usize) { 295 | self.listeners.remove(&id); 296 | } 297 | 298 | fn notify_listeners(&mut self, mut context: DispatchContext, store: &S, event: &S::Event) { 299 | for (_, listener) in &mut self.listeners { 300 | listener.notify(context.reborrow(), store, event); 301 | } 302 | } 303 | } 304 | 305 | impl ListenerContainer for ListenerContainerImpl { } 306 | 307 | /// A context object for waiting for stores and deferring payloads while 308 | /// dispatching. 309 | pub struct DispatchContext<'a, P: 'a> { 310 | payload: &'a P, 311 | index: &'a HashMap>, 312 | deferred: &'a mut VecDeque

, 313 | } 314 | 315 | impl<'a, P> DispatchContext<'a, P> { 316 | /// Wait for another store to finish updating, and get a reference to it 317 | /// if it exists. 318 | /// 319 | /// #Panics 320 | /// 321 | /// Panics if the store `S` is already waiting for another store. 322 | pub fn wait_for>(&mut self) -> Option> { 323 | match self.try_wait_for() { 324 | Ok(s) => Some(s), 325 | Err(WaitError::Missing) => None, 326 | Err(WaitError::Waiting) => panic!("tried to wait for a store that is currently waiting for another store"), 327 | } 328 | } 329 | 330 | /// The same as `wait_for`, but returns an error instead of panicking if 331 | /// the store `S` is already waiting for another store. 332 | pub fn try_wait_for>(&mut self) -> Result, WaitError> { 333 | if let Some(entry) = self.index.get(&TypeId::of::()) { 334 | entry.store.try_write().map(|mut store| { 335 | let context = DispatchContext { 336 | payload: self.payload, 337 | index: self.index, 338 | deferred: self.deferred, 339 | }; 340 | 341 | store.handle(context, self.payload, &mut **entry.listeners.lock()); 342 | 343 | Ok(OwningRef::new(Guard::new(store.downgrade()))) 344 | }).unwrap_or(Err(WaitError::Waiting)) 345 | } else { 346 | Err(WaitError::Missing) 347 | } 348 | } 349 | 350 | /// Queue up another payload and dispatch it immediately after the current 351 | /// one. 352 | pub fn defer(&mut self, payload: P) { 353 | self.deferred.push_back(payload); 354 | } 355 | 356 | /// Make a temporary copy of the context, where the context references are 357 | /// reborrowed. 358 | pub fn reborrow(&mut self) -> DispatchContext

{ 359 | DispatchContext { 360 | payload: self.payload, 361 | index: self.index, 362 | deferred: self.deferred, 363 | } 364 | } 365 | } 366 | 367 | impl<'a, P> GenericDispatcher for DispatchContext<'a, P> { 368 | type Payload = P; 369 | 370 | fn get_store<'s, S: Store>(&'s mut self) -> Option> { 371 | self.wait_for() 372 | } 373 | 374 | fn dispatch(&mut self, payload: P) { 375 | self.defer(payload); 376 | } 377 | } 378 | 379 | /// Errors that may occur while waiting for a store to finish updating. 380 | pub enum WaitError { 381 | /// The store is waiting for another store. 382 | Waiting, 383 | 384 | /// The store hasn't been registered in the dispatcher. 385 | Missing, 386 | } 387 | 388 | /// A handle for a store listener. It can be used to unregister the listener. 389 | pub struct ListenerHandle { 390 | id: usize, 391 | store: PhantomData, 392 | } 393 | 394 | impl Copy for ListenerHandle {} 395 | 396 | impl Clone for ListenerHandle { 397 | fn clone(&self) -> ListenerHandle { 398 | *self 399 | } 400 | } 401 | 402 | impl fmt::Debug for ListenerHandle { 403 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 404 | write!(f, "ListenerHandle {{ id: {:?}, store: {:?} }}", self.id, self.store) 405 | } 406 | } 407 | 408 | impl ListenerHandle { 409 | fn new(id: usize) -> ListenerHandle { 410 | ListenerHandle { 411 | id: id, 412 | store: PhantomData, 413 | } 414 | } 415 | } 416 | 417 | /// A store handles payloads and decides if its listeners should be notified. 418 | pub trait Store: Send + Sync + Any { 419 | /// The type of payload that this store handles. 420 | type Payload; 421 | 422 | /// The type of event that is sent to the listeners. 423 | type Event; 424 | 425 | /// Handle a payload and maybe return an event for the listeners. 426 | fn handle(&mut self, context: DispatchContext, payload: &Self::Payload) -> Option; 427 | } 428 | 429 | /// A listener can listen for update notifications from a store. 430 | pub trait Listener: Send + 'static { 431 | /// Let the listener know that a store has been updated. 432 | fn notify(&mut self, context: DispatchContext, store: &S, event: &S::Event); 433 | } 434 | 435 | impl, &S, &S::Event) + Send + 'static> Listener for F { 436 | fn notify(&mut self, context: DispatchContext, store: &S, event: &S::Event) { 437 | self(context, store, event); 438 | } 439 | } 440 | 441 | /// The most common dispatcher functionality. 442 | /// 443 | /// ``` 444 | /// use flow::GenericDispatcher; 445 | /// # use flow::{ DispatchContext, Store }; 446 | /// # struct MyPayload; 447 | /// # struct Message { username: String, body: String } 448 | /// # 449 | /// struct MessageStore { 450 | /// messages: Vec<(usize, String)>, 451 | /// } 452 | /// 453 | /// impl MessageStore { 454 | /// fn get_messages(&self, dispatcher: &mut D) -> Vec where 455 | /// D: GenericDispatcher, 456 | /// { 457 | /// self.messages.iter().map(|&(user_id, ref message)| { 458 | /// let name = dispatcher 459 | /// .get_store::() 460 | /// .expect("UserStore wasn't registered") 461 | /// .get_username(user_id) 462 | /// .into(); 463 | /// 464 | /// Message { 465 | /// username: name, 466 | /// body: message.clone(), 467 | /// } 468 | /// }).collect() 469 | /// } 470 | /// } 471 | /// # 472 | /// # impl Store for MessageStore { 473 | /// # type Payload = MyPayload; 474 | /// # 475 | /// # type Event = (); 476 | /// # 477 | /// # fn handle(&mut self, context: DispatchContext, payload: &MyPayload) -> Option<()> { 478 | /// # unimplemented!() 479 | /// # } 480 | /// # } 481 | /// # 482 | /// # struct UserStore; 483 | /// # 484 | /// # impl UserStore { 485 | /// # fn get_username(&self, id: usize) -> &str { 486 | /// # unimplemented!() 487 | /// # } 488 | /// # } 489 | /// # 490 | /// # impl Store for UserStore { 491 | /// # type Payload = MyPayload; 492 | /// # 493 | /// # type Event = (); 494 | /// # 495 | /// # fn handle(&mut self, context: DispatchContext, payload: &MyPayload) -> Option<()> { 496 | /// # unimplemented!() 497 | /// # } 498 | /// # } 499 | /// # 500 | /// ``` 501 | pub trait GenericDispatcher { 502 | ///The type of payload that the dispatcher can handle. 503 | type Payload; 504 | 505 | ///Get an immutable reference to a registered store. The dispatcher may 506 | ///have to do some computations before the store is ready to be returned. 507 | fn get_store<'a, S: Store>(&'a mut self) -> Option>; 508 | 509 | ///Dispatch a payload, either immediately or later. 510 | fn dispatch(&mut self, payload: Self::Payload); 511 | } 512 | 513 | #[cfg(test)] 514 | mod tests { 515 | use super::{ 516 | Dispatcher, 517 | Store, 518 | DispatchContext, 519 | Ref, 520 | }; 521 | 522 | enum Payload { 523 | Payload1(&'static str), 524 | Payload2(usize), 525 | Payload3(bool), 526 | } 527 | 528 | struct Store1 { 529 | message: &'static str, 530 | } 531 | 532 | impl Store for Store1 { 533 | type Payload = Payload; 534 | 535 | type Event = (); 536 | 537 | fn handle(&mut self, _context: DispatchContext, payload: &Payload) -> Option<()> { 538 | match *payload { 539 | Payload::Payload1(message) => { 540 | self.message = message; 541 | Some(()) 542 | }, 543 | _ => None, 544 | } 545 | } 546 | } 547 | 548 | struct Store2 { 549 | number: usize, 550 | } 551 | 552 | impl Store for Store2 { 553 | type Payload = Payload; 554 | 555 | type Event = (); 556 | 557 | fn handle(&mut self, _context: DispatchContext, payload: &Payload) -> Option<()> { 558 | match *payload { 559 | Payload::Payload2(number) => { 560 | self.number = number; 561 | Some(()) 562 | }, 563 | _ => None, 564 | } 565 | } 566 | } 567 | 568 | #[test] 569 | fn single_store() { 570 | let mut dispatcher = Dispatcher::new(); 571 | dispatcher.register_store(Store1 { 572 | message: "foo", 573 | }); 574 | 575 | dispatcher.dispatch(Payload::Payload2(4)); 576 | { 577 | let store: Option> = dispatcher.get_store(); 578 | assert_eq!(store.map(|s| s.message), Some("foo")); 579 | } 580 | 581 | dispatcher.dispatch(Payload::Payload1("bar")); 582 | { 583 | let store: Option> = dispatcher.get_store(); 584 | assert_eq!(store.map(|s| s.message), Some("bar")); 585 | } 586 | 587 | dispatcher.dispatch(Payload::Payload3(true)); 588 | { 589 | let store: Option> = dispatcher.get_store(); 590 | assert_eq!(store.map(|s| s.message), Some("bar")); 591 | } 592 | } 593 | 594 | #[test] 595 | fn multiple_stores() { 596 | let mut dispatcher = Dispatcher::new(); 597 | dispatcher.register_store(Store1 { 598 | message: "foo", 599 | }); 600 | dispatcher.register_store(Store2 { 601 | number: 0, 602 | }); 603 | 604 | dispatcher.dispatch(Payload::Payload2(4)); 605 | { 606 | let store: Option> = dispatcher.get_store(); 607 | assert_eq!(store.map(|s| s.message), Some("foo")); 608 | 609 | let store: Option> = dispatcher.get_store(); 610 | assert_eq!(store.map(|s| s.number), Some(4)); 611 | } 612 | 613 | dispatcher.dispatch(Payload::Payload1("bar")); 614 | { 615 | let store: Option> = dispatcher.get_store(); 616 | assert_eq!(store.map(|s| s.message), Some("bar")); 617 | 618 | let store: Option> = dispatcher.get_store(); 619 | assert_eq!(store.map(|s| s.number), Some(4)); 620 | } 621 | 622 | dispatcher.dispatch(Payload::Payload3(true)); 623 | { 624 | let store: Option> = dispatcher.get_store(); 625 | assert_eq!(store.map(|s| s.message), Some("bar")); 626 | 627 | let store: Option> = dispatcher.get_store(); 628 | assert_eq!(store.map(|s| s.number), Some(4)); 629 | } 630 | } 631 | 632 | #[test] 633 | fn waiting_store() { 634 | struct WaitingStore { 635 | message: String, 636 | } 637 | 638 | impl Store for WaitingStore { 639 | type Payload = Payload; 640 | 641 | type Event = (); 642 | 643 | fn handle(&mut self, mut context: DispatchContext, payload: &Payload) -> Option<()> { 644 | let own_message = match *payload { 645 | Payload::Payload1(message) => format!("str: {}", message), 646 | Payload::Payload2(number) => format!("num: {}", number), 647 | Payload::Payload3(boolean) => format!("bool: {}", boolean), 648 | }; 649 | let message = context.wait_for::().unwrap().message; 650 | let number = context.wait_for::().unwrap().number; 651 | self.message = format!("{}, {}, {}", message, number, own_message); 652 | 653 | Some(()) 654 | } 655 | } 656 | 657 | let mut dispatcher = Dispatcher::new(); 658 | dispatcher.register_store(Store1 { 659 | message: "foo", 660 | }); 661 | dispatcher.register_store(Store2 { 662 | number: 0, 663 | }); 664 | dispatcher.register_store(WaitingStore { 665 | message: "".into() 666 | }); 667 | 668 | dispatcher.dispatch(Payload::Payload2(4)); 669 | { 670 | let store: Option> = dispatcher.get_store(); 671 | assert_eq!(store.map(|s| s.message), Some("foo")); 672 | 673 | let store: Option> = dispatcher.get_store(); 674 | assert_eq!(store.map(|s| s.number), Some(4)); 675 | 676 | let store: Option> = dispatcher.get_store(); 677 | assert_eq!(store.map(|s| s.message.clone()), Some("foo, 4, num: 4".into())); 678 | } 679 | 680 | dispatcher.dispatch(Payload::Payload1("bar")); 681 | { 682 | let store: Option> = dispatcher.get_store(); 683 | assert_eq!(store.map(|s| s.message), Some("bar")); 684 | 685 | let store: Option> = dispatcher.get_store(); 686 | assert_eq!(store.map(|s| s.number), Some(4)); 687 | 688 | let store: Option> = dispatcher.get_store(); 689 | assert_eq!(store.map(|s| s.message.clone()), Some("bar, 4, str: bar".into())); 690 | } 691 | 692 | dispatcher.dispatch(Payload::Payload3(true)); 693 | { 694 | let store: Option> = dispatcher.get_store(); 695 | assert_eq!(store.map(|s| s.message), Some("bar")); 696 | 697 | let store: Option> = dispatcher.get_store(); 698 | assert_eq!(store.map(|s| s.number), Some(4)); 699 | 700 | let store: Option> = dispatcher.get_store(); 701 | assert_eq!(store.map(|s| s.message.clone()), Some("bar, 4, bool: true".into())); 702 | } 703 | } 704 | 705 | #[test] 706 | fn listeners() { 707 | let mut dispatcher = Dispatcher::new(); 708 | dispatcher.register_store(Store1 { 709 | message: "foo", 710 | }); 711 | dispatcher.register_store(Store2 { 712 | number: 0, 713 | }); 714 | 715 | let mut counter = 0; 716 | let a = dispatcher.listen(move |mut context: DispatchContext, store: &Store1, _event: &()| { 717 | if store.message == "bar" { 718 | assert_eq!(counter, 0); 719 | context.defer(Payload::Payload1("baz")); 720 | } else { 721 | assert_eq!(counter, 1); 722 | context.defer(Payload::Payload2(4)); 723 | } 724 | 725 | counter += 1; 726 | }).unwrap(); 727 | 728 | let mut counter = 0; 729 | let b = dispatcher.listen(move |mut context: DispatchContext, store: &Store2, _event: &()| { 730 | if store.number == 4 { 731 | assert_eq!(counter, 0); 732 | context.defer(Payload::Payload2(10)); 733 | } else { 734 | assert_eq!(counter, 1); 735 | } 736 | 737 | counter += 1; 738 | }).unwrap(); 739 | 740 | dispatcher.dispatch(Payload::Payload1("bar")); 741 | { 742 | let store: Option> = dispatcher.get_store(); 743 | assert_eq!(store.map(|s| s.message), Some("baz")); 744 | 745 | let store: Option> = dispatcher.get_store(); 746 | assert_eq!(store.map(|s| s.number), Some(10)); 747 | } 748 | 749 | dispatcher.unlisten(a); 750 | dispatcher.unlisten(b); 751 | 752 | dispatcher.dispatch(Payload::Payload1("bar")); 753 | { 754 | let store: Option> = dispatcher.get_store(); 755 | assert_eq!(store.map(|s| s.message), Some("bar")); 756 | 757 | let store: Option> = dispatcher.get_store(); 758 | assert_eq!(store.map(|s| s.number), Some(10)); 759 | } 760 | } 761 | } 762 | --------------------------------------------------------------------------------