Skip to main content

flashkraft_core/domain/
image_info.rs

1//! Image Information Domain Model
2//!
3//! This module contains the ImageInfo struct which represents
4//! information about a disk image file.
5
6use std::path::PathBuf;
7
8/// Information about a disk image file
9#[derive(Debug, Clone)]
10pub struct ImageInfo {
11    /// Full path to the image file
12    pub path: PathBuf,
13    /// Display name of the file
14    pub name: String,
15    /// Size of the file in megabytes
16    pub size_mb: f64,
17}
18
19impl ImageInfo {
20    /// Return the image size in bytes.
21    pub fn size_bytes(&self) -> u64 {
22        (self.size_mb * 1_048_576.0) as u64
23    }
24
25    /// Create a new ImageInfo from a PathBuf
26    ///
27    /// # Arguments
28    ///
29    /// * `path` - The path to the image file
30    ///
31    /// # Returns
32    ///
33    /// An ImageInfo instance with extracted file name and size
34    pub fn from_path(path: PathBuf) -> Self {
35        let name = path
36            .file_name()
37            .and_then(|n| n.to_str())
38            .unwrap_or("Unknown")
39            .to_string();
40
41        let size_mb = path
42            .metadata()
43            .map(|m| m.len() as f64 / (1024.0 * 1024.0))
44            .unwrap_or(0.0);
45
46        Self {
47            path,
48            name,
49            size_mb,
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use std::fs::File;
58    use std::io::Write;
59
60    #[test]
61    fn test_image_info_from_path() {
62        // Create a temporary file for testing
63        let temp_dir = std::env::temp_dir();
64        let test_path = temp_dir.join("test_image.img");
65
66        // Write some data to get a known size
67        if let Ok(mut file) = File::create(&test_path) {
68            let _ = file.write_all(&[0u8; 1024 * 1024]); // 1 MB
69        }
70
71        let image_info = ImageInfo::from_path(test_path.clone());
72
73        assert_eq!(image_info.name, "test_image.img");
74        assert_eq!(image_info.path, test_path);
75        // Size should be approximately 1 MB
76        assert!((image_info.size_mb - 1.0).abs() < 0.1);
77
78        // Cleanup
79        let _ = std::fs::remove_file(test_path);
80    }
81
82    #[test]
83    fn test_image_info_nonexistent_file() {
84        let path = PathBuf::from("/nonexistent/test.img");
85        let image_info = ImageInfo::from_path(path);
86
87        assert_eq!(image_info.name, "test.img");
88        assert_eq!(image_info.size_mb, 0.0);
89    }
90}