uutils_term_grid-0.6.0/.cargo_vcs_info.json0000644000000001360000000000100144200ustar { "git": { "sha1": "2b15ba7625dfeaa19ca5530236aca7ee72069abc" }, "path_in_vcs": "" }uutils_term_grid-0.6.0/.github/workflows/ci.yml000064400000000000000000000124111046102023000177220ustar 00000000000000name: CI # Continuous Integration on: push: branches: - main pull_request: env: CARGO_TERM_COLOR: always jobs: test: name: Test Suite runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - run: cargo test --all-features --workspace rustfmt: name: Rustfmt runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: components: rustfmt - uses: Swatinem/rust-cache@v2 - name: Check formatting run: cargo fmt --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: components: clippy - uses: Swatinem/rust-cache@v2 - name: Clippy check run: cargo clippy --all-targets --all-features --workspace -- -D warnings docs: name: Docs runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - name: Check documentation env: RUSTDOCFLAGS: -D warnings run: cargo doc coverage: name: Code Coverage runs-on: ${{ matrix.job.os }} strategy: fail-fast: true matrix: job: - { os: ubuntu-latest , features: unix } - { os: macos-latest , features: macos } - { os: windows-latest , features: windows } steps: - uses: actions/checkout@v4 - name: Initialize workflow variables id: vars shell: bash run: | ## VARs setup outputs() { step_id="vars"; for var in "$@" ; do echo steps.${step_id}.outputs.${var}="${!var}"; echo "${var}=${!var}" >> $GITHUB_OUTPUT; done; } # toolchain TOOLCHAIN="nightly" ## default to "nightly" toolchain (required for certain required unstable compiler flags) ## !maint: refactor when stable channel has needed support # * specify gnu-type TOOLCHAIN for windows; `grcov` requires gnu-style code coverage data files case ${{ matrix.job.os }} in windows-*) TOOLCHAIN="$TOOLCHAIN-x86_64-pc-windows-gnu" ;; esac; # * use requested TOOLCHAIN if specified if [ -n "${{ matrix.job.toolchain }}" ]; then TOOLCHAIN="${{ matrix.job.toolchain }}" ; fi outputs TOOLCHAIN # target-specific options # * CARGO_FEATURES_OPTION CARGO_FEATURES_OPTION='--all -- --check' ; ## default to '--all-features' for code coverage # * CODECOV_FLAGS CODECOV_FLAGS=$( echo "${{ matrix.job.os }}" | sed 's/[^[:alnum:]]/_/g' ) outputs CODECOV_FLAGS - name: rust toolchain ~ install uses: dtolnay/rust-toolchain@nightly - name: Test run: cargo test ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} --no-fail-fast env: CARGO_INCREMENTAL: "0" RUSTC_WRAPPER: "" RUSTFLAGS: "-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort" RUSTDOCFLAGS: "-Cpanic=abort" - name: "`grcov` ~ install" id: build_grcov shell: bash run: | git clone https://github.com/mozilla/grcov.git ~/grcov/ cd ~/grcov # Hardcode the version of crossbeam-epoch. See # https://github.com/uutils/coreutils/issues/3680 sed -i -e "s|tempfile =|crossbeam-epoch = \"=0.9.8\"\ntempfile =|" Cargo.toml cargo install --path . cd - # Uncomment when the upstream issue # https://github.com/mozilla/grcov/issues/849 is fixed # uses: actions-rs/install@v0.1 # with: # crate: grcov # version: latest # use-tool-cache: false - name: Generate coverage data (via `grcov`) id: coverage shell: bash run: | ## Generate coverage data COVERAGE_REPORT_DIR="target/debug" COVERAGE_REPORT_FILE="${COVERAGE_REPORT_DIR}/lcov.info" mkdir -p "${COVERAGE_REPORT_DIR}" # display coverage files grcov . --output-type files --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()" | sort --unique # generate coverage report grcov . --output-type lcov --output-path "${COVERAGE_REPORT_FILE}" --branch --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()" echo "name=report::${COVERAGE_REPORT_FILE}" >> $GITHUB_OUTPUT - name: Upload coverage results (to Codecov.io) uses: codecov/codecov-action@v4 # if: steps.vars.outputs.HAS_CODECOV_TOKEN with: # token: ${{ secrets.CODECOV_TOKEN }} file: ${{ steps.coverage.outputs.report }} ## flags: IntegrationTests, UnitTests, ${{ steps.vars.outputs.CODECOV_FLAGS }} flags: ${{ steps.vars.outputs.CODECOV_FLAGS }} name: codecov-umbrella fail_ci_if_error: false uutils_term_grid-0.6.0/.gitignore000064400000000000000000000000221046102023000151720ustar 00000000000000target Cargo.lock uutils_term_grid-0.6.0/Cargo.lock0000644000000011570000000000100123770ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "ansi-width" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "219e3ce6f2611d83b51ec2098a12702112c29e57203a6b0a0929b2cddb486608" dependencies = [ "unicode-width", ] [[package]] name = "unicode-width" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" [[package]] name = "uutils_term_grid" version = "0.6.0" dependencies = [ "ansi-width", ] uutils_term_grid-0.6.0/Cargo.toml0000644000000016550000000000100124250ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.70" name = "uutils_term_grid" version = "0.6.0" authors = [ "uutils developers", "Benjamin Sago ", ] description = "Library for formatting strings into a grid layout. Fork of term_grid." documentation = "https://docs.rs/uutils_term_grid/" readme = "README.md" license = "MIT" repository = "https://github.com/uutils/uutils-term-grid" [lib] name = "term_grid" [dependencies.ansi-width] version = "0.1.0" uutils_term_grid-0.6.0/Cargo.toml.orig000064400000000000000000000007101046102023000160750ustar 00000000000000[package] name = "uutils_term_grid" description = "Library for formatting strings into a grid layout. Fork of term_grid." authors = ["uutils developers", "Benjamin Sago "] documentation = "https://docs.rs/uutils_term_grid/" license = "MIT" readme = "README.md" repository = "https://github.com/uutils/uutils-term-grid" version = "0.6.0" edition = "2021" rust-version = "1.70" [lib] name = "term_grid" [dependencies] ansi-width = "0.1.0" uutils_term_grid-0.6.0/Justfile000064400000000000000000000011241046102023000147160ustar 00000000000000all: build test all-release: build-release test-release MIN_RUST := "1.31.0" # compiles the code build: cargo +{{MIN_RUST}} build cargo +stable build # compiles the code in release mode build-release: cargo +{{MIN_RUST}} build --release --verbose cargo +stable build --release --verbose # runs unit tests test: cargo +{{MIN_RUST}} test --all -- --quiet cargo +stable test --all -- --quiet # runs unit tests in release mode test-release: cargo +{{MIN_RUST}} test --all --release --verbose cargo +stable test --all --release --verbose uutils_term_grid-0.6.0/LICENSE000064400000000000000000000020561046102023000142200ustar 00000000000000MIT License Copyright (c) 2018 Benjamin Sago 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. uutils_term_grid-0.6.0/README.md000064400000000000000000000071651046102023000145000ustar 00000000000000[![Crates.io](https://img.shields.io/crates/v/uutils-term-grid.svg)](https://crates.io/crates/uutils-term-grid) [![dependency status](https://deps.rs/repo/github/uutils/uutils-term-grid/status.svg)](https://deps.rs/repo/github/uutils/uutils-term-grid) [![CodeCov](https://codecov.io/gh/uutils/uutils-term-grid/branch/master/graph/badge.svg)](https://codecov.io/gh/uutils/uutils-term-grid) # uutils-term-grid This library arranges textual data in a grid format suitable for fixed-width fonts, using an algorithm to minimise the amount of space needed. --- This library is forked from the unmaintained [`rust-term-grid`](https://github.com/ogham/rust-term-grid) library. The core functionality has remained the same, with some additional bugfixes, performance improvements and a new API. --- # Installation This crate works with `cargo`. Add the following to your `Cargo.toml` dependencies section: ```toml [dependencies] uutils_term_grid = "0.4" ``` The Minimum Supported Rust Version is 1.70. ## Creating a grid To add data to a grid, first create a new [`Grid`] value with a list of strings and a set of options. There are three options that must be specified in the [`GridOptions`] value that dictate how the grid is formatted: - [`filling`][filling]: what to put in between two columns — either a number of spaces, or a text string; - [`direction`][direction]: specifies whether the cells should go along rows, or columns: - [`Direction::LeftToRight`][LeftToRight] starts them in the top left and moves _rightwards_, going to the start of a new row after reaching the final column; - [`Direction::TopToBottom`][TopToBottom] starts them in the top left and moves _downwards_, going to the top of a new column after reaching the final row. - [`width`][width]: the width to fill the grid into. Usually, this should be the width of the terminal. In practice, creating a grid can be done as follows: ```rust use term_grid::{Grid, GridOptions, Direction, Filling}; // Create a `Vec` of text to put in the grid let cells = vec![ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve" ]; // Then create a `Grid` with those cells. // The grid requires several options: // - The filling determines the string used as separator // between the columns. // - The direction specifies whether the layout should // be done row-wise or column-wise. // - The width is the maximum width that the grid might // have. let grid = Grid::new( cells, GridOptions { filling: Filling::Spaces(1), direction: Direction::LeftToRight, width: 24, } ); // A `Grid` implements `Display` and can be printed directly. println!("{grid}"); ``` Produces the following tabular result: ```text one two three four five six seven eight nine ten eleven twelve ``` [filling]: struct.GridOptions.html#structfield.filling [direction]: struct.GridOptions.html#structfield.direction [width]: struct.GridOptions.html#structfield.width [LeftToRight]: enum.Direction.html#variant.LeftToRight [TopToBottom]: enum.Direction.html#variant.TopToBottom ## Width of grid cells This library calculates the width of strings as displayed in the terminal using the [`textwrap`][textwrap] library (with the [`display_width`][display_width] function). This takes into account the width of characters and ignores ANSI codes. The width calculation is currently not configurable. If you have a use-case for which this calculation is wrong, please open an issue. [textwrap]: https://docs.rs/textwrap/latest/textwrap/index.html [display_width]: https://docs.rs/textwrap/latest/textwrap/core/fn.display_width.html uutils_term_grid-0.6.0/examples/basic.rs000064400000000000000000000021061046102023000164540ustar 00000000000000// For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. use term_grid::{Direction, Filling, Grid, GridOptions}; // This produces: // // 1 | 128 | 16384 | 2097152 | 268435456 | 34359738368 | 4398046511104 // 2 | 256 | 32768 | 4194304 | 536870912 | 68719476736 | 8796093022208 // 4 | 512 | 65536 | 8388608 | 1073741824 | 137438953472 | 17592186044416 // 8 | 1024 | 131072 | 16777216 | 2147483648 | 274877906944 | 35184372088832 // 16 | 2048 | 262144 | 33554432 | 4294967296 | 549755813888 | 70368744177664 // 32 | 4096 | 524288 | 67108864 | 8589934592 | 1099511627776 | 140737488355328 // 64 | 8192 | 1048576 | 134217728 | 17179869184 | 2199023255552 | fn main() { let cells: Vec<_> = (0..48).map(|i| 2_isize.pow(i).to_string()).collect(); let grid = Grid::new( cells, GridOptions { direction: Direction::TopToBottom, filling: Filling::Text(" | ".into()), width: 80, }, ); println!("{}", grid); } uutils_term_grid-0.6.0/examples/big.rs000064400000000000000000000012511046102023000161340ustar 00000000000000// For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. use term_grid::{Direction, Filling, Grid, GridOptions}; fn main() { let mut n: u64 = 1234; for _ in 0..50 { let mut cells = Vec::new(); for _ in 0..10000 { cells.push(n.to_string()); n = n.overflowing_pow(2).0 % 100000000; } let grid = Grid::new( cells, GridOptions { direction: Direction::TopToBottom, filling: Filling::Text(" | ".into()), width: 80, }, ); println!("{grid}"); } } uutils_term_grid-0.6.0/renovate.json000064400000000000000000000001531046102023000157250ustar 00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:base" ] } uutils_term_grid-0.6.0/src/lib.rs000064400000000000000000000264141046102023000151220ustar 00000000000000// For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #![warn(future_incompatible)] #![warn(missing_copy_implementations)] #![warn(missing_docs)] #![warn(nonstandard_style)] #![warn(trivial_casts, trivial_numeric_casts)] #![warn(unused)] #![deny(unsafe_code)] #![doc = include_str!("../README.md")] use ansi_width::ansi_width; use std::fmt; /// Direction cells should be written in: either across or downwards. #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub enum Direction { /// Starts at the top left and moves rightwards, going back to the first /// column for a new row, like a typewriter. LeftToRight, /// Starts at the top left and moves downwards, going back to the first /// row for a new column, like how `ls` lists files by default. TopToBottom, } /// The text to put in between each pair of columns. /// /// This does not include any spaces used when aligning cells. #[derive(PartialEq, Eq, Debug)] pub enum Filling { /// A number of spaces Spaces(usize), /// An arbitrary string /// /// `"|"` is a common choice. Text(String), } impl Filling { fn width(&self) -> usize { match self { Filling::Spaces(w) => *w, Filling::Text(t) => ansi_width(t), } } } /// The options for a grid view that should be passed to [`Grid::new`] #[derive(Debug)] pub struct GridOptions { /// The direction that the cells should be written in pub direction: Direction, /// The string to put in between each column of cells pub filling: Filling, /// The width to fill with the grid pub width: usize, } #[derive(PartialEq, Eq, Debug)] struct Dimensions { /// The number of lines in the grid. num_lines: usize, /// The width of each column in the grid. The length of this vector serves /// as the number of columns. widths: Vec, } impl Dimensions { fn total_width(&self, separator_width: usize) -> usize { if self.widths.is_empty() { 0 } else { let values = self.widths.iter().sum::(); let separators = separator_width * (self.widths.len() - 1); values + separators } } } /// Everything needed to format the cells with the grid options. #[derive(Debug)] pub struct Grid> { options: GridOptions, cells: Vec, widths: Vec, widest_cell_width: usize, dimensions: Dimensions, } impl> Grid { /// Creates a new grid view with the given cells and options pub fn new(cells: Vec, options: GridOptions) -> Self { let widths: Vec = cells.iter().map(|c| ansi_width(c.as_ref())).collect(); let widest_cell_width = widths.iter().copied().max().unwrap_or(0); let width = options.width; let mut grid = Self { options, cells, widths, widest_cell_width, dimensions: Dimensions { num_lines: 0, widths: Vec::new(), }, }; grid.dimensions = grid.width_dimensions(width).unwrap_or(Dimensions { num_lines: grid.cells.len(), widths: vec![widest_cell_width], }); grid } /// The number of terminal columns this display takes up, based on the separator /// width and the number and width of the columns. pub fn width(&self) -> usize { self.dimensions.total_width(self.options.filling.width()) } /// The number of rows this display takes up. pub fn row_count(&self) -> usize { self.dimensions.num_lines } /// The width of each column pub fn column_widths(&self) -> &[usize] { &self.dimensions.widths } /// Returns whether this display takes up as many columns as were allotted /// to it. /// /// It’s possible to construct tables that don’t actually use up all the /// columns that they could, such as when there are more columns than /// cells! In this case, a column would have a width of zero. This just /// checks for that. pub fn is_complete(&self) -> bool { self.dimensions.widths.iter().all(|&x| x > 0) } fn compute_dimensions(&self, num_lines: usize, num_columns: usize) -> Dimensions { let mut column_widths = vec![0; num_columns]; for (index, cell_width) in self.widths.iter().copied().enumerate() { let index = match self.options.direction { Direction::LeftToRight => index % num_columns, Direction::TopToBottom => index / num_lines, }; if cell_width > column_widths[index] { column_widths[index] = cell_width; } } Dimensions { num_lines, widths: column_widths, } } fn theoretical_max_num_lines(&self, maximum_width: usize) -> usize { // TODO: Make code readable / efficient. let mut widths = self.widths.clone(); // Sort widths in reverse order widths.sort_unstable_by(|a, b| b.cmp(a)); let mut col_total_width_so_far = 0; for (i, &width) in widths.iter().enumerate() { let adjusted_width = if i == 0 { width } else { width + self.options.filling.width() }; if col_total_width_so_far + adjusted_width <= maximum_width { col_total_width_so_far += adjusted_width; } else { return div_ceil(self.cells.len(), i); } } // If we make it to this point, we have exhausted all cells before // reaching the maximum width; the theoretical max number of lines // needed to display all cells is 1. 1 } fn width_dimensions(&self, maximum_width: usize) -> Option { if self.widest_cell_width > maximum_width { // Largest cell is wider than maximum width; it is impossible to fit. return None; } if self.cells.is_empty() { return Some(Dimensions { num_lines: 0, widths: Vec::new(), }); } if self.cells.len() == 1 { let cell_widths = self.widths[0]; return Some(Dimensions { num_lines: 1, widths: vec![cell_widths], }); } let theoretical_max_num_lines = self.theoretical_max_num_lines(maximum_width); if theoretical_max_num_lines == 1 { // This if—statement is necessary for the function to work correctly // for small inputs. return Some(Dimensions { num_lines: 1, widths: self.widths.clone(), }); } // Instead of numbers of columns, try to find the fewest number of *lines* // that the output will fit in. let mut smallest_dimensions_yet = None; for num_lines in (1..=theoretical_max_num_lines).rev() { // The number of columns is the number of cells divided by the number // of lines, *rounded up*. let num_columns = div_ceil(self.cells.len(), num_lines); // Early abort: if there are so many columns that the width of the // *column separators* is bigger than the width of the screen, then // don’t even try to tabulate it. // This is actually a necessary check, because the width is stored as // a usize, and making it go negative makes it huge instead, but it // also serves as a speed-up. let total_separator_width = (num_columns - 1) * self.options.filling.width(); if maximum_width < total_separator_width { continue; } // Remove the separator width from the available space. let adjusted_width = maximum_width - total_separator_width; let potential_dimensions = self.compute_dimensions(num_lines, num_columns); if potential_dimensions.widths.iter().sum::() <= adjusted_width { smallest_dimensions_yet = Some(potential_dimensions); } else { break; } } smallest_dimensions_yet } } impl> fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { let separator = match &self.options.filling { Filling::Spaces(n) => " ".repeat(*n), Filling::Text(s) => s.clone(), }; // Initialize a buffer of spaces. The idea here is that any cell // that needs padding gets a slice of this buffer of the needed // size. This avoids the need of creating a string of spaces for // each cell that needs padding. // // We overestimate how many spaces we need, but this is not // part of the loop and it's therefore not super important to // get exactly right. let padding = " ".repeat(self.widest_cell_width); for y in 0..self.dimensions.num_lines { for x in 0..self.dimensions.widths.len() { let num = match self.options.direction { Direction::LeftToRight => y * self.dimensions.widths.len() + x, Direction::TopToBottom => y + self.dimensions.num_lines * x, }; // Abandon a line mid-way through if that’s where the cells end if num >= self.cells.len() { continue; } let contents = &self.cells[num]; let width = self.widths[num]; let last_in_row = x == self.dimensions.widths.len() - 1; let col_width = self.dimensions.widths[x]; let padding_size = col_width - width; // The final column doesn’t need to have trailing spaces, // as long as it’s left-aligned. // // We use write_str directly instead of a the write! macro to // avoid some of the formatting overhead. For example, if we pad // using `write!("{contents:>width}")`, the unicode width will // have to be independently calculated by the macro, which is slow and // redundant because we already know the width. // // For the padding, we instead slice into a buffer of spaces defined // above, so we don't need to call `" ".repeat(n)` each loop. // We also only call `write_str` when we actually need padding as // another optimization. f.write_str(contents.as_ref())?; if !last_in_row { if padding_size > 0 { f.write_str(&padding[0..padding_size])?; } f.write_str(&separator)?; } } f.write_str("\n")?; } Ok(()) } } // Adapted from the unstable API: // https://doc.rust-lang.org/std/primitive.usize.html#method.div_ceil // Can be removed on MSRV 1.73. /// Division with upward rounding pub const fn div_ceil(lhs: usize, rhs: usize) -> usize { let d = lhs / rhs; let r = lhs % rhs; if r > 0 && rhs > 0 { d + 1 } else { d } } uutils_term_grid-0.6.0/tests/test.rs000064400000000000000000000203051046102023000156770ustar 00000000000000// For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore underflowed use term_grid::{Direction, Filling, Grid, GridOptions}; #[test] fn no_items() { let grid = Grid::new( Vec::::new(), GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 40, }, ); assert_eq!("", grid.to_string()); } #[test] fn one_item() { let grid = Grid::new( vec!["1"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 40, }, ); assert_eq!("1\n", grid.to_string()); } #[test] fn one_item_exact_width() { let grid = Grid::new( vec!["1234567890"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 10, }, ); assert_eq!("1234567890\n", grid.to_string()); } #[test] fn one_item_just_over() { let grid = Grid::new( vec!["1234567890!"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 10, }, ); assert_eq!(grid.row_count(), 1); } #[test] fn two_small_items() { let grid = Grid::new( vec!["1", "2"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 40, }, ); assert_eq!(grid.width(), 1 + 2 + 1); assert_eq!("1 2\n", grid.to_string()); } #[test] fn two_medium_size_items() { let grid = Grid::new( vec!["hello there", "how are you today?"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 40, }, ); assert_eq!(grid.width(), 11 + 2 + 18); assert_eq!("hello there how are you today?\n", grid.to_string()); } #[test] fn two_big_items() { let grid = Grid::new( vec![ "nuihuneihsoenhisenouiuteinhdauisdonhuisudoiosadiuohnteihaosdinhteuieudi", "oudisnuthasuouneohbueobaugceoduhbsauglcobeuhnaeouosbubaoecgueoubeohubeo", ], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 40, }, ); assert_eq!(grid.row_count(), 2); } #[test] fn that_example_from_earlier() { let grid = Grid::new( vec![ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ], GridOptions { filling: Filling::Spaces(1), direction: Direction::LeftToRight, width: 24, }, ); let bits = "one two three four\nfive six seven eight\nnine ten eleven twelve\n"; assert_eq!(grid.to_string(), bits); assert_eq!(grid.row_count(), 3); } #[test] fn number_grid_with_pipe() { let grid = Grid::new( vec![ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ], GridOptions { filling: Filling::Text("|".into()), direction: Direction::LeftToRight, width: 24, }, ); let bits = "one |two|three |four\nfive|six|seven |eight\nnine|ten|eleven|twelve\n"; assert_eq!(grid.to_string(), bits); assert_eq!(grid.row_count(), 3); } #[test] fn huge_separator() { let grid = Grid::new( vec!["a", "b"], GridOptions { filling: Filling::Spaces(100), direction: Direction::LeftToRight, width: 99, }, ); assert_eq!(grid.row_count(), 2); } #[test] fn huge_yet_unused_separator() { let grid = Grid::new( vec!["abcd"], GridOptions { filling: Filling::Spaces(100), direction: Direction::LeftToRight, width: 99, }, ); assert_eq!(grid.width(), 4); assert_eq!("abcd\n", grid.to_string()); } // Note: This behaviour is right or wrong depending on your terminal // This test is mostly added so that we don't change our current // behaviour, unless we explicitly want to do that. #[test] fn emoji() { let grid = Grid::new( vec!["🦀", "hello", "👩‍🔬", "hello"], GridOptions { direction: Direction::LeftToRight, filling: Filling::Spaces(2), width: 12, }, ); assert_eq!("🦀 hello\n👩‍🔬 hello\n", grid.to_string()); } // This test once underflowed, which should never happen. The test is just // checking that we do not get a panic. #[test] fn possible_underflow() { let cells: Vec<_> = (0..48).map(|i| 2_isize.pow(i).to_string()).collect(); let grid = Grid::new( cells, GridOptions { direction: Direction::TopToBottom, filling: Filling::Text(" | ".into()), width: 15, }, ); println!("{}", grid); } #[test] fn exact_fit() { let grid = Grid::new( vec!["a", "b", "c", "d"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 4, }, ); assert_eq!(grid.row_count(), 2); } // This is a reproduction of https://github.com/eza-community/eza/issues/845 #[test] fn eza_many_folders() { let cells: Vec<_> = (100000i32..=100401).map(|i| i.to_string()).collect(); let grid = Grid::new( cells, GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 166, }, ); assert_eq!(grid.row_count(), 20); } // These test are based on the tests in uutils ls, to ensure we won't break // it while editing this library. mod uutils_ls { use super::*; #[test] fn different_widths() { for (width, expected) in [ ( 100, "test-width-1 test-width-2 test-width-3 test-width-4\n", ), ( 50, "test-width-1 test-width-3\ntest-width-2 test-width-4\n", ), ( 25, "test-width-1\ntest-width-2\ntest-width-3\ntest-width-4\n", ), ] { let grid = Grid::new( vec![ "test-width-1", "test-width-2", "test-width-3", "test-width-4", ], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width, }, ); assert_eq!(expected, grid.to_string()); } } #[test] fn across_width_30() { let grid = Grid::new( vec![ "test-across1", "test-across2", "test-across3", "test-across4", ], GridOptions { direction: Direction::LeftToRight, filling: Filling::Spaces(2), width: 30, }, ); assert_eq!( "test-across1 test-across2\ntest-across3 test-across4\n", grid.to_string() ); } #[test] fn columns_width_30() { let grid = Grid::new( vec![ "test-columns1", "test-columns2", "test-columns3", "test-columns4", ], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 30, }, ); assert_eq!( "test-columns1 test-columns3\ntest-columns2 test-columns4\n", grid.to_string() ); } #[test] fn three_short_one_long() { let grid = Grid::new( vec!["a", "b", "a-long-name", "z"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 15, }, ); assert_eq!("a a-long-name\nb z\n", grid.to_string()); } }