1use std::fs::{self, File};
21use std::io::{Read, Write};
22use std::path::PathBuf;
23use std::time::Duration;
24
25pub const DEFAULT_BC5D_URL: &str = "https://ballistics.tools/downloads/bc5d";
27
28const DOWNLOAD_TIMEOUT_SECS: u64 = 60;
30
31const MANIFEST_FILE: &str = "manifest.json";
33
34#[derive(Debug)]
36pub enum Bc5dDownloadError {
37 NetworkError(String),
39 Timeout,
41 IoError(std::io::Error),
43 ChecksumMismatch { expected: String, actual: String },
45 CaliberNotAvailable { requested: f64, available: Vec<f64> },
47 ManifestParseError(String),
49 CacheDirectoryError(String),
51}
52
53impl std::fmt::Display for Bc5dDownloadError {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 match self {
56 Bc5dDownloadError::NetworkError(msg) => write!(f, "Network error: {}", msg),
57 Bc5dDownloadError::Timeout => write!(f, "Download timed out"),
58 Bc5dDownloadError::IoError(e) => write!(f, "IO error: {}", e),
59 Bc5dDownloadError::ChecksumMismatch { expected, actual } => {
60 write!(f, "Checksum mismatch: expected {}, got {}", expected, actual)
61 }
62 Bc5dDownloadError::CaliberNotAvailable { requested, available } => {
63 let available_str: Vec<String> = available.iter().map(|c| format!(".{}", (c * 1000.0) as i32)).collect();
64 write!(
65 f,
66 "No BC5D table available for caliber {:.3} ({:.1}mm)\nAvailable calibers: {}",
67 requested,
68 requested * 25.4,
69 available_str.join(", ")
70 )
71 }
72 Bc5dDownloadError::ManifestParseError(msg) => write!(f, "Manifest parse error: {}", msg),
73 Bc5dDownloadError::CacheDirectoryError(msg) => write!(f, "Cache directory error: {}", msg),
74 }
75 }
76}
77
78impl std::error::Error for Bc5dDownloadError {}
79
80impl From<std::io::Error> for Bc5dDownloadError {
81 fn from(e: std::io::Error) -> Self {
82 Bc5dDownloadError::IoError(e)
83 }
84}
85
86#[derive(Debug, Clone)]
88pub struct TableEntry {
89 pub file: String,
91 pub size: u64,
93 pub crc32: String,
95}
96
97#[derive(Debug, Clone)]
99pub struct Bc5dManifest {
100 pub version: String,
102 pub generated: String,
104 pub tables: std::collections::HashMap<String, TableEntry>,
106}
107
108pub struct Bc5dDownloader {
110 base_url: String,
112 cache_dir: PathBuf,
114 force_refresh: bool,
116 manifest: Option<Bc5dManifest>,
118}
119
120impl Bc5dDownloader {
121 pub fn new(base_url: &str, force_refresh: bool) -> Result<Self, Bc5dDownloadError> {
130 let cache_dir = get_cache_directory()?;
131
132 if !cache_dir.exists() {
134 fs::create_dir_all(&cache_dir).map_err(|e| {
135 Bc5dDownloadError::CacheDirectoryError(format!(
136 "Failed to create cache directory {}: {}",
137 cache_dir.display(),
138 e
139 ))
140 })?;
141 }
142
143 Ok(Bc5dDownloader {
144 base_url: base_url.trim_end_matches('/').to_string(),
145 cache_dir,
146 force_refresh,
147 manifest: None,
148 })
149 }
150
151 pub fn ensure_table(&mut self, caliber: f64) -> Result<PathBuf, Bc5dDownloadError> {
161 if self.manifest.is_none() {
163 self.manifest = Some(self.fetch_manifest()?);
164 }
165 let manifest = self.manifest.as_ref().unwrap();
166
167 let caliber_key = format!("{}", (caliber * 1000.0).round() as i32);
169
170 let entry = manifest.tables.get(&caliber_key).ok_or_else(|| {
172 Bc5dDownloadError::CaliberNotAvailable {
173 requested: caliber,
174 available: self.available_calibers_from_manifest(manifest),
175 }
176 })?;
177
178 let cached_path = self.cache_dir.join(&entry.file);
180 if !self.force_refresh && cached_path.exists() {
181 if let Ok(actual_crc) = calculate_file_crc32(&cached_path) {
183 if actual_crc == entry.crc32 {
184 return Ok(cached_path);
185 }
186 eprintln!("Warning: Cached table checksum mismatch, re-downloading...");
188 }
189 }
190
191 self.download_table(&entry.file, &cached_path, &entry.crc32)?;
193
194 Ok(cached_path)
195 }
196
197 pub fn available_calibers(&mut self) -> Result<Vec<f64>, Bc5dDownloadError> {
199 if self.manifest.is_none() {
200 self.manifest = Some(self.fetch_manifest()?);
201 }
202 Ok(self.available_calibers_from_manifest(self.manifest.as_ref().unwrap()))
203 }
204
205 pub fn cache_dir(&self) -> &PathBuf {
207 &self.cache_dir
208 }
209
210 pub fn is_cached(&self, caliber: f64) -> bool {
212 let caliber_key = format!("{}", (caliber * 1000.0).round() as i32);
213 let filename = self
217 .manifest
218 .as_ref()
219 .and_then(|m| m.tables.get(&caliber_key))
220 .map(|entry| entry.file.clone())
221 .unwrap_or_else(|| format!("bc5d_{}.bin", caliber_key));
222 self.cache_dir.join(&filename).exists()
223 }
224
225 fn available_calibers_from_manifest(&self, manifest: &Bc5dManifest) -> Vec<f64> {
227 let mut calibers: Vec<f64> = manifest
228 .tables
229 .keys()
230 .filter_map(|k| k.parse::<i32>().ok())
231 .map(|k| k as f64 / 1000.0)
232 .collect();
233 calibers.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
234 calibers
235 }
236
237 #[cfg(feature = "online")]
239 fn fetch_manifest(&self) -> Result<Bc5dManifest, Bc5dDownloadError> {
240 let url = format!("{}/{}", self.base_url, MANIFEST_FILE);
241
242 let response = ureq::get(&url)
243 .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
244 .call()
245 .map_err(|e| match e {
246 ureq::Error::Transport(t) if t.kind() == ureq::ErrorKind::Io => {
247 Bc5dDownloadError::NetworkError(format!("Connection failed: {}", t))
248 }
249 _ => Bc5dDownloadError::NetworkError(format!("{}", e)),
250 })?;
251
252 let json: serde_json::Value = response.into_json().map_err(|e| {
253 Bc5dDownloadError::ManifestParseError(format!("Failed to parse JSON: {}", e))
254 })?;
255
256 let version = json["version"]
258 .as_str()
259 .unwrap_or("unknown")
260 .to_string();
261 let generated = json["generated"]
262 .as_str()
263 .unwrap_or("unknown")
264 .to_string();
265
266 let tables_obj = json["tables"]
267 .as_object()
268 .ok_or_else(|| Bc5dDownloadError::ManifestParseError("Missing 'tables' field".to_string()))?;
269
270 let mut tables = std::collections::HashMap::new();
271 for (caliber, entry) in tables_obj {
272 let file = entry["file"]
273 .as_str()
274 .ok_or_else(|| Bc5dDownloadError::ManifestParseError(format!("Missing 'file' for caliber {}", caliber)))?
275 .to_string();
276 let size = entry["size"]
277 .as_u64()
278 .ok_or_else(|| Bc5dDownloadError::ManifestParseError(format!("Missing 'size' for caliber {}", caliber)))?;
279 let crc32 = entry["crc32"]
280 .as_str()
281 .ok_or_else(|| Bc5dDownloadError::ManifestParseError(format!("Missing 'crc32' for caliber {}", caliber)))?
282 .to_string();
283
284 tables.insert(caliber.clone(), TableEntry { file, size, crc32 });
285 }
286
287 Ok(Bc5dManifest {
288 version,
289 generated,
290 tables,
291 })
292 }
293
294 #[cfg(not(feature = "online"))]
296 fn fetch_manifest(&self) -> Result<Bc5dManifest, Bc5dDownloadError> {
297 Err(Bc5dDownloadError::NetworkError(
298 "Online features not enabled. Build with --features online".to_string(),
299 ))
300 }
301
302 #[cfg(feature = "online")]
304 fn download_table(&self, filename: &str, dest_path: &PathBuf, expected_crc: &str) -> Result<(), Bc5dDownloadError> {
305 let url = format!("{}/{}", self.base_url, filename);
306
307 eprintln!("Downloading BC5D table: {}...", filename);
308
309 let response = ureq::get(&url)
310 .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
311 .call()
312 .map_err(|e| match e {
313 ureq::Error::Transport(t) if t.kind() == ureq::ErrorKind::Io => {
314 Bc5dDownloadError::NetworkError(format!("Connection failed: {}", t))
315 }
316 _ => Bc5dDownloadError::NetworkError(format!("{}", e)),
317 })?;
318
319 let mut data = Vec::new();
321 response.into_reader().read_to_end(&mut data).map_err(|e| {
322 Bc5dDownloadError::NetworkError(format!("Failed to read response: {}", e))
323 })?;
324
325 let actual_crc = calculate_crc32(&data);
327 if actual_crc != expected_crc {
328 return Err(Bc5dDownloadError::ChecksumMismatch {
329 expected: expected_crc.to_string(),
330 actual: actual_crc,
331 });
332 }
333
334 let mut file = File::create(dest_path)?;
336 file.write_all(&data)?;
337
338 eprintln!("Downloaded {} ({} bytes)", filename, data.len());
339
340 Ok(())
341 }
342
343 #[cfg(not(feature = "online"))]
345 fn download_table(&self, _filename: &str, _dest_path: &PathBuf, _expected_crc: &str) -> Result<(), Bc5dDownloadError> {
346 Err(Bc5dDownloadError::NetworkError(
347 "Online features not enabled. Build with --features online".to_string(),
348 ))
349 }
350}
351
352pub fn get_cache_directory() -> Result<PathBuf, Bc5dDownloadError> {
354 if let Some(cache_dir) = dirs::cache_dir() {
356 return Ok(cache_dir.join("ballistics-engine").join("bc5d"));
357 }
358
359 if let Some(home) = dirs::home_dir() {
361 #[cfg(target_os = "macos")]
362 return Ok(home.join("Library").join("Caches").join("ballistics-engine").join("bc5d"));
363
364 #[cfg(target_os = "windows")]
365 return Ok(home.join("AppData").join("Local").join("ballistics-engine").join("cache").join("bc5d"));
366
367 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
368 return Ok(home.join(".cache").join("ballistics-engine").join("bc5d"));
369 }
370
371 Err(Bc5dDownloadError::CacheDirectoryError(
372 "Could not determine cache directory".to_string(),
373 ))
374}
375
376fn calculate_crc32(data: &[u8]) -> String {
378 const TABLE: [u32; 256] = make_crc32_table();
379 let mut crc = 0xFFFFFFFFu32;
380 for &byte in data {
381 let idx = ((crc ^ byte as u32) & 0xFF) as usize;
382 crc = (crc >> 8) ^ TABLE[idx];
383 }
384 format!("{:08x}", !crc)
385}
386
387fn calculate_file_crc32(path: &PathBuf) -> Result<String, std::io::Error> {
389 let mut file = File::open(path)?;
390 let mut data = Vec::new();
391 file.read_to_end(&mut data)?;
392 Ok(calculate_crc32(&data))
393}
394
395const fn make_crc32_table() -> [u32; 256] {
397 const POLY: u32 = 0xEDB88320;
398 let mut table = [0u32; 256];
399 let mut i = 0;
400 while i < 256 {
401 let mut crc = i as u32;
402 let mut j = 0;
403 while j < 8 {
404 if crc & 1 != 0 {
405 crc = (crc >> 1) ^ POLY;
406 } else {
407 crc >>= 1;
408 }
409 j += 1;
410 }
411 table[i] = crc;
412 i += 1;
413 }
414 table
415}
416
417#[cfg(test)]
418mod tests {
419 use super::*;
420
421 #[test]
422 fn test_crc32_calculation() {
423 let data = b"123456789";
425 let crc = calculate_crc32(data);
426 assert_eq!(crc, "cbf43926");
427 }
428
429 #[test]
430 fn test_cache_directory() {
431 let cache_dir = get_cache_directory();
432 assert!(cache_dir.is_ok());
433 let path = cache_dir.unwrap();
434 assert!(path.to_string_lossy().contains("bc5d"));
435 }
436
437 #[test]
438 fn test_caliber_key_conversion() {
439 let caliber: f64 = 0.308;
441 let key = format!("{}", (caliber * 1000.0).round() as i32);
442 assert_eq!(key, "308");
443
444 let caliber: f64 = 0.224;
445 let key = format!("{}", (caliber * 1000.0).round() as i32);
446 assert_eq!(key, "224");
447 }
448
449 #[test]
450 fn test_error_display() {
451 let err = Bc5dDownloadError::CaliberNotAvailable {
452 requested: 0.375,
453 available: vec![0.224, 0.308, 0.338],
454 };
455 let msg = format!("{}", err);
456 assert!(msg.contains("0.375"));
457 assert!(msg.contains("9.5mm"));
458 assert!(msg.contains(".224"));
459 assert!(msg.contains(".308"));
460 assert!(msg.contains(".338"));
461 }
462}