use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};
use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike};
use rust_decimal::{Decimal, RoundingStrategy};
use crate::value::CellValue;
pub fn concat(parts: &[&str]) -> String {
parts.concat()
}
pub fn join(sep: &str, parts: &[&str]) -> String {
parts.join(sep)
}
pub fn upper(s: &str) -> String {
s.to_uppercase()
}
pub fn lower(s: &str) -> String {
s.to_lowercase()
}
pub fn trim(s: &str) -> String {
s.trim().to_string()
}
pub fn replace_all(s: &str, from: &str, to: &str) -> String {
s.replace(from, to)
}
pub fn substr(s: &str, start: usize, len: usize) -> String {
s.chars().skip(start).take(len).collect()
}
pub fn pad_left(s: &str, width: usize, fill: char) -> String {
let n = s.chars().count();
if n >= width {
return s.to_string();
}
let mut out = String::with_capacity(width);
out.extend(std::iter::repeat(fill).take(width - n));
out.push_str(s);
out
}
pub fn money(v: Decimal) -> String {
v.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero)
.normalize()
.to_string()
}
pub fn money_fixed(v: Decimal) -> String {
format!("{:.2}", v.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero))
}
pub fn percent(v: f64, scale: u32) -> String {
format!("{:.*}%", scale as usize, v * 100.0)
}
pub fn round(v: f64, scale: u32) -> f64 {
let f = 10f64.powi(scale as i32);
(v * f).round() / f
}
pub fn today() -> NaiveDate {
chrono::Local::now().date_naive()
}
pub fn now() -> NaiveDateTime {
chrono::Local::now().naive_local()
}
pub fn date_fmt(d: NaiveDate, fmt: &str) -> String {
d.format(fmt).to_string()
}
pub fn datetime_fmt(dt: NaiveDateTime, fmt: &str) -> String {
dt.format(fmt).to_string()
}
pub fn ymd(d: NaiveDate) -> i64 {
(d.year() as i64) * 10_000 + (d.month() as i64) * 100 + d.day() as i64
}
pub fn seconds_of_day(dt: NaiveDateTime) -> i64 {
dt.hour() as i64 * 3600 + dt.minute() as i64 * 60 + dt.second() as i64
}
pub fn text(v: impl Into<CellValue>) -> CellValue {
v.into()
}
pub fn coalesce(values: &[CellValue]) -> CellValue {
values
.iter()
.find(|v| !v.is_empty())
.cloned()
.unwrap_or(CellValue::Empty)
}
pub fn if_empty(v: CellValue, fallback: CellValue) -> CellValue {
if v.is_empty() { fallback } else { v }
}
pub fn map_dict(v: &CellValue, pairs: &[(&str, &str)]) -> CellValue {
let key = v.to_text();
let key = key.trim();
match pairs.iter().find(|(from, _)| *from == key) {
Some((_, to)) => CellValue::Text((*to).to_string()),
None => v.clone(),
}
}
#[derive(Clone, Debug)]
pub struct Seq {
n: Arc<AtomicI64>,
step: i64,
}
impl Seq {
pub fn new(start: i64, step: i64) -> Self {
Self {
n: Arc::new(AtomicI64::new(start)),
step: if step == 0 { 1 } else { step },
}
}
pub fn next(&self) -> i64 {
self.n.fetch_add(self.step, Ordering::Relaxed)
}
pub fn next_cell(&self) -> CellValue {
CellValue::Number(self.next() as f64)
}
pub fn current(&self) -> i64 {
self.n.load(Ordering::Relaxed)
}
}
pub fn seq(start: i64, step: i64) -> Seq {
Seq::new(start, step)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_text_helpers() {
assert_eq!(concat(&["A", "-", "B"]), "A-B");
assert_eq!(join("/", &["x", "y"]), "x/y");
assert_eq!(upper("ab"), "AB");
assert_eq!(substr("abcdef", 1, 3), "bcd");
assert_eq!(pad_left("7", 4, '0'), "0007");
assert_eq!(replace_all("a-b-c", "-", "_"), "a_b_c");
}
#[test]
fn test_value_helpers() {
let v = coalesce(&[CellValue::Empty, CellValue::Text("x".into())]);
assert_eq!(v.to_text(), "x");
assert_eq!(
if_empty(CellValue::Empty, CellValue::Number(1.0)).to_text(),
"1"
);
let mapped = map_dict(&CellValue::Text("1".into()), &[("1", "启用")]);
assert_eq!(mapped.to_text(), "启用");
}
#[test]
fn test_seq() {
let s = seq(10, 2);
assert_eq!(s.next(), 10);
assert_eq!(s.next(), 12);
assert_eq!(s.current(), 14);
}
#[test]
fn test_money_and_round() {
assert_eq!(money(Decimal::new(125, 1)), "12.5");
assert_eq!(money_fixed(Decimal::new(125, 1)), "12.50");
assert_eq!(round(1.2345, 2), 1.23);
assert_eq!(percent(0.1234, 1), "12.3%");
}
}