Context

R3BL TUI library & suite of apps focused on developer productivity

We are working on building command line apps in Rust which have rich text user interfaces (TUI). We want to lean into the terminal as a place of productivity, and build all kinds of awesome apps for it.

  1. 🔮 Instead of just building one app, we are building a library to enable any kind of rich TUI development w/ a twist: taking concepts that work really well for the frontend mobile and web development world and re-imagining them for TUI & Rust.

  2. 🌎 We are building apps to enhance developer productivity & workflows.

r3blrsutils

This crate is the first thing that's described above. It provides lots of useful functionality to help you build TUI (text user interface) apps, along w/ general niceties & ergonomics that all Rustaceans 🦀 can enjoy 🎉:

This crate provides lots of useful functionality to help you build TUI (text user interface) apps, along w/ general niceties & ergonomics that all Rustaceans 🦀 can enjoy 🎉:

  1. Loosely coupled & fully asynchronous TUI framework to make it possible (and easy) to build sophisticated TUIs (Text User Interface apps) in Rust.
  2. Fully asynchronous & thread safe Redux library (using Tokio to run subscribers and middleware in separate tasks). The reducer functions are run sequentially.
  3. 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.
  4. Utility functions to improve ergonomics of commonly used patterns in Rust programming, ranging from things like colorizing stdout, stderr output, to having less noisy Result and Error types.
  5. Non binary tree data structure (written more like a graph than a non binary tree) inspired by memory arenas, that is thread safe and supports parallel tree walking.

🦜 To learn more about this library, please read how it was built (on developerlife.com):

  1. https://developerlife.com/2022/02/24/rust-non-binary-tree/
  2. https://developerlife.com/2022/03/12/rust-redux/
  3. https://developerlife.com/2022/03/30/rust-proc-macro/

🦀 You can also find all the Rust related content on developerlife.com here.

🤷‍♂️ Fun fact: before we built this crate, we built a library that is similar in spirit for TypeScript (for TUI apps on Node.js) called r3bl-ts-utils. We have since switched to Rust 🦀🎉.


Table of contents:


tui and tui_core

For more information please read the README for the r3bl_tui crate.

Here's a video of the demo in action:

https://user-images.githubusercontent.com/2966499/193947362-0c4fd1c8-d0fb-4bfc-9a07-9d36a9dda5ce.webm

redux

For more information please read the README for the r3bl_redux crate.

Macros

Declarative

For more information please read the README for the r3blrsutils_core crate.

Procedural

For more information please read the README for the r3blrsutils_macro crate.

treememoryarena (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:

```rust use r3blrsutils::{ treememoryarena::{Arena, HasId, MTArena, ResultUidList}, utils::{styleprimary, styleprompt}, };

let mut arena = Arena::::new(); let node1value = 42 as usize; let node1id = arena.addnewnode(node1value, None); println!("{} {:#?}", styleprimary("node1id"), node1id); asserteq!(node1id, 0); ```

Here's how you get weak and strong references from the arena (tree), and tree walk:

```rust use r3blrsutils::{ treememoryarena::{Arena, HasId, MTArena, ResultUidList}, utils::{styleprimary, styleprompt}, };

let mut arena = Arena::::new(); let node1value = 42 as usize; let node1id = arena.addnewnode(node1value, None);

{ assert!(arena.getnodearc(&node1id).issome()); let node1ref = dbg!(arena.getnodearc(&node1id).unwrap()); let node1refweak = arena.getnodearcweak(&node1id).unwrap(); asserteq!(node1ref.read().unwrap().payload, node1value); asserteq!( node1refweak.upgrade().unwrap().read().unwrap().payload, 42 ); }

{ let nodeiddne = 200 as usize; assert!(arena.getnodearc(&nodeiddne).is_none()); }

{ let node1id = 0 as usize; let nodelist = dbg!(arena.treewalkdfs(&node1id).unwrap()); asserteq!(nodelist.len(), 1); asserteq!(node_list, vec![0]); } ```

Here's an example of how to use the [MTArena] type:

```rust use std::{ sync::Arc, thread::{self, JoinHandle}, };

use r3blrsutils::{ treememoryarena::{Arena, HasId, MTArena, ResultUidList}, utils::{styleprimary, styleprompt}, };

type ThreadResult = Vec; type Handles = Vec>;

let mut handles: Handles = Vec::new(); let arena = MTArena::::new();

// Thread 1 - add root. Spawn and wait (since the 2 threads below need the root). { let arenaarc = arena.getarenaarc(); let thread = thread::spawn(move || { let mut arenawrite = arenaarc.write().unwrap(); let root = arenawrite.addnewnode("foo".to_string(), None); vec![root] }); thread.join().unwrap(); }

// Perform tree walking in parallel. Note the lambda does capture many enclosing variable context. { let arenaarc = arena.getarenaarc(); let fnarc = Arc::new(move |uid, payload| { println!( "{} {} {} Arena weakcount:{} strongcount:{}", styleprimary("walkerfn - closure"), uid, payload, Arc::weakcount(&arenaarc), Arc::weakcount(&arenaarc) ); });

// Walk tree w/ a new thread using arc to lambda. { let threadhandle: JoinHandle = arena.treewalkparallel(&0, fnarc.clone());

let result_node_list = thread_handle.join().unwrap();
println!("{:#?}", result_node_list);

}

// Walk tree w/ a new thread using arc to lambda. { let threadhandle: JoinHandle = arena.treewalkparallel(&1, fnarc.clone());

let result_node_list = thread_handle.join().unwrap();
println!("{:#?}", result_node_list);

} } ```

📜 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

LazyField

This combo of struct & trait object allows you to create a lazy field that is only evaluated when it is first accessed. You have to provide a trait implementation that computes the value of the field (once). Here's an example.

```rust use r3blrsutils::{LazyExecutor, LazyField};

[test]

fn testlazyfield() { struct MyExecutor; impl LazyExecutor for MyExecutor { fn compute(&mut self) -> i32 { 1 } }

let mut lazyfield = LazyField::new(Box::new(MyExecutor)); asserteq!(lazyfield.hascomputed, false);

// First access will trigger the computation. let value = lazyfield.compute(); asserteq!(lazyfield.hascomputed, true); assert_eq!(value, 1);

// Subsequent accesses will not trigger the computation. let value = lazyfield.compute(); asserteq!(lazyfield.hascomputed, true); assert_eq!(value, 1); } ```

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.

```rust use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use r3blrsutils::utils::LazyMemoValues;

// These are copied in the closure below. let arcatomiccount = AtomicUsize::new(0); let mut avariable = 123; let mut aflag = false;

let mut generatevaluefn = LazyMemoValues::new(|it| { arcatomiccount.fetchadd(1, SeqCst); avariable = 12; aflag = true; avariable + it });

asserteq!(arcatomiccount.load(SeqCst), 0); asserteq!(generatevaluefn.getref(&1), &13); asserteq!(arcatomiccount.load(SeqCst), 1); asserteq!(generatevaluefn.getref(&1), &13); // Won't regenerate the value. asserteq!(arcatomic_count.load(SeqCst), 1); // 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():

rust fn run(args: Vec<String>) -> Result<(), Box<dyn Error>> { match is_stdin_piped() { true => piped_grep(PipedGrepOptionsBuilder::parse(args)?)?, false => grep(GrepOptionsBuilder::parse(args)?)?, } Ok(()) }

The following is an example of how to use readline():

```rust use r3blrsutils::utils::{ printheader, readline, styledimmed, styleerror, styleprimary, style_prompt, };

fn makeaguess() -> String { println!("{}", Blue.paint("Please input your guess.")); let (bytesread, guess) = readline(); println!( "{} {}, {} {}", styledimmed("#bytes read:"), styleprimary(&bytesread.tostring()), styledimmed("You guessed:"), style_primary(&guess) ); guess } ```

Here's a list of functions available in this module:

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.

```rust use r3blrsutils::utils::{ callifsome, unwraparcreadlockandcall, unwraparcwritelockandcall, withmut, }; use r3blrsutils::utils::{ReadGuarded, WriteGuarded}; use r3blrsutils::{ arenatypes::HasId, ArenaMap, FilterFn, NodeRef, ResultUidList, WeakNodeRef, };

if let Some(parentid) = parentidopt { let parentnodearcopt = self.getnodearc(parentid); callifsome(&parentnodearcopt, &|parentnodearc| { unwraparcwritelockandcall(&parentnodearc, &mut |parentnode| { parentnode.children.push(newnode_id); }); }); } ```

Here's a list of functions that are provided:

Here's a list of type aliases provided for better readability:

color_text

ANSI colorized text https://github.com/ogham/rust-ansi-term helper methods. Here's an example.

```rust use r3blrsutils::utils::{ printheader, readline, styledimmed, styleerror, styleprimary, style_prompt, };

fn makeaguess() -> String { println!("{}", Blue.paint("Please input your guess.")); let (bytesread, guess) = readline(); println!( "{} {}, {} {}", styledimmed("#bytes read:"), styleprimary(&bytesread.tostring()), styledimmed("You guessed:"), style_primary(&guess) ); guess } ```

Here's a list of functions available in this module:

Notes

Here are some notes on using experimental / unstable features in Tokio.

```toml

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

[target.x8664-unknown-linux-gnu] rustflags = [ "--cfg", "tokiounstable", ] ```

Issues, comments, feedback, and PRs

Please report any issues to the issue tracker. And if you have any feature requests, feel free to add them there too 👍.