1#![no_std]
43#![forbid(unsafe_code)]
44
45extern crate alloc;
46
47use alloc::collections::BTreeMap;
48use alloc::format;
49use alloc::string::{String, ToString};
50use alloc::vec::Vec;
51
52pub mod csv;
53pub mod xlsx;
54mod xlsx_write;
55mod xml;
56
57pub use datetime::Civil;
59
60pub const MAX_ROWS: u32 = 1_048_576;
62pub const MAX_COLS: u32 = 16_384;
64
65#[derive(Clone, Debug, PartialEq, Default)]
72pub enum Value {
73 #[default]
75 Empty,
76 Number(f64),
78 Text(String),
80 Bool(bool),
82 Date(f64),
84 Error(CellError),
86}
87
88impl Value {
89 pub fn text(&self) -> String {
94 match self {
95 Value::Empty => String::new(),
96 Value::Number(v) => number_text(*v),
97 Value::Text(s) => s.clone(),
98 Value::Bool(b) => String::from(if *b { "TRUE" } else { "FALSE" }),
99 Value::Date(v) => date_text(*v),
100 Value::Error(e) => String::from(e.text()),
101 }
102 }
103 pub fn is_empty(&self) -> bool {
105 matches!(self, Value::Empty)
106 }
107 pub fn number(&self) -> Option<f64> {
109 match self {
110 Value::Number(v) | Value::Date(v) => Some(*v),
111 _ => None,
112 }
113 }
114}
115
116pub(crate) fn number_text(v: f64) -> String {
117 if v == 0.0 { String::from("0") } else { base::f64_format(v) }
118}
119
120fn date_text(v: f64) -> String {
121 let Some(c) = civil(v) else { return number_text(v) };
122 let mut time = format!("{:02}:{:02}:{:02}", c.hour, c.minute, c.second);
123 if c.nanos != 0 {
124 time.push_str(&format!(".{:03}", c.nanos / 1_000_000));
125 }
126 if v >= 0.0 && (c.year, c.month, c.day) == (1899, 12, 30) {
127 return time;
128 }
129 let date = format!("{:04}-{:02}-{:02}", c.year, c.month, c.day);
130 if c.hour == 0 && c.minute == 0 && c.second == 0 && c.nanos == 0 { date } else { format!("{date} {time}") }
131}
132
133const OLE_EPOCH: i64 = -25_569;
135
136pub fn civil(serial: f64) -> Option<Civil> {
139 if !serial.is_finite() || serial.abs() > 1.0e8 {
140 return None;
141 }
142 let x = serial * 86_400_000.0;
143 let ms = if x >= 0.0 { (x + 0.5) as i64 } else { -((-x + 0.5) as i64) };
144 let days = ms.div_euclid(86_400_000);
145 let rem = ms.rem_euclid(86_400_000);
146 let (year, month, day) = datetime::civil_from_days(days + OLE_EPOCH);
147 Some(Civil {
148 year,
149 month,
150 day,
151 hour: (rem / 3_600_000) as u8,
152 minute: (rem / 60_000 % 60) as u8,
153 second: (rem / 1000 % 60) as u8,
154 nanos: (rem % 1000) as u32 * 1_000_000,
155 })
156}
157
158pub fn serial(c: &Civil) -> f64 {
161 let days = datetime::days_from_civil(c.year, c.month, c.day) - OLE_EPOCH;
162 let secs = c.hour as f64 * 3600.0 + c.minute as f64 * 60.0 + c.second as f64 + c.nanos as f64 / 1.0e9;
163 days as f64 + secs / 86_400.0
164}
165
166pub(crate) fn ole_day(y: i32, m: u8, d: u8) -> Option<f64> {
168 if !(1..=12).contains(&m) || d == 0 || d > datetime::days_in_month(y, m) {
169 return None;
170 }
171 Some((datetime::days_from_civil(y, m, d) - OLE_EPOCH) as f64)
172}
173
174pub(crate) fn parse_time(s: &str) -> Option<f64> {
176 let b = s.as_bytes();
177 let two = |i: usize| -> Option<u32> {
178 let (x, y) = (*b.get(i)?, *b.get(i + 1)?);
179 (x.is_ascii_digit() && y.is_ascii_digit()).then(|| ((x - b'0') * 10 + (y - b'0')) as u32)
180 };
181 let h = two(0)?;
182 if b.get(2) != Some(&b':') {
183 return None;
184 }
185 let m = two(3)?;
186 let mut secs = 0.0;
187 let mut i = 5;
188 if b.get(5) == Some(&b':') {
189 secs = two(6)? as f64;
190 i = 8;
191 if b.get(8) == Some(&b'.') {
192 let frac = &s[9..];
193 if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|c| c.is_ascii_digit()) {
194 return None;
195 }
196 let (f, used) = base::f64_parse(&b[8..]);
197 if used != b.len() - 8 {
198 return None;
199 }
200 secs += f;
201 i = b.len();
202 }
203 }
204 if i != b.len() || h > 23 || m > 59 || secs >= 60.0 {
205 return None;
206 }
207 Some((h as f64 * 3600.0 + m as f64 * 60.0 + secs) / 86_400.0)
208}
209
210pub(crate) fn parse_iso(s: &str, time_only: bool) -> Option<f64> {
213 let s = s.strip_suffix('Z').unwrap_or(s);
214 let b = s.as_bytes();
215 if time_only && b.get(2) == Some(&b':') {
216 return parse_time(s);
217 }
218 if b.len() < 10 || b[4] != b'-' || b[7] != b'-' {
219 return None;
220 }
221 let digits = |r: core::ops::Range<usize>| -> Option<u32> {
222 let t = b.get(r)?;
223 t.iter().all(u8::is_ascii_digit).then(|| t.iter().fold(0, |a, &c| a * 10 + (c - b'0') as u32))
224 };
225 let (y, m, d) = (digits(0..4)?, digits(5..7)?, digits(8..10)?);
226 let day = ole_day(y as i32, m as u8, d as u8)?;
227 match b.get(10) {
228 None => Some(day),
229 Some(b'T' | b' ') => Some(day + parse_time(&s[11..])?),
230 _ => None,
231 }
232}
233
234#[derive(Clone, Debug, PartialEq, Eq, Hash)]
236pub enum CellError {
237 Null,
239 Div0,
241 Value,
243 Ref,
245 Name,
247 Num,
249 NA,
251 GettingData,
253 Spill,
255 Calc,
257 Other(String),
259}
260
261impl CellError {
262 pub fn text(&self) -> &str {
264 match self {
265 CellError::Null => "#NULL!",
266 CellError::Div0 => "#DIV/0!",
267 CellError::Value => "#VALUE!",
268 CellError::Ref => "#REF!",
269 CellError::Name => "#NAME?",
270 CellError::Num => "#NUM!",
271 CellError::NA => "#N/A",
272 CellError::GettingData => "#GETTING_DATA",
273 CellError::Spill => "#SPILL!",
274 CellError::Calc => "#CALC!",
275 CellError::Other(s) => s,
276 }
277 }
278 pub fn parse(s: &str) -> CellError {
281 const ALL: [CellError; 10] = [
282 CellError::Null,
283 CellError::Div0,
284 CellError::Value,
285 CellError::Ref,
286 CellError::Name,
287 CellError::Num,
288 CellError::NA,
289 CellError::GettingData,
290 CellError::Spill,
291 CellError::Calc,
292 ];
293 let t = s.trim();
294 ALL.into_iter().find(|e| e.text().eq_ignore_ascii_case(t)).unwrap_or_else(|| CellError::Other(String::from(s)))
295 }
296}
297
298#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
300pub struct CellRef {
301 pub row: u32,
303 pub col: u32,
305}
306
307impl CellRef {
308 pub const fn new(row: u32, col: u32) -> CellRef {
310 CellRef { row, col }
311 }
312 pub fn a1(&self) -> String {
314 format!("{}{}", col_name(self.col), self.row as u64 + 1)
315 }
316}
317
318pub fn col_name(col: u32) -> String {
320 let mut n = col as u64 + 1;
321 let mut out = Vec::new();
322 while n > 0 {
323 n -= 1;
324 out.push(b'A' + (n % 26) as u8);
325 n /= 26;
326 }
327 out.reverse();
328 out.into_iter().map(char::from).collect()
329}
330
331fn letters(s: &str) -> Option<u32> {
333 if s.is_empty() || !s.bytes().all(|c| c.is_ascii_alphabetic()) {
334 return None;
335 }
336 let mut v: u64 = 0;
337 for c in s.bytes() {
338 v = v * 26 + (c.to_ascii_uppercase() - b'A') as u64 + 1;
339 if v > u32::MAX as u64 + 1 {
340 return None;
341 }
342 }
343 Some((v - 1) as u32)
344}
345
346fn row_digits(s: &str) -> Option<u32> {
348 if s.is_empty() || s.len() > 10 || !s.bytes().all(|c| c.is_ascii_digit()) {
349 return None;
350 }
351 let v: u64 = s.parse().ok()?;
352 if v == 0 || v > u32::MAX as u64 + 1 {
353 return None;
354 }
355 Some((v - 1) as u32)
356}
357
358pub fn parse_ref(s: &str) -> Option<CellRef> {
361 let s = s.strip_prefix('$').unwrap_or(s);
362 let split = s.find(|c: char| !c.is_ascii_alphabetic())?;
363 let col = letters(&s[..split])?;
364 let rest = &s[split..];
365 let row = row_digits(rest.strip_prefix('$').unwrap_or(rest))?;
366 Some(CellRef { row, col })
367}
368
369#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
372pub struct Area {
373 pub sheet: Option<usize>,
375 pub first: CellRef,
377 pub last: CellRef,
379}
380
381impl Area {
382 pub fn new(sheet: Option<usize>, a: CellRef, b: CellRef) -> Area {
384 Area {
385 sheet,
386 first: CellRef { row: a.row.min(b.row), col: a.col.min(b.col) },
387 last: CellRef { row: a.row.max(b.row), col: a.col.max(b.col) },
388 }
389 }
390 pub fn rows(&self) -> u64 {
392 self.last.row as u64 - self.first.row as u64 + 1
393 }
394 pub fn cols(&self) -> u64 {
396 self.last.col as u64 - self.first.col as u64 + 1
397 }
398 pub fn contains(&self, at: CellRef) -> bool {
400 (self.first.row..=self.last.row).contains(&at.row) && (self.first.col..=self.last.col).contains(&at.col)
401 }
402 pub fn a1(&self) -> String {
404 if self.first == self.last { self.first.a1() } else { format!("{}:{}", self.first.a1(), self.last.a1()) }
405 }
406}
407
408pub fn quote_sheet(name: &str) -> String {
412 let plain = !name.is_empty()
413 && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '.')
414 && !name.starts_with(|c: char| c.is_ascii_digit())
415 && parse_ref(name).is_none();
416 if plain { String::from(name) } else { format!("'{}'", name.replace('\'', "''")) }
417}
418
419#[derive(Clone, Copy, PartialEq)]
421enum Side {
422 Cell(CellRef),
423 Col(u32),
424 Row(u32),
425}
426
427fn side(s: &str) -> Option<Side> {
428 if let Some(c) = parse_ref(s) {
429 return Some(Side::Cell(c));
430 }
431 let t = s.strip_prefix('$').unwrap_or(s);
432 if let Some(c) = letters(t) {
433 return Some(Side::Col(c));
434 }
435 row_digits(t).map(Side::Row)
436}
437
438pub fn parse_area<S: AsRef<str>>(text: &str, sheets: &[S]) -> Option<Area> {
446 parse_area_by(text, |fold| sheets.iter().position(|s| s.as_ref().to_lowercase() == fold))
447}
448
449pub(crate) fn parse_area_by(text: &str, find: impl Fn(&str) -> Option<usize>) -> Option<Area> {
452 let t = text.trim();
453 let t = t.strip_prefix('=').unwrap_or(t).trim();
454 let (sheet, rest) = if let Some(q) = t.strip_prefix('\'') {
455 let mut name = String::new();
457 let mut it = q.char_indices();
458 let end = loop {
459 let (i, c) = it.next()?;
460 if c == '\'' {
461 if q[i + 1..].starts_with('\'') {
462 name.push('\'');
463 it.next();
464 } else {
465 break i + 1;
466 }
467 } else {
468 name.push(c);
469 }
470 };
471 (Some(name), q[end..].strip_prefix('!')?)
472 } else if let Some((name, rest)) = t.split_once('!') {
473 (Some(String::from(name)), rest)
474 } else {
475 (None, t)
476 };
477 let sheet = match sheet {
478 Some(name) => {
479 if name.is_empty() || name.contains(['[', ']', ':']) {
480 return None;
481 }
482 Some(find(&name.to_lowercase())?)
483 }
484 None => None,
485 };
486 let (a, b) = match rest.split_once(':') {
487 Some((a, b)) => (side(a)?, side(b)?),
488 None => match side(rest)? {
489 Side::Cell(c) => (Side::Cell(c), Side::Cell(c)),
490 _ => return None,
491 },
492 };
493 let (first, last) = match (a, b) {
494 (Side::Cell(x), Side::Cell(y)) => (x, y),
495 (Side::Col(x), Side::Col(y)) => (CellRef::new(0, x), CellRef::new(MAX_ROWS - 1, y)),
496 (Side::Row(x), Side::Row(y)) => (CellRef::new(x, 0), CellRef::new(y, MAX_COLS - 1)),
497 _ => return None,
498 };
499 Some(Area::new(sheet, first, last))
500}
501
502#[derive(Clone, Debug, Default, PartialEq)]
504pub struct Table {
505 pub columns: Vec<String>,
509 pub rows: Vec<Vec<Value>>,
511}
512
513impl Table {
514 pub fn column(&self, name: &str) -> Option<usize> {
516 let fold = name.to_lowercase();
517 self.columns.iter().position(|c| c.to_lowercase() == fold)
518 }
519}
520
521pub(crate) fn column_names(raw: Vec<String>) -> Vec<String> {
523 let mut out: Vec<String> = Vec::with_capacity(raw.len());
524 let mut taken: BTreeMap<String, u32> = BTreeMap::new();
526 for (i, n) in raw.into_iter().enumerate() {
527 let t = n.trim();
528 let base = if t.is_empty() { format!("F{}", i + 1) } else { t.to_string() };
529 let mut name = base.clone();
530 let fold = base.to_lowercase();
531 if taken.contains_key(&fold) {
532 let mut k = taken.get(&fold).copied().unwrap_or(1);
533 loop {
534 name = format!("{base}{k}");
535 k += 1;
536 if !taken.contains_key(&name.to_lowercase()) {
537 break;
538 }
539 }
540 taken.insert(fold, k);
541 }
542 taken.entry(name.to_lowercase()).or_insert(1);
543 out.push(name);
544 }
545 out
546}
547
548pub(crate) fn plain_names(n: usize) -> Vec<String> {
550 (1..=n).map(|i| format!("F{i}")).collect()
551}
552
553#[cfg(test)]
556rt::test_main!();
557
558#[cfg(test)]
559mod tests;
560#[cfg(test)]
561mod tests_write;