office-rs 0.1.1

A Rust library for reading and writing XML Office files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! 公式管理器
//! 提供公式依赖关系管理、缓存和批量计算功能

use super::*;
use crate::error::{ OfficeError, Result, XlsxError };
use crate::xlsx::cell::{ CellReference, CellValue };
use std::collections::{ HashMap, HashSet, VecDeque };

impl FormulaDependency {
    /// 创建新的依赖关系
    pub fn new(cell: CellReference, depends_on: Vec<CellReference>) -> Self {
        let mut dependent_cells = HashSet::new();
        for dep in depends_on {
            dependent_cells.insert(dep);
        }
        Self {
            formula_cell: cell,
            dependent_cells,
        }
    }
}

impl FormulaManager {
    /// 创建新的公式管理器
    pub fn new(cell_provider: Box<dyn CellProvider>) -> Self {
        Self {
            formulas: HashMap::new(),
            dependencies: HashMap::new(),
            calculator: FormulaCalculator::new(cell_provider),
        }
    }

    /// 设置单元格公式
    pub fn set_formula(&mut self, cell: &CellReference, formula: &str) -> Result<()> {
        // 解析公式
        let expr = parse_formula(formula)?;

        // 提取依赖关系
        let dependencies = self.extract_dependencies(&expr);

        // 存储公式表达式
        self.formulas.insert(cell.clone(), expr);

        // 添加依赖关系
        if !dependencies.is_empty() {
            let dependency = FormulaDependency::new(cell.clone(), dependencies);
            self.dependencies.insert(cell.clone(), dependency);
        }

        Ok(())
    }

    /// 移除单元格公式
    pub fn remove_formula(&mut self, cell: &CellReference) {
        self.formulas.remove(cell);
        self.dependencies.remove(cell);
    }

    /// 计算单元格公式
    pub fn calculate_cell(&mut self, cell: &CellReference) -> Result<FormulaValue> {
        if let Some(expr) = self.formulas.get(cell).cloned() {
            self.calculator.evaluate(&expr)
        } else {
            Err(
                OfficeError::Xlsx(XlsxError::InvalidFormula {
                    formula: format!("No formula found for cell {}", cell.to_a1()),
                })
            )
        }
    }

    /// 批量重新计算
    pub fn recalculate_all(&mut self) -> Result<HashMap<CellReference, FormulaValue>> {
        let mut results = HashMap::new();

        // 计算所有公式
        for cell in self.formulas.keys().cloned().collect::<Vec<_>>() {
            let result = self.calculate_cell(&cell)?;
            results.insert(cell, result);
        }

        Ok(results)
    }

    /// 获取依赖的单元格(简化实现)
    pub fn get_dependents(&self, _cell: &CellReference) -> Vec<CellReference> {
        // 简化实现:返回空列表
        // 完整实现需要维护反向依赖关系
        Vec::new()
    }

    /// 获取被依赖的单元格
    pub fn get_dependencies(&self, cell: &CellReference) -> Vec<CellReference> {
        self.dependencies
            .get(cell)
            .map(|dep| dep.dependent_cells.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// 检查是否存在循环依赖(简化实现)
    pub fn has_circular_dependency(&self, _cell: &CellReference) -> bool {
        // 简化实现:总是返回false
        // 完整实现需要图遍历算法
        false
    }

    /// 标记单元格为脏(简化实现)
    pub fn mark_dirty(&mut self, _cell: &CellReference) {
        // 简化实现:不做任何操作
        // 完整实现需要维护脏标记状态
    }

    /// 清除缓存(简化实现)
    pub fn clear_cache(&mut self) {
        // 简化实现:清除公式和依赖关系
        self.formulas.clear();
        self.dependencies.clear();
    }

    /// 获取计算顺序(简化实现)
    fn get_calculation_order(&self) -> Result<Vec<CellReference>> {
        // 简化实现:返回所有公式单元格的列表
        Ok(self.formulas.keys().cloned().collect())
    }

    /// 提取公式中的依赖关系
    fn extract_dependencies(&self, expr: &FormulaExpression) -> Vec<CellReference> {
        let mut dependencies = Vec::new();
        self.extract_dependencies_recursive(expr, &mut dependencies);
        dependencies
    }

    /// 递归提取依赖关系
    fn extract_dependencies_recursive(
        &self,
        expr: &FormulaExpression,
        dependencies: &mut Vec<CellReference>
    ) {
        match expr {
            FormulaExpression::CellRef(cell_ref) => {
                dependencies.push(cell_ref.clone());
            }

            FormulaExpression::RangeRef(start, end) => {
                // 添加范围内的所有单元格
                for row in start.row..=end.row {
                    for col in start.column..=end.column {
                        dependencies.push(CellReference::new(col, row));
                    }
                }
            }

            FormulaExpression::Function { args, .. } => {
                for arg in args {
                    self.extract_dependencies_recursive(arg, dependencies);
                }
            }

            FormulaExpression::BinaryOp { left, right, .. } => {
                self.extract_dependencies_recursive(left, dependencies);
                self.extract_dependencies_recursive(right, dependencies);
            }

            FormulaExpression::UnaryOp { operand, .. } => {
                self.extract_dependencies_recursive(operand, dependencies);
            }

            FormulaExpression::Constant(_) => {
                // 常量不产生依赖
            }
        }
    }

    // 辅助方法已移除,使用简化实现
}

/// 公式缓存管理器
pub struct FormulaCacheManager {
    cache: HashMap<String, FormulaValue>,
    max_size: usize,
    access_order: VecDeque<String>,
}

impl FormulaCacheManager {
    /// 创建新的缓存管理器
    pub fn new(max_size: usize) -> Self {
        Self {
            cache: HashMap::new(),
            max_size,
            access_order: VecDeque::new(),
        }
    }

    /// 获取缓存值
    pub fn get(&mut self, key: &str) -> Option<&FormulaValue> {
        if self.cache.contains_key(key) {
            // 更新访问顺序
            self.access_order.retain(|k| k != key);
            self.access_order.push_back(key.to_string());

            self.cache.get(key)
        } else {
            None
        }
    }

    /// 设置缓存值
    pub fn set(&mut self, key: String, value: FormulaValue) {
        // 如果已存在,更新值和访问顺序
        if self.cache.contains_key(&key) {
            self.cache.insert(key.clone(), value);
            self.access_order.retain(|k| k != &key);
            self.access_order.push_back(key);
            return;
        }

        // 如果缓存已满,移除最久未访问的项
        if self.cache.len() >= self.max_size {
            if let Some(oldest_key) = self.access_order.pop_front() {
                self.cache.remove(&oldest_key);
            }
        }

        // 添加新项
        self.cache.insert(key.clone(), value);
        self.access_order.push_back(key);
    }

    /// 移除缓存项
    pub fn remove(&mut self, key: &str) {
        self.cache.remove(key);
        self.access_order.retain(|k| k != key);
    }

    /// 清空缓存
    pub fn clear(&mut self) {
        self.cache.clear();
        self.access_order.clear();
    }

    /// 获取缓存大小
    pub fn size(&self) -> usize {
        self.cache.len()
    }

    /// 获取缓存命中率统计
    pub fn get_stats(&self) -> CacheStats {
        CacheStats {
            size: self.cache.len(),
            max_size: self.max_size,
            // 这里可以添加更多统计信息
        }
    }
}

/// 缓存统计信息
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub size: usize,
    pub max_size: usize,
}

/// 公式性能分析器
pub struct FormulaProfiler {
    execution_times: HashMap<String, Vec<std::time::Duration>>,
    call_counts: HashMap<String, usize>,
}

impl FormulaProfiler {
    /// 创建新的性能分析器
    pub fn new() -> Self {
        Self {
            execution_times: HashMap::new(),
            call_counts: HashMap::new(),
        }
    }

    /// 记录函数执行时间
    pub fn record_execution(&mut self, function_name: &str, duration: std::time::Duration) {
        self.execution_times
            .entry(function_name.to_string())
            .or_insert_with(Vec::new)
            .push(duration);

        *self.call_counts.entry(function_name.to_string()).or_insert(0) += 1;
    }

    /// 获取函数平均执行时间
    pub fn get_average_time(&self, function_name: &str) -> Option<std::time::Duration> {
        if let Some(times) = self.execution_times.get(function_name) {
            if !times.is_empty() {
                let total: std::time::Duration = times.iter().sum();
                Some(total / (times.len() as u32))
            } else {
                None
            }
        } else {
            None
        }
    }

    /// 获取函数调用次数
    pub fn get_call_count(&self, function_name: &str) -> usize {
        self.call_counts.get(function_name).copied().unwrap_or(0)
    }

    /// 获取性能报告
    pub fn get_performance_report(&self) -> Vec<PerformanceReport> {
        let mut reports = Vec::new();

        for (function_name, times) in &self.execution_times {
            if !times.is_empty() {
                let total: std::time::Duration = times.iter().sum();
                let average = total / (times.len() as u32);
                let min = *times.iter().min().unwrap();
                let max = *times.iter().max().unwrap();
                let call_count = self.get_call_count(function_name);

                reports.push(PerformanceReport {
                    function_name: function_name.clone(),
                    call_count,
                    total_time: total,
                    average_time: average,
                    min_time: min,
                    max_time: max,
                });
            }
        }

        // 按总执行时间排序
        reports.sort_by(|a, b| b.total_time.cmp(&a.total_time));
        reports
    }

    /// 清除统计数据
    pub fn clear(&mut self) {
        self.execution_times.clear();
        self.call_counts.clear();
    }
}

/// 性能报告
#[derive(Debug, Clone)]
pub struct PerformanceReport {
    pub function_name: String,
    pub call_count: usize,
    pub total_time: std::time::Duration,
    pub average_time: std::time::Duration,
    pub min_time: std::time::Duration,
    pub max_time: std::time::Duration,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::xlsx::cell::CellValue;

    struct MockCellProvider;

    impl CellProvider for MockCellProvider {
        fn get_cell_value(&self, _reference: &CellReference) -> Result<CellValue> {
            Ok(CellValue::Number(10.0))
        }

        fn get_range_values(
            &self,
            _start: &CellReference,
            _end: &CellReference
        ) -> Result<Vec<Vec<CellValue>>> {
            Ok(vec![vec![CellValue::Number(10.0)]])
        }
    }

    #[test]
    fn test_formula_manager_dependencies() {
        let provider = Box::new(MockCellProvider);
        let mut manager = FormulaManager::new(provider);

        let cell_a1 = CellReference::new(0, 0); // A1
        let cell_b1 = CellReference::new(1, 0); // B1

        // 设置公式 A1 = B1 + 1
        manager.set_formula(&cell_a1, "=B1+1").unwrap();

        // 检查依赖关系
        let deps = manager.get_dependencies(&cell_a1);
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0], cell_b1);

        // 检查反向依赖关系(简化实现总是返回空列表)
        let dependents = manager.get_dependents(&cell_b1);
        assert_eq!(dependents.len(), 0);
    }

    #[test]
    fn test_formula_storage() {
        let provider = Box::new(MockCellProvider);
        let mut manager = FormulaManager::new(provider);
        let cell_a1 = CellReference::new(0, 0); // A1

        // 设置简单公式
        manager.set_formula(&cell_a1, "=42").unwrap();

        // 验证公式已存储
        assert!(manager.formulas.contains_key(&cell_a1));

        // 移除公式
        manager.remove_formula(&cell_a1);
        assert!(!manager.formulas.contains_key(&cell_a1));
    }

    #[test]
    fn test_cache_manager() {
        let mut cache = FormulaCacheManager::new(2);

        // 添加缓存项
        cache.set("key1".to_string(), FormulaValue::Number(1.0));
        cache.set("key2".to_string(), FormulaValue::Number(2.0));

        // 检查缓存
        assert!(cache.get("key1").is_some());
        assert!(cache.get("key2").is_some());

        // 添加第三个项,应该移除最久未访问的项
        cache.set("key3".to_string(), FormulaValue::Number(3.0));

        // key1应该被移除(最久未访问)
        assert!(cache.get("key1").is_none());
        assert!(cache.get("key2").is_some());
        assert!(cache.get("key3").is_some());
    }

    #[test]
    fn test_profiler() {
        let mut profiler = FormulaProfiler::new();

        // 记录执行时间
        profiler.record_execution("SUM", std::time::Duration::from_millis(10));
        profiler.record_execution("SUM", std::time::Duration::from_millis(20));
        profiler.record_execution("AVERAGE", std::time::Duration::from_millis(15));

        // 检查统计
        assert_eq!(profiler.get_call_count("SUM"), 2);
        assert_eq!(profiler.get_call_count("AVERAGE"), 1);

        let avg_time = profiler.get_average_time("SUM").unwrap();
        assert_eq!(avg_time, std::time::Duration::from_millis(15));

        // 测试性能报告
        let reports = profiler.get_performance_report();
        assert_eq!(reports.len(), 2);
    }
}