uutils_term_grid-0.3.0/.cargo_vcs_info.json0000644000000001360000000000100144150ustar { "git": { "sha1": "b1fb84bd7eb70fd00cf401fd88d70b9219c45971" }, "path_in_vcs": "" }uutils_term_grid-0.3.0/.github/dependabot.yml000064400000000000000000000004141046102023000173740ustar 00000000000000version: 2 updates: - package-ecosystem: "cargo" directory: "/" schedule: interval: "daily" open-pull-requests-limit: 10 - package-ecosystem: "github-actions" directory: "/" schedule: interval: daily open-pull-requests-limit: 5 uutils_term_grid-0.3.0/.github/workflows/ci.yml000064400000000000000000000140221046102023000177170ustar 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: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - uses: Swatinem/rust-cache@v2 - uses: actions-rs/cargo@v1 with: command: test args: --all-features --workspace rustfmt: name: Rustfmt runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true components: rustfmt - uses: Swatinem/rust-cache@v2 - name: Check formatting uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true components: clippy - uses: Swatinem/rust-cache@v2 - name: Clippy check uses: actions-rs/cargo@v1 with: command: clippy args: --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: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - uses: Swatinem/rust-cache@v2 - name: Check documentation env: RUSTDOCFLAGS: -D warnings uses: actions-rs/cargo@v1 with: command: 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 ::set-output name=${var}::${!var}; 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: actions-rs/toolchain@v1 with: toolchain: ${{ steps.vars.outputs.TOOLCHAIN }} default: true profile: minimal # minimal component installation (ie, no documentation) - name: Test uses: actions-rs/cargo@v1 with: command: test args: ${{ 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 ::set-output name=report::${COVERAGE_REPORT_FILE} - name: Upload coverage results (to Codecov.io) uses: codecov/codecov-action@v3 # 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.3.0/.gitignore000064400000000000000000000000221046102023000151670ustar 00000000000000target Cargo.lock uutils_term_grid-0.3.0/Cargo.lock0000644000000006130000000000100123700ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[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.3.0" dependencies = [ "unicode-width", ] uutils_term_grid-0.3.0/Cargo.toml0000644000000016610000000000100124170ustar # 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.3.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.unicode-width] version = "0.1.11" uutils_term_grid-0.3.0/Cargo.toml.orig000064400000000000000000000007141046102023000160760ustar 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.3.0" edition = "2021" rust-version = "1.70" [lib] name = "term_grid" [dependencies] unicode-width = "0.1.11" uutils_term_grid-0.3.0/Justfile000064400000000000000000000011241046102023000147130ustar 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.3.0/LICENSE000064400000000000000000000020561046102023000142150ustar 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.3.0/README.md000064400000000000000000000074201046102023000144670ustar 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 [`rust-term-grid`](https://github.com/ogham/rust-term-grid) library. --- # Installation This crate works with `cargo`. Add the following to your `Cargo.toml` dependencies section: ```toml [dependencies] uutils_term_grid = "0.2" ``` The Minimum Supported Rust Version is 1.56. ## Usage This library arranges textual data in a grid format suitable for fixed-width fonts, using an algorithm to minimise the amount of space needed. For example: ```rust use term_grid::{Grid, GridOptions, Direction, Filling, Cell}; let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(1), direction: Direction::LeftToRight, }); for s in &["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"] { grid.add(Cell::from(*s)); } println!("{}", grid.fit_into_width(24).unwrap()); ``` Produces the following tabular result: ``` one two three four five six seven eight nine ten eleven twelve ``` ## Creating a grid To add data to a grid, first create a new `Grid` value, and then add cells to them with the `add` method. There are two options that must be specified in the `GridOptions` value that dictate how the grid is formatted: - `filling`: what to put in between two columns - either a number of spaces, or a text string; - `direction`, which specifies whether the cells should go along rows, or columns: - `Direction::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` starts them in the top left and moves *downwards*, going to the top of a new column after reaching the final row. ## Displaying a grid When display a grid, you can either specify the number of columns in advance, or try to find the maximum number of columns that can fit in an area of a given width. Splitting a series of cells into columns - or, in other words, starting a new row every *n* cells - is achieved with the `fit_into_columns` method on a `Grid` value. It takes as its argument the number of columns. Trying to fit as much data onto one screen as possible is the main use case for specifying a maximum width instead. This is achieved with the `fit_into_width` method. It takes the maximum allowed width, including separators, as its argument. However, it returns an *optional* `Display` value, depending on whether any of the cells actually had a width greater than the maximum width! If this is the case, your best bet is to just output the cells with one per line. ## Cells and data Grids do not take `String`s or `&str`s - they take `Cells`. A **Cell** is a struct containing an individual cell’s contents, as a string, and its pre-computed length, which gets used when calculating a grid’s final dimensions. Usually, you want the *Unicode width* of the string to be used for this, so you can turn a `String` into a `Cell` with the `.into()` method. However, you may also want to supply your own width: when you already know the width in advance, or when you want to change the measurement, such as skipping over terminal control characters. For cases like these, the fields on the `Cell` values are public, meaning you can construct your own instances as necessary. uutils_term_grid-0.3.0/examples/basic.rs000064400000000000000000000021261046102023000164530ustar 00000000000000extern crate term_grid; use term_grid::{Cell, 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 mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Text(" | ".into()), }); for i in 0..48 { let cell = Cell::from(2_isize.pow(i).to_string()); grid.add(cell) } if let Some(grid_display) = grid.fit_into_width(80) { println!("{}", grid_display); } else { println!("Couldn't fit grid into 80 columns!"); } } uutils_term_grid-0.3.0/examples/big.rs000064400000000000000000000013631046102023000161350ustar 00000000000000// For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. extern crate term_grid; use term_grid::{Cell, Direction, Filling, Grid, GridOptions}; fn main() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Text(" | ".into()), }); let mut n: u64 = 1234; for _ in 0..50 { for _ in 0..10000 { grid.add(Cell::from(n.to_string())); n = n.overflowing_pow(2).0 % 100000000; } if let Some(grid_display) = grid.fit_into_width(80) { println!("{}", grid_display); } else { println!("Couldn't fit grid into 80 columns!"); } } } uutils_term_grid-0.3.0/renovate.json000064400000000000000000000001531046102023000157220ustar 00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:base" ] } uutils_term_grid-0.3.0/src/lib.rs000064400000000000000000000414541046102023000151200ustar 00000000000000#![warn(future_incompatible)] #![warn(missing_copy_implementations)] #![warn(missing_docs)] #![warn(nonstandard_style)] #![warn(trivial_casts, trivial_numeric_casts)] #![warn(unused)] #![deny(unsafe_code)] //! This library arranges textual data in a grid format suitable for //! fixed-width fonts, using an algorithm to minimise the amount of space //! needed. For example: //! //! ```rust //! use term_grid::{Grid, GridOptions, Direction, Filling, Cell}; //! //! let mut grid = Grid::new(GridOptions { //! filling: Filling::Spaces(1), //! direction: Direction::LeftToRight, //! }); //! //! for s in &["one", "two", "three", "four", "five", "six", "seven", //! "eight", "nine", "ten", "eleven", "twelve"] //! { //! grid.add(Cell::from(*s)); //! } //! //! println!("{}", grid.fit_into_width(24).unwrap()); //! ``` //! //! Produces the following tabular result: //! //! ```text //! one two three four //! five six seven eight //! nine ten eleven twelve //! ``` //! //! //! ## Creating a grid //! //! To add data to a grid, first create a new [`Grid`] value, and then add //! cells to them with the `add` function. //! //! There are two options that must be specified in the [`GridOptions`] value //! that dictate how the grid is formatted: //! //! - `filling`: what to put in between two columns — either a number of //! spaces, or a text string; //! - `direction`, which specifies whether the cells should go along //! rows, or columns: //! - `Direction::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` starts them in the top left and moves //! *downwards*, going to the top of a new column after reaching the final //! row. //! //! //! ## Displaying a grid //! //! When display a grid, you can either specify the number of columns in advance, //! or try to find the maximum number of columns that can fit in an area of a //! given width. //! //! Splitting a series of cells into columns — or, in other words, starting a new //! row every n cells — is achieved with the [`fit_into_columns`] function //! on a `Grid` value. It takes as its argument the number of columns. //! //! Trying to fit as much data onto one screen as possible is the main use case //! for specifying a maximum width instead. This is achieved with the //! [`fit_into_width`] function. It takes the maximum allowed width, including //! separators, as its argument. However, it returns an *optional* [`Display`] //! value, depending on whether any of the cells actually had a width greater than //! the maximum width! If this is the case, your best bet is to just output the //! cells with one per line. //! //! //! ## Cells and data //! //! Grids to not take `String`s or `&str`s — they take [`Cell`] values. //! //! A **Cell** is a struct containing an individual cell’s contents, as a string, //! and its pre-computed length, which gets used when calculating a grid’s final //! dimensions. Usually, you want the *Unicode width* of the string to be used for //! this, so you can turn a `String` into a `Cell` with the `.into()` function. //! //! However, you may also want to supply your own width: when you already know the //! width in advance, or when you want to change the measurement, such as skipping //! over terminal control characters. For cases like these, the fields on the //! `Cell` values are public, meaning you can construct your own instances as //! necessary. //! //! [`Cell`]: ./struct.Cell.html //! [`Display`]: ./struct.Display.html //! [`Grid`]: ./struct.Grid.html //! [`fit_into_columns`]: ./struct.Grid.html#method.fit_into_columns //! [`fit_into_width`]: ./struct.Grid.html#method.fit_into_width //! [`GridOptions`]: ./struct.GridOptions.html use std::fmt; use unicode_width::UnicodeWidthStr; /// A **Cell** is the combination of a string and its pre-computed length. /// /// The easiest way to create a Cell is just by using `string.into()`, which /// uses the **unicode width** of the string (see the `unicode_width` crate). /// However, the fields are public, if you wish to provide your own length. #[derive(PartialEq, Eq, Debug, Clone)] pub struct Cell { /// The string to display when this cell gets rendered. pub contents: String, /// The pre-computed length of the string. pub width: Width, } impl From for Cell { fn from(string: String) -> Self { Self { width: UnicodeWidthStr::width(&*string), contents: string, } } } impl<'a> From<&'a str> for Cell { fn from(string: &'a str) -> Self { Self { width: UnicodeWidthStr::width(string), contents: string.into(), } } } /// 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 width of a cell, in columns. pub type Width = usize; /// 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 certain number of spaces should be used as the separator. Spaces(Width), /// An arbitrary string. /// `"|"` is a common choice. Text(String), } impl Filling { fn width(&self) -> Width { match *self { Filling::Spaces(w) => w, Filling::Text(ref t) => UnicodeWidthStr::width(&t[..]), } } } /// The user-assignable options for a grid view that should be passed to /// [`Grid::new()`](struct.Grid.html#method.new). #[derive(Debug)] pub struct GridOptions { /// The direction that the cells should be written in — either /// across, or downwards. pub direction: Direction, /// The number of spaces to put in between each column of cells. pub filling: Filling, } #[derive(PartialEq, Eq, Debug)] struct Dimensions { /// The number of lines in the grid. num_lines: Width, /// 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: Width) -> Width { 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. /// /// For more information, see the [`term_grid` crate documentation](index.html). #[derive(Debug)] pub struct Grid { options: GridOptions, cells: Vec, widest_cell_length: Width, width_sum: Width, cell_count: usize, } impl Grid { /// Creates a new grid view with the given options. pub fn new(options: GridOptions) -> Self { let cells = Vec::new(); Self { options, cells, widest_cell_length: 0, width_sum: 0, cell_count: 0, } } /// Reserves space in the vector for the given number of additional cells /// to be added. (See the `Vec::reserve` function.) pub fn reserve(&mut self, additional: usize) { self.cells.reserve(additional) } /// Adds another cell onto the vector. pub fn add(&mut self, cell: Cell) { if cell.width > self.widest_cell_length { self.widest_cell_length = cell.width; } self.width_sum += cell.width; self.cell_count += 1; self.cells.push(cell) } /// Returns a displayable grid that’s been packed to fit into the given /// width in the fewest number of rows. /// /// Returns `None` if any of the cells has a width greater than the /// maximum width. pub fn fit_into_width(&self, maximum_width: Width) -> Option> { self.width_dimensions(maximum_width).map(|dims| Display { grid: self, dimensions: dims, }) } /// Returns a displayable grid with the given number of columns, and no /// maximum width. pub fn fit_into_columns(&self, num_columns: usize) -> Display<'_> { Display { grid: self, dimensions: self.columns_dimensions(num_columns), } } fn columns_dimensions(&self, num_columns: usize) -> Dimensions { let num_lines = div_ceil(self.cells.len(), num_columns); self.column_widths(num_lines, num_columns) } fn column_widths(&self, num_lines: usize, num_columns: usize) -> Dimensions { let mut widths = vec![0; num_columns]; for (index, cell) in self.cells.iter().enumerate() { let index = match self.options.direction { Direction::LeftToRight => index % num_columns, Direction::TopToBottom => index / num_lines, }; if cell.width > widths[index] { widths[index] = cell.width; } } Dimensions { num_lines, widths } } fn theoretical_max_num_lines(&self, maximum_width: usize) -> usize { // TODO: Make code readable / efficient. let mut widths: Vec<_> = self.cells.iter().map(|c| c.width).collect(); // 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() { if width + col_total_width_so_far <= maximum_width { col_total_width_so_far += self.options.filling.width() + width; } else { return div_ceil(self.cell_count, 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: Width) -> Option { if self.widest_cell_length > maximum_width { // Largest cell is wider than maximum width; it is impossible to fit. return None; } if self.cell_count == 0 { return Some(Dimensions { num_lines: 0, widths: Vec::new(), }); } if self.cell_count == 1 { let the_cell = &self.cells[0]; return Some(Dimensions { num_lines: 1, widths: vec![the_cell.width], }); } let theoretical_max_num_lines = self.theoretical_max_num_lines(maximum_width); if theoretical_max_num_lines == 1 { // This if—statement is neccesary for the function to work correctly // for small inputs. return Some(Dimensions { num_lines: 1, widths: self.cells.iter().map(|cell| cell.width).collect(), }); } // 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.cell_count, 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.column_widths(num_lines, num_columns); if potential_dimensions.widths.iter().sum::() < adjusted_width { smallest_dimensions_yet = Some(potential_dimensions); } else { return smallest_dimensions_yet; } } None } } /// A displayable representation of a [`Grid`](struct.Grid.html). /// /// This type implements `Display`, so you can get the textual version /// of the grid by calling `.to_string()`. #[derive(Debug)] pub struct Display<'grid> { /// The grid to display. grid: &'grid Grid, /// The pre-computed column widths for this grid. dimensions: Dimensions, } impl Display<'_> { /// Returns how many columns this display takes up, based on the separator /// width and the number and width of the columns. pub fn width(&self) -> Width { self.dimensions .total_width(self.grid.options.filling.width()) } /// Returns how many rows this display takes up. pub fn row_count(&self) -> usize { self.dimensions.num_lines } /// 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) } } impl fmt::Display for Display<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { let separator = match &self.grid.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.grid.widest_cell_length); for y in 0..self.dimensions.num_lines { for x in 0..self.dimensions.widths.len() { let num = match self.grid.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.grid.cells.len() { continue; } let cell = &self.grid.cells[num]; let contents = &cell.contents; let last_in_row = x == self.dimensions.widths.len() - 1; let col_width = self.dimensions.widths[x]; let padding_size = col_width - cell.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)?; 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 /// Division with upward rouding 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.3.0/tests/test.rs000064400000000000000000000164321046102023000157020ustar 00000000000000use term_grid::{Cell, Direction, Filling, Grid, GridOptions}; #[test] fn no_items() { let grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); let display = grid.fit_into_width(40).unwrap(); assert_eq!("", display.to_string()); } #[test] fn one_item() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1")); let display = grid.fit_into_width(40).unwrap(); assert_eq!("1\n", display.to_string()); } #[test] fn one_item_exact_width() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1234567890")); let display = grid.fit_into_width(10).unwrap(); assert_eq!("1234567890\n", display.to_string()); } #[test] fn one_item_just_over() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1234567890!")); assert!(grid.fit_into_width(10).is_none()); } #[test] fn two_small_items() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1")); grid.add(Cell::from("2")); let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.width(), 1 + 2 + 1); assert_eq!("1 2\n", display.to_string()); } #[test] fn two_medium_size_items() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("hello there")); grid.add(Cell::from("how are you today?")); let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.width(), 11 + 2 + 18); assert_eq!("hello there how are you today?\n", display.to_string()); } #[test] fn two_big_items() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from( "nuihuneihsoenhisenouiuteinhdauisdonhuisudoiosadiuohnteihaosdinhteuieudi", )); grid.add(Cell::from( "oudisnuthasuouneohbueobaugceoduhbsauglcobeuhnaeouosbubaoecgueoubeohubeo", )); assert!(grid.fit_into_width(40).is_none()); } #[test] fn that_example_from_earlier() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(1), direction: Direction::LeftToRight, }); for s in &[ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ] { grid.add(Cell::from(*s)); } let bits = "one two three four\nfive six seven eight\nnine ten eleven twelve\n"; assert_eq!(grid.fit_into_width(24).unwrap().to_string(), bits); assert_eq!(grid.fit_into_width(24).unwrap().row_count(), 3); } #[test] fn number_grid_with_pipe() { let mut grid = Grid::new(GridOptions { filling: Filling::Text("|".into()), direction: Direction::LeftToRight, }); for s in &[ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ] { grid.add(Cell::from(*s)); } let bits = "one |two|three |four\nfive|six|seven |eight\nnine|ten|eleven|twelve\n"; assert_eq!(grid.fit_into_width(24).unwrap().to_string(), bits); assert_eq!(grid.fit_into_width(24).unwrap().row_count(), 3); } #[test] fn huge_separator() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(100), direction: Direction::LeftToRight, }); grid.add("a".into()); grid.add("b".into()); assert!(grid.fit_into_width(99).is_none()); } #[test] fn huge_yet_unused_separator() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(100), direction: Direction::LeftToRight, }); grid.add("abcd".into()); let display = grid.fit_into_width(99).unwrap(); assert_eq!(display.width(), 4); assert_eq!("abcd\n", display.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 mut grid = Grid::new(GridOptions { direction: Direction::LeftToRight, filling: Filling::Spaces(2), }); for s in ["🦀", "hello", "👩‍🔬", "hello"] { grid.add(s.into()); } let display = grid.fit_into_width(12).unwrap(); assert_eq!("🦀 hello\n👩‍🔬 hello\n", display.to_string()); } // 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 mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); for s in [ "test-width-1", "test-width-2", "test-width-3", "test-width-4", ] { grid.add(s.into()); } let display = grid.fit_into_width(width).unwrap(); assert_eq!(expected, display.to_string()); } } #[test] fn across_width_30() { let mut grid = Grid::new(GridOptions { direction: Direction::LeftToRight, filling: Filling::Spaces(2), }); for s in [ "test-across1", "test-across2", "test-across3", "test-across4", ] { grid.add(s.into()); } let display = grid.fit_into_width(30).unwrap(); assert_eq!( "test-across1 test-across2\ntest-across3 test-across4\n", display.to_string() ); } #[test] fn columns_width_30() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); for s in [ "test-columns1", "test-columns2", "test-columns3", "test-columns4", ] { grid.add(s.into()); } let display = grid.fit_into_width(30).unwrap(); assert_eq!( "test-columns1 test-columns3\ntest-columns2 test-columns4\n", display.to_string() ); } #[test] fn three_short_one_long() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); for s in ["a", "b", "a-long-name", "z"] { grid.add(s.into()); } let display = grid.fit_into_width(15).unwrap(); assert_eq!("a a-long-name\nb z\n", display.to_string()); } }