### Papergrid Table Generation Example Source: https://docs.rs/papergrid/latest/index.html This example demonstrates how to use the Papergrid library to create and render a text-based table with custom borders and data. ```APIDOC ## Papergrid Table Generation Example ### Description This example demonstrates how to use the Papergrid library to create and render a text-based table with custom borders and data. ### Method N/A (This is a code example, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```rust use papergrid::{ records::IterRecords, dimension::Estimate, config::Borders, colors::NoColors, grid::iterable::IterGrid, config::spanned::SpannedConfig, dimension::iterable::IterGridDimension, }; // Creating a borders structure of a grid. let borders = Borders { top: Some('-'), top_left: Some('+'), top_right: Some('+'), top_intersection: Some('+'), bottom: Some('-'), bottom_left: Some('+'), bottom_right: Some('+'), bottom_intersection: Some('+'), horizontal: Some('-'), vertical: Some('|'), left: Some('|'), right: Some('|'), intersection: Some('+'), left_intersection: Some('+'), right_intersection: Some('+'), }; // Creating a grid config. let mut cfg = SpannedConfig::default(); cfg.set_borders(borders); // Creating an actual data for grid. let records = vec![vec!["Hello", "World"], vec!["Hi", "World"]]; let records = IterRecords::new(records, 2, None); // Estimate grid dimension. let mut dims = IterGridDimension::default(); dims.estimate(&records, &cfg); // Creating a grid. let grid = IterGrid::new(&records, &cfg, &dims, NoColors); assert_eq!( grid.to_string(), concat!( "+-----+-----+\n", "|Hello|World|\n", "+-----+-----+\n", "|Hi |World|\n", "+-----+-----+", ), ); ``` ### Response N/A (This is a code example, not an API endpoint) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Count Empty Lines at Start Source: https://docs.rs/papergrid/latest/src/papergrid/grid/peekable.rs.html Counts consecutive empty lines starting from the beginning of a record set. Useful for trimming leading whitespace. ```rust fn count_empty_lines_at_start(records: &R, pos: Position) -> usize where R: Records + PeekableRecords, { (0..records.count_lines(pos)) .map(|i| records.get_line(pos, i)) .take_while(|s| s.trim().is_empty()) .count() ``` -------------------------------- ### CompactConfig Get Borders Source: https://docs.rs/papergrid/latest/src/papergrid/config/compact/mod.rs.html Retrieves the current border characters configuration for the grid. ```rust pub const fn get_borders(&self) -> &Borders { &self.borders } ``` -------------------------------- ### Manage Justification Source: https://docs.rs/papergrid/latest/src/papergrid/config/spanned/mod.rs.html Methods for getting and setting cell justification and associated colors. ```rust pub fn get_justification(&self, pos: Position) -> char { *self.justification.get(pos) } ``` ```rust pub fn get_justification_color(&self, pos: Position) -> Option<&ANSIBuf> { self.justification_color.get(pos).as_ref() } ``` ```rust pub fn set_justification(&mut self, entity: Entity, c: char) { self.justification.insert(entity, c); } ``` ```rust pub fn set_justification_color(&mut self, entity: Entity, color: Option) { self.justification_color.insert(entity, color); } ``` -------------------------------- ### Get ANSIStr Prefix Source: https://docs.rs/papergrid/latest/src/papergrid/ansi/ansi_str.rs.html Returns a reference to the prefix string of the ANSIStr instance. This is the ANSI escape code that starts the formatting. ```rust pub const fn get_prefix(&self) -> &'a str { self.prefix } ``` -------------------------------- ### Create and Render a Text Table Source: https://docs.rs/papergrid/latest/src/papergrid/lib.rs.html Demonstrates creating a text-based table with custom borders and rendering it to a string. This example requires the 'std' feature to be enabled. ```rust #![cfg_attr(not(any(feature = "std", test)), no_std)] #![warn( rust_2018_idioms, rust_2018_compatibility, rust_2021_compatibility, missing_debug_implementations, unreachable_pub, missing_docs )] #![allow(clippy::uninlined_format_args)] #![deny(unused_must_use)] #![doc( html_logo_url = "https://raw.githubusercontent.com/zhiburt/tabled/86ac146e532ce9f7626608d7fd05072123603a2e/assets/tabled-gear.svg" )] //! Papergrid is a library for generating text-based tables. //! //! It has relatively low level API. //! If you're interested in a more friendly one take a look at [`tabled`](https://github.com/zhiburt/tabled). //! //! # Example //! #![cfg_attr(feature = "std", doc = "```")] #![cfg_attr(not(feature = "std"), doc = "```ignore")] use papergrid::{ records::IterRecords, dimension::Estimate, config::Borders, colors::NoColors, grid::iterable::IterGrid, config::spanned::SpannedConfig, dimension::iterable::IterGridDimension, }; // Creating a borders structure of a grid. let borders = Borders { top: Some('-'), top_left: Some('+'), top_right: Some('+'), top_intersection: Some('+'), bottom: Some('-'), bottom_left: Some('+'), bottom_right: Some('+'), bottom_intersection: Some('+'), horizontal: Some('-'), vertical: Some('|'), left: Some('|'), right: Some('|'), intersection: Some('+'), left_intersection: Some('+'), right_intersection: Some('+'), }; // Creating a grid config. let mut cfg = SpannedConfig::default(); cfg.set_borders(borders); // Creating an actual data for grid. let records = vec![vec!["Hello", "World"], vec!["Hi", "World"]]; let records = IterRecords::new(records, 2, None); // Estimate grid dimension. let mut dims = IterGridDimension::default(); dims.estimate(&records, &cfg); // Creating a grid. let grid = IterGrid::new(&records, &cfg, &dims, NoColors); assert_eq!( grid.to_string(), concat!( "+-----+-----+\n", "|Hello|World|\n", "+-----+-----+\n", "|Hi |World|\n", "+-----+-----+", ), ); ``` ``` -------------------------------- ### Check slice prefix Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Verifies if a slice starts with a specific sequence. Empty slices always return true. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Generate Text-Based Tables with Papergrid Source: https://docs.rs/papergrid/latest/index.html This example demonstrates how to create and render a text-based table using the papergrid library. It involves setting up borders, configuration, data records, estimating dimensions, and finally generating the grid string. Ensure all necessary imports are included. ```rust use papergrid::{ records::IterRecords, dimension::{Estimate}, config::Borders, colors::NoColors, grid::iterable::IterGrid, config::spanned::SpannedConfig, dimension::iterable::IterGridDimension, }; // Creating a borders structure of a grid. let borders = Borders { top: Some('-'), top_left: Some('+'), top_right: Some('+'), top_intersection: Some('+'), bottom: Some('-'), bottom_left: Some('+'), bottom_right: Some('+'), bottom_intersection: Some('+'), horizontal: Some('-'), vertical: Some('|'), left: Some('|'), right: Some('|'), intersection: Some('+'), left_intersection: Some('+'), right_intersection: Some('+'), }; // Creating a grid config. let mut cfg = SpannedConfig::default(); cfg.set_borders(borders); // Creating an actual data for grid. let records = vec![vec!["Hello", "World"], vec!["Hi", "World"]]; let records = IterRecords::new(records, 2, None); // Estimate grid dimension. let mut dims = IterGridDimension::default(); dims.estimate(&records, &cfg); // Creating a grid. let grid = IterGrid::new(&records, &cfg, &dims, NoColors); assert_eq!( grid.to_string(), concat!( "+-----+-----+\n", "|Hello|World|\n", "+-----+-----+\n", "|Hi |World|\n", "+-----+-----+", ), ); ``` -------------------------------- ### Iterate Over Mutable Slice Chunks From the End (rchunks_mut) Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `rchunks_mut` to get an iterator over mutable slices of a specified size, starting from the end. This is useful for modifying elements in place within chunks. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### Initialize WritableGrid Source: https://docs.rs/papergrid/latest/src/papergrid/grid/writable/grid.rs.html Creates a new WritableGrid instance with provided records, configuration, dimensions, and colors. This is the entry point for creating a grid. ```rust pub fn new(records: R, config: G, dimension: D, colors: C) -> Self { WritableGrid { records, config, dimension, colors, } } ``` -------------------------------- ### Iterate Over Slice Chunks From the End (rchunks) Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `rchunks` to get an iterator over mutable slices of a specified size, starting from the end. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### IterGrid::new Source: https://docs.rs/papergrid/latest/papergrid/grid/iterable/struct.IterGrid.html Creates a new instance of IterGrid with default styles. ```APIDOC ## IterGrid::new ### Description The new method creates a grid instance with default styles. ### Parameters - **records** (R) - Required - The records to be used in the grid. - **config** (G) - Required - The configuration for the grid. - **dimension** (D) - Required - The dimensions of the grid. - **colors** (C) - Required - The color settings for the grid. ``` -------------------------------- ### Iterate Over Exact Slice Chunks From the End (rchunks_exact) Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `rchunks_exact` to get an iterator over mutable slices of a specified size, starting from the end. This iterator guarantees each chunk has exactly `chunk_size` elements, omitting any remainder. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### PeekableGrid::new Source: https://docs.rs/papergrid/latest/papergrid/grid/peekable/struct.PeekableGrid.html Creates a new PeekableGrid instance with default styles. ```APIDOC ## impl PeekableGrid ### pub fn new(records: R, config: G, dimension: D, colors: C) -> Self The new method creates a grid instance with default styles. ``` -------------------------------- ### Iterate Over Exact Mutable Slice Chunks From the End (rchunks_exact_mut) Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `rchunks_exact_mut` to get an iterator over mutable slices of a specified size, starting from the end. This iterator guarantees each chunk has exactly `chunk_size` elements, omitting any remainder. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` -------------------------------- ### Get Last Element of a Slice Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `last` to get an immutable reference to the last element. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Building and Converting Grids Source: https://docs.rs/papergrid/latest/src/papergrid/grid/iterable.rs.html Explains how to build a grid into a writer or directly into a string using the `build` and `to_string` methods. ```APIDOC ## Grid Building and Conversion ### Methods #### `build(self, f: F) -> fmt::Result` Builds the grid and writes the output to the provided `Write` trait implementor `f`. This method handles the rendering of the grid based on its configuration and data. **Constraints:** - `R: Records` - `::Cell: AsRef` - `D: Dimension` - `C: Colors` - `G: Borrow` - `F: Write` #### `to_string(self) -> String` Builds the grid and returns it as a `String`. This method consumes the `IterGrid` instance. **Constraints:** - `R: Records` - `::Cell: AsRef` - `D: Dimension` - `G: Borrow` - `C: Colors` ### Example ```rust // Building to a writer let mut buffer = String::new(); grid.build(&mut buffer)?; // Building to a string let grid_string = grid.to_string(); ``` ``` -------------------------------- ### CompactGrid Methods Source: https://docs.rs/papergrid/latest/papergrid/grid/compact/struct.CompactGrid.html Methods for initializing, configuring, and building tables using the CompactGrid struct. ```APIDOC ## CompactGrid::new ### Description Creates a new grid instance with default styles. ### Parameters - **records** (R) - Required - The data records to be displayed. - **config** (G) - Required - The grid configuration. - **dimension** (D) - Required - The grid dimensions. - **colors** (C) - Required - The color configuration. ## CompactGrid::with_colors ### Description Sets the colors map for the grid. ### Parameters - **colors** (Colors) - Required - The color configuration to apply. ## CompactGrid::build ### Description Builds a table and writes it to the provided writer. ### Parameters - **f** (F) - Required - The writer to output the table to. ## CompactGrid::to_string ### Description Builds the table and returns it as a String. Note that this method consumes the CompactGrid instance. ``` -------------------------------- ### Initialize vector elements via as_non_null Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Demonstrates manual initialization using the nightly-only as_non_null API. ```rust #![feature(box_vec_non_null)] // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_non_null(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { x_ptr.add(i).write(i as i32); } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### Get Last Chunk of a Slice Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `last_chunk` to get an array reference to the last `N` items. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### Get First Chunk of a Slice Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `first_chunk` to get an array reference to the first `N` items. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### PeekableGrid::new Source: https://docs.rs/papergrid/latest/src/papergrid/grid/peekable.rs.html Creates a new instance of a PeekableGrid with the provided records, configuration, dimensions, and color settings. ```APIDOC ## PeekableGrid::new ### Description Initializes a new PeekableGrid instance. ### Parameters - **records** (R) - Required - The data records to be displayed. - **config** (G) - Required - The configuration settings for the grid. - **dimension** (D) - Required - The dimension settings for the grid. - **colors** (C) - Required - The color configuration for the grid. ``` -------------------------------- ### Get Mutable Reference to Last Element of a Slice Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `last_mut` to get a mutable reference to the last element. Returns `None` if the slice is empty. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); let y: &mut [i32] = &mut []; assert_eq!(None, y.last_mut()); ``` -------------------------------- ### CompactConfig Configuration Methods Source: https://docs.rs/papergrid/latest/papergrid/config/compact/struct.CompactConfig.html Methods for configuring grid layout properties including margins, borders, padding, and alignment. ```APIDOC ## CompactConfig Configuration ### Description Methods to initialize and modify the configuration of a grid, including visual properties like borders, margins, and padding. ### Methods - **new()** -> Self: Returns a standard configuration. - **set_margin(margin: Sides)** -> Self: Sets the grid margin. - **get_margin()** -> &Sides: Returns the grid margin. - **set_borders(borders: Borders)** -> Self: Sets the borders. - **get_borders()** -> &Borders: Returns the current borders. - **set_padding(padding: Sides)** -> Self: Sets padding for cells. - **get_padding()** -> &Sides: Gets the padding. - **set_alignment_horizontal(alignment: AlignmentHorizontal)** -> Self: Sets horizontal alignment. - **get_alignment_horizontal()** -> AlignmentHorizontal: Gets horizontal alignment. - **set_borders_color(borders: Borders>)** -> Self: Sets border colors. - **set_margin_color(color: Sides>)** -> Self: Sets margin colors. - **get_margin_color()** -> &Sides>: Returns margin color. - **set_padding_color(color: Sides>)** -> Self: Sets padding colors. - **get_padding_color()** -> &Sides>: Returns padding color. ``` -------------------------------- ### Get Mutable First Chunk of a Slice Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `first_chunk_mut` to get a mutable array reference to the first `N` items. Returns `None` if the slice is shorter than `N`. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ``` -------------------------------- ### Initialize vector elements via as_mut_ptr Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Demonstrates manual initialization of vector elements using a raw mutable pointer obtained from as_mut_ptr. ```rust // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### Get Raw Pointer to Vec Buffer Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Use `as_ptr` to get a raw pointer to the vector's buffer. Ensure the vector outlives the pointer and do not mutate the buffer through this pointer. ```rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` ```rust unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } ``` -------------------------------- ### VecRecords Initialization Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Methods to create a new instance of VecRecords. ```APIDOC ## pub fn new(data: Vec>) -> Self ### Description Creates a new VecRecords structure. It assumes that the data vector has all rows with the same length. ## pub fn with_size(data: Vec>, count_rows: usize, count_cols: usize) -> Self ### Description Creates a new VecRecords structure with specified row and column counts. ``` -------------------------------- ### Border Management Source: https://docs.rs/papergrid/latest/src/papergrid/config/spanned/borders_config.rs.html Methods for setting and getting grid borders. ```APIDOC ## SET BORDERS ### Description Sets the borders for the entire grid. ### Method `set_borders` ### Parameters - `borders` (Borders) - The `Borders` struct containing top, bottom, left, right, and internal border information. ### Request Example ```rust // Assuming `grid` is a mutable instance of PaperGrid and `border_data` is a Borders grid.set_borders(border_data); ``` ## GET BORDERS ### Description Retrieves a reference to the `Borders` struct of the grid. ### Method `get_borders` ### Response #### Success Response (&Borders) - Returns a reference to the grid's `Borders` struct. ### Request Example ```rust // Assuming `grid` is an instance of PaperGrid let borders = grid.get_borders(); ``` ``` -------------------------------- ### PeekableGrid::build Source: https://docs.rs/papergrid/latest/papergrid/grid/peekable/struct.PeekableGrid.html Builds a table from the grid configuration. ```APIDOC ## impl PeekableGrid ### pub fn build(&self, f: F) -> Result where R: Records + PeekableRecords + ExactRecords, D: Dimension, C: Colors, G: Borrow, F: Write, Builds a table. ``` -------------------------------- ### get Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Returns a reference to an element or subslice based on the provided index. ```APIDOC ## get(&self, index: I) ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position. If given a range, returns the subslice corresponding to that range. ### Parameters #### Path Parameters - **index** (I) - Required - The index or range to access. ### Response #### Success Response (200) - **Option<&>::Output>** - The requested element or subslice, or None if out of bounds. ``` -------------------------------- ### WritableGrid Build Method Source: https://docs.rs/papergrid/latest/src/papergrid/grid/writable/grid.rs.html Details the `build` method, which renders the grid into a specified output format. ```APIDOC ## `WritableGrid::build` ### Description Builds and renders the text-based table using the provided `Typewriter`. ### Method `build` ### Parameters - **f** (F) - Required - A mutable reference to a `Typewriter` implementation that will be used to write the grid content. ### Type Parameters - **R**: Must implement `Records`, `PeekableRecords`, and `ExactRecords`. - **G**: Must implement `Borrow`. - **D**: Must implement `Dimension`. - **C**: Must implement `Colors`. - **F**: Must implement `Typewriter`. ### Returns A `fmt::Result` indicating success or failure during the build process. ### Behavior - If the grid has no columns or zero rows, it returns `Ok(())` immediately. - It determines whether to use `grid_spanned`, `grid_basic`, or `grid_not_spanned` based on configuration and data. - It calls `print_grid` to handle the actual rendering logic. ``` -------------------------------- ### PeekableGrid::build Source: https://docs.rs/papergrid/latest/src/papergrid/grid/peekable.rs.html Builds the table and writes it to the provided formatter. ```APIDOC ## PeekableGrid::build ### Description Constructs the table based on the internal records and configuration, writing the output to the provided writer. ### Parameters - **f** (F) - Required - A mutable reference to a type implementing std::fmt::Write. ``` -------------------------------- ### Get Grid Borders Source: https://docs.rs/papergrid/latest/src/papergrid/config/spanned/borders_config.rs.html Retrieves a reference to the grid's borders. ```rust pub(crate) fn get_borders(&self) -> &Borders { &self.borders } ``` -------------------------------- ### CompactConfig Get Margin Source: https://docs.rs/papergrid/latest/src/papergrid/config/compact/mod.rs.html Retrieves the current margin settings for the grid. ```rust pub const fn get_margin(&self) -> &Sides { &self.margin } ``` -------------------------------- ### Borders Implementation Methods Source: https://docs.rs/papergrid/latest/src/papergrid/config/borders.rs.html Methods for initializing empty or filled borders, and checking the state of specific frame lines. ```rust 40impl Borders { 41 /// Returns empty borders. 42 pub const fn empty() -> Self { 43 Self { 44 top: None, 45 top_left: None, 46 top_right: None, 47 top_intersection: None, 48 bottom: None, 49 bottom_left: None, 50 bottom_right: None, 51 bottom_intersection: None, 52 horizontal: None, 53 left: None, 54 right: None, 55 vertical: None, 56 left_intersection: None, 57 right_intersection: None, 58 intersection: None, 59 } 60 } 61 62 /// Returns Borders filled in with a supplied value. 63 pub const fn filled(val: T) -> Self 64 where 65 T: Copy, 66 { 67 Self { 68 top: Some(val), 69 top_left: Some(val), 70 top_right: Some(val), 71 top_intersection: Some(val), 72 bottom: Some(val), 73 bottom_left: Some(val), 74 bottom_right: Some(val), 75 bottom_intersection: Some(val), 76 horizontal: Some(val), 77 left: Some(val), 78 right: Some(val), 79 vertical: Some(val), 80 left_intersection: Some(val), 81 right_intersection: Some(val), 82 intersection: Some(val), 83 } 64 } 85 86 /// A verification whether any border was set. 87 pub const fn is_empty(&self) -> bool { 88 self.top.is_none() 89 && self.top_left.is_none() 90 && self.top_right.is_none() 91 && self.top_intersection.is_none() 92 && self.bottom.is_none() 93 && self.bottom_left.is_none() 94 && self.bottom_right.is_none() 95 && self.bottom_intersection.is_none() 96 && self.horizontal.is_none() 97 && self.left.is_none() 98 && self.right.is_none() 99 && self.vertical.is_none() 100 && self.left_intersection.is_none() 101 && self.right_intersection.is_none() 102 && self.intersection.is_none() 103 } 104 105 /// Verifies if borders has left line set on the frame. 106 pub const fn has_left(&self) -> bool { 107 self.left.is_some() 108 || self.left_intersection.is_some() 109 || self.top_left.is_some() 110 || self.bottom_left.is_some() 111 } 112 113 /// Verifies if borders has right line set on the frame. 114 pub const fn has_right(&self) -> bool { 115 self.right.is_some() 116 || self.right_intersection.is_some() 117 || self.top_right.is_some() 118 || self.bottom_right.is_some() 119 } 120 121 /// Verifies if borders has top line set on the frame. 122 pub const fn has_top(&self) -> bool { 123 self.top.is_some() 124 || self.top_intersection.is_some() 125 || self.top_left.is_some() 126 || self.top_right.is_some() 127 } 128 129 /// Verifies if borders has bottom line set on the frame. 130 pub const fn has_bottom(&self) -> bool { 131 self.bottom.is_some() 132 || self.bottom_intersection.is_some() 133 || self.bottom_left.is_some() 134 || self.bottom_right.is_some() 135 } 136 137 /// Verifies if borders has horizontal lines set. 138 pub const fn has_horizontal(&self) -> bool { 139 self.horizontal.is_some() 140 || self.left_intersection.is_some() 141 || self.right_intersection.is_some() 142 } ``` -------------------------------- ### Border Management Source: https://docs.rs/papergrid/latest/papergrid/config/spanned/struct.SpannedConfig.html APIs for setting, getting, and managing borders and their colors. ```APIDOC ## set_border ### Description Sets a border value for all cells within a specified entity. ### Method POST ### Endpoint /papergrid/set_border ### Parameters #### Path Parameters - **pos** (Position) - Required - The starting position of the entity. - **border** (Border) - Required - The border configuration. ### Response #### Success Response (200) - **None** ``` ```APIDOC ## get_border ### Description Retrieves the border of a cell at a given position and shape. ### Method GET ### Endpoint /papergrid/get_border ### Parameters #### Path Parameters - **pos** (Position) - Required - The position of the cell. - **shape** (tuple) - Required - The shape of the border to retrieve. ### Response #### Success Response (200) - **Border** - The border configuration for the cell. ``` ```APIDOC ## get_border_color ### Description Retrieves the border color of a cell at a given position and shape. ### Method GET ### Endpoint /papergrid/get_border_color ### Parameters #### Path Parameters - **pos** (Position) - Required - The position of the cell. - **shape** (tuple) - Required - The shape of the border color to retrieve. ### Response #### Success Response (200) - **Border<&ANSIBuf>** - The border color configuration for the cell. ``` ```APIDOC ## set_borders_missing ### Description Sets the character used when border configurations are missing. ### Method POST ### Endpoint /papergrid/set_borders_missing ### Parameters #### Path Parameters - **c** (char) - Required - The character to use for missing borders. ### Response #### Success Response (200) - **None** ``` ```APIDOC ## get_borders_missing ### Description Gets the character used for missing border configurations. ### Method GET ### Endpoint /papergrid/get_borders_missing ### Response #### Success Response (200) - **char** - The character used for missing borders. ``` ```APIDOC ## get_border_color_default ### Description Gets the default color for all borders on the grid. ### Method GET ### Endpoint /papergrid/get_border_color_default ### Response #### Success Response (200) - **Option<&ANSIBuf>** - The default border color, if set. ``` ```APIDOC ## set_border_color_default ### Description Sets the default color for all borders on the grid. ### Method POST ### Endpoint /papergrid/set_border_color_default ### Parameters #### Path Parameters - **clr** (ANSIBuf) - Required - The default border color. ### Response #### Success Response (200) - **None** ``` ```APIDOC ## get_color_borders ### Description Gets the colors of the border carcass on the grid. ### Method GET ### Endpoint /papergrid/get_color_borders ### Response #### Success Response (200) - **Borders** - The colors of the border carcass. ``` ```APIDOC ## set_borders_color ### Description Sets the colors of the border carcass on the grid. ### Method POST ### Endpoint /papergrid/set_borders_color ### Parameters #### Path Parameters - **clrs** (Borders) - Required - The border colors to set. ### Response #### Success Response (200) - **None** ``` ```APIDOC ## set_border_color ### Description Sets the color of a specific border of a cell on the grid. ### Method POST ### Endpoint /papergrid/set_border_color ### Parameters #### Path Parameters - **pos** (Position) - Required - The position of the cell. - **border** (Border) - Required - The border color configuration. ### Response #### Success Response (200) - **None** ``` ```APIDOC ## remove_border ### Description Removes all possible borders from an entity. This does not affect globally set borders. ### Method DELETE ### Endpoint /papergrid/remove_border ### Parameters #### Path Parameters - **pos** (Position) - Required - The starting position of the entity. - **shape** (tuple) - Required - The shape of the borders to remove. ### Response #### Success Response (200) - **None** ``` -------------------------------- ### VecRecords Initialization Source: https://docs.rs/papergrid/latest/src/papergrid/records/vec_records/mod.rs.html Methods for creating a new VecRecords instance from existing data. ```APIDOC ## VecRecords::new ### Description Creates a new VecRecords structure, assuming all rows in the provided data have the same length. ### Parameters - **data** (Vec>) - Required - A vector of vectors containing the grid data. ## VecRecords::with_size ### Description Creates a new VecRecords structure with explicit row and column counts. ### Parameters - **data** (Vec>) - Required - A vector of vectors containing the grid data. - **count_rows** (usize) - Required - The number of rows in the grid. - **count_cols** (usize) - Required - The number of columns in the grid. ``` -------------------------------- ### Count Verticals in Range - Rust Source: https://docs.rs/papergrid/latest/src/papergrid/grid/peekable.rs.html Counts the number of vertical lines within a specified column range. It checks for the presence of a vertical line at each column index (excluding the start and end columns) up to a maximum limit. Requires configuration, start and end column indices, and a maximum value. ```rust fn count_verticals_range(cfg: &SpannedConfig, start: usize, end: usize, max: usize) -> usize { (start + 1..end) .map(|i| cfg.has_vertical(i, max) as usize) .sum() } ``` -------------------------------- ### CompactConfig New Function Source: https://docs.rs/papergrid/latest/src/papergrid/config/compact/mod.rs.html Creates a new CompactConfig with standard settings. Initializes borders, margins, padding, and alignment to default values. ```rust pub const fn new() -> Self { Self { halignment: AlignmentHorizontal::Left, borders: Borders::empty(), border_colors: Borders::empty(), margin: Sides::filled(Indent::zero()), margin_color: Sides::filled(ANSIStr::new("", "")), padding: Sides::new( Indent::spaced(1), Indent::spaced(1), Indent::zero(), Indent::zero(), ), padding_color: Sides::filled(ANSIStr::new("", "")), } } ``` -------------------------------- ### Basic Grid Builder Implementation Source: https://docs.rs/papergrid/latest/src/papergrid/grid/peekable.rs.html The grid_basic module provides a simplified builder for grids without spans or complex styling. ```rust mod grid_basic { use super::*; struct TextCfg { alignment: AlignmentHorizontal, formatting: Formatting, justification: char, } #[derive(Debug, Clone, Copy)] struct Shape { count_rows: usize, count_columns: usize, } struct HIndent { left: usize, right: usize, } pub(super) fn build_grid(f: &mut F, ctx: PrintCtx<'_, R, D, C>) -> fmt::Result where F: Write, R: Records + PeekableRecords + ExactRecords, D: Dimension, { let shape = Shape { count_rows: ctx.records.count_rows(), count_columns: ctx.records.count_columns(), }; let mut new_line = false; for row in 0..shape.count_rows { let height = ctx.dims.get_height(row); let has_horizontal = ctx.cfg.has_horizontal(row, shape.count_rows); if new_line && (has_horizontal || height > 0) { f.write_char('\n')?; new_line = false; } if has_horizontal { print_split_line(f, ctx.cfg, ctx.dims, row, shape)?; if height > 0 { f.write_char('\n')?; } else { new_line = true; } } if height > 0 { print_grid_line(f, &ctx, shape, height, row, 0)?; } } } } ``` -------------------------------- ### Get Cell Padding Source: https://docs.rs/papergrid/latest/src/papergrid/config/spanned/mod.rs.html Retrieves the padding settings for a cell at a given position. ```rust pub fn get_padding(&self, pos: Position) -> &Sides { self.padding.get(pos) } ``` -------------------------------- ### Implement CloneToUninit for T (Nightly) Source: https://docs.rs/papergrid/latest/papergrid/colors/struct.NoColors.html Experimental nightly feature for cloning into uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Create Padding Configuration Source: https://docs.rs/papergrid/latest/src/papergrid/grid/compact.rs.html Constructs a Sides object containing ColoredIndent instances based on a CompactConfig. ```rust fn create_padding(cfg: &CompactConfig) -> Sides { let pad = cfg.get_padding(); let colors = cfg.get_padding_color(); Sides::new( ColoredIndent::new(pad.left.size, pad.left.fill, create_color(colors.left)), ColoredIndent::new(pad.right.size, pad.right.fill, create_color(colors.right)), ColoredIndent::new(pad.top.size, pad.top.fill, create_color(colors.top)), ColoredIndent::new( pad.bottom.size, pad.bottom.fill, create_color(colors.bottom), ), ) } ``` -------------------------------- ### CompactConfig Get Padding Source: https://docs.rs/papergrid/latest/src/papergrid/config/compact/mod.rs.html Retrieves the current padding settings for the grid cells. ```rust pub const fn get_padding(&self) -> &Sides { &self.padding } ``` -------------------------------- ### IterGrid Structure and Initialization Source: https://docs.rs/papergrid/latest/src/papergrid/grid/iterable.rs.html Details the IterGrid struct and its constructor for creating grid instances with specified records, configuration, dimensions, and colors. ```APIDOC ## IterGrid ### Description Represents a grid structure that provides methods for building text-based tables. ### Fields - **records** (R): The data records to be displayed in the grid. - **config** (G): The configuration settings for the grid's appearance and behavior. - **dimension** (D): The dimensions of the grid. - **colors** (C): The color settings for the grid. ### Methods #### `new(records: R, config: G, dimension: D, colors: C) -> Self` Creates a new `IterGrid` instance with the provided records, configuration, dimensions, and colors. This method initializes the grid with default styles. ### Example ```rust let grid = IterGrid::new(records, config, dimension, colors); ``` ``` -------------------------------- ### Justification Management Source: https://docs.rs/papergrid/latest/papergrid/config/spanned/struct.SpannedConfig.html Methods for getting and setting cell justification and associated colors. ```APIDOC ## GET /justification ### Description Get a justification character used while expanding cell dimensions. ### Parameters #### Query Parameters - **pos** (Position) - Required - The grid position of the cell. ## POST /justification ### Description Set a justification character for a specific entity. ### Request Body - **entity** (Entity) - Required - The entity to update. - **c** (char) - Required - The justification character. ``` -------------------------------- ### Using partition_point with binary_search in Rust Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Shows how `partition_point` can be used in conjunction with `binary_search` to find the range of matching elements or determine the correct insertion point for maintaining sorted order. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let low = s.partition_point(|x| x < &1); assert_eq!(low, 1); let high = s.partition_point(|x| x <= &1); assert_eq!(high, 5); let r = s.binary_search(&1); assert!((low..high).contains(&r.unwrap())); assert!(s[..low].iter().all(|&x| x < 1)); assert!(s[low..high].iter().all(|&x| x == 1)); assert!(s[high..].iter().all(|&x| x > 1)); // For something not found, the "range" of equal items is empty assert_eq!(s.partition_point(|x| x < &11), 9); assert_eq!(s.partition_point(|x| x <= &11), 9); assert_eq!(s.binary_search(&11), Err(9)); ``` ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert` // to shift less elements. s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### CompactConfig Configuration API Source: https://docs.rs/papergrid/latest/src/papergrid/config/compact/mod.rs.html Methods for configuring and retrieving grid settings such as borders, margins, padding, and alignment. ```APIDOC ## CompactConfig Struct ### Description Represents the configuration settings for a grid, including borders, margins, padding, and horizontal alignment. ### Methods - **new()**: Returns a default standard configuration. - **set_margin(Sides)**: Sets the grid margin. - **get_margin()**: Returns the current grid margin. - **set_borders(Borders)**: Sets the border characters. - **get_borders()**: Returns the current border characters. - **set_padding(Sides)**: Sets the padding for cells. - **get_padding()**: Returns the current cell padding. - **set_alignment_horizontal(AlignmentHorizontal)**: Sets the horizontal alignment. - **get_alignment_horizontal()**: Returns the current horizontal alignment. - **set_borders_color(Borders)**: Sets the colors for the border carcass. - **get_borders_color()**: Returns the current border colors. - **set_margin_color(Sides)**: Sets the colors for the margin. - **get_margin_color()**: Returns the current margin colors. - **set_padding_color(Sides)**: Sets the colors for the padding. - **get_padding_color()**: Returns the current padding colors. ``` -------------------------------- ### Get vector length with len Source: https://docs.rs/papergrid/latest/papergrid/records/vec_records/struct.VecRecords.html Returns the number of elements currently stored in the vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### PeekableGrid::new Constructor Source: https://docs.rs/papergrid/latest/papergrid/grid/peekable/struct.PeekableGrid.html Creates a new instance of PeekableGrid with default styles. It requires record, configuration, dimension, and color types as generic parameters. ```rust pub fn new(records: R, config: G, dimension: D, colors: C) -> Self ```