Skip to main content

ballistics_engine/
bc_table_5d.rs

1// BC5D - 5-Dimensional BC Correction Table with Caliber-Specific Files
2//
3// This module provides offline BC corrections by loading precomputed tables
4// of correction factors derived from ML model predictions. The tables are
5// caliber-specific and indexed by:
6//   - Weight (grains) - caliber-specific ranges
7//   - Base BC (0.05-1.2)
8//   - Muzzle Velocity (2000-4000 fps)
9//   - Current Velocity (500-4000 fps, dense in transonic)
10//   - Drag Model (G1, G7)
11//
12// Binary file format (BC5D v2):
13//   Header (80 bytes):
14//     - Magic: 4 bytes ('BC5D')
15//     - Version: 4 bytes (uint32)
16//     - Caliber: 4 bytes (float32)
17//     - Flags: 4 bytes (uint32)
18//     - Padding: 4 bytes
19//     - dim_weight: 4 bytes (uint32)
20//     - dim_bc: 4 bytes (uint32)
21//     - dim_muzzle_vel: 4 bytes (uint32)
22//     - dim_current_vel: 4 bytes (uint32)
23//     - dim_drag_types: 4 bytes (uint32)
24//     - timestamp: 8 bytes (uint64)
25//     - checksum: 4 bytes (uint32, CRC32 of data section)
26//     - api_version: 16 bytes (null-padded string)
27//     - reserved: 12 bytes
28//   Bin definitions:
29//     - Weight bins: dim_weight * 4 bytes (float32)
30//     - BC bins: dim_bc * 4 bytes (float32)
31//     - Muzzle velocity bins: dim_muzzle_vel * 4 bytes (float32)
32//     - Current velocity bins: dim_current_vel * 4 bytes (float32)
33//   Data section:
34//     - Correction factors: total_cells * 4 bytes (float32)
35//     - Layout: [drag_type][weight][bc][muzzle_vel][current_vel]
36//
37// Correction factors are ratios: predicted_bc / base_bc
38// Range: 0.5 to 1.5 (clipped during generation)
39
40use std::collections::HashMap;
41use std::fs::File;
42use std::io::{BufReader, Read};
43use std::path::{Path, PathBuf};
44
45/// Magic bytes for BC5D format
46const MAGIC: &[u8; 4] = b"BC5D";
47
48/// Supported format version
49const SUPPORTED_VERSION: u32 = 2;
50
51/// Header size in bytes
52const HEADER_SIZE: usize = 80;
53
54/// BC5D table with 4D interpolation (drag type is discrete)
55#[derive(Debug)]
56pub struct Bc5dTable {
57    /// Caliber this table is for
58    caliber: f32,
59    /// Correction data: [drag_type][weight][bc][muzzle_vel][current_vel]
60    data: Vec<f32>,
61    /// Weight bin values (grains)
62    weight_bins: Vec<f32>,
63    /// BC bin values
64    bc_bins: Vec<f32>,
65    /// Muzzle velocity bin values (fps)
66    muzzle_vel_bins: Vec<f32>,
67    /// Current velocity bin values (fps)
68    current_vel_bins: Vec<f32>,
69    /// Number of drag types (typically 2: G1=0, G7=1)
70    num_drag_types: usize,
71    /// Table version
72    version: u32,
73    /// API version used to generate the table
74    api_version: String,
75    /// Generation timestamp
76    timestamp: u64,
77}
78
79/// Manager for loading caliber-specific BC5D tables
80#[derive(Debug, Default)]
81pub struct Bc5dTableManager {
82    /// Directory containing BC5D table files
83    table_dir: Option<PathBuf>,
84    /// Loaded tables by caliber (rounded to 3 decimal places)
85    tables: HashMap<i32, Bc5dTable>,
86}
87
88/// Error type for BC5D table operations
89#[derive(Debug)]
90pub enum Bc5dError {
91    IoError(std::io::Error),
92    InvalidMagic,
93    UnsupportedVersion(u32),
94    ChecksumMismatch { expected: u32, actual: u32 },
95    InvalidDimensions,
96    TableNotFound(f64),
97    NoTableDirectory,
98}
99
100impl std::fmt::Display for Bc5dError {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        match self {
103            Bc5dError::IoError(e) => write!(f, "IO error: {}", e),
104            Bc5dError::InvalidMagic => write!(f, "Invalid file magic (expected 'BC5D')"),
105            Bc5dError::UnsupportedVersion(v) => write!(f, "Unsupported table version: {}", v),
106            Bc5dError::ChecksumMismatch { expected, actual } => {
107                write!(f, "Checksum mismatch: expected {:08x}, got {:08x}", expected, actual)
108            }
109            Bc5dError::InvalidDimensions => write!(f, "Invalid table dimensions"),
110            Bc5dError::TableNotFound(cal) => write!(f, "No BC5D table found for caliber {:.3}", cal),
111            Bc5dError::NoTableDirectory => write!(f, "No BC table directory configured"),
112        }
113    }
114}
115
116impl std::error::Error for Bc5dError {}
117
118impl From<std::io::Error> for Bc5dError {
119    fn from(e: std::io::Error) -> Self {
120        Bc5dError::IoError(e)
121    }
122}
123
124impl Bc5dTable {
125    /// Load a BC5D table from a binary file
126    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Bc5dError> {
127        let file = File::open(&path)?;
128        let mut reader = BufReader::new(file);
129
130        // Read and validate magic
131        let mut magic = [0u8; 4];
132        reader.read_exact(&mut magic)?;
133        if &magic != MAGIC {
134            return Err(Bc5dError::InvalidMagic);
135        }
136
137        // Read header fields
138        let version = read_u32(&mut reader)?;
139        if version != SUPPORTED_VERSION {
140            return Err(Bc5dError::UnsupportedVersion(version));
141        }
142
143        let caliber = read_f32(&mut reader)?;
144        let _flags = read_u32(&mut reader)?;
145        let _padding = read_u32(&mut reader)?;
146
147        let dim_weight = read_u32(&mut reader)? as usize;
148        let dim_bc = read_u32(&mut reader)? as usize;
149        let dim_muzzle_vel = read_u32(&mut reader)? as usize;
150        let dim_current_vel = read_u32(&mut reader)? as usize;
151        let dim_drag_types = read_u32(&mut reader)? as usize;
152
153        let timestamp = read_u64(&mut reader)?;
154        let stored_checksum = read_u32(&mut reader)?;
155
156        // Read API version (16 bytes, null-terminated)
157        let mut api_version_bytes = [0u8; 16];
158        reader.read_exact(&mut api_version_bytes)?;
159        let api_version = String::from_utf8_lossy(&api_version_bytes)
160            .trim_end_matches('\0')
161            .to_string();
162
163        // Skip reserved bytes
164        let mut reserved = [0u8; 12];
165        reader.read_exact(&mut reserved)?;
166
167        // Validate dimensions
168        if dim_weight == 0 || dim_bc == 0 || dim_muzzle_vel == 0 || dim_current_vel == 0 || dim_drag_types == 0 {
169            return Err(Bc5dError::InvalidDimensions);
170        }
171
172        // Read bin definitions
173        let weight_bins = read_f32_array(&mut reader, dim_weight)?;
174        let bc_bins = read_f32_array(&mut reader, dim_bc)?;
175        let muzzle_vel_bins = read_f32_array(&mut reader, dim_muzzle_vel)?;
176        let current_vel_bins = read_f32_array(&mut reader, dim_current_vel)?;
177
178        // Read data section
179        let total_cells = dim_drag_types * dim_weight * dim_bc * dim_muzzle_vel * dim_current_vel;
180        let data = read_f32_array(&mut reader, total_cells)?;
181
182        // Verify checksum (CRC32 of bins + data)
183        let mut checksum_data = Vec::new();
184        for &v in &weight_bins {
185            checksum_data.extend_from_slice(&v.to_le_bytes());
186        }
187        for &v in &bc_bins {
188            checksum_data.extend_from_slice(&v.to_le_bytes());
189        }
190        for &v in &muzzle_vel_bins {
191            checksum_data.extend_from_slice(&v.to_le_bytes());
192        }
193        for &v in &current_vel_bins {
194            checksum_data.extend_from_slice(&v.to_le_bytes());
195        }
196        for &v in &data {
197            checksum_data.extend_from_slice(&v.to_le_bytes());
198        }
199
200        let calculated_checksum = crc32_ieee(&checksum_data);
201        if calculated_checksum != stored_checksum {
202            return Err(Bc5dError::ChecksumMismatch {
203                expected: stored_checksum,
204                actual: calculated_checksum,
205            });
206        }
207
208        Ok(Bc5dTable {
209            caliber,
210            data,
211            weight_bins,
212            bc_bins,
213            muzzle_vel_bins,
214            current_vel_bins,
215            num_drag_types: dim_drag_types,
216            version,
217            api_version,
218            timestamp,
219        })
220    }
221
222    /// Look up a BC correction factor with 4D linear interpolation
223    /// (drag type is discrete, not interpolated)
224    ///
225    /// # Arguments
226    /// * `weight_grains` - Bullet weight in grains
227    /// * `base_bc` - Published BC value
228    /// * `muzzle_velocity` - Initial muzzle velocity in fps
229    /// * `current_velocity` - Current bullet velocity in fps
230    /// * `drag_type` - "G1" or "G7"
231    ///
232    /// # Returns
233    /// Correction factor (multiply published BC by this value)
234    pub fn lookup(
235        &self,
236        weight_grains: f64,
237        base_bc: f64,
238        muzzle_velocity: f64,
239        current_velocity: f64,
240        drag_type: &str,
241    ) -> f64 {
242        // Get drag type index (0 = G1, 1 = G7)
243        let drag_idx = if drag_type.eq_ignore_ascii_case("G7") { 1 } else { 0 };
244
245        // Clamp drag_idx to valid range
246        let drag_idx = drag_idx.min(self.num_drag_types - 1);
247
248        // Find interpolation indices and weights for each continuous dimension
249        let (weight_idx, weight_w) = self.interp_idx(weight_grains as f32, &self.weight_bins);
250        let (bc_idx, bc_w) = self.interp_idx(base_bc as f32, &self.bc_bins);
251        let (muzzle_idx, muzzle_w) = self.interp_idx(muzzle_velocity as f32, &self.muzzle_vel_bins);
252        let (current_idx, current_w) = self.interp_idx(current_velocity as f32, &self.current_vel_bins);
253
254        // 4D linear interpolation (16 corners of a hypercube)
255        let mut result = 0.0f64;
256
257        for dw in 0..2 {
258            for db in 0..2 {
259                for dm in 0..2 {
260                    for dc in 0..2 {
261                        // Calculate weight for this corner
262                        let weight = (if dw == 0 { 1.0 - weight_w } else { weight_w })
263                            * (if db == 0 { 1.0 - bc_w } else { bc_w })
264                            * (if dm == 0 { 1.0 - muzzle_w } else { muzzle_w })
265                            * (if dc == 0 { 1.0 - current_w } else { current_w });
266
267                        // Get clamped indices
268                        let wi = (weight_idx + dw).min(self.weight_bins.len() - 1);
269                        let bi = (bc_idx + db).min(self.bc_bins.len() - 1);
270                        let mi = (muzzle_idx + dm).min(self.muzzle_vel_bins.len() - 1);
271                        let ci = (current_idx + dc).min(self.current_vel_bins.len() - 1);
272
273                        // Calculate flat index
274                        let idx = self.flat_index(drag_idx, wi, bi, mi, ci);
275                        result += weight * self.data[idx] as f64;
276                    }
277                }
278            }
279        }
280
281        // Clamp result to valid range
282        result.max(0.5).min(1.5)
283    }
284
285    /// Get the effective BC at a given velocity
286    ///
287    /// This multiplies the base BC by the correction factor from the table.
288    pub fn get_effective_bc(
289        &self,
290        weight_grains: f64,
291        base_bc: f64,
292        muzzle_velocity: f64,
293        current_velocity: f64,
294        drag_type: &str,
295    ) -> f64 {
296        let correction = self.lookup(weight_grains, base_bc, muzzle_velocity, current_velocity, drag_type);
297        base_bc * correction
298    }
299
300    /// Find interpolation index and weight for a value in bins
301    fn interp_idx(&self, value: f32, bins: &[f32]) -> (usize, f64) {
302        if bins.is_empty() {
303            return (0, 0.0);
304        }
305
306        // Handle out of range (clamp to edges)
307        if value <= bins[0] {
308            return (0, 0.0);
309        }
310        if value >= bins[bins.len() - 1] {
311            return (bins.len().saturating_sub(2), 1.0);
312        }
313
314        // Binary search for interval containing value
315        let idx = match bins.binary_search_by(|probe| {
316            probe.partial_cmp(&value).unwrap_or(std::cmp::Ordering::Equal)
317        }) {
318            Ok(i) => i.saturating_sub(1).min(bins.len() - 2),
319            Err(i) => i.saturating_sub(1).min(bins.len() - 2),
320        };
321
322        // Calculate interpolation weight
323        let low = bins[idx];
324        let high = bins[idx + 1];
325        let weight = if high > low {
326            ((value - low) / (high - low)) as f64
327        } else {
328            0.0
329        };
330
331        (idx, weight)
332    }
333
334    /// Calculate flat array index from 5D indices
335    fn flat_index(&self, drag_idx: usize, weight_idx: usize, bc_idx: usize, muzzle_idx: usize, current_idx: usize) -> usize {
336        let n_weight = self.weight_bins.len();
337        let n_bc = self.bc_bins.len();
338        let n_muzzle = self.muzzle_vel_bins.len();
339        let n_current = self.current_vel_bins.len();
340
341        drag_idx * (n_weight * n_bc * n_muzzle * n_current)
342            + weight_idx * (n_bc * n_muzzle * n_current)
343            + bc_idx * (n_muzzle * n_current)
344            + muzzle_idx * n_current
345            + current_idx
346    }
347
348    /// Get caliber this table is for
349    pub fn caliber(&self) -> f32 {
350        self.caliber
351    }
352
353    /// Get table version
354    pub fn version(&self) -> u32 {
355        self.version
356    }
357
358    /// Get API version used to generate the table
359    pub fn api_version(&self) -> &str {
360        &self.api_version
361    }
362
363    /// Get generation timestamp
364    pub fn timestamp(&self) -> u64 {
365        self.timestamp
366    }
367
368    /// Get total number of cells in the table
369    pub fn total_cells(&self) -> usize {
370        self.data.len()
371    }
372
373    /// Get table dimensions as a string
374    pub fn dimensions_str(&self) -> String {
375        format!(
376            "{}x{}x{}x{}x{} (weight x bc x muzzle_vel x current_vel x drag_types)",
377            self.weight_bins.len(),
378            self.bc_bins.len(),
379            self.muzzle_vel_bins.len(),
380            self.current_vel_bins.len(),
381            self.num_drag_types
382        )
383    }
384
385    /// Get weight range
386    pub fn weight_range(&self) -> (f32, f32) {
387        (*self.weight_bins.first().unwrap_or(&0.0), *self.weight_bins.last().unwrap_or(&0.0))
388    }
389
390    /// Get velocity range
391    pub fn velocity_range(&self) -> (f32, f32) {
392        (*self.current_vel_bins.first().unwrap_or(&0.0), *self.current_vel_bins.last().unwrap_or(&0.0))
393    }
394}
395
396impl Bc5dTableManager {
397    /// Create a new table manager with a directory path
398    pub fn new<P: AsRef<Path>>(table_dir: P) -> Self {
399        Bc5dTableManager {
400            table_dir: Some(table_dir.as_ref().to_path_buf()),
401            tables: HashMap::new(),
402        }
403    }
404
405    /// Create an empty manager (no table directory)
406    pub fn empty() -> Self {
407        Bc5dTableManager {
408            table_dir: None,
409            tables: HashMap::new(),
410        }
411    }
412
413    /// Get or load the table for a caliber
414    ///
415    /// Tables are cached after first load.
416    pub fn get_table(&mut self, caliber: f64) -> Result<&Bc5dTable, Bc5dError> {
417        let caliber_key = caliber_to_key(caliber);
418
419        // Check if already loaded
420        if self.tables.contains_key(&caliber_key) {
421            return Ok(self.tables.get(&caliber_key).unwrap());
422        }
423
424        // Need to load
425        let table_dir = self.table_dir.as_ref().ok_or(Bc5dError::NoTableDirectory)?;
426        let table_path = find_table_file(table_dir, caliber)?;
427        let table = Bc5dTable::load(&table_path)?;
428        self.tables.insert(caliber_key, table);
429        Ok(self.tables.get(&caliber_key).unwrap())
430    }
431
432    /// Look up BC correction for a bullet
433    pub fn lookup(
434        &mut self,
435        caliber: f64,
436        weight_grains: f64,
437        base_bc: f64,
438        muzzle_velocity: f64,
439        current_velocity: f64,
440        drag_type: &str,
441    ) -> Result<f64, Bc5dError> {
442        let table = self.get_table(caliber)?;
443        Ok(table.lookup(weight_grains, base_bc, muzzle_velocity, current_velocity, drag_type))
444    }
445
446    /// Get effective BC with correction applied
447    pub fn get_effective_bc(
448        &mut self,
449        caliber: f64,
450        weight_grains: f64,
451        base_bc: f64,
452        muzzle_velocity: f64,
453        current_velocity: f64,
454        drag_type: &str,
455    ) -> Result<f64, Bc5dError> {
456        let table = self.get_table(caliber)?;
457        Ok(table.get_effective_bc(weight_grains, base_bc, muzzle_velocity, current_velocity, drag_type))
458    }
459
460    /// Check if a table is available for a caliber
461    pub fn has_table(&self, caliber: f64) -> bool {
462        if let Some(ref table_dir) = self.table_dir {
463            find_table_file(table_dir, caliber).is_ok()
464        } else {
465            false
466        }
467    }
468
469    /// List available calibers in the table directory
470    pub fn available_calibers(&self) -> Vec<f64> {
471        let mut calibers = Vec::new();
472        if let Some(ref table_dir) = self.table_dir {
473            if let Ok(entries) = std::fs::read_dir(table_dir) {
474                for entry in entries.flatten() {
475                    let path = entry.path();
476                    if let Some(ext) = path.extension() {
477                        if ext == "bin" {
478                            if let Some(stem) = path.file_stem() {
479                                let name = stem.to_string_lossy();
480                                if name.starts_with("bc5d_") {
481                                    // Parse caliber from filename (e.g., bc5d_308.bin -> 0.308)
482                                    if let Ok(cal_int) = name[5..].parse::<i32>() {
483                                        calibers.push(cal_int as f64 / 1000.0);
484                                    }
485                                }
486                            }
487                        }
488                    }
489                }
490            }
491        }
492        calibers.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
493        calibers
494    }
495}
496
497/// Convert caliber to integer key (multiply by 1000)
498fn caliber_to_key(caliber: f64) -> i32 {
499    (caliber * 1000.0).round() as i32
500}
501
502/// Find the table file for a caliber
503fn find_table_file(table_dir: &Path, caliber: f64) -> Result<PathBuf, Bc5dError> {
504    let caliber_int = (caliber * 1000.0).round() as i32;
505    let filename = format!("bc5d_{}.bin", caliber_int);
506    let path = table_dir.join(&filename);
507
508    if path.exists() {
509        return Ok(path);
510    }
511
512    // Try common variations
513    let variations = [
514        format!("bc5d_{:03}.bin", caliber_int),
515        format!("bc5d_0{}.bin", caliber_int),
516    ];
517
518    for var in &variations {
519        let var_path = table_dir.join(var);
520        if var_path.exists() {
521            return Ok(var_path);
522        }
523    }
524
525    Err(Bc5dError::TableNotFound(caliber))
526}
527
528// Helper functions for reading binary data
529
530fn read_u32<R: Read>(reader: &mut R) -> Result<u32, std::io::Error> {
531    let mut buf = [0u8; 4];
532    reader.read_exact(&mut buf)?;
533    Ok(u32::from_le_bytes(buf))
534}
535
536fn read_u64<R: Read>(reader: &mut R) -> Result<u64, std::io::Error> {
537    let mut buf = [0u8; 8];
538    reader.read_exact(&mut buf)?;
539    Ok(u64::from_le_bytes(buf))
540}
541
542fn read_f32<R: Read>(reader: &mut R) -> Result<f32, std::io::Error> {
543    let mut buf = [0u8; 4];
544    reader.read_exact(&mut buf)?;
545    Ok(f32::from_le_bytes(buf))
546}
547
548fn read_f32_array<R: Read>(reader: &mut R, count: usize) -> Result<Vec<f32>, std::io::Error> {
549    let mut data = vec![0f32; count];
550    let mut buf = vec![0u8; count * 4];
551    reader.read_exact(&mut buf)?;
552
553    for (i, chunk) in buf.chunks_exact(4).enumerate() {
554        data[i] = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
555    }
556
557    Ok(data)
558}
559
560/// Simple CRC32 (IEEE polynomial) implementation
561fn crc32_ieee(data: &[u8]) -> u32 {
562    const TABLE: [u32; 256] = make_crc32_table();
563    let mut crc = 0xFFFFFFFFu32;
564    for &byte in data {
565        let idx = ((crc ^ byte as u32) & 0xFF) as usize;
566        crc = (crc >> 8) ^ TABLE[idx];
567    }
568    !crc
569}
570
571const fn make_crc32_table() -> [u32; 256] {
572    const POLY: u32 = 0xEDB88320;
573    let mut table = [0u32; 256];
574    let mut i = 0;
575    while i < 256 {
576        let mut crc = i as u32;
577        let mut j = 0;
578        while j < 8 {
579            if crc & 1 != 0 {
580                crc = (crc >> 1) ^ POLY;
581            } else {
582                crc >>= 1;
583            }
584            j += 1;
585        }
586        table[i] = crc;
587        i += 1;
588    }
589    table
590}
591
592#[cfg(test)]
593mod tests {
594    use super::*;
595
596    fn create_test_table() -> Bc5dTable {
597        // Create a small test table with known values
598        let weight_bins = vec![100.0, 150.0, 200.0];
599        let bc_bins = vec![0.3, 0.4, 0.5];
600        let muzzle_vel_bins = vec![2500.0, 3000.0];
601        let current_vel_bins = vec![1000.0, 2000.0, 3000.0];
602        let num_drag_types = 2;
603
604        // Total cells: 2 * 3 * 3 * 2 * 3 = 108
605        let total = num_drag_types * weight_bins.len() * bc_bins.len() * muzzle_vel_bins.len() * current_vel_bins.len();
606        let mut data = vec![1.0f32; total];
607
608        // Set some non-uniform values for testing interpolation
609        // At weight=150, bc=0.4, muzzle=2750 (interpolated), current=2000, G1
610        // We'll set corners to test 4D interpolation
611        data[0] = 0.95; // First corner
612        data[total - 1] = 1.05; // Last corner
613
614        Bc5dTable {
615            caliber: 0.308,
616            data,
617            weight_bins,
618            bc_bins,
619            muzzle_vel_bins,
620            current_vel_bins,
621            num_drag_types,
622            version: 2,
623            api_version: "test".to_string(),
624            timestamp: 0,
625        }
626    }
627
628    #[test]
629    fn test_interp_idx_in_range() {
630        let table = create_test_table();
631
632        // Test middle of range
633        let (idx, weight) = table.interp_idx(125.0, &table.weight_bins);
634        assert_eq!(idx, 0);
635        assert!((weight - 0.5).abs() < 0.01);
636
637        // Test at bin boundary
638        let (idx, weight) = table.interp_idx(150.0, &table.weight_bins);
639        assert_eq!(idx, 0);
640        assert!((weight - 1.0).abs() < 0.01);
641    }
642
643    #[test]
644    fn test_interp_idx_out_of_range() {
645        let table = create_test_table();
646
647        // Test below range
648        let (idx, weight) = table.interp_idx(50.0, &table.weight_bins);
649        assert_eq!(idx, 0);
650        assert_eq!(weight, 0.0);
651
652        // Test above range
653        let (idx, weight) = table.interp_idx(250.0, &table.weight_bins);
654        assert_eq!(idx, 1); // len - 2
655        assert_eq!(weight, 1.0);
656    }
657
658    #[test]
659    fn test_lookup_returns_valid_range() {
660        let table = create_test_table();
661
662        let correction = table.lookup(150.0, 0.4, 2750.0, 2000.0, "G1");
663        assert!(correction >= 0.5 && correction <= 1.5);
664
665        let correction = table.lookup(150.0, 0.4, 2750.0, 2000.0, "G7");
666        assert!(correction >= 0.5 && correction <= 1.5);
667    }
668
669    #[test]
670    fn test_effective_bc() {
671        let table = create_test_table();
672
673        let base_bc = 0.4;
674        let effective = table.get_effective_bc(150.0, base_bc, 2750.0, 2000.0, "G1");
675
676        // Effective BC should be base_bc * correction
677        assert!(effective >= base_bc * 0.5 && effective <= base_bc * 1.5);
678    }
679
680    #[test]
681    fn test_caliber_to_key() {
682        assert_eq!(caliber_to_key(0.308), 308);
683        assert_eq!(caliber_to_key(0.224), 224);
684        assert_eq!(caliber_to_key(0.338), 338);
685    }
686
687    #[test]
688    fn test_table_metadata() {
689        let table = create_test_table();
690        assert!((table.caliber() - 0.308).abs() < 0.001);
691        assert_eq!(table.version(), 2);
692        assert_eq!(table.api_version(), "test");
693    }
694
695    #[test]
696    fn test_crc32() {
697        // Test with known CRC32 value
698        let data = b"123456789";
699        let crc = crc32_ieee(data);
700        assert_eq!(crc, 0xCBF43926);
701    }
702}