use crate::error::ExcelError;
pub fn column_index_from_string(column: &str) -> Result<u32, ExcelError> {
let column = column.trim().trim_start_matches('$');
if column.is_empty() || column.len() > 3 || !column.chars().all(|c| c.is_ascii_alphabetic()) {
return Err(ExcelError::InvalidCoordinate(column.to_owned()));
}
Ok(column.chars().fold(0, |index, c| {
index * 26 + (c.to_ascii_uppercase() as u32 - 'A' as u32 + 1)
}))
}
pub fn string_from_column_index(index: u32) -> String {
let mut index = index.max(1);
let mut letters = Vec::new();
while index > 0 {
let remainder = (index - 1) % 26;
letters.push((b'A' + remainder as u8) as char);
index = (index - 1) / 26;
}
letters.iter().rev().collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Coordinate {
pub column: u32,
pub row: u32,
}
impl Coordinate {
pub const fn new(column: u32, row: u32) -> Self {
Self { column, row }
}
pub fn parse(coordinate: &str) -> Result<Self, ExcelError> {
let coordinate = coordinate.trim().replace('$', "");
let split = coordinate
.find(|c: char| c.is_ascii_digit())
.ok_or_else(|| ExcelError::InvalidCoordinate(coordinate.clone()))?;
let (letters, digits) = coordinate.split_at(split);
let column = column_index_from_string(letters)?;
let row = digits
.parse::<u32>()
.ok()
.filter(|row| *row > 0)
.ok_or_else(|| ExcelError::InvalidCoordinate(coordinate.clone()))?;
Ok(Self { column, row })
}
pub fn column_letter(&self) -> String {
string_from_column_index(self.column)
}
}
impl std::fmt::Display for Coordinate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}", self.column_letter(), self.row)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellRange {
Cells(Coordinate, Coordinate),
Columns(u32, u32),
Rows(u32, u32),
}
impl CellRange {
pub fn parse(range: &str) -> Result<Self, ExcelError> {
let range = range.trim().replace('$', "");
let (start, end) = match range.split_once(':') {
Some((start, end)) => (start.to_owned(), end.to_owned()),
None => (range.clone(), range.clone()),
};
if start.chars().all(|c| c.is_ascii_digit()) && end.chars().all(|c| c.is_ascii_digit()) {
let first: u32 = start
.parse()
.map_err(|_| ExcelError::InvalidCoordinate(range.clone()))?;
let last: u32 = end.parse().map_err(|_| ExcelError::InvalidCoordinate(range.clone()))?;
return Ok(Self::Rows(first.min(last), first.max(last)));
}
if start.chars().all(|c| c.is_ascii_alphabetic()) && end.chars().all(|c| c.is_ascii_alphabetic()) {
let first = column_index_from_string(&start)?;
let last = column_index_from_string(&end)?;
return Ok(Self::Columns(first.min(last), first.max(last)));
}
let first = Coordinate::parse(&start)?;
let last = Coordinate::parse(&end)?;
Ok(Self::Cells(
Coordinate::new(first.column.min(last.column), first.row.min(last.row)),
Coordinate::new(first.column.max(last.column), first.row.max(last.row)),
))
}
pub fn contains(&self, coordinate: Coordinate) -> bool {
match *self {
Self::Cells(start, end) => {
(start.column..=end.column).contains(&coordinate.column)
&& (start.row..=end.row).contains(&coordinate.row)
}
Self::Columns(first, last) => (first..=last).contains(&coordinate.column),
Self::Rows(first, last) => (first..=last).contains(&coordinate.row),
}
}
}
impl std::fmt::Display for CellRange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Self::Cells(start, end) if start == end => write!(f, "{start}"),
Self::Cells(start, end) => write!(f, "{start}:{end}"),
Self::Columns(first, last) => {
write!(
f,
"{}:{}",
string_from_column_index(first),
string_from_column_index(last)
)
}
Self::Rows(first, last) => write!(f, "{first}:{last}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn columns_convert_both_ways() {
assert_eq!(column_index_from_string("A").unwrap(), 1);
assert_eq!(column_index_from_string("Z").unwrap(), 26);
assert_eq!(column_index_from_string("AA").unwrap(), 27);
assert_eq!(column_index_from_string("XFD").unwrap(), 16384);
assert_eq!(string_from_column_index(1), "A");
assert_eq!(string_from_column_index(28), "AB");
assert_eq!(string_from_column_index(16384), "XFD");
}
#[test]
fn ranges_parse() {
assert_eq!(
CellRange::parse("B2:A1").unwrap(),
CellRange::Cells(Coordinate::new(1, 1), Coordinate::new(2, 2))
);
assert_eq!(CellRange::parse("C").unwrap(), CellRange::Columns(3, 3));
assert_eq!(CellRange::parse("2:4").unwrap(), CellRange::Rows(2, 4));
assert_eq!(CellRange::parse("$A$1").unwrap().to_string(), "A1");
}
}