use std::{
cell::RefCell,
convert::Infallible,
fmt,
fmt::Write as _,
io,
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
use crate::{
engine::{AggregateRow, Branch, GroupInfo},
model::{
CellValue, ColumnSet, GridColumns, GridRow, NumberFormat, OwnedValue, display_text_in,
number_fraction_digits, push_fixed, push_timestamp,
},
state::{ColumnAlign, ColumnZone},
store::PinnedEdge,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExportScope {
Visible,
Selection,
Expanded,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExportLine {
Data,
Caption,
Footer,
Totals,
}
impl ExportLine {
const ALL: [Self; 4] = [Self::Data, Self::Caption, Self::Footer, Self::Totals];
const fn bit(self) -> u8 {
1 << self as u8
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExportLines(u8);
impl ExportLines {
pub const EMPTY: Self = Self(0);
pub const ALL: Self = Self((1 << ExportLine::ALL.len()) - 1);
pub const fn with(self, line: ExportLine) -> Self {
Self(self.0 | line.bit())
}
pub const fn without(self, line: ExportLine) -> Self {
Self(self.0 & !line.bit())
}
pub const fn contains(self, line: ExportLine) -> bool {
self.0 & line.bit() != 0
}
}
impl Default for ExportLines {
fn default() -> Self {
Self::ALL
}
}
impl fmt::Debug for ExportLines {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set()
.entries(ExportLine::ALL.iter().filter(|line| self.contains(**line)))
.finish()
}
}
pub trait CellExporter<R: GridRow>: Send + Sync + 'static {
fn write_cell(&self, cell: &ExportCell<'_, R>, out: &mut String);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RawCells {
decimal_separator: char,
precision: NumberPrecision,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NumberPrecision {
#[default]
Shown,
Full,
}
impl RawCells {
pub const fn new() -> Self {
Self {
decimal_separator: '.',
precision: NumberPrecision::Shown,
}
}
pub const fn with_precision(mut self, precision: NumberPrecision) -> Self {
self.precision = precision;
self
}
pub const fn precision(&self) -> NumberPrecision {
self.precision
}
pub const fn with_decimal_separator(mut self, separator: char) -> Self {
self.decimal_separator = separator;
self
}
pub const fn decimal_separator(&self) -> char {
self.decimal_separator
}
fn write_float(self, value: f64, format: NumberFormat, out: &mut String) {
if !value.is_finite() {
return;
}
let start = out.len();
match self.precision {
NumberPrecision::Shown => push_fixed(value, format.decimals(), out),
NumberPrecision::Full => {
let _ = write!(out, "{value}");
}
}
self.replace_point(start, out);
}
#[cfg(feature = "decimal")]
fn write_decimal(self, value: rust_decimal::Decimal, out: &mut String) {
let start = out.len();
let _ = write!(out, "{value}");
self.replace_point(start, out);
}
fn replace_point(self, start: usize, out: &mut String) {
if self.decimal_separator != '.'
&& let Some(dot) = out[start..].find('.')
{
let dot = start + dot;
let mut separator = [0; 4];
out.replace_range(
dot..dot + 1,
self.decimal_separator.encode_utf8(&mut separator),
);
}
}
}
impl Default for RawCells {
fn default() -> Self {
Self::new()
}
}
impl<R: GridRow> CellExporter<R> for RawCells {
#[inline]
fn write_cell(&self, cell: &ExportCell<'_, R>, out: &mut String) {
match cell.value() {
CellValue::Custom(value) => match value.export_value() {
Some(export) => self.write_value(export, cell.number_format(), out),
None => value.write_text(out),
},
value => self.write_value(value, cell.number_format(), out),
}
}
}
impl RawCells {
#[inline]
fn write_value(self, value: CellValue<'_>, format: NumberFormat, out: &mut String) {
match value {
CellValue::Empty => {}
CellValue::Bool(value) => out.push_str(if value { "TRUE" } else { "FALSE" }),
CellValue::Int(value) => {
let _ = write!(out, "{value}");
}
CellValue::Float(value) => self.write_float(value, format, out),
#[cfg(feature = "decimal")]
CellValue::Decimal(value) => self.write_decimal(value, out),
CellValue::Text(text) => out.push_str(text),
CellValue::Timestamp(value) => push_timestamp(value, out),
CellValue::Icon(icon) => out.push_str(icon.text()),
CellValue::Image(image) => out.push_str(image.text()),
CellValue::Link(link) => out.push_str(link.text()),
CellValue::Custom(value) => value.write_text(out),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DisplayedCells;
thread_local! {
static DISPLAY_BUFFER: RefCell<String> = const { RefCell::new(String::new()) };
}
impl<R: GridRow> CellExporter<R> for DisplayedCells {
#[inline]
fn write_cell(&self, cell: &ExportCell<'_, R>, out: &mut String) {
DISPLAY_BUFFER.with_borrow_mut(|buffer| {
out.push_str(display_text_in(cell.value(), cell.number_format(), buffer))
});
}
}
#[non_exhaustive]
pub enum CellExport<R: GridRow> {
Raw(RawCells),
Displayed(DisplayedCells),
Custom(Arc<dyn CellExporter<R>>),
}
impl<R: GridRow> Default for CellExport<R> {
fn default() -> Self {
Self::Raw(RawCells::new())
}
}
impl<R: GridRow> Clone for CellExport<R> {
fn clone(&self) -> Self {
match self {
Self::Raw(raw) => Self::Raw(*raw),
Self::Displayed(displayed) => Self::Displayed(*displayed),
Self::Custom(custom) => Self::Custom(custom.clone()),
}
}
}
impl<R: GridRow> CellExporter<R> for CellExport<R> {
#[inline]
fn write_cell(&self, cell: &ExportCell<'_, R>, out: &mut String) {
match self {
Self::Raw(raw) => raw.write_cell(cell, out),
Self::Displayed(displayed) => displayed.write_cell(cell, out),
Self::Custom(custom) => custom.write_cell(cell, out),
}
}
}
pub trait Exporter<R: GridRow>: Send + Sync + 'static {
fn export(&self, table: &ExportTable<'_, R>, cells: &CellExport<R>, out: &mut String);
}
pub trait ExportFormat<R: GridRow>: Send + Sync + 'static {
fn extension(&self) -> &str;
fn export(
&self,
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
out: &mut dyn io::Write,
control: &ExportControl,
) -> Result<(), ExportError>;
}
#[derive(Clone, Debug)]
pub struct ExportControl {
shared: Arc<ControlState>,
}
#[derive(Debug)]
struct ControlState {
rows_total: AtomicUsize,
rows_written: AtomicUsize,
cancelled: AtomicBool,
}
impl ExportControl {
pub fn new(rows_total: usize) -> Self {
Self {
shared: Arc::new(ControlState {
rows_total: AtomicUsize::new(rows_total),
rows_written: Default::default(),
cancelled: Default::default(),
}),
}
}
pub fn rows_total(&self) -> usize {
self.shared.rows_total.load(Ordering::Relaxed)
}
pub(crate) fn set_rows_total(&self, rows_total: usize) {
self.shared.rows_total.store(rows_total, Ordering::Relaxed);
}
pub fn rows_written(&self) -> usize {
self.shared.rows_written.load(Ordering::Relaxed)
}
pub fn advance(&self, rows: usize) -> Result<(), ExportError> {
self.shared.rows_written.fetch_add(rows, Ordering::Relaxed);
if self.is_cancelled() {
return Err(ExportError::Cancelled);
}
Ok(())
}
pub fn is_cancelled(&self) -> bool {
self.shared.cancelled.load(Ordering::Relaxed)
}
pub fn cancel(&self) {
self.shared.cancelled.store(true, Ordering::Relaxed);
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ExportError {
Nothing,
Cancelled,
Io(Arc<io::Error>),
Other(Arc<dyn std::error::Error + Send + Sync>),
}
impl ExportError {
pub fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
Self::Other(Arc::from(error.into()))
}
}
impl From<io::Error> for ExportError {
fn from(error: io::Error) -> Self {
Self::Io(Arc::new(error))
}
}
impl fmt::Display for ExportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Nothing => f.write_str("nothing to export"),
Self::Cancelled => f.write_str("the export was cancelled"),
Self::Io(error) => fmt::Display::fmt(error, f),
Self::Other(error) => fmt::Display::fmt(error, f),
}
}
}
impl std::error::Error for ExportError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => error.source(),
Self::Other(error) => error.source(),
Self::Nothing | Self::Cancelled => None,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct TsvExporter;
const CELL_ESTIMATE: usize = 8;
const FLUSH_ROWS: usize = 1024;
#[derive(Clone, Copy)]
struct TextDialect {
separator: char,
between_lines: &'static str,
after_line: &'static str,
}
impl TextDialect {
const TSV: Self = Self {
separator: '\t',
between_lines: "\n",
after_line: "",
};
const fn csv(separator: char) -> Self {
Self {
separator,
between_lines: "",
after_line: "\r\n",
}
}
}
impl<R: GridRow> Exporter<R> for TsvExporter {
fn export(&self, table: &ExportTable<'_, R>, cells: &CellExport<R>, out: &mut String) {
out.reserve(table.rows().len() * (table.columns().len() * CELL_ESTIMATE + 1));
write_delimited(table, cells, TextDialect::TSV, out, |_, _| {
Ok::<_, Infallible>(())
})
.unwrap_or_else(|never| match never {});
}
}
impl<R: GridRow> ExportFormat<R> for TsvExporter {
fn extension(&self) -> &str {
"tsv"
}
fn export(
&self,
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
out: &mut dyn io::Write,
control: &ExportControl,
) -> Result<(), ExportError> {
write_delimited_file(table, cells, TextDialect::TSV, "", out, control)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CsvFormat {
separator: char,
encoding: CsvEncoding,
}
impl CsvFormat {
pub const fn new() -> Self {
Self {
separator: ',',
encoding: CsvEncoding::Utf8WithBom,
}
}
pub const fn with_separator(mut self, separator: char) -> Self {
assert!(
!matches!(separator, '"' | '\r' | '\n'),
"a CSV separator cannot be a quote or a line break"
);
self.separator = separator;
self
}
pub const fn separator(&self) -> char {
self.separator
}
pub const fn with_encoding(mut self, encoding: CsvEncoding) -> Self {
self.encoding = encoding;
self
}
pub const fn encoding(&self) -> CsvEncoding {
self.encoding
}
}
impl Default for CsvFormat {
fn default() -> Self {
Self::new()
}
}
impl<R: GridRow> ExportFormat<R> for CsvFormat {
fn extension(&self) -> &str {
"csv"
}
fn export(
&self,
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
out: &mut dyn io::Write,
control: &ExportControl,
) -> Result<(), ExportError> {
write_delimited_file(
table,
cells,
TextDialect::csv(self.separator),
self.encoding.preamble(),
out,
control,
)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CsvEncoding {
#[default]
Utf8WithBom,
Utf8,
}
impl CsvEncoding {
const fn preamble(self) -> &'static str {
match self {
Self::Utf8WithBom => "\u{feff}",
Self::Utf8 => "",
}
}
}
fn write_delimited<R: GridRow, E>(
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
dialect: TextDialect,
buffer: &mut String,
mut flush: impl FnMut(&mut String, usize) -> Result<(), E>,
) -> Result<(), E> {
let columns = table.columns();
let separator = dialect.separator;
let mut scratch = String::new();
let mut is_first_line = true;
let mut begin_line = |buffer: &mut String| {
if !is_first_line {
buffer.push_str(dialect.between_lines);
}
is_first_line = false;
};
if table.has_header() {
begin_line(buffer);
for (ix, column) in columns.iter().enumerate() {
if ix > 0 {
buffer.push(separator);
}
let start = buffer.len();
buffer.push_str(column.title());
quote_field(buffer, start, separator, &mut scratch);
}
buffer.push_str(dialect.after_line);
}
if table.rows().is_empty() {
return flush(buffer, 0);
}
for chunk in table.rows().chunks(FLUSH_ROWS) {
for row in chunk {
begin_line(buffer);
for (ix, column) in columns.iter().enumerate() {
if ix > 0 {
buffer.push(separator);
}
if let Some(cell) = row.cell(column.column()) {
let start = buffer.len();
cells.write_cell(&cell, buffer);
quote_field(buffer, start, separator, &mut scratch);
}
}
buffer.push_str(dialect.after_line);
}
flush(buffer, chunk.len())?;
}
Ok(())
}
fn write_delimited_file<R: GridRow>(
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
dialect: TextDialect,
preamble: &str,
out: &mut dyn io::Write,
control: &ExportControl,
) -> Result<(), ExportError> {
let rows = table.rows().len().min(FLUSH_ROWS);
let mut buffer = String::with_capacity(
preamble.len() + (rows + 1) * (table.columns().len() * CELL_ESTIMATE + 2),
);
buffer.push_str(preamble);
write_delimited(table, cells, dialect, &mut buffer, |buffer, rows| {
out.write_all(buffer.as_bytes())?;
buffer.clear();
control.advance(rows)
})?;
out.flush()?;
Ok(())
}
#[inline]
fn quote_field(out: &mut String, start: usize, separator: char, scratch: &mut String) {
let field = &out.as_bytes()[start..];
let needs_quotes = if separator.is_ascii() {
let separator = separator as u8;
field
.iter()
.any(|&byte| byte == separator || matches!(byte, b'\n' | b'\r' | b'"'))
} else {
field
.iter()
.any(|byte| matches!(byte, b'\n' | b'\r' | b'"'))
|| out[start..].contains(separator)
};
if !needs_quotes {
return;
}
scratch.clear();
scratch.push_str(&out[start..]);
out.truncate(start);
out.push('"');
for (ix, part) in scratch.split('"').enumerate() {
if ix > 0 {
out.push_str("\"\"");
}
out.push_str(part);
}
out.push('"');
}
#[derive(Clone, Debug)]
pub struct TextFile<E> {
exporter: E,
extension: Arc<str>,
}
impl<E> TextFile<E> {
pub fn new(exporter: E, extension: impl Into<Arc<str>>) -> Self {
Self {
exporter,
extension: extension.into(),
}
}
pub fn exporter(&self) -> &E {
&self.exporter
}
}
impl<R: GridRow, E: Exporter<R>> ExportFormat<R> for TextFile<E> {
fn extension(&self) -> &str {
&self.extension
}
fn export(
&self,
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
out: &mut dyn io::Write,
control: &ExportControl,
) -> Result<(), ExportError> {
control.advance(0)?;
let mut text = String::new();
self.exporter.export(table, cells, &mut text);
out.write_all(text.as_bytes())?;
out.flush()?;
control.advance(table.rows().len())
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct LineFilter<E> {
exporter: E,
lines: ExportLines,
}
impl<E> LineFilter<E> {
pub fn new(exporter: E, lines: ExportLines) -> Self {
Self { exporter, lines }
}
pub fn exporter(&self) -> &E {
&self.exporter
}
pub fn lines(&self) -> ExportLines {
self.lines
}
fn kept_rows<'a, R: GridRow>(
&self,
table: &ExportTable<'a, R>,
) -> Option<Vec<ExportRow<'a, R>>> {
let is_kept = |row: &ExportRow<'_, R>| self.lines.contains(row.line());
if table.rows().iter().all(is_kept) {
return None;
}
Some(table.rows().iter().copied().filter(is_kept).collect())
}
}
impl<R: GridRow, E: Exporter<R>> Exporter<R> for LineFilter<E> {
fn export(&self, table: &ExportTable<'_, R>, cells: &CellExport<R>, out: &mut String) {
match self.kept_rows(table) {
None => self.exporter.export(table, cells, out),
Some(kept) => self.exporter.export(&table.with_rows(&kept), cells, out),
}
}
}
impl<R: GridRow, E: ExportFormat<R>> ExportFormat<R> for LineFilter<E> {
fn extension(&self) -> &str {
self.exporter.extension()
}
fn export(
&self,
table: &ExportTable<'_, R>,
cells: &CellExport<R>,
out: &mut dyn io::Write,
control: &ExportControl,
) -> Result<(), ExportError> {
match self.kept_rows(table) {
None => self.exporter.export(table, cells, out, control),
Some(kept) => {
control.advance(table.rows().len() - kept.len())?;
self.exporter
.export(&table.with_rows(&kept), cells, out, control)
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ExportColumn<'a, C> {
column: C,
title: &'a str,
width: Option<f32>,
align: ColumnAlign,
zone: ColumnZone,
bands: &'a [&'a str],
}
impl<'a, C: GridColumns> ExportColumn<'a, C> {
pub const fn new(column: C, title: &'a str) -> Self {
Self {
column,
title,
width: None,
align: ColumnAlign::Auto,
zone: ColumnZone::Scrolling,
bands: &[],
}
}
pub fn with_width(self, width: f32) -> Self {
Self {
width: Some(width),
..self
}
}
pub fn with_align(self, align: ColumnAlign) -> Self {
Self { align, ..self }
}
pub fn with_zone(self, zone: ColumnZone) -> Self {
Self { zone, ..self }
}
pub fn with_bands(self, bands: &'a [&'a str]) -> Self {
Self { bands, ..self }
}
pub fn column(&self) -> C {
self.column
}
pub fn title(&self) -> &'a str {
self.title
}
pub fn width(&self) -> Option<f32> {
self.width
}
pub fn align(&self) -> ColumnAlign {
self.align
}
pub fn zone(&self) -> ColumnZone {
self.zone
}
pub fn bands(&self) -> &'a [&'a str] {
self.bands
}
}
pub struct ExportRow<'a, R: GridRow> {
source: RowSource<'a, R>,
columns: ColumnSet,
formats: &'a [NumberFormat],
depth: u16,
band: Option<PinnedEdge>,
hidden: bool,
}
enum RowSource<'a, R: GridRow> {
Data {
row: &'a R,
pending: &'a [(R::Column, OwnedValue)],
branch: Option<Branch>,
},
Caption {
group: GroupInfo<'a>,
value_column: R::Column,
},
Footer(GroupInfo<'a>),
Totals {
aggregates: AggregateRow<'a>,
label: Option<(R::Column, &'a str)>,
},
}
impl<R: GridRow> Clone for RowSource<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: GridRow> Copy for RowSource<'_, R> {}
impl<'a, R: GridRow> ExportRow<'a, R> {
pub fn new(row: &'a R) -> Self {
Self::of(
RowSource::Data {
row,
pending: &[],
branch: None,
},
0,
)
}
pub fn caption(value_column: R::Column, group: GroupInfo<'a>) -> Self {
Self::of(
RowSource::Caption {
group,
value_column,
},
group.depth(),
)
}
pub fn footer(group: GroupInfo<'a>) -> Self {
Self::of(RowSource::Footer(group), group.depth())
}
pub fn totals(aggregates: AggregateRow<'a>, label: Option<(R::Column, &'a str)>) -> Self {
Self::of(RowSource::Totals { aggregates, label }, 0)
}
fn of(source: RowSource<'a, R>, depth: u16) -> Self {
Self {
source,
columns: ColumnSet::first(R::Column::all().len()),
formats: &[],
depth,
band: None,
hidden: false,
}
}
pub fn with_number_formats(self, formats: &'a [NumberFormat]) -> Self {
Self { formats, ..self }
}
pub fn with_depth(self, depth: u16) -> Self {
Self { depth, ..self }
}
pub fn with_columns(self, columns: ColumnSet) -> Self {
Self { columns, ..self }
}
pub fn with_band(self, edge: PinnedEdge) -> Self {
Self {
band: Some(edge),
..self
}
}
pub fn with_hidden(self, hidden: bool) -> Self {
Self { hidden, ..self }
}
pub fn with_branch(self, branch: Branch) -> Self {
let source = match self.source {
RowSource::Data { row, pending, .. } => RowSource::Data {
row,
pending,
branch: Some(branch),
},
source => source,
};
Self { source, ..self }
}
pub fn with_pending(self, pending: &'a [(R::Column, OwnedValue)]) -> Self {
let source = match self.source {
RowSource::Data { row, branch, .. } => RowSource::Data {
row,
pending,
branch,
},
source => source,
};
Self { source, ..self }
}
pub fn line(&self) -> ExportLine {
match self.source {
RowSource::Data { .. } => ExportLine::Data,
RowSource::Caption { .. } => ExportLine::Caption,
RowSource::Footer(_) => ExportLine::Footer,
RowSource::Totals { .. } => ExportLine::Totals,
}
}
pub fn row(&self) -> Option<&'a R> {
match self.source {
RowSource::Data { row, .. } => Some(row),
_ => None,
}
}
pub fn band(&self) -> Option<PinnedEdge> {
self.band
}
pub fn is_hidden(&self) -> bool {
self.hidden
}
pub fn branch(&self) -> Option<Branch> {
match self.source {
RowSource::Data { branch, .. } => branch,
_ => None,
}
}
pub fn group(&self) -> Option<GroupInfo<'a>> {
match self.source {
RowSource::Caption { group, .. } | RowSource::Footer(group) => Some(group),
_ => None,
}
}
pub fn depth(&self) -> u16 {
self.depth
}
pub fn columns(&self) -> ColumnSet {
self.columns
}
pub fn cell(&self, column: R::Column) -> Option<ExportCell<'a, R>> {
let ix = column.ix();
if !self.columns.contains(ix) {
return None;
}
let mut is_pending = false;
let (source, value, is_aggregate) = match self.source {
RowSource::Data { row, pending, .. } => {
let value = match pending.iter().find(|(edited, _)| *edited == column) {
Some((_, value)) => {
is_pending = true;
value.as_cell()
}
None => row.value(column),
};
(CellSource::Data(row), value, false)
}
RowSource::Caption {
group,
value_column,
} => {
let source = CellSource::Caption(group);
if column == value_column {
(source, group.value().as_cell(), false)
} else {
(source, group.aggregates().get(ix)?.as_cell(), true)
}
}
RowSource::Footer(group) => (
CellSource::Footer(group),
group.aggregates().get(ix)?.as_cell(),
true,
),
RowSource::Totals { aggregates, label } => match (aggregates.get(ix), label) {
(Some(aggregate), _) => (CellSource::Totals, aggregate.as_cell(), true),
(None, Some((label_column, label))) if label_column == column => {
(CellSource::Totals, CellValue::Text(label), false)
}
(None, _) => return None,
},
};
Some(ExportCell {
source,
column,
value,
number_format: self.formats.get(ix.get()).copied().unwrap_or_default(),
depth: self.depth,
is_aggregate,
is_pending,
})
}
}
impl<R: GridRow> Clone for ExportRow<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: GridRow> Copy for ExportRow<'_, R> {}
pub struct ExportCell<'a, R: GridRow> {
source: CellSource<'a, R>,
column: R::Column,
value: CellValue<'a>,
number_format: NumberFormat,
depth: u16,
is_aggregate: bool,
is_pending: bool,
}
enum CellSource<'a, R: GridRow> {
Data(&'a R),
Caption(GroupInfo<'a>),
Footer(GroupInfo<'a>),
Totals,
}
impl<R: GridRow> Clone for CellSource<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: GridRow> Copy for CellSource<'_, R> {}
impl<'a, R: GridRow> ExportCell<'a, R> {
pub fn row(&self) -> Option<&'a R> {
match self.source {
CellSource::Data(row) => Some(row),
_ => None,
}
}
pub fn column(&self) -> R::Column {
self.column
}
pub fn value(&self) -> CellValue<'a> {
self.value
}
pub fn is_pending(&self) -> bool {
self.is_pending
}
pub fn row_value(&self) -> Option<CellValue<'a>> {
match self.source {
CellSource::Data(row) if self.is_pending => Some(row.value(self.column)),
CellSource::Data(_) => Some(self.value),
_ => None,
}
}
pub fn number_format(&self) -> NumberFormat {
self.number_format
}
pub fn number_hint(&self) -> Option<NumberHint> {
number_fraction_digits(self.value, self.number_format)
.map(|fraction_digits| NumberHint { fraction_digits })
}
pub fn line(&self) -> ExportLine {
match self.source {
CellSource::Data(_) => ExportLine::Data,
CellSource::Caption(_) => ExportLine::Caption,
CellSource::Footer(_) => ExportLine::Footer,
CellSource::Totals => ExportLine::Totals,
}
}
pub fn depth(&self) -> u16 {
self.depth
}
pub fn group(&self) -> Option<GroupInfo<'a>> {
match self.source {
CellSource::Caption(group) | CellSource::Footer(group) => Some(group),
_ => None,
}
}
pub fn is_aggregate(&self) -> bool {
self.is_aggregate
}
}
impl<R: GridRow> Clone for ExportCell<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: GridRow> Copy for ExportCell<'_, R> {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NumberHint {
fraction_digits: u32,
}
impl NumberHint {
pub const fn fraction_digits(&self) -> u32 {
self.fraction_digits
}
}
pub struct ExportTable<'a, R: GridRow> {
columns: &'a [ExportColumn<'a, R::Column>],
rows: &'a [ExportRow<'a, R>],
header: bool,
}
impl<'a, R: GridRow> ExportTable<'a, R> {
pub fn new(columns: &'a [ExportColumn<'a, R::Column>], rows: &'a [ExportRow<'a, R>]) -> Self {
Self {
columns,
rows,
header: false,
}
}
pub fn with_header(self, header: bool) -> Self {
Self { header, ..self }
}
pub fn columns(&self) -> &'a [ExportColumn<'a, R::Column>] {
self.columns
}
pub fn has_header(&self) -> bool {
self.header
}
pub fn rows(&self) -> &'a [ExportRow<'a, R>] {
self.rows
}
pub fn frozen_columns(&self) -> usize {
self.columns
.iter()
.take_while(|column| column.zone() == ColumnZone::FrozenLeft)
.count()
}
pub fn band_depth(&self) -> usize {
self.columns
.iter()
.map(|column| column.bands().len())
.max()
.unwrap_or(0)
}
fn with_rows<'b>(&self, rows: &'b [ExportRow<'b, R>]) -> ExportTable<'b, R>
where
'a: 'b,
{
ExportTable {
columns: self.columns,
rows,
header: self.header,
}
}
}
impl<R: GridRow> Clone for ExportTable<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: GridRow> Copy for ExportTable<'_, R> {}
#[cfg(test)]
mod tests {
use std::{
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
time::Instant,
};
use super::*;
use crate::{
engine::{
Aggregate, EveryGroupFooter, GroupBy, GroupId, Projection, ProjectionEngine as _,
Rebuild, ViewSpec,
},
highlight::HighlightPolicy,
model::{ColumnIx, OwnedValue, display_text},
store::{Ingest, Op, StoreSnapshot},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Column {
Symbol,
Price,
Note,
}
impl GridColumns for Column {
fn all() -> &'static [Self] {
&[Self::Symbol, Self::Price, Self::Note]
}
fn id(self) -> &'static str {
match self {
Self::Symbol => "symbol",
Self::Price => "price",
Self::Note => "note",
}
}
fn ix(self) -> ColumnIx {
ColumnIx::new(self as u16)
}
}
struct Row {
key: u32,
cells: [CellValue<'static>; 3],
parent: Option<u32>,
}
impl Row {
fn new(key: u32, cells: [CellValue<'static>; 3]) -> Self {
Self {
key,
cells,
parent: None,
}
}
fn with_parent(self, parent: u32) -> Self {
Self {
parent: Some(parent),
..self
}
}
}
impl GridRow for Row {
type Key = u32;
type Column = Column;
fn key(&self) -> &u32 {
&self.key
}
fn value(&self, column: Column) -> CellValue<'_> {
self.cells[column.ix().get()]
}
fn parent_key(&self) -> Option<&u32> {
self.parent.as_ref()
}
}
const COLUMNS: [ExportColumn<'static, Column>; 3] = [
ExportColumn::new(Column::Symbol, "Symbol"),
ExportColumn::new(Column::Price, "Price"),
ExportColumn::new(Column::Note, "Note \"short\""),
];
fn columns(columns: &[Column]) -> ColumnSet {
let mut set = ColumnSet::EMPTY;
for column in columns {
set.insert(column.ix());
}
set
}
fn cell_text(cells: &CellExport<Row>, value: CellValue<'static>) -> String {
let row = Row::new(0, [value, CellValue::Empty, CellValue::Empty]);
let cell = ExportRow::new(&row).cell(Column::Symbol).unwrap();
let mut out = String::new();
cells.write_cell(&cell, &mut out);
out
}
fn tsv(table: &ExportTable<'_, Row>, cells: &CellExport<Row>) -> String {
let mut out = String::new();
Exporter::export(&TsvExporter, table, cells, &mut out);
out
}
#[test]
fn test_tsv_quoting_and_raw_cells() {
let raw = CellExport::Raw(RawCells::new().with_precision(NumberPrecision::Full));
let cases = [
(CellValue::Int(-1234), "-1234"),
(CellValue::Int(i64::MIN), "-9223372036854775808"),
(CellValue::Float(1234.5), "1234.5"),
(CellValue::Float(0.1), "0.1"),
(CellValue::Float(0.1 + 0.2), "0.30000000000000004"),
(CellValue::Float(-0.5), "-0.5"),
(CellValue::Float(2.0), "2"),
(CellValue::Float(1e21), "1000000000000000000000"),
(CellValue::Float(1e-7), "0.0000001"),
(CellValue::Float(f64::NAN), ""),
(CellValue::Float(f64::INFINITY), ""),
(CellValue::Float(f64::NEG_INFINITY), ""),
(CellValue::Bool(true), "TRUE"),
(CellValue::Bool(false), "FALSE"),
(CellValue::Empty, ""),
(CellValue::Text("Сбербанк"), "Сбербанк"),
];
for (value, expected) in cases {
assert_eq!(cell_text(&raw, value), expected, "{value:?}");
}
let shown = CellExport::default();
for (value, expected) in [
(CellValue::Float(-0.489_999_999_999_994_9), "-0.49"),
(CellValue::Float(1234.5), "1234.50"),
(CellValue::Float(0.1 + 0.2), "0.30"),
(CellValue::Float(2.0), "2.00"),
(CellValue::Float(1e21), "1000000000000000000000.00"),
(CellValue::Float(f64::NAN), ""),
(CellValue::Int(-1234), "-1234"),
] {
assert_eq!(cell_text(&shown, value), expected, "{value:?}");
}
let row = Row::new(0, [CellValue::Float(-0.489_999_999_999_994_9); 3]);
let formats = [
NumberFormat::new().with_decimals(1),
NumberFormat::new().with_decimals(4),
];
let exported = ExportRow::new(&row).with_number_formats(&formats);
let written = |cells: &CellExport<Row>, column| {
let mut out = String::new();
cells.write_cell(&exported.cell(column).unwrap(), &mut out);
out
};
assert_eq!(written(&shown, Column::Symbol), "-0.5");
assert_eq!(written(&shown, Column::Price), "-0.4900");
assert_eq!(written(&shown, Column::Note), "-0.49");
assert_eq!(
written(&CellExport::Displayed(DisplayedCells), Column::Symbol),
"-0.5"
);
assert_eq!(written(&raw, Column::Symbol), "-0.4899999999999949");
assert_eq!(
exported.cell(Column::Price).unwrap().number_hint(),
Some(NumberHint { fraction_digits: 4 })
);
let comma = RawCells::new().with_decimal_separator(',');
assert_eq!(comma.decimal_separator(), ',');
let comma = CellExport::Raw(comma);
assert_eq!(cell_text(&comma, CellValue::Float(-1234.5)), "-1234,50");
assert_eq!(
cell_text(&comma, CellValue::Float(1e21)),
"1000000000000000000000,00"
);
assert_eq!(cell_text(&comma, CellValue::Int(-1234)), "-1234");
assert_eq!(cell_text(&comma, CellValue::Text("1.5")), "1.5");
let arabic = CellExport::Raw(RawCells::new().with_decimal_separator('٫'));
assert_eq!(cell_text(&arabic, CellValue::Float(0.25)), "0٫25");
assert_eq!(cell_text(&arabic, CellValue::Float(0.5)), "0٫50");
let rows = [
Row::new(
1,
[
CellValue::Text("AAPL"),
CellValue::Float(187.25),
CellValue::Text("tab\there"),
],
),
Row::new(
2,
[
CellValue::Text("say \"hi\""),
CellValue::Int(-3),
CellValue::Text("two\nlines\r"),
],
),
Row::new(
3,
[CellValue::Empty, CellValue::Bool(true), CellValue::Empty],
),
];
let all: Vec<_> = rows.iter().map(ExportRow::new).collect();
let table = ExportTable::new(&COLUMNS, &all).with_header(true);
assert!(table.has_header());
assert_eq!(
tsv(&table, &raw),
"Symbol\tPrice\t\"Note \"\"short\"\"\"\n\
AAPL\t187.25\t\"tab\there\"\n\
\"say \"\"hi\"\"\"\t-3\t\"two\nlines\r\"\n\
\tTRUE\t"
);
let rectangle = [
ExportRow::new(&rows[0]).with_columns(columns(&[Column::Symbol])),
ExportRow::new(&rows[1]).with_columns(columns(&[Column::Note])),
];
assert_eq!(rectangle[1].columns(), columns(&[Column::Note]));
assert!(rectangle[1].cell(Column::Symbol).is_none());
let table = ExportTable::new(&COLUMNS, &rectangle);
assert!(!table.has_header());
assert_eq!(tsv(&table, &raw), "AAPL\t\t\n\t\t\"two\nlines\r\"");
let reordered = [
ExportColumn::new(Column::Price, "Price"),
ExportColumn::new(Column::Symbol, "Symbol"),
];
let table = ExportTable::new(&reordered, &all[..1]);
assert_eq!(tsv(&table, &comma), "187,25\tAAPL");
assert_eq!(tsv(&ExportTable::new(&COLUMNS[..2], &[]), &raw), "");
let header_only = ExportTable::new(&COLUMNS[..2], &[]).with_header(true);
assert_eq!(tsv(&header_only, &raw), "Symbol\tPrice");
let mut out = String::from("x");
Exporter::export(
&TsvExporter,
&ExportTable::new(&COLUMNS[..1], &all[..1]),
&raw,
&mut out,
);
assert_eq!(out, "xAAPL");
}
#[test]
fn test_raw_cells_new_values() {
use chrono::{TimeZone as _, Utc};
use crate::model::{GridValue, IconValue, ImageValue};
#[derive(Debug)]
struct Tenor(i64);
impl GridValue for Tenor {
fn cmp_value(&self, other: &dyn GridValue) -> std::cmp::Ordering {
other
.downcast_ref::<Tenor>()
.map_or(std::cmp::Ordering::Less, |other| self.0.cmp(&other.0))
}
fn write_text(&self, out: &mut String) {
let _ = write!(out, "{}M", self.0 / 30);
}
fn export_value(&self) -> Option<CellValue<'_>> {
Some(CellValue::Float(self.0 as f64 / 360.0))
}
}
#[derive(Debug)]
struct Severity;
impl GridValue for Severity {
fn cmp_value(&self, _: &dyn GridValue) -> std::cmp::Ordering {
std::cmp::Ordering::Equal
}
fn write_text(&self, out: &mut String) {
out.push_str("Critical");
}
}
#[derive(Debug)]
struct Alias;
impl GridValue for Alias {
fn cmp_value(&self, _: &dyn GridValue) -> std::cmp::Ordering {
std::cmp::Ordering::Equal
}
fn write_text(&self, out: &mut String) {
out.push_str("alias");
}
fn export_value(&self) -> Option<CellValue<'_>> {
Some(CellValue::Custom(&Severity))
}
}
static TENOR: Tenor = Tenor(90);
let placed = Utc.with_ymd_and_hms(2026, 11, 4, 12, 34, 56).unwrap();
let raw = CellExport::default();
let comma = CellExport::Raw(RawCells::new().with_decimal_separator(','));
let displayed = CellExport::Displayed(DisplayedCells);
let mut buffer = String::new();
for (value, expected, with_comma) in [
(
CellValue::Timestamp(placed),
"2026-11-04 12:34:56",
"2026-11-04 12:34:56",
),
(
CellValue::Icon(IconValue::new("icons/check.svg", "Filled")),
"Filled",
"Filled",
),
(
CellValue::Image(ImageValue::new("images/ada.png", "Ada")),
"Ada",
"Ada",
),
(CellValue::Custom(&Severity), "Critical", "Critical"),
(CellValue::Custom(&TENOR), "0.25", "0,25"),
(CellValue::Custom(&Alias), "Critical", "Critical"),
] {
assert_eq!(cell_text(&raw, value), expected, "{value:?}");
assert_eq!(cell_text(&comma, value), with_comma, "{value:?}");
assert_eq!(
cell_text(&displayed, value),
display_text(value, &mut buffer),
"{value:?}"
);
}
assert_eq!(cell_text(&displayed, CellValue::Custom(&TENOR)), "3M");
let rows = [Row::new(
1,
[
CellValue::Icon(IconValue::new("icons/check.svg", "Filled")),
CellValue::Custom(&TENOR),
CellValue::Custom(&Severity),
],
)];
let all: Vec<_> = rows.iter().map(ExportRow::new).collect();
assert_eq!(
tsv(&ExportTable::new(&COLUMNS, &all), &raw),
"Filled\t0.25\tCritical"
);
assert_eq!(
tsv(&ExportTable::new(&COLUMNS, &all), &displayed),
"Filled\t3M\tCritical"
);
}
#[test]
fn test_cell_export_variants() {
fn assert_send_sync<T: Send + Sync + 'static>() {}
assert_send_sync::<CellExport<Row>>();
assert_send_sync::<TsvExporter>();
assert_send_sync::<Box<dyn Exporter<Row>>>();
assert_send_sync::<Box<dyn ExportFormat<Row>>>();
assert_send_sync::<CsvFormat>();
assert_send_sync::<TextFile<TsvExporter>>();
assert_send_sync::<LineFilter<CsvFormat>>();
assert_send_sync::<ExportControl>();
assert_send_sync::<ExportError>();
assert!(matches!(
CellExport::<Row>::default(),
CellExport::Raw(raw) if raw == RawCells::new() && raw.decimal_separator() == '.'
));
assert_eq!(RawCells::default(), RawCells::new());
let displayed = CellExport::Displayed(DisplayedCells);
let mut buffer = String::new();
for value in [
CellValue::Empty,
CellValue::Bool(true),
CellValue::Bool(false),
CellValue::Int(-42),
CellValue::Float(1234.567),
CellValue::Float(0.1),
CellValue::Float(f64::NAN),
CellValue::Text("tab\there"),
] {
assert_eq!(
cell_text(&displayed, value),
display_text(value, &mut buffer),
"{value:?}"
);
}
#[derive(Default)]
struct KeyAndColumn {
calls: AtomicUsize,
}
impl CellExporter<Row> for KeyAndColumn {
fn write_cell(&self, cell: &ExportCell<'_, Row>, out: &mut String) {
self.calls.fetch_add(1, Ordering::Relaxed);
let key = cell.row().expect("a data row").key();
let _ = write!(out, "{key}:{}", cell.column().id());
if cell.value() == CellValue::Empty {
out.push('\t');
}
}
}
let custom = Arc::new(KeyAndColumn::default());
let cells = CellExport::Custom(custom.clone());
let rows = [
Row::new(7, [CellValue::Int(1), CellValue::Empty, CellValue::Int(3)]),
Row::new(9, [CellValue::Int(4); 3]),
];
let exported = [
ExportRow::new(&rows[0]),
ExportRow::new(&rows[1]).with_columns(columns(&[Column::Price])),
];
let table = ExportTable::new(&COLUMNS, &exported).with_header(true);
assert_eq!(
tsv(&table, &cells.clone()),
"Symbol\tPrice\t\"Note \"\"short\"\"\"\n\
7:symbol\t\"7:price\t\"\t7:note\n\
\t9:price\t"
);
assert_eq!(custom.calls.load(Ordering::Relaxed), 4);
}
fn snapshot_of(
rows: impl IntoIterator<Item = [CellValue<'static>; 3]>,
) -> Arc<StoreSnapshot<Row>> {
snapshot_of_rows(
rows.into_iter()
.zip(0..)
.map(|(cells, key)| Row::new(key, cells)),
)
}
fn snapshot_of_rows(rows: impl IntoIterator<Item = Row>) -> Arc<StoreSnapshot<Row>> {
let epoch = Instant::now();
let mut ingest = Ingest::new(HighlightPolicy::default(), epoch);
ingest.apply(
rows.into_iter().map(|row| Op::UpsertSilent(Arc::new(row))),
epoch,
);
ingest.snapshot()
}
fn trades() -> Arc<StoreSnapshot<Row>> {
const TRADES: [(&str, f64, &str); 12] = [
("AAPL", 1000.25, "buy"),
("MSFT", 10.0, "x"),
("SBER", 1.5, "y"),
("AAPL", 234.25, ""),
("MSFT", 20.0, "x"),
("SBER", 1.5, ""),
("MSFT", 30.0, "x"),
("SBER", 1.5, "y"),
("MSFT", 40.0, ""),
("SBER", 1.5, "y"),
("MSFT", 50.0, "x"),
("SBER", 1.5, "y"),
];
snapshot_of(TRADES.map(|(symbol, price, note)| {
[
CellValue::Text(symbol),
CellValue::Float(price),
if note.is_empty() {
CellValue::Empty
} else {
CellValue::Text(note)
},
]
}))
}
fn grouped(
snapshot: &StoreSnapshot<Row>,
levels: &[Column],
aggregates: impl IntoIterator<Item = (Column, Aggregate<Row>)>,
) -> Projection {
let spec = ViewSpec::new()
.with_group_by(levels.iter().map(|&level| GroupBy::column(level)))
.with_aggregates(aggregates)
.with_group_footer(EveryGroupFooter);
Rebuild::default()
.with_max_threads(1)
.rebuild(snapshot, &spec)
}
fn group<'a>(projection: &'a Projection, value: &str) -> GroupInfo<'a> {
projection
.groups()
.iter()
.find(|group| group.depth() == 0 && group.value() == &OwnedValue::Text(value.into()))
.expect("the group")
}
fn aapl_lines<'a>(
snapshot: &'a StoreSnapshot<Row>,
projection: &'a Projection,
) -> Vec<ExportRow<'a, Row>> {
let aapl = group(projection, "AAPL");
let mut rows = vec![ExportRow::caption(Column::Symbol, aapl)];
rows.extend(
aapl.rows()
.iter()
.map(|&id| ExportRow::new(&**snapshot.row(id).unwrap()).with_depth(1)),
);
rows.push(ExportRow::footer(aapl));
rows.push(ExportRow::totals(
projection.totals(),
Some((Column::Symbol, "Total")),
));
rows
}
const SUMMARY_COLUMNS: [ExportColumn<'static, Column>; 3] = [
ExportColumn::new(Column::Symbol, "Symbol"),
ExportColumn::new(Column::Price, "Price"),
ExportColumn::new(Column::Note, "Note"),
];
fn cells_of<'a>(row: &ExportRow<'a, Row>) -> Vec<Option<(CellValue<'a>, bool)>> {
Column::all()
.iter()
.map(|&column| {
row.cell(column)
.map(|cell| (cell.value(), cell.is_aggregate()))
})
.collect()
}
#[test]
fn test_export_summary_cells() {
use CellValue::{Empty, Float, Int, Text};
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[
(Column::Symbol, Aggregate::Count),
(Column::Price, Aggregate::Sum),
(Column::Note, Aggregate::Sum),
],
);
let aapl = group(&projection, "AAPL");
let caption = ExportRow::caption(Column::Symbol, aapl);
assert_eq!(caption.line(), ExportLine::Caption);
assert!(caption.row().is_none());
assert_eq!(caption.group().map(|group| group.id()), Some(aapl.id()));
assert_eq!(caption.depth(), 0);
assert_eq!(
cells_of(&caption),
[
Some((Text("AAPL"), false)),
Some((Float(1234.5), true)),
Some((Empty, true)),
]
);
assert_eq!(
cells_of(&ExportRow::caption(Column::Price, aapl)),
[
Some((Int(2), true)),
Some((Text("AAPL"), false)),
Some((Empty, true)),
]
);
assert_eq!(
cells_of(&caption.with_columns(columns(&[Column::Price]))),
[None, Some((Float(1234.5), true)), None]
);
let footer = ExportRow::footer(aapl);
assert_eq!(footer.line(), ExportLine::Footer);
assert!(footer.row().is_none());
assert_eq!(footer.group().map(|group| group.id()), Some(aapl.id()));
assert_eq!(footer.depth(), 0);
assert_eq!(
cells_of(&footer),
[
Some((Int(2), true)),
Some((Float(1234.5), true)),
Some((Empty, true)),
]
);
let totals = ExportRow::totals(projection.totals(), Some((Column::Symbol, "Total")));
assert_eq!(totals.line(), ExportLine::Totals);
assert!(totals.row().is_none() && totals.group().is_none());
assert_eq!(
cells_of(&totals),
[
Some((Int(12), true)),
Some((Float(1392.0), true)),
Some((Empty, true)),
]
);
let summed = grouped(
&snapshot,
&[Column::Symbol],
[(Column::Price, Aggregate::Sum)],
);
let aapl = group(&summed, "AAPL");
assert_eq!(
cells_of(&ExportRow::caption(Column::Symbol, aapl)),
[
Some((Text("AAPL"), false)),
Some((Float(1234.5), true)),
None,
]
);
assert_eq!(
cells_of(&ExportRow::footer(aapl)),
[None, Some((Float(1234.5), true)), None]
);
for (label, expected) in [
(
Some((Column::Symbol, "Total")),
Some((Text("Total"), false)),
),
(Some((Column::Price, "Total")), None),
(None, None),
] {
assert_eq!(
cells_of(&ExportRow::totals(summed.totals(), label)),
[expected, Some((Float(1392.0), true)), None],
"{label:?}"
);
}
let trade = &**snapshot.row(aapl.rows()[0]).unwrap();
let data = ExportRow::new(trade);
assert_eq!(data.line(), ExportLine::Data);
assert!(data.row().is_some_and(|row| std::ptr::eq(row, trade)));
assert!(data.group().is_none());
assert_eq!(data.depth(), 0);
assert_eq!(data.with_depth(1).depth(), 1);
assert_eq!(
cells_of(&data),
[
Some((Text("AAPL"), false)),
Some((Float(1000.25), false)),
Some((Text("buy"), false)),
]
);
let nested = grouped(&snapshot, &[Column::Symbol, Column::Note], []);
let subgroup = nested
.groups()
.iter()
.find(|group| group.depth() == 1)
.expect("a subgroup");
let caption = ExportRow::<Row>::caption(Column::Note, subgroup);
assert_eq!(caption.depth(), 1);
assert_eq!(caption.cell(Column::Note).map(|cell| cell.depth()), Some(1));
assert_eq!(ExportRow::<Row>::footer(subgroup).depth(), 1);
assert_eq!(caption.with_depth(3).depth(), 3);
}
#[test]
fn test_tsv_with_summaries() {
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[
(Column::Price, Aggregate::Sum),
(Column::Note, Aggregate::Count),
],
);
let rows = aapl_lines(&snapshot, &projection);
let table = ExportTable::new(&SUMMARY_COLUMNS, &rows).with_header(true);
let raw = CellExport::default();
assert_eq!(
tsv(&table, &raw),
"Symbol\tPrice\tNote\n\
AAPL\t1234.50\t1\n\
AAPL\t1000.25\tbuy\n\
AAPL\t234.25\t\n\
\t1234.50\t1\n\
Total\t1392.00\t9"
);
assert_eq!(
tsv(&table, &CellExport::Displayed(DisplayedCells)),
"Symbol\tPrice\tNote\n\
AAPL\t1234.50\t1\n\
AAPL\t1000.25\tbuy\n\
AAPL\t234.25\t\n\
\t1234.50\t1\n\
Total\t1392.00\t9"
);
let comma = CellExport::Raw(RawCells::new().with_decimal_separator(','));
assert!(tsv(&table, &comma).ends_with("\n\t1234,50\t1\nTotal\t1392,00\t9"));
assert!(
tsv(&ExportTable::new(&SUMMARY_COLUMNS, &rows), &raw)
.starts_with("AAPL\t1234.50\t1\nAAPL\t1000.25\tbuy\n")
);
let snapshot = snapshot_of([
[
CellValue::Text("a\tb"),
CellValue::Int(1),
CellValue::Bool(true),
],
[
CellValue::Text("a\tb"),
CellValue::Int(2),
CellValue::Bool(false),
],
]);
let by_flag = grouped(&snapshot, &[Column::Note, Column::Symbol], []);
let captions: Vec<_> = by_flag
.groups()
.iter()
.map(|group| {
let value_column = if group.depth() == 0 {
Column::Note
} else {
Column::Symbol
};
ExportRow::caption(value_column, group)
})
.collect();
let table = ExportTable::new(&SUMMARY_COLUMNS, &captions);
assert_eq!(
tsv(&table, &raw),
"\t\tFALSE\n\"a\tb\"\t\t\n\t\tTRUE\n\"a\tb\"\t\t"
);
assert_eq!(
tsv(&table, &CellExport::Displayed(DisplayedCells)),
"\t\t\n\"a\tb\"\t\t\n\t\t✓\n\"a\tb\"\t\t"
);
}
#[test]
fn test_line_filter() {
assert_eq!(ExportLines::default(), ExportLines::ALL);
for line in ExportLine::ALL {
assert!(ExportLines::ALL.contains(line));
assert!(!ExportLines::EMPTY.contains(line));
assert_eq!(ExportLines::ALL.without(line).with(line), ExportLines::ALL);
assert!(!ExportLines::ALL.without(line).contains(line));
}
assert_eq!(
format!(
"{:?}",
ExportLines::EMPTY
.with(ExportLine::Totals)
.with(ExportLine::Data)
),
"{Data, Totals}"
);
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[
(Column::Price, Aggregate::Sum),
(Column::Note, Aggregate::Count),
],
);
let rows = aapl_lines(&snapshot, &projection);
let table = ExportTable::new(&SUMMARY_COLUMNS, &rows).with_header(true);
let raw = CellExport::default();
let filtered = |lines: ExportLines| {
let filter = LineFilter::new(TsvExporter, lines);
assert_eq!(filter.lines(), lines);
let mut out = String::new();
Exporter::export(&filter, &table, &raw, &mut out);
out
};
assert_eq!(filtered(ExportLines::ALL), tsv(&table, &raw));
assert_eq!(
filtered(
ExportLines::ALL
.without(ExportLine::Footer)
.without(ExportLine::Totals)
),
"Symbol\tPrice\tNote\nAAPL\t1234.50\t1\nAAPL\t1000.25\tbuy\nAAPL\t234.25\t"
);
assert_eq!(
filtered(ExportLines::EMPTY.with(ExportLine::Data)),
"Symbol\tPrice\tNote\nAAPL\t1000.25\tbuy\nAAPL\t234.25\t"
);
assert_eq!(
filtered(ExportLines::ALL.without(ExportLine::Data)),
"Symbol\tPrice\tNote\nAAPL\t1234.50\t1\n\t1234.50\t1\nTotal\t1392.00\t9"
);
assert_eq!(filtered(ExportLines::EMPTY), "Symbol\tPrice\tNote");
struct Shape;
impl Exporter<Row> for Shape {
fn export(&self, table: &ExportTable<'_, Row>, _: &CellExport<Row>, out: &mut String) {
let lines: Vec<_> = table.rows().iter().map(ExportRow::line).collect();
let _ = write!(
out,
"{} {} {lines:?}",
table.columns().len(),
table.has_header()
);
}
}
let filter = LineFilter::new(Shape, ExportLines::EMPTY.with(ExportLine::Caption));
let mut out = String::new();
Exporter::export(&filter, &table, &raw, &mut out);
assert_eq!(out, "3 true [Caption]");
let _: &Shape = filter.exporter();
}
#[test]
fn test_export_cell_row_is_optional() {
#[derive(Default)]
struct Seen(Mutex<Vec<(Option<u32>, ExportLine, u16, bool, Option<GroupId>)>>);
impl CellExporter<Row> for Seen {
fn write_cell(&self, cell: &ExportCell<'_, Row>, out: &mut String) {
self.0.lock().unwrap().push((
cell.row().map(|row| row.key),
cell.line(),
cell.depth(),
cell.is_aggregate(),
cell.group().map(|group| group.id()),
));
RawCells::new().write_cell(cell, out);
if cell.line() == ExportLine::Caption
&& !cell.is_aggregate()
&& let Some(group) = cell.group()
{
let _ = write!(out, " ({})", group.row_count());
}
}
}
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[(Column::Price, Aggregate::Sum)],
);
let rows = aapl_lines(&snapshot, &projection);
let aapl = group(&projection, "AAPL").id();
let seen = Arc::new(Seen::default());
let table = ExportTable::new(&SUMMARY_COLUMNS, &rows);
assert_eq!(
tsv(&table, &CellExport::Custom(seen.clone())),
"AAPL (2)\t1234.50\t\n\
AAPL\t1000.25\tbuy\n\
AAPL\t234.25\t\n\
\t1234.50\t\n\
Total\t1392.00\t"
);
use ExportLine::{Caption, Data, Footer, Totals};
assert_eq!(
*seen.0.lock().unwrap(),
[
(None, Caption, 0, false, Some(aapl)),
(None, Caption, 0, true, Some(aapl)),
(Some(0), Data, 1, false, None),
(Some(0), Data, 1, false, None),
(Some(0), Data, 1, false, None),
(Some(3), Data, 1, false, None),
(Some(3), Data, 1, false, None),
(Some(3), Data, 1, false, None),
(None, Footer, 0, true, Some(aapl)),
(None, Totals, 0, false, None),
(None, Totals, 0, true, None),
]
);
}
#[test]
fn test_export_scope_variants() {
fn scope_name(scope: ExportScope) -> &'static str {
match scope {
ExportScope::Visible => "Visible",
ExportScope::Selection => "Selection",
ExportScope::Expanded => "Expanded",
}
}
fn line_ix(line: ExportLine) -> usize {
match line {
ExportLine::Data => 0,
ExportLine::Caption => 1,
ExportLine::Footer => 2,
ExportLine::Totals => 3,
}
}
let scopes = [
ExportScope::Visible,
ExportScope::Selection,
ExportScope::Expanded,
];
for (ix, scope) in scopes.into_iter().enumerate() {
assert_eq!(format!("{scope:?}"), scope_name(scope));
for (other_ix, other) in scopes.into_iter().enumerate() {
assert_eq!(scope == other, ix == other_ix, "{scope:?} {other:?}");
}
}
for (ix, line) in ExportLine::ALL.into_iter().enumerate() {
assert_eq!(line_ix(line), ix);
}
}
#[cfg(feature = "decimal")]
#[test]
fn test_decimal_group_value() {
let price = rust_decimal::Decimal::new(1230, 2);
let snapshot = snapshot_of([[
CellValue::Text("AAPL"),
CellValue::Decimal(price),
CellValue::Empty,
]]);
let projection = grouped(
&snapshot,
&[Column::Price],
[(Column::Symbol, Aggregate::Count)],
);
let caption = [ExportRow::caption(
Column::Price,
projection.groups().iter().next().expect("a group"),
)];
let table = ExportTable::new(&SUMMARY_COLUMNS, &caption);
assert_eq!(tsv(&table, &CellExport::default()), "1\t12.30\t");
let comma = CellExport::Raw(RawCells::new().with_decimal_separator(','));
assert_eq!(tsv(&table, &comma), "1\t12,30\t");
assert_eq!(
tsv(&table, &CellExport::Displayed(DisplayedCells)),
"1\t12.30\t"
);
}
fn file(
format: &dyn ExportFormat<Row>,
table: &ExportTable<'_, Row>,
cells: &CellExport<Row>,
) -> Vec<u8> {
let control = ExportControl::new(table.rows().len());
let mut out = Vec::new();
format
.export(table, cells, &mut out, &control)
.expect("the export");
assert_eq!(control.rows_written(), control.rows_total());
out
}
fn file_text(
format: &dyn ExportFormat<Row>,
table: &ExportTable<'_, Row>,
cells: &CellExport<Row>,
) -> String {
String::from_utf8(file(format, table, cells)).expect("UTF-8")
}
#[test]
fn test_csv_rfc4180() {
use CellValue::{Bool, Empty, Float, Int, Text};
let rows = [
Row::new(1, [Text("a,b"), Float(1234.5), Text("say \"hi\"")]),
Row::new(2, [Text("two\nlines"), Bool(true), Text("cr\rhere")]),
Row::new(3, [Text(" padded "), Empty, Text("semi;colon")]),
Row::new(4, [Text("plain"), Int(-3), Bool(false)]),
];
let all: Vec<_> = rows.iter().map(ExportRow::new).collect();
let table = ExportTable::new(&COLUMNS, &all).with_header(true);
let raw = CellExport::default();
let format = CsvFormat::new();
assert_eq!(format, CsvFormat::default());
assert_eq!(format.separator(), ',');
assert_eq!(format.encoding(), CsvEncoding::Utf8WithBom);
assert_eq!(CsvEncoding::default(), CsvEncoding::Utf8WithBom);
assert_eq!(ExportFormat::<Row>::extension(&format), "csv");
let expected = "Symbol,Price,\"Note \"\"short\"\"\"\r\n\
\"a,b\",1234.50,\"say \"\"hi\"\"\"\r\n\
\"two\nlines\",TRUE,\"cr\rhere\"\r\n\
\x20padded ,,semi;colon\r\n\
plain,-3,FALSE\r\n";
let with_mark = file(&format, &table, &raw);
assert_eq!(with_mark[..3], [0xEF, 0xBB, 0xBF]);
assert_eq!(with_mark[3..], *expected.as_bytes());
let utf8 = format.with_encoding(CsvEncoding::Utf8);
assert_eq!(utf8.encoding(), CsvEncoding::Utf8);
assert_eq!(file_text(&utf8, &table, &raw), expected);
let semicolon = utf8.with_separator(';');
assert_eq!(semicolon.separator(), ';');
let comma = CellExport::Raw(RawCells::new().with_decimal_separator(','));
assert_eq!(
file_text(&semicolon, &table, &comma),
"Symbol;Price;\"Note \"\"short\"\"\"\r\n\
a,b;1234,50;\"say \"\"hi\"\"\"\r\n\
\"two\nlines\";TRUE;\"cr\rhere\"\r\n\
\x20padded ;;\"semi;colon\"\r\n\
plain;-3;FALSE\r\n"
);
let narrowed = [
ExportRow::new(&rows[0]).with_columns(columns(&[Column::Price])),
ExportRow::new(&rows[3]),
];
assert_eq!(
file_text(
&utf8,
&ExportTable::new(&COLUMNS, &narrowed),
&CellExport::Displayed(DisplayedCells)
),
",1234.50,\r\nplain,-3,\r\n"
);
let header_only = ExportTable::new(&COLUMNS[..2], &[]).with_header(true);
assert_eq!(file_text(&utf8, &header_only, &raw), "Symbol,Price\r\n");
assert_eq!(
file(&format, &ExportTable::new(&COLUMNS, &[]), &raw),
[0xEF, 0xBB, 0xBF]
);
let mut field = String::from("x¦a¦b");
quote_field(&mut field, 3, '¦', &mut String::new());
assert_eq!(field, "x¦\"a¦b\"");
let mut field = String::from("a|b");
quote_field(&mut field, 0, '¦', &mut String::new());
assert_eq!(field, "a|b");
}
#[test]
#[should_panic(expected = "a CSV separator cannot be a quote or a line break")]
fn test_csv_separator_is_not_a_quote() {
let _ = CsvFormat::new().with_separator('"');
}
#[test]
fn test_tsv_file_matches_clipboard() {
use CellValue::{Bool, Empty, Float, Int, Text};
let rows = [
Row::new(1, [Text("AAPL"), Float(187.25), Text("tab\there")]),
Row::new(2, [Text("say \"hi\""), Int(-3), Text("two\nlines\r")]),
Row::new(3, [Empty, Bool(true), Empty]),
];
let all: Vec<_> = rows.iter().map(ExportRow::new).collect();
let rectangle = [
ExportRow::new(&rows[0]).with_columns(columns(&[Column::Symbol])),
ExportRow::new(&rows[1]).with_columns(columns(&[Column::Note])),
];
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[
(Column::Price, Aggregate::Sum),
(Column::Note, Aggregate::Count),
],
);
let summaries = aapl_lines(&snapshot, &projection);
let tables = [
ExportTable::new(&COLUMNS, &all).with_header(true),
ExportTable::new(&COLUMNS, &all),
ExportTable::new(&COLUMNS, &rectangle),
ExportTable::new(&SUMMARY_COLUMNS, &summaries).with_header(true),
ExportTable::new(&SUMMARY_COLUMNS, &summaries),
ExportTable::new(&COLUMNS[..2], &[]).with_header(true),
ExportTable::new(&COLUMNS, &[]),
];
assert_eq!(ExportFormat::<Row>::extension(&TsvExporter), "tsv");
for cells in [
CellExport::default(),
CellExport::Displayed(DisplayedCells),
CellExport::Raw(RawCells::new().with_decimal_separator(',')),
] {
for table in &tables {
assert_eq!(
file(&TsvExporter, table, &cells),
tsv(table, &cells).as_bytes()
);
}
}
assert!(file(&TsvExporter, &tables[5], &CellExport::default()) == b"Symbol\tPrice");
}
struct ProgressSink {
control: ExportControl,
bytes: Vec<u8>,
writes: Vec<usize>,
}
impl ProgressSink {
fn new(control: &ExportControl) -> Self {
Self {
control: control.clone(),
bytes: Vec::new(),
writes: Vec::new(),
}
}
}
impl io::Write for ProgressSink {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.writes.push(self.control.rows_written());
self.bytes.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn test_formats_report_progress_and_stop() {
let control = ExportControl::new(10);
assert_eq!((control.rows_total(), control.rows_written()), (10, 0));
assert!(control.advance(4).is_ok());
let shared = control.clone();
assert_eq!(shared.rows_written(), 4);
assert!(!control.is_cancelled());
shared.cancel();
assert!(control.is_cancelled());
assert!(matches!(control.advance(0), Err(ExportError::Cancelled)));
let rows: Vec<Row> = (0..3000)
.map(|key| {
Row::new(
key,
[
CellValue::Int(key.into()),
CellValue::Float(f64::from(key) / 4.0),
CellValue::Text("x"),
],
)
})
.collect();
let lines: Vec<_> = rows.iter().map(ExportRow::new).collect();
let table = ExportTable::new(&COLUMNS, &lines).with_header(true);
let raw = CellExport::default();
let csv = CsvFormat::new();
let formats: [(&dyn ExportFormat<Row>, &str, usize); 2] =
[(&csv, "\r\n", 1025), (&TsvExporter, "\n", 1024)];
for (format, line_break, first_buffer_breaks) in formats {
let name = format.extension();
let control = ExportControl::new(table.rows().len());
let mut sink = ProgressSink::new(&control);
format
.export(&table, &raw, &mut sink, &control)
.expect("the export");
assert_eq!(sink.writes, [0, 1024, 2048], "{name}");
assert_eq!(control.rows_written(), control.rows_total(), "{name}");
let whole = sink.bytes;
assert_eq!(whole, file(format, &table, &raw), "{name}");
let control = ExportControl::new(table.rows().len());
control.cancel();
let mut sink = ProgressSink::new(&control);
assert!(
matches!(
format.export(&table, &raw, &mut sink, &control),
Err(ExportError::Cancelled)
),
"{name}"
);
assert_eq!(sink.writes, [0], "{name}");
assert!(whole.starts_with(&sink.bytes), "{name}");
let text = String::from_utf8(sink.bytes).expect("UTF-8");
assert_eq!(
text.matches(line_break).count(),
first_buffer_breaks,
"{name}"
);
}
let text_file = TextFile::new(TsvExporter, "tsv");
let control = ExportControl::new(table.rows().len());
let mut sink = ProgressSink::new(&control);
text_file
.export(&table, &raw, &mut sink, &control)
.expect("the export");
assert_eq!(sink.writes, [0]);
assert_eq!(control.rows_written(), 3000);
let control = ExportControl::new(table.rows().len());
control.cancel();
let mut sink = ProgressSink::new(&control);
assert!(matches!(
text_file.export(&table, &raw, &mut sink, &control),
Err(ExportError::Cancelled)
));
assert!(sink.bytes.is_empty());
struct Full;
impl io::Write for Full {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::StorageFull, "disk full"))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let control = ExportControl::new(table.rows().len());
let error = CsvFormat::new()
.export(&table, &raw, &mut Full, &control)
.expect_err("a full disk");
assert!(
matches!(&error, ExportError::Io(error) if error.kind() == io::ErrorKind::StorageFull)
);
assert_eq!(control.rows_written(), 0);
}
#[test]
fn test_text_file_and_line_filter() {
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[
(Column::Price, Aggregate::Sum),
(Column::Note, Aggregate::Count),
],
);
let rows = aapl_lines(&snapshot, &projection);
let table = ExportTable::new(&SUMMARY_COLUMNS, &rows).with_header(true);
let raw = CellExport::default();
let text_file = TextFile::new(TsvExporter, "tsv");
let _: &TsvExporter = text_file.exporter();
assert_eq!(ExportFormat::<Row>::extension(&text_file), "tsv");
assert_eq!(file(&text_file, &table, &raw), tsv(&table, &raw).as_bytes());
let data_only = TextFile::new(
LineFilter::new(TsvExporter, ExportLines::EMPTY.with(ExportLine::Data)),
String::from("txt"),
);
assert_eq!(ExportFormat::<Row>::extension(&data_only), "txt");
assert_eq!(
file_text(&data_only, &table, &raw),
"Symbol\tPrice\tNote\nAAPL\t1000.25\tbuy\nAAPL\t234.25\t"
);
let utf8 = CsvFormat::new().with_encoding(CsvEncoding::Utf8);
let without_footers = LineFilter::new(utf8, ExportLines::ALL.without(ExportLine::Footer));
assert_eq!(ExportFormat::<Row>::extension(&without_footers), "csv");
assert_eq!(
file_text(&without_footers, &table, &raw),
"Symbol,Price,Note\r\n\
AAPL,1234.50,1\r\n\
AAPL,1000.25,buy\r\n\
AAPL,234.25,\r\n\
Total,1392.00,9\r\n"
);
assert_eq!(
file(&LineFilter::new(utf8, ExportLines::ALL), &table, &raw),
file(&utf8, &table, &raw)
);
assert_eq!(
file_text(&LineFilter::new(utf8, ExportLines::EMPTY), &table, &raw),
"Symbol,Price,Note\r\n"
);
}
#[test]
fn test_export_metadata() {
use crate::engine::TreeSpec;
let price = ExportColumn::new(Column::Price, "Price");
assert_eq!(price.width(), None);
assert_eq!(price.align(), ColumnAlign::Auto);
assert_eq!(price.zone(), ColumnZone::Scrolling);
assert!(price.bands().is_empty());
let bands = ["Market", "Quote"];
let price = price
.with_width(140.0)
.with_align(ColumnAlign::End)
.with_zone(ColumnZone::FrozenLeft)
.with_bands(&bands);
assert_eq!(price.width(), Some(140.0));
assert_eq!(price.align(), ColumnAlign::End);
assert_eq!(price.zone(), ColumnZone::FrozenLeft);
assert_eq!(price.bands(), ["Market", "Quote"]);
assert_eq!((price.column(), price.title()), (Column::Price, "Price"));
assert_ne!(price, ExportColumn::new(Column::Price, "Price"));
let symbol = ExportColumn::new(Column::Symbol, "Symbol").with_zone(ColumnZone::FrozenLeft);
let note = ExportColumn::new(Column::Note, "Note").with_bands(&bands[..1]);
let metadata = [symbol, price, note, symbol];
let table = ExportTable::<Row>::new(&metadata, &[]);
assert_eq!(table.frozen_columns(), 2);
assert_eq!(table.band_depth(), 2);
let right = note.with_zone(ColumnZone::FrozenRight);
for (columns, frozen, depth) in [
(&[note, symbol][..], 0, 1),
(&[symbol, right][..], 1, 1),
(&COLUMNS[..], 0, 0),
(&[][..], 0, 0),
] {
let table = ExportTable::<Row>::new(columns, &[]);
assert_eq!(table.frozen_columns(), frozen, "{columns:?}");
assert_eq!(table.band_depth(), depth, "{columns:?}");
}
let snapshot = snapshot_of_rows([
Row::new(0, [CellValue::Text("Book"); 3]),
Row::new(1, [CellValue::Text("Desk"); 3]).with_parent(0),
Row::new(2, [CellValue::Text("Trader"); 3]).with_parent(1),
Row::new(3, [CellValue::Text("Trader"); 3]).with_parent(1),
]);
let tree = Rebuild::default().with_max_threads(1).rebuild(
&snapshot,
&ViewSpec::new().with_tree(TreeSpec::new().with_column(Column::Symbol)),
);
let row = |key: u32| &**snapshot.get(&key).expect("the row");
let branch = |key: u32| tree.branch(snapshot.row_id(&key).expect("the row"));
let desk = branch(1).expect("a branch");
assert_eq!(desk.child_count(), 2);
assert_eq!(branch(2), None);
let data = ExportRow::new(row(1));
assert_eq!(data.band(), None);
assert!(!data.is_hidden());
assert_eq!(data.branch(), None);
let marked = data
.with_band(PinnedEdge::Top)
.with_hidden(true)
.with_branch(desk);
assert_eq!(marked.band(), Some(PinnedEdge::Top));
assert!(marked.is_hidden());
assert_eq!(marked.branch(), Some(desk));
assert!(!marked.with_hidden(false).is_hidden());
let pending = [(Column::Note, OwnedValue::Int(1))];
let rebuilt = marked
.with_depth(1)
.with_columns(columns(&[Column::Note]))
.with_pending(&pending);
assert_eq!(
(rebuilt.band(), rebuilt.is_hidden(), rebuilt.branch()),
(Some(PinnedEdge::Top), true, Some(desk))
);
assert!(
rebuilt
.cell(Column::Note)
.is_some_and(|cell| cell.is_pending())
);
let trades = trades();
let projection = grouped(
&trades,
&[Column::Symbol],
[(Column::Price, Aggregate::Sum)],
);
let totals = ExportRow::<Row>::totals(projection.totals(), None)
.with_band(PinnedEdge::Bottom)
.with_branch(desk);
assert_eq!(
(totals.band(), totals.branch()),
(Some(PinnedEdge::Bottom), None)
);
let footer = ExportRow::<Row>::footer(group(&projection, "AAPL")).with_hidden(true);
assert!(footer.is_hidden() && footer.band().is_none());
#[cfg(target_pointer_width = "64")]
assert!(
size_of::<ExportRow<'_, Row>>() <= 128,
"{} bytes",
size_of::<ExportRow<'_, Row>>()
);
}
#[test]
fn test_number_hint() {
use CellValue::{Bool, Empty, Float, Int, Text, Timestamp};
let digits = |value: CellValue<'static>| {
let row = Row::new(0, [value, Empty, Empty]);
ExportRow::new(&row)
.cell(Column::Symbol)
.unwrap()
.number_hint()
.map(|hint| hint.fraction_digits())
};
assert_eq!(digits(Float(1.0)), Some(2));
assert_eq!(digits(Float(-0.125)), Some(2));
assert_eq!(digits(Int(5)), Some(0));
for value in [
Text("1.5"),
Bool(true),
Empty,
Timestamp(chrono::DateTime::<chrono::Utc>::UNIX_EPOCH),
] {
assert_eq!(digits(value), None, "{value:?}");
}
#[cfg(feature = "decimal")]
{
use rust_decimal::Decimal;
assert_eq!(digits(CellValue::Decimal(Decimal::new(1230, 2))), Some(2));
assert_eq!(digits(CellValue::Decimal(Decimal::new(5, 0))), Some(0));
}
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[
(Column::Price, Aggregate::Sum),
(Column::Note, Aggregate::Count),
],
);
let aapl = group(&projection, "AAPL");
let hint = |row: ExportRow<'_, Row>, column| row.cell(column).unwrap().number_hint();
let two = hint(ExportRow::footer(aapl), Column::Price).expect("a hint");
assert_eq!(two.fraction_digits(), 2);
assert_eq!(two, two.clone());
assert_eq!(
hint(ExportRow::footer(aapl), Column::Note).map(|hint| hint.fraction_digits()),
Some(0)
);
assert_eq!(
hint(ExportRow::caption(Column::Symbol, aapl), Column::Symbol),
None
);
assert_eq!(
hint(ExportRow::totals(projection.totals(), None), Column::Price),
Some(two)
);
}
#[test]
fn test_pending_values() {
use CellValue::{Float, Int, Text};
let rows = [Row::new(1, [Text("AAPL"), Float(187.25), Text("buy")])];
let pending = [
(Column::Price, OwnedValue::Float(2.5)),
(Column::Note, OwnedValue::Int(7)),
];
let row = ExportRow::new(&rows[0]).with_pending(&pending);
let price = row.cell(Column::Price).unwrap();
assert_eq!(price.value(), Float(2.5));
assert!(price.is_pending());
assert_eq!(price.row_value(), Some(Float(187.25)));
let note = row.cell(Column::Note).unwrap();
assert_eq!(
(note.value(), note.row_value()),
(Int(7), Some(Text("buy")))
);
assert_eq!(
note.number_hint().map(|hint| hint.fraction_digits()),
Some(0)
);
let symbol = row.cell(Column::Symbol).unwrap();
assert!(!symbol.is_pending());
assert_eq!(
(symbol.value(), symbol.row_value()),
(Text("AAPL"), Some(Text("AAPL")))
);
let plain = ExportRow::new(&rows[0]).cell(Column::Price).unwrap();
assert!(!plain.is_pending());
assert_eq!(plain.row_value(), Some(Float(187.25)));
assert!(
row.with_columns(columns(&[Column::Price]))
.cell(Column::Price)
.is_some_and(|cell| cell.is_pending())
);
struct Stored;
impl CellExporter<Row> for Stored {
fn write_cell(&self, cell: &ExportCell<'_, Row>, out: &mut String) {
RawCells::new().write_value(
cell.row_value().unwrap_or(cell.value()),
cell.number_format(),
out,
);
}
}
let table = ExportTable::new(&COLUMNS, std::slice::from_ref(&row));
assert_eq!(tsv(&table, &CellExport::default()), "AAPL\t2.50\t7");
assert_eq!(
file_text(
&CsvFormat::new().with_encoding(CsvEncoding::Utf8),
&table,
&CellExport::default()
),
"AAPL,2.50,7\r\n"
);
assert_eq!(
tsv(&table, &CellExport::Custom(Arc::new(Stored))),
"AAPL\t187.25\tbuy"
);
let snapshot = trades();
let projection = grouped(
&snapshot,
&[Column::Symbol],
[(Column::Price, Aggregate::Sum)],
);
let footer = ExportRow::<Row>::footer(group(&projection, "AAPL")).with_pending(&pending);
let sum = footer.cell(Column::Price).unwrap();
assert_eq!(sum.value(), Float(1234.5));
assert!(!sum.is_pending());
assert_eq!(sum.row_value(), None);
}
#[test]
fn test_export_error() {
use std::error::Error as _;
fn assert_error<T: std::error::Error + Clone + Send + Sync + 'static>() {}
assert_error::<ExportError>();
assert_eq!(ExportError::Nothing.to_string(), "nothing to export");
assert_eq!(
ExportError::Cancelled.to_string(),
"the export was cancelled"
);
assert!(ExportError::Cancelled.source().is_none());
fn write_to_missing_directory() -> Result<(), ExportError> {
Err(io::Error::new(io::ErrorKind::NotFound, "no such directory"))?
}
let error = write_to_missing_directory().expect_err("an error");
assert_eq!(error.to_string(), "no such directory");
let ExportError::Io(io_error) = &error else {
panic!("{error:?}");
};
assert_eq!(io_error.kind(), io::ErrorKind::NotFound);
let ExportError::Io(cloned) = error.clone() else {
panic!("a clone of {error:?}");
};
assert!(Arc::ptr_eq(io_error, &cloned));
let message = ExportError::other("the workbook is too large");
assert!(matches!(message, ExportError::Other(_)));
assert_eq!(message.to_string(), "the workbook is too large");
assert!(message.source().is_none());
#[derive(Debug)]
struct Library(io::Error);
impl fmt::Display for Library {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the library failed")
}
}
impl std::error::Error for Library {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
let library = ExportError::other(Library(io::Error::other("zip")));
assert_eq!(library.to_string(), "the library failed");
assert_eq!(
library.source().map(ToString::to_string).as_deref(),
Some("zip")
);
assert_eq!(library.clone().to_string(), "the library failed");
}
}