|
| 1 | +//! Build-time codegen (dual-track, Constitution Principle IV). |
| 2 | +//! |
| 3 | +//! Reads the same normalized dictionary sources the runtime loads, and generates per-version |
| 4 | +//! message-type constants plus a content hash. The runtime asserts its parsed hash equals the |
| 5 | +//! generated one, proving codegen and runtime derive from one source. |
| 6 | +
|
| 7 | +use std::env; |
| 8 | +use std::fmt::Write as _; |
| 9 | +use std::fs; |
| 10 | +use std::path::Path; |
| 11 | + |
| 12 | +fn fnv1a(bytes: &[u8]) -> u64 { |
| 13 | + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; |
| 14 | + for &b in bytes { |
| 15 | + hash ^= u64::from(b); |
| 16 | + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); |
| 17 | + } |
| 18 | + hash |
| 19 | +} |
| 20 | + |
| 21 | +fn main() { |
| 22 | + let manifest = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"); |
| 23 | + let out_dir = env::var("OUT_DIR").expect("OUT_DIR"); |
| 24 | + let mut code = String::new(); |
| 25 | + code.push_str("// @generated by build.rs from dict-src/normalized — do not edit.\n"); |
| 26 | + |
| 27 | + for (name, file) in [ |
| 28 | + ("FIX44", "FIX44.fixdict"), |
| 29 | + ("FIXT11", "FIXT11.fixdict"), |
| 30 | + ("FIX50", "FIX50.fixdict"), |
| 31 | + ] { |
| 32 | + let path = Path::new(&manifest).join("dict-src/normalized").join(file); |
| 33 | + println!("cargo:rerun-if-changed={}", path.display()); |
| 34 | + let bytes = fs::read(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); |
| 35 | + let hash = fnv1a(&bytes); |
| 36 | + let _ = writeln!(code, "/// Content hash of the {name} dictionary source."); |
| 37 | + let _ = writeln!(code, "pub const {name}_DICT_HASH: u64 = {hash};"); |
| 38 | + |
| 39 | + let module = name.to_lowercase(); |
| 40 | + let _ = writeln!( |
| 41 | + code, |
| 42 | + "/// Generated MsgType constants for the {name} dictionary." |
| 43 | + ); |
| 44 | + let _ = writeln!(code, "pub mod {module}_msgs {{"); |
| 45 | + for line in String::from_utf8_lossy(&bytes).lines() { |
| 46 | + let line = line.trim(); |
| 47 | + if let Some(rest) = line.strip_prefix("message ") { |
| 48 | + let mut it = rest.split_whitespace(); |
| 49 | + if let (Some(msg_type), Some(msg_name)) = (it.next(), it.next()) { |
| 50 | + let ident = msg_name.to_uppercase(); |
| 51 | + let _ = writeln!(code, " /// MsgType for {msg_name}."); |
| 52 | + let _ = writeln!(code, " pub const {ident}: &str = {msg_type:?};"); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + let _ = writeln!(code, "}}"); |
| 57 | + } |
| 58 | + |
| 59 | + let dest = Path::new(&out_dir).join("generated.rs"); |
| 60 | + fs::write(&dest, code).unwrap_or_else(|e| panic!("write generated.rs: {e}")); |
| 61 | +} |
0 commit comments