r3bl_rs_utils
- Usage
- redux
- Macros
- tree_memory_arena (non-binary tree data structure)
- utils
- tui (experimental)
- Stability
This library provides utility functions:
- Thread safe asynchronous Redux library (uses Tokio to run subscribers and middleware in separate tasks). The reducer functions are run in sequence (not in Tokio tasks).
- Declarative macros, and procedural macros (both function like and derive) to avoid having to write lots of boilerplate code for many common (and complex) tasks.
- Non binary tree data structure inspired by memory arenas, that is thread safe and supports parallel tree walking.
- Functions to unwrap deeply nested objects inspired by Kotlin scope functions.
- Capabilities to make it easier to build TUIs (Text User Interface apps) in Rust. This is currently experimental and is being actively developed.
π‘ To learn more about this library, please read how it was built on developerlife.com:
π‘ You can also read all the Rust content on developerlife.com here. Also, the equivalent of this library is available for TypeScript and is called r3bl-ts-utils.
Usage
Please add the following to your Cargo.toml
file:
[]
= "0.7.23"
redux
Store
is thread safe and asynchronous (using Tokio). You have to implement async
traits in order to use it, by defining your own reducer, subscriber, and middleware trait
objects. You also have to supply the Tokio runtime, this library will not create its own
runtime. However, for best results, it is best to use the multithreaded Tokio runtime.
Once you setup your Redux store w/ your reducer, subscriber, and middleware, you can use
it by calling store.dispatch_spawn(action)
. This kicks off a parallel Tokio task that
will run the middleware functions, reducer functions, and finally the subscriber
functions. So this will not block the thread of whatever code you call this from. The
dispatch_spawn()
method itself is not async
. So you can call it from non async
code,
however you still have to provide a Tokio executor / runtime, without which you will get a
panic when dispatch_spawn()
is called.
Middlewares
Your middleware (async
trait implementations) will be run concurrently or in parallel
via Tokio tasks. You get to choose which async
trait to implement to do one or the
other. And regardless of which kind you implement the Action
that is optionally returned
will be dispatched to the Redux store at the end of execution of all the middlewares (for
that particular dispatch_spawn()
call).
-
AsyncMiddlewareSpawns<State, Action>
- Your middleware has to usetokio::spawn
to runasync
blocks in a separate thread and return aJoinHandle
that contains anOption<Action>
. A macrofire_and_forget!
is provided so that you can easily spawn parallel blocks of code in yourasync
functions. These are added to the store via a call toadd_middleware_spawns(...)
. -
AsyncMiddleware<State, Action>
- They are will all be run together concurrently usingfutures::join_all()
. These are added to the store via a call toadd_middleware(...)
.
Subscribers
The subscribers will be run asynchronously via Tokio tasks. They are all run together
concurrently but not in parallel, using
futures::join_all()
.
Reducers
The reducer functions are also are async
functions that are run in the tokio runtime.
They're also run one after another in the order in which they're added.
β‘ Any functions or blocks that you write which uses the Redux library will have to be marked
async
as well. And you will have to spawn the Tokio runtime by using the#[tokio::main]
macro. If you use the default runtime then Tokio will use multiple threads and its task stealing implementation to give you parallel and concurrent behavior. You can also use the single threaded runtime; its really up to you.
-
To create middleware you have to implement the
AsyncMiddleware<S,A>
trait orAsyncMiddlewareSpawns<S,A>
trait. Please read theAsyncMiddleware
docs for examples of both. Therun()
method is passed two arguments: theState
and theAction
.- For
AsyncMiddlewareSpawns<S,A>
in yourrun()
implementation you have to use thefire_and_forget!
macro to surround your code. And this will return aJoinHandle<Option<A>>
. - For
AsyncMiddleware<S,A>
in yourrun()
implementation you just have to return anOption<A>>
.
- For
-
To create reducers you have to implement the
AsyncReducer
trait.- These should be
pure functions
and simply return a new
State
object. - The
run()
method will be passed two arguments: a ref toAction
and ref toState
.
- These should be
pure functions
and simply return a new
-
To create subscribers you have to implement the
AsyncSubscriber
trait.- The
run()
method will be passed aState
object as an argument. - It returns nothing
()
.
- The
Summary
Here's the gist of how to make & use one of these:
- Create a struct. Make it derive
Default
. Or you can add your own properties / fields to this struct, and construct it yourself, or even provide a constructor function.- A default constructor function
new()
is provided for you by the trait. - Just follow that works for when you need to make your own constructor function for a struct w/ your own properties.
- A default constructor function
- Implement the
AsyncMiddleware
,AsyncMiddlewareSpawns
,AsyncReducer
, orAsyncSubscriber
trait on your struct. - Register this struct w/ the store using one of the
add_middleware()
,add_middleware_spawns()
,add_reducer()
, oradd_subscriber()
methods. You can register as many of these as you like.- If you have a struct w/ no properties, you can just use the default
::new()
method to create an instance and pass that to theadd_???()
methods. - If you have a struct w/ custom properties, you can either implement your own
constructor function or use the following as an argument to the
add_???()
methods:Box::new($YOUR_STRUCT))
.
- If you have a struct w/ no properties, you can just use the default
Examples
π‘ There are lots of examples in the tests for this library and in this CLI application built using it.
Here's an example of how to use it. Let's start w/ the import statements.
/// Imports.
use async_trait;
use ;
use ;
use RwLock;
- Make sure to have the
tokio
andasync-trait
crates installed as well asr3bl_rs_utils
in yourCargo.toml
file.- Here's an example
Cargo.toml
.
Let's say we have the following action enum, and state struct.
/// Action enum.
/// State.
Here's an example of the reducer function.
/// Reducer function (pure).
;
Here's an example of an async subscriber function (which are run in parallel after an action is dispatched). The following example uses a lambda that captures a shared object. This is a pretty common pattern that you might encounter when creating subscribers that share state in your enclosing block or scope.
/// This shared object is used to collect results from the subscriber
/// function & test it later.
let shared_object = new;
let my_subscriber = MySubscriber ;
Here are two types of async middleware functions. One that returns an action (which will
get dispatched once this middleware returns), and another that doesn't return anything
(like a logger middleware that just dumps the current action to the console). Note that
both these functions share the shared_object
reference from above.
/// This shared object is used to collect results from the subscriber
/// function & test it later.
let mw_example_no_spawn = MwExampleNoSpawn ;
/// This shared object is used to collect results from the subscriber
/// function & test it later.
let mw_example_spawns = MwExampleSpawns ;
Here's how you can setup a store with the above reducer, middleware, and subscriber functions.
// Setup store.
let mut store = default;
store
.add_reducer // Note the use of `::new()` here.
.await
.add_subscriber
.await
.add_middleware_spawns
.await
.add_middleware
.await;
Finally here's an example of how to dispatch an action in a test. You can dispatch actions
in parallel using dispatch_spawn()
which is "fire and forget" meaning that the caller
won't block or wait for the dispatch_spawn()
to return.
// Test reducer and subscriber by dispatching `Add`, `AddPop`, `Clear` actions in parallel.
store.dispatch_spawn.await;
assert_eq!;
store.dispatch_spawn.await;
assert_eq!;
store.dispatch_spawn.await;
assert_eq!;
Macros
Declarative
There are quite a few declarative macros that you will find in the library. They tend to
be used internally in the implementation of the library itself. Here are some that are
actually externally exposed via #[macro_export]
.
log!
You can use this macro to dump log messages at 3 levels to a file. By default this file is
named log.txt
and is dumped in the current directory. Here's how you can use it. Please
note that the macro returns a Result
. A type alias is provided to save some typing
called ResultCommon<T>
which is just a short hand for
std::result::Result<T, Box<dyn Error>>
. The log file itself is overwritten for each
"session" that you run your program.
use ;
Please check out the source here.
make_api_call_for!
This macro makes it easy to create simple HTTP GET requests using the reqwest
crate. It
generates an async
function called make_request()
that returns a ResultCommon<T>
where T
is the type of the response body. Here's an example.
use ;
use make_api_call_for;
use ;
const ENDPOINT: &str = "https://api.namefake.com/english-united-states/female/";
make_api_call_for!
let fake_data = fake_contact_data_api
.await
.unwrap_or_else;
You can find lots of examples here.
fire_and_forget!
This is a really simple wrapper around tokio::spawn()
for the given block. Its just
syntactic sugar. Here's an example of using it for a non-async
block.
And, here's an example of using it for an async
block.
debug!
This is a really simple macro to make it effortless to use the color console logger. It
takes an identifier as an argument. It simply dumps an arrow symbol, followed by the
identifier (stringified) along with the value that it contains (using the Debug
formatter). All of the output is colorized for easy readability. You can use it like this.
let my_string = "Hello World!";
debug!;
with!
This is a macro that takes inspiration from the with
scoping function in Kotlin. It just
makes it easier to express a block of code that needs to run after an expression is
evaluated and saved to a given variable. Here's an example.
with!
It does the following:
- Evaluates the
$eval
expression and assigns it to$id
. - Runs the
$code
block.
Procedural
All the procedural macros are organized in 3 crates using an internal or core crate: the public crate, an internal or core crate, and the proc macro crate.
#[derive(Builder)]
This derive macro makes it easy to generate builders when annotating a struct
or enum
.
It generates It has full support for generics. It can be used like this.
let my_pt: = new
.set_x
.set_y
.build;
assert_eq!;
assert_eq!;
make_struct_safe_to_share_and_mutate!
This function like macro (with custom syntax) makes it easy to manage shareability and interior mutability of a struct. We call this pattern the "manager" of "things").
πͺ You can read all about it here.
- This struct gets wrapped in a
RwLock
for thread safety. - That is then wrapped inside an
Arc
so we can share it across threads. - Additionally it works w/ Tokio so that it is totally async. It also fully supports
generics and trait bounds w/ an optional
where
clause.
Here's a very simple usage:
make_struct_safe_to_share_and_mutate!
Here's an async example.
async
make_safe_async_fn_wrapper!
This function like macro (with custom syntax) makes it easy to share functions and lambdas that are async. They should be safe to share between threads and they should support either being invoked or spawned.
πͺ You can read all about how to write proc macros here.
- A struct is generated that wraps the given function or lambda in an
Arc<RwLock<>>
for thread safety and interior mutability. - A
get()
method is generated which makes it possible to share this struct across threads. - A
from()
method is generated which makes it easy to create this struct from a function or lambda. - A
spawn()
method is generated which makes it possible to spawn the enclosed function or lambda asynchronously using Tokio. - An
invoke()
method is generated which makes it possible to invoke the enclosed function or lambda synchronously.
Here's an example of how to use this macro.
use make_safe_async_fn_wrapper;
make_safe_async_fn_wrapper!
Here's another example.
use make_safe_async_fn_wrapper;
make_safe_async_fn_wrapper!
tree_memory_arena (non-binary tree data structure)
[Arena
] and [MTArena
] types are the implementation of a
non-binary tree data
structure that is inspired by memory arenas.
Here's a simple example of how to use the [Arena
] type:
use ;
let mut arena = new;
let node_1_value = 42 as usize;
let node_1_id = arena.add_new_node;
println!;
assert_eq!;
Here's how you get weak and strong references from the arena (tree), and tree walk:
use ;
let mut arena = new;
let node_1_value = 42 as usize;
let node_1_id = arena.add_new_node;
Here's an example of how to use the [MTArena
] type:
use ;
use ;
type ThreadResult = ;
type Handles = ;
let mut handles: Handles = Vec new;
let arena = new;
// Thread 1 - add root. Spawn and wait (since the 2 threads below need the root).
// Perform tree walking in parallel. Note the lambda does capture many enclosing variable context.
π There are more complex ways of using [
Arena
] and [MTArena
]. Please look at these extensive integration tests that put them thru their paces here.
utils
LazyMemoValues
This struct allows users to create a lazy hash map. A function must be provided that computes the values when they are first requested. These values are cached for the lifetime this struct. Here's an example.
use ;
use LazyMemoValues;
// These are copied in the closure below.
let arc_atomic_count = new;
let mut a_variable = 123;
let mut a_flag = false;
let mut generate_value_fn = new;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!; // Won't regenerate the value.
assert_eq!; // Doesn't change.
tty
This module contains a set of functions to make it easier to work with terminals.
The following is an example of how to use is_stdin_piped()
:
The following is an example of how to use readline()
:
use ;
Here's a list of functions available in this module:
readline_with_prompt()
print_prompt()
readline()
is_tty()
is_stdout_piped()
is_stdin_piped()
safe_unwrap
Functions that make it easy to unwrap a value safely. These functions are provided to
improve the ergonomics of using wrapped values in Rust. Examples of wrapped values are
<Arc<RwLock<T>>
, and <Option>
. These functions are inspired by Kotlin scope functions
& TypeScript expression based language library which can be found
here on r3bl-ts-utils
.
Here are some examples.
use ;
use ;
use ;
if let Some = parent_id_opt
Here's a list of functions that are provided:
call_if_some()
call_if_none()
call_if_ok()
call_if_err()
with()
with_mut()
unwrap_arc_write_lock_and_call()
unwrap_arc_read_lock_and_call()
Here's a list of type aliases provided for better readability:
ReadGuarded<T>
WriteGuarded<T>
color_text
ANSI colorized text https://github.com/ogham/rust-ansi-term helper methods. Here's an example.
use ;
Here's a list of functions available in this module:
print_header()
style_prompt()
style_primary()
style_dimmed()
style_error()
tui (experimental)
π§ WIP - This is an experimental module that isnβt ready yet. It is the first step towards
creating a TUI library that can be used to create sophisticated TUI applications. This is
similar to Ink library for Node.js & TypeScript (that uses React and Yoga). Or kinda like
tui
built atop crossterm
(and not termion
).
Stability
π§βπ¬ This library is in early development.
- There are extensive integration tests for code that is production ready.
- Everything else is marked experimental in the source.
Please report any issues to the issue tracker. And if you have any feature requests, feel free to add them there too π.
Here are some notes on using experimental / unstable features in Tokio.
# The rustflags needs to be set since we are using unstable features
# in Tokio.
# - https://github.com/tokio-rs/console
# - https://docs.rs/tokio/latest/tokio/#unstable-features
# This is how you set rustflags for cargo build defaults.
# - https://github.com/rust-lang/rust-analyzer/issues/5828
[]
= [
"--cfg", "tokio_unstable",
]