Skip to main content

json_fibonacci/
json_fibonacci.rs

1//! Fibonacci sequence generator using JSON format for storage.
2//! This program maintains a sequence of Fibonacci numbers in a JSON file,
3//! reading the existing sequence and appending the next number on each run.
4
5use babbel_json::{FileDestination, FileSource, Node, Numeric, parse, stringify};
6use std::path::Path;
7
8/// Reads a Fibonacci sequence from a JSON-encoded file.
9/// If the file doesn't exist, initializes a new sequence starting with [1, 1].
10///
11/// # Arguments
12/// * `file_path` - Path to the JSON file containing the sequence
13///
14/// # Returns
15/// * `Ok(Node)` - A Node::List containing the sequence
16/// * `Err(String)` - Error message if reading or parsing fails
17fn read_sequence(file_path: &Path) -> Result<Node, String> {
18    // Initialize with the default sequence if the file doesn't exist
19    if !file_path.exists() {
20        return Ok(Node::Array(vec![
21            Node::Number(Numeric::Integer(1)),
22            Node::Number(Numeric::Integer(1)),
23        ]));
24    }
25
26    // Try to open and parse the existing file
27    match FileSource::new(file_path) {
28        Ok(mut file) => match parse(&mut file) {
29            Ok(Node::Array(list)) => Ok(Node::Array(list)),
30            Ok(_) => Err("Invalid file format: expected a list".to_string()),
31            Err(e) => Err(e),
32        },
33        Err(e) => Err(format!("Failed to open file: {}", e)),
34    }
35}
36
37/// Adds the next Fibonacci number to the sequence by summing the last two numbers.
38/// Uses checked addition to prevent integer overflow.
39///
40/// # Arguments
41/// * `sequence` - Mutable reference to the Node containing the sequence
42fn add_next(sequence: &mut Node) {
43    // Extract the list of numbers from the Node
44    if let Node::Array(items) = sequence {
45        if items.len() < 2 {
46            return;
47        }
48        match (&items[items.len() - 2], &items[items.len() - 1]) {
49            (Node::Number(Numeric::Integer(a)), Node::Number(Numeric::Integer(b))) => {
50                if let Some(sum) = a.checked_add(*b) {
51                    items.push(Node::Number(Numeric::Integer(sum)));
52                }
53            }
54            _ => {}
55        }
56    }
57}
58
59/// Saves the Fibonacci sequence to a JSON-encoded file.
60///
61/// # Arguments
62/// * `file_path` - Path where to save the sequence
63/// * `sequence` - The Node containing the sequence to save
64///
65/// # Returns
66/// * `Ok(())` - Write operation succeeded
67/// * `Err(String)` - Error message if writing fails
68fn write_sequence(file_path: &Path, sequence: &Node) -> Result<(), String> {
69    // Create a new file destination, falling back to empty string if the path is invalid
70    let file = FileDestination::new(file_path.to_str().unwrap_or(""));
71    match file {
72        Ok(mut f) => {
73            stringify(&sequence, &mut f).unwrap();
74            Ok(())
75        }
76        Err(e) => Err(e.to_string()),
77    }
78}
79
80/// Main program entry point.
81/// Reads the existing Fibonacci sequence, adds the next number,
82/// and saves the updated sequence back to the file.
83fn main() {
84    // Define the file_path to the sequence file
85    let file_path = Path::new("fibonacci.json");
86    match read_sequence(file_path) {
87        Ok(mut sequence) => {
88            add_next(&mut sequence);
89            if let Err(e) = write_sequence(file_path, &sequence) {
90                eprintln!("Failed to write sequence: {}", e);
91                return;
92            }
93        }
94        Err(e) => eprintln!("Failed to read sequence: {}", e),
95    }
96}