use crate::qualified::Prepared;
use crate::CellId;
use formula_lang::{CellResolver, ExcelError, Value};
use std::string::String;
pub(crate) struct EngineResolver<'a> {
engine: &'a crate::Engine,
owner: &'a str,
prepared: &'a Prepared,
}
impl<'a> EngineResolver<'a> {
pub(crate) fn new(engine: &'a crate::Engine, owner: &'a str, prepared: &'a Prepared) -> Self {
Self {
engine,
owner,
prepared,
}
}
fn local_key(&self, col: u32, row: u32) -> CellId {
(String::from(self.owner), row - 1, col - 1)
}
fn stub_target(&self, col: u32, row: u32) -> Option<(CellId, u64)> {
let lin = u64::from(row - 1) * GRID_W + u64::from(col - 1);
let (stub, off) = self.prepared.resolve_stub(lin)?;
let target_sheet = &stub.target.0;
let target = (
String::clone(target_sheet),
stub.target.1 + u32::try_from(off / GRID_W).unwrap_or(u32::MAX),
stub.target.2 + u32::try_from(off % GRID_W).unwrap_or(u32::MAX),
);
Some((target, off))
}
fn read(&self, col: u32, row: u32) -> Value {
if let Some((target, _)) = self.stub_target(col, row) {
if !self.engine.has_sheet(&target.0) {
return Value::Error(ExcelError::Ref);
}
return self.engine.cached(&target).unwrap_or(Value::Empty);
}
self.engine
.cached(&self.local_key(col, row))
.unwrap_or(Value::Empty)
}
}
impl CellResolver for EngineResolver<'_> {
fn get(&self, col: u32, row: u32) -> Option<Value> {
debug_assert!(col >= 1 && row >= 1);
if col == 0 || row == 0 {
return None;
}
Some(self.read(col, row))
}
fn get_range(&self, start: (u32, u32), end: (u32, u32)) -> Vec<Value> {
let (c0, r0, c1, r1) = formula_lang::ast::normalize_range(
&formula_lang::ast::CellRef::new(start.0, start.1),
&formula_lang::ast::CellRef::new(end.0, end.1),
);
let mut out = Vec::with_capacity(((c1 - c0 + 1) * (r1 - r0 + 1)) as usize);
for row in r0..=r1 {
for col in c0..=c1 {
out.push(self.read(col, row));
}
}
out
}
}
const GRID_W: u64 = 16_384;