use crate::exceptions::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedRange {
pub name: String,
pub destinations: Vec<(usize, String)>,
pub scope: Option<usize>,
}
impl NamedRange {
pub fn new(
name: impl Into<String>,
destinations: Vec<(usize, String)>,
scope: Option<usize>,
) -> Self {
NamedRange {
name: name.into(),
destinations,
scope,
}
}
pub fn to_string_with_titles(&self, titles: &[String]) -> String {
self.destinations
.iter()
.map(|(index, range)| {
let title = titles.get(*index).cloned().unwrap_or_default();
format!("{title}!{range}")
})
.collect::<Vec<_>>()
.join(",")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedRangeContainingValue {
pub name: String,
pub value: String,
pub scope: Option<usize>,
}
impl NamedRangeContainingValue {
pub fn new(name: impl Into<String>, value: impl Into<String>, scope: Option<usize>) -> Self {
NamedRangeContainingValue {
name: name.into(),
value: value.into(),
scope,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DefinedName {
Range(NamedRange),
Value(NamedRangeContainingValue),
}
impl DefinedName {
pub fn name(&self) -> &str {
match self {
DefinedName::Range(r) => &r.name,
DefinedName::Value(v) => &v.name,
}
}
pub fn scope(&self) -> Option<usize> {
match self {
DefinedName::Range(r) => r.scope,
DefinedName::Value(v) => v.scope,
}
}
}
pub fn split_named_range(range_string: &str) -> Result<Vec<(String, String)>> {
let mut destinations = Vec::new();
for part in split_outside_quotes(range_string) {
let part = part.trim();
if part.is_empty() {
continue;
}
let (sheet, range) = parse_destination(part)?;
destinations.push((sheet, range));
}
if destinations.is_empty() {
return Err(Error::NamedRange(format!(
"Invalid named range string: \"{range_string}\""
)));
}
Ok(destinations)
}
fn split_outside_quotes(input: &str) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
let mut in_quotes = false;
let mut chars = input.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\'' => {
if chars.peek() == Some(&'\'') {
current.push(chars.next().expect("peeked quote"));
current.push('\'');
} else {
in_quotes = !in_quotes;
current.push(ch);
}
}
',' if !in_quotes => {
parts.push(std::mem::take(&mut current));
}
_ => current.push(ch),
}
}
parts.push(current);
parts
}
fn parse_destination(part: &str) -> Result<(String, String)> {
let (sheet, range) = split_sheet_and_range(part)?;
if !is_valid_range(&range) {
return Err(Error::NamedRange(format!(
"Invalid named range string: \"{part}\""
)));
}
Ok((sheet, range))
}
fn split_sheet_and_range(part: &str) -> Result<(String, String)> {
if let Some(rest) = part.strip_prefix('\'') {
let bytes = rest.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'\'' {
if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
i += 2;
continue;
}
let sheet = rest[..i].replace("''", "'");
let after = &rest[i + 1..];
let range = after.strip_prefix('!').ok_or_else(|| {
Error::NamedRange(format!("Invalid named range string: \"{part}\""))
})?;
return Ok((sheet, range.to_string()));
}
i += 1;
}
return Err(Error::NamedRange(format!(
"Invalid named range string: \"{part}\""
)));
}
match part.split_once('!') {
Some((sheet, range)) => Ok((sheet.to_string(), range.to_string())),
None => Err(Error::NamedRange(format!(
"Invalid named range string: \"{part}\""
))),
}
}
fn is_valid_range(range: &str) -> bool {
if range.is_empty() {
return true;
}
let (first, second) = match range.split_once(':') {
Some((a, b)) => (a, Some(b)),
None => (range, None),
};
if !is_cell_like(first) {
return false;
}
match second {
Some(s) => is_cell_like(s),
None => true,
}
}
fn is_cell_like(token: &str) -> bool {
if token.is_empty() {
return true;
}
let rest = token.strip_prefix('$').unwrap_or(token);
match rest.split_once('$') {
Some((letters, digits)) => {
letters.chars().all(|c| c.is_ascii_alphabetic())
&& digits.chars().all(|c| c.is_ascii_digit())
}
None => {
let split = rest
.char_indices()
.find(|(_, c)| c.is_ascii_digit())
.map(|(i, _)| i)
.unwrap_or(rest.len());
let (letters, digits) = rest.split_at(split);
letters.chars().all(|c| c.is_ascii_alphabetic())
&& digits.chars().all(|c| c.is_ascii_digit())
}
}
}
pub fn refers_to_range(range_string: &str) -> bool {
if range_string.is_empty() {
return false;
}
split_named_range(range_string).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_quoted_sheet() {
assert_eq!(
split_named_range("'My Sheet'!$D$8").unwrap(),
vec![("My Sheet".to_string(), "$D$8".to_string())]
);
}
#[test]
fn splits_unquoted_sheet() {
assert_eq!(
split_named_range("HYPOTHESES!$B$3:$L$3").unwrap(),
vec![("HYPOTHESES".to_string(), "$B$3:$L$3".to_string())]
);
}
#[test]
fn rejects_missing_bang() {
assert!(matches!(
split_named_range("HYPOTHESES$B$3"),
Err(Error::NamedRange(_))
));
}
#[test]
fn handles_commas_and_commas_in_quotes() {
let result = split_named_range(
"'My Sheet with a , and '''!$U$16:$U$24,'My Sheet with a , and '''!$V$28:$V$36",
)
.unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result[0].0, "My Sheet with a , and '");
assert_eq!(result[0].1, "$U$16:$U$24");
assert_eq!(result[1].0, "My Sheet with a , and '");
assert_eq!(result[1].1, "$V$28:$V$36");
}
#[test]
fn refers_to_range_detects_shape() {
assert!(refers_to_range("'My Sheet'!$D$8"));
assert!(refers_to_range("SHEET!$A$1:$B$2"));
assert!(!refers_to_range("9.99"));
assert!(!refers_to_range("NA()"));
assert!(!refers_to_range(""));
}
#[test]
fn bare_sheet_name_is_a_range() {
assert_eq!(
split_named_range("Sheet1!").unwrap(),
vec![("Sheet1".to_string(), String::new())]
);
}
#[test]
fn rendering_uses_titles() {
let titles = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let range = NamedRange::new(
"MyRef",
vec![(0, "$A$1".to_string()), (1, "$B$2".to_string())],
None,
);
assert_eq!(
range.to_string_with_titles(&titles),
"Sheet1!$A$1,Sheet2!$B$2"
);
}
}