diff --git a/.rustfmt.toml b/.rustfmt.toml deleted file mode 100644 index 38bf3ab..0000000 --- a/.rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -disable_all_formatting = true -# For now... diff --git a/examples/basic.rs b/examples/basic.rs index 7fdb204..3bdebb8 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -1,5 +1,5 @@ extern crate term_grid; -use term_grid::{Grid, GridOptions, Direction, Filling, Cell, Alignment}; +use term_grid::{Alignment, Cell, Direction, Filling, Grid, GridOptions}; // This produces: // @@ -13,8 +13,8 @@ use term_grid::{Grid, GridOptions, Direction, Filling, Cell, Alignment}; fn main() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Text(" | ".into()), + direction: Direction::TopToBottom, + filling: Filling::Text(" | ".into()), }); for i in 0..48 { @@ -25,8 +25,7 @@ fn main() { if let Some(grid_display) = grid.fit_into_width(80) { println!("{}", grid_display); - } - else { + } else { println!("Couldn't fit grid into 80 columns!"); } } diff --git a/src/lib.rs b/src/lib.rs index d726abd..7459242 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,10 +4,8 @@ #![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: @@ -16,8 +14,8 @@ //! use term_grid::{Grid, GridOptions, Direction, Filling, Cell}; //! //! let mut grid = Grid::new(GridOptions { -//! filling: Filling::Spaces(1), -//! direction: Direction::LeftToRight, +//! filling: Filling::Spaces(1), +//! direction: Direction::LeftToRight, //! }); //! //! for s in &["one", "two", "three", "four", "five", "six", "seven", @@ -99,19 +97,16 @@ //! [`fit_into_width`]: ./struct.Grid.html#method.fit_into_width //! [`GridOptions`]: ./struct.GridOptions.html - use std::cmp::max; use std::fmt; use std::iter::repeat; use unicode_width::UnicodeWidthStr; - /// Alignment indicate on which side the content should stick if some filling /// is required. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Alignment { - /// The content will stick to the left. Left, @@ -119,7 +114,6 @@ pub enum Alignment { Right, } - /// 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 @@ -127,7 +121,6 @@ pub enum Alignment { /// However, the fields are public, if you wish to provide your own length. #[derive(PartialEq, Debug, Clone)] pub struct Cell { - /// The string to display when this cell gets rendered. pub contents: String, @@ -158,11 +151,9 @@ impl<'a> From<&'a str> for Cell { } } - /// Direction cells should be written in — either across, or downwards. #[derive(PartialEq, 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, @@ -172,16 +163,13 @@ pub enum Direction { 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, Debug)] pub enum Filling { - /// A certain number of spaces should be used as the separator. Spaces(Width), @@ -193,7 +181,7 @@ pub enum Filling { impl Filling { fn width(&self) -> Width { match *self { - Filling::Spaces(w) => w, + Filling::Spaces(w) => w, Filling::Text(ref t) => UnicodeWidthStr::width(&t[..]), } } @@ -203,7 +191,6 @@ impl Filling { /// [`Grid::new()`](struct.Grid.html#method.new). #[derive(PartialEq, Debug)] pub struct GridOptions { - /// The direction that the cells should be written in — either /// across, or downwards. pub direction: Direction, @@ -212,10 +199,8 @@ pub struct GridOptions { pub filling: Filling, } - #[derive(PartialEq, Debug)] struct Dimensions { - /// The number of lines in the grid. num_lines: Width, @@ -228,8 +213,7 @@ impl Dimensions { fn total_width(&self, separator_width: Width) -> Width { if self.widths.is_empty() { 0 - } - else { + } else { let values = self.widths.iter().sum::(); let separators = separator_width * (self.widths.len() - 1); values + separators @@ -237,7 +221,6 @@ impl Dimensions { } } - /// Everything needed to format the cells with the grid options. /// /// For more information, see the [`term_grid` crate documentation](index.html). @@ -251,12 +234,16 @@ pub struct Grid { } 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 } + 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 @@ -281,18 +268,17 @@ impl Grid { /// 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, - }) + 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, + grid: self, dimensions: self.columns_dimensions(num_columns), } } @@ -310,8 +296,8 @@ impl Grid { let mut widths: Vec = repeat(0).take(num_columns).collect(); for (index, cell) in self.cells.iter().enumerate() { let index = match self.options.direction { - Direction::LeftToRight => index % num_columns, - Direction::TopToBottom => index / num_lines, + Direction::LeftToRight => index % num_columns, + Direction::TopToBottom => index / num_lines, }; widths[index] = max(widths[index], cell.width); } @@ -354,12 +340,18 @@ impl Grid { } if self.cell_count == 0 { - return Some(Dimensions { num_lines: 0, widths: Vec::new() }); + 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 ] }); + return Some(Dimensions { + num_lines: 1, + widths: vec![the_cell.width], + }); } let theoretical_max_num_lines = self.theoretical_max_num_lines(maximum_width); @@ -371,14 +363,18 @@ impl Grid { // I clone self.cells twice. Once here, and once in // self.theoretical_max_num_lines. Perhaps not the best for // performance? - widths: self.cells.clone().into_iter().map(|cell| cell.width).collect() + widths: self + .cells + .clone() + .into_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 mut num_columns = self.cell_count / num_lines; @@ -412,14 +408,12 @@ impl Grid { } } - /// 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(PartialEq, Debug)] pub struct Display<'grid> { - /// The grid to display. grid: &'grid Grid, @@ -428,11 +422,11 @@ pub struct Display<'grid> { } 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()) + self.dimensions + .total_width(self.grid.options.filling.width()) } /// Returns how many rows this display takes up. @@ -454,11 +448,11 @@ impl Display<'_> { impl fmt::Display for Display<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - for y in 0 .. self.dimensions.num_lines { - for x in 0 .. self.dimensions.widths.len() { + 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, + 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 @@ -473,29 +467,46 @@ impl fmt::Display for Display<'_> { // The final column doesn’t need to have trailing spaces, // as long as it’s left-aligned. write!(f, "{}", cell.contents)?; - }, + } Alignment::Right => { let extra_spaces = self.dimensions.widths[x] - cell.width; - write!(f, "{}", pad_string(&cell.contents, extra_spaces, Alignment::Right))?; + write!( + f, + "{}", + pad_string(&cell.contents, extra_spaces, Alignment::Right) + )?; } } - } - else { + } else { assert!(self.dimensions.widths[x] >= cell.width); match (&self.grid.options.filling, cell.alignment) { (Filling::Spaces(n), Alignment::Left) => { let extra_spaces = self.dimensions.widths[x] - cell.width + n; - write!(f, "{}", pad_string(&cell.contents, extra_spaces, cell.alignment))?; - }, + write!( + f, + "{}", + pad_string(&cell.contents, extra_spaces, cell.alignment) + )?; + } (Filling::Spaces(n), Alignment::Right) => { let s = spaces(*n); let extra_spaces = self.dimensions.widths[x] - cell.width; - write!(f, "{}{}", pad_string(&cell.contents, extra_spaces, cell.alignment), s)?; - }, + write!( + f, + "{}{}", + pad_string(&cell.contents, extra_spaces, cell.alignment), + s + )?; + } (Filling::Text(ref t), _) => { let extra_spaces = self.dimensions.widths[x] - cell.width; - write!(f, "{}{}", pad_string(&cell.contents, extra_spaces, cell.alignment), t)?; - }, + write!( + f, + "{}{}", + pad_string(&cell.contents, extra_spaces, cell.alignment), + t + )?; + } } } } @@ -507,7 +518,6 @@ impl fmt::Display for Display<'_> { } } - /// Pad a string with the given number of spaces. fn spaces(length: usize) -> String { repeat(" ").take(length).collect() @@ -520,13 +530,11 @@ fn spaces(length: usize) -> String { fn pad_string(string: &str, padding: usize, alignment: Alignment) -> String { if alignment == Alignment::Left { format!("{}{}", string, spaces(padding)) - } - else { + } else { format!("{}{}", spaces(padding), string) } } - #[cfg(test)] mod test { use super::*; @@ -534,8 +542,8 @@ mod test { #[test] fn no_items() { let grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); let display = grid.fit_into_width(40).unwrap(); @@ -549,8 +557,8 @@ mod test { #[test] fn one_item() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); grid.add(Cell::from("1")); @@ -558,7 +566,7 @@ mod test { let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 1); - assert_eq!(display.dimensions.widths, vec![ 1 ]); + assert_eq!(display.dimensions.widths, vec![1]); assert_eq!(display.width(), 1); } @@ -566,8 +574,8 @@ mod test { #[test] fn one_item_exact_width() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); grid.add(Cell::from("1234567890")); @@ -575,7 +583,7 @@ mod test { let display = grid.fit_into_width(10).unwrap(); assert_eq!(display.dimensions.num_lines, 1); - assert_eq!(display.dimensions.widths, vec![ 10 ]); + assert_eq!(display.dimensions.widths, vec![10]); assert_eq!(display.width(), 10); } @@ -583,8 +591,8 @@ mod test { #[test] fn one_item_just_over() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); grid.add(Cell::from("1234567890!")); @@ -595,8 +603,8 @@ mod test { #[test] fn two_small_items() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); grid.add(Cell::from("1")); @@ -605,7 +613,7 @@ mod test { let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 1); - assert_eq!(display.dimensions.widths, vec![ 1, 1 ]); + assert_eq!(display.dimensions.widths, vec![1, 1]); assert_eq!(display.width(), 1 + 2 + 1); } @@ -613,8 +621,8 @@ mod test { #[test] fn two_medium_size_items() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); grid.add(Cell::from("hello there")); @@ -623,7 +631,7 @@ mod test { let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 1); - assert_eq!(display.dimensions.widths, vec![ 11, 18 ]); + assert_eq!(display.dimensions.widths, vec![11, 18]); assert_eq!(display.width(), 11 + 2 + 18); } @@ -631,12 +639,16 @@ mod test { #[test] fn two_big_items() { let mut grid = Grid::new(GridOptions { - direction: Direction::TopToBottom, - filling: Filling::Spaces(2), + direction: Direction::TopToBottom, + filling: Filling::Spaces(2), }); - grid.add(Cell::from("nuihuneihsoenhisenouiuteinhdauisdonhuisudoiosadiuohnteihaosdinhteuieudi")); - grid.add(Cell::from("oudisnuthasuouneohbueobaugceoduhbsauglcobeuhnaeouosbubaoecgueoubeohubeo")); + grid.add(Cell::from( + "nuihuneihsoenhisenouiuteinhdauisdonhuisudoiosadiuohnteihaosdinhteuieudi", + )); + grid.add(Cell::from( + "oudisnuthasuouneohbueobaugceoduhbsauglcobeuhnaeouosbubaoecgueoubeohubeo", + )); assert_eq!(grid.fit_into_width(40), None); } @@ -644,13 +656,14 @@ mod test { #[test] fn that_example_from_earlier() { let mut grid = Grid::new(GridOptions { - filling: Filling::Spaces(1), - direction: Direction::LeftToRight, + filling: Filling::Spaces(1), + direction: Direction::LeftToRight, }); - for s in &["one", "two", "three", "four", "five", "six", "seven", - "eight", "nine", "ten", "eleven", "twelve"] - { + for s in &[ + "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", + "eleven", "twelve", + ] { grid.add(Cell::from(*s)); } @@ -662,13 +675,14 @@ mod test { #[test] fn number_grid_with_pipe() { let mut grid = Grid::new(GridOptions { - filling: Filling::Text("|".into()), - direction: Direction::LeftToRight, + filling: Filling::Text("|".into()), + direction: Direction::LeftToRight, }); - for s in &["one", "two", "three", "four", "five", "six", "seven", - "eight", "nine", "ten", "eleven", "twelve"] - { + for s in &[ + "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", + "eleven", "twelve", + ] { grid.add(Cell::from(*s)); } @@ -680,13 +694,14 @@ mod test { #[test] fn numbers_right() { let mut grid = Grid::new(GridOptions { - filling: Filling::Spaces(1), - direction: Direction::LeftToRight, + filling: Filling::Spaces(1), + direction: Direction::LeftToRight, }); - for s in &["one", "two", "three", "four", "five", "six", "seven", - "eight", "nine", "ten", "eleven", "twelve"] - { + for s in &[ + "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", + "eleven", "twelve", + ] { let mut cell = Cell::from(*s); cell.alignment = Alignment::Right; grid.add(cell); @@ -700,13 +715,14 @@ mod test { #[test] fn numbers_right_pipe() { let mut grid = Grid::new(GridOptions { - filling: Filling::Text("|".into()), - direction: Direction::LeftToRight, + filling: Filling::Text("|".into()), + direction: Direction::LeftToRight, }); - for s in &["one", "two", "three", "four", "five", "six", "seven", - "eight", "nine", "ten", "eleven", "twelve"] - { + for s in &[ + "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", + "eleven", "twelve", + ] { let mut cell = Cell::from(*s); cell.alignment = Alignment::Right; grid.add(cell); @@ -720,8 +736,8 @@ mod test { #[test] fn huge_separator() { let mut grid = Grid::new(GridOptions { - filling: Filling::Spaces(100), - direction: Direction::LeftToRight, + filling: Filling::Spaces(100), + direction: Direction::LeftToRight, }); grid.add("a".into()); @@ -733,8 +749,8 @@ mod test { #[test] fn huge_yet_unused_separator() { let mut grid = Grid::new(GridOptions { - filling: Filling::Spaces(100), - direction: Direction::LeftToRight, + filling: Filling::Spaces(100), + direction: Direction::LeftToRight, }); grid.add("abcd".into()); @@ -742,7 +758,7 @@ mod test { let display = grid.fit_into_width(99).unwrap(); assert_eq!(display.dimensions.num_lines, 1); - assert_eq!(display.dimensions.widths, vec![ 4 ]); + assert_eq!(display.dimensions.widths, vec![4]); assert_eq!(display.width(), 4); }