use crate::header::excel_column_name;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MergeRange {
pub first_row: u32,
pub last_row: u32,
pub first_col: u16,
pub last_col: u16,
}
impl MergeRange {
pub fn contains(&self, row: u32, col: u16) -> bool {
row >= self.first_row && row <= self.last_row && col >= self.first_col && col <= self.last_col
}
pub fn is_single_row(&self) -> bool {
self.first_row == self.last_row
}
pub fn is_single_col(&self) -> bool {
self.first_col == self.last_col
}
pub fn is_anchor(&self, row: u32, col: u16) -> bool {
row == self.first_row && col == self.first_col
}
pub fn len(&self) -> u64 {
(self.last_row - self.first_row + 1) as u64 * (self.last_col - self.first_col + 1) as u64
}
pub fn is_empty(&self) -> bool {
false
}
pub fn to_a1(&self) -> String {
format!(
"{}{}:{}{}",
excel_column_name(self.first_col),
self.first_row,
excel_column_name(self.last_col),
self.last_row
)
}
}
pub(crate) fn parse_range(s: &str) -> Option<MergeRange> {
let (a, b) = s.split_once(':')?;
let (c1, r1) = parse_ref(a)?;
let (c2, r2) = parse_ref(b)?;
Some(MergeRange {
first_row: r1.min(r2),
last_row: r1.max(r2),
first_col: c1.min(c2),
last_col: c1.max(c2),
})
}
pub(crate) fn parse_ref(s: &str) -> Option<(u16, u32)> {
let mut col: u32 = 0;
let mut row: u32 = 0;
let mut has_col = false;
let mut has_row = false;
for ch in s.chars() {
match ch {
'$' => {}
c if c.is_ascii_alphabetic() => {
has_col = true;
col = col * 26 + (c.to_ascii_uppercase() as u32 - 'A' as u32 + 1);
}
c if c.is_ascii_digit() => {
has_row = true;
row = row * 10 + (c as u32 - '0' as u32);
}
_ => return None,
}
}
if has_col && has_row && col > 0 && row > 0 && col <= u16::MAX as u32 {
Some(((col - 1) as u16, row))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_range() {
assert_eq!(
parse_range("A1:C3"),
Some(MergeRange {
first_row: 1,
last_row: 3,
first_col: 0,
last_col: 2
})
);
assert_eq!(
parse_range("$C$3:$A$1"),
Some(MergeRange {
first_row: 1,
last_row: 3,
first_col: 0,
last_col: 2
})
);
assert_eq!(parse_range("B2"), None);
assert_eq!(parse_range("garbage"), None);
}
#[test]
fn test_range_helpers() {
let r = MergeRange {
first_row: 2,
last_row: 4,
first_col: 1,
last_col: 3,
};
assert!(r.contains(3, 2));
assert!(!r.contains(1, 2));
assert!(r.is_anchor(2, 1));
assert!(!r.is_anchor(3, 1));
assert_eq!(r.len(), 9);
assert_eq!(r.to_a1(), "B2:D4");
}
}