crabular 0.5.0

A high-performance ASCII table library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
[![CI](https://github.com/kakilangit/crabular/actions/workflows/ci.yml/badge.svg)](https://github.com/kakilangit/crabular/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/crates/v/crabular.svg)](https://crates.io/crates/crabular)
[![Documentation](https://docs.rs/crabular/badge.svg)](https://docs.rs/crabular)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

![Dall-E generated crabular image](https://raw.githubusercontent.com/kakilangit/static/refs/heads/main/crabular/crabular.jpeg)

# Crabular

A high-performance ASCII table library for Rust with zero dependencies.

## Features

- **Multiple table styles** - Classic, Modern (Unicode), Minimal, Compact, Markdown
- **Flexible alignment** - Left, Center, Right per-cell and per-column
- **Vertical alignment** - Top, Middle, Bottom for multi-line cells
- **Width constraints** - Fixed, Min, Max, Proportional, Wrap
- **Multi-line cells** - Automatic word wrapping with configurable widths
- **Cell spanning** - Colspan support for merged cells
- **Sorting** - Sort by column (alphabetic or numeric, ascending or descending)
- **Filtering** - Filter rows by exact match, predicate, or substring
- **Builder API** - Fluent interface for table construction
- **Zero dependencies** - No external crates required
- **Safe Rust** - `#![forbid(unsafe_code)]`
- **High performance** - Zero-allocation Display trait, allocation pooling for repeated renders

## Performance

Crabular v0.2.0+ includes Rust 1.93 optimizations for significant performance improvements:

### Zero-Allocation Display

```rust
use crabular::Table;

let table = Table::new()
    .header(["Name", "Age"])
    .row(["Kata", "30"]);

// Zero-allocation printing (20-40% faster)
println!("{table}");

// For comparison, this allocates:
println!("{}", table.render());
```

### Allocation Pooling for Repeated Renders

```rust,ignore
use std::io::{stdout, Write};

let mut buffer = Vec::with_capacity(4096);
for item in 0..10 {
    buffer.clear();
    table.render_into(&mut buffer)?;
    stdout().write_all(&buffer)?;
}
```

**Benefits:** 30-50% faster for repeated renders (pagination, filtering UI)

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
crabular = "0.5"
```

## Quick Start

```rust
use crabular::{Table, TableStyle};

let mut table = Table::new();
table.set_style(TableStyle::Modern);
table.set_headers(["Name", "Age", "City"]);
table.add_row(["Kelana", "30", "Berlin"]);
table.add_row(["Kata", "25", "Yogyakarta"]);

println!("{}", table.render());
```

Output:
```text
┌────────┬─────┬────────────┐
│ Name   │ Age │ City       │
├────────┼─────┼────────────┤
│ Kelana │ 30  │ Berlin     │
│ Kata   │ 25  │ Yogyakarta │
└────────┴─────┴────────────┘
```

## Builder API

For a more fluent experience, use `TableBuilder`:

```rust
use crabular::{TableBuilder, TableStyle, Alignment, WidthConstraint};

let output = TableBuilder::new()
    .style(TableStyle::Modern)
    .header(["ID", "Name", "Score"])
    .constrain(0, WidthConstraint::Fixed(5))
    .constrain(1, WidthConstraint::Min(15))
    .align(2, Alignment::Right)
    .rows([
        ["1", "Kelana", "95.5"],
        ["2", "Kata", "87.2"],
        ["3", "Cherry Blossom", "92.0"],
    ])
    .render();

print!("{output}");  // Or use .print() directly with std feature
```

## Truncation

Limit cell content length with truncation:

```rust
use crabular::{TableBuilder, TableStyle};

let output = TableBuilder::new()
    .style(TableStyle::Modern)
    .header(["ID", "Name", "Description", "Score"])
    .truncate(20)  // Truncate to 20 characters with "..." suffix
    .rows([
        ["1", "Kata", "A very long description that should be truncated", "95.5"],
        ["2", "Kelana", "Short desc", "87.2"],
        ["3", "Squidward", "Another extremely long description text here", "92.0"],
    ])
    .render();

print!("{output}");
```

Output:
```text
┌─────┬────────────┬───────────────────────┬───────┐
│ ID  │ Name       │ Description           │ Score │
├─────┼────────────┼───────────────────────┼───────┤
│ 1   │ Kata       │ A very long descr...  │ 95.5  │
│ 2   │ Kelana     │ Short desc            │ 87.2  │
│ 3   │ Squidward  │ Another extremely...  │ 92.0  │
└─────┴────────────┴───────────────────────┴───────┘
```

**Note:** Truncation is applied lazily during row insertion, so there's zero overhead when not used.

## Table Styles

```rust
use crabular::TableStyle;

// Available styles:
let _ = TableStyle::Classic;   // +---+---+ with | and -
let _ = TableStyle::Modern;    // Unicode box-drawing characters
let _ = TableStyle::Minimal;   // Header separator only
let _ = TableStyle::Compact;   // No outer borders
let _ = TableStyle::Markdown;  // GitHub-flavored markdown tables
```

### Classic
```text
+-----------------+-----+---------------+
| Name            | Age | City          |
+-----------------+-----+---------------+
| Kelana          | 30  | Berlin        |
| Kata            | 25  | Yogyakarta    |
| Cherry Blossom  | 35  | Bikini Bottom |
+-----------------+-----+---------------+
```

### Modern
```text
┌─────────────────┬─────┬───────────────┐
│ Name            │ Age │ City          │
├─────────────────┼─────┼───────────────┤
│ Kelana          │ 30  │ Berlin        │
│ Kata            │ 25  │ Yogyakarta    │
│ Cherry Blossom  │ 35  │ Bikini Bottom │
└─────────────────┴─────┴───────────────┘
```

### Minimal
```text
  Name              Age    City           
──────────────────────────────────────────
  Kelana            30     Berlin         
  Kata              25     Yogyakarta     
  Cherry Blossom    35     Bikini Bottom  
```

### Compact
```text
│ Name            │ Age  │ City          │
──────────────────┼──────┼────────────────
│ Kelana          │ 30   │ Berlin        │
│ Kata            │ 25   │ Yogyakarta    │
│ Cherry Blossom  │ 35   │ Bikini Bottom │
```

### Markdown
```text
| Name           | Age | City          |
|----------------|-----|---------------|
| Kelana         | 30  | Berlin        |
| Kata           | 25  | Yogyakarta    |
| Cherry Blossom | 35  | Bikini Bottom |
```

## Width Constraints

Control column widths with various constraints:

```rust
use crabular::{Table, WidthConstraint};

let mut table = Table::new();

// Fixed width (exactly N characters)
table.constrain(WidthConstraint::Fixed(20));

// Minimum width (at least N characters)
table.constrain(WidthConstraint::Min(10));

// Maximum width (at most N characters, truncates if needed)
table.constrain(WidthConstraint::Max(30));

// Proportional (percentage of available width)
table.constrain(WidthConstraint::Proportional(50));

// Wrap (word wrap at N characters)
table.constrain(WidthConstraint::Wrap(25));
```

## Alignment

```rust
use crabular::{Table, Row, Alignment};

let mut table = Table::new();

// Set column alignment
table.align(0, Alignment::Left);
table.align(1, Alignment::Center);
table.align(2, Alignment::Right);

// Per-row alignment via Row::with_alignment
let row = Row::with_alignment(["text"], Alignment::Center);
table.add_row(row);
```

## Vertical Alignment

For multi-line cells:

```rust
use crabular::{Table, VerticalAlignment};

let mut table = Table::new();

table.valign(VerticalAlignment::Top);    // Default
table.valign(VerticalAlignment::Middle);
table.valign(VerticalAlignment::Bottom);
```

## Cell Spanning (Colspan)

Create cells that span multiple columns:

```rust
use crabular::{Table, Cell, Row, Alignment};

let mut table = Table::new();
table.set_headers(["A", "B", "C"]);

let mut row = Row::new();
let mut merged = Cell::new("Spans two columns", Alignment::Center);
merged.set_span(2);  // This cell spans 2 columns
row.push(merged);
row.push(Cell::new("Normal", Alignment::Left));
table.add_row(row);
```

> **Note:** Standard Markdown does not support colspan. When using `TableStyle::Markdown`
> with spanned cells, the output will render visually but won't be valid Markdown table syntax.

## Sorting

Sort table rows by any column:

```rust
use crabular::{Table, Row, Alignment};

let mut table = Table::new();
table.add_row(["Kelana", "30"]);
table.add_row(["Kata", "25"]);

// Alphabetic sorting
table.sort(0);           // Ascending by column 0
table.sort_desc(0);      // Descending by column 0

// Numeric sorting
table.sort_num(1);       // Ascending numeric by column 1
table.sort_num_desc(1);  // Descending numeric by column 1

// Custom sorting - compare by first column content
table.sort_by(|a, b| {
    let a_content = a.cells().first().map_or("", |c| c.content());
    let b_content = b.cells().first().map_or("", |c| c.content());
    a_content.cmp(b_content)
});
```

## Filtering

Filter rows based on conditions:

```rust
use crabular::{Table, Row, Alignment};

let mut table = Table::new();
table.add_row(["Kelana", "Active", "100"]);
table.add_row(["Kata", "Inactive", "50"]);
table.add_row(["Cherry Blossom", "Active", "75"]);

// Exact match - keeps rows where column 1 equals "Active"
table.filter_eq(1, "Active");

// Substring match - keeps rows where column 0 contains "Kelana"
// table.filter_has(0, "Kelana");

// Custom predicate on column - keeps rows where column 2 > 50
// table.filter_col(2, |val| val.parse::<i32>().unwrap_or(0) > 50);

// Full row predicate - keeps rows with more than 2 cells
let filtered = table.filtered(|row| row.len() > 2);
let _ = filtered;
```

## Column Operations

```rust
use crabular::{Table, Row, Alignment};

let mut table = Table::new();
table.set_headers(["A", "B"]);
table.add_row(["1", "2"]);
table.add_row(["3", "4"]);

// Add column at the end (first value is header, rest are row values)
table.add_column(&["C", "5", "6"], Alignment::Left);

// Insert column at position (first value is header, rest are row values)
table.insert_column(1, &["X", "a", "b"], Alignment::Center);

// Remove column
table.remove_column(2);
```

 ## CLI Tool

A separate CLI tool is available at [crabular-cli](https://github.com/kakilangit/crabular/tree/main/crabular-cli):

```bash
# Install
cargo install crabular-cli

# From CSV file (default: first row is header)
crabular-cli -i data.csv

# Truncate long cell content to 20 characters
crabular-cli -i data.csv --truncate 20

# Treat all rows as data (no header)
crabular-cli -i data.csv --no-header

# Skip first row, treat remaining as data
crabular-cli -i data.csv --skip-header

# From stdin
cat data.csv | crabular-cli -i -

# From JSON (supports nested objects)
echo '[{"name":"Kata","info":{"city":"NYC"}}]' | crabular-cli -i - --format json

# Different styles
crabular-cli -s modern -i data.csv
crabular-cli -s markdown -i data.csv
```

### CLI Options

| Option | Description |
|--------|-------------|
| `-i, --input <FILE>` | Input file path (use `-` for stdin) |
| `-o, --output <FILE>` | Output file path |
| `-s, --style <STYLE>` | Table style: classic, modern, minimal, compact, markdown |
| `--format <FORMAT>` | Input format: csv, tsv, ssv, json, jsonl |
| `-S, --separator <CHAR>` | Field separator (default: auto-detect) |
| `--truncate N` | Truncate cell content to N characters with "..." suffix |
| `--no-header` | Treat all rows as data (no header row) |
| `--skip-header` | Skip first row, treat remaining as data |

 ## API Reference

### Table

| Method | Description |
|--------|-------------|
| `new()` | Create empty table |
| `set_headers(row)` | Set header row |
| `add_row(row)` | Add data row |
| `truncate(limit)` | Set max cell content length |
| `render()` | Render to string |
| `print()` | Print to stdout |
| `set_style(style)` | Set table style |
| `align(col, alignment)` | Set column alignment |
| `valign(alignment)` | Set vertical alignment |
| `constrain(constraint)` | Add width constraint |
| `sort(col)` | Sort ascending |
| `sort_desc(col)` | Sort descending |
| `sort_num(col)` | Sort numeric ascending |
| `sort_num_desc(col)` | Sort numeric descending |
| `filter_eq(col, value)` | Filter by exact match |
| `filter_has(col, substr)` | Filter by substring |
| `filter_col(col, pred)` | Filter by predicate |

### `TableBuilder`

| Method | Description |
|--------|-------------|
| `new()` | Create new builder |
| `style(style)` | Set table style |
| `header(cells)` | Set header row |
| `row(cells)` | Add data row |
| `rows(data)` | Add multiple rows |
| `truncate(limit)` | Set max cell content length |
| `align(col, alignment)` | Set column alignment |
| `valign(alignment)` | Set vertical alignment |
| `constrain(col, constraint)` | Set column constraint |
| `padding(padding)` | Set cell padding |
| `build()` | Build table |
| `render()` | Build and render |
| `print()` | Build and print |

## License

MIT License - see [LICENSE](LICENSE) for details.