Skip to main content

bencode_fibonacci/
bencode_fibonacci.rs

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