Crate grux

source ·
Expand description

A library for drawing grid-based user interfaces using ASCII characters.

grux provides:

  • A uniform interface for drawing to a 2D grid: GridWriter.
  • A uniform interface for displaying a 2D grid: DisplayGrid.

The grux::art module provides helper types for drawing ASCII art.

Examples

Using a fixed-size nested array

💡 TIP: Use a fixed-size nested array for a grid dimensions known ahead of time.

  • Nested arrays will be faster and more efficient than a growable grid
  • Nested arrays support Display trait for cells, which means graphemes are supported and ANSI escape codes can be used for colors (see examples/emojis.rs and examples/ansi.rs).
use grux::GridWriter;

// Create a 2x2 array of zeros.
let mut array = [[0; 2]; 2];

// Set the element at (1, 1) to 1.
array.set((1, 1), 1);
assert_eq!(array, [[0, 0], [0, 1]]);

Using a growable nested vector

💡 TIP: Use a growable nested vector for a grid dimensions not known ahead of time.

  • Nested vectors will be slower and less efficient than a fixed-size grid
  • Nested vectors support Display trait for cells, which means graphemes are supported
  • A rectangular grid is not guaranteed
use grux::GridWriter;

// Create an empty vector (of vectors)
let mut vec: Vec<Vec<i32>> = Vec::new();

// Set the element at (1, 1) to 1.
// This will grow the vector to fit the position, adding empty default vectors as needed.
vec.set((1, 1), 1);
assert_eq!(vec, vec![vec![], vec![0, 1]]);

Using a growable string

⚠️ WARNING: Only supports ASCII characters (char) and not graphemes or ANSI escape codes.

  • Strings are not as efficient or flexible as nested arrays or vectors
  • Strings do not support graphemes or ANSI escape codes
  • A rectangular grid is not guaranteed

See print any grid to a output stream for alternatives.

use grux::GridWriter;

// Create an empty string.
let mut string = String::new();

// Set the element at (1, 2) to '1'.
// This will grow the string to fit the position, adding empty lines as needed.
string.set((1, 2), '1');
assert_eq!(string, "\n\n 1");

Any type that implements DisplayGrid can be printed to a output stream or a new string.

use grux::DisplayGrid;

// Create a 3x3 array of the letters 'A' - 'I'.
let mut array = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']];

// Convert the array to a string.
// TIP: Use `print` instead if you want to print to a output stream.
let string = array.to_string().unwrap();

assert_eq!(string, "ABC\nDEF\nGHI\n");

Modules

Configure and draw simple ASCII or ASCII-like* sprites to a 2D grid.

Traits

A trait that can be used to display a grid-like buffer to a output stream or a new string.
A trait for a grid-like writable buffer, typically with a fixed width and height.