Repository navigation
Expand file tree
/
Copy pathformat.rs
More file actions
789 lines (682 loc) · 26.7 KB
/
Copy pathformat.rs
File metadata and controls
789 lines (682 loc) · 26.7 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Template-based label generation for scale RENAMING wildcards
//!
//! Supports placeholder syntax in templates:
//! - `{}` - Insert value as-is
//! - `{:UPPER}` - Convert to UPPERCASE
//! - `{:lower}` - Convert to lowercase
//! - `{:Title}` - Convert to Title Case
//! - `{:time %fmt}` - DateTime strftime format (e.g., `{:time %b %Y}` -> "Jan 2024")
//! - `{:num %fmt}` - Number printf format (e.g., `{:num %.2f}` -> "25.50")
use arrow::array::ArrayRef;
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use regex::Regex;
use std::collections::HashMap;
use std::sync::OnceLock;
use crate::array_util::{map_column, value_to_display};
use crate::plot::ArrayElement;
/// Placeholder types supported in label templates
#[derive(Debug, Clone)]
enum Placeholder {
/// `{}` - Insert value as-is
Plain,
/// `{:UPPER}` - Convert to UPPERCASE
Upper,
/// `{:lower}` - Convert to lowercase
Lower,
/// `{:Title}` - Convert to Title Case
Title,
/// `{:time %Y-%m-%d}` or similar strftime format
DateTime(String),
/// `{:num %.2f}` or similar printf format
Number(String),
}
/// Parsed placeholder with its full match text
#[derive(Debug, Clone)]
struct ParsedPlaceholder {
placeholder: Placeholder,
match_text: String,
}
/// Regex for matching placeholders in templates
fn placeholder_regex() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"\{([^}]*)\}").expect("Invalid placeholder regex"))
}
/// Parse all placeholders from a template string
fn parse_placeholders(template: &str) -> Vec<ParsedPlaceholder> {
placeholder_regex()
.find_iter(template)
.map(|cap| {
let inner = &template[cap.start() + 1..cap.end() - 1];
let placeholder = match inner {
"" => Placeholder::Plain,
":UPPER" => Placeholder::Upper,
":lower" => Placeholder::Lower,
":Title" => Placeholder::Title,
s if s.starts_with(":time ") => {
Placeholder::DateTime(s.strip_prefix(":time ").unwrap().to_string())
}
s if s.starts_with(":num ") => {
Placeholder::Number(s.strip_prefix(":num ").unwrap().to_string())
}
_ => Placeholder::Plain, // Unknown, treat as plain
};
ParsedPlaceholder {
placeholder,
match_text: cap.as_str().to_string(),
}
})
.collect()
}
/// Apply transformation based on placeholder type.
/// `precision` controls decimal places for `Plain` placeholders on numeric values.
fn apply_transformation(
value: &str,
placeholder: &Placeholder,
precision: Option<usize>,
) -> String {
match placeholder {
Placeholder::Plain => match precision {
Some(prec) => match value.parse::<f64>() {
Ok(n) => format!("{n:.prec$}"),
Err(_) => value.to_string(),
},
None => value.to_string(),
},
Placeholder::Upper => value.to_uppercase(),
Placeholder::Lower => value.to_lowercase(),
Placeholder::Title => to_title_case(value),
Placeholder::DateTime(fmt) => format_datetime(value, fmt),
Placeholder::Number(fmt) => format_number_with_spec(value, fmt),
}
}
/// Convert string to Title Case
fn to_title_case(s: &str) -> String {
s.split_whitespace()
.map(|word| {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) => first
.to_uppercase()
.chain(chars.flat_map(|c| c.to_lowercase()))
.collect(),
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Format datetime string using strftime format
fn format_datetime(value: &str, fmt: &str) -> String {
// Try parsing as NaiveDateTime first (various formats)
if let Ok(dt) = NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S") {
return dt.format(fmt).to_string();
}
if let Ok(dt) = NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%.f") {
return dt.format(fmt).to_string();
}
if let Ok(dt) = NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S") {
return dt.format(fmt).to_string();
}
if let Ok(dt) = NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S%.f") {
return dt.format(fmt).to_string();
}
// Try parsing as NaiveDate
if let Ok(d) = NaiveDate::parse_from_str(value, "%Y-%m-%d") {
return d.format(fmt).to_string();
}
// Try parsing as NaiveTime
if let Ok(d) = NaiveTime::parse_from_str(value, "%H:%M:%S") {
return d.format(fmt).to_string();
}
if let Ok(d) = NaiveTime::parse_from_str(value, "%H:%M:%S%.f") {
return d.format(fmt).to_string();
}
// Fallback: return original value if parsing fails
value.to_string()
}
/// Format number using printf-style format specifier (e.g., "%.2f", "%d", "%e")
fn format_number_with_spec(value: &str, fmt: &str) -> String {
// Try to parse as f64
if let Ok(n) = value.parse::<f64>() {
// Use sprintf crate for full printf compatibility
// Supports: %d, %i, %f, %e, %E, %g, %G, %o, %x, %X, width, precision, flags
return sprintf::sprintf!(fmt, n).unwrap_or_else(|_| value.to_string());
}
// Fallback: return original value if parsing fails
value.to_string()
}
/// Default template: passes a value through unchanged. Shared `serde`
/// default for every `*_template` field using this module's placeholder
/// syntax (`Scale::label_template`, `Format::value_template`) — their
/// default can't just be `String::default()`, since `""` would blank every
/// value instead of passing it through.
pub(crate) fn default_template() -> String {
"{}".to_string()
}
/// Apply a label template to an array of break values.
///
/// Each break value is formatted using the template string.
/// Explicit mappings (from existing label_mapping) take priority over template-generated ones.
///
/// # Arguments
/// * `breaks` - Array elements to apply template to
/// * `template` - Template string with placeholders (e.g., "{} units", "{:UPPER}")
/// * `existing` - Optional existing label mappings (explicit mappings take priority)
///
/// # Returns
/// HashMap of original value -> formatted label
///
/// # Example
/// ```ignore
/// let breaks = vec![ArrayElement::Number(0.0), ArrayElement::Number(25.0)];
/// let result = apply_label_template(&breaks, "{} units", &None);
/// // result: {"0" => Some("0 units"), "25" => Some("25 units")}
/// ```
pub fn apply_label_template(
breaks: &[ArrayElement],
template: &str,
existing: &Option<HashMap<String, Option<String>>>,
) -> HashMap<String, Option<String>> {
let mut result = existing.clone().unwrap_or_default();
// Parse all placeholders once
let placeholders = parse_placeholders(template);
// For numeric breaks with a plain placeholder, determine consistent decimal
// precision so that e.g. [54.5, 55, 55.5] formats as ["54.5", "55.0", "55.5"]
// rather than stripping the ".0" from the integer-valued break.
let has_plain = placeholders
.iter()
.any(|p| matches!(p.placeholder, Placeholder::Plain))
|| placeholders.is_empty();
let numeric_precision = if has_plain {
let numbers: Vec<f64> = breaks
.iter()
.filter_map(|e| match e {
ArrayElement::Number(n) => Some(*n),
_ => None,
})
.collect();
compute_numeric_precision(&numbers)
} else {
None
};
for elem in breaks {
// Skip null values
if matches!(elem, ArrayElement::Null) {
continue;
}
let key = elem.to_key_string();
// Only apply template if no explicit mapping exists
result.entry(key.clone()).or_insert_with(|| {
Some(format_value(
&key,
template,
&placeholders,
numeric_precision,
))
});
}
result
}
/// Determine the number of decimal places needed to display numeric values
/// consistently. Based on the algorithm from R's `scales::precision()`: uses
/// the smallest inter-value difference to derive display precision. Returns
/// `None` if there are fewer than 2 numbers or all are integers.
fn compute_numeric_precision(numbers: &[f64]) -> Option<usize> {
let tol = f64::EPSILON.sqrt();
let mut numbers: Vec<f64> = numbers.to_vec();
if numbers.len() < 2 {
return None;
}
numbers.sort_by(|a, b| a.total_cmp(b));
let smallest_diff = numbers
.windows(2)
.map(|w| (w[1] - w[0]).abs())
.filter(|d| *d > 0.0)
.fold(f64::INFINITY, f64::min);
if smallest_diff == f64::INFINITY || smallest_diff < tol {
return None;
}
let mut precision = 10f64.powf(smallest_diff.log10().floor() - 1.0);
// If all values are multiples of 10*precision, coarsen by one level
if numbers
.iter()
.all(|&x| ((x / precision).round() % 10.0).abs() < tol)
{
precision *= 10.0;
}
let n_decimals = (-precision.log10().floor()) as isize;
if n_decimals > 0 {
Some(n_decimals.min(20) as usize)
} else {
None
}
}
/// Apply label formatting template to a DataFrame column.
///
/// Returns a new DataFrame with the specified column formatted according to the template.
///
/// # Arguments
/// * `df` - DataFrame containing the column to format
/// * `column_name` - Name of the column to format
/// * `template` - Template string with placeholders (e.g., "{:Title}", "{:num %.2f}")
///
/// # Returns
/// New DataFrame with formatted column
///
/// # Example
/// ```ignore
/// let formatted_df = format_dataframe_column(&df, "_aesthetic_label", "Region: {:Title}")?;
/// ```
pub fn format_dataframe_column(
df: &crate::DataFrame,
column_name: &str,
template: &str,
) -> Result<crate::DataFrame, String> {
use crate::array_util::new_str_array;
// Get the column
let column = df
.column(column_name)
.map_err(|e| format!("Column '{}' not found: {}", column_name, e))?;
let string_values: Vec<Option<String>> = map_column(column, |i| value_to_display(column, i));
// Step 2: Apply formatting template to all string values
let placeholders = parse_placeholders(template);
let formatted_owned: Vec<Option<String>> = string_values
.into_iter()
.map(|opt| opt.map(|s| format_value(&s, template, &placeholders, None)))
.collect();
let formatted_refs: Vec<Option<&str>> =
formatted_owned.iter().map(|opt| opt.as_deref()).collect();
let formatted_col = new_str_array(formatted_refs);
// Replace column in DataFrame
df.with_column(column_name, formatted_col)
.map_err(|e| format!("Failed to replace column: {}", e))
}
/// Look up `key` in `mapping`. `Some(_)` (possibly empty, for an explicit
/// `=> NULL` suppression) means the mapping resolves this key outright;
/// `None` means there is no entry for it at all.
fn resolve_override(
mapping: &Option<HashMap<String, Option<String>>>,
key: &str,
) -> Option<String> {
match mapping.as_ref().and_then(|m| m.get(key)) {
Some(Some(display)) => Some(display.clone()),
Some(None) => Some(String::new()),
None => None,
}
}
/// Resolve one display value per row of a column, for `TABULATE FORMAT`'s
/// `RENAMING` clause: an explicit `mapping` entry wins outright (including
/// suppressing a cell to blank text via `=> NULL`); every other value gets
/// `template` applied, except a null cell with no explicit `"null"` entry,
/// which is left unresolved.
///
/// `Ok(None)` at a given row means "no resolution, use the caller's own
/// default content for that row"; `Ok(Some(s))` (possibly empty) is the
/// resolved display text.
pub fn resolve_column_values(
column: &ArrayRef,
template: &str,
mapping: &Option<HashMap<String, Option<String>>>,
) -> Result<Vec<Option<String>>, String> {
let string_values: Vec<Option<String>> = map_column(column, |i| value_to_display(column, i));
let placeholders = parse_placeholders(template);
Ok(string_values
.into_iter()
.map(|value| match value {
None => resolve_override(mapping, "null"),
Some(raw) => resolve_override(mapping, &raw)
.or_else(|| Some(format_value(&raw, template, &placeholders, None))),
})
.collect())
}
/// Format a single value using template and parsed placeholders
fn format_value(
value: &str,
template: &str,
placeholders: &[ParsedPlaceholder],
precision: Option<usize>,
) -> String {
if placeholders.is_empty() {
// No placeholders - use template as literal string
template.to_string()
} else {
// Replace each placeholder with its transformed value
let mut result = template.to_string();
for parsed in placeholders.iter().rev() {
let transformed = apply_transformation(value, &parsed.placeholder, precision);
result = result.replace(&parsed.match_text, &transformed);
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_plain_placeholder() {
let breaks = vec![
ArrayElement::Number(0.0),
ArrayElement::Number(25.0),
ArrayElement::Number(50.0),
];
let result = apply_label_template(&breaks, "{} units", &None);
assert_eq!(result.get("0"), Some(&Some("0 units".to_string())));
assert_eq!(result.get("25"), Some(&Some("25 units".to_string())));
assert_eq!(result.get("50"), Some(&Some("50 units".to_string())));
}
#[test]
fn test_upper_placeholder() {
let breaks = vec![
ArrayElement::String("north".to_string()),
ArrayElement::String("south".to_string()),
];
let result = apply_label_template(&breaks, "{:UPPER}", &None);
assert_eq!(result.get("north"), Some(&Some("NORTH".to_string())));
assert_eq!(result.get("south"), Some(&Some("SOUTH".to_string())));
}
#[test]
fn test_lower_placeholder() {
let breaks = vec![
ArrayElement::String("HELLO".to_string()),
ArrayElement::String("WORLD".to_string()),
];
let result = apply_label_template(&breaks, "{:lower}", &None);
assert_eq!(result.get("HELLO"), Some(&Some("hello".to_string())));
assert_eq!(result.get("WORLD"), Some(&Some("world".to_string())));
}
#[test]
fn test_title_placeholder() {
let breaks = vec![
ArrayElement::String("us east".to_string()),
ArrayElement::String("eu west".to_string()),
];
let result = apply_label_template(&breaks, "Region: {:Title}", &None);
assert_eq!(
result.get("us east"),
Some(&Some("Region: Us East".to_string()))
);
assert_eq!(
result.get("eu west"),
Some(&Some("Region: Eu West".to_string()))
);
}
#[test]
fn test_datetime_placeholder() {
let breaks = vec![
ArrayElement::String("2024-01-15".to_string()),
ArrayElement::String("2024-02-15".to_string()),
];
let result = apply_label_template(&breaks, "{:time %b %Y}", &None);
assert_eq!(
result.get("2024-01-15"),
Some(&Some("Jan 2024".to_string()))
);
assert_eq!(
result.get("2024-02-15"),
Some(&Some("Feb 2024".to_string()))
);
}
#[test]
fn test_explicit_takes_priority() {
let breaks = vec![
ArrayElement::String("A".to_string()),
ArrayElement::String("B".to_string()),
ArrayElement::String("C".to_string()),
];
let mut existing = HashMap::new();
existing.insert("A".to_string(), Some("Alpha".to_string()));
let result = apply_label_template(&breaks, "Category {}", &Some(existing));
// A should keep explicit mapping
assert_eq!(result.get("A"), Some(&Some("Alpha".to_string())));
// B and C should get template
assert_eq!(result.get("B"), Some(&Some("Category B".to_string())));
assert_eq!(result.get("C"), Some(&Some("Category C".to_string())));
}
#[test]
fn test_multiple_placeholders() {
let breaks = vec![ArrayElement::String("hello".to_string())];
let result = apply_label_template(&breaks, "{} - {:UPPER}", &None);
assert_eq!(
result.get("hello"),
Some(&Some("hello - HELLO".to_string()))
);
}
#[test]
fn test_no_placeholder_literal() {
let breaks = vec![
ArrayElement::String("A".to_string()),
ArrayElement::String("B".to_string()),
];
let result = apply_label_template(&breaks, "Constant Label", &None);
assert_eq!(result.get("A"), Some(&Some("Constant Label".to_string())));
assert_eq!(result.get("B"), Some(&Some("Constant Label".to_string())));
}
#[test]
fn test_to_key_string_number_integer() {
assert_eq!(ArrayElement::Number(0.0).to_key_string(), "0");
assert_eq!(ArrayElement::Number(25.0).to_key_string(), "25");
assert_eq!(ArrayElement::Number(-100.0).to_key_string(), "-100");
}
#[test]
fn test_to_key_string_number_decimal() {
assert_eq!(ArrayElement::Number(25.5).to_key_string(), "25.5");
assert_eq!(ArrayElement::Number(0.123).to_key_string(), "0.123");
}
#[test]
fn test_to_title_case() {
assert_eq!(to_title_case("hello world"), "Hello World");
assert_eq!(to_title_case("HELLO WORLD"), "Hello World");
assert_eq!(to_title_case("hello"), "Hello");
assert_eq!(to_title_case(""), "");
}
#[test]
fn test_datetime_with_time() {
let breaks = vec![ArrayElement::String("2024-01-15T10:30:00".to_string())];
let result = apply_label_template(&breaks, "{:time %Y-%m-%d %H:%M}", &None);
assert_eq!(
result.get("2024-01-15T10:30:00"),
Some(&Some("2024-01-15 10:30".to_string()))
);
}
#[test]
fn test_invalid_datetime_fallback() {
let breaks = vec![ArrayElement::String("not-a-date".to_string())];
let result = apply_label_template(&breaks, "{:time %Y-%m-%d}", &None);
// Should fall back to original value
assert_eq!(
result.get("not-a-date"),
Some(&Some("not-a-date".to_string()))
);
}
#[test]
fn test_null_skipped() {
let breaks = vec![
ArrayElement::String("A".to_string()),
ArrayElement::Null,
ArrayElement::String("B".to_string()),
];
let result = apply_label_template(&breaks, "{}", &None);
assert_eq!(result.len(), 2);
assert!(result.contains_key("A"));
assert!(result.contains_key("B"));
}
#[test]
fn test_number_format_decimal_places() {
let breaks = vec![ArrayElement::Number(25.5), ArrayElement::Number(100.0)];
let result = apply_label_template(&breaks, "${:num %.2f}", &None);
assert_eq!(result.get("25.5"), Some(&Some("$25.50".to_string())));
assert_eq!(result.get("100"), Some(&Some("$100.00".to_string())));
}
#[test]
fn test_number_format_no_decimals() {
let breaks = vec![ArrayElement::Number(25.7)];
let result = apply_label_template(&breaks, "{:num %.0f} items", &None);
assert_eq!(result.get("25.7"), Some(&Some("26 items".to_string())));
}
#[test]
fn test_number_format_scientific() {
let breaks = vec![ArrayElement::Number(1234.5)];
let result = apply_label_template(&breaks, "{:num %.2e}", &None);
assert_eq!(result.get("1234.5"), Some(&Some("1.23e+03".to_string())));
}
#[test]
fn test_number_format_non_numeric_fallback() {
let breaks = vec![ArrayElement::String("hello".to_string())];
let result = apply_label_template(&breaks, "{:num %.2f}", &None);
// Non-numeric should fall back to original value
assert_eq!(result.get("hello"), Some(&Some("hello".to_string())));
}
#[test]
fn test_number_format_integer() {
let breaks = vec![ArrayElement::Number(42.0)];
let result = apply_label_template(&breaks, "{:num %d}", &None);
assert_eq!(result.get("42"), Some(&Some("42".to_string())));
}
#[test]
fn test_plain_placeholder_consistent_decimal_precision() {
let breaks = vec![
ArrayElement::Number(54.5),
ArrayElement::Number(55.0),
ArrayElement::Number(55.5),
];
let result = apply_label_template(&breaks, "{}", &None);
assert_eq!(result.get("54.5"), Some(&Some("54.5".to_string())));
assert_eq!(result.get("55"), Some(&Some("55.0".to_string())));
assert_eq!(result.get("55.5"), Some(&Some("55.5".to_string())));
}
#[test]
fn test_plain_placeholder_all_integers_no_decimals() {
let breaks = vec![
ArrayElement::Number(10.0),
ArrayElement::Number(20.0),
ArrayElement::Number(30.0),
];
let result = apply_label_template(&breaks, "{}", &None);
assert_eq!(result.get("10"), Some(&Some("10".to_string())));
assert_eq!(result.get("20"), Some(&Some("20".to_string())));
assert_eq!(result.get("30"), Some(&Some("30".to_string())));
}
#[test]
fn test_plain_placeholder_small_fractional_steps() {
let breaks = vec![
ArrayElement::Number(0.0),
ArrayElement::Number(0.05),
ArrayElement::Number(0.1),
];
let result = apply_label_template(&breaks, "{}", &None);
assert_eq!(result.get("0"), Some(&Some("0.00".to_string())));
assert_eq!(result.get("0.05"), Some(&Some("0.05".to_string())));
assert_eq!(result.get("0.1"), Some(&Some("0.10".to_string())));
}
#[test]
fn resolve_column_values_applies_template_to_unmapped_values() {
use crate::array_util::new_str_array;
let column = new_str_array(vec![Some("a"), Some("b")]);
let result = resolve_column_values(&column, "[{}]", &None).unwrap();
assert_eq!(
result,
vec![Some("[a]".to_string()), Some("[b]".to_string())]
);
}
#[test]
fn resolve_column_values_explicit_mapping_wins_over_template() {
use crate::array_util::new_f64_array;
let column = new_f64_array(vec![Some(0.0), Some(5.0)]);
let mapping = Some(HashMap::from([("0".to_string(), Some("-".to_string()))]));
let result = resolve_column_values(&column, "{:num %.2f}", &mapping).unwrap();
assert_eq!(
result,
vec![Some("-".to_string()), Some("5.00".to_string())]
);
}
#[test]
fn resolve_column_values_null_with_explicit_entry_is_resolved() {
use crate::array_util::new_f64_array;
let column = new_f64_array(vec![None, Some(1.0)]);
let mapping = Some(HashMap::from([("null".to_string(), None)])); // => NULL suppresses
let result = resolve_column_values(&column, "{:num %.0f}", &mapping).unwrap();
assert_eq!(result[0], Some(String::new())); // suppressed, not templated
assert_eq!(result[1], Some("1".to_string()));
}
#[test]
fn resolve_column_values_formats_temporal_columns_as_iso_text() {
use arrow::array::Date32Array;
use std::sync::Arc;
// 19737 days after the epoch
let column: ArrayRef = Arc::new(Date32Array::from(vec![Some(19737)]));
let result = resolve_column_values(&column, "{:time %b %Y}", &None).unwrap();
assert_eq!(result, vec![Some("Jan 2024".to_string())]);
let result = resolve_column_values(&column, "{}", &None).unwrap();
assert_eq!(result, vec![Some("2024-01-15".to_string())]);
}
#[test]
fn resolve_column_values_formats_timestamps_for_time_placeholders() {
use arrow::array::TimestampMicrosecondArray;
use std::sync::Arc;
// 2024-01-15 10:30:00 UTC, in microseconds
let column: ArrayRef = Arc::new(TimestampMicrosecondArray::from(vec![Some(
1_705_315_800_000_000,
)]));
let result = resolve_column_values(&column, "{:time %b %Y}", &None).unwrap();
assert_eq!(result, vec![Some("Jan 2024".to_string())]);
}
#[test]
fn resolve_column_values_keeps_large_integers_exact() {
use arrow::array::Int64Array;
use std::sync::Arc;
// Beyond 2^53: not representable as f64
let column: ArrayRef = Arc::new(Int64Array::from(vec![9007199254740993]));
let result = resolve_column_values(&column, "{}", &None).unwrap();
assert_eq!(result, vec![Some("9007199254740993".to_string())]);
}
#[test]
fn resolve_column_values_renders_booleans_as_true_and_false() {
use arrow::array::BooleanArray;
use std::sync::Arc;
let column: ArrayRef = Arc::new(BooleanArray::from(vec![true, false]));
let result = resolve_column_values(&column, "{}", &None).unwrap();
assert_eq!(
result,
vec![Some("true".to_string()), Some("false".to_string())]
);
}
#[test]
fn resolve_column_values_does_not_align_precision_across_cells() {
use crate::array_util::new_f64_array;
let column = new_f64_array(vec![Some(1.5), Some(3.0), Some(3.0001)]);
let result = resolve_column_values(&column, "{}", &None).unwrap();
assert_eq!(
result,
vec![
Some("1.5".to_string()),
Some("3".to_string()),
Some("3.0001".to_string())
]
);
}
#[test]
fn resolve_column_values_leaves_numeric_looking_strings_alone() {
use crate::array_util::new_str_array;
let column = new_str_array(vec![Some("007"), Some("3.0001")]);
let result = resolve_column_values(&column, "{}", &None).unwrap();
assert_eq!(
result,
vec![Some("007".to_string()), Some("3.0001".to_string())]
);
}
#[test]
fn compute_numeric_precision_tolerates_nan() {
assert_eq!(compute_numeric_precision(&[1.5, f64::NAN, 3.0]), Some(1));
}
#[test]
fn resolve_column_values_null_without_an_explicit_entry_is_left_unresolved() {
use crate::array_util::new_f64_array;
let column = new_f64_array(vec![None, Some(1.0)]);
let result = resolve_column_values(&column, "{:num %.2f}", &None).unwrap();
// Caller falls back to its own default rendering for this row, the
// same way an unmapped null break is left untouched by
// apply_label_template.
assert_eq!(result[0], None);
assert_eq!(result[1], Some("1.00".to_string()));
}
}