tazor 1.0.2

Tazor is Rust library implementing a calculator based on mathematical expression
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Tazor
//!
//! Tazor is Rust library implementing a calculator based on mathematical expression
//!

pub mod expression;

use expression::Expression;

use std::collections::HashMap;

/// Evaluate mathematical expression and store user-define variable and function to reuse it after.
///
/// The calculator is based on Evaluator which is a function taking a string, representing a mathematical expression
/// and return the value of evaluation on 64-bit float.
///
/// # Example with simple expression
/// ```
/// use tazor;
///
/// fn evaluate(expression: &str) -> Result<f64, String> {
///     if expression.is_empty() {
///         return Err(String::from("Expression is empty"));
///     }
///
///     return Ok(expression.len() as f64);
/// }
///
/// let mut calculator = tazor::Calculator::new(evaluate);
///
/// let expression: String = String::from("1 + 1");
///
/// match calculator.process(expression.as_str()) {
///     Ok(str_result) => println!("{}", str_result),
///     Err(_) => assert!(false),
/// }
///
/// ```
///
/// # Example with expression defining variables and use it in other expression
/// ```
/// use tazor;
///
/// fn evaluate(expression: &str) -> Result<f64, String> {
///     if expression.is_empty() {
///         return Err(String::from("Expression is empty"));
///     }
///
///     return Ok(expression.len() as f64);
/// }
///
/// let mut calculator = tazor::Calculator::new(evaluate);
///
/// let variable_x: String = String::from("x = 4.5 * 23.67");
/// assert!(calculator.process(variable_x.as_str()).is_ok());
///
/// let variable_y: String = String::from("y = 43.5 + 2.75");
/// assert!(calculator.process(variable_y.as_str()).is_ok());
///
/// let expression: String = String::from("x * x + y * y");
///
/// match calculator.process(expression.as_str()) {
///     Ok(str_result) => println!("{}", str_result),
///     Err(_) => assert!(false),
/// }
///
/// ```
///
/// # Example with expression defining a variable, a function and use it in other expression
/// ```
/// use tazor;
///
/// fn evaluate(expression: &str) -> Result<f64, String> {
///     if expression.is_empty() {
///         return Err(String::from("Expression is empty"));
///     }
///
///     return Ok(expression.len() as f64);
/// }
///
/// let mut calculator = tazor::Calculator::new(evaluate);
///
/// let factor: String = String::from("factor = 4.5 * 23.67");
/// assert!(calculator.process(factor.as_str()).is_ok());
///
/// let function: String = String::from("f: x, y = factor * (x * x + y * y)");
/// assert!(calculator.process(function.as_str()).is_ok());
///
/// let expression: String = String::from("f(1,75, 2.54) + 2.43");
///
/// match calculator.process(expression.as_str()) {
///     Ok(str_result) => println!("{}", str_result),
///     Err(_) => assert!(false),
/// }
///
/// ```
///
pub struct Calculator<Evaluator>
where
    Evaluator: Fn(&str) -> Result<f64, String>,
{
    evaluator: Evaluator,            // mathematical expression evaluator
    variables: HashMap<String, f64>, // map to store custom variable defined by user, key is name of variable and value is its evaluation
    functions: HashMap<String, (Vec<String>, String)>, // map to store custom function defined by user, key is name of function and value is its expression (variables, definition)
}

impl<Evaluator> Calculator<Evaluator>
where
    Evaluator: Fn(&str) -> Result<f64, String>,
{
    /// Construct a calculator given an evaluator in argument
    pub fn new(evaluator: Evaluator) -> Self {
        return Self {
            evaluator,
            variables: HashMap::with_capacity(25),
            functions: HashMap::with_capacity(25),
        };
    }

    /// Process an expression
    ///
    /// If error occurs during process, an error message is stored in string contained in Result output.
    ///
    /// Otherwise, the Result output contains string which represent result according to kind of expression:
    ///    - raw => `last = evaluated_expression`
    ///    - variable => `variable_name = variable_value`
    ///    - function => `function_name(function_variables) = function_definition`
    ///
    pub fn process(&mut self, expression_str: &str) -> Result<String, String> {
        let mut expression: Expression = Expression::new(expression_str);

        expression.replace_functions(&self.functions)?;
        expression.replace_variables(&self.variables);

        let result: String = match expression {
            Expression::Raw(raw_expression) => {
                let value: f64 = (self.evaluator)(&raw_expression.as_str())?;

                let raw_expression_result: String = format!("last = {}", value);
                self.variables.insert(String::from("last"), value);

                raw_expression_result
            }
            Expression::Variable(name, definition) => {
                let value: f64 = (self.evaluator)(&definition.as_str())?;

                let variable_result: String = format!("{} = {}", name, value);
                self.variables.insert(name, value);

                variable_result
            }
            Expression::Function(name, variables, definition) => {
                let function_result: String =
                    format!("{}({}) = {}", name, variables.join(", "), definition);

                self.functions.insert(name, (variables, definition));

                function_result
            }
        };

        return Ok(result);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Define mock evaluator for units tests
    fn evaluate(expression: &str) -> Result<f64, String> {
        if expression.is_empty() {
            return Err(String::from("Expression is empty"));
        }

        return Ok(expression.len() as f64);
    }

    #[test]
    fn test_calculator_new() {
        let calculator = Calculator::new(evaluate);

        assert!(calculator.variables.capacity() > 0);

        let empty_expression: String = String::default();
        assert!((calculator.evaluator)(empty_expression.as_str()).is_err());

        let expression: String = String::from("taz");
        let result: Result<f64, String> = (calculator.evaluator)(expression.as_str());

        assert!(result.is_ok());
        assert_eq!(result.unwrap() as usize, expression.len())
    }

    #[test]
    fn test_calculator_process_raw_expression() {
        let mut calculator = Calculator::new(evaluate);

        let expression: String = String::from("1 + 1");

        match calculator.process(expression.as_str()) {
            Ok(str_result) => {
                let variable_name: String = String::from("last");
                let variable_value: f64 = expression.len() as f64;

                let str_reference: String = format!("{} = {}", variable_name, variable_value);
                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.variables.len(), 1);
                assert!(calculator.variables.contains_key(&variable_name));
                assert_eq!(calculator.variables[&variable_name], variable_value);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_several_raw_expression() {
        let mut calculator = Calculator::new(evaluate);

        // Evaluate first expression
        let first_expression: String = String::from("1 + 1");

        let variable_name: String = String::from("last");

        match calculator.process(first_expression.as_str()) {
            Ok(str_result) => {
                let variable_value: f64 = first_expression.len() as f64;

                let str_reference: String = format!("{} = {}", variable_name, variable_value);
                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.variables.len(), 1);
                assert!(calculator.variables.contains_key(&variable_name));
                assert_eq!(calculator.variables[&variable_name], variable_value);
            }
            Err(_) => assert!(false),
        }

        // Evaluate second expresion
        // The value of variable named 'last' must be replaced by value of second expression
        let second_expression: String = String::from("1 + 1 + 3");

        match calculator.process(second_expression.as_str()) {
            Ok(str_result) => {
                let variable_value: f64 = second_expression.len() as f64;

                let str_reference: String = format!("{} = {}", variable_name, variable_value);
                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.variables.len(), 1);
                assert!(calculator.variables.contains_key(&variable_name));
                assert_eq!(calculator.variables[&variable_name], variable_value);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_variable_expression() {
        let mut calculator = Calculator::new(evaluate);

        let variable_name: String = String::from("x");
        let variable_definition: String = String::from("1 + 1");

        let expression: String = format!("{} = {}", variable_name, variable_definition);

        match calculator.process(expression.as_str()) {
            Ok(str_result) => {
                let variable_value: f64 = variable_definition.len() as f64;

                let str_reference: String = format!("{} = {}", variable_name, variable_value);
                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.variables.len(), 1);
                assert!(calculator.variables.contains_key(&variable_name));
                assert_eq!(calculator.variables[&variable_name], variable_value);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_several_variable_expression() {
        let mut calculator = Calculator::new(evaluate);

        let first_variable_name: String = String::from("x");
        let first_variable_definition: String = String::from("1 + 1");

        let first_expression: String =
            format!("{} = {}", first_variable_name, first_variable_definition);

        match calculator.process(first_expression.as_str()) {
            Ok(str_result) => {
                let variable_value: f64 = first_variable_definition.len() as f64;

                let str_reference: String = format!("{} = {}", first_variable_name, variable_value);
                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.variables.len(), 1);
                assert!(calculator.variables.contains_key(&first_variable_name));
                assert_eq!(calculator.variables[&first_variable_name], variable_value);
            }
            Err(_) => assert!(false),
        }

        let second_variable_name: String = String::from("y");
        let second_variable_definition: String = String::from("9 + 1");

        let second_expression: String =
            format!("{} = {}", second_variable_name, second_variable_definition);

        match calculator.process(second_expression.as_str()) {
            Ok(str_result) => {
                let variable_value: f64 = second_variable_definition.len() as f64;

                let str_reference: String =
                    format!("{} = {}", second_variable_name, variable_value);

                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.variables.len(), 2);
                assert!(calculator.variables.contains_key(&second_variable_name));
                assert_eq!(calculator.variables[&second_variable_name], variable_value);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_expression_with_variables() {
        let mut calculator = Calculator::new(evaluate);

        let first_variable_name: String = String::from("x");
        let first_variable_definition: String = String::from("1 + 1");

        let first_expression: String =
            format!("{} = {}", first_variable_name, first_variable_definition);

        let first_process_result = calculator.process(first_expression.as_str());
        assert!(first_process_result.is_ok());

        let second_variable_name: String = String::from("y");
        let second_variable_definition: String = String::from("97 + 1");

        let second_expression: String =
            format!("{} = {}", second_variable_name, second_variable_definition);

        let second_process_result = calculator.process(second_expression.as_str());
        assert!(second_process_result.is_ok());

        let variable_name: String = String::from("distance");
        let variable_definition: String = String::from("x + y");

        let expression: String = format!("{} = {}", variable_name, variable_definition);

        match calculator.process(expression.as_str()) {
            Ok(str_result) => {
                let variable_value: f64 = (first_variable_definition.len().to_string().len()
                    + second_variable_definition.len().to_string().len()
                    + 3) as f64;

                let str_reference: String = format!("{} = {}", variable_name, variable_value);
                assert_eq!(str_result, str_reference);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_function_expression() {
        let mut calculator = Calculator::new(evaluate);

        let function_name: String = String::from("distance");
        let function_variables: Vec<String> = vec![String::from("x"), String::from("y")];
        let function_definition: String = format!(
            "{} * {} + {} * {}",
            function_variables[0],
            function_variables[0],
            function_variables[1],
            function_variables[1]
        );

        let expression: String = format!(
            "{}: {}, {} = {}",
            function_name, function_variables[0], function_variables[1], function_definition
        );

        match calculator.process(expression.as_str()) {
            Ok(str_result) => {
                let str_reference: String = format!(
                    "{}({}) = {}",
                    function_name,
                    function_variables.join(", "),
                    function_definition
                );

                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.functions.len(), 1);
                assert!(calculator.functions.contains_key(&function_name));
                assert_eq!(
                    calculator.functions[&function_name],
                    (function_variables, function_definition)
                );
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_several_function_expression() {
        let mut calculator = Calculator::new(evaluate);

        let first_function_name: String = String::from("distance");
        let first_function_variables: Vec<String> = vec![String::from("x"), String::from("y")];
        let first_function_definition: String = format!(
            "{} * {} + {} * {}",
            first_function_variables[0],
            first_function_variables[0],
            first_function_variables[1],
            first_function_variables[1]
        );

        let first_expression: String = format!(
            "{}: {}, {} = {}",
            first_function_name,
            first_function_variables[0],
            first_function_variables[1],
            first_function_definition
        );

        match calculator.process(first_expression.as_str()) {
            Ok(str_result) => {
                let str_reference: String = format!(
                    "{}({}) = {}",
                    first_function_name,
                    first_function_variables.join(", "),
                    first_function_definition
                );

                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.functions.len(), 1);
                assert!(calculator.functions.contains_key(&first_function_name));
                assert_eq!(
                    calculator.functions[&first_function_name],
                    (first_function_variables, first_function_definition)
                );
            }
            Err(_) => assert!(false),
        }

        let second_function_name: String = String::from("velocity");
        let second_function_variables: Vec<String> =
            vec![String::from("distance"), String::from("time")];

        let second_function_definition: String = format!(
            "{} / {}",
            second_function_variables[0], second_function_variables[1]
        );

        let second_expression: String = format!(
            "{}: {}, {} = {}",
            second_function_name,
            second_function_variables[0],
            second_function_variables[1],
            second_function_definition
        );

        match calculator.process(second_expression.as_str()) {
            Ok(str_result) => {
                let str_reference: String = format!(
                    "{}({}) = {}",
                    second_function_name,
                    second_function_variables.join(", "),
                    second_function_definition
                );

                assert_eq!(str_result, str_reference);

                assert_eq!(calculator.functions.len(), 2);
                assert!(calculator.functions.contains_key(&second_function_name));
                assert_eq!(
                    calculator.functions[&second_function_name],
                    (second_function_variables, second_function_definition)
                );
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_expression_with_functions() {
        let mut calculator = Calculator::new(evaluate);

        let first_function_name: String = String::from("distance");
        let first_function_variables: Vec<String> = vec![String::from("x"), String::from("y")];
        let first_function_definition: String = format!(
            "{} * {} + {} * {}",
            first_function_variables[0],
            first_function_variables[0],
            first_function_variables[1],
            first_function_variables[1]
        );

        let first_function_expression: String = format!(
            "{}: {}, {} = {}",
            first_function_name,
            first_function_variables[0],
            first_function_variables[1],
            first_function_definition
        );

        assert!(calculator
            .process(first_function_expression.as_str())
            .is_ok());

        let second_function_name: String = String::from("velocity");
        let second_function_variables: Vec<String> =
            vec![String::from("distance"), String::from("time")];

        let second_function_definition: String = format!(
            "{} / {}",
            second_function_variables[0], second_function_variables[1]
        );

        let second_function_expression: String = format!(
            "{}: {}, {} = {}",
            second_function_name,
            second_function_variables[0],
            second_function_variables[1],
            second_function_definition
        );

        assert!(calculator
            .process(second_function_expression.as_str())
            .is_ok());

        let expression: String = format!(
            "3.14 * {}(6.89, 5.43) - {}(2.4, 4.3) + (2 * 3 - 7)",
            second_function_name, first_function_name
        );

        let replaced_expression: String =
            String::from("3.14 * (6.89 / 5.43) - (2.4 * 2.4 + 4.3 * 4.3) + (2 * 3 - 7)");

        match calculator.process(expression.as_str()) {
            Ok(str_result) => {
                let str_reference: String = format!("last = {}", replaced_expression.len());
                assert_eq!(str_result, str_reference);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_expression_with_variables_and_functions() {
        let mut calculator = Calculator::new(evaluate);

        let first_function_name: String = String::from("distance");
        let first_function_variables: Vec<String> = vec![String::from("x"), String::from("y")];
        let first_function_definition: String = format!(
            "{} * {} + {} * {}",
            first_function_variables[0],
            first_function_variables[0],
            first_function_variables[1],
            first_function_variables[1]
        );

        let first_function_expression: String = format!(
            "{}: {}, {} = {}",
            first_function_name,
            first_function_variables[0],
            first_function_variables[1],
            first_function_definition
        );

        assert!(calculator
            .process(first_function_expression.as_str())
            .is_ok());

        let second_function_name: String = String::from("velocity");
        let second_function_variables: Vec<String> =
            vec![String::from("distance"), String::from("time")];

        let second_function_definition: String = format!(
            "{} / {}",
            second_function_variables[0], second_function_variables[1]
        );

        let second_function_expression: String = format!(
            "{}: {}, {} = {}",
            second_function_name,
            second_function_variables[0],
            second_function_variables[1],
            second_function_definition
        );

        assert!(calculator
            .process(second_function_expression.as_str())
            .is_ok());

        let first_variable_name: String = String::from("x");
        let first_variable_definition: String = String::from("1 + 1");

        let first_expression: String =
            format!("{} = {}", first_variable_name, first_variable_definition);

        assert!(calculator.process(first_expression.as_str()).is_ok());

        let second_variable_name: String = String::from("y");
        let second_variable_definition: String = String::from("97 + 1");

        let second_expression: String =
            format!("{} = {}", second_variable_name, second_variable_definition);

        assert!(calculator.process(second_expression.as_str()).is_ok());

        let expression: String = format!(
            "3.14 * {}({}, {}) - {}(2.4, 4.3) + (2 * 3 - 7)",
            second_function_name, first_variable_name, second_variable_name, first_function_name
        );

        let replaced_expression: String = format!(
            "3.14 * ({} / {}) - (2.4 * 2.4 + 4.3 * 4.3) + (2 * 3 - 7)",
            first_variable_definition.len(),
            second_variable_definition.len()
        );

        match calculator.process(expression.as_str()) {
            Ok(str_result) => {
                let str_reference: String = format!("last = {}", replaced_expression.len());
                assert_eq!(str_result, str_reference);
            }
            Err(_) => assert!(false),
        }
    }

    #[test]
    fn test_calculator_process_expression_with_variables_and_function_variables_equal_to_variables()
    {
        let mut calculator = Calculator::new(evaluate);

        let first_variable_name: String = String::from("x");
        let first_variable_definition: String = String::from("1 + 1");

        let first_expression: String =
            format!("{} = {}", first_variable_name, first_variable_definition);

        assert!(calculator.process(first_expression.as_str()).is_ok());

        let second_variable_name: String = String::from("y");
        let second_variables_definition: String = String::from("2 * 5");

        let second_expression: String =
            format!("{} = {}", second_variable_name, second_variables_definition);

        assert!(calculator.process(second_expression.as_str()).is_ok());

        let function_name: String = String::from("distance");
        let function_variables: Vec<String> = vec![String::from("x"), String::from("y")];
        let function_definition: String = format!(
            "{} * {} + {} * {}",
            function_variables[0],
            function_variables[0],
            function_variables[1],
            function_variables[1]
        );

        let function_expression: String = format!(
            "{}: {}, {} = {}",
            function_name, function_variables[0], function_variables[1], function_definition
        );

        assert!(calculator.process(function_expression.as_str()).is_ok());
        assert!(function_definition == calculator.functions[&function_name].1);
    }
}