uutils_term_grid-0.7.0/.cargo_vcs_info.json0000644000000001360000000000100144210ustar { "git": { "sha1": "93af5ee78421b3ff9bd49d0de0ecfa2327745614" }, "path_in_vcs": "" }uutils_term_grid-0.7.0/.github/workflows/ci.yml000064400000000000000000000123611046102023000177270ustar 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 # * CODECOV_FLAGS CODECOV_FLAGS=$( echo "${{ matrix.job.os }}" | sed 's/[^[:alnum:]]/_/g' ) outputs CODECOV_FLAGS - name: rust toolchain ~ install uses: dtolnay/rust-toolchain@nightly with: components: llvm-tools-preview - name: Test run: cargo test --no-fail-fast env: CARGO_INCREMENTAL: "0" RUSTC_WRAPPER: "" RUSTFLAGS: "-Cinstrument-coverage -Zcoverage-options=branch -Ccodegen-units=1 -Copt-level=0 -Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort" RUSTDOCFLAGS: "-Cpanic=abort" LLVM_PROFILE_FILE: "uutils-term-grid-%p-%m.profraw" - 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 . --binary-path="${COVERAGE_REPORT_DIR}" --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 . --binary-path="${COVERAGE_REPORT_DIR}" --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@v5 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.7.0/.gitignore000064400000000000000000000000221046102023000151730ustar 00000000000000target Cargo.lock uutils_term_grid-0.7.0/Cargo.lock0000644000000011570000000000100124000ustar # 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.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "uutils_term_grid" version = "0.7.0" dependencies = [ "ansi-width", ] uutils_term_grid-0.7.0/Cargo.toml0000644000000023710000000000100124220ustar # 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.7.0" authors = [ "uutils developers", "Benjamin Sago ", ] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false 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" path = "src/lib.rs" [[example]] name = "basic" path = "examples/basic.rs" [[example]] name = "big" path = "examples/big.rs" [[example]] name = "tabs" path = "examples/tabs.rs" [[test]] name = "test" path = "tests/test.rs" [dependencies.ansi-width] version = "0.1.0" uutils_term_grid-0.7.0/Cargo.toml.orig000064400000000000000000000007101046102023000160760ustar 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.7.0" edition = "2021" rust-version = "1.70" [lib] name = "term_grid" [dependencies] ansi-width = "0.1.0" uutils_term_grid-0.7.0/Justfile000064400000000000000000000011241046102023000147170ustar 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.7.0/LICENSE000064400000000000000000000020561046102023000142210ustar 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.7.0/README.md000064400000000000000000000102721046102023000144720ustar 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.7" ``` 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]: how to fill empty space between columns: - [`Filling::Spaces`][Spaces] number of spaces between columns; - [`Filling::Text`][Text] text string separator between columns; - [`Filling::Tabs`][Tabs] special option which allows to set number of spaces between columns and set the size of `\t` character. - [`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]: https://docs.rs/uutils_term_grid/latest/term_grid/struct.GridOptions.html#structfield.filling [direction]: https://docs.rs/uutils_term_grid/latest/term_grid/struct.GridOptions.html#structfield.direction [width]: https://docs.rs/uutils_term_grid/latest/term_grid/struct.GridOptions.html#structfield.width [LeftToRight]: https://docs.rs/uutils_term_grid/latest/term_grid/enum.Direction.html#variant.LeftToRight [TopToBottom]: https://docs.rs/uutils_term_grid/latest/term_grid/enum.Direction.html#variant.TopToBottom [Spaces]: https://docs.rs/uutils_term_grid/latest/term_grid/enum.Filling.html#variant.Spaces [Text]: https://docs.rs/uutils_term_grid/latest/term_grid/enum.Filling.html#variant.Text [Tabs]:https://docs.rs/uutils_term_grid/latest/term_grid/enum.Filling.html#variant.Tabs ## Width of grid cells This library calculates the width of strings as displayed in the terminal using the [`ansi-width`][ansi-width] crate. 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. [ansi-width]: https://docs.rs/ansi-width uutils_term_grid-0.7.0/examples/basic.rs000064400000000000000000000021041046102023000164530ustar 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.7.0/examples/big.rs000064400000000000000000000012511046102023000161350ustar 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.7.0/examples/tabs.rs000064400000000000000000000024311046102023000163260ustar 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, DEFAULT_SEPARATOR_SIZE}; // 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::Tabs { spaces: DEFAULT_SEPARATOR_SIZE, tab_size: 8, }, width: 80, }, ); println!("{}", grid); } uutils_term_grid-0.7.0/renovate.json000064400000000000000000000001531046102023000157260ustar 00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:base" ] } uutils_term_grid-0.7.0/src/lib.rs000064400000000000000000000311451046102023000151200ustar 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; /// Number of spaces in one \t. pub const SPACES_IN_TAB: usize = 8; /// Default size for separator in spaces. pub const DEFAULT_SEPARATOR_SIZE: usize = 2; /// 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), /// Fill spaces with `\t` Tabs { /// A number of spaces spaces: usize, /// Size of `\t` in spaces tab_size: usize, }, } impl Filling { fn width(&self) -> usize { match self { Filling::Spaces(w) => *w, Filling::Text(t) => ansi_width(t), Filling::Tabs { spaces, .. } => *spaces, } } } /// 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_rows: 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 mut grid = Self { options, cells, widths, widest_cell_width, dimensions: Dimensions { num_rows: 0, widths: Vec::new(), }, }; if !grid.cells.is_empty() { grid.dimensions = grid.width_dimensions(); } 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_rows } /// 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_rows: num_lines, widths: column_widths, } } fn width_dimensions(&mut self) -> Dimensions { if self.cells.len() == 1 { let cell_widths = self.widths[0]; return Dimensions { num_rows: 1, widths: vec![cell_widths], }; } // Calculate widest column size with separator. let widest_column = self.widest_cell_width + self.options.filling.width(); // If it exceeds terminal's width, return, since it is impossible to fit. if widest_column > self.options.width { return Dimensions { num_rows: self.cells.len(), widths: vec![self.widest_cell_width], }; } // Calculate the number of columns if all columns had the size of the largest // column. This is a lower bound on the number of columns. let min_columns = self .cells .len() .min((self.options.width + self.options.filling.width()) / widest_column); // Calculate maximum number of lines and columns. let max_rows = div_ceil(self.cells.len(), min_columns); // This is a potential dimension, which can definitely fit all of the cells. let mut potential_dimension = self.compute_dimensions(max_rows, min_columns); // If all of the cells can be fit on one line, return immediately. if max_rows == 1 { return potential_dimension; } // Try to increase number of columns, to see if new dimension can still fit. for num_columns in min_columns + 1..self.cells.len() { let Some(adjusted_width) = self .options .width .checked_sub((num_columns - 1) * self.options.filling.width()) else { break; }; let num_rows = div_ceil(self.cells.len(), num_columns); let new_dimension = self.compute_dimensions(num_rows, num_columns); if new_dimension.widths.iter().sum::() <= adjusted_width { potential_dimension = new_dimension; } } potential_dimension } } impl> fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { // If cells are empty then, nothing to print, skip. if self.cells.is_empty() { return Ok(()); } let (tab_size, separator) = match &self.options.filling { Filling::Spaces(n) => (0, " ".repeat(*n)), Filling::Text(s) => (0, s.clone()), Filling::Tabs { spaces, tab_size } => (*tab_size, " ".repeat(*spaces)), }; // 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 + self.options.filling.width()); for y in 0..self.dimensions.num_rows { // Current position on the line. let mut cursor: usize = 0; for x in 0..self.dimensions.widths.len() { // Calculate position of the current element of the grid // in cells and widths vectors and the offset to the next value. let (current, offset) = match self.options.direction { Direction::LeftToRight => (y * self.dimensions.widths.len() + x, 1), Direction::TopToBottom => { (y + self.dimensions.num_rows * x, self.dimensions.num_rows) } }; // Abandon a line mid-way through if that’s where the cells end. if current >= self.cells.len() { break; } // Last in row checks only the predefined grid width. // It does not check if there will be more entries. // For this purpose we define next value as well. // This prevents printing separator after the actual last value in a row. let last_in_row = x == self.dimensions.widths.len() - 1; let contents = &self.cells[current]; let width = self.widths[current]; 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())?; // In case this entry was the last on the current line, // there is no need to print the separator and padding. if last_in_row || current + offset >= self.cells.len() { break; } // Special case if tab size was not set. Fill with spaces and separator. if tab_size == 0 { f.write_str(&padding[..padding_size])?; f.write_str(&separator)?; } else { // Move cursor to the end of the current contents. cursor += width; let total_spaces = padding_size + self.options.filling.width(); // The size of \t can be inconsistent in terminal. // Tab stops are relative to the cursor position e.g., // * cursor = 0, \t moves to column 8; // * cursor = 5, \t moves to column 8 (3 spaces); // * cursor = 9, \t moves to column 16 (7 spaces). // Calculate the nearest \t position in relation to cursor. let closest_tab = tab_size - (cursor % tab_size); if closest_tab > total_spaces { f.write_str(&padding[..total_spaces])?; } else { let rest_spaces = total_spaces - closest_tab; let tabs = 1 + (rest_spaces / tab_size); let spaces = rest_spaces % tab_size; f.write_str(&"\t".repeat(tabs))?; f.write_str(&padding[..spaces])?; } cursor += total_spaces; } } 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.7.0/tests/test.rs000064400000000000000000000310031046102023000156750ustar 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, DEFAULT_SEPARATOR_SIZE, SPACES_IN_TAB}; #[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); } #[test] fn filling_with_tabs() { let grid = Grid::new( vec![ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ], GridOptions { direction: Direction::LeftToRight, filling: Filling::Tabs { spaces: DEFAULT_SEPARATOR_SIZE, tab_size: 2, }, width: 24, }, ); let bits = "one\t\t two\t\t three\nfour\t five\t\t six\nseven\t eight\t nine\nten\t\t eleven\t twelve\n"; assert_eq!(grid.to_string(), bits); assert_eq!(grid.row_count(), 4); } #[test] fn padding_bigger_than_widest() { let grid = Grid::new( vec!["1", "2", "3"], GridOptions { direction: Direction::LeftToRight, filling: Filling::Tabs { spaces: DEFAULT_SEPARATOR_SIZE, tab_size: SPACES_IN_TAB, }, width: 20, }, ); let bits = "1 2 3\n"; assert_eq!(grid.to_string(), bits); } #[test] fn odd_number_of_entries() { let cells = vec!["one", "two", "three", "four", "five"]; let grid = Grid::new( cells.clone(), GridOptions { direction: Direction::LeftToRight, filling: Filling::Spaces(2), width: 15, }, ); assert_eq!(grid.to_string(), "one two\nthree four\nfive\n"); let grid = Grid::new( cells.clone(), GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 15, }, ); assert_eq!(grid.to_string(), "one four\ntwo five\nthree\n"); } #[test] fn different_size_separator_with_tabs() { let grid = Grid::new( vec![ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ], GridOptions { direction: Direction::LeftToRight, filling: Filling::Tabs { spaces: 4, tab_size: 2, }, width: 40, }, ); let bits = "one\t\t\ttwo\t\t three\t\t four\nfive\t\tsix\t\t seven\t\t eight\nnine\t\tten\t\t eleven\t\t twelve\n"; assert_eq!(grid.to_string(), bits); } #[test] fn use_max_possible_width() { let grid = Grid::new( vec![ "test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", ], GridOptions { filling: Filling::Text("||".to_string()), direction: Direction::LeftToRight, width: 69, }, ); let bits = "test1 ||test2 ||test3||test4||test5||test6||test7||test8||test9\ntest10||test11\n"; assert_eq!(grid.to_string(), bits); assert_eq!(grid.row_count(), 2); } #[test] fn dont_use_max_possible_width() { let grid = Grid::new( vec![ "test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", ], GridOptions { filling: Filling::Text("||".to_string()), direction: Direction::TopToBottom, width: 69, }, ); let bits = "test1||test3||test5||test7||test9 ||test11\ntest2||test4||test6||test8||test10\n"; assert_eq!(grid.to_string(), bits); assert_eq!(grid.row_count(), 2); } #[test] fn use_minimal_optimal_lines() { let grid = Grid::new( vec!["a", "b", "ccc", "ddd"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 6, }, ); let expected = "a ccc\nb ddd\n"; assert_eq!(grid.to_string(), expected); } #[test] fn weird_column_edge_case() { // Here, 5 columns fit while fewer columns don't. So if we exit too early // while increasing columns, we don't find the optimal solution. let grid = Grid::new( vec!["0", "1", "222222222", "333333333", "4", "5", "6", "7", "8"], GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), width: 21, }, ); let expected = "\ 0 222222222 4 6 8\n\ 1 333333333 5 7\n\ "; println!("{grid}"); assert_eq!(grid.to_string(), expected); } // 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()); } }