#![cfg_attr(feature = "derive", doc = "```")]
#![cfg_attr(not(feature = "derive"), doc = "```ignore")]
use papergrid::{
records::{Records, RecordsMut, Resizable},
width::CfgWidthFunction,
};
use crate::{Table, TableOption};
#[derive(Debug)]
pub struct Concat<T> {
table: Table<T>,
mode: ConcatMode,
default_cell: String,
}
#[derive(Debug)]
enum ConcatMode {
Vertical,
Horizontal,
}
impl<T> Concat<T> {
fn new(table: Table<T>, mode: ConcatMode) -> Self {
Self {
table,
mode,
default_cell: String::new(),
}
}
pub fn vertical(table: Table<T>) -> Self {
Self::new(table, ConcatMode::Vertical)
}
pub fn horizontal(table: Table<T>) -> Self {
Self::new(table, ConcatMode::Horizontal)
}
pub fn default_cell(mut self, cell: impl Into<String>) -> Self {
self.default_cell = cell.into();
self
}
}
impl<T, R> TableOption<R> for Concat<T>
where
R: Records + Resizable + RecordsMut<String>,
T: Records,
{
fn change(&mut self, lhs: &mut Table<R>) {
let (count_rows, count_cols) = lhs.shape();
let ctrl = CfgWidthFunction::from_cfg(lhs.get_config());
let rhs = &self.table;
match self.mode {
ConcatMode::Horizontal => {
for _ in 0..rhs.get_records().count_columns() {
lhs.get_records_mut().push_column();
}
for row in count_rows..rhs.shape().0 {
lhs.get_records_mut().push_row();
for col in 0..lhs.get_records().count_columns() {
lhs.get_records_mut()
.set((row, col), self.default_cell.clone(), &ctrl);
}
}
for row in 0..rhs.shape().0 {
for col in 0..rhs.shape().1 {
let text = rhs.get_records().get_text((row, col)).to_owned();
let col = col + count_cols;
lhs.get_records_mut().set((row, col), text, &ctrl);
}
}
}
ConcatMode::Vertical => {
for _ in 0..rhs.shape().0 {
lhs.get_records_mut().push_row();
}
for col in count_cols..rhs.shape().1 {
lhs.get_records_mut().push_column();
for row in 0..lhs.shape().0 {
lhs.get_records_mut()
.set((row, col), self.default_cell.clone(), &ctrl);
}
}
for row in 0..rhs.shape().0 {
for col in 0..rhs.shape().1 {
let text = rhs.get_records().get_text((row, col)).to_owned();
let row = row + count_rows;
lhs.get_records_mut().set((row, col), text, &ctrl);
}
}
}
}
}
}