Skip to content

Commit

Permalink
Merge pull request #434 from zhiburt/patch/refactorings-1
Browse files Browse the repository at this point in the history
More refactorings
  • Loading branch information
zhiburt authored Nov 4, 2024
2 parents 68f139f + 56f2dae commit 035cdb1
Show file tree
Hide file tree
Showing 32 changed files with 312 additions and 290 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@1.62.1
- uses: dtolnay/rust-toolchain@1.66.0
- run: cargo build --manifest-path=./tabled/Cargo.toml --all-features

fmt:
Expand Down
17 changes: 17 additions & 0 deletions papergrid/src/config/border.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,23 @@ impl<T> Border<T> {
|| self.right_top_corner.is_some()
|| self.right_bottom_corner.is_some()
}

/// Converts a border with a given function.
pub fn map<F, T1>(self, f: F) -> Border<T1>
where
F: Fn(T) -> T1,
{
Border {
top: self.top.map(&f),
bottom: self.bottom.map(&f),
left: self.left.map(&f),
right: self.right.map(&f),
left_top_corner: self.left_top_corner.map(&f),
left_bottom_corner: self.left_bottom_corner.map(&f),
right_top_corner: self.right_top_corner.map(&f),
right_bottom_corner: self.right_bottom_corner.map(&f),
}
}
}

impl<T: Copy> Border<T> {
Expand Down
24 changes: 24 additions & 0 deletions papergrid/src/config/borders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,28 @@ impl<T> Borders<T> {
vertical: self.vertical.map(Into::into),
}
}

/// Converts borders with a given function.
pub fn map<F, T1>(self, f: F) -> Borders<T1>
where
F: Fn(T) -> T1,
{
Borders {
left: self.left.map(&f),
right: self.right.map(&f),
top: self.top.map(&f),
bottom: self.bottom.map(&f),
bottom_intersection: self.bottom_intersection.map(&f),
bottom_left: self.bottom_left.map(&f),
bottom_right: self.bottom_right.map(&f),
horizontal: self.horizontal.map(&f),
intersection: self.intersection.map(&f),
left_intersection: self.left_intersection.map(&f),
right_intersection: self.right_intersection.map(&f),
top_intersection: self.top_intersection.map(&f),
top_left: self.top_left.map(&f),
top_right: self.top_right.map(&f),
vertical: self.vertical.map(&f),
}
}
}
20 changes: 13 additions & 7 deletions papergrid/src/config/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,7 @@ pub enum Entity {
impl Entity {
/// Iterate over cells which are covered via the [`Entity`].
pub fn iter(&self, count_rows: usize, count_cols: usize) -> EntityIterator {
EntityIterator {
entity: *self,
count_rows,
count_cols,
i: 0,
j: 0,
}
EntityIterator::new(*self, count_rows, count_cols)
}
}

Expand All @@ -65,6 +59,18 @@ pub struct EntityIterator {
j: usize,
}

impl EntityIterator {
fn new(entity: Entity, count_rows: usize, count_cols: usize) -> Self {
Self {
entity,
count_rows,
count_cols,
i: 0,
j: 0,
}
}
}

impl Iterator for EntityIterator {
type Item = Position;

Expand Down
2 changes: 1 addition & 1 deletion papergrid/src/config/formatting.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// Formatting represent a logic of formatting of a cell.
/// Formatting represent a logic of formatting of a cell text.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Formatting {
/// An setting to allow horizontal trim.
Expand Down
13 changes: 13 additions & 0 deletions papergrid/src/config/sides.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,17 @@ impl<T> Sides<T> {
self.bottom.into(),
)
}

/// Converts all sides with a given function.
pub fn map<F, T1>(self, f: F) -> Sides<T1>
where
F: Fn(T) -> T1,
{
Sides::new(
(f)(self.left),
(f)(self.right),
(f)(self.top),
(f)(self.bottom),
)
}
}
32 changes: 0 additions & 32 deletions papergrid/src/grid/iterable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1313,40 +1313,8 @@ fn text_width(text: &str, trim: bool) -> usize {

#[cfg(test)]
mod tests {
// use crate::util::string_width;

use super::*;

// #[test]
// fn horizontal_alignment_test() {
// use std::fmt;

// struct F<'a>(&'a str, AlignmentHorizontal, usize);

// impl fmt::Display for F<'_> {
// fn fmt(&self, f: &mut impl fmt::Write) -> fmt::Result {
// let (left, right) = calculate_indent(self.1, string_width(self.0), self.2);
// print_text_formatted(f, &self.0, 4, Option::<&AnsiColor<'_>>::None)
// }
// }

// assert_eq!(F("AAA", AlignmentHorizontal::Right, 4).to_string(), " AAA");
// assert_eq!(F("AAA", AlignmentHorizontal::Left, 4).to_string(), "AAA ");
// assert_eq!(F("AAA", AlignmentHorizontal::Center, 4).to_string(), "AAA ");
// assert_eq!(F("🎩", AlignmentHorizontal::Center, 4).to_string(), " 🎩 ");
// assert_eq!(F("🎩", AlignmentHorizontal::Center, 3).to_string(), "🎩 ");

// #[cfg(feature = "ansi")]
// {
// use owo_colors::OwoColorize;
// let text = "Colored Text".red().to_string();
// assert_eq!(
// F(&text, AlignmentHorizontal::Center, 15).to_string(),
// format!(" {} ", text)
// );
// }
// }

#[test]
fn vertical_alignment_test() {
use AlignmentVertical::*;
Expand Down
4 changes: 2 additions & 2 deletions papergrid/src/grid/peekable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ mod grid_basic {
where
F: fmt::Write,
{
let intersection = match cfg.get_intersection(pos, (shape.count_rows, shape.count_columns))
{
let intersection = cfg.get_intersection(pos, (shape.count_rows, shape.count_columns));
let intersection = match intersection {
Some(c) => c,
None => return Ok(()),
};
Expand Down
12 changes: 11 additions & 1 deletion papergrid/src/util/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,17 @@ pub fn get_char_width(c: char) -> usize {

/// Returns a string width (accouting all characters).
pub fn get_string_width(text: &str) -> usize {
unicode_width::UnicodeWidthStr::width(text.replace(|c| c < ' ', "").as_str())
#[cfg(feature = "std")]
{
let text = text.replace(|c| c < ' ', "");
unicode_width::UnicodeWidthStr::width(text.as_str())
}

#[cfg(not(feature = "std"))]
{
// todo: make sure it's allright
unicode_width::UnicodeWidthStr::width(text)
}
}

/// Calculates a number of lines.
Expand Down
4 changes: 2 additions & 2 deletions tabled/examples/nested_table_3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use tabled::{
settings::{
object::Rows,
style::{BorderSpanCorrection, Style},
Alignment, Border, Extract, Highlight, Padding, Panel,
Alignment, Extract, Highlight, Padding, Panel,
},
Table, Tabled,
};
Expand Down Expand Up @@ -54,7 +54,7 @@ fn main() {
.with(Style::ascii().remove_horizontal())
.modify(Rows::new(1..), Padding::new(1, 1, 1, 0))
.with(Alignment::center())
.with(Highlight::border(Rows::first(), Border::filled('*')));
.with(Highlight::outline(Rows::first(), '*'));

println!("{welcome_table}");
}
52 changes: 26 additions & 26 deletions tabled/src/builder/index_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ impl IndexBuilder {
std::mem::swap(&mut self.index, &mut columns);

let count_columns = columns.len();
make_rows_columns(&mut self.data, self.index.len());
rotate_vector(&mut self.data, self.index.len());

self.data.insert(0, columns);

Expand Down Expand Up @@ -280,35 +280,22 @@ fn build_range_index(n: usize) -> Vec<Text<String>> {
(0..n).map(|i| i.to_string()).map(Text::new).collect()
}

fn get_column<T>(v: &mut [Vec<T>], col: usize) -> Vec<T>
// note: Pretty heavy operation.
fn rotate_vector<T>(rows: &mut Vec<Vec<T>>, count_columns: usize)
where
T: Default,
T: Default + Clone,
{
let mut column = Vec::with_capacity(v.len());
for row in v.iter_mut() {
let value = row.remove(col);
column.push(value);
}

column
}

// todo: Seems like can be hugely simplified.
fn make_rows_columns<T>(v: &mut Vec<Vec<T>>, count_columns: usize)
where
T: Default,
{
let mut columns = Vec::with_capacity(count_columns);
for _ in 0..count_columns {
let column = get_column(v, 0);
columns.push(column);
let count_rows = rows.len();
let mut columns = vec![vec![T::default(); count_rows]; count_columns];
for col in 0..count_columns {
for (row, data) in rows.iter_mut().enumerate() {
let value = data.pop().expect("expected to be controlled");
let col = count_columns - col - 1;
columns[col][row] = value;
}
}

v.clear();

for column in columns {
v.push(column);
}
*rows = columns;
}

fn insert_column<T: Default>(v: &mut [Vec<T>], mut column: Vec<T>, col: usize) {
Expand All @@ -317,3 +304,16 @@ fn insert_column<T: Default>(v: &mut [Vec<T>], mut column: Vec<T>, col: usize) {
row.insert(col, value);
}
}

fn get_column<T>(v: &mut [Vec<T>], col: usize) -> Vec<T>
where
T: Default,
{
let mut column = Vec::with_capacity(v.len());
for row in v.iter_mut() {
let value = row.remove(col);
column.push(value);
}

column
}
File renamed without changes.
1 change: 1 addition & 0 deletions tabled/src/grid/config/compact_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub use papergrid::config::compact::CompactConfig;
File renamed without changes.
26 changes: 26 additions & 0 deletions tabled/src/grid/config/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Module contains a list of configs for varios tables/grids.
#[cfg(feature = "std")]
mod colored_config;

#[cfg(feature = "std")]
mod spanned_config;

mod compact_config;
mod compact_multiline_config;

pub use papergrid::config::{
AlignmentHorizontal, AlignmentVertical, Border, Borders, Entity, EntityIterator, Formatting,
HorizontalLine, Indent, Position, Sides, VerticalLine,
};

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use spanned_config::{EntityMap, Offset, SpannedConfig};

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use colored_config::{ColorMap, ColoredConfig};

pub use compact_config::CompactConfig;
pub use compact_multiline_config::CompactMultilineConfig;
1 change: 1 addition & 0 deletions tabled/src/grid/config/spanned_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub use papergrid::config::spanned::{EntityMap, Offset, SpannedConfig};
24 changes: 1 addition & 23 deletions tabled/src/grid/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,15 @@
//!
//! [`TableOption`]: crate::settings::TableOption
//! [`CellOption`]: crate::settings::CellOption
#[cfg(feature = "std")]
mod colored_config;

mod compact_multiline_config;
pub mod config;
pub mod dimension;
pub mod records;

pub use papergrid::ansi;
pub use papergrid::colors;
pub use papergrid::util;

pub mod config {
//! Module contains a list of configs for varios tables/grids.
pub use papergrid::config::{
compact::CompactConfig, AlignmentHorizontal, AlignmentVertical, Border, Borders, Entity,
EntityIterator, Formatting, HorizontalLine, Indent, Position, Sides, VerticalLine,
};

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use papergrid::config::spanned::{EntityMap, Offset, SpannedConfig};

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use super::colored_config::{ColorMap, ColoredConfig};

pub use super::compact_multiline_config::CompactMultilineConfig;
}

pub use papergrid::grid::compact::CompactGrid;

#[cfg(feature = "std")]
Expand Down
4 changes: 2 additions & 2 deletions tabled/src/settings/alignment/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,15 @@ impl Alignment {
}

/// Convert alignment to horizontal.
pub const fn get_horizontal(self) -> Option<AlignmentHorizontal> {
pub const fn as_horizontal(self) -> Option<AlignmentHorizontal> {
match self.inner {
Horizontal(alignment) => Some(alignment),
Vertical(_) => None,
}
}

/// Convert alignment to vertical.
pub const fn get_vertical(self) -> Option<AlignmentVertical> {
pub const fn as_vertical(self) -> Option<AlignmentVertical> {
match self.inner {
Horizontal(_) => None,
Vertical(alignment) => Some(alignment),
Expand Down
Loading

0 comments on commit 035cdb1

Please sign in to comment.