diff --git a/gen/rust/access_control.rs b/gen/rust/access_control.rs index 3672e5ba..a36cbdde 100644 --- a/gen/rust/access_control.rs +++ b/gen/rust/access_control.rs @@ -65,7 +65,7 @@ pub fn role_meets_minimum(role: u32, min_role: u32) -> bool { pub fn check_access(policy: u32, role: u32) -> u32 { let min_role = get_min_role(policy); - if !(role_meets_minimum(role, min_role)) { + if ((role_meets_minimum(role, min_role)) == 0) { return DENY; } if (role == ROLE_GUEST) { @@ -111,7 +111,7 @@ pub fn change_role(creds: u32, new_role: u32) -> u32 { } pub fn check_resource_access(creds: u32, policy: u32, provided_token: u32) -> u32 { - if !(verify_creds(creds, provided_token)) { + if ((verify_creds(creds, provided_token)) == 0) { return DENY; } let role = get_role(creds); diff --git a/gen/rust/adaptive_retry.rs b/gen/rust/adaptive_retry.rs index baf655ac..1a8a5d90 100644 --- a/gen/rust/adaptive_retry.rs +++ b/gen/rust/adaptive_retry.rs @@ -24,6 +24,7 @@ pub fn base_probability(quality_q8: u8) -> u8 { unimplemented!() } pub fn retry_success_probability(attempt: u8, quality_q8: u8) -> u8 { let base_prob: u8 = base_probability(quality_q8); + let decay: u8 = ((base_prob / 4) * attempt); } pub fn total_retry_time(max_retries: u8) -> u16 { unimplemented!() } diff --git a/gen/rust/anomaly_detector.rs b/gen/rust/anomaly_detector.rs index 6a4b5a69..9a93b433 100644 --- a/gen/rust/anomaly_detector.rs +++ b/gen/rust/anomaly_detector.rs @@ -67,12 +67,12 @@ pub const TYPE_PATTERN: u32 = 2; pub const TYPE_TREND: u32 = 3; -pub fn calculate_baseline(history: Vec, count: u32) -> u32 { +pub fn calculate_baseline(history: [u32; MAX_METRICS as usize], count: u32) -> u32 { let mut sum: u32 = 0; let mut valid_count: u32 = 0; let mut i: u32 = 0; while (i < count) { - let value: u32 = get_metric_value(history[i]); + let value: u32 = get_metric_value(history[(i) as usize]); sum = (sum + value); valid_count = (valid_count + 1); i = (i + 1); @@ -84,11 +84,11 @@ pub fn calculate_baseline(history: Vec, count: u32) -> u32 { } } -pub fn calculate_variance(history: Vec, count: u32, baseline: u32) -> u32 { +pub fn calculate_variance(history: [u32; MAX_METRICS as usize], count: u32, baseline: u32) -> u32 { let mut sum_diff: u32 = 0; let mut i: u32 = 0; while (i < count) { - let value: u32 = get_metric_value(history[i]); + let value: u32 = get_metric_value(history[(i) as usize]); let mut diff: u32 = 0; if (value > baseline) { diff = (value - baseline); @@ -139,16 +139,16 @@ pub fn detect_drop(current: u32, baseline: u32, variance: u32) -> u32 { return 0; } -pub fn detect_pattern(history: Vec, count: u32) -> u32 { +pub fn detect_pattern(history: [u32; MAX_METRICS as usize], count: u32) -> u32 { if (count < 4) { return 0; } let mut pattern_count: u32 = 0; let mut i: u32 = 0; while (i < (count - 2)) { - let val1: u32 = get_metric_value(history[i]); - let val2: u32 = get_metric_value(history[(i + 1)]); - let val3: u32 = get_metric_value(history[(i + 2)]); + let val1: u32 = get_metric_value(history[(i) as usize]); + let val2: u32 = get_metric_value(history[(i + 1) as usize]); + let val3: u32 = get_metric_value(history[(i + 2) as usize]); if (((val1 > val2) && (val2 < val3)) || ((val1 < val2) && (val2 > val3))) { pattern_count = (pattern_count + 1); } @@ -161,7 +161,7 @@ pub fn detect_pattern(history: Vec, count: u32) -> u32 { } } -pub fn detect_trend(history: Vec, count: u32) -> u32 { +pub fn detect_trend(history: [u32; MAX_METRICS as usize], count: u32) -> u32 { if (count < 4) { return 0; } @@ -169,8 +169,8 @@ pub fn detect_trend(history: Vec, count: u32) -> u32 { let mut decreases: u32 = 0; let mut i: u32 = 0; while (i < (count - 1)) { - let current: u32 = get_metric_value(history[i]); - let next: u32 = get_metric_value(history[(i + 1)]); + let current: u32 = get_metric_value(history[(i) as usize]); + let next: u32 = get_metric_value(history[(i + 1) as usize]); if (next > current) { increases = (increases + 1); } else { @@ -209,7 +209,11 @@ pub fn calculate_severity(current: u32, baseline: u32) -> u32 { } } -pub fn detect_anomaly(history: Vec, count: u32, current_reading: u32) -> u32 { +pub fn detect_anomaly( + history: [u32; MAX_METRICS as usize], + count: u32, + current_reading: u32, +) -> u32 { if (count < BASELINE_WINDOW) { return 0; } @@ -278,8 +282,8 @@ pub fn get_anomaly_description(report: u32) -> u32 { pub fn correlate_metrics( metric1_id: u32, metric2_id: u32, - history1: Vec, - history2: Vec, + history1: [u32; MAX_METRICS as usize], + history2: [u32; MAX_METRICS as usize], count: u32, ) -> u32 { if (count < 4) { @@ -288,10 +292,10 @@ pub fn correlate_metrics( let mut same_direction: u32 = 0; let mut i: u32 = 0; while (i < (count - 1)) { - let val1_current: u32 = get_metric_value(history1[i]); - let val1_next: u32 = get_metric_value(history1[(i + 1)]); - let val2_current: u32 = get_metric_value(history2[i]); - let val2_next: u32 = get_metric_value(history2[(i + 1)]); + let val1_current: u32 = get_metric_value(history1[(i) as usize]); + let val1_next: u32 = get_metric_value(history1[(i + 1) as usize]); + let val2_current: u32 = get_metric_value(history2[(i) as usize]); + let val2_next: u32 = get_metric_value(history2[(i + 1) as usize]); let mut direction1: u32 = 0; if (val1_next > val1_current) { direction1 = 1; @@ -320,11 +324,11 @@ pub fn correlate_metrics( } } -pub fn detect_coordinated_attack(anomalies: Vec, count: u32) -> u32 { +pub fn detect_coordinated_attack(anomalies: [u32; MAX_METRICS as usize], count: u32) -> u32 { let mut critical_count: u32 = 0; let mut i: u32 = 0; while (i < count) { - if (is_critical_anomaly(anomalies[i]) == 1) { + if (is_critical_anomaly(anomalies[(i) as usize]) == 1) { critical_count = (critical_count + 1); } i = (i + 1); diff --git a/gen/rust/api_documenter.rs b/gen/rust/api_documenter.rs index 5bd94b1c..1f195640 100644 --- a/gen/rust/api_documenter.rs +++ b/gen/rust/api_documenter.rs @@ -92,8 +92,10 @@ pub fn get_example_explanation(example: u32) -> u32 { pub fn generate_function_example(func_doc: u32) -> u32 { let func_id: u32 = get_doc_function_id(func_doc); let param_count: u32 = get_doc_param_count(func_doc); + let return_type: u32 = get_doc_return_type(func_doc); let example_input: u32 = (param_count * 10); let example_output: u32 = (example_input + 5); + let explanation: u32 = 1; return create_function_example(func_id, example_input, example_output, 1); } @@ -119,10 +121,14 @@ pub fn get_description_category(desc: u32) -> u32 { pub fn generate_function_description(func_doc: u32, complexity: u32) -> u32 { let func_id: u32 = get_doc_function_id(func_doc); + let param_count: u32 = get_doc_param_count(func_doc); + let return_type: u32 = get_doc_return_type(func_doc); let mut desc_length: u32 = (50 + (complexity * 10)); if (desc_length > 255) { desc_length = 255; } + let importance: u32 = 1; + let category: u32 = 0; return create_description_text(func_id, desc_length, 1, 0); } @@ -178,11 +184,11 @@ pub fn get_module_description(module_doc: u32) -> u32 { return (module_doc & 0xFF); } -pub fn calculate_average_complexity(func_docs: Vec<>, func_count: u32) -> u32 { +pub fn calculate_average_complexity(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32) -> u32 { let mut total_complexity: u32 = 0; let mut i: u32 = 0; while (i < func_count) { - total_complexity = (total_complexity + get_doc_complexity(func_docs[i])); + total_complexity = (total_complexity + get_doc_complexity(func_docs[(i) as usize])); i = (i + 1); } if (func_count > 0) { @@ -192,12 +198,12 @@ pub fn calculate_average_complexity(func_docs: Vec<>, func_count: u32) -> u32 { } } -pub fn generate_api_documentation(func_docs: Vec<>, func_count: u32, param_docs: Vec<>, param_count: u32) -> u32 { +pub fn generate_api_documentation(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32, param_docs: [u32; MAX_PARAMETERS as usize], param_count: u32) -> u32 { let mut total_complexity: u32 = 0; let mut documented_funcs: u32 = 0; let mut i: u32 = 0; while (i < func_count) { - let func_doc: u32 = func_docs[i]; + let func_doc: u32 = func_docs[(i) as usize]; total_complexity = (total_complexity + get_doc_complexity(func_doc)); let description: u32 = generate_function_description(func_doc, get_doc_complexity(func_doc)); let example: u32 = generate_function_example(func_doc); @@ -223,12 +229,12 @@ pub fn generate_usage_example(func_doc: u32, context: u32) -> u32 { return create_function_example(func_id, usage_pattern, (usage_pattern + 10), 2); } -pub fn create_dependency_graph(xrefs: Vec<>, xref_count: u32) -> u32 { +pub fn create_dependency_graph(xrefs: [u32; MAX_FUNCTIONS as usize], xref_count: u32) -> u32 { let mut total_connections: u32 = 0; let mut strong_connections: u32 = 0; let mut i: u32 = 0; while (i < xref_count) { - let strength: u32 = get_xref_strength(xrefs[i]); + let strength: u32 = get_xref_strength(xrefs[(i) as usize]); total_connections = (total_connections + 1); if (strength > 70) { strong_connections = (strong_connections + 1); @@ -242,12 +248,13 @@ pub fn create_dependency_graph(xrefs: Vec<>, xref_count: u32) -> u32 { return (((((total_connections & 0xFF) << 24) | ((strong_connections & 0xFF) << 16)) | ((avg_strength & 0xFF) << 8)) | (xref_count & 0xFF)); } -pub fn validate_documentation(func_docs: Vec<>, func_count: u32) -> u32 { +pub fn validate_documentation(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32) -> u32 { let mut missing_descriptions: u32 = 0; + let missing_examples: u32 = 0; let mut missing_params: u32 = 0; let mut i: u32 = 0; while (i < func_count) { - let func_doc: u32 = func_docs[i]; + let func_doc: u32 = func_docs[(i) as usize]; let complexity: u32 = get_doc_complexity(func_doc); if (complexity == 0) { missing_descriptions = (missing_descriptions + 1); @@ -265,12 +272,13 @@ pub fn validate_documentation(func_docs: Vec<>, func_count: u32) -> u32 { return (((((missing_descriptions & 0xFF) << 24) | 0) | ((missing_params & 0xFF) << 8)) | (quality_score & 0xFF)); } -pub fn generate_documentation_report(func_docs: Vec<>, func_count: u32, xrefs: Vec<>, xref_count: u32) -> u32 { +pub fn generate_documentation_report(func_docs: [u32; MAX_FUNCTIONS as usize], func_count: u32, xrefs: [u32; MAX_FUNCTIONS as usize], xref_count: u32) -> u32 { let doc_summary: u32 = generate_api_documentation(func_docs, func_count, func_docs, 0); let documented_funcs: u32 = ((doc_summary >> 24) & 0xFF); let coverage: u32 = calculate_documentation_coverage(documented_funcs, func_count); let validation: u32 = validate_documentation(func_docs, func_count); let quality_score: u32 = (validation & 0xFF); + let dependency_graph: u32 = create_dependency_graph(xrefs, xref_count); let doc_complexity: u32 = ((doc_summary >> 8) & 0xFF); return (((((coverage & 0xFF) << 24) | ((quality_score & 0xFF) << 16)) | ((doc_complexity & 0xFF) << 8)) | (xref_count & 0xFF)); } diff --git a/gen/rust/auto_config.rs b/gen/rust/auto_config.rs index 73ec90f8..a1cb0987 100644 --- a/gen/rust/auto_config.rs +++ b/gen/rust/auto_config.rs @@ -61,31 +61,31 @@ pub const PARAM_QOS_ENABLED: u32 = 6; pub const PARAM_SECURITY_LEVEL: u32 = 7; -pub fn create_default_config() -> Vec<> { - let config: Vec<> = vec![]; +pub fn create_default_config() -> [u32; MAX_PARAMS as usize] { + let config: [u32; MAX_PARAMS as usize] = vec![]; return config; } -pub fn get_config_value(config: Vec<>, param_id: u32) -> u32 { +pub fn get_config_value(config: [u32; MAX_PARAMS as usize], param_id: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_PARAMS) { - let current_param_id: u32 = get_param_id(config[i]); + let current_param_id: u32 = get_param_id(config[(i) as usize]); if (current_param_id == param_id) { - return get_param_value(config[i]); + return get_param_value(config[(i) as usize]); } i = (i + 1); } return 0; } -pub fn set_config_value(config: Vec<>, param_id: u32, new_value: u32) -> u32 { +pub fn set_config_value(config: [u32; MAX_PARAMS as usize], param_id: u32, new_value: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_PARAMS) { - let current_param_id: u32 = get_param_id(config[i]); + let current_param_id: u32 = get_param_id(config[(i) as usize]); if (current_param_id == param_id) { - let scope: u32 = get_param_scope(config[i]); + let scope: u32 = get_param_scope(config[(i) as usize]); let status: u32 = STATUS_PENDING; - config[i] = create_config_param(param_id, new_value, scope, status); + config[(i) as usize] = create_config_param(param_id, new_value, scope, status); return 1; } i = (i + 1); @@ -94,7 +94,7 @@ pub fn set_config_value(config: Vec<>, param_id: u32, new_value: u32) -> u32 { } pub fn discover_network_params(node_count: u32, interference_level: u32) -> u32 { - let config: Vec<> = create_default_config(); + let config: [u32; MAX_PARAMS as usize] = create_default_config(); let mut tx_power: u32 = 50; if (node_count < 4) { tx_power = 30; @@ -125,15 +125,15 @@ pub fn discover_network_params(node_count: u32, interference_level: u32) -> u32 return 1; } -pub fn apply_config(config: Vec<>, param_id: u32) -> u32 { +pub fn apply_config(config: [u32; MAX_PARAMS as usize], param_id: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_PARAMS) { - let current_param_id: u32 = get_param_id(config[i]); + let current_param_id: u32 = get_param_id(config[(i) as usize]); if (current_param_id == param_id) { - let value: u32 = get_param_value(config[i]); - let scope: u32 = get_param_scope(config[i]); + let value: u32 = get_param_value(config[(i) as usize]); + let scope: u32 = get_param_scope(config[(i) as usize]); let success: u32 = 1; - config[i] = create_config_param(param_id, value, scope, STATUS_APPLIED); + config[(i) as usize] = create_config_param(param_id, value, scope, STATUS_APPLIED); return success; } i = (i + 1); @@ -141,13 +141,13 @@ pub fn apply_config(config: Vec<>, param_id: u32) -> u32 { return 0; } -pub fn apply_all_pending(config: Vec<>) -> u32 { +pub fn apply_all_pending(config: [u32; MAX_PARAMS as usize]) -> u32 { let mut applied_count: u32 = 0; let mut i: u32 = 0; while (i < MAX_PARAMS) { - let status: u32 = get_param_status(config[i]); + let status: u32 = get_param_status(config[(i) as usize]); if (status == STATUS_PENDING) { - let param_id: u32 = get_param_id(config[i]); + let param_id: u32 = get_param_id(config[(i) as usize]); if (apply_config(config, param_id) == 1) { applied_count = (applied_count + 1); } @@ -157,7 +157,7 @@ pub fn apply_all_pending(config: Vec<>) -> u32 { return applied_count; } -pub fn validate_config(config: Vec<>, param_id: u32) -> u32 { +pub fn validate_config(config: [u32; MAX_PARAMS as usize], param_id: u32) -> u32 { let value: u32 = get_config_value(config, param_id); if (param_id == PARAM_TX_POWER) { if ((value >= 0) && (value <= 100)) { @@ -209,7 +209,7 @@ pub fn validate_config(config: Vec<>, param_id: u32) -> u32 { return 0; } -pub fn optimize_config(config: Vec<>, network_load: u32, error_rate: u32) -> u32 { +pub fn optimize_config(config: [u32; MAX_PARAMS as usize], network_load: u32, error_rate: u32) -> u32 { let mut optimizations: u32 = 0; if (network_load > 80) { let current_retries: u32 = get_config_value(config, PARAM_RETRY_LIMIT); @@ -235,19 +235,19 @@ pub fn optimize_config(config: Vec<>, network_load: u32, error_rate: u32) -> u32 return optimizations; } -pub fn sync_config(local_config: Vec<>, remote_config: Vec<>) -> u32 { +pub fn sync_config(local_config: [u32; MAX_PARAMS as usize], remote_config: [u32; MAX_PARAMS as usize]) -> u32 { let mut synced_count: u32 = 0; let mut i: u32 = 0; while (i < MAX_PARAMS) { - let local_param_id: u32 = get_param_id(local_config[i]); - let local_value: u32 = get_param_value(local_config[i]); - let local_scope: u32 = get_param_scope(local_config[i]); + let local_param_id: u32 = get_param_id(local_config[(i) as usize]); + let local_value: u32 = get_param_value(local_config[(i) as usize]); + let local_scope: u32 = get_param_scope(local_config[(i) as usize]); let mut j: u32 = 0; while (j < MAX_PARAMS) { - let remote_param_id: u32 = get_param_id(remote_config[j]); + let remote_param_id: u32 = get_param_id(remote_config[(j) as usize]); if (remote_param_id == local_param_id) { - let remote_value: u32 = get_param_value(remote_config[j]); - let remote_scope: u32 = get_param_scope(remote_config[j]); + let remote_value: u32 = get_param_value(remote_config[(j) as usize]); + let remote_scope: u32 = get_param_scope(remote_config[(j) as usize]); if ((remote_scope == SCOPE_NETWORK) || (remote_scope == SCOPE_GLOBAL)) { if (remote_value != local_value) { set_config_value(local_config, local_param_id, remote_value); @@ -263,18 +263,18 @@ pub fn sync_config(local_config: Vec<>, remote_config: Vec<>) -> u32 { return synced_count; } -pub fn rollback_config(config: Vec<>, backup_config: Vec<>) -> u32 { +pub fn rollback_config(config: [u32; MAX_PARAMS as usize], backup_config: [u32; MAX_PARAMS as usize]) -> u32 { let mut rolled_back: u32 = 0; let mut i: u32 = 0; while (i < MAX_PARAMS) { - let backup_param_id: u32 = get_param_id(backup_config[i]); - let backup_value: u32 = get_param_value(backup_config[i]); - let backup_scope: u32 = get_param_scope(backup_config[i]); + let backup_param_id: u32 = get_param_id(backup_config[(i) as usize]); + let backup_value: u32 = get_param_value(backup_config[(i) as usize]); + let backup_scope: u32 = get_param_scope(backup_config[(i) as usize]); let mut j: u32 = 0; while (j < MAX_PARAMS) { - let local_param_id: u32 = get_param_id(config[j]); + let local_param_id: u32 = get_param_id(config[(j) as usize]); if (local_param_id == backup_param_id) { - config[j] = create_config_param(backup_param_id, backup_value, backup_scope, STATUS_PENDING); + config[(j) as usize] = create_config_param(backup_param_id, backup_value, backup_scope, STATUS_PENDING); rolled_back = (rolled_back + 1); break; } @@ -285,28 +285,28 @@ pub fn rollback_config(config: Vec<>, backup_config: Vec<>) -> u32 { return rolled_back; } -pub fn create_backup(config: Vec<>) -> Vec<> { - let mut backup: Vec<>; +pub fn create_backup(config: [u32; MAX_PARAMS as usize]) -> [u32; MAX_PARAMS as usize] { + let mut backup: [u32; MAX_PARAMS as usize]; let mut i: u32 = 0; while (i < MAX_PARAMS) { - backup[i] = config[i]; + backup[(i) as usize] = config[(i) as usize]; i = (i + 1); } return backup; } -pub fn calculate_config_drift(config1: Vec<>, config2: Vec<>) -> u32 { +pub fn calculate_config_drift(config1: [u32; MAX_PARAMS as usize], config2: [u32; MAX_PARAMS as usize]) -> u32 { let mut drift_count: u32 = 0; let mut total_params: u32 = 0; let mut i: u32 = 0; while (i < MAX_PARAMS) { - let param1_id: u32 = get_param_id(config1[i]); - let param1_value: u32 = get_param_value(config1[i]); + let param1_id: u32 = get_param_id(config1[(i) as usize]); + let param1_value: u32 = get_param_value(config1[(i) as usize]); let mut j: u32 = 0; while (j < MAX_PARAMS) { - let param2_id: u32 = get_param_id(config2[j]); + let param2_id: u32 = get_param_id(config2[(j) as usize]); if (param1_id == param2_id) { - let param2_value: u32 = get_param_value(config2[j]); + let param2_value: u32 = get_param_value(config2[(j) as usize]); if (param1_value != param2_value) { drift_count = (drift_count + 1); } @@ -336,13 +336,13 @@ pub fn discover_neighbors(node_id: u32, scan_count: u32) -> u32 { pub fn assign_node_role(node_id: u32, capabilities: u32) -> u32 { let mut role: u32 = 0; - if (capabilities & 0x1) { + if ((capabilities & 0x1)) != 0 { role = 1; } else { - if (capabilities & 0x2) { + if ((capabilities & 0x2)) != 0 { role = 2; } else { - if (capabilities & 0x4) { + if ((capabilities & 0x4)) != 0 { role = 3; } } diff --git a/gen/rust/bandwidth_allocator.rs b/gen/rust/bandwidth_allocator.rs index 526cf903..1f8a8e95 100644 --- a/gen/rust/bandwidth_allocator.rs +++ b/gen/rust/bandwidth_allocator.rs @@ -197,6 +197,7 @@ pub fn find_reclaimable_bandwidth(state: u32, flow_array: u64) -> u32 { } pub fn prioritize_bandwidth(flow_array: u64, available_bw: u32) -> u64 { + let remaining_bw = available_bw; let f0 = get_flow_req(flow_array, 0); let f1 = get_flow_req(flow_array, 1); let f2 = get_flow_req(flow_array, 2); diff --git a/gen/rust/cache_management.rs b/gen/rust/cache_management.rs index 1e4f0dea..04a9d5af 100644 --- a/gen/rust/cache_management.rs +++ b/gen/rust/cache_management.rs @@ -47,10 +47,10 @@ pub fn update_age(entry: u32, new_age: u32) -> u32 { return create_cache_entry(data_id, access_count, new_age, size); } -pub fn find_entry(cache: Vec<>, data_id: u32) -> u32 { +pub fn find_entry(cache: [u32; MAX_ENTRIES as usize], data_id: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_ENTRIES) { - let entry_data_id: u32 = get_data_id(cache[i]); + let entry_data_id: u32 = get_data_id(cache[(i) as usize]); if (entry_data_id == data_id) { return i; } @@ -59,7 +59,7 @@ pub fn find_entry(cache: Vec<>, data_id: u32) -> u32 { return MAX_ENTRIES; } -pub fn cache_hit(cache: Vec<>, data_id: u32) -> u32 { +pub fn cache_hit(cache: [u32; MAX_ENTRIES as usize], data_id: u32) -> u32 { let entry_index: u32 = find_entry(cache, data_id); if (entry_index < MAX_ENTRIES) { return 1; @@ -68,16 +68,16 @@ pub fn cache_hit(cache: Vec<>, data_id: u32) -> u32 { } } -pub fn get_entry(cache: Vec<>, data_id: u32) -> u32 { +pub fn get_entry(cache: [u32; MAX_ENTRIES as usize], data_id: u32) -> u32 { let entry_index: u32 = find_entry(cache, data_id); if (entry_index < MAX_ENTRIES) { - return cache[entry_index]; + return cache[(entry_index) as usize]; } else { return 0; } } -pub fn add_entry(cache: Vec<>, current_size: u32, data_id: u32, size: u32) -> u32 { +pub fn add_entry(cache: [u32; MAX_ENTRIES as usize], current_size: u32, data_id: u32, size: u32) -> u32 { let existing_index: u32 = find_entry(cache, data_id); if (existing_index < MAX_ENTRIES) { return current_size; @@ -85,7 +85,7 @@ pub fn add_entry(cache: Vec<>, current_size: u32, data_id: u32, size: u32) -> u3 let mut empty_index: u32 = MAX_ENTRIES; let mut i: u32 = 0; while (i < MAX_ENTRIES) { - if (get_data_id(cache[i]) == 0) { + if (get_data_id(cache[(i) as usize]) == 0) { empty_index = i; break; } @@ -96,22 +96,22 @@ pub fn add_entry(cache: Vec<>, current_size: u32, data_id: u32, size: u32) -> u3 if (empty_index == MAX_ENTRIES) { return current_size; } - let evicted_size: u32 = get_entry_size(cache[empty_index]); + let evicted_size: u32 = get_entry_size(cache[(empty_index) as usize]); current_size = (current_size - evicted_size); } if ((current_size + size) > MAX_CACHE_SIZE) { return current_size; } - cache[empty_index] = create_cache_entry(data_id, 1, 0, size); + cache[(empty_index) as usize] = create_cache_entry(data_id, 1, 0, size); return (current_size + size); } -pub fn find_eviction_candidate(cache: Vec<>) -> u32 { +pub fn find_eviction_candidate(cache: [u32; MAX_ENTRIES as usize]) -> u32 { let mut worst_score: u32 = 0xFFFFFFFF; let mut candidate: u32 = MAX_ENTRIES; let mut i: u32 = 0; while (i < MAX_ENTRIES) { - let entry: u32 = cache[i]; + let entry: u32 = cache[(i) as usize]; let data_id: u32 = get_data_id(entry); if (data_id != 0) { let access_count: u32 = get_access_count(entry); @@ -127,35 +127,35 @@ pub fn find_eviction_candidate(cache: Vec<>) -> u32 { return candidate; } -pub fn remove_entry(cache: Vec<>, current_size: u32, data_id: u32) -> u32 { +pub fn remove_entry(cache: [u32; MAX_ENTRIES as usize], current_size: u32, data_id: u32) -> u32 { let entry_index: u32 = find_entry(cache, data_id); if (entry_index < MAX_ENTRIES) { - let entry_size: u32 = get_entry_size(cache[entry_index]); - cache[entry_index] = 0; + let entry_size: u32 = get_entry_size(cache[(entry_index) as usize]); + cache[(entry_index) as usize] = 0; return (current_size - entry_size); } else { return current_size; } } -pub fn access_cache(cache: Vec<>, data_id: u32) -> u32 { +pub fn access_cache(cache: [u32; MAX_ENTRIES as usize], data_id: u32) -> u32 { let entry_index: u32 = find_entry(cache, data_id); if (entry_index < MAX_ENTRIES) { - cache[entry_index] = update_access_count(cache[entry_index]); - cache[entry_index] = update_age(cache[entry_index], 0); + cache[(entry_index) as usize] = update_access_count(cache[(entry_index) as usize]); + cache[(entry_index) as usize] = update_age(cache[(entry_index) as usize], 0); return 1; } else { return 0; } } -pub fn age_cache(cache: Vec<>) -> () { +pub fn age_cache(cache: [u32; MAX_ENTRIES as usize]) -> () { let mut i: u32 = 0; while (i < MAX_ENTRIES) { - let entry: u32 = cache[i]; + let entry: u32 = cache[(i) as usize]; let age: u32 = get_age(entry); if (age < 255) { - cache[i] = update_age(entry, (age + 1)); + cache[(i) as usize] = update_age(entry, (age + 1)); } i = (i + 1); } @@ -173,12 +173,12 @@ pub fn calculate_utilization(current_size: u32) -> u32 { return ((current_size * 100) / MAX_CACHE_SIZE); } -pub fn find_most_popular(cache: Vec<>) -> u32 { +pub fn find_most_popular(cache: [u32; MAX_ENTRIES as usize]) -> u32 { let mut max_access: u32 = 0; let mut popular_index: u32 = MAX_ENTRIES; let mut i: u32 = 0; while (i < MAX_ENTRIES) { - let access_count: u32 = get_access_count(cache[i]); + let access_count: u32 = get_access_count(cache[(i) as usize]); if (access_count > max_access) { max_access = access_count; popular_index = i; @@ -188,12 +188,12 @@ pub fn find_most_popular(cache: Vec<>) -> u32 { return popular_index; } -pub fn find_least_popular(cache: Vec<>) -> u32 { +pub fn find_least_popular(cache: [u32; MAX_ENTRIES as usize]) -> u32 { let mut min_access: u32 = 0xFFFFFFFF; let mut unpopular_index: u32 = MAX_ENTRIES; let mut i: u32 = 0; while (i < MAX_ENTRIES) { - let entry: u32 = cache[i]; + let entry: u32 = cache[(i) as usize]; let data_id: u32 = get_data_id(entry); let access_count: u32 = get_access_count(entry); if ((data_id != 0) && (access_count < min_access)) { @@ -205,13 +205,13 @@ pub fn find_least_popular(cache: Vec<>) -> u32 { return unpopular_index; } -pub fn should_prefetch(cache: Vec<>, data_id: u32) -> u32 { +pub fn should_prefetch(cache: [u32; MAX_ENTRIES as usize], data_id: u32) -> u32 { let popular_index: u32 = find_most_popular(cache); if (popular_index < MAX_ENTRIES) { - let popular_access: u32 = get_access_count(cache[popular_index]); + let popular_access: u32 = get_access_count(cache[(popular_index) as usize]); let entry_index: u32 = find_entry(cache, data_id); if (entry_index < MAX_ENTRIES) { - let access_count: u32 = get_access_count(cache[entry_index]); + let access_count: u32 = get_access_count(cache[(entry_index) as usize]); if (access_count >= CACHE_HIT_THRESHOLD) { return 1; } diff --git a/gen/rust/compression_engine.rs b/gen/rust/compression_engine.rs index 3957f4b9..fedb0e79 100644 --- a/gen/rust/compression_engine.rs +++ b/gen/rust/compression_engine.rs @@ -83,12 +83,12 @@ pub fn decompress_rle(compressed: u32) -> u32 { return decompressed; } -pub fn compress_dictionary(data: u32, dictionary: Vec<>) -> u32 { +pub fn compress_dictionary(data: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { let mut best_match: u32 = 0; let mut best_score: u32 = 0; let mut i: u32 = 0; while (i < DICTIONARY_SIZE) { - let dict_value: u32 = dictionary[i]; + let dict_value: u32 = dictionary[(i) as usize]; let mut score: u32 = 0; let mut j: u32 = 0; while (j < 8) { @@ -108,9 +108,9 @@ pub fn compress_dictionary(data: u32, dictionary: Vec<>) -> u32 { return best_match; } -pub fn decompress_dictionary(index: u32, dictionary: Vec<>) -> u32 { +pub fn decompress_dictionary(index: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { if (index < DICTIONARY_SIZE) { - return dictionary[index]; + return dictionary[(index) as usize]; } else { return 0; } @@ -162,7 +162,8 @@ pub fn decompress_delta(encoded: u32, previous: u32) -> u32 { } } -pub fn choose_compression_method(data: u32, previous: u32, dictionary: Vec<>) -> u32 { +pub fn choose_compression_method(data: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { + let data_nibbles: u32 = 8; let rle_compressed: u32 = compress_rle(data, 8); let rle_ratio: u32 = calculate_compression_ratio(8, rle_compressed); let delta_compressed: u32 = compress_delta(data, previous); @@ -188,7 +189,7 @@ pub fn choose_compression_method(data: u32, previous: u32, dictionary: Vec<>) -> } } -pub fn compress_block(data: u32, previous: u32, dictionary: Vec<>) -> u32 { +pub fn compress_block(data: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { let method: u32 = choose_compression_method(data, previous, dictionary); let mut compressed: u32 = 0; let mut compressed_size: u32 = 8; @@ -215,7 +216,7 @@ pub fn compress_block(data: u32, previous: u32, dictionary: Vec<>) -> u32 { return create_block_info(8, compressed_size, method, compressed_size); } -pub fn decompress_block(compressed_data: u32, method: u32, previous: u32, dictionary: Vec<>) -> u32 { +pub fn decompress_block(compressed_data: u32, method: u32, previous: u32, dictionary: [u32; DICTIONARY_SIZE as usize]) -> u32 { if (method == METHOD_RLE) { return decompress_rle(compressed_data); } else { @@ -231,13 +232,13 @@ pub fn decompress_block(compressed_data: u32, method: u32, previous: u32, dictio } } -pub fn calculate_total_savings(blocks: Vec<>, count: u32) -> u32 { +pub fn calculate_total_savings(blocks: [u32; MAX_BLOCKS as usize], count: u32) -> u32 { let mut total_original: u32 = 0; let mut total_compressed: u32 = 0; let mut i: u32 = 0; while (i < count) { - total_original = (total_original + get_original_size(blocks[i])); - total_compressed = (total_compressed + get_compressed_size(blocks[i])); + total_original = (total_original + get_original_size(blocks[(i) as usize])); + total_compressed = (total_compressed + get_compressed_size(blocks[(i) as usize])); i = (i + 1); } if (total_compressed > 0) { @@ -247,9 +248,9 @@ pub fn calculate_total_savings(blocks: Vec<>, count: u32) -> u32 { } } -pub fn update_dictionary(dictionary: Vec<>, new_entry: u32, index: u32) -> u32 { +pub fn update_dictionary(dictionary: [u32; DICTIONARY_SIZE as usize], new_entry: u32, index: u32) -> u32 { if (index < DICTIONARY_SIZE) { - dictionary[index] = new_entry; + dictionary[(index) as usize] = new_entry; return 1; } else { return 0; @@ -257,6 +258,7 @@ pub fn update_dictionary(dictionary: Vec<>, new_entry: u32, index: u32) -> u32 { } pub fn find_pattern(data: u32, pattern: u32) -> u32 { + let mask: u32 = 0xFFFFFFFF; let mut i: u32 = 0; while (i < 32) { let shifted: u32 = ((data >> i) & 0xFFFFFFFF); diff --git a/gen/rust/congestion_control.rs b/gen/rust/congestion_control.rs index 92874c1f..2a05b9d4 100644 --- a/gen/rust/congestion_control.rs +++ b/gen/rust/congestion_control.rs @@ -91,6 +91,7 @@ pub fn on_triple_dup_ack(congestion: u32) -> u32 { let mut ssthresh: u32 = get_ssthresh(congestion); let mut state: u32 = get_congestion_state(congestion); let losses: u32 = get_loss_count(congestion); + let old_cwnd: u32 = cwnd; ssthresh = (cwnd / 2); if (ssthresh < MIN_WINDOW) { ssthresh = MIN_WINDOW; @@ -139,7 +140,7 @@ pub fn estimate_bandwidth(congestion: u32, rtt: u32, packet_size: u32) -> u32 { } } -pub fn find_congestion_controller(controllers: Vec<>, flow_id: u32) -> u32 { +pub fn find_congestion_controller(controllers: [u32; MAX_FLOWS as usize], flow_id: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_FLOWS) { if (i == flow_id) { @@ -150,10 +151,10 @@ pub fn find_congestion_controller(controllers: Vec<>, flow_id: u32) -> u32 { return MAX_FLOWS; } -pub fn is_any_flow_congested(controllers: Vec<>) -> u32 { +pub fn is_any_flow_congested(controllers: [u32; MAX_FLOWS as usize]) -> u32 { let mut i: u32 = 0; while (i < MAX_FLOWS) { - if (is_congested(controllers[i]) == 1) { + if (is_congested(controllers[(i) as usize]) == 1) { return 1; } i = (i + 1); @@ -161,21 +162,21 @@ pub fn is_any_flow_congested(controllers: Vec<>) -> u32 { return 0; } -pub fn calculate_total_cwnd(controllers: Vec<>) -> u32 { +pub fn calculate_total_cwnd(controllers: [u32; MAX_FLOWS as usize]) -> u32 { let mut total: u32 = 0; let mut i: u32 = 0; while (i < MAX_FLOWS) { - total = (total + get_cwnd(controllers[i])); + total = (total + get_cwnd(controllers[(i) as usize])); i = (i + 1); } return total; } -pub fn allocate_fair_bandwidth(controllers: Vec<>, total_bandwidth: u32) -> u32 { +pub fn allocate_fair_bandwidth(controllers: [u32; MAX_FLOWS as usize], total_bandwidth: u32) -> u32 { let mut active_flows: u32 = 0; let mut i: u32 = 0; while (i < MAX_FLOWS) { - let cwnd: u32 = get_cwnd(controllers[i]); + let cwnd: u32 = get_cwnd(controllers[(i) as usize]); if (cwnd > 0) { active_flows = (active_flows + 1); } diff --git a/gen/rust/crypto_frame.rs b/gen/rust/crypto_frame.rs new file mode 100644 index 00000000..16932b2e --- /dev/null +++ b/gen/rust/crypto_frame.rs @@ -0,0 +1,119 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const EPOCH_LEN: usize = 4; + +pub const COUNTER_LEN: usize = 8; + +pub const HEADER_LEN: usize = 12; + +pub const TAG_LEN: usize = 16; + +pub const NONCE_LEN: usize = 12; + +pub fn counter_offset() -> usize { + return EPOCH_LEN; +} + +pub fn ciphertext_offset() -> usize { + return HEADER_LEN; +} + +pub fn frame_len_ok(byte_len: usize) -> bool { + return (byte_len >= HEADER_LEN); +} + +pub const REKEY_EVERY_FRAMES: u64 = 1048576; + +pub const REKEY_HARD_CAP: u64 = 16777216; + +pub fn should_ratchet(tx_counter: u64) -> bool { + return (tx_counter >= REKEY_EVERY_FRAMES); +} + +pub fn must_reject(tx_counter: u64) -> bool { + return (tx_counter >= REKEY_HARD_CAP); +} + +pub fn nonce_byte(dir: u8, epoch: u32, ctr: u64, i: u32) -> u32 { + if (i == 0) { + return dir; + } + if (i < 5) { + return ((epoch >> ((4 - i) * 8)) & 255); + } + return ((ctr >> ((11 - i) << 3)) & 255); +} + +pub fn rx_dir(tx_dir: u8) -> u8 { + return (1 - tx_dir); +} + +pub const WINDOW_WIDTH: u64 = 64; + +pub fn replay_accept(seen_any: bool, top: u64, blo: u32, bhi: u32, ctr: u64) -> bool { + if ((seen_any) == 0) { + return true; + } + if (ctr > top) { + return true; + } + let d: u64 = (top - ctr); + if (d >= WINDOW_WIDTH) { + return false; + } + if (d < 32) { + return ((blo & (1 << d)) == 0); + } + return ((bhi & (1 << (d - 32))) == 0); +} + +pub fn replay_next_top(seen_any: bool, top: u64, ctr: u64) -> u64 { + if ((seen_any) == 0) { + return ctr; + } + if (ctr > top) { + return ctr; + } + return top; +} + +pub fn replay_next_blo(seen_any: bool, top: u64, blo: u32, bhi: u32, ctr: u64) -> u32 { + if ((seen_any) == 0) { + return 1; + } + if (ctr > top) { + let s: u64 = (ctr - top); + if (s >= 32) { + return 1; + } + return ((blo << s) | 1); + } + let d: u64 = (top - ctr); + if (d < 32) { + return (blo | (1 << d)); + } + return blo; +} + +pub fn replay_next_bhi(seen_any: bool, top: u64, blo: u32, bhi: u32, ctr: u64) -> u32 { + if ((seen_any) == 0) { + return 0; + } + if (ctr > top) { + let s: u64 = (ctr - top); + if (s >= WINDOW_WIDTH) { + return 0; + } + if (s >= 32) { + return (blo << (s - 32)); + } + return ((bhi << s) | (blo >> (32 - s))); + } + let d: u64 = (top - ctr); + if (d >= 32) { + return (bhi | (1 << (d - 32))); + } + return bhi; +} + diff --git a/gen/rust/discovery.rs b/gen/rust/discovery.rs new file mode 100644 index 00000000..780d1e2d --- /dev/null +++ b/gen/rust/discovery.rs @@ -0,0 +1,31 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const HDR_LEN: usize = 17; + +pub const HEARD_ENTRY_LEN: usize = 4; + +pub const MAC_LEN: usize = 16; + +pub const FRESHNESS_MS: u64 = 600000; + +pub fn mac_offset(n: usize) -> usize { + return (HDR_LEN + (n * HEARD_ENTRY_LEN)); +} + +pub fn hello_len(n: usize) -> usize { + return (mac_offset(n) + MAC_LEN); +} + +pub fn parse_len_ok(byte_len: usize, n: usize) -> bool { + return (byte_len >= hello_len(n)); +} + +pub fn is_fresh(now_ms: u64, ts_ms: u64) -> bool { + if (now_ms >= ts_ms) { + return ((now_ms - ts_ms) <= FRESHNESS_MS); + } else { + return ((ts_ms - now_ms) <= FRESHNESS_MS); + } +} + diff --git a/gen/rust/docs_generator.rs b/gen/rust/docs_generator.rs index 5f959b0e..19951df6 100644 --- a/gen/rust/docs_generator.rs +++ b/gen/rust/docs_generator.rs @@ -231,14 +231,15 @@ pub fn get_margin_right(layout: u32) -> u32 { return (layout & 0xFF); } -pub fn calculate_document_stats(sections: Vec<>, section_count: u32) -> u32 { +pub fn calculate_document_stats(sections: [u32; MAX_SECTIONS as usize], section_count: u32) -> u32 { let mut total_pages: u32 = 0; let mut total_words: u32 = 0; let mut total_tables: u32 = 0; + let total_figures: u32 = 0; let mut i: u32 = 0; while (i < section_count) { - let content_len: u32 = get_section_content_length(sections[i]); - let subsections: u32 = get_section_subsection_count(sections[i]); + let content_len: u32 = get_section_content_length(sections[(i) as usize]); + let subsections: u32 = get_section_subsection_count(sections[(i) as usize]); total_words = (total_words + (content_len / 5)); total_pages = (total_pages + (content_len / 300)); if (subsections > 0) { @@ -269,11 +270,11 @@ pub fn get_metadata_version(metadata: u32) -> u32 { return (metadata & 0xFF); } -pub fn format_document(sections: Vec<>, section_count: u32, format: u32, layout: u32) -> u32 { +pub fn format_document(sections: [u32; MAX_SECTIONS as usize], section_count: u32, format: u32, layout: u32) -> u32 { let mut formatted_size: u32 = 0; let mut i: u32 = 0; while (i < section_count) { - let content_len: u32 = get_section_content_length(sections[i]); + let content_len: u32 = get_section_content_length(sections[(i) as usize]); formatted_size = (formatted_size + content_len); i = (i + 1); } @@ -290,7 +291,8 @@ pub fn format_document(sections: Vec<>, section_count: u32, format: u32, layout: return formatted_size; } -pub fn generate_complete_document(func_docs: Vec<>, func_count: u32, sections: Vec<>, section_count: u32, format: u32) -> u32 { +pub fn generate_complete_document(func_docs: [u32; 64], func_count: u32, sections: [u32; MAX_SECTIONS as usize], section_count: u32, format: u32) -> u32 { + let metadata: u32 = generate_document_metadata(1, 1, 20260703, 1); let layout: u32 = generate_page_layout(20, 20, 15, 15); let toc_size: u32 = (section_count * 10); let body_size: u32 = format_document(sections, section_count, format, layout); diff --git a/gen/rust/etx.rs b/gen/rust/etx.rs index b00cd025..2e433ccf 100644 --- a/gen/rust/etx.rs +++ b/gen/rust/etx.rs @@ -36,7 +36,7 @@ pub fn ewma_update(est: u8, sample: u8, alpha: u8) -> u8 { if ((est == 255) && (sample == 255)) { return 255; } - return (fp_mul(alpha, sample) + fp_mul((256 - alpha), est)); + return (fp_mul(alpha, sample) + fp_mul((255 - alpha), est)); } pub fn is_dead(ratio: u8) -> bool { diff --git a/gen/rust/flow_control.rs b/gen/rust/flow_control.rs index d3a9378e..1e6b8fb0 100644 --- a/gen/rust/flow_control.rs +++ b/gen/rust/flow_control.rs @@ -153,10 +153,10 @@ pub fn send_ack(flow: u32, flow_id: u32, seq: u32) -> u32 { return msg; } -pub fn find_flow_by_sender(flows: Vec, sender: u32) -> u32 { +pub fn find_flow_by_sender(flows: [u32; MAX_FLOWS as usize], sender: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_FLOWS) { - let flow_sender: u32 = get_sender_id(flows[i]); + let flow_sender: u32 = get_sender_id(flows[(i) as usize]); if (flow_sender == sender) { return i; } @@ -165,10 +165,10 @@ pub fn find_flow_by_sender(flows: Vec, sender: u32) -> u32 { return MAX_FLOWS; } -pub fn find_flow_by_receiver(flows: Vec, receiver: u32) -> u32 { +pub fn find_flow_by_receiver(flows: [u32; MAX_FLOWS as usize], receiver: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_FLOWS) { - let flow_receiver: u32 = get_receiver_id(flows[i]); + let flow_receiver: u32 = get_receiver_id(flows[(i) as usize]); if (flow_receiver == receiver) { return i; } @@ -177,10 +177,10 @@ pub fn find_flow_by_receiver(flows: Vec, receiver: u32) -> u32 { return MAX_FLOWS; } -pub fn is_any_flow_blocked(flows: Vec) -> u32 { +pub fn is_any_flow_blocked(flows: [u32; MAX_FLOWS as usize]) -> u32 { let mut i: u32 = 0; while (i < MAX_FLOWS) { - if (has_credits(flows[i]) == 0) { + if (has_credits(flows[(i) as usize]) == 0) { return 1; } i = (i + 1); @@ -188,11 +188,11 @@ pub fn is_any_flow_blocked(flows: Vec) -> u32 { return 0; } -pub fn count_active_flows(flows: Vec) -> u32 { +pub fn count_active_flows(flows: [u32; MAX_FLOWS as usize]) -> u32 { let mut count: u32 = 0; let mut i: u32 = 0; while (i < MAX_FLOWS) { - let sender: u32 = get_sender_id(flows[i]); + let sender: u32 = get_sender_id(flows[(i) as usize]); if (sender != 0) { count = (count + 1); } @@ -201,26 +201,27 @@ pub fn count_active_flows(flows: Vec) -> u32 { return count; } -pub fn calculate_total_credits(flows: Vec) -> u32 { +pub fn calculate_total_credits(flows: [u32; MAX_FLOWS as usize]) -> u32 { let mut total: u32 = 0; let mut i: u32 = 0; while (i < MAX_FLOWS) { - total = (total + get_credits(flows[i])); + total = (total + get_credits(flows[(i) as usize])); i = (i + 1); } return total; } -pub fn apply_backpressure(flows: Vec, flow_index: u32) -> u32 { - let flow: u32 = flows[flow_index]; +pub fn apply_backpressure(flows: [u32; MAX_FLOWS as usize], flow_index: u32) -> u32 { + let flow: u32 = flows[(flow_index) as usize]; + let window: u32 = get_window_size(flow); let credits: u32 = get_credits(flow); let reduction: u32 = (credits / 2); let new_credits: u32 = (credits - reduction); return update_credits(flow, new_credits); } -pub fn release_backpressure(flows: Vec, flow_index: u32) -> u32 { - let flow: u32 = flows[flow_index]; +pub fn release_backpressure(flows: [u32; MAX_FLOWS as usize], flow_index: u32) -> u32 { + let flow: u32 = flows[(flow_index) as usize]; let window: u32 = get_window_size(flow); return update_credits(flow, window); } diff --git a/gen/rust/gf16_format.rs b/gen/rust/gf16_format.rs new file mode 100644 index 00000000..ff592819 --- /dev/null +++ b/gen/rust/gf16_format.rs @@ -0,0 +1,49 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const M_BITS: u32 = 9; + +pub const E_BITS: u32 = 6; + +pub const BIAS: u32 = 31; + +pub const M_MAX: u32 = 511; + +pub const E_MAX: u32 = 63; + +pub const SIGN_SHIFT: u32 = 15; + +pub fn sign_field(bits: u32) -> u32 { + return ((bits >> SIGN_SHIFT) & 1); +} + +pub fn exponent_field(bits: u32) -> u32 { + return ((bits >> M_BITS) & E_MAX); +} + +pub fn mantissa_field(bits: u32) -> u32 { + return (bits & M_MAX); +} + +pub fn compose(sign: u32, exponent: u32, mantissa: u32) -> u32 { + return ((((sign & 1) << SIGN_SHIFT) | ((exponent & E_MAX) << M_BITS)) | (mantissa & M_MAX)); +} + +pub fn is_nan(bits: u32) -> bool { + if (exponent_field(bits) == E_MAX) { + return (mantissa_field(bits) != 0); + } + return false; +} + +pub fn is_inf(bits: u32) -> bool { + if (exponent_field(bits) == E_MAX) { + return (mantissa_field(bits) == 0); + } + return false; +} + +pub fn is_zero(bits: u32) -> bool { + return ((bits & 32767) == 0); +} + diff --git a/gen/rust/health_dashboard.rs b/gen/rust/health_dashboard.rs index c806aa4d..2725c78f 100644 --- a/gen/rust/health_dashboard.rs +++ b/gen/rust/health_dashboard.rs @@ -69,16 +69,16 @@ pub fn get_score_timestamp(score: u32) -> u32 { return (score & 0xFF); } -pub fn calculate_node_health(metrics: Vec, count: u32) -> u32 { +pub fn calculate_node_health(metrics: [u32; MAX_METRICS as usize], count: u32) -> u32 { if (count == 0) { return 100; } let mut total_score: u32 = 0; let mut metric_count: u32 = 0; let mut i: u32 = 0; - while ((i < count) && (metrics[i] != 0)) { - let metric_type: u32 = get_health_metric_type(metrics[i]); - let value: u32 = get_health_value(metrics[i]); + while ((i < count) && (metrics[(i) as usize] != 0)) { + let metric_type: u32 = get_health_metric_type(metrics[(i) as usize]); + let value: u32 = get_health_value(metrics[(i) as usize]); let mut metric_score: u32 = 0; if ((metric_type == METRIC_CPU) || (metric_type == METRIC_MEMORY)) { metric_score = (100 - value); @@ -110,26 +110,26 @@ pub fn calculate_node_health(metrics: Vec, count: u32) -> u32 { } } -pub fn calculate_network_health(node_metrics: Vec, node_count: u32) -> u32 { +pub fn calculate_network_health(node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { if (node_count == 0) { return 100; } let mut total_health: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - let node_health: u32 = node_metrics[i]; + let node_health: u32 = node_metrics[(i) as usize]; total_health = (total_health + node_health); i = (i + 1); } return (total_health / node_count); } -pub fn detect_critical_issues(metrics: Vec, count: u32) -> u32 { +pub fn detect_critical_issues(metrics: [u32; MAX_METRICS as usize], count: u32) -> u32 { let mut critical_count: u32 = 0; let mut i: u32 = 0; - while ((i < count) && (metrics[i] != 0)) { - let metric_type: u32 = get_health_metric_type(metrics[i]); - let value: u32 = get_health_value(metrics[i]); + while ((i < count) && (metrics[(i) as usize] != 0)) { + let metric_type: u32 = get_health_metric_type(metrics[(i) as usize]); + let value: u32 = get_health_value(metrics[(i) as usize]); let mut is_critical: u32 = 0; if ((metric_type == METRIC_CPU) || (metric_type == METRIC_MEMORY)) { if (value > CRITICAL_THRESHOLD) { @@ -160,12 +160,12 @@ pub fn detect_critical_issues(metrics: Vec, count: u32) -> u32 { return critical_count; } -pub fn detect_warning_issues(metrics: Vec, count: u32) -> u32 { +pub fn detect_warning_issues(metrics: [u32; MAX_METRICS as usize], count: u32) -> u32 { let mut warning_count: u32 = 0; let mut i: u32 = 0; - while ((i < count) && (metrics[i] != 0)) { - let metric_type: u32 = get_health_metric_type(metrics[i]); - let value: u32 = get_health_value(metrics[i]); + while ((i < count) && (metrics[(i) as usize] != 0)) { + let metric_type: u32 = get_health_metric_type(metrics[(i) as usize]); + let value: u32 = get_health_value(metrics[(i) as usize]); let mut is_warning: u32 = 0; if ((metric_type == METRIC_CPU) || (metric_type == METRIC_MEMORY)) { if ((value > ALERT_THRESHOLD) && (value <= CRITICAL_THRESHOLD)) { @@ -196,7 +196,11 @@ pub fn detect_warning_issues(metrics: Vec, count: u32) -> u32 { return warning_count; } -pub fn generate_health_report(node_metrics: Vec, count: u32, timestamp: u32) -> u32 { +pub fn generate_health_report( + node_metrics: [u32; MAX_METRICS as usize], + count: u32, + timestamp: u32, +) -> u32 { let node_health: u32 = calculate_node_health(node_metrics, count); let critical_count: u32 = detect_critical_issues(node_metrics, count); let warning_count: u32 = detect_warning_issues(node_metrics, count); @@ -272,11 +276,11 @@ pub fn analyze_health_trend(current_health: u32, previous_health: u32) -> u32 { } } -pub fn find_unhealthy_nodes(node_healths: Vec, threshold: u32) -> u32 { +pub fn find_unhealthy_nodes(node_healths: [u32; MAX_NODES as usize], threshold: u32) -> u32 { let mut count: u32 = 0; let mut i: u32 = 0; while (i < MAX_NODES) { - if (node_healths[i] < threshold) { + if (node_healths[(i) as usize] < threshold) { count = (count + 1); } i = (i + 1); @@ -284,12 +288,17 @@ pub fn find_unhealthy_nodes(node_healths: Vec, threshold: u32) -> u32 { return count; } -pub fn calculate_network_trend(current_scores: Vec, previous_scores: Vec, node_count: u32) -> u32 { +pub fn calculate_network_trend( + current_scores: [u32; MAX_NODES as usize], + previous_scores: [u32; MAX_NODES as usize], + node_count: u32, +) -> u32 { let mut improving: u32 = 0; let mut degrading: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - let trend: u32 = analyze_health_trend(current_scores[i], previous_scores[i]); + let trend: u32 = + analyze_health_trend(current_scores[(i) as usize], previous_scores[(i) as usize]); if ((trend == 1) || (trend == 2)) { improving = (improving + 1); } else { diff --git a/gen/rust/integration_framework.rs b/gen/rust/integration_framework.rs index 5a15c62f..b935f53f 100644 --- a/gen/rust/integration_framework.rs +++ b/gen/rust/integration_framework.rs @@ -81,13 +81,14 @@ pub const MSG_ERROR: u32 = 3; pub const MSG_EVENT: u32 = 4; -pub fn send_message(modules: Vec<>, message: u32) -> u32 { +pub fn send_message(modules: [u32; MAX_MODULES as usize], message: u32) -> u32 { let dest: u32 = get_integration_message_dest(message); + let msg_type: u32 = get_integration_message_type(message); let mut i: u32 = 0; while (i < MAX_MODULES) { - let module_id: u32 = get_registered_module_id(modules[i]); + let module_id: u32 = get_registered_module_id(modules[(i) as usize]); if (module_id == dest) { - let status: u32 = get_registered_module_status(modules[i]); + let status: u32 = get_registered_module_status(modules[(i) as usize]); if ((status == STATUS_ACTIVE) || (status == STATUS_BUSY)) { return 1; } else { @@ -99,10 +100,10 @@ pub fn send_message(modules: Vec<>, message: u32) -> u32 { return 0; } -pub fn receive_message(messages: Vec<>, message_count: u32, module_id: u32) -> u32 { +pub fn receive_message(messages: [u32; MAX_MESSAGES as usize], message_count: u32, module_id: u32) -> u32 { let mut i: u32 = 0; while (i < message_count) { - let dest: u32 = get_integration_message_dest(messages[i]); + let dest: u32 = get_integration_message_dest(messages[(i) as usize]); if (dest == module_id) { return i; } @@ -141,12 +142,12 @@ pub const EVENT_SIMULATION_STEP: u32 = 3; pub const EVENT_VISUALIZATION_UPDATE: u32 = 4; -pub fn subscribe_to_event(module_id: u32, event_type: u32, subscriptions: Vec<>) -> u32 { +pub fn subscribe_to_event(module_id: u32, event_type: u32, subscriptions: [u32; MAX_EVENTS as usize]) -> u32 { let subscription_id: u32 = ((module_id * 10) + event_type); let mut i: u32 = 0; while (i < MAX_EVENTS) { - if (subscriptions[i] == 0) { - subscriptions[i] = create_event(subscription_id, event_type, module_id, 0); + if (subscriptions[(i) as usize] == 0) { + subscriptions[(i) as usize] = create_event(subscription_id, event_type, module_id, 0); return 1; } i = (i + 1); @@ -154,14 +155,14 @@ pub fn subscribe_to_event(module_id: u32, event_type: u32, subscriptions: Vec<>) return 0; } -pub fn publish_event(event: u32, subscriptions: Vec<>, modules: Vec<>) -> u32 { +pub fn publish_event(event: u32, subscriptions: [u32; MAX_EVENTS as usize], modules: [u32; MAX_MODULES as usize]) -> u32 { let event_type: u32 = get_event_type(event); let mut notified_count: u32 = 0; let mut i: u32 = 0; while (i < MAX_EVENTS) { - let sub_event_type: u32 = get_event_type(subscriptions[i]); + let sub_event_type: u32 = get_event_type(subscriptions[(i) as usize]); if (sub_event_type == event_type) { - let source: u32 = get_event_source(subscriptions[i]); + let source: u32 = get_event_source(subscriptions[(i) as usize]); let module_id: u32 = source; let msg: u32 = create_integration_message(i, 0, module_id, MSG_EVENT); if (send_message(modules, msg) == 1) { @@ -193,12 +194,12 @@ pub fn get_sync_checksum(sync: u32) -> u32 { return (sync & 0xFF); } -pub fn synchronize_states(modules: Vec<>, module_count: u32, sync_requests: u32) -> u32 { +pub fn synchronize_states(modules: [u32; MAX_MODULES as usize], module_count: u32, sync_requests: u32) -> u32 { let mut synced_count: u32 = 0; let mut i: u32 = 0; while (i < module_count) { - let module_id: u32 = get_registered_module_id(modules[i]); - let status: u32 = get_registered_module_status(modules[i]); + let module_id: u32 = get_registered_module_id(modules[(i) as usize]); + let status: u32 = get_registered_module_status(modules[(i) as usize]); if ((status == STATUS_ACTIVE) && (sync_requests > 0)) { let state_version: u32 = 1; let state_data: u32 = (i * 10); @@ -239,12 +240,12 @@ pub const SEVERITY_ERROR: u32 = 2; pub const SEVERITY_CRITICAL: u32 = 3; -pub fn propagate_error(error: u32, modules: Vec<>, module_count: u32) -> u32 { +pub fn propagate_error(error: u32, modules: [u32; MAX_MODULES as usize], module_count: u32) -> u32 { let severity: u32 = get_error_severity(error); let mut notified_count: u32 = 0; let mut i: u32 = 0; while (i < module_count) { - let module_type: u32 = get_registered_module_type(modules[i]); + let module_type: u32 = get_registered_module_type(modules[(i) as usize]); if (severity == SEVERITY_CRITICAL) { let msg: u32 = create_integration_message(0, 0, i, MSG_ERROR); if (send_message(modules, msg) == 1) { @@ -265,11 +266,11 @@ pub fn propagate_error(error: u32, modules: Vec<>, module_count: u32) -> u32 { return notified_count; } -pub fn load_module(module_id: u32, module_type: u32, priority: u32, modules: Vec<>) -> u32 { +pub fn load_module(module_id: u32, module_type: u32, priority: u32, modules: [u32; MAX_MODULES as usize]) -> u32 { let mut i: u32 = 0; while (i < MAX_MODULES) { - if (get_registered_module_id(modules[i]) == 0) { - modules[i] = create_module_registration(module_id, module_type, priority, STATUS_IDLE); + if (get_registered_module_id(modules[(i) as usize]) == 0) { + modules[(i) as usize] = create_module_registration(module_id, module_type, priority, STATUS_IDLE); return 1; } i = (i + 1); @@ -277,12 +278,12 @@ pub fn load_module(module_id: u32, module_type: u32, priority: u32, modules: Vec return 0; } -pub fn unload_module(module_id: u32, modules: Vec<>) -> u32 { +pub fn unload_module(module_id: u32, modules: [u32; MAX_MODULES as usize]) -> u32 { let mut i: u32 = 0; while (i < MAX_MODULES) { - let registered_id: u32 = get_registered_module_id(modules[i]); + let registered_id: u32 = get_registered_module_id(modules[(i) as usize]); if (registered_id == module_id) { - modules[i] = 0; + modules[(i) as usize] = 0; return 1; } i = (i + 1); @@ -310,19 +311,19 @@ pub fn get_dependency_required(dep: u32) -> u32 { return (dep & 0xFFF); } -pub fn check_dependencies(module_id: u32, dependencies: Vec<>, loaded_modules: Vec<>, module_count: u32) -> u32 { +pub fn check_dependencies(module_id: u32, dependencies: [u32; MAX_MODULES as usize], loaded_modules: [u32; MAX_MODULES as usize], module_count: u32) -> u32 { let mut satisfied: u32 = 1; let mut i: u32 = 0; while (i < MAX_MODULES) { - let dep_module_id: u32 = get_dependency_module_id(dependencies[i]); + let dep_module_id: u32 = get_dependency_module_id(dependencies[(i) as usize]); if (dep_module_id == module_id) { - let depends_on: u32 = get_dependency_depends_on(dependencies[i]); - let required: u32 = get_dependency_required(dependencies[i]); + let depends_on: u32 = get_dependency_depends_on(dependencies[(i) as usize]); + let required: u32 = get_dependency_required(dependencies[(i) as usize]); if (required == 1) { let mut j: u32 = 0; let mut found: u32 = 0; while (j < module_count) { - let loaded_id: u32 = get_registered_module_id(loaded_modules[j]); + let loaded_id: u32 = get_registered_module_id(loaded_modules[(j) as usize]); if (loaded_id == depends_on) { found = 1; break; @@ -367,12 +368,12 @@ pub const RESOURCE_BANDWIDTH: u32 = 2; pub const RESOURCE_STORAGE: u32 = 3; -pub fn allocate_resources(requests: Vec<>, request_count: u32, available_resources: u32) -> u32 { +pub fn allocate_resources(requests: [u32; MAX_MESSAGES as usize], request_count: u32, available_resources: u32) -> u32 { let mut total_requested: u32 = 0; let mut allocated_count: u32 = 0; let mut i: u32 = 0; while (i < request_count) { - let amount: u32 = get_resource_request_amount(requests[i]); + let amount: u32 = get_resource_request_amount(requests[(i) as usize]); total_requested = (total_requested + amount); i = (i + 1); } @@ -382,8 +383,8 @@ pub fn allocate_resources(requests: Vec<>, request_count: u32, available_resourc let mut allocated: u32 = 0; let mut j: u32 = 0; while ((j < request_count) && (allocated < available_resources)) { - let amount: u32 = get_resource_request_amount(requests[j]); - let priority: u32 = get_resource_request_priority(requests[j]); + let amount: u32 = get_resource_request_amount(requests[(j) as usize]); + let priority: u32 = get_resource_request_priority(requests[(j) as usize]); if ((priority > 7) && ((allocated + amount) <= available_resources)) { allocated = (allocated + amount); allocated_count = (allocated_count + 1); @@ -398,13 +399,14 @@ pub fn create_integration_report(loaded_modules: u32, active_messages: u32, even return (((((loaded_modules & 0xFF) << 24) | ((active_messages & 0xFF) << 16)) | ((events_processed & 0xFF) << 8)) | (errors_handled & 0xFF)); } -pub fn generate_integration_stats(modules: Vec<>, module_count: u32, messages: Vec<>, message_count: u32, events: Vec<>, event_count: u32) -> u32 { +pub fn generate_integration_stats(modules: [u32; MAX_MODULES as usize], module_count: u32, messages: [u32; MAX_MESSAGES as usize], message_count: u32, events: [u32; MAX_EVENTS as usize], event_count: u32) -> u32 { let mut active_modules: u32 = 0; let mut active_messages: u32 = 0; let mut events_processed: u32 = 0; + let errors_handled: u32 = 0; let mut i: u32 = 0; while (i < module_count) { - let status: u32 = get_registered_module_status(modules[i]); + let status: u32 = get_registered_module_status(modules[(i) as usize]); if ((status == STATUS_ACTIVE) || (status == STATUS_BUSY)) { active_modules = (active_modules + 1); } @@ -423,12 +425,12 @@ pub fn generate_integration_stats(modules: Vec<>, module_count: u32, messages: V return create_integration_report(active_modules, active_messages, events_processed, 0); } -pub fn validate_integration_health(modules: Vec<>, module_count: u32) -> u32 { +pub fn validate_integration_health(modules: [u32; MAX_MODULES as usize], module_count: u32) -> u32 { let mut active_count: u32 = 0; let mut error_count: u32 = 0; let mut i: u32 = 0; while (i < module_count) { - let status: u32 = get_registered_module_status(modules[i]); + let status: u32 = get_registered_module_status(modules[(i) as usize]); if (status == STATUS_ACTIVE) { active_count = (active_count + 1); } else { diff --git a/gen/rust/link_quality_monitor.rs b/gen/rust/link_quality_monitor.rs index 0e43657a..78a1efb9 100644 --- a/gen/rust/link_quality_monitor.rs +++ b/gen/rust/link_quality_monitor.rs @@ -18,11 +18,17 @@ pub const TREND_THRESHOLD: u8 = 0x05; pub fn update_ewma(current: u8, sample: u8) -> u8 { let term1: u16 = (((ALPHA_Q8 as u16) * (sample as u16)) >> 8); let term2: u16 = (((ONE_MINUS_ALPHA_Q8 as u16) * (current as u16)) >> 8); + let new_estimate: u16 = (term1 + term2); } -pub fn calculate_trend(history: Vec<>) -> i8 { unimplemented!() } +pub fn calculate_trend(history: [u8; 8]) -> i8 { + let recent_avg: u8 = ((((((history[7] as u16) + (history[6] as u16)) + (history[5] as u16)) + (history[4] as u16)) >> 2) as u8); + let older_avg: u8 = ((((((history[3] as u16) + (history[2] as u16)) + (history[1] as u16)) + (history[0] as u16)) >> 2) as u8); +} -pub fn predict_next_etx(current: u8, trend: i8) -> u8 { unimplemented!() } +pub fn predict_next_etx(current: u8, trend: i8) -> u8 { + let prediction: i16 = ((current as i16) + (trend as i16)); +} pub fn is_degrading(current_etx: u8, trend: i8) -> bool { ((current_etx > QUALITY_POOR) && (trend > TREND_THRESHOLD)); @@ -31,6 +37,7 @@ pub fn is_degrading(current_etx: u8, trend: i8) -> bool { pub fn quality_score(etx: u8, latency_ms: u16) -> u8 { let etx_component: u16 = (((etx as u16) * 7) / 10); let latency_component: u16 = (latency_ms / 100); + let combined: u16 = (etx_component + latency_component); } pub fn classify_quality(score: u8) -> u8 { unimplemented!() } diff --git a/gen/rust/lite_crypto.rs b/gen/rust/lite_crypto.rs index acdc8e90..083af8d7 100644 --- a/gen/rust/lite_crypto.rs +++ b/gen/rust/lite_crypto.rs @@ -16,6 +16,14 @@ pub fn quarter_round(state: u32, input: u32) -> u32 { let s1 = ((state >> 64) & 0xFFFFFFFF); let s2 = ((state >> 32) & 0xFFFFFFFF); let s3 = (state & 0xFFFFFFFF); + let c0 = 0x61707865; + let c1 = 0x3320646E; + let c2 = 0x79622D2E; + let c3 = 0x6B206574; + let new_s0 = ((s0 + input) & 0xFFFFFFFF); + let new_s1 = ((s1 + 0x61707865) & 0xFFFFFFFF); + let new_s2 = ((s2 + 0x3320646E) & 0xFFFFFFFF); + let new_s3 = ((s3 + 0x79622D2E) & 0xFFFFFFFF); } pub fn generate_psk(seed: u32) -> u32 { diff --git a/gen/rust/load_predictor.rs b/gen/rust/load_predictor.rs index bc08fd29..5dbc1663 100644 --- a/gen/rust/load_predictor.rs +++ b/gen/rust/load_predictor.rs @@ -51,11 +51,11 @@ pub fn get_time_horizon(prediction: u32) -> u32 { return (prediction & 0x3FFF); } -pub fn calculate_moving_average(history: Vec<>, count: u32) -> u32 { +pub fn calculate_moving_average(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { let mut sum: u32 = 0; let mut i: u32 = 0; while (i < count) { - let metrics = history[i]; + let metrics = history[(i) as usize]; sum = (sum + get_bandwidth_usage(metrics)); i = (i + 1); } @@ -66,12 +66,12 @@ pub fn calculate_moving_average(history: Vec<>, count: u32) -> u32 { } } -pub fn detect_trend(history: Vec<>, count: u32) -> u32 { +pub fn detect_trend(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { if (count < 3) { return 0; } - let recent: u32 = get_bandwidth_usage(history[(count - 1)]); - let previous: u32 = get_bandwidth_usage(history[(count - 3)]); + let recent: u32 = get_bandwidth_usage(history[((count - 1)) as usize]); + let previous: u32 = get_bandwidth_usage(history[((count - 3)) as usize]); let mut diff: u32 = 0; if (recent > previous) { diff = (recent - previous); @@ -89,11 +89,11 @@ pub fn detect_trend(history: Vec<>, count: u32) -> u32 { } } -pub fn predict_load(history: Vec<>, count: u32) -> u32 { +pub fn predict_load(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { if (count == 0) { return 0; } - let current: u32 = get_bandwidth_usage(history[(count - 1)]); + let current: u32 = get_bandwidth_usage(history[((count - 1)) as usize]); let trend: u32 = detect_trend(history, count); let avg: u32 = calculate_moving_average(history, count); let mut predicted: u32 = current; @@ -116,7 +116,7 @@ pub fn predict_load(history: Vec<>, count: u32) -> u32 { return predicted; } -pub fn calculate_confidence(history: Vec<>, count: u32) -> u32 { +pub fn calculate_confidence(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { if (count < 3) { return 20; } @@ -124,7 +124,7 @@ pub fn calculate_confidence(history: Vec<>, count: u32) -> u32 { let avg: u32 = calculate_moving_average(history, count); let mut i: u32 = 0; while (i < count) { - let value: u32 = get_bandwidth_usage(history[i]); + let value: u32 = get_bandwidth_usage(history[(i) as usize]); let mut diff: u32 = 0; if (value > avg) { diff = (value - avg); @@ -153,10 +153,11 @@ pub fn calculate_confidence(history: Vec<>, count: u32) -> u32 { } } -pub fn create_load_prediction(history: Vec<>, count: u32) -> u32 { +pub fn create_load_prediction(history: [u32; HISTORY_SIZE as usize], count: u32) -> u32 { let predicted: u32 = predict_load(history, count); let confidence: u32 = calculate_confidence(history, count); let trend: u32 = detect_trend(history, count); + let horizon: u32 = PREDICTION_WINDOW; return create_prediction(predicted, confidence, trend, PREDICTION_WINDOW); } @@ -180,11 +181,11 @@ pub fn is_warning_predicted(prediction: u32) -> u32 { } } -pub fn calculate_network_load(node_metrics: Vec<>, node_count: u32) -> u32 { +pub fn calculate_network_load(node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let mut total_load: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - let load: u32 = get_bandwidth_usage(node_metrics[i]); + let load: u32 = get_bandwidth_usage(node_metrics[(i) as usize]); total_load = (total_load + load); i = (i + 1); } @@ -195,12 +196,12 @@ pub fn calculate_network_load(node_metrics: Vec<>, node_count: u32) -> u32 { } } -pub fn find_most_loaded_node(node_metrics: Vec<>, node_count: u32) -> u32 { +pub fn find_most_loaded_node(node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let mut max_load: u32 = 0; let mut max_node: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - let load: u32 = get_bandwidth_usage(node_metrics[i]); + let load: u32 = get_bandwidth_usage(node_metrics[(i) as usize]); if (load > max_load) { max_load = load; max_node = i; @@ -210,12 +211,12 @@ pub fn find_most_loaded_node(node_metrics: Vec<>, node_count: u32) -> u32 { return max_node; } -pub fn find_least_loaded_node(node_metrics: Vec<>, node_count: u32) -> u32 { +pub fn find_least_loaded_node(node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let mut min_load: u32 = 255; let mut min_node: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - let load: u32 = get_bandwidth_usage(node_metrics[i]); + let load: u32 = get_bandwidth_usage(node_metrics[(i) as usize]); if (load < min_load) { min_load = load; min_node = i; @@ -225,12 +226,12 @@ pub fn find_least_loaded_node(node_metrics: Vec<>, node_count: u32) -> u32 { return min_node; } -pub fn calculate_load_imbalance(node_metrics: Vec<>, node_count: u32) -> u32 { +pub fn calculate_load_imbalance(node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let mut max_load: u32 = 0; let mut min_load: u32 = 255; let mut i: u32 = 0; while (i < node_count) { - let load: u32 = get_bandwidth_usage(node_metrics[i]); + let load: u32 = get_bandwidth_usage(node_metrics[(i) as usize]); if (load > max_load) { max_load = load; } @@ -246,8 +247,8 @@ pub fn calculate_load_imbalance(node_metrics: Vec<>, node_count: u32) -> u32 { return imbalance; } -pub fn recommend_rerouting(prediction: u32, current_node: u32, node_metrics: Vec<>, node_count: u32) -> u32 { - if !(is_congestion_predicted(prediction)) { +pub fn recommend_rerouting(prediction: u32, current_node: u32, node_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { + if ((is_congestion_predicted(prediction)) == 0) { return current_node; } let least_loaded: u32 = find_least_loaded_node(node_metrics, node_count); diff --git a/gen/rust/local_processing.rs b/gen/rust/local_processing.rs index 97b2058f..ccd766c2 100644 --- a/gen/rust/local_processing.rs +++ b/gen/rust/local_processing.rs @@ -69,21 +69,21 @@ pub fn process_task(task: u32) -> u32 { return create_result(task_id, STATUS_COMPLETED, data_size, result_value); } -pub fn aggregate_results(results: Vec<>, count: u32) -> u32 { +pub fn aggregate_results(results: [u32; MAX_RESULTS as usize], count: u32) -> u32 { let mut sum: u32 = 0; let mut i: u32 = 0; while (i < count) { - let value: u32 = get_result_value(results[i]); + let value: u32 = get_result_value(results[(i) as usize]); sum = (sum + value); i = (i + 1); } return sum; } -pub fn find_task_by_priority(tasks: Vec<>, priority: u32) -> u32 { +pub fn find_task_by_priority(tasks: [u32; MAX_TASKS as usize], priority: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_TASKS) { - let task_priority: u32 = get_priority(tasks[i]); + let task_priority: u32 = get_priority(tasks[(i) as usize]); if (task_priority == priority) { return i; } @@ -92,12 +92,12 @@ pub fn find_task_by_priority(tasks: Vec<>, priority: u32) -> u32 { return MAX_TASKS; } -pub fn find_highest_priority_task(tasks: Vec<>) -> u32 { +pub fn find_highest_priority_task(tasks: [u32; MAX_TASKS as usize]) -> u32 { let mut highest_priority: u32 = TASK_PRIORITY_LOW; let mut task_index: u32 = MAX_TASKS; let mut i: u32 = 0; while (i < MAX_TASKS) { - let task_priority: u32 = get_priority(tasks[i]); + let task_priority: u32 = get_priority(tasks[(i) as usize]); if (task_priority < highest_priority) { highest_priority = task_priority; task_index = i; @@ -107,11 +107,11 @@ pub fn find_highest_priority_task(tasks: Vec<>) -> u32 { return task_index; } -pub fn count_pending_tasks(tasks: Vec<>) -> u32 { +pub fn count_pending_tasks(tasks: [u32; MAX_TASKS as usize]) -> u32 { let mut count: u32 = 0; let mut i: u32 = 0; while (i < MAX_TASKS) { - let task_id: u32 = get_task_id(tasks[i]); + let task_id: u32 = get_task_id(tasks[(i) as usize]); if (task_id != 0) { count = (count + 1); } @@ -120,18 +120,18 @@ pub fn count_pending_tasks(tasks: Vec<>) -> u32 { return count; } -pub fn calculate_processing_load(tasks: Vec<>) -> u32 { +pub fn calculate_processing_load(tasks: [u32; MAX_TASKS as usize]) -> u32 { let mut total_load: u32 = 0; let mut i: u32 = 0; while (i < MAX_TASKS) { - let proc_time: u32 = get_processing_time(tasks[i]); + let proc_time: u32 = get_processing_time(tasks[(i) as usize]); total_load = (total_load + proc_time); i = (i + 1); } return total_load; } -pub fn can_accept_task(tasks: Vec<>, new_task: u32) -> u32 { +pub fn can_accept_task(tasks: [u32; MAX_TASKS as usize], new_task: u32) -> u32 { let current_load: u32 = calculate_processing_load(tasks); let new_load: u32 = get_processing_time(new_task); let total_load: u32 = (current_load + new_load); @@ -142,11 +142,11 @@ pub fn can_accept_task(tasks: Vec<>, new_task: u32) -> u32 { } } -pub fn find_completed_result(results: Vec<>, task_id: u32, count: u32) -> u32 { +pub fn find_completed_result(results: [u32; MAX_RESULTS as usize], task_id: u32, count: u32) -> u32 { let mut i: u32 = 0; while (i < count) { - let result_task_id: u32 = get_result_task_id(results[i]); - let status: u32 = get_status(results[i]); + let result_task_id: u32 = get_result_task_id(results[(i) as usize]); + let status: u32 = get_status(results[(i) as usize]); if ((result_task_id == task_id) && (status == STATUS_COMPLETED)) { return i; } @@ -155,17 +155,17 @@ pub fn find_completed_result(results: Vec<>, task_id: u32, count: u32) -> u32 { return MAX_RESULTS; } -pub fn calculate_efficiency(tasks: Vec<>, results: Vec<>, result_count: u32) -> u32 { +pub fn calculate_efficiency(tasks: [u32; MAX_TASKS as usize], results: [u32; MAX_RESULTS as usize], result_count: u32) -> u32 { let mut total_input: u32 = 0; let mut total_output: u32 = 0; let mut i: u32 = 0; while (i < MAX_TASKS) { - total_input = (total_input + get_data_size(tasks[i])); + total_input = (total_input + get_data_size(tasks[(i) as usize])); i = (i + 1); } i = 0; while (i < result_count) { - total_output = (total_output + get_result_size(results[i])); + total_output = (total_output + get_result_size(results[(i) as usize])); i = (i + 1); } if (total_input > 0) { @@ -175,24 +175,24 @@ pub fn calculate_efficiency(tasks: Vec<>, results: Vec<>, result_count: u32) -> } } -pub fn aggregate_data(data_values: Vec<>, count: u32) -> u32 { +pub fn aggregate_data(data_values: [u32; MAX_RESULTS as usize], count: u32) -> u32 { if (count == 0) { return 0; } let mut sum: u32 = 0; let mut i: u32 = 0; while (i < count) { - sum = (sum + data_values[i]); + sum = (sum + data_values[(i) as usize]); i = (i + 1); } return (sum / count); } -pub fn filter_data(data_values: Vec<>, count: u32, threshold: u32) -> u32 { +pub fn filter_data(data_values: [u32; MAX_RESULTS as usize], count: u32, threshold: u32) -> u32 { let mut filtered_count: u32 = 0; let mut i: u32 = 0; while (i < count) { - if (data_values[i] > threshold) { + if (data_values[(i) as usize] > threshold) { filtered_count = (filtered_count + 1); } i = (i + 1); @@ -200,7 +200,7 @@ pub fn filter_data(data_values: Vec<>, count: u32, threshold: u32) -> u32 { return filtered_count; } -pub fn make_local_decision(tasks: Vec<>, results: Vec<>, result_count: u32) -> u32 { +pub fn make_local_decision(tasks: [u32; MAX_TASKS as usize], results: [u32; MAX_RESULTS as usize], result_count: u32) -> u32 { let efficiency: u32 = calculate_efficiency(tasks, results, result_count); let pending: u32 = count_pending_tasks(tasks); if ((efficiency > 50) && (pending < (MAX_TASKS / 2))) { diff --git a/gen/rust/m3_multihop.rs b/gen/rust/m3_multihop.rs index 6ae20c20..27994df8 100644 --- a/gen/rust/m3_multihop.rs +++ b/gen/rust/m3_multihop.rs @@ -24,8 +24,10 @@ pub fn iperf3_sequence(packet_byte: u8) -> u32 { } pub fn expected_loss_rate_p10(attenuation_db: u8) -> u8 { + let base_loss: u8 = 0x10; let att_factor: u8 = ((attenuation_db / 3) as u8); let add_loss: u8 = (att_factor * 0x10); + let total: u16 = ((0x10 as u16) + (add_loss as u16)); } pub fn throughput_factor_p8(attenuation_db: u8) -> u8 { @@ -36,7 +38,9 @@ pub fn throughput_factor_p8(attenuation_db: u8) -> u8 { pub fn signal_quality(attenuation_db: u8) -> u8 { unimplemented!() } -pub fn total_attenuation(hop1_db: u8, hop2_db: u8) -> u8 { unimplemented!() } +pub fn total_attenuation(hop1_db: u8, hop2_db: u8) -> u8 { + let sum: u16 = ((hop1_db as u16) + (hop2_db as u16)); +} pub fn delivery_rate_p8(hop1_db: u8, hop2_db: u8) -> u8 { let factor1: u8 = throughput_factor_p8(hop1_db); diff --git a/gen/rust/modem_frame.rs b/gen/rust/modem_frame.rs new file mode 100644 index 00000000..7a201ee0 --- /dev/null +++ b/gen/rust/modem_frame.rs @@ -0,0 +1,41 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const PREAMBLE_LEN: usize = 13; + +pub const BITS_PER_BYTE: usize = 8; + +pub const MAX_PAYLOAD: usize = 255; + +pub const PEAK: usize = 13; + +pub const SYNC_THRESHOLD: usize = 8; + +pub fn frame_symbols(payload_len: usize) -> usize { + return ((PREAMBLE_LEN + BITS_PER_BYTE) + (payload_len * BITS_PER_BYTE)); +} + +pub fn min_parse_len() -> usize { + return (PREAMBLE_LEN + BITS_PER_BYTE); +} + +pub fn can_parse(nsamples: usize) -> bool { + return (nsamples >= min_parse_len()); +} + +pub fn payload_fits(n: usize) -> bool { + return (n <= MAX_PAYLOAD); +} + +pub fn decode_fits(sym_start: usize, out_len: usize, total: usize) -> bool { + return ((sym_start + (out_len * BITS_PER_BYTE)) <= total); +} + +pub fn is_synced(corr_peak: usize) -> bool { + return (corr_peak >= SYNC_THRESHOLD); +} + +pub fn sync_margin_pct() -> usize { + return ((SYNC_THRESHOLD * 100) / PEAK); +} + diff --git a/gen/rust/multipath_router.rs b/gen/rust/multipath_router.rs index ed465cd3..ce3c2613 100644 --- a/gen/rust/multipath_router.rs +++ b/gen/rust/multipath_router.rs @@ -7,7 +7,8 @@ pub const ETX_THRESHOLD_GOOD: u8 = 0x30; pub const ETX_THRESHOLD_POOR: u8 = 0x60; -pub fn select_path_index(etx_values: Vec<>) -> u8 { +pub fn select_path_index(etx_values: [u8; 3]) -> u8 { + let min_etx: u8 = etx_values[0]; let mut; } @@ -15,6 +16,7 @@ pub fn path_quality_score(etx: u8, latency: u16, loss_p8: u8) -> u8 { let etx_component: u16 = ((etx as u16) * 7); let latency_component: u16 = ((latency / 10) << 1); let loss_component: u16 = ((loss_p8 as u16) * 1); + let total: u16 = (((etx_component + latency_component) + loss_component) / 10); } pub fn needs_failover(current_etx: u8, current_idx: u8, max_paths: u8) -> bool { @@ -23,7 +25,9 @@ pub fn needs_failover(current_etx: u8, current_idx: u8, max_paths: u8) -> bool { (etx_degraded && has_backup); } -pub fn next_path_index(current_idx: u8, max_paths: u8) -> u8 { unimplemented!() } +pub fn next_path_index(current_idx: u8, max_paths: u8) -> u8 { + let next: u8 = (current_idx + 1); +} pub fn path_reliability(etx: u8, loss_rate: u8) -> u8 { let product: u16 = ((etx as u16) * (loss_rate as u16)); diff --git a/gen/rust/multipath_routing.rs b/gen/rust/multipath_routing.rs index c2b14b86..476f4536 100644 --- a/gen/rust/multipath_routing.rs +++ b/gen/rust/multipath_routing.rs @@ -88,11 +88,11 @@ pub fn count_valid_paths(path_array: u64) -> u32 { } pub fn is_multipath_viable(path_array: u64) -> u32 { - return (count_valid_paths(path_array) >= MIN_PATHS); + return (count_valid_paths(path_array) >= MIN_PATHS) as u32; } pub fn select_primary_path(path_array: u64, quality_array: u64) -> u32 { - if !(is_multipath_viable(path_array)) { + if ((is_multipath_viable(path_array)) == 0) { return 0xFF; } if (get_path_valid(get_multipath(path_array, 0)) == PATH_VALID) { @@ -111,6 +111,7 @@ pub fn select_primary_path(path_array: u64, quality_array: u64) -> u32 { } pub fn calculate_path_diversity(path_array: u64) -> u32 { + let diversity_score = 0; let mut hop1_set = 0; if (get_path_valid(get_multipath(path_array, 0)) == PATH_VALID) { hop1_set = (hop1_set | (1 << get_multipath_hop1(get_multipath(path_array, 0)))); @@ -121,7 +122,7 @@ pub fn calculate_path_diversity(path_array: u64) -> u32 { if (get_path_valid(get_multipath(path_array, 2)) == PATH_VALID) { hop1_set = (hop1_set | (1 << get_multipath_hop1(get_multipath(path_array, 2)))); } - if ((get_path_valid(get_multipath(path_array, 3)) == path_valid) == PATH_VALID) { + if (get_path_valid(get_multipath(path_array, 3)) == PATH_VALID) { hop1_set = (hop1_set | (1 << get_multipath_hop1(get_multipath(path_array, 3)))); } let mut count = 0; diff --git a/gen/rust/network_analytics.rs b/gen/rust/network_analytics.rs index 9bdff086..c579de9a 100644 --- a/gen/rust/network_analytics.rs +++ b/gen/rust/network_analytics.rs @@ -115,6 +115,7 @@ pub fn update_traffic(stats: u32, sent_add: u32, recv_add: u32, packets_add: u32 pub fn needs_attention(data: u64) -> bool { let pattern = get_analysis_pattern(data); let traffic = get_analysis_traffic(data); + let stats = traffic; return ((pattern != PATTERN_NORMAL) || is_high_error_rate(traffic)); } diff --git a/gen/rust/network_orchestrator.rs b/gen/rust/network_orchestrator.rs index a21fd35f..82ad975c 100644 --- a/gen/rust/network_orchestrator.rs +++ b/gen/rust/network_orchestrator.rs @@ -116,14 +116,14 @@ pub fn is_coordination_timeout(state: u32, current_time: u32) -> u32 { return 0; } -pub fn apply_policy(policies: Vec<>, policy_id: u32, node_id: u32) -> u32 { +pub fn apply_policy(policies: [u32; MAX_POLICIES as usize], policy_id: u32, node_id: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_POLICIES) { - let current_policy_id: u32 = get_policy_id(policies[i]); - let scope: u32 = get_policy_scope(policies[i]); + let current_policy_id: u32 = get_policy_id(policies[(i) as usize]); + let scope: u32 = get_policy_scope(policies[(i) as usize]); if (current_policy_id == policy_id) { if ((scope == SCOPE_NODE) || (scope == SCOPE_GLOBAL)) { - return get_policy_parameter(policies[i]); + return get_policy_parameter(policies[(i) as usize]); } } i = (i + 1); @@ -131,13 +131,13 @@ pub fn apply_policy(policies: Vec<>, policy_id: u32, node_id: u32) -> u32 { return 0; } -pub fn find_highest_priority_policy(policies: Vec<>, scope: u32) -> u32 { +pub fn find_highest_priority_policy(policies: [u32; MAX_POLICIES as usize], scope: u32) -> u32 { let mut highest_priority: u32 = 0; let mut policy_index: u32 = MAX_POLICIES; let mut i: u32 = 0; while (i < MAX_POLICIES) { - let policy_scope: u32 = get_policy_scope(policies[i]); - let priority: u32 = get_policy_priority(policies[i]); + let policy_scope: u32 = get_policy_scope(policies[(i) as usize]); + let priority: u32 = get_policy_priority(policies[(i) as usize]); if ((policy_scope == scope) || (policy_scope == SCOPE_GLOBAL)) { if (priority > highest_priority) { highest_priority = priority; @@ -177,7 +177,7 @@ pub const OPT_LATENCY_REDUCTION: u32 = 2; pub const OPT_BANDWIDTH_MAXIMIZATION: u32 = 3; -pub fn process_optimization(request: u32, policies: Vec<>) -> u32 { +pub fn process_optimization(request: u32, policies: [u32; MAX_POLICIES as usize]) -> u32 { let opt_type: u32 = get_optimization_type(request); let target: u32 = get_optimization_target(request); if (opt_type == OPT_LOAD_BALANCE) { @@ -229,6 +229,8 @@ pub const ACTION_QOS_SET: u32 = 3; pub fn execute_action(action: u32, current_time: u32) -> u32 { let action_type: u32 = get_action_type(action); + let target: u32 = get_action_target(action); + let parameter: u32 = get_action_parameter(action); if (action_type == ACTION_ROUTE_UPDATE) { return 1; } else { @@ -248,12 +250,12 @@ pub fn execute_action(action: u32, current_time: u32) -> u32 { } } -pub fn coordinate_nodes(node_states: Vec<>, node_count: u32, coordinator_id: u32, current_time: u32) -> u32 { +pub fn coordinate_nodes(node_states: [u32; MAX_NODES as usize], node_count: u32, coordinator_id: u32, current_time: u32) -> u32 { let coord_state: u32 = initiate_coordination(0, coordinator_id, current_time); let mut participating_nodes: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - if (node_states[i] != 0) { + if (node_states[(i) as usize] != 0) { participating_nodes = (participating_nodes + 1); } i = (i + 1); @@ -266,11 +268,11 @@ pub fn coordinate_nodes(node_states: Vec<>, node_count: u32, coordinator_id: u32 } } -pub fn calculate_optimization_score(metrics: Vec<>, metric_count: u32) -> u32 { +pub fn calculate_optimization_score(metrics: [u32; MAX_NODES as usize], metric_count: u32) -> u32 { let mut total_score: u32 = 0; let mut i: u32 = 0; while (i < metric_count) { - total_score = (total_score + metrics[i]); + total_score = (total_score + metrics[(i) as usize]); i = (i + 1); } if (metric_count > 0) { @@ -280,7 +282,7 @@ pub fn calculate_optimization_score(metrics: Vec<>, metric_count: u32) -> u32 { } } -pub fn detect_optimization_opportunity(load_metrics: Vec<>, energy_metrics: Vec<>, node_count: u32) -> u32 { +pub fn detect_optimization_opportunity(load_metrics: [u32; MAX_NODES as usize], energy_metrics: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let load_score: u32 = calculate_optimization_score(load_metrics, node_count); let energy_score: u32 = calculate_optimization_score(energy_metrics, node_count); if ((load_score > 70) || (energy_score < 30)) { @@ -294,11 +296,11 @@ pub fn generate_optimization_plan(opportunity_type: u32, affected_nodes: u32) -> return create_optimization_request(0, opportunity_type, affected_nodes, 50); } -pub fn monitor_network_health(node_states: Vec<>, node_count: u32) -> u32 { +pub fn monitor_network_health(node_states: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let mut healthy_nodes: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - if (node_states[i] != 0) { + if (node_states[(i) as usize] != 0) { healthy_nodes = (healthy_nodes + 1); } i = (i + 1); diff --git a/gen/rust/network_simulator.rs b/gen/rust/network_simulator.rs index 2fb7d190..c8903457 100644 --- a/gen/rust/network_simulator.rs +++ b/gen/rust/network_simulator.rs @@ -185,7 +185,7 @@ pub fn advance_simulation(state: u32, time_delta: u32) -> u32 { return create_sim_state(new_time, event_count, node_count); } -pub fn process_event(event: u32, node_states: Vec<>, link_states: Vec<>) -> u32 { +pub fn process_event(event: u32, node_states: [u32; MAX_NODES as usize], link_states: [u32; MAX_NODES as usize]) -> u32 { let event_type: u32 = get_event_type(event); let node_id: u32 = get_event_node_id(event); if (event_type == EVENT_PACKET_SEND) { @@ -195,8 +195,8 @@ pub fn process_event(event: u32, node_states: Vec<>, link_states: Vec<>) -> u32 return 1; } else { if (event_type == EVENT_NODE_FAILURE) { - let current_state: u32 = node_states[node_id]; - node_states[node_id] = update_node_status(current_state, NODE_FAILED); + let current_state: u32 = node_states[(node_id) as usize]; + node_states[(node_id) as usize] = update_node_status(current_state, NODE_FAILED); return 1; } else { if (event_type == EVENT_LINK_FAILURE) { @@ -261,10 +261,10 @@ pub fn create_topology(node_count: u32, density: u32) -> u32 { return link_count; } -pub fn inject_fault(fault_type: u32, target_id: u32, node_states: Vec<>) -> u32 { +pub fn inject_fault(fault_type: u32, target_id: u32, node_states: [u32; MAX_NODES as usize]) -> u32 { if (fault_type == EVENT_NODE_FAILURE) { - let current_state: u32 = node_states[target_id]; - node_states[target_id] = update_node_status(current_state, NODE_FAILED); + let current_state: u32 = node_states[(target_id) as usize]; + node_states[(target_id) as usize] = update_node_status(current_state, NODE_FAILED); return 1; } else { if (fault_type == EVENT_LINK_FAILURE) { @@ -275,14 +275,14 @@ pub fn inject_fault(fault_type: u32, target_id: u32, node_states: Vec<>) -> u32 } } -pub fn run_simulation_step(state: u32, events: Vec<>, event_count: u32, node_states: Vec<>, link_states: Vec<>) -> u32 { +pub fn run_simulation_step(state: u32, events: [u32; MAX_EVENTS as usize], event_count: u32, node_states: [u32; MAX_NODES as usize], link_states: [u32; MAX_NODES as usize]) -> u32 { let current_time: u32 = get_sim_time(state); let mut processed_count: u32 = 0; let mut i: u32 = 0; while (i < event_count) { - let event_time: u32 = get_event_timestamp(events[i]); + let event_time: u32 = get_event_timestamp(events[(i) as usize]); if (event_time <= current_time) { - process_event(events[i], node_states, link_states); + process_event(events[(i) as usize], node_states, link_states); processed_count = (processed_count + 1); } i = (i + 1); diff --git a/gen/rust/performance_profiler.rs b/gen/rust/performance_profiler.rs index 950cd537..b6a587ab 100644 --- a/gen/rust/performance_profiler.rs +++ b/gen/rust/performance_profiler.rs @@ -65,13 +65,13 @@ pub fn get_hotspot_impact(hotspot: u32) -> u32 { return (hotspot & 0xFF); } -pub fn calculate_average_cpu(samples: Vec<>, sample_count: u32, func_id: u32) -> u32 { +pub fn calculate_average_cpu(samples: [u32; MAX_SAMPLES as usize], sample_count: u32, func_id: u32) -> u32 { let mut total_cpu: u32 = 0; let mut matching_samples: u32 = 0; let mut i: u32 = 0; while (i < sample_count) { - if (get_sample_function_id(samples[i]) == func_id) { - total_cpu = (total_cpu + get_sample_cpu(samples[i])); + if (get_sample_function_id(samples[(i) as usize]) == func_id) { + total_cpu = (total_cpu + get_sample_cpu(samples[(i) as usize])); matching_samples = (matching_samples + 1); } i = (i + 1); @@ -83,13 +83,13 @@ pub fn calculate_average_cpu(samples: Vec<>, sample_count: u32, func_id: u32) -> } } -pub fn calculate_average_memory(samples: Vec<>, sample_count: u32, func_id: u32) -> u32 { +pub fn calculate_average_memory(samples: [u32; MAX_SAMPLES as usize], sample_count: u32, func_id: u32) -> u32 { let mut total_memory: u32 = 0; let mut matching_samples: u32 = 0; let mut i: u32 = 0; while (i < sample_count) { - if (get_sample_function_id(samples[i]) == func_id) { - total_memory = (total_memory + get_sample_memory(samples[i])); + if (get_sample_function_id(samples[(i) as usize]) == func_id) { + total_memory = (total_memory + get_sample_memory(samples[(i) as usize])); matching_samples = (matching_samples + 1); } i = (i + 1); @@ -101,18 +101,18 @@ pub fn calculate_average_memory(samples: Vec<>, sample_count: u32, func_id: u32) } } -pub fn identify_hotspots(profiles: Vec<>, profile_count: u32) -> u32 { +pub fn identify_hotspots(profiles: [u32; MAX_FUNCTIONS as usize], profile_count: u32) -> u32 { let mut max_calls: u32 = 0; let mut max_cpu: u32 = 0; let mut hotspot_func: u32 = 0; let mut i: u32 = 0; while (i < profile_count) { - let calls: u32 = get_profile_call_count(profiles[i]); - let cpu: u32 = get_profile_total_cpu(profiles[i]); + let calls: u32 = get_profile_call_count(profiles[(i) as usize]); + let cpu: u32 = get_profile_total_cpu(profiles[(i) as usize]); if ((calls > max_calls) || ((calls == max_calls) && (cpu > max_cpu))) { max_calls = calls; max_cpu = cpu; - hotspot_func = get_profile_function_id(profiles[i]); + hotspot_func = get_profile_function_id(profiles[(i) as usize]); } i = (i + 1); } @@ -160,11 +160,11 @@ pub fn get_allocation_pool(alloc: u32) -> u32 { return (alloc & 0xFF); } -pub fn track_allocation(allocations: Vec<>, alloc_id: u32, size: u32, pool: u32) -> u32 { +pub fn track_allocation(allocations: [u32; MAX_SAMPLES as usize], alloc_id: u32, size: u32, pool: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_SAMPLES) { - if (get_allocation_id(allocations[i]) == 0) { - allocations[i] = create_allocation(alloc_id, size, 255, pool); + if (get_allocation_id(allocations[(i) as usize]) == 0) { + allocations[(i) as usize] = create_allocation(alloc_id, size, 255, pool); return 1; } i = (i + 1); @@ -172,18 +172,18 @@ pub fn track_allocation(allocations: Vec<>, alloc_id: u32, size: u32, pool: u32) return 0; } -pub fn calculate_total_memory(allocations: Vec<>, sample_count: u32) -> u32 { +pub fn calculate_total_memory(allocations: [u32; MAX_SAMPLES as usize], sample_count: u32) -> u32 { let mut total_memory: u32 = 0; let mut i: u32 = 0; while (i < sample_count) { - let size: u32 = get_allocation_size(allocations[i]); + let size: u32 = get_allocation_size(allocations[(i) as usize]); total_memory = (total_memory + size); i = (i + 1); } return total_memory; } -pub fn detect_memory_leak(allocations: Vec<>, current_count: u32, previous_count: u32) -> u32 { +pub fn detect_memory_leak(allocations: [u32; MAX_SAMPLES as usize], current_count: u32, previous_count: u32) -> u32 { if (current_count > previous_count) { let growth: u32 = (current_count - previous_count); if (growth > 5) { @@ -213,13 +213,13 @@ pub fn get_stack_cpu_contribution(entry: u32) -> u32 { return (entry & 0xFF); } -pub fn analyze_call_tree(call_stack: Vec<>, stack_size: u32) -> u32 { +pub fn analyze_call_tree(call_stack: [u32; MAX_SAMPLES as usize], stack_size: u32) -> u32 { let mut max_depth: u32 = 0; let mut total_cpu: u32 = 0; let mut i: u32 = 0; while (i < stack_size) { - let depth: u32 = get_stack_depth(call_stack[i]); - let cpu: u32 = get_stack_cpu_contribution(call_stack[i]); + let depth: u32 = get_stack_depth(call_stack[(i) as usize]); + let cpu: u32 = get_stack_cpu_contribution(call_stack[(i) as usize]); if (depth > max_depth) { max_depth = depth; } @@ -258,6 +258,7 @@ pub fn generate_recommendations(report: u32, hotspot: u32) -> u32 { let hotspot_score: u32 = get_hotspot_score(hotspot); let overhead: u32 = get_report_overhead(report); let mut rec_optimize_cpu: u32 = 0; + let rec_optimize_memory: u32 = 0; let mut rec_reduce_overhead: u32 = 0; let mut rec_parallelize: u32 = 0; if (total_cpu > 80) { diff --git a/gen/rust/quarantine_manager.rs b/gen/rust/quarantine_manager.rs index 77eff9c1..0f1f45d7 100644 --- a/gen/rust/quarantine_manager.rs +++ b/gen/rust/quarantine_manager.rs @@ -178,10 +178,10 @@ pub fn calculate_quarantine_severity(state: u32) -> u32 { } } -pub fn find_quarantined_node(states: Vec, node_id: u32) -> u32 { +pub fn find_quarantined_node(states: [u32; MAX_NODES as usize], node_id: u32) -> u32 { let mut i: u32 = 0; while (i < MAX_NODES) { - let state_node_id: u32 = get_quarantine_node_id(states[i]); + let state_node_id: u32 = get_quarantine_node_id(states[(i) as usize]); if (state_node_id == node_id) { return i; } @@ -190,11 +190,11 @@ pub fn find_quarantined_node(states: Vec, node_id: u32) -> u32 { return MAX_NODES; } -pub fn count_quarantined_nodes(states: Vec) -> u32 { +pub fn count_quarantined_nodes(states: [u32; MAX_NODES as usize]) -> u32 { let mut count: u32 = 0; let mut i: u32 = 0; while (i < MAX_NODES) { - if (is_quarantined(states[i]) == 1) { + if (is_quarantined(states[(i) as usize]) == 1) { count = (count + 1); } i = (i + 1); @@ -244,8 +244,9 @@ pub fn is_communication_allowed(state: u32, trust_score: u32) -> u32 { return 1; } -pub fn calculate_health_impact(states: Vec) -> u32 { +pub fn calculate_health_impact(states: [u32; MAX_NODES as usize]) -> u32 { let quarantined_count: u32 = count_quarantined_nodes(states); + let total_nodes: u32 = MAX_NODES; if (MAX_NODES > 0) { return ((quarantined_count * 100) / MAX_NODES); } else { diff --git a/gen/rust/routing_etx.rs b/gen/rust/routing_etx.rs new file mode 100644 index 00000000..6d677ccb --- /dev/null +++ b/gen/rust/routing_etx.rs @@ -0,0 +1,61 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const MILLI: u32 = 1000; + +pub const DEAD_EPS_MILLI: u32 = 150; + +pub const OPTIMISTIC_MILLI: u32 = 900; + +pub const ETX_DEAD: u32 = 0; + +pub const PENALTY_MAX_MILLI: u32 = 32000; + +pub fn etx_milli(df_milli: u32, dr_milli: u32, penalty_milli: u32) -> u32 { + if (df_milli < DEAD_EPS_MILLI) { + return ETX_DEAD; + } + if (dr_milli < DEAD_EPS_MILLI) { + return ETX_DEAD; + } + let base: u32 = (1000000000 / (df_milli * dr_milli)); + if (penalty_milli > PENALTY_MAX_MILLI) { + return ((base * PENALTY_MAX_MILLI) / MILLI); + } + return ((base * penalty_milli) / MILLI); +} + +pub fn better_route(candidate_etx: u32, incumbent_etx: u32) -> bool { + if (candidate_etx == ETX_DEAD) { + return false; + } + if (incumbent_etx == ETX_DEAD) { + return true; + } + return (candidate_etx < incumbent_etx); +} + +pub fn path_etx(upstream_etx: u32, link_etx: u32) -> u32 { + if (upstream_etx == ETX_DEAD) { + return ETX_DEAD; + } + if (link_etx == ETX_DEAD) { + return ETX_DEAD; + } + return (upstream_etx + link_etx); +} + +pub fn is_feasible(new_etx: u32, existing_etx: u32, has_existing: u32) -> bool { + if (has_existing == 0) { + return true; + } + return better_route(new_etx, existing_etx); +} + +pub fn learn_ok(is_self_route: u32, feasible: bool) -> bool { + if (is_self_route == 1) { + return false; + } + return feasible; +} + diff --git a/gen/rust/rti_alert.rs b/gen/rust/rti_alert.rs new file mode 100644 index 00000000..b6f2f3df --- /dev/null +++ b/gen/rust/rti_alert.rs @@ -0,0 +1,27 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const SEV_CATASTROPHIC: u8 = 4; + +pub const SEV_CRITICAL: u8 = 3; + +pub const SEV_URGENT: u8 = 2; + +pub const SEV_WARNING: u8 = 1; + +pub fn alert_severity(anom_sev: u32) -> u8 { + if (anom_sev >= 80) { + return SEV_CATASTROPHIC; + } else { + if (anom_sev >= 60) { + return SEV_CRITICAL; + } else { + if (anom_sev >= 40) { + return SEV_URGENT; + } else { + return SEV_WARNING; + } + } + } +} + diff --git a/gen/rust/rti_security.rs b/gen/rust/rti_security.rs new file mode 100644 index 00000000..7587f288 --- /dev/null +++ b/gen/rust/rti_security.rs @@ -0,0 +1,140 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const MAX_ZONES: u8 = 16; + +pub const ZONE_GRID: u8 = 40; + +pub const ALERT_COOLDOWN_MS: u16 = 5000; + +pub const SENSITIVITY_LOW: u8 = 1; + +pub const SENSITIVITY_MEDIUM: u8 = 2; + +pub const SENSITIVITY_HIGH: u8 = 3; + +pub const ALERT_NONE: u8 = 0; + +pub const ALERT_INFO: u8 = 1; + +pub const ALERT_WARNING: u8 = 2; + +pub const ALERT_CRITICAL: u8 = 3; + +pub const ALERT_TEST: u8 = 4; + +pub const ALERT_ENTRY_SIZE: u8 = 8; + +pub const ZONE_DEF_SIZE: u8 = 6; + +pub fn alert_threshold(sensitivity: u8, is_night: bool) -> u16 { + if is_night { + if (sensitivity == SENSITIVITY_HIGH) { + return 20; + } + if (sensitivity == SENSITIVITY_LOW) { + return 40; + } + return 30; + } + if (sensitivity == SENSITIVITY_HIGH) { + return 40; + } + if (sensitivity == SENSITIVITY_LOW) { + return 80; + } + return 60; +} + +pub fn classify_alert(brightness: u8, size_cells: u8, sensitivity: u8, is_night: bool) -> u8 { + let threshold: u16 = alert_threshold(sensitivity, is_night); + if (brightness < threshold) { + return ALERT_NONE; + } + if (size_cells > 8) { + return ALERT_CRITICAL; + } + if (size_cells > 4) { + return ALERT_WARNING; + } + return ALERT_INFO; +} + +pub fn in_cooldown(ms_since_last_alert: u16) -> bool { + return (ms_since_last_alert < ALERT_COOLDOWN_MS); +} + +pub fn should_suppress(level: u8, prev_level: u8, cooldown_ms: u16) -> bool { + if (level == ALERT_NONE) { + return true; + } + if in_cooldown(cooldown_ms) { + if (level <= prev_level) { + return true; + } + } + return false; +} + +pub fn zone_from_coord(x: u8, y: u8, zone_size: u8) -> u8 { + if (zone_size == 0) { + return 0; + } + let zx: u8 = (x / zone_size); + let zy: u8 = (y / zone_size); + return ((zy * (ZONE_GRID / zone_size)) + zx); +} + +pub fn in_zone(px: u8, py: u8, x1: u8, y1: u8, x2: u8, y2: u8) -> bool { + if (px < x1) { + return false; + } + if (px > x2) { + return false; + } + if (py < y1) { + return false; + } + if (py > y2) { + return false; + } + return true; +} + +pub fn threat_score(level: u8, size: u8, confidence: u8) -> u16 { + if (level == ALERT_NONE) { + return 0; + } + let base: u16 = ((level as u16) * 100); + let size_bonus: u16 = ((size as u16) * 10); + let conf_bonus: u16 = (confidence as u16); + return ((base + size_bonus) + conf_bonus); +} + +pub fn should_escalate(current: u8, accumulated_threat: u16) -> bool { + if (current == ALERT_CRITICAL) { + return false; + } + return (accumulated_threat > 400); +} + +pub fn is_night_time(hour: u8) -> bool { + if (hour < 6) { + return true; + } + if (hour >= 22) { + return true; + } + return false; +} + +pub fn notification_priority(level: u8) -> u8 { + if (level == ALERT_CRITICAL) { + return 10; + } + if (level == ALERT_WARNING) { + return 5; + } + return 1; +} + diff --git a/gen/rust/swarm_coordinator.rs b/gen/rust/swarm_coordinator.rs index 9560332e..188f8573 100644 --- a/gen/rust/swarm_coordinator.rs +++ b/gen/rust/swarm_coordinator.rs @@ -133,6 +133,7 @@ pub fn calculate_consensus_value(vote_array: u64, proposal_id: u32) -> u32 { } pub fn cooperative_decision(neighbor_values: u32, my_value: u32, weight_neighbors: u32) -> u32 { + let neighbor_avg = neighbor_values; let weighted_neighbors = ((neighbor_values * weight_neighbors) / 100); let weighted_self = ((my_value * (100 - weight_neighbors)) / 100); return (weighted_neighbors + weighted_self); diff --git a/gen/rust/test_framework.rs b/gen/rust/test_framework.rs index 4c5d38a1..22906c43 100644 --- a/gen/rust/test_framework.rs +++ b/gen/rust/test_framework.rs @@ -148,8 +148,10 @@ pub fn check_assertion(assertion: u32) -> u32 { pub fn run_test_case(test_case: u32, function_ptr: u32) -> u32 { let test_id: u32 = get_test_case_id(test_case); + let function_id: u32 = get_function_id(test_case); let input: u32 = get_test_input(test_case); let expected: u32 = get_expected_output(test_case); + let actual: u32 = input; let assertion: u32 = create_assertion(ASSERT_EQUAL, input, expected, 0); let passed: u32 = check_assertion(assertion); if (passed == 1) { @@ -179,14 +181,14 @@ pub fn get_teardown_id(suite: u32) -> u32 { return (suite & 0xFF); } -pub fn run_test_suite(suite: u32, tests: Vec<>, test_count: u32) -> u32 { +pub fn run_test_suite(suite: u32, tests: [u32; MAX_TESTS as usize], test_count: u32) -> u32 { let suite_id: u32 = get_suite_id(suite); let mut total_assertions: u32 = 0; let mut total_failures: u32 = 0; let mut passed_tests: u32 = 0; let mut i: u32 = 0; while (i < test_count) { - let result: u32 = run_test_case(tests[i], 0); + let result: u32 = run_test_case(tests[(i) as usize], 0); let assertions: u32 = get_assertion_count(result); let failures: u32 = get_failure_count(result); let status: u32 = get_test_status(result); @@ -230,13 +232,13 @@ pub fn calculate_coverage_percentage(coverage: u32) -> u32 { } } -pub fn aggregate_coverage(coverage_data: Vec<>, count: u32) -> u32 { +pub fn aggregate_coverage(coverage_data: [u32; MAX_TESTS as usize], count: u32) -> u32 { let mut total_branches: u32 = 0; let mut total_covered: u32 = 0; let mut i: u32 = 0; while (i < count) { - total_branches = (total_branches + get_branch_count(coverage_data[i])); - total_covered = (total_covered + get_covered_branches(coverage_data[i])); + total_branches = (total_branches + get_branch_count(coverage_data[(i) as usize])); + total_covered = (total_covered + get_covered_branches(coverage_data[(i) as usize])); i = (i + 1); } if (total_branches > 0) { @@ -284,6 +286,7 @@ pub fn generate_test_input(generator_id: u32, seed: u32) -> u32 { } pub fn run_property_test(prop_id: u32, generator_count: u32, test_count: u32) -> u32 { + let failures: u32 = 0; let mut i: u32 = 0; while (i < test_count) { let mut j: u32 = 0; @@ -337,6 +340,7 @@ pub fn meets_coverage_target(coverage_percentage: u32, target: u32) -> u32 { pub fn generate_test_report(summary: u32, coverage: u32, duration_ms: u32) -> u32 { let pass_rate: u32 = calculate_pass_rate(summary); let coverage_pct: u32 = calculate_coverage_percentage(coverage); + let mut status: u32 = 0; if ((pass_rate >= 90) && (coverage_pct >= COVERAGE_TARGET)) { status = 1; } else { diff --git a/gen/rust/test_validator.rs b/gen/rust/test_validator.rs index 261a6153..c600386d 100644 --- a/gen/rust/test_validator.rs +++ b/gen/rust/test_validator.rs @@ -224,14 +224,14 @@ pub const VALIDATION_FAIL: u32 = 1; pub const VALIDATION_WARNING: u32 = 2; -pub fn run_validation(errors: Vec<>, error_count: u32, warnings: Vec<>, warning_count: u32) -> u32 { +pub fn run_validation(errors: [u32; MAX_ERRORS as usize], error_count: u32, warnings: [u32; MAX_WARNINGS as usize], warning_count: u32) -> u32 { let mut total_errors: u32 = 0; let mut total_warnings: u32 = 0; let mut total_info: u32 = 0; let mut status: u32 = VALIDATION_PASS; let mut i: u32 = 0; while (i < error_count) { - let severity: u32 = get_error_severity(errors[i]); + let severity: u32 = get_error_severity(errors[(i) as usize]); if (severity == SEVERITY_ERROR) { total_errors = (total_errors + 1); } else { diff --git a/gen/rust/topology_visualizer.rs b/gen/rust/topology_visualizer.rs index 3ec23a8e..d3716bb4 100644 --- a/gen/rust/topology_visualizer.rs +++ b/gen/rust/topology_visualizer.rs @@ -139,7 +139,7 @@ pub const ALGORITHM_HIERARCHICAL: u32 = 2; pub const ALGORITHM_GRID: u32 = 3; -pub fn calculate_force_layout(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_count: u32, params: u32) -> u32 { +pub fn calculate_force_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32, params: u32) -> u32 { let iterations: u32 = get_layout_iterations(params); let mut temperature: u32 = get_layout_temperature(params); let mut placed_nodes: u32 = 0; @@ -147,14 +147,14 @@ pub fn calculate_force_layout(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_ while ((i < iterations) && (placed_nodes < node_count)) { let mut j: u32 = 0; while (j < node_count) { - let node_id: u32 = get_viz_node_id(nodes[j]); - let x: u32 = get_node_x_position(nodes[j]); - let y: u32 = get_node_y_position(nodes[j]); + let node_id: u32 = get_viz_node_id(nodes[(j) as usize]); + let x: u32 = get_node_x_position(nodes[(j) as usize]); + let y: u32 = get_node_y_position(nodes[(j) as usize]); let mut k: u32 = 0; while (k < node_count) { if (k != j) { - let other_x: u32 = get_node_x_position(nodes[k]); - let other_y: u32 = get_node_y_position(nodes[k]); + let other_x: u32 = get_node_x_position(nodes[(k) as usize]); + let other_y: u32 = get_node_y_position(nodes[(k) as usize]); let mut dx: u32 = 0; if (x > other_x) { dx = (x - other_x); @@ -176,8 +176,8 @@ pub fn calculate_force_layout(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_ } let mut l: u32 = 0; while (l < edge_count) { - let source: u32 = get_viz_edge_source(edges[l]); - let dest: u32 = get_viz_edge_dest(edges[l]); + let source: u32 = get_viz_edge_source(edges[(l) as usize]); + let dest: u32 = get_viz_edge_dest(edges[(l) as usize]); if ((source == node_id) || (dest == node_id)) { } l = (l + 1); @@ -193,7 +193,7 @@ pub fn calculate_force_layout(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_ return placed_nodes; } -pub fn calculate_circular_layout(nodes: Vec<>, node_count: u32) -> u32 { +pub fn calculate_circular_layout(nodes: [u32; MAX_NODES as usize], node_count: u32) -> u32 { let center_x: u32 = (CANVAS_SIZE / 2); let center_y: u32 = _cse1; let radius: u32 = (CANVAS_SIZE / 3); @@ -203,15 +203,16 @@ pub fn calculate_circular_layout(nodes: Vec<>, node_count: u32) -> u32 { let angle: u32 = ((i * 360) / node_count); let x: u32 = (center_x + ((radius * angle) / 360)); let y: u32 = (center_y + ((radius * angle) / 360)); - let node_id: u32 = get_viz_node_id(nodes[i]); - let status: u32 = get_node_visual_status(nodes[i]); - nodes[i] = create_visual_node(node_id, x, y, status); + let node_id: u32 = get_viz_node_id(nodes[(i) as usize]); + let status: u32 = get_node_visual_status(nodes[(i) as usize]); + nodes[(i) as usize] = create_visual_node(node_id, x, y, status); i = (i + 1); } return node_count; } -pub fn calculate_hierarchical_layout(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_count: u32) -> u32 { +pub fn calculate_hierarchical_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32) -> u32 { + let level_count: u32 = 4; let nodes_per_level: u32 = (node_count / 4); let mut i: u32 = 0; let mut current_level: u32 = 0; @@ -219,9 +220,9 @@ pub fn calculate_hierarchical_layout(nodes: Vec<>, edges: Vec<>, node_count: u32 while (i < node_count) { let y: u32 = ((current_level * CANVAS_SIZE) / 4); let x: u32 = ((nodes_in_level * CANVAS_SIZE) / nodes_per_level); - let node_id: u32 = get_viz_node_id(nodes[i]); - let status: u32 = get_node_visual_status(nodes[i]); - nodes[i] = create_visual_node(node_id, x, y, status); + let node_id: u32 = get_viz_node_id(nodes[(i) as usize]); + let status: u32 = get_node_visual_status(nodes[(i) as usize]); + nodes[(i) as usize] = create_visual_node(node_id, x, y, status); nodes_in_level = (nodes_in_level + 1); if (nodes_in_level >= nodes_per_level) { nodes_in_level = 0; @@ -232,7 +233,7 @@ pub fn calculate_hierarchical_layout(nodes: Vec<>, edges: Vec<>, node_count: u32 return node_count; } -pub fn apply_layout(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_count: u32, params: u32) -> u32 { +pub fn apply_layout(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32, params: u32) -> u32 { let algorithm: u32 = get_layout_algorithm(params); if (algorithm == ALGORITHM_FORCE_DIRECTED) { return calculate_force_layout(nodes, edges, node_count, edge_count, params); @@ -257,7 +258,7 @@ pub fn render_node(node: u32, size: u32, color: u32) -> u32 { return (((((x & 0xFF) << 24) | ((y & 0xFF) << 16)) | ((size & 0xFF) << 8)) | (node_color & 0xFF)); } -pub fn render_edge(edge: u32, nodes: Vec<>, thickness: u32) -> u32 { +pub fn render_edge(edge: u32, nodes: [u32; MAX_NODES as usize], thickness: u32) -> u32 { let source: u32 = get_viz_edge_source(edge); let dest: u32 = get_viz_edge_dest(edge); let quality: u32 = get_viz_edge_quality(edge); @@ -267,17 +268,18 @@ pub fn render_edge(edge: u32, nodes: Vec<>, thickness: u32) -> u32 { let mut dest_y: u32 = 0; let mut i: u32 = 0; while (i < MAX_NODES) { - let node_id: u32 = get_viz_node_id(nodes[i]); + let node_id: u32 = get_viz_node_id(nodes[(i) as usize]); if (node_id == source) { - source_x = get_node_x_position(nodes[i]); - source_y = get_node_y_position(nodes[i]); + source_x = get_node_x_position(nodes[(i) as usize]); + source_y = get_node_y_position(nodes[(i) as usize]); } if (node_id == dest) { - dest_x = get_node_x_position(nodes[i]); - dest_y = get_node_y_position(nodes[i]); + dest_x = get_node_x_position(nodes[(i) as usize]); + dest_y = get_node_y_position(nodes[(i) as usize]); } i = (i + 1); } + let mut edge_color: u32 = 0; if (quality > 70) { edge_color = COLOR_GREEN; } else { @@ -290,17 +292,17 @@ pub fn render_edge(edge: u32, nodes: Vec<>, thickness: u32) -> u32 { return (((((source_x & 0xFF) << 24) | ((source_y & 0xFF) << 16)) | ((dest_x & 0xFF) << 8)) | (dest_y & 0xFF)); } -pub fn create_visualization_frame(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_count: u32) -> u32 { +pub fn create_visualization_frame(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32) -> u32 { let mut frame_size: u32 = 0; let mut i: u32 = 0; while (i < node_count) { - let rendered: u32 = render_node(nodes[i], 20, COLOR_GREEN); + let rendered: u32 = render_node(nodes[(i) as usize], 20, COLOR_GREEN); frame_size = (frame_size + 1); i = (i + 1); } let mut j: u32 = 0; while (j < edge_count) { - let rendered: u32 = render_edge(edges[j], nodes, 2); + let rendered: u32 = render_edge(edges[(j) as usize], nodes, 2); frame_size = (frame_size + 1); j = (j + 1); } @@ -324,9 +326,10 @@ pub fn optimize_rendering(node_count: u32, edge_count: u32, target_fps: u32) -> } } -pub fn generate_topology_visualization(nodes: Vec<>, edges: Vec<>, node_count: u32, edge_count: u32, layout_params: u32) -> u32 { +pub fn generate_topology_visualization(nodes: [u32; MAX_NODES as usize], edges: [u32; MAX_EDGES as usize], node_count: u32, edge_count: u32, layout_params: u32) -> u32 { let layout_result: u32 = apply_layout(nodes, edges, node_count, edge_count, layout_params); let frame: u32 = create_visualization_frame(nodes, edges, node_count, edge_count); + let fps: u32 = 30; let detail_level: u32 = optimize_rendering(node_count, edge_count, 30); let complexity: u32 = calculate_viz_complexity(node_count, edge_count); return (((((layout_result & 0xFF) << 24) | ((frame & 0xFF) << 16)) | ((detail_level & 0xFF) << 8)) | (complexity & 0xFF)); diff --git a/gen/rust/traffic_animator.rs b/gen/rust/traffic_animator.rs index aeb2f5ec..639dfee8 100644 --- a/gen/rust/traffic_animator.rs +++ b/gen/rust/traffic_animator.rs @@ -229,21 +229,21 @@ pub fn calculate_packet_position(source_x: u32, source_y: u32, dest_x: u32, dest return (((current_x & 0xFF) << 24) | ((current_y & 0xFF) << 16)); } -pub fn update_animation_packets(packets: Vec<>, packet_count: u32, speed: u32) -> u32 { +pub fn update_animation_packets(packets: [u32; MAX_PACKETS as usize], packet_count: u32, speed: u32) -> u32 { let mut updated_count: u32 = 0; let mut completed_count: u32 = 0; let mut i: u32 = 0; while (i < packet_count) { - let progress: u32 = get_anim_packet_progress(packets[i]); + let progress: u32 = get_anim_packet_progress(packets[(i) as usize]); if (progress < 100) { let mut new_progress: u32 = (progress + speed); if (new_progress > 100) { new_progress = 100; } - let packet_id: u32 = get_anim_packet_id(packets[i]); - let source: u32 = get_anim_packet_source(packets[i]); - let dest: u32 = get_anim_packet_dest(packets[i]); - packets[i] = create_anim_packet(packet_id, source, dest, new_progress); + let packet_id: u32 = get_anim_packet_id(packets[(i) as usize]); + let source: u32 = get_anim_packet_source(packets[(i) as usize]); + let dest: u32 = get_anim_packet_dest(packets[(i) as usize]); + packets[(i) as usize] = create_anim_packet(packet_id, source, dest, new_progress); updated_count = (updated_count + 1); } else { completed_count = (completed_count + 1); @@ -253,7 +253,7 @@ pub fn update_animation_packets(packets: Vec<>, packet_count: u32, speed: u32) - return ((((updated_count & 0xFF) << 24) | ((completed_count & 0xFF) << 16)) | ((packet_count & 0xFF) << 8)); } -pub fn render_animation_frame(packets: Vec<>, packet_count: u32, paths: Vec<>, path_count: u32, frame_id: u32) -> u32 { +pub fn render_animation_frame(packets: [u32; MAX_PACKETS as usize], packet_count: u32, paths: [u32; MAX_PATHS as usize], path_count: u32, frame_id: u32) -> u32 { let timestamp: u32 = (frame_id * (1000 / ANIMATION_FPS)); let duration: u32 = (1000 / ANIMATION_FPS); return create_animation_frame(frame_id, timestamp, packet_count, duration); @@ -275,23 +275,23 @@ pub fn optimize_animation_performance(packet_count: u32, target_fps: u32) -> u32 } } -pub fn generate_traffic_heat_map(packets: Vec<>, packet_count: u32, node_count: u32) -> u32 { - let mut traffic_counts: Vec<> = vec![]; +pub fn generate_traffic_heat_map(packets: [u32; MAX_PACKETS as usize], packet_count: u32, node_count: u32) -> u32 { + let mut traffic_counts: [u32; 32] = vec![]; let mut max_traffic: u32 = 0; let mut i: u32 = 0; while (i < packet_count) { - let source: u32 = get_anim_packet_source(packets[i]); - let dest: u32 = get_anim_packet_dest(packets[i]); + let source: u32 = get_anim_packet_source(packets[(i) as usize]); + let dest: u32 = get_anim_packet_dest(packets[(i) as usize]); if (source < 32) { - traffic_counts[source] = (traffic_counts[source] + 1); - if (traffic_counts[source] > max_traffic) { - max_traffic = traffic_counts[source]; + traffic_counts[(source) as usize] = (traffic_counts[(source) as usize] + 1); + if (traffic_counts[(source) as usize] > max_traffic) { + max_traffic = traffic_counts[(source) as usize]; } } if (dest < 32) { - traffic_counts[dest] = (traffic_counts[dest] + 1); - if (traffic_counts[dest] > max_traffic) { - max_traffic = traffic_counts[dest]; + traffic_counts[(dest) as usize] = (traffic_counts[(dest) as usize] + 1); + if (traffic_counts[(dest) as usize] > max_traffic) { + max_traffic = traffic_counts[(dest) as usize]; } } i = (i + 1); @@ -300,9 +300,9 @@ pub fn generate_traffic_heat_map(packets: Vec<>, packet_count: u32, node_count: let mut total_traffic: u32 = 0; let mut j: u32 = 0; while ((j < node_count) && (j < 32)) { - if (traffic_counts[j] > 0) { + if (traffic_counts[(j) as usize] > 0) { total_active = (total_active + 1); - total_traffic = (total_traffic + traffic_counts[j]); + total_traffic = (total_traffic + traffic_counts[(j) as usize]); } j = (j + 1); } @@ -313,10 +313,13 @@ pub fn generate_traffic_heat_map(packets: Vec<>, packet_count: u32, node_count: return ((((max_traffic & 0xFF) << 24) | ((total_active & 0xFF) << 16)) | ((avg_traffic & 0xFF) << 8)); } -pub fn generate_traffic_animation(packets: Vec<>, packet_count: u32, paths: Vec<>, path_count: u32, node_count: u32, duration_frames: u32) -> u32 { +pub fn generate_traffic_animation(packets: [u32; MAX_PACKETS as usize], packet_count: u32, paths: [u32; MAX_PATHS as usize], path_count: u32, node_count: u32, duration_frames: u32) -> u32 { + let total_frames: u32 = duration_frames; + let current_frame: u32 = 0; let complexity: u32 = calculate_animation_complexity(packet_count, path_count, node_count); let optimization: u32 = optimize_animation_performance(packet_count, ANIMATION_FPS); let actual_packet_count: u32 = (packet_count - optimization); + let timeline: u32 = create_animation_timeline(0, duration_frames, 0, 1); let heat_map: u32 = generate_traffic_heat_map(packets, actual_packet_count, node_count); let max_traffic: u32 = ((heat_map >> 24) & 0xFF); return (((((duration_frames & 0xFF) << 24) | ((complexity & 0xFF) << 16)) | ((actual_packet_count & 0xFF) << 8)) | (max_traffic & 0xFF)); @@ -342,13 +345,13 @@ pub fn process_animation_control(control: u32, timeline: u32) -> u32 { } } -pub fn calculate_animation_stats(frames: Vec<>, frame_count: u32) -> u32 { +pub fn calculate_animation_stats(frames: [u32; MAX_FRAMES as usize], frame_count: u32) -> u32 { let mut total_packets: u32 = 0; let mut total_bytes: u32 = 0; let mut avg_latency: u32 = 0; let mut i: u32 = 0; while (i < frame_count) { - let packet_count: u32 = get_anim_frame_packet_count(frames[i]); + let packet_count: u32 = get_anim_frame_packet_count(frames[(i) as usize]); total_packets = (total_packets + packet_count); total_bytes = (total_bytes + (packet_count * 256)); i = (i + 1); diff --git a/gen/rust/tri_challenge.rs b/gen/rust/tri_challenge.rs new file mode 100644 index 00000000..a6526c31 --- /dev/null +++ b/gen/rust/tri_challenge.rs @@ -0,0 +1,35 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const DEFENDER_HONEST: u32 = 1; + +pub const DEFENDER_LIED: u32 = 2; + +pub fn is_valid_challenge(defender_seal: u32, challenger_seal: u32) -> bool { + return (defender_seal != challenger_seal); +} + +pub fn resolve(defender_seal: u32, truth_seal: u32) -> u32 { + if (defender_seal == truth_seal) { + return DEFENDER_HONEST; + } else { + return DEFENDER_LIED; + } +} + +pub fn defender_bond_after(verdict: u32, defender_bond: u32, challenger_bond: u32) -> u32 { + if (verdict == DEFENDER_HONEST) { + return (defender_bond + challenger_bond); + } else { + return 0; + } +} + +pub fn challenger_bond_after(verdict: u32, defender_bond: u32, challenger_bond: u32) -> u32 { + if (verdict == DEFENDER_HONEST) { + return 0; + } else { + return (challenger_bond + defender_bond); + } +} + diff --git a/gen/rust/tri_depin.rs b/gen/rust/tri_depin.rs new file mode 100644 index 00000000..2c6d774b --- /dev/null +++ b/gen/rust/tri_depin.rs @@ -0,0 +1,58 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const TRI_GENESIS: u32 = 0x54524921; + +pub const TRI_PHI: u32 = 0x9E3779B9; + +pub fn rotl32(x: u32, k: u32) -> u32 { + return ((x << k) | (x >> (32 - k))); +} + +pub fn mix32(x: u32) -> u32 { + let a: u32 = (x ^ (x >> 16)); + let b: u32 = (a + (a << 3)); + let c: u32 = (b ^ (b >> 11)); + let d: u32 = (c + (c << 15)); + return (d ^ (d >> 16)); +} + +pub fn relay_absorb(acc: u32, pkt_digest: u32, nbytes: u32) -> u32 { + return mix32((((acc ^ pkt_digest) ^ rotl32(nbytes, 7)) ^ TRI_PHI)); +} + +pub fn epoch_seal(acc: u32, total_bytes: u32, node_key: u32, epoch: u32) -> u32 { + let idbind: u32 = mix32((node_key ^ rotl32(epoch, 13))); + let workbind: u32 = mix32((acc ^ rotl32(total_bytes, 19))); + return mix32((workbind ^ idbind)); +} + +pub fn verify_epoch(claimed_seal: u32, acc: u32, total_bytes: u32, node_key: u32, epoch: u32) -> bool { + return (epoch_seal(acc, total_bytes, node_key, epoch) == claimed_seal); +} + +pub fn bytes_add(total: u32, nbytes: u32) -> u32 { + let sum: u32 = (total + nbytes); + if (sum < total) { + return 0xFFFFFFFF; + } else { + return sum; + } +} + +pub fn relay_absorb_verified(acc: u32, computed_digest: u32, expected_digest: u32, nbytes: u32) -> u32 { + if (computed_digest == expected_digest) { + return relay_absorb(acc, computed_digest, nbytes); + } else { + return acc; + } +} + +pub fn bytes_add_verified(total: u32, nbytes: u32, computed_digest: u32, expected_digest: u32) -> u32 { + if (computed_digest == expected_digest) { + return bytes_add(total, nbytes); + } else { + return total; + } +} + diff --git a/gen/rust/tri_fec.rs b/gen/rust/tri_fec.rs new file mode 100644 index 00000000..d034f939 --- /dev/null +++ b/gen/rust/tri_fec.rs @@ -0,0 +1,15 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub fn fec_parity4(a: u32, b: u32, c: u32, d: u32) -> u32 { + return (((a ^ b) ^ c) ^ d); +} + +pub fn fec_xor(a: u32, b: u32) -> u32 { + return (a ^ b); +} + +pub fn fec_recover(parity: u32, survivors_xor: u32) -> u32 { + return (parity ^ survivors_xor); +} + diff --git a/gen/rust/tri_ilv.rs b/gen/rust/tri_ilv.rs new file mode 100644 index 00000000..5f052127 --- /dev/null +++ b/gen/rust/tri_ilv.rs @@ -0,0 +1,33 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const DEPTH_CAP: u32 = 64; + +pub fn ilv_tx_pos(o: u32, depth: u32, width: u32) -> u32 { + return (((o % width) * depth) + (o / width)); +} + +pub fn ilv_orig(t: u32, depth: u32, width: u32) -> u32 { + return (((t % depth) * width) + (t / depth)); +} + +pub fn ilv_codeword(o: u32, width: u32) -> u32 { + return (o / width); +} + +pub fn choose_depth(max_burst: u32) -> u32 { + if (max_burst == 0) { + return 1; + } else { + if (max_burst >= DEPTH_CAP) { + return DEPTH_CAP; + } else { + return max_burst; + } + } +} + +pub fn depth_survives(depth: u32, burst: u32) -> bool { + return (depth >= burst); +} + diff --git a/gen/rust/tri_ledger.rs b/gen/rust/tri_ledger.rs new file mode 100644 index 00000000..c2737e6a --- /dev/null +++ b/gen/rust/tri_ledger.rs @@ -0,0 +1,39 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const LEDGER_GENESIS: u32 = 0x54524C47; + +pub const L_C: u32 = 0x9E3779B9; + +pub fn rotl(x: u32, k: u32) -> u32 { + return ((x << k) | (x >> (32 - k))); +} + +pub fn mix32(x: u32) -> u32 { + let a: u32 = (x ^ (x >> 16)); + let b: u32 = (a + (a << 3)); + let c: u32 = (b ^ (b >> 11)); + let d: u32 = (c + (c << 15)); + return (d ^ (d >> 16)); +} + +pub fn balance_add(bal: u32, reward: u32) -> u32 { + let sum: u32 = (bal + reward); + if (sum < bal) { + return 0xFFFFFFFF; + } else { + return sum; + } +} + +pub fn state_step(prev_state: u32, round_root: u32, epoch: u32) -> u32 { + return mix32((prev_state ^ mix32((round_root ^ rotl(epoch, 13))))); +} + +pub fn verify_chain3(rr0: u32, e0: u32, rr1: u32, e1: u32, rr2: u32, e2: u32, claimed: u32) -> bool { + let s0: u32 = state_step(LEDGER_GENESIS, rr0, e0); + let s1: u32 = state_step(s0, rr1, e1); + let s2: u32 = state_step(s1, rr2, e2); + return (s2 == claimed); +} + diff --git a/gen/rust/tri_merkle.rs b/gen/rust/tri_merkle.rs new file mode 100644 index 00000000..0aaa5474 --- /dev/null +++ b/gen/rust/tri_merkle.rs @@ -0,0 +1,58 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const M_C: u32 = 0x9E3779B9; + +pub fn rotl(x: u32, k: u32) -> u32 { + return ((x << k) | (x >> (32 - k))); +} + +pub fn mix32(x: u32) -> u32 { + let a: u32 = (x ^ (x >> 16)); + let b: u32 = (a + (a << 3)); + let c: u32 = (b ^ (b >> 11)); + let d: u32 = (c + (c << 15)); + return (d ^ (d >> 16)); +} + +pub fn hpair(l: u32, r: u32) -> u32 { + let a: u32 = mix32((l ^ M_C)); + let b: u32 = mix32((r ^ rotl(l, 13))); + return mix32((a ^ rotl(b, 7))); +} + +pub fn leaf_hash(node_id: u32, total_bytes: u32, quality: u32, reward: u32) -> u32 { + let a: u32 = mix32((node_id ^ rotl(total_bytes, 5))); + let b: u32 = mix32((quality ^ rotl(reward, 11))); + return hpair(a, b); +} + +pub fn account_leaf(node_id: u32, balance: u32) -> u32 { + return hpair(mix32((node_id ^ M_C)), mix32((balance ^ rotl(node_id, 7)))); +} + +pub fn merkle_root8(l0: u32, l1: u32, l2: u32, l3: u32, l4: u32, l5: u32, l6: u32, l7: u32) -> u32 { + let p0: u32 = hpair(l0, l1); + let p1: u32 = hpair(l2, l3); + let p2: u32 = hpair(l4, l5); + let p3: u32 = hpair(l6, l7); + let q0: u32 = hpair(p0, p1); + let q1: u32 = hpair(p2, p3); + return hpair(q0, q1); +} + +pub fn merkle_step(node: u32, sibling: u32, is_right: u32) -> u32 { + if (is_right == 1) { + return hpair(sibling, node); + } else { + return hpair(node, sibling); + } +} + +pub fn merkle_verify8(leaf: u32, s0: u32, s1: u32, s2: u32, idx: u32, root: u32) -> bool { + let n0: u32 = merkle_step(leaf, s0, (idx & 1)); + let n1: u32 = merkle_step(n0, s1, ((idx >> 1) & 1)); + let n2: u32 = merkle_step(n1, s2, ((idx >> 2) & 1)); + return (n2 == root); +} + diff --git a/gen/rust/tri_settle.rs b/gen/rust/tri_settle.rs new file mode 100644 index 00000000..0c259831 --- /dev/null +++ b/gen/rust/tri_settle.rs @@ -0,0 +1,68 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const PPM: u32 = 1000000; + +pub const SNR_FLOOR: u32 = 3; + +pub const SNR_CEIL: u32 = 40; + +pub fn round_add(round_total: u32, epoch_bytes: u32) -> u32 { + let sum: u32 = (round_total + epoch_bytes); + if (sum < round_total) { + return 0xFFFFFFFF; + } else { + return sum; + } +} + +pub fn reward_share_ppm(node_bytes: u32, round_bytes: u32) -> u32 { + if (round_bytes == 0) { + return 0; + } else { + let scaled: u64 = ((node_bytes as u64) * (PPM as u64)); + return ((scaled / (round_bytes as u64)) as u32); + } +} + +pub fn reward_units(node_bytes: u32, round_bytes: u32, pool: u32) -> u64 { + if (round_bytes == 0) { + return 0; + } else { + let num: u64 = ((pool as u64) * (node_bytes as u64)); + return (num / (round_bytes as u64)); + } +} + +pub fn weighted_contrib(node_bytes: u32, quality: u32) -> u64 { + return ((node_bytes as u64) * (quality as u64)); +} + +pub fn round_add_weighted(wtotal: u64, node_bytes: u32, quality: u32) -> u64 { + return (wtotal + weighted_contrib(node_bytes, quality)); +} + +pub fn reward_weighted(node_bytes: u32, quality: u32, weighted_total: u64, pool: u32) -> u64 { + let hi: u32 = ((weighted_total >> 32) as u32); + let lo: u32 = (weighted_total as u32); + if ((hi == 0) && (lo == 0)) { + return 0; + } else { + let contrib: u64 = ((node_bytes as u64) * (quality as u64)); + let ppm: u64 = ((contrib * 1000000) / weighted_total); + return (((pool as u64) * ppm) / 1000000); + } +} + +pub fn snr_to_quality(snr_db: u32) -> u32 { + if (snr_db <= SNR_FLOOR) { + return 0; + } else { + if (snr_db >= SNR_CEIL) { + return (SNR_CEIL - SNR_FLOOR); + } else { + return (snr_db - SNR_FLOOR); + } + } +} + diff --git a/gen/rust/tri_sha256.rs b/gen/rust/tri_sha256.rs new file mode 100644 index 00000000..ee67ad58 --- /dev/null +++ b/gen/rust/tri_sha256.rs @@ -0,0 +1,771 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub fn rotr(x: u32, n: u32) -> u32 { + return ((x >> n) | (x << (32 - n))); +} + +pub fn shr(x: u32, n: u32) -> u32 { + return (x >> n); +} + +pub fn ch(x: u32, y: u32, z: u32) -> u32 { + return ((x & y) ^ ((x ^ 0xFFFFFFFF) & z)); +} + +pub fn maj(x: u32, y: u32, z: u32) -> u32 { + return (((x & y) ^ (x & z)) ^ (y & z)); +} + +pub fn bsig0(x: u32) -> u32 { + return ((rotr(x, 2) ^ rotr(x, 13)) ^ rotr(x, 22)); +} + +pub fn bsig1(x: u32) -> u32 { + return ((rotr(x, 6) ^ rotr(x, 11)) ^ rotr(x, 25)); +} + +pub fn ssig0(x: u32) -> u32 { + return ((rotr(x, 7) ^ rotr(x, 18)) ^ shr(x, 3)); +} + +pub fn ssig1(x: u32) -> u32 { + return ((rotr(x, 17) ^ rotr(x, 19)) ^ shr(x, 10)); +} + +pub fn sha256_word(w0: u32, w1: u32, w2: u32, w3: u32, w4: u32, w5: u32, w6: u32, w7: u32, w8: u32, w9: u32, w10: u32, w11: u32, w12: u32, w13: u32, w14: u32, w15: u32, which: u32) -> u32 { + let w16: u32 = (((ssig1(w14) + w9) + ssig0(w1)) + w0); + let w17: u32 = (((ssig1(w15) + w10) + ssig0(w2)) + w1); + let w18: u32 = (((ssig1(w16) + w11) + ssig0(w3)) + w2); + let w19: u32 = (((ssig1(w17) + w12) + ssig0(w4)) + w3); + let w20: u32 = (((ssig1(w18) + w13) + ssig0(w5)) + w4); + let w21: u32 = (((ssig1(w19) + w14) + ssig0(w6)) + w5); + let w22: u32 = (((ssig1(w20) + w15) + ssig0(w7)) + w6); + let w23: u32 = (((ssig1(w21) + w16) + ssig0(w8)) + w7); + let w24: u32 = (((ssig1(w22) + w17) + ssig0(w9)) + w8); + let w25: u32 = (((ssig1(w23) + w18) + ssig0(w10)) + w9); + let w26: u32 = (((ssig1(w24) + w19) + ssig0(w11)) + w10); + let w27: u32 = (((ssig1(w25) + w20) + ssig0(w12)) + w11); + let w28: u32 = (((ssig1(w26) + w21) + ssig0(w13)) + w12); + let w29: u32 = (((ssig1(w27) + w22) + ssig0(w14)) + w13); + let w30: u32 = (((ssig1(w28) + w23) + ssig0(w15)) + w14); + let w31: u32 = (((ssig1(w29) + w24) + ssig0(w16)) + w15); + let w32: u32 = (((ssig1(w30) + w25) + ssig0(w17)) + w16); + let w33: u32 = (((ssig1(w31) + w26) + ssig0(w18)) + w17); + let w34: u32 = (((ssig1(w32) + w27) + ssig0(w19)) + w18); + let w35: u32 = (((ssig1(w33) + w28) + ssig0(w20)) + w19); + let w36: u32 = (((ssig1(w34) + w29) + ssig0(w21)) + w20); + let w37: u32 = (((ssig1(w35) + w30) + ssig0(w22)) + w21); + let w38: u32 = (((ssig1(w36) + w31) + ssig0(w23)) + w22); + let w39: u32 = (((ssig1(w37) + w32) + ssig0(w24)) + w23); + let w40: u32 = (((ssig1(w38) + w33) + ssig0(w25)) + w24); + let w41: u32 = (((ssig1(w39) + w34) + ssig0(w26)) + w25); + let w42: u32 = (((ssig1(w40) + w35) + ssig0(w27)) + w26); + let w43: u32 = (((ssig1(w41) + w36) + ssig0(w28)) + w27); + let w44: u32 = (((ssig1(w42) + w37) + ssig0(w29)) + w28); + let w45: u32 = (((ssig1(w43) + w38) + ssig0(w30)) + w29); + let w46: u32 = (((ssig1(w44) + w39) + ssig0(w31)) + w30); + let w47: u32 = (((ssig1(w45) + w40) + ssig0(w32)) + w31); + let w48: u32 = (((ssig1(w46) + w41) + ssig0(w33)) + w32); + let w49: u32 = (((ssig1(w47) + w42) + ssig0(w34)) + w33); + let w50: u32 = (((ssig1(w48) + w43) + ssig0(w35)) + w34); + let w51: u32 = (((ssig1(w49) + w44) + ssig0(w36)) + w35); + let w52: u32 = (((ssig1(w50) + w45) + ssig0(w37)) + w36); + let w53: u32 = (((ssig1(w51) + w46) + ssig0(w38)) + w37); + let w54: u32 = (((ssig1(w52) + w47) + ssig0(w39)) + w38); + let w55: u32 = (((ssig1(w53) + w48) + ssig0(w40)) + w39); + let w56: u32 = (((ssig1(w54) + w49) + ssig0(w41)) + w40); + let w57: u32 = (((ssig1(w55) + w50) + ssig0(w42)) + w41); + let w58: u32 = (((ssig1(w56) + w51) + ssig0(w43)) + w42); + let w59: u32 = (((ssig1(w57) + w52) + ssig0(w44)) + w43); + let w60: u32 = (((ssig1(w58) + w53) + ssig0(w45)) + w44); + let w61: u32 = (((ssig1(w59) + w54) + ssig0(w46)) + w45); + let w62: u32 = (((ssig1(w60) + w55) + ssig0(w47)) + w46); + let w63: u32 = (((ssig1(w61) + w56) + ssig0(w48)) + w47); + let a0: u32 = 0x6A09E667; + let b0: u32 = 0xBB67AE85; + let c0: u32 = 0x3C6EF372; + let d0: u32 = 0xA54FF53A; + let e0: u32 = 0x510E527F; + let f0: u32 = 0x9B05688C; + let g0: u32 = 0x1F83D9AB; + let h0: u32 = 0x5BE0CD19; + let t1_0: u32 = ((((0x5BE0CD19 + bsig1(0x510E527F)) + ch(0x510E527F, 0x9B05688C, 0x1F83D9AB)) + 0x428A2F98) + w0); + let t2_0: u32 = (bsig0(0x6A09E667) + maj(0x6A09E667, 0xBB67AE85, 0x3C6EF372)); + let a1: u32 = (t1_0 + t2_0); + let b1: u32 = 0x6A09E667; + let c1: u32 = 0xBB67AE85; + let d1: u32 = 0x3C6EF372; + let e1: u32 = (0xA54FF53A + t1_0); + let f1: u32 = 0x510E527F; + let g1: u32 = 0x9B05688C; + let h1: u32 = 0x1F83D9AB; + let t1_1: u32 = ((((h1 + bsig1(e1)) + ch(e1, f1, g1)) + 0x71374491) + w1); + let t2_1: u32 = (bsig0(a1) + maj(a1, b1, c1)); + let a2: u32 = (t1_1 + t2_1); + let b2: u32 = a1; + let c2: u32 = b1; + let d2: u32 = c1; + let e2: u32 = (d1 + t1_1); + let f2: u32 = e1; + let g2: u32 = f1; + let h2: u32 = g1; + let t1_2: u32 = ((((g1 + bsig1(e2)) + ch(e2, e1, f1)) + 0xB5C0FBCF) + w2); + let t2_2: u32 = (bsig0(a2) + maj(a2, a1, b1)); + let a3: u32 = (t1_2 + t2_2); + let b3: u32 = a2; + let c3: u32 = a1; + let d3: u32 = b1; + let e3: u32 = (c1 + t1_2); + let f3: u32 = e2; + let g3: u32 = e1; + let h3: u32 = f1; + let t1_3: u32 = ((((g2 + bsig1(e3)) + ch(e3, e2, f2)) + 0xE9B5DBA5) + w3); + let t2_3: u32 = (bsig0(a3) + maj(a3, a2, b2)); + let a4: u32 = (t1_3 + t2_3); + let b4: u32 = a3; + let c4: u32 = a2; + let d4: u32 = b2; + let e4: u32 = (c2 + t1_3); + let f4: u32 = e3; + let g4: u32 = e2; + let h4: u32 = f2; + let t1_4: u32 = ((((g3 + bsig1(e4)) + ch(e4, e3, f3)) + 0x3956C25B) + w4); + let t2_4: u32 = (bsig0(a4) + maj(a4, a3, b3)); + let a5: u32 = (t1_4 + t2_4); + let b5: u32 = a4; + let c5: u32 = a3; + let d5: u32 = b3; + let e5: u32 = (c3 + t1_4); + let f5: u32 = e4; + let g5: u32 = e3; + let h5: u32 = f3; + let t1_5: u32 = ((((g4 + bsig1(e5)) + ch(e5, e4, f4)) + 0x59F111F1) + w5); + let t2_5: u32 = (bsig0(a5) + maj(a5, a4, b4)); + let a6: u32 = (t1_5 + t2_5); + let b6: u32 = a5; + let c6: u32 = a4; + let d6: u32 = b4; + let e6: u32 = (c4 + t1_5); + let f6: u32 = e5; + let g6: u32 = e4; + let h6: u32 = f4; + let t1_6: u32 = ((((g5 + bsig1(e6)) + ch(e6, e5, f5)) + 0x923F82A4) + w6); + let t2_6: u32 = (bsig0(a6) + maj(a6, a5, b5)); + let a7: u32 = (t1_6 + t2_6); + let b7: u32 = a6; + let c7: u32 = a5; + let d7: u32 = b5; + let e7: u32 = (c5 + t1_6); + let f7: u32 = e6; + let g7: u32 = e5; + let h7: u32 = f5; + let t1_7: u32 = ((((g6 + bsig1(e7)) + ch(e7, e6, f6)) + 0xAB1C5ED5) + w7); + let t2_7: u32 = (bsig0(a7) + maj(a7, a6, b6)); + let a8: u32 = (t1_7 + t2_7); + let b8: u32 = a7; + let c8: u32 = a6; + let d8: u32 = b6; + let e8: u32 = (c6 + t1_7); + let f8: u32 = e7; + let g8: u32 = e6; + let h8: u32 = f6; + let t1_8: u32 = ((((g7 + bsig1(e8)) + ch(e8, e7, f7)) + 0xD807AA98) + w8); + let t2_8: u32 = (bsig0(a8) + maj(a8, a7, b7)); + let a9: u32 = (t1_8 + t2_8); + let b9: u32 = a8; + let c9: u32 = a7; + let d9: u32 = b7; + let e9: u32 = (c7 + t1_8); + let f9: u32 = e8; + let g9: u32 = e7; + let h9: u32 = f7; + let t1_9: u32 = ((((g8 + bsig1(e9)) + ch(e9, e8, f8)) + 0x12835B01) + w9); + let t2_9: u32 = (bsig0(a9) + maj(a9, a8, b8)); + let a10: u32 = (t1_9 + t2_9); + let b10: u32 = a9; + let c10: u32 = a8; + let d10: u32 = b8; + let e10: u32 = (c8 + t1_9); + let f10: u32 = e9; + let g10: u32 = e8; + let h10: u32 = f8; + let t1_10: u32 = ((((g9 + bsig1(e10)) + ch(e10, e9, f9)) + 0x243185BE) + w10); + let t2_10: u32 = (bsig0(a10) + maj(a10, a9, b9)); + let a11: u32 = (t1_10 + t2_10); + let b11: u32 = a10; + let c11: u32 = a9; + let d11: u32 = b9; + let e11: u32 = (c9 + t1_10); + let f11: u32 = e10; + let g11: u32 = e9; + let h11: u32 = f9; + let t1_11: u32 = ((((g10 + bsig1(e11)) + ch(e11, e10, f10)) + 0x550C7DC3) + w11); + let t2_11: u32 = (bsig0(a11) + maj(a11, a10, b10)); + let a12: u32 = (t1_11 + t2_11); + let b12: u32 = a11; + let c12: u32 = a10; + let d12: u32 = b10; + let e12: u32 = (c10 + t1_11); + let f12: u32 = e11; + let g12: u32 = e10; + let h12: u32 = f10; + let t1_12: u32 = ((((g11 + bsig1(e12)) + ch(e12, e11, f11)) + 0x72BE5D74) + w12); + let t2_12: u32 = (bsig0(a12) + maj(a12, a11, b11)); + let a13: u32 = (t1_12 + t2_12); + let b13: u32 = a12; + let c13: u32 = a11; + let d13: u32 = b11; + let e13: u32 = (c11 + t1_12); + let f13: u32 = e12; + let g13: u32 = e11; + let h13: u32 = f11; + let t1_13: u32 = ((((g12 + bsig1(e13)) + ch(e13, e12, f12)) + 0x80DEB1FE) + w13); + let t2_13: u32 = (bsig0(a13) + maj(a13, a12, b12)); + let a14: u32 = (t1_13 + t2_13); + let b14: u32 = a13; + let c14: u32 = a12; + let d14: u32 = b12; + let e14: u32 = (c12 + t1_13); + let f14: u32 = e13; + let g14: u32 = e12; + let h14: u32 = f12; + let t1_14: u32 = ((((g13 + bsig1(e14)) + ch(e14, e13, f13)) + 0x9BDC06A7) + w14); + let t2_14: u32 = (bsig0(a14) + maj(a14, a13, b13)); + let a15: u32 = (t1_14 + t2_14); + let b15: u32 = a14; + let c15: u32 = a13; + let d15: u32 = b13; + let e15: u32 = (c13 + t1_14); + let f15: u32 = e14; + let g15: u32 = e13; + let h15: u32 = f13; + let t1_15: u32 = ((((g14 + bsig1(e15)) + ch(e15, e14, f14)) + 0xC19BF174) + w15); + let t2_15: u32 = (bsig0(a15) + maj(a15, a14, b14)); + let a16: u32 = (t1_15 + t2_15); + let b16: u32 = a15; + let c16: u32 = a14; + let d16: u32 = b14; + let e16: u32 = (c14 + t1_15); + let f16: u32 = e15; + let g16: u32 = e14; + let h16: u32 = f14; + let t1_16: u32 = ((((g15 + bsig1(e16)) + ch(e16, e15, f15)) + 0xE49B69C1) + w16); + let t2_16: u32 = (bsig0(a16) + maj(a16, a15, b15)); + let a17: u32 = (t1_16 + t2_16); + let b17: u32 = a16; + let c17: u32 = a15; + let d17: u32 = b15; + let e17: u32 = (c15 + t1_16); + let f17: u32 = e16; + let g17: u32 = e15; + let h17: u32 = f15; + let t1_17: u32 = ((((g16 + bsig1(e17)) + ch(e17, e16, f16)) + 0xEFBE4786) + w17); + let t2_17: u32 = (bsig0(a17) + maj(a17, a16, b16)); + let a18: u32 = (t1_17 + t2_17); + let b18: u32 = a17; + let c18: u32 = a16; + let d18: u32 = b16; + let e18: u32 = (c16 + t1_17); + let f18: u32 = e17; + let g18: u32 = e16; + let h18: u32 = f16; + let t1_18: u32 = ((((g17 + bsig1(e18)) + ch(e18, e17, f17)) + 0x0FC19DC6) + w18); + let t2_18: u32 = (bsig0(a18) + maj(a18, a17, b17)); + let a19: u32 = (t1_18 + t2_18); + let b19: u32 = a18; + let c19: u32 = a17; + let d19: u32 = b17; + let e19: u32 = (c17 + t1_18); + let f19: u32 = e18; + let g19: u32 = e17; + let h19: u32 = f17; + let t1_19: u32 = ((((g18 + bsig1(e19)) + ch(e19, e18, f18)) + 0x240CA1CC) + w19); + let t2_19: u32 = (bsig0(a19) + maj(a19, a18, b18)); + let a20: u32 = (t1_19 + t2_19); + let b20: u32 = a19; + let c20: u32 = a18; + let d20: u32 = b18; + let e20: u32 = (c18 + t1_19); + let f20: u32 = e19; + let g20: u32 = e18; + let h20: u32 = f18; + let t1_20: u32 = ((((g19 + bsig1(e20)) + ch(e20, e19, f19)) + 0x2DE92C6F) + w20); + let t2_20: u32 = (bsig0(a20) + maj(a20, a19, b19)); + let a21: u32 = (t1_20 + t2_20); + let b21: u32 = a20; + let c21: u32 = a19; + let d21: u32 = b19; + let e21: u32 = (c19 + t1_20); + let f21: u32 = e20; + let g21: u32 = e19; + let h21: u32 = f19; + let t1_21: u32 = ((((g20 + bsig1(e21)) + ch(e21, e20, f20)) + 0x4A7484AA) + w21); + let t2_21: u32 = (bsig0(a21) + maj(a21, a20, b20)); + let a22: u32 = (t1_21 + t2_21); + let b22: u32 = a21; + let c22: u32 = a20; + let d22: u32 = b20; + let e22: u32 = (c20 + t1_21); + let f22: u32 = e21; + let g22: u32 = e20; + let h22: u32 = f20; + let t1_22: u32 = ((((g21 + bsig1(e22)) + ch(e22, e21, f21)) + 0x5CB0A9DC) + w22); + let t2_22: u32 = (bsig0(a22) + maj(a22, a21, b21)); + let a23: u32 = (t1_22 + t2_22); + let b23: u32 = a22; + let c23: u32 = a21; + let d23: u32 = b21; + let e23: u32 = (c21 + t1_22); + let f23: u32 = e22; + let g23: u32 = e21; + let h23: u32 = f21; + let t1_23: u32 = ((((g22 + bsig1(e23)) + ch(e23, e22, f22)) + 0x76F988DA) + w23); + let t2_23: u32 = (bsig0(a23) + maj(a23, a22, b22)); + let a24: u32 = (t1_23 + t2_23); + let b24: u32 = a23; + let c24: u32 = a22; + let d24: u32 = b22; + let e24: u32 = (c22 + t1_23); + let f24: u32 = e23; + let g24: u32 = e22; + let h24: u32 = f22; + let t1_24: u32 = ((((g23 + bsig1(e24)) + ch(e24, e23, f23)) + 0x983E5152) + w24); + let t2_24: u32 = (bsig0(a24) + maj(a24, a23, b23)); + let a25: u32 = (t1_24 + t2_24); + let b25: u32 = a24; + let c25: u32 = a23; + let d25: u32 = b23; + let e25: u32 = (c23 + t1_24); + let f25: u32 = e24; + let g25: u32 = e23; + let h25: u32 = f23; + let t1_25: u32 = ((((g24 + bsig1(e25)) + ch(e25, e24, f24)) + 0xA831C66D) + w25); + let t2_25: u32 = (bsig0(a25) + maj(a25, a24, b24)); + let a26: u32 = (t1_25 + t2_25); + let b26: u32 = a25; + let c26: u32 = a24; + let d26: u32 = b24; + let e26: u32 = (c24 + t1_25); + let f26: u32 = e25; + let g26: u32 = e24; + let h26: u32 = f24; + let t1_26: u32 = ((((g25 + bsig1(e26)) + ch(e26, e25, f25)) + 0xB00327C8) + w26); + let t2_26: u32 = (bsig0(a26) + maj(a26, a25, b25)); + let a27: u32 = (t1_26 + t2_26); + let b27: u32 = a26; + let c27: u32 = a25; + let d27: u32 = b25; + let e27: u32 = (c25 + t1_26); + let f27: u32 = e26; + let g27: u32 = e25; + let h27: u32 = f25; + let t1_27: u32 = ((((g26 + bsig1(e27)) + ch(e27, e26, f26)) + 0xBF597FC7) + w27); + let t2_27: u32 = (bsig0(a27) + maj(a27, a26, b26)); + let a28: u32 = (t1_27 + t2_27); + let b28: u32 = a27; + let c28: u32 = a26; + let d28: u32 = b26; + let e28: u32 = (c26 + t1_27); + let f28: u32 = e27; + let g28: u32 = e26; + let h28: u32 = f26; + let t1_28: u32 = ((((g27 + bsig1(e28)) + ch(e28, e27, f27)) + 0xC6E00BF3) + w28); + let t2_28: u32 = (bsig0(a28) + maj(a28, a27, b27)); + let a29: u32 = (t1_28 + t2_28); + let b29: u32 = a28; + let c29: u32 = a27; + let d29: u32 = b27; + let e29: u32 = (c27 + t1_28); + let f29: u32 = e28; + let g29: u32 = e27; + let h29: u32 = f27; + let t1_29: u32 = ((((g28 + bsig1(e29)) + ch(e29, e28, f28)) + 0xD5A79147) + w29); + let t2_29: u32 = (bsig0(a29) + maj(a29, a28, b28)); + let a30: u32 = (t1_29 + t2_29); + let b30: u32 = a29; + let c30: u32 = a28; + let d30: u32 = b28; + let e30: u32 = (c28 + t1_29); + let f30: u32 = e29; + let g30: u32 = e28; + let h30: u32 = f28; + let t1_30: u32 = ((((g29 + bsig1(e30)) + ch(e30, e29, f29)) + 0x06CA6351) + w30); + let t2_30: u32 = (bsig0(a30) + maj(a30, a29, b29)); + let a31: u32 = (t1_30 + t2_30); + let b31: u32 = a30; + let c31: u32 = a29; + let d31: u32 = b29; + let e31: u32 = (c29 + t1_30); + let f31: u32 = e30; + let g31: u32 = e29; + let h31: u32 = f29; + let t1_31: u32 = ((((g30 + bsig1(e31)) + ch(e31, e30, f30)) + 0x14292967) + w31); + let t2_31: u32 = (bsig0(a31) + maj(a31, a30, b30)); + let a32: u32 = (t1_31 + t2_31); + let b32: u32 = a31; + let c32: u32 = a30; + let d32: u32 = b30; + let e32: u32 = (c30 + t1_31); + let f32: u32 = e31; + let g32: u32 = e30; + let h32: u32 = f30; + let t1_32: u32 = ((((g31 + bsig1(e32)) + ch(e32, e31, f31)) + 0x27B70A85) + w32); + let t2_32: u32 = (bsig0(a32) + maj(a32, a31, b31)); + let a33: u32 = (t1_32 + t2_32); + let b33: u32 = a32; + let c33: u32 = a31; + let d33: u32 = b31; + let e33: u32 = (c31 + t1_32); + let f33: u32 = e32; + let g33: u32 = e31; + let h33: u32 = f31; + let t1_33: u32 = ((((g32 + bsig1(e33)) + ch(e33, e32, f32)) + 0x2E1B2138) + w33); + let t2_33: u32 = (bsig0(a33) + maj(a33, a32, b32)); + let a34: u32 = (t1_33 + t2_33); + let b34: u32 = a33; + let c34: u32 = a32; + let d34: u32 = b32; + let e34: u32 = (c32 + t1_33); + let f34: u32 = e33; + let g34: u32 = e32; + let h34: u32 = f32; + let t1_34: u32 = ((((g33 + bsig1(e34)) + ch(e34, e33, f33)) + 0x4D2C6DFC) + w34); + let t2_34: u32 = (bsig0(a34) + maj(a34, a33, b33)); + let a35: u32 = (t1_34 + t2_34); + let b35: u32 = a34; + let c35: u32 = a33; + let d35: u32 = b33; + let e35: u32 = (c33 + t1_34); + let f35: u32 = e34; + let g35: u32 = e33; + let h35: u32 = f33; + let t1_35: u32 = ((((g34 + bsig1(e35)) + ch(e35, e34, f34)) + 0x53380D13) + w35); + let t2_35: u32 = (bsig0(a35) + maj(a35, a34, b34)); + let a36: u32 = (t1_35 + t2_35); + let b36: u32 = a35; + let c36: u32 = a34; + let d36: u32 = b34; + let e36: u32 = (c34 + t1_35); + let f36: u32 = e35; + let g36: u32 = e34; + let h36: u32 = f34; + let t1_36: u32 = ((((g35 + bsig1(e36)) + ch(e36, e35, f35)) + 0x650A7354) + w36); + let t2_36: u32 = (bsig0(a36) + maj(a36, a35, b35)); + let a37: u32 = (t1_36 + t2_36); + let b37: u32 = a36; + let c37: u32 = a35; + let d37: u32 = b35; + let e37: u32 = (c35 + t1_36); + let f37: u32 = e36; + let g37: u32 = e35; + let h37: u32 = f35; + let t1_37: u32 = ((((g36 + bsig1(e37)) + ch(e37, e36, f36)) + 0x766A0ABB) + w37); + let t2_37: u32 = (bsig0(a37) + maj(a37, a36, b36)); + let a38: u32 = (t1_37 + t2_37); + let b38: u32 = a37; + let c38: u32 = a36; + let d38: u32 = b36; + let e38: u32 = (c36 + t1_37); + let f38: u32 = e37; + let g38: u32 = e36; + let h38: u32 = f36; + let t1_38: u32 = ((((g37 + bsig1(e38)) + ch(e38, e37, f37)) + 0x81C2C92E) + w38); + let t2_38: u32 = (bsig0(a38) + maj(a38, a37, b37)); + let a39: u32 = (t1_38 + t2_38); + let b39: u32 = a38; + let c39: u32 = a37; + let d39: u32 = b37; + let e39: u32 = (c37 + t1_38); + let f39: u32 = e38; + let g39: u32 = e37; + let h39: u32 = f37; + let t1_39: u32 = ((((g38 + bsig1(e39)) + ch(e39, e38, f38)) + 0x92722C85) + w39); + let t2_39: u32 = (bsig0(a39) + maj(a39, a38, b38)); + let a40: u32 = (t1_39 + t2_39); + let b40: u32 = a39; + let c40: u32 = a38; + let d40: u32 = b38; + let e40: u32 = (c38 + t1_39); + let f40: u32 = e39; + let g40: u32 = e38; + let h40: u32 = f38; + let t1_40: u32 = ((((g39 + bsig1(e40)) + ch(e40, e39, f39)) + 0xA2BFE8A1) + w40); + let t2_40: u32 = (bsig0(a40) + maj(a40, a39, b39)); + let a41: u32 = (t1_40 + t2_40); + let b41: u32 = a40; + let c41: u32 = a39; + let d41: u32 = b39; + let e41: u32 = (c39 + t1_40); + let f41: u32 = e40; + let g41: u32 = e39; + let h41: u32 = f39; + let t1_41: u32 = ((((g40 + bsig1(e41)) + ch(e41, e40, f40)) + 0xA81A664B) + w41); + let t2_41: u32 = (bsig0(a41) + maj(a41, a40, b40)); + let a42: u32 = (t1_41 + t2_41); + let b42: u32 = a41; + let c42: u32 = a40; + let d42: u32 = b40; + let e42: u32 = (c40 + t1_41); + let f42: u32 = e41; + let g42: u32 = e40; + let h42: u32 = f40; + let t1_42: u32 = ((((g41 + bsig1(e42)) + ch(e42, e41, f41)) + 0xC24B8B70) + w42); + let t2_42: u32 = (bsig0(a42) + maj(a42, a41, b41)); + let a43: u32 = (t1_42 + t2_42); + let b43: u32 = a42; + let c43: u32 = a41; + let d43: u32 = b41; + let e43: u32 = (c41 + t1_42); + let f43: u32 = e42; + let g43: u32 = e41; + let h43: u32 = f41; + let t1_43: u32 = ((((g42 + bsig1(e43)) + ch(e43, e42, f42)) + 0xC76C51A3) + w43); + let t2_43: u32 = (bsig0(a43) + maj(a43, a42, b42)); + let a44: u32 = (t1_43 + t2_43); + let b44: u32 = a43; + let c44: u32 = a42; + let d44: u32 = b42; + let e44: u32 = (c42 + t1_43); + let f44: u32 = e43; + let g44: u32 = e42; + let h44: u32 = f42; + let t1_44: u32 = ((((g43 + bsig1(e44)) + ch(e44, e43, f43)) + 0xD192E819) + w44); + let t2_44: u32 = (bsig0(a44) + maj(a44, a43, b43)); + let a45: u32 = (t1_44 + t2_44); + let b45: u32 = a44; + let c45: u32 = a43; + let d45: u32 = b43; + let e45: u32 = (c43 + t1_44); + let f45: u32 = e44; + let g45: u32 = e43; + let h45: u32 = f43; + let t1_45: u32 = ((((g44 + bsig1(e45)) + ch(e45, e44, f44)) + 0xD6990624) + w45); + let t2_45: u32 = (bsig0(a45) + maj(a45, a44, b44)); + let a46: u32 = (t1_45 + t2_45); + let b46: u32 = a45; + let c46: u32 = a44; + let d46: u32 = b44; + let e46: u32 = (c44 + t1_45); + let f46: u32 = e45; + let g46: u32 = e44; + let h46: u32 = f44; + let t1_46: u32 = ((((g45 + bsig1(e46)) + ch(e46, e45, f45)) + 0xF40E3585) + w46); + let t2_46: u32 = (bsig0(a46) + maj(a46, a45, b45)); + let a47: u32 = (t1_46 + t2_46); + let b47: u32 = a46; + let c47: u32 = a45; + let d47: u32 = b45; + let e47: u32 = (c45 + t1_46); + let f47: u32 = e46; + let g47: u32 = e45; + let h47: u32 = f45; + let t1_47: u32 = ((((g46 + bsig1(e47)) + ch(e47, e46, f46)) + 0x106AA070) + w47); + let t2_47: u32 = (bsig0(a47) + maj(a47, a46, b46)); + let a48: u32 = (t1_47 + t2_47); + let b48: u32 = a47; + let c48: u32 = a46; + let d48: u32 = b46; + let e48: u32 = (c46 + t1_47); + let f48: u32 = e47; + let g48: u32 = e46; + let h48: u32 = f46; + let t1_48: u32 = ((((g47 + bsig1(e48)) + ch(e48, e47, f47)) + 0x19A4C116) + w48); + let t2_48: u32 = (bsig0(a48) + maj(a48, a47, b47)); + let a49: u32 = (t1_48 + t2_48); + let b49: u32 = a48; + let c49: u32 = a47; + let d49: u32 = b47; + let e49: u32 = (c47 + t1_48); + let f49: u32 = e48; + let g49: u32 = e47; + let h49: u32 = f47; + let t1_49: u32 = ((((g48 + bsig1(e49)) + ch(e49, e48, f48)) + 0x1E376C08) + w49); + let t2_49: u32 = (bsig0(a49) + maj(a49, a48, b48)); + let a50: u32 = (t1_49 + t2_49); + let b50: u32 = a49; + let c50: u32 = a48; + let d50: u32 = b48; + let e50: u32 = (c48 + t1_49); + let f50: u32 = e49; + let g50: u32 = e48; + let h50: u32 = f48; + let t1_50: u32 = ((((g49 + bsig1(e50)) + ch(e50, e49, f49)) + 0x2748774C) + w50); + let t2_50: u32 = (bsig0(a50) + maj(a50, a49, b49)); + let a51: u32 = (t1_50 + t2_50); + let b51: u32 = a50; + let c51: u32 = a49; + let d51: u32 = b49; + let e51: u32 = (c49 + t1_50); + let f51: u32 = e50; + let g51: u32 = e49; + let h51: u32 = f49; + let t1_51: u32 = ((((g50 + bsig1(e51)) + ch(e51, e50, f50)) + 0x34B0BCB5) + w51); + let t2_51: u32 = (bsig0(a51) + maj(a51, a50, b50)); + let a52: u32 = (t1_51 + t2_51); + let b52: u32 = a51; + let c52: u32 = a50; + let d52: u32 = b50; + let e52: u32 = (c50 + t1_51); + let f52: u32 = e51; + let g52: u32 = e50; + let h52: u32 = f50; + let t1_52: u32 = ((((g51 + bsig1(e52)) + ch(e52, e51, f51)) + 0x391C0CB3) + w52); + let t2_52: u32 = (bsig0(a52) + maj(a52, a51, b51)); + let a53: u32 = (t1_52 + t2_52); + let b53: u32 = a52; + let c53: u32 = a51; + let d53: u32 = b51; + let e53: u32 = (c51 + t1_52); + let f53: u32 = e52; + let g53: u32 = e51; + let h53: u32 = f51; + let t1_53: u32 = ((((g52 + bsig1(e53)) + ch(e53, e52, f52)) + 0x4ED8AA4A) + w53); + let t2_53: u32 = (bsig0(a53) + maj(a53, a52, b52)); + let a54: u32 = (t1_53 + t2_53); + let b54: u32 = a53; + let c54: u32 = a52; + let d54: u32 = b52; + let e54: u32 = (c52 + t1_53); + let f54: u32 = e53; + let g54: u32 = e52; + let h54: u32 = f52; + let t1_54: u32 = ((((g53 + bsig1(e54)) + ch(e54, e53, f53)) + 0x5B9CCA4F) + w54); + let t2_54: u32 = (bsig0(a54) + maj(a54, a53, b53)); + let a55: u32 = (t1_54 + t2_54); + let b55: u32 = a54; + let c55: u32 = a53; + let d55: u32 = b53; + let e55: u32 = (c53 + t1_54); + let f55: u32 = e54; + let g55: u32 = e53; + let h55: u32 = f53; + let t1_55: u32 = ((((g54 + bsig1(e55)) + ch(e55, e54, f54)) + 0x682E6FF3) + w55); + let t2_55: u32 = (bsig0(a55) + maj(a55, a54, b54)); + let a56: u32 = (t1_55 + t2_55); + let b56: u32 = a55; + let c56: u32 = a54; + let d56: u32 = b54; + let e56: u32 = (c54 + t1_55); + let f56: u32 = e55; + let g56: u32 = e54; + let h56: u32 = f54; + let t1_56: u32 = ((((g55 + bsig1(e56)) + ch(e56, e55, f55)) + 0x748F82EE) + w56); + let t2_56: u32 = (bsig0(a56) + maj(a56, a55, b55)); + let a57: u32 = (t1_56 + t2_56); + let b57: u32 = a56; + let c57: u32 = a55; + let d57: u32 = b55; + let e57: u32 = (c55 + t1_56); + let f57: u32 = e56; + let g57: u32 = e55; + let h57: u32 = f55; + let t1_57: u32 = ((((g56 + bsig1(e57)) + ch(e57, e56, f56)) + 0x78A5636F) + w57); + let t2_57: u32 = (bsig0(a57) + maj(a57, a56, b56)); + let a58: u32 = (t1_57 + t2_57); + let b58: u32 = a57; + let c58: u32 = a56; + let d58: u32 = b56; + let e58: u32 = (c56 + t1_57); + let f58: u32 = e57; + let g58: u32 = e56; + let h58: u32 = f56; + let t1_58: u32 = ((((g57 + bsig1(e58)) + ch(e58, e57, f57)) + 0x84C87814) + w58); + let t2_58: u32 = (bsig0(a58) + maj(a58, a57, b57)); + let a59: u32 = (t1_58 + t2_58); + let b59: u32 = a58; + let c59: u32 = a57; + let d59: u32 = b57; + let e59: u32 = (c57 + t1_58); + let f59: u32 = e58; + let g59: u32 = e57; + let h59: u32 = f57; + let t1_59: u32 = ((((g58 + bsig1(e59)) + ch(e59, e58, f58)) + 0x8CC70208) + w59); + let t2_59: u32 = (bsig0(a59) + maj(a59, a58, b58)); + let a60: u32 = (t1_59 + t2_59); + let b60: u32 = a59; + let c60: u32 = a58; + let d60: u32 = b58; + let e60: u32 = (c58 + t1_59); + let f60: u32 = e59; + let g60: u32 = e58; + let h60: u32 = f58; + let t1_60: u32 = ((((g59 + bsig1(e60)) + ch(e60, e59, f59)) + 0x90BEFFFA) + w60); + let t2_60: u32 = (bsig0(a60) + maj(a60, a59, b59)); + let a61: u32 = (t1_60 + t2_60); + let b61: u32 = a60; + let c61: u32 = a59; + let d61: u32 = b59; + let e61: u32 = (c59 + t1_60); + let f61: u32 = e60; + let g61: u32 = e59; + let h61: u32 = f59; + let t1_61: u32 = ((((g60 + bsig1(e61)) + ch(e61, e60, f60)) + 0xA4506CEB) + w61); + let t2_61: u32 = (bsig0(a61) + maj(a61, a60, b60)); + let a62: u32 = (t1_61 + t2_61); + let b62: u32 = a61; + let c62: u32 = a60; + let d62: u32 = b60; + let e62: u32 = (c60 + t1_61); + let f62: u32 = e61; + let g62: u32 = e60; + let h62: u32 = f60; + let t1_62: u32 = ((((g61 + bsig1(e62)) + ch(e62, e61, f61)) + 0xBEF9A3F7) + w62); + let t2_62: u32 = (bsig0(a62) + maj(a62, a61, b61)); + let a63: u32 = (t1_62 + t2_62); + let b63: u32 = a62; + let c63: u32 = a61; + let d63: u32 = b61; + let e63: u32 = (c61 + t1_62); + let f63: u32 = e62; + let g63: u32 = e61; + let h63: u32 = f61; + let t1_63: u32 = ((((g62 + bsig1(e63)) + ch(e63, e62, f62)) + 0xC67178F2) + w63); + let t2_63: u32 = (bsig0(a63) + maj(a63, a62, b62)); + let a64: u32 = (t1_63 + t2_63); + let b64: u32 = a63; + let c64: u32 = a62; + let d64: u32 = b62; + let e64: u32 = (c62 + t1_63); + let f64: u32 = e63; + let g64: u32 = e62; + let h64: u32 = f62; + let out0: u32 = (0x6A09E667 + a64); + let out1: u32 = (0xBB67AE85 + a63); + let out2: u32 = (0x3C6EF372 + b63); + let out3: u32 = (0xA54FF53A + c63); + let out4: u32 = (0x510E527F + e64); + let out5: u32 = (0x9B05688C + e63); + let out6: u32 = (0x1F83D9AB + f63); + let out7: u32 = (0x5BE0CD19 + g63); + if (which == 0) { + return out0; + } else { + if (which == 1) { + return out1; + } else { + if (which == 2) { + return out2; + } else { + if (which == 3) { + return out3; + } else { + if (which == 4) { + return out4; + } else { + if (which == 5) { + return out5; + } else { + if (which == 6) { + return out6; + } else { + return out7; + } + } + } + } + } + } + } +} + diff --git a/gen/rust/tri_slash.rs b/gen/rust/tri_slash.rs new file mode 100644 index 00000000..a37d0f6e --- /dev/null +++ b/gen/rust/tri_slash.rs @@ -0,0 +1,34 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const MIN_BOND: u32 = 100; + +pub fn bond_ok(bond: u32) -> bool { + return (bond >= MIN_BOND); +} + +pub fn receipt_matches(claimed_seal: u32, recomputed_seal: u32) -> bool { + return (claimed_seal == recomputed_seal); +} + +pub fn balance_add(bal: u32, reward: u32) -> u32 { + let sum: u32 = (bal + reward); + if (sum < bal) { + return 0xFFFFFFFF; + } else { + return sum; + } +} + +pub fn settle_or_slash(balance: u32, reward: u32, bond: u32, matched: bool) -> u32 { + if matched { + return balance_add(balance, reward); + } else { + if (balance >= bond) { + return (balance - bond); + } else { + return 0; + } + } +} + diff --git a/gen/rust/trust_manager.rs b/gen/rust/trust_manager.rs index 859c040f..9874abe2 100644 --- a/gen/rust/trust_manager.rs +++ b/gen/rust/trust_manager.rs @@ -52,7 +52,7 @@ pub fn get_trust_verified(rel: u32) -> u32 { } pub fn create_trust_array(t0: u32, t1: u32, t2: u32, t3: u32, t4: u32, t5: u32, t6: u32, t7: u32) -> u64 { - return (((((((t0 as u64) << 56) | ((t1 as u64) << 48)) | ((t2 as u64) << 40)) | ((t3 as u64) << 32)) | ((t4 as u64) << 24)) || ((((t5 as u64) << 16) | ((t6 as u64) << 8)) | (t7 as u64))); + return ((((((((t0 as u64) << 56) | ((t1 as u64) << 48)) | ((t2 as u64) << 40)) | ((t3 as u64) << 32)) | ((t4 as u64) << 24)) || ((((t5 as u64) << 16) | ((t6 as u64) << 8)) | (t7 as u64)))) as u64; } pub fn get_trust_score(array: u64, index: u32) -> u32 { diff --git a/gen/rust/twr_timestamp.rs b/gen/rust/twr_timestamp.rs new file mode 100644 index 00000000..05844bdb --- /dev/null +++ b/gen/rust/twr_timestamp.rs @@ -0,0 +1,19 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub fn tick(counter: u32) -> u32 { + return (counter + 1); +} + +pub fn capture(counter: u32) -> u32 { + return counter; +} + +pub fn elapsed(t_start: u32, t_end: u32) -> u32 { + return (t_end - t_start); +} + +pub fn twr_tof(t1: u32, t2: u32, t3: u32, t4: u32) -> u32 { + return (((t4 - t1) - (t3 - t2)) >> 1); +} + diff --git a/gen/rust/video_bridge.rs b/gen/rust/video_bridge.rs new file mode 100644 index 00000000..71dfecac --- /dev/null +++ b/gen/rust/video_bridge.rs @@ -0,0 +1,239 @@ +// Generated from .t27 spec +// DO NOT EDIT — generated by t27c + +pub const VSTREAM_TYPE: u8 = 8; + +pub const FRAG_HEADER_LEN: u8 = 5; + +pub const MAX_FRAG_DATA: u8 = 70; + +pub const TYPE_OFFSET: u8 = 0; + +pub const SEQ_LOW_OFFSET: u8 = 1; + +pub const SEQ_HIGH_OFFSET: u8 = 2; + +pub const FRAG_INDEX_OFFSET: u8 = 3; + +pub const FRAG_COUNT_OFFSET: u8 = 4; + +pub const VIDEO_IN_PORT: u16 = 7000; + +pub const VIDEO_OUT_PORT: u16 = 7001; + +pub const MESH_PORT: u16 = 5000; + +pub const AUDIO_IN_PORT: u16 = 7002; + +pub const FEEDBACK_PORT: u16 = 7003; + +pub const FEEDBACK_TYPE: u8 = 10; + +pub const FEEDBACK_LEN: u8 = 6; + +pub const ADVICE_HOLD: u8 = 0; + +pub const ADVICE_BACK_OFF: u8 = 1; + +pub const ADVICE_CLIMB: u8 = 2; + +pub const FB_UTIL_OFFSET: u8 = 1; + +pub const FB_DROP_OFFSET: u8 = 2; + +pub const FB_RATE_LO_OFFSET: u8 = 3; + +pub const FB_RATE_HI_OFFSET: u8 = 4; + +pub const FB_ADVICE_OFFSET: u8 = 5; + +pub fn fb_util_pct(spent: u16, rate: u16) -> u8 { + if (rate == 0) { + return 100; + } + let scaled: u32 = spent; + let pct: u32 = ((spent * 100) / rate); + if (pct > 100) { + return 100; + } + return pct; +} + +pub fn fb_drop_pct(dropped: u16, offered: u16) -> u8 { + if (offered == 0) { + return 0; + } + let scaled: u32 = dropped; + let total: u32 = offered; + let pct: u32 = ((dropped * 100) / offered); + return pct; +} + +pub const CLIMB_BELOW_PCT: u8 = 85; + +pub const BACK_OFF_AT_PCT: u8 = 85; + +pub fn fb_should_back_off(util_pct: u8, drop_pct: u8, back_off_at: u8) -> bool { + if (drop_pct > 0) { + return true; + } + return (util_pct >= back_off_at); +} + +pub fn fb_may_climb(util_pct: u8, drop_pct: u8, climb_below: u8) -> bool { + if (drop_pct > 0) { + return false; + } + return (util_pct < climb_below); +} + +pub fn fb_advice(util_pct: u8, drop_pct: u8, climb_below: u8, back_off_at: u8) -> u8 { + if fb_should_back_off(util_pct, drop_pct, back_off_at) { + return ADVICE_BACK_OFF; + } + if fb_may_climb(util_pct, drop_pct, climb_below) { + return ADVICE_CLIMB; + } + return ADVICE_HOLD; +} + +pub const SEQ_EXPRESS_BASE: u16 = 32768; + +pub fn video_seq(counter: u16) -> u16 { + return (counter % 32768); +} + +pub fn express_seq(counter: u16) -> u16 { + return ((counter % 32768) + 32768); +} + +pub const RX_REPORT_TYPE: u8 = 11; + +pub const RX_REPORT_LEN: u8 = 3; + +pub fn fb_effective_rate(sent: u16, delivered: u16, configured: u16) -> u16 { + if (sent == 0) { + return configured; + } + let s: u32 = sent; + let d: u32 = delivered; + let threshold: u32 = ((sent * 9) / 10); + if (delivered >= threshold) { + return configured; + } + return delivered; +} + +pub fn fb_chain_report(received_here: u16, downstream_delivered: u16) -> u16 { + if (downstream_delivered < received_here) { + return downstream_delivered; + } + return received_here; +} + +pub const VSTREAM_FEC_TYPE: u8 = 9; + +pub const FEC_HEADER_LEN: u8 = 6; + +pub const FEC_GROUP: u8 = 16; + +pub const FEC_GROUP_OFFSET: u8 = 3; + +pub const FEC_COUNT_OFFSET: u8 = 4; + +pub const FEC_LAST_LEN_OFFSET: u8 = 5; + +pub fn fec_group_count(frag_count: u8) -> u8 { + if (frag_count == 0) { + return 0; + } + let full: u8 = (frag_count / 16); + let remainder: u8 = (frag_count % 16); + if (remainder > 0) { + return (full + 1); + } + return full; +} + +pub fn fec_stride(frag_count: u8) -> u8 { + return fec_group_count(frag_count); +} + +pub fn fec_group_of(frag_idx: u8, frag_count: u8) -> u8 { + let stride: u8 = fec_group_count(frag_count); + return (frag_idx % stride); +} + +pub fn fec_group_first(group_idx: u8) -> u8 { + return group_idx; +} + +pub fn fec_group_len(group_idx: u8, frag_count: u8) -> u8 { + if (group_idx >= frag_count) { + return 0; + } + let stride: u8 = fec_group_count(frag_count); + let span: u8 = ((frag_count - group_idx) - 1); + return ((span / stride) + 1); +} + +pub fn fec_can_recover(missing_in_group: u8) -> bool { + return (missing_in_group == 1); +} + +pub fn fec_packet_size() -> u8 { + return (FEC_HEADER_LEN + MAX_FRAG_DATA); +} + +pub fn frag_seq(seq_lo: u8, seq_hi: u8) -> u16 { + let lo: u16 = seq_lo; + let hi: u16 = seq_hi; + return (seq_lo + (seq_hi << 8)); +} + +pub fn seq_lo(seq: u16) -> u8 { + let low: u16 = (seq % 256); + return low; +} + +pub fn seq_hi(seq: u16) -> u8 { + let high: u16 = (seq / 256); + return high; +} + +pub fn fragment_count(nal_size: u16) -> u8 { + if (nal_size == 0) { + return 1; + } + let full_frags: u16 = (nal_size / 70); + let remainder: u16 = (nal_size % 70); + if (remainder > 0) { + return (full_frags + 1); + } + return full_frags; +} + +pub fn packet_size(data_len: u8) -> u8 { + return (FRAG_HEADER_LEN + data_len); +} + +pub fn is_last_fragment(frag_idx: u8, frag_count: u8) -> bool { + return ((frag_idx + 1) == frag_count); +} + +pub fn is_first_fragment(frag_idx: u8) -> bool { + return (frag_idx == 0); +} + +pub fn data_offset() -> u8 { + return FRAG_HEADER_LEN; +} + +pub fn max_nal_size() -> u16 { + return 17850; +} + +pub fn nal_fits(nal_size: u16) -> bool { + return (nal_size <= 17850); +} + diff --git a/specs/etx.t27 b/specs/etx.t27 index b43b4f6c..5dfcd5dc 100644 --- a/specs/etx.t27 +++ b/specs/etx.t27 @@ -42,7 +42,8 @@ module MeshEtx { if (est == 255 && sample == 255) { return 255; } - return fp_mul(alpha, sample) + fp_mul(256 - alpha, est); + // 256 does not fit in u8: the complement of alpha in Q0.8 is 255 - alpha. + return fp_mul(alpha, sample) + fp_mul(255 - alpha, est); } // Check if delivery ratio is dead diff --git a/specs/multipath_routing.t27 b/specs/multipath_routing.t27 index b9843fa6..a20862dc 100644 --- a/specs/multipath_routing.t27 +++ b/specs/multipath_routing.t27 @@ -125,7 +125,7 @@ module multipath_routing { hop1_set = hop1_set | (1 << get_multipath_hop1(get_multipath(path_array, 2))); } - if (get_path_valid(get_multipath(path_array, 3)) == path_valid == PATH_VALID) { + if (get_path_valid(get_multipath(path_array, 3)) == PATH_VALID) { hop1_set = hop1_set | (1 << get_multipath_hop1(get_multipath(path_array, 3))); } diff --git a/src/bin/tri_rti.rs b/src/bin/tri_rti.rs index 78500ee8..aacee4f2 100644 --- a/src/bin/tri_rti.rs +++ b/src/bin/tri_rti.rs @@ -6,7 +6,7 @@ // scan — read RSSI from all 3 boards via SSH (host-side orchestrator) // render — render a JSON image from stdin measurements use std::env; -use trios_mesh::rti::{LinkMeasurement, RtiNetwork, RtiTracker, KalmanTracker}; +use trios_mesh::rti::{KalmanTracker, LinkMeasurement, RtiNetwork, RtiTracker}; fn main() { let args: Vec = env::args().collect(); @@ -44,23 +44,60 @@ fn run_sim() { eprintln!("Object blocks link 1↔2 → attenuation blob on bottom edge.\n"); let mut net = RtiNetwork::new(30, 30); // Nodes at triangle corners. - net.add_node(1, 5.0, 5.0); // top-left - net.add_node(2, 25.0, 5.0); // top-right - net.add_node(3, 15.0, 25.0); // bottom-center - // Calibrate: all links clean (strong RSS). + net.add_node(1, 5.0, 5.0); // top-left + net.add_node(2, 25.0, 5.0); // top-right + net.add_node(3, 15.0, 25.0); // bottom-center + // Calibrate: all links clean (strong RSS). net.calibrate(&[ - LinkMeasurement { from: 1, to: 2, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 1, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 2, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, + LinkMeasurement { + from: 1, + to: 2, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 1, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 2, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, ]); // Object present: link 1-2 attenuated by 12 dB (object in the beam). let img = net.reconstruct(&[ - LinkMeasurement { from: 1, to: 2, rssi_dbm: -62.0, link_quality: 1.0 }, - LinkMeasurement { from: 1, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 2, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, + LinkMeasurement { + from: 1, + to: 2, + rssi_dbm: -62.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 1, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 2, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, ]); - eprintln!("Reconstructed attenuation field ({}×{}):", img.width, img.height); - eprintln!("max atten = {:.1} dB, mean = {:.1} dB", img.max_atten(), img.mean_atten()); + eprintln!( + "Reconstructed attenuation field ({}×{}):", + img.width, img.height + ); + eprintln!( + "max atten = {:.1} dB, mean = {:.1} dB", + img.max_atten(), + img.mean_atten() + ); if let Some((cx, cy)) = img.centroid() { eprintln!("brightest-blob centroid (FIX_RTI): ({:.1}, {:.1})", cx, cy); } @@ -82,10 +119,19 @@ fn run_scan() { let mut measurements = Vec::new(); for (id, ip) in &boards { let out = Command::new("sshpass") - .args(["-p", "analog", "ssh", "-o", "StrictHostKeyChecking=no", - "-o", "UserKnownHostsFile=/dev/null", "-o", "ConnectTimeout=5", - &format!("root@{}", ip), - "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null"]) + .args([ + "-p", + "analog", + "ssh", + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "ConnectTimeout=5", + &format!("root@{}", ip), + "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null", + ]) .output(); if let Ok(o) = out { let s = String::from_utf8_lossy(&o.stdout).trim().to_string(); @@ -94,12 +140,20 @@ fn run_scan() { // The driver reports RSSI in dB (e.g. 52-96 range). Map to a dBm // proxy: stronger (lower number) → less negative dBm. let dbm = -(rssi_val); - eprintln!(" node {}: RSSI readback = {} → {:.0} dBm proxy", id, rssi_val, dbm); + eprintln!( + " node {}: RSSI readback = {} → {:.0} dBm proxy", + id, rssi_val, dbm + ); // Create links from this node to the others (each board "sees" // a composite of nearby transmitters). for (other_id, _) in &boards { if other_id != id { - measurements.push(LinkMeasurement { from: *id, to: *other_id, rssi_dbm: dbm, link_quality: 1.0 }); + measurements.push(LinkMeasurement { + from: *id, + to: *other_id, + rssi_dbm: dbm, + link_quality: 1.0, + }); } } } @@ -114,8 +168,15 @@ fn run_scan() { net.add_node(2, 25.0, 5.0); net.add_node(3, 15.0, 25.0); let img = net.reconstruct_raw(&measurements, -100.0); - eprintln!("\nReconstructed attenuation field ({}×{}):", img.width, img.height); - eprintln!("max atten = {:.1}, mean = {:.1}", img.max_atten(), img.mean_atten()); + eprintln!( + "\nReconstructed attenuation field ({}×{}):", + img.width, img.height + ); + eprintln!( + "max atten = {:.1}, mean = {:.1}", + img.max_atten(), + img.mean_atten() + ); if let Some((cx, cy)) = img.centroid() { eprintln!("FIX_RTI centroid: ({:.1}, {:.1})", cx, cy); } @@ -129,24 +190,47 @@ fn run_scan() { fn run_scan_links() { use std::process::Command; eprintln!("═══ RTI Per-Link Scan (TX-scheduled) ═══"); - let boards: Vec<(u32, &str)> = vec![(1, "192.168.1.11"), (2, "192.168.1.12"), (3, "192.168.1.13")]; + let boards: Vec<(u32, &str)> = vec![ + (1, "192.168.1.11"), + (2, "192.168.1.12"), + (3, "192.168.1.13"), + ]; let ssh = |ip: &str, cmd: &str| -> String { let o = Command::new("sshpass") - .args(["-p","analog","ssh","-o","StrictHostKeyChecking=no", - "-o","UserKnownHostsFile=/dev/null","-o","ConnectTimeout=5", - &format!("root@{}", ip), cmd]) + .args([ + "-p", + "analog", + "ssh", + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "ConnectTimeout=5", + &format!("root@{}", ip), + cmd, + ]) .output(); - match o { Ok(out) => String::from_utf8_lossy(&out.stdout).trim().to_string(), Err(_) => String::new() } + match o { + Ok(out) => String::from_utf8_lossy(&out.stdout).trim().to_string(), + Err(_) => String::new(), + } }; // Step 1: baseline RSSI on all boards (TX off everywhere). eprintln!("\nCalibration: baseline RSSI (all TX off)..."); - for ip in ["192.168.1.11","192.168.1.12","192.168.1.13"] { - ssh(ip, "echo 1 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown 2>/dev/null"); + for ip in ["192.168.1.11", "192.168.1.12", "192.168.1.13"] { + ssh( + ip, + "echo 1 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown 2>/dev/null", + ); } std::thread::sleep(std::time::Duration::from_millis(500)); let mut baseline = std::collections::HashMap::new(); for (id, ip) in &boards { - let r = ssh(ip, "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null"); + let r = ssh( + ip, + "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null", + ); if let Ok(v) = r.parse::() { baseline.insert(*id, v); eprintln!(" node {}: baseline RSSI = {}", id, v); @@ -161,18 +245,34 @@ fn run_scan_links() { std::thread::sleep(std::time::Duration::from_millis(500)); eprintln!(" TX node {} → measuring receivers:", tx_id); for (rx_id, rx_ip) in &boards { - if rx_id == tx_id { continue; } - let r = ssh(rx_ip, "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null"); + if rx_id == tx_id { + continue; + } + let r = ssh( + rx_ip, + "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null", + ); if let Ok(v) = r.parse::() { let base = baseline.get(rx_id).copied().unwrap_or(100.0); let atten = (base - v).max(0.0); - eprintln!(" link {}→{}: RSSI {} (Δ{:.1} dB atten)", tx_id, rx_id, v, atten); + eprintln!( + " link {}→{}: RSSI {} (Δ{:.1} dB atten)", + tx_id, rx_id, v, atten + ); // The measured RSS is the receiver seeing the TX. Model as link. - measurements.push(LinkMeasurement { from: *tx_id, to: *rx_id, rssi_dbm: -v, link_quality: 1.0 }); + measurements.push(LinkMeasurement { + from: *tx_id, + to: *rx_id, + rssi_dbm: -v, + link_quality: 1.0, + }); } } // Power down this board's TX. - ssh(tx_ip, "echo 1 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown 2>/dev/null"); + ssh( + tx_ip, + "echo 1 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown 2>/dev/null", + ); std::thread::sleep(std::time::Duration::from_millis(300)); } if measurements.is_empty() { @@ -180,13 +280,20 @@ fn run_scan_links() { return; } // Step 3: reconstruct. - eprintln!("\nReconstructing attenuation field from {} per-link measurements...", measurements.len()); + eprintln!( + "\nReconstructing attenuation field from {} per-link measurements...", + measurements.len() + ); let mut net = RtiNetwork::new(30, 30); net.add_node(1, 5.0, 5.0); net.add_node(2, 25.0, 5.0); net.add_node(3, 15.0, 25.0); let img = net.reconstruct_raw(&measurements, -100.0); - eprintln!("max atten = {:.1}, mean = {:.1}", img.max_atten(), img.mean_atten()); + eprintln!( + "max atten = {:.1}, mean = {:.1}", + img.max_atten(), + img.mean_atten() + ); if let Some((cx, cy)) = img.centroid() { eprintln!("FIX_RTI centroid: ({:.1}, {:.1})", cx, cy); } @@ -209,29 +316,55 @@ fn run_track() { net.add_node(3, 15.0, 25.0); // Calibrate clean links. net.calibrate(&[ - LinkMeasurement { from: 1, to: 2, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 1, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 2, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, + LinkMeasurement { + from: 1, + to: 2, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 1, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 2, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, ]); let mut tracker = RtiTracker::new(30, 30, 0.4); // Simulate the object's position moving across the field (8 frames). // Path: starts near link 1-2 (bottom), moves toward node 3 (top). - let path: Vec<(f32, f32)> = (0..8).map(|i| { - let t = i as f32 / 7.0; - (5.0 + t * 10.0, 5.0 + t * 18.0) // (5,5) → (15,23) - }).collect(); + let path: Vec<(f32, f32)> = (0..8) + .map(|i| { + let t = i as f32 / 7.0; + (5.0 + t * 10.0, 5.0 + t * 18.0) // (5,5) → (15,23) + }) + .collect(); eprintln!("frame | object_pos | raw_centroid | ewma_centroid | max_atten"); eprintln!("------|------------|--------------|---------------|----------"); for (frame, (ox, oy)) in path.iter().enumerate() { // Compute which links the object attenuates and by how much. // Object at (ox,oy) attenuates each link proportional to closeness. - let links = [(1u32,2u32,5.0f32,5.0,25.0,5.0),(1,3,5.0,5.0,15.0,25.0),(2,3,25.0,5.0,15.0,25.0)]; + let links = [ + (1u32, 2u32, 5.0f32, 5.0, 25.0, 5.0), + (1, 3, 5.0, 5.0, 15.0, 25.0), + (2, 3, 25.0, 5.0, 15.0, 25.0), + ]; let mut meas = Vec::new(); for (a, b, ax, ay, bx, by) in links { // distance from object to link line let d = point_to_seg_dist(ax, ay, bx, by, *ox, *oy); let atten = (20.0 / (1.0 + d * d)).min(15.0); // dB, falls off with distance - meas.push(LinkMeasurement { from: a, to: b, rssi_dbm: -50.0 - atten, link_quality: 1.0 }); + meas.push(LinkMeasurement { + from: a, + to: b, + rssi_dbm: -50.0 - atten, + link_quality: 1.0, + }); } // Raw reconstruction (single frame, no smoothing). let img_raw = net.reconstruct(&meas); @@ -239,10 +372,21 @@ fn run_track() { // Feed through EWMA tracker. let img_ewma = tracker.update(&img_raw.pixels); let ewma_c = img_ewma.centroid(); - let raw_str = raw_c.map(|(x,y)| format!("({:.0},{:.0})", x, y)).unwrap_or_else(|| "none".into()); - let ewma_str = ewma_c.map(|(x,y)| format!("({:.0},{:.0})", x, y)).unwrap_or_else(|| "none".into()); - eprintln!(" {:>2} | ({:>4.0},{:>4.0}) | {:>12} | {:>13} | {:>5.1} dB", - frame, ox, oy, raw_str, ewma_str, img_ewma.max_atten()); + let raw_str = raw_c + .map(|(x, y)| format!("({:.0},{:.0})", x, y)) + .unwrap_or_else(|| "none".into()); + let ewma_str = ewma_c + .map(|(x, y)| format!("({:.0},{:.0})", x, y)) + .unwrap_or_else(|| "none".into()); + eprintln!( + " {:>2} | ({:>4.0},{:>4.0}) | {:>12} | {:>13} | {:>5.1} dB", + frame, + ox, + oy, + raw_str, + ewma_str, + img_ewma.max_atten() + ); } eprintln!("\nThe EWMA centroid trails the object slightly (smoothing lag) but"); eprintln!("tracks its trajectory across the field — device-free localization."); @@ -256,11 +400,13 @@ fn point_to_seg_dist(ax: f32, ay: f32, bx: f32, by: f32, px: f32, py: f32) -> f3 let dx = bx - ax; let dy = by - ay; let len2 = dx * dx + dy * dy; - if len2 < 1e-9 { return ((px-ax).powi(2) + (py-ay).powi(2)).sqrt(); } - let t = (((px-ax)*dx + (py-ay)*dy) / len2).clamp(0.0, 1.0); + if len2 < 1e-9 { + return ((px - ax).powi(2) + (py - ay).powi(2)).sqrt(); + } + let t = (((px - ax) * dx + (py - ay) * dy) / len2).clamp(0.0, 1.0); let cx = ax + t * dx; let cy = ay + t * dy; - ((px-cx).powi(2) + (py-cy).powi(2)).sqrt() + ((px - cx).powi(2) + (py - cy).powi(2)).sqrt() } /// 8-node dense network demo: shows the spatial PoC producing meaningful @@ -272,45 +418,70 @@ fn run_multi() { let mut net = RtiNetwork::new(30, 30); // 8 nodes around a perimeter (octagon). let positions: Vec<(u32, f32, f32)> = vec![ - (1, 15.0, 3.0), // top - (2, 25.0, 8.0), // top-right - (3, 27.0, 18.0), // right - (4, 25.0, 27.0), // bottom-right (note: y grows down, 27 ≈ bottom) - (5, 15.0, 27.0), // bottom - (6, 5.0, 22.0), // bottom-left - (7, 3.0, 12.0), // left - (8, 5.0, 5.0), // top-left + (1, 15.0, 3.0), // top + (2, 25.0, 8.0), // top-right + (3, 27.0, 18.0), // right + (4, 25.0, 27.0), // bottom-right (note: y grows down, 27 ≈ bottom) + (5, 15.0, 27.0), // bottom + (6, 5.0, 22.0), // bottom-left + (7, 3.0, 12.0), // left + (8, 5.0, 5.0), // top-left ]; - for (id, x, y) in &positions { net.add_node(*id, *x, *y); } - eprintln!("{} nodes, {} links", net.nodes.len(), net.nodes.len() * (net.nodes.len()-1) / 2); + for (id, x, y) in &positions { + net.add_node(*id, *x, *y); + } + eprintln!( + "{} nodes, {} links", + net.nodes.len(), + net.nodes.len() * (net.nodes.len() - 1) / 2 + ); // Calibrate: all links clean. let mut cal = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - cal.push(LinkMeasurement { from: net.nodes[i].id, to: net.nodes[j].id, rssi_dbm: -50.0, link_quality: 1.0 }); + for j in (i + 1)..net.nodes.len() { + cal.push(LinkMeasurement { + from: net.nodes[i].id, + to: net.nodes[j].id, + rssi_dbm: -50.0, + link_quality: 1.0, + }); } } net.calibrate(&cal); // Object at center (15,15) attenuates the links passing through center. - let ox = 15.0; let oy = 15.0; + let ox = 15.0; + let oy = 15.0; let mut meas = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - let a = net.nodes[i]; let b = net.nodes[j]; + for j in (i + 1)..net.nodes.len() { + let a = net.nodes[i]; + let b = net.nodes[j]; let d = point_to_seg_dist(a.x, a.y, b.x, b.y, ox, oy); let atten = (25.0 / (1.0 + d * d * 0.5)).min(20.0); - meas.push(LinkMeasurement { from: a.id, to: b.id, rssi_dbm: -50.0 - atten, link_quality: 1.0 }); + meas.push(LinkMeasurement { + from: a.id, + to: b.id, + rssi_dbm: -50.0 - atten, + link_quality: 1.0, + }); } } let img = net.reconstruct(&meas); eprintln!("\nReconstructed field (object at center 15,15):"); - eprintln!("max atten = {:.1} dB, mean = {:.1} dB", img.max_atten(), img.mean_atten()); + eprintln!( + "max atten = {:.1} dB, mean = {:.1} dB", + img.max_atten(), + img.mean_atten() + ); if let Some((cx, cy)) = img.centroid() { - eprintln!("FIX_RTI centroid: ({:.1}, {:.1}) — object localized", cx, cy); + eprintln!( + "FIX_RTI centroid: ({:.1}, {:.1}) — object localized", + cx, cy + ); } // Spatial PoC score (threshold 3 dB). let (covered, frac, mean, score, tier) = img.coverage_score(3.0); - let tier_name = ["None","Bronze","Silver","Gold","Diamond"][tier as usize]; + let tier_name = ["None", "Bronze", "Silver", "Gold", "Diamond"][tier as usize]; let mult = [0, 100, 120, 150, 200][tier as usize]; eprintln!("\nSpatial Proof-of-Coverage:"); eprintln!(" covered pixels: {}/900 ({:.1}%)", covered, frac as f32); @@ -334,14 +505,27 @@ fn run_beamform() { // Simulated 8-node network with a central obstruction. let mut net = RtiNetwork::new(30, 30); let positions: Vec<(u32, f32, f32)> = vec![ - (1, 15.0, 3.0), (2, 25.0, 8.0), (3, 27.0, 18.0), (4, 25.0, 27.0), - (5, 15.0, 27.0), (6, 5.0, 22.0), (7, 3.0, 12.0), (8, 5.0, 5.0), + (1, 15.0, 3.0), + (2, 25.0, 8.0), + (3, 27.0, 18.0), + (4, 25.0, 27.0), + (5, 15.0, 27.0), + (6, 5.0, 22.0), + (7, 3.0, 12.0), + (8, 5.0, 5.0), ]; - for (id, x, y) in &positions { net.add_node(*id, *x, *y); } + for (id, x, y) in &positions { + net.add_node(*id, *x, *y); + } let mut cal = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - cal.push(LinkMeasurement { from: net.nodes[i].id, to: net.nodes[j].id, rssi_dbm: -50.0, link_quality: 1.0 }); + for j in (i + 1)..net.nodes.len() { + cal.push(LinkMeasurement { + from: net.nodes[i].id, + to: net.nodes[j].id, + rssi_dbm: -50.0, + link_quality: 1.0, + }); } } net.calibrate(&cal); @@ -349,11 +533,17 @@ fn run_beamform() { let mut meas = Vec::new(); let mut link_attens = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - let a = net.nodes[i]; let b = net.nodes[j]; + for j in (i + 1)..net.nodes.len() { + let a = net.nodes[i]; + let b = net.nodes[j]; let d = point_to_seg_dist(a.x, a.y, b.x, b.y, 15.0, 15.0); let atten = (25.0 / (1.0 + d * d * 0.5)).min(20.0); - meas.push(LinkMeasurement { from: a.id, to: b.id, rssi_dbm: -50.0 - atten, link_quality: 1.0 }); + meas.push(LinkMeasurement { + from: a.id, + to: b.id, + rssi_dbm: -50.0 - atten, + link_quality: 1.0, + }); link_attens.push((a.id, b.id, atten)); } } @@ -361,7 +551,7 @@ fn run_beamform() { // Apply beamforming policy to each link. eprintln!("link | atten | quality | TX gain | boost | reroute"); eprintln!("------|-------|------------|---------|-------|--------"); - let qual_names = ["blocked","degraded","fair","good","excellent"]; + let qual_names = ["blocked", "degraded", "fair", "good", "excellent"]; for (a, b, atten) in &link_attens { let policy = tri_beamform::link_policy(*atten as u32, 10); let gain = policy & 0xFF; @@ -369,8 +559,16 @@ fn run_beamform() { let reroute = (policy >> 16) & 1; let qual = (policy >> 24) as usize; let qname = qual_names[qual.min(4)]; - eprintln!(" {}↔{} | {:>4.0} | {:>10} | {:>4} dB | {:>5} | {:>7}", - a, b, atten, qname, -(gain as i32), if boost==1 {"yes"} else {"no"}, if reroute==1 {"yes"} else {"no"}); + eprintln!( + " {}↔{} | {:>4.0} | {:>10} | {:>4} dB | {:>5} | {:>7}", + a, + b, + atten, + qname, + -(gain as i32), + if boost == 1 { "yes" } else { "no" }, + if reroute == 1 { "yes" } else { "no" } + ); } eprintln!("\nLinks crossing the central obstruction (high atten) get boosted TX"); eprintln!("power (lower gain dB). Clear links back off. Blocked links flagged"); @@ -384,14 +582,23 @@ fn run_count() { eprintln!("Connected-components blob detection on the attenuation field.\n"); let mut net = RtiNetwork::new(30, 30); let positions: Vec<(u32, f32, f32)> = vec![ - (1, 15.0, 3.0), (2, 27.0, 18.0), (3, 15.0, 27.0), + (1, 15.0, 3.0), + (2, 27.0, 18.0), + (3, 15.0, 27.0), (4, 3.0, 12.0), ]; - for (id, x, y) in &positions { net.add_node(*id, *x, *y); } + for (id, x, y) in &positions { + net.add_node(*id, *x, *y); + } let mut cal = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - cal.push(LinkMeasurement { from: net.nodes[i].id, to: net.nodes[j].id, rssi_dbm: -50.0, link_quality: 1.0 }); + for j in (i + 1)..net.nodes.len() { + cal.push(LinkMeasurement { + from: net.nodes[i].id, + to: net.nodes[j].id, + rssi_dbm: -50.0, + link_quality: 1.0, + }); } } net.calibrate(&cal); @@ -399,28 +606,49 @@ fn run_count() { let people = [(8.0f32, 8.0f32), (22.0f32, 22.0f32)]; let mut meas = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - let a = net.nodes[i]; let b = net.nodes[j]; + for j in (i + 1)..net.nodes.len() { + let a = net.nodes[i]; + let b = net.nodes[j]; // Attenuation from each person on this link. let mut total_atten = 0.0f32; for &(px, py) in &people { let d = point_to_seg_dist(a.x, a.y, b.x, b.y, px, py); total_atten += (20.0 / (1.0 + d * d * 0.3)).min(15.0); } - meas.push(LinkMeasurement { from: a.id, to: b.id, rssi_dbm: -50.0 - total_atten, link_quality: 1.0 }); + meas.push(LinkMeasurement { + from: a.id, + to: b.id, + rssi_dbm: -50.0 - total_atten, + link_quality: 1.0, + }); } } let img = net.reconstruct(&meas); let blobs = img.detect_blobs(5.0, 3); eprintln!("Detected {} blob(s) in the field:", blobs.len()); for (i, (cx, cy, n, atten)) in blobs.iter().enumerate() { - eprintln!(" person {}: centroid ({:.0},{:.0}), {} pixels, atten {:.0} dB", - i + 1, cx, cy, n, atten); + eprintln!( + " person {}: centroid ({:.0},{:.0}), {} pixels, atten {:.0} dB", + i + 1, + cx, + cy, + n, + atten + ); } - eprintln!("\n{} people simulated → {} blobs detected", people.len(), blobs.len()); + eprintln!( + "\n{} people simulated → {} blobs detected", + people.len(), + blobs.len() + ); // Output JSON for the ATAK forwarder (one alert per person). for (i, (cx, cy, _n, _a)) in blobs.iter().enumerate() { - println!("RTI:{},{},person_{}", *cx as f32 / 10.0, *cy as f32 / 10.0, i + 1); + println!( + "RTI:{},{},person_{}", + *cx as f32 / 10.0, + *cy as f32 / 10.0, + i + 1 + ); } } @@ -432,44 +660,74 @@ fn run_fusion() { eprintln!("Detect objects via RTI → compute camera PTZ slew commands.\n"); // Simulated 4-node network with 2 people. let mut net = RtiNetwork::new(30, 30); - for (id, x, y) in [(1u32,15.0f32,3.0f32),(2,27.0,18.0),(3,15.0,27.0),(4,3.0,12.0)] { + for (id, x, y) in [ + (1u32, 15.0f32, 3.0f32), + (2, 27.0, 18.0), + (3, 15.0, 27.0), + (4, 3.0, 12.0), + ] { net.add_node(id, x, y); } let mut cal = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - cal.push(LinkMeasurement { from: net.nodes[i].id, to: net.nodes[j].id, rssi_dbm: -50.0, link_quality: 1.0 }); + for j in (i + 1)..net.nodes.len() { + cal.push(LinkMeasurement { + from: net.nodes[i].id, + to: net.nodes[j].id, + rssi_dbm: -50.0, + link_quality: 1.0, + }); } } net.calibrate(&cal); let people = [(8.0f32, 8.0f32), (22.0f32, 22.0f32)]; let mut meas = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - let a = net.nodes[i]; let b = net.nodes[j]; + for j in (i + 1)..net.nodes.len() { + let a = net.nodes[i]; + let b = net.nodes[j]; let mut total_atten = 0.0f32; for &(px, py) in &people { let d = point_to_seg_dist(a.x, a.y, b.x, b.y, px, py); total_atten += (20.0 / (1.0 + d * d * 0.3)).min(15.0); } - meas.push(LinkMeasurement { from: a.id, to: b.id, rssi_dbm: -50.0 - total_atten, link_quality: 1.0 }); + meas.push(LinkMeasurement { + from: a.id, + to: b.id, + rssi_dbm: -50.0 - total_atten, + link_quality: 1.0, + }); } } let img = net.reconstruct(&meas); let blobs = img.detect_blobs(5.0, 3); - eprintln!("Detected {} object(s). Camera at node 1 (15,3), heading 0°.\n", blobs.len()); + eprintln!( + "Detected {} object(s). Camera at node 1 (15,3), heading 0°.\n", + blobs.len() + ); eprintln!("object | RTI pos | bearing | slew | direction | action"); eprintln!("-------|----------|---------|------|-----------|--------"); - let cam_x = 15u32; let cam_y = 3u32; let cam_heading = 0u32; + let cam_x = 15u32; + let cam_y = 3u32; + let cam_heading = 0u32; for (i, (bx, by, _, _)) in blobs.iter().enumerate() { - let cmd = tri_video_fusion::fusion_command(cam_x, cam_y, cam_heading, *bx as u32, *by as u32); + let cmd = + tri_video_fusion::fusion_command(cam_x, cam_y, cam_heading, *bx as u32, *by as u32); let slew = cmd & 0xFFF; let dir = (cmd >> 12) & 3; let should = (cmd >> 14) & 1; let dir_name = ["CCW", "CW", "none"][dir as usize]; let action = if should == 1 { "SLEW" } else { "in view" }; - eprintln!(" {:>3} | ({:>4.0},{:>4.0}) | {:>5}° | {:>3}° | {:>9} | {}", - i+1, bx, by, 0, slew, dir_name, action); + eprintln!( + " {:>3} | ({:>4.0},{:>4.0}) | {:>5}° | {:>3}° | {:>9} | {}", + i + 1, + bx, + by, + 0, + slew, + dir_name, + action + ); } eprintln!("\nFusion: RTI finds objects → camera slews to confirm visually."); } @@ -483,12 +741,26 @@ fn run_daemon() { use std::time::Duration; eprintln!("═══ RTI Continuous Monitoring Daemon ═══"); eprintln!("Scans every 10s, writes /tmp/mesh.penalty, logs to stderr.\n"); - let boards: Vec<(u32, &str)> = vec![(1, "192.168.1.11"), (2, "192.168.1.12"), (3, "192.168.1.13")]; + let boards: Vec<(u32, &str)> = vec![ + (1, "192.168.1.11"), + (2, "192.168.1.12"), + (3, "192.168.1.13"), + ]; let ssh = |ip: &str, cmd: &str| -> String { Command::new("sshpass") - .args(["-p","analog","ssh","-o","StrictHostKeyChecking=no", - "-o","UserKnownHostsFile=/dev/null","-o","ConnectTimeout=5", - &format!("root@{}", ip), cmd]) + .args([ + "-p", + "analog", + "ssh", + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "ConnectTimeout=5", + &format!("root@{}", ip), + cmd, + ]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) .unwrap_or_default() @@ -508,10 +780,20 @@ fn run_daemon() { ssh(tx_ip, "echo 0 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown; echo -5 > /sys/bus/iio/devices/iio:device0/out_voltage0_hardwaregain"); thread::sleep(Duration::from_millis(400)); for (rx_id, rx_ip) in &boards { - if rx_id == tx_id { continue; } - let r = ssh(rx_ip, "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null"); + if rx_id == tx_id { + continue; + } + let r = ssh( + rx_ip, + "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null", + ); if let Ok(v) = r.parse::() { - measurements.push(LinkMeasurement { from: *tx_id, to: *rx_id, rssi_dbm: -v, link_quality: 1.0 }); + measurements.push(LinkMeasurement { + from: *tx_id, + to: *rx_id, + rssi_dbm: -v, + link_quality: 1.0, + }); } } ssh(tx_ip, "echo 1 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown 2>/dev/null"); @@ -526,14 +808,23 @@ fn run_daemon() { let img = tracker.update(&raw.pixels); let blobs = img.detect_blobs(5.0, 3); let (covered, pct, mean, score, tier) = img.coverage_score(3.0); - eprintln!("[daemon] blobs={}, covered={}({}%), score={}, tier={}", - blobs.len(), covered, pct, score, tier); + eprintln!( + "[daemon] blobs={}, covered={}({}%), score={}, tier={}", + blobs.len(), + covered, + pct, + score, + tier + ); // Write penalties for blocked links (if any blob is strong). // In a 3-node demo we can't identify which specific link is blocked // from composite RSSI, so we just log. meshd reads /tmp/mesh.penalty. if let Some(&(bx, by, _, ba)) = blobs.first() { if ba > 50.0 { - eprintln!("[daemon] ⚠ strong blob at ({:.0},{:.0}) atten {:.0} — alert", bx, by, ba); + eprintln!( + "[daemon] ⚠ strong blob at ({:.0},{:.0}) atten {:.0} — alert", + bx, by, ba + ); // Emit ATAK-ready RTI line to stdout. println!("RTI:{},{},intruder_detected", bx / 10.0, by / 10.0); } @@ -551,21 +842,47 @@ fn run_dense() { eprintln!("8 nodes (virtual relay expansion), Kalman object tracker.\n"); // Range estimation from calibration model. let max_range = tri_rfi_calib::max_range_meters(); - eprintln!("Deployment calibration: max detection range ≈ {} m", max_range); - eprintln!("Link margin at 30m: {} dB", tri_rfi_calib::link_margin_db(30)); - eprintln!("Nodes for 900m² area: {}\n", tri_rfi_calib::nodes_for_area(900)); + eprintln!( + "Deployment calibration: max detection range ≈ {} m", + max_range + ); + eprintln!( + "Link margin at 30m: {} dB", + tri_rfi_calib::link_margin_db(30) + ); + eprintln!( + "Nodes for 900m² area: {}\n", + tri_rfi_calib::nodes_for_area(900) + ); // 8-node network. let mut net = RtiNetwork::new(30, 30); let positions: Vec<(u32, f32, f32)> = vec![ - (1, 15.0, 3.0), (2, 25.0, 8.0), (3, 27.0, 18.0), (4, 25.0, 27.0), - (5, 15.0, 27.0), (6, 5.0, 22.0), (7, 3.0, 12.0), (8, 5.0, 5.0), + (1, 15.0, 3.0), + (2, 25.0, 8.0), + (3, 27.0, 18.0), + (4, 25.0, 27.0), + (5, 15.0, 27.0), + (6, 5.0, 22.0), + (7, 3.0, 12.0), + (8, 5.0, 5.0), ]; - for (id, x, y) in &positions { net.add_node(*id, *x, *y); } - eprintln!("{} nodes, {} links", net.nodes.len(), net.nodes.len()*(net.nodes.len()-1)/2); + for (id, x, y) in &positions { + net.add_node(*id, *x, *y); + } + eprintln!( + "{} nodes, {} links", + net.nodes.len(), + net.nodes.len() * (net.nodes.len() - 1) / 2 + ); let mut cal = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - cal.push(LinkMeasurement { from: net.nodes[i].id, to: net.nodes[j].id, rssi_dbm: -50.0, link_quality: 1.0 }); + for j in (i + 1)..net.nodes.len() { + cal.push(LinkMeasurement { + from: net.nodes[i].id, + to: net.nodes[j].id, + rssi_dbm: -50.0, + link_quality: 1.0, + }); } } net.calibrate(&cal); @@ -579,20 +896,28 @@ fn run_dense() { // Build measurements: object attenuates links near it. let mut meas = Vec::new(); for i in 0..net.nodes.len() { - for j in (i+1)..net.nodes.len() { - let a = net.nodes[i]; let b = net.nodes[j]; + for j in (i + 1)..net.nodes.len() { + let a = net.nodes[i]; + let b = net.nodes[j]; let d = point_to_seg_dist(a.x, a.y, b.x, b.y, ox, oy); - let atten = (25.0 / (1.0 + d*d*0.5)).min(20.0); - meas.push(LinkMeasurement { from: a.id, to: b.id, rssi_dbm: -50.0 - atten, link_quality: 1.0 }); + let atten = (25.0 / (1.0 + d * d * 0.5)).min(20.0); + meas.push(LinkMeasurement { + from: a.id, + to: b.id, + rssi_dbm: -50.0 - atten, + link_quality: 1.0, + }); } } let img = net.reconstruct(&meas); if let Some((cx, cy)) = img.centroid() { let (kx, ky, kvx, kvy) = kf.update(cx, cy); let (_, _, _, _, tier) = img.coverage_score(3.0); - let tier_name = ["None","Bronze","Silver","Gold","Diamond"][tier as usize]; - eprintln!(" {:>2} | ({:>4.0},{:>4.0}) | ({:>4.0},{:>4.0}) | ({:>4.1},{:>4.1}) | {}", - frame, ox, oy, kx, ky, kvx, kvy, tier_name); + let tier_name = ["None", "Bronze", "Silver", "Gold", "Diamond"][tier as usize]; + eprintln!( + " {:>2} | ({:>4.0},{:>4.0}) | ({:>4.0},{:>4.0}) | ({:>4.1},{:>4.1}) | {}", + frame, ox, oy, kx, ky, kvx, kvy, tier_name + ); } } eprintln!("\n8-node dense RTI + Kalman tracking: object trajectory estimated"); @@ -608,16 +933,38 @@ fn run_record() { use std::thread; use std::time::Duration; let file = std::env::args().nth(2).unwrap_or("rti_log.csv".to_string()); - let max_ticks: u32 = std::env::args().nth(3).and_then(|s| s.parse().ok()).unwrap_or(10); + let max_ticks: u32 = std::env::args() + .nth(3) + .and_then(|s| s.parse().ok()) + .unwrap_or(10); eprintln!("═══ RTI Recording ═══"); - eprintln!("Recording {} ticks to {} (CSV: tick,from,to,rssi)", max_ticks, file); - let boards: Vec<(u32, &str)> = vec![(1, "192.168.1.11"), (2, "192.168.1.12"), (3, "192.168.1.13")]; + eprintln!( + "Recording {} ticks to {} (CSV: tick,from,to,rssi)", + max_ticks, file + ); + let boards: Vec<(u32, &str)> = vec![ + (1, "192.168.1.11"), + (2, "192.168.1.12"), + (3, "192.168.1.13"), + ]; let ssh = |ip: &str, cmd: &str| -> String { Command::new("sshpass") - .args(["-p","analog","ssh","-o","StrictHostKeyChecking=no", - "-o","UserKnownHostsFile=/dev/null","-o","ConnectTimeout=5", - &format!("root@{}", ip), cmd]) - .output().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default() + .args([ + "-p", + "analog", + "ssh", + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "ConnectTimeout=5", + &format!("root@{}", ip), + cmd, + ]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default() }; let mut out = String::from("tick,from,to,rssi_dbm\n"); for tick in 1..=max_ticks { @@ -626,8 +973,13 @@ fn run_record() { ssh(tx_ip, "echo 0 > /sys/bus/iio/devices/iio:device0/out_altvoltage1_TX_LO_powerdown; echo -5 > /sys/bus/iio/devices/iio:device0/out_voltage0_hardwaregain"); thread::sleep(Duration::from_millis(400)); for (rx_id, rx_ip) in &boards { - if rx_id == tx_id { continue; } - let r = ssh(rx_ip, "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null"); + if rx_id == tx_id { + continue; + } + let r = ssh( + rx_ip, + "cat /sys/bus/iio/devices/iio:device0/in_voltage0_rssi 2>/dev/null", + ); if let Ok(v) = r.parse::() { out.push_str(&format!("{},{},{},{}\n", tick, tx_id, rx_id, -v)); } @@ -651,23 +1003,43 @@ fn run_record() { fn run_replay() { let file = std::env::args().nth(2).unwrap_or("rti_log.csv".to_string()); eprintln!("═══ RTI Replay ═══"); - eprintln!("Replaying {} through reconstruct → Kalman → blobs → coverage", file); + eprintln!( + "Replaying {} through reconstruct → Kalman → blobs → coverage", + file + ); let data = match std::fs::read_to_string(&file) { Ok(d) => d, - Err(e) => { eprintln!("❌ read failed: {} (run 'tri-rti record' first)", e); return; } + Err(e) => { + eprintln!("❌ read failed: {} (run 'tri-rti record' first)", e); + return; + } }; // Parse CSV: tick,from,to,rssi_dbm. Group by tick. - let mut frames: std::collections::BTreeMap> = std::collections::BTreeMap::new(); - for line in data.lines().skip(1) { // skip header + let mut frames: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + for line in data.lines().skip(1) { + // skip header let parts: Vec<&str> = line.split(',').collect(); if parts.len() >= 4 { - if let (Ok(tick), Ok(from), Ok(to), Ok(rssi)) = - (parts[0].parse::(), parts[1].parse::(), parts[2].parse::(), parts[3].parse::()) { - frames.entry(tick).or_default().push(LinkMeasurement { from, to, rssi_dbm: rssi, link_quality: 1.0 }); + if let (Ok(tick), Ok(from), Ok(to), Ok(rssi)) = ( + parts[0].parse::(), + parts[1].parse::(), + parts[2].parse::(), + parts[3].parse::(), + ) { + frames.entry(tick).or_default().push(LinkMeasurement { + from, + to, + rssi_dbm: rssi, + link_quality: 1.0, + }); } } } - if frames.is_empty() { eprintln!("no data frames found"); return; } + if frames.is_empty() { + eprintln!("no data frames found"); + return; + } eprintln!("{} frames loaded\n", frames.len()); let mut net = RtiNetwork::new(30, 30); net.add_node(1, 5.0, 5.0); @@ -681,13 +1053,30 @@ fn run_replay() { let max_atten = img.max_atten(); let blobs = img.detect_blobs(5.0, 3); let (covered, _, _, score, tier) = img.coverage_score(3.0); - let tier_name = ["None","Bronze","Silver","Gold","Diamond"][tier as usize]; + let tier_name = ["None", "Bronze", "Silver", "Gold", "Diamond"][tier as usize]; if let Some((cx, cy)) = img.centroid() { let (kx, ky, _, _) = kf.update(cx, cy); - eprintln!(" {:>3} | {:>11} | {:>6.1} dB | ({:>4.0},{:>4.0}) | {:>5} | {} (s={},c={})", - tick, meas.len(), max_atten, kx, ky, blobs.len(), tier_name, score, covered); + eprintln!( + " {:>3} | {:>11} | {:>6.1} dB | ({:>4.0},{:>4.0}) | {:>5} | {} (s={},c={})", + tick, + meas.len(), + max_atten, + kx, + ky, + blobs.len(), + tier_name, + score, + covered + ); } else { - eprintln!(" {:>3} | {:>11} | {:>6.1} dB | none | {:>5} | {}", tick, meas.len(), max_atten, blobs.len(), tier_name); + eprintln!( + " {:>3} | {:>11} | {:>6.1} dB | none | {:>5} | {}", + tick, + meas.len(), + max_atten, + blobs.len(), + tier_name + ); } } eprintln!("\n✅ Replay complete — offline analysis of recorded RTI data."); @@ -706,23 +1095,23 @@ fn run_train() { let mut samples: Vec<(u32, u32, u32, u32, u32)> = Vec::new(); // (max,mean,blobs,cov,label) for i in 0..50 { // Present (person in field): varied attenuation. - let max = 8 + (i % 15); // 8-22 dB - let mean = 3 + (i % 8); // 3-10 dB + let max = 8 + (i % 15); // 8-22 dB + let mean = 3 + (i % 8); // 3-10 dB let blobs = 1 + (i % 3); // 1-3 let cov = 15 + (i % 70); // 15-84% samples.push((max, mean, blobs, cov, 1)); } for i in 0..50 { // Absent (empty field): low values. - let max = i % 5; // 0-4 dB - let mean = i % 3; // 0-2 dB + let max = i % 5; // 0-4 dB + let mean = i % 3; // 0-2 dB let blobs = 0; - let cov = i % 10; // 0-9% + let cov = i % 10; // 0-9% samples.push((max, mean, blobs, cov, 0)); } eprintln!("Dataset: {} samples (50 present, 50 absent)", samples.len()); // Train: iterate, compute error, update weights. - let mut w_max = 30u32; // initial weights (from spec) + let mut w_max = 30u32; // initial weights (from spec) let mut w_mean = 50u32; let mut w_blob = 200u32; let mut w_cov = 5u32; @@ -735,8 +1124,14 @@ fn run_train() { let mut correct = 0u32; for &(mx, mn, bl, cv, label) in &samples { let score = mx * w_max + mn * w_mean + bl * w_blob + cv * w_cov + bias; - let predicted = if score > tri_rti_ml::DECISION_THRESHOLD { 1 } else { 0 }; - if predicted == label { correct += 1; } + let predicted = if score > tri_rti_ml::DECISION_THRESHOLD { + 1 + } else { + 0 + }; + if predicted == label { + correct += 1; + } // Gradient: update weights based on prediction error. if predicted != label { let err = tri_rti_ml::prediction_error(score, label); @@ -748,12 +1143,17 @@ fn run_train() { } let acc = correct * 100 / samples.len() as u32; if epoch % 5 == 0 || epoch == epochs - 1 { - eprintln!(" {:>3} | {:>5} | {:>6} | {:>6} | {:>5} | {}%", - epoch, w_max, w_mean, w_blob, w_cov, acc); + eprintln!( + " {:>3} | {:>5} | {:>6} | {:>6} | {:>5} | {}%", + epoch, w_max, w_mean, w_blob, w_cov, acc + ); } } eprintln!("\n✅ Training complete."); - eprintln!("Learned weights: w_max={}, w_mean={}, w_blob={}, w_cov={}", w_max, w_mean, w_blob, w_cov); + eprintln!( + "Learned weights: w_max={}, w_mean={}, w_blob={}, w_cov={}", + w_max, w_mean, w_blob, w_cov + ); eprintln!("Hardcode these into specs/tri_rti_ml.t27 for deployment."); } @@ -768,20 +1168,53 @@ fn run_bench() { net.add_node(2, 25.0, 5.0); net.add_node(3, 15.0, 25.0); net.calibrate(&[ - LinkMeasurement { from: 1, to: 2, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 1, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 2, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, + LinkMeasurement { + from: 1, + to: 2, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 1, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 2, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, ]); let meas = vec![ - LinkMeasurement { from: 1, to: 2, rssi_dbm: -62.0, link_quality: 1.0 }, - LinkMeasurement { from: 1, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, - LinkMeasurement { from: 2, to: 3, rssi_dbm: -50.0, link_quality: 1.0 }, + LinkMeasurement { + from: 1, + to: 2, + rssi_dbm: -62.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 1, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, + LinkMeasurement { + from: 2, + to: 3, + rssi_dbm: -50.0, + link_quality: 1.0, + }, ]; let mut kf = KalmanTracker::new(0.5, 3.0); let n = 100; // Warm up. let img0 = net.reconstruct(&meas); - let _ = kf.update(img0.centroid().unwrap_or((0.0,0.0)).0, img0.centroid().unwrap_or((0.0,0.0)).1); + let _ = kf.update( + img0.centroid().unwrap_or((0.0, 0.0)).0, + img0.centroid().unwrap_or((0.0, 0.0)).1, + ); // Benchmark: reconstruct only. let t0 = Instant::now(); @@ -809,15 +1242,33 @@ fn run_bench() { } let lw_us = t2.elapsed().as_micros() / n as u128; - eprintln!(" reconstruct (backprojection): {} μs ({:.2} ms)", recon_us, recon_us as f64 / 1000.0); - eprintln!(" full pipeline (recon+blobs+cov+kalman): {} μs ({:.2} ms)", full_us, full_us as f64 / 1000.0); - eprintln!(" Landweber (30 iters): {} μs ({:.2} ms)", lw_us, lw_us as f64 / 1000.0); + eprintln!( + " reconstruct (backprojection): {} μs ({:.2} ms)", + recon_us, + recon_us as f64 / 1000.0 + ); + eprintln!( + " full pipeline (recon+blobs+cov+kalman): {} μs ({:.2} ms)", + full_us, + full_us as f64 / 1000.0 + ); + eprintln!( + " Landweber (30 iters): {} μs ({:.2} ms)", + lw_us, + lw_us as f64 / 1000.0 + ); eprintln!(""); let target = 100_000u128; // 100ms in μs if full_us < target { - eprintln!("✅ Full pipeline {} μs < 100ms target — real-time capable", full_us); + eprintln!( + "✅ Full pipeline {} μs < 100ms target — real-time capable", + full_us + ); } else { - eprintln!("⚠ Full pipeline {} μs > 100ms target — needs optimization", full_us); + eprintln!( + "⚠ Full pipeline {} μs > 100ms target — needs optimization", + full_us + ); } let fps = 1_000_000u128 / full_us.max(1); eprintln!(" Max frame rate: ~{} FPS", fps); @@ -833,7 +1284,12 @@ fn run_render() { let parts: Vec<&str> = line.split(',').collect(); if parts.len() >= 3 { if let (Ok(f), Ok(t), Ok(r)) = (parts[0].parse(), parts[1].parse(), parts[2].parse()) { - measurements.push(LinkMeasurement { from: f, to: t, rssi_dbm: r, link_quality: 1.0 }); + measurements.push(LinkMeasurement { + from: f, + to: t, + rssi_dbm: r, + link_quality: 1.0, + }); } } } diff --git a/src/bin/trios_meshd_video.rs b/src/bin/trios_meshd_video.rs index 303a382a..c6ef169f 100644 --- a/src/bin/trios_meshd_video.rs +++ b/src/bin/trios_meshd_video.rs @@ -104,7 +104,9 @@ fn repair_groups(state: &mut ReassemblyState) -> u32 { let stride = video_bridge::fec_stride(count) as usize; for group in 0..video_bridge::fec_group_count(count) { - let Some(par) = state.parity.get(&group) else { continue }; + let Some(par) = state.parity.get(&group) else { + continue; + }; let first = video_bridge::fec_group_first(group) as usize; // Interleaved: the group is fragments first, first+stride, first+2*stride... @@ -168,16 +170,17 @@ fn main() { // RELAY mode: this node has no device; every mesh fragment it receives is // forwarded as-is (cut-through, no reassembly) to the next hop, and its // upstream rx-report carries the CHAIN MINIMUM -- see fb_chain_report. - let next_hop: Option = - env::var("NEXT_HOP").ok().and_then(|s| s.parse().ok()); + let next_hop: Option = env::var("NEXT_HOP").ok().and_then(|s| s.parse().ok()); // The hysteresis band. Overridable ONLY so it can be swept on hardware and // become a measured number instead of the guess it started as; the decision // itself stays in the spec. let climb_below: u8 = env::var("CLIMB_BELOW") - .ok().and_then(|s| s.parse().ok()) + .ok() + .and_then(|s| s.parse().ok()) .unwrap_or(video_bridge::CLIMB_BELOW_PCT); let back_off_at: u8 = env::var("BACK_OFF_AT") - .ok().and_then(|s| s.parse().ok()) + .ok() + .and_then(|s| s.parse().ok()) .unwrap_or(video_bridge::BACK_OFF_AT_PCT); // PORTS. The device's payload and the peer's fragments MUST arrive on @@ -247,14 +250,35 @@ fn main() { s.spawn(|| { // Video pays for the reservation: the two budgets sum to frag_rate. let video_rate = frag_rate.saturating_sub(AUDIO_RATE_PER_SEC).max(1); - uplink(&app_sock, peer_mesh, &device, out_port, video_rate, fec_enabled, &load, started) + uplink( + &app_sock, + peer_mesh, + &device, + out_port, + video_rate, + fec_enabled, + &load, + started, + ) }); s.spawn(|| { let video_rate = frag_rate.saturating_sub(AUDIO_RATE_PER_SEC).max(1); - report_link(&device, video_rate, &load, &peer_rx, climb_below, back_off_at, started) + report_link( + &device, + video_rate, + &load, + &peer_rx, + climb_below, + back_off_at, + started, + ) }); s.spawn(|| express(&audio_sock, peer_mesh, started)); - s.spawn(|| downlink(&mesh_sock, &app_sock, &device, peer_mesh, next_hop, &peer_rx, started)); + s.spawn(|| { + downlink( + &mesh_sock, &app_sock, &device, peer_mesh, next_hop, &peer_rx, started, + ) + }); }); } @@ -314,7 +338,10 @@ fn uplink( let mut d = device.lock().unwrap(); if d.is_none() { let addr = SocketAddr::new(from.ip(), out_port); - println!("[video] device attached: {} -> delivering inbound to {addr}", from.ip()); + println!( + "[video] device attached: {} -> delivering inbound to {addr}", + from.ip() + ); *d = Some(addr); } } @@ -374,7 +401,11 @@ fn uplink( // the NAL. The parity is over cells padded to max_data — the same // padding a receiver's zero-initialised buffer reproduces. let last_len = size - (nfrags as usize - 1) * max_data; - let ngroups = if fec_enabled { video_bridge::fec_group_count(nfrags) } else { 0 }; + let ngroups = if fec_enabled { + video_bridge::fec_group_count(nfrags) + } else { + 0 + }; let stride = video_bridge::fec_stride(nfrags) as usize; for group in 0..ngroups { let first = video_bridge::fec_group_first(group) as usize; @@ -483,12 +514,18 @@ fn report_link( } else { lossy_streak = 0; } - let effective = if lossy_streak >= 2 { candidate } else { configured }; + let effective = if lossy_streak >= 2 { + candidate + } else { + configured + }; prev_sent = d_frags; let util = video_bridge::fb_util_pct(d_frags, effective); let drop = video_bridge::fb_drop_pct(d_dropped, d_offered); - let Some(dev) = *device.lock().unwrap() else { continue }; + let Some(dev) = *device.lock().unwrap() else { + continue; + }; let to = SocketAddr::new(dev.ip(), video_bridge::FEEDBACK_PORT); let rate16 = effective; // The node decides; the app obeys. The numbers ride along only so the @@ -507,7 +544,8 @@ fn report_link( if advice == video_bridge::ADVICE_BACK_OFF { println!( "[link] BACK OFF: util={util}% drops={drop}% rate={rate16}/s -> {} t={:.1}s", - dev.ip(), started.elapsed().as_secs_f32() + dev.ip(), + started.elapsed().as_secs_f32() ); } } @@ -528,11 +566,15 @@ fn express(audio_sock: &UdpSocket, peer_mesh: SocketAddr, started: Instant) { loop { let now = Instant::now(); if now.duration_since(window_start) >= Duration::from_secs(1) { - spent = spent.saturating_sub(AUDIO_RATE_PER_SEC).min(AUDIO_RATE_PER_SEC); + spent = spent + .saturating_sub(AUDIO_RATE_PER_SEC) + .min(AUDIO_RATE_PER_SEC); window_start = now; } - audio_sock.set_read_timeout(Some(Duration::from_secs(5))).ok(); + audio_sock + .set_read_timeout(Some(Duration::from_secs(5))) + .ok(); let (n, _) = match audio_sock.recv_from(&mut rx_buf) { Ok(v) => v, Err(_) => continue, @@ -634,15 +676,15 @@ fn downlink( last_report = now; } - mesh_sock.set_read_timeout(Some(Duration::from_secs(1))).ok(); + mesh_sock + .set_read_timeout(Some(Duration::from_secs(1))) + .ok(); let n = match mesh_sock.recv_from(&mut rx_buf) { Ok((n, _)) => n, Err(_) => continue, }; // The peer's own rx-report: how much of OUR egress survived the link. - if n >= video_bridge::RX_REPORT_LEN as usize - && rx_buf[0] == video_bridge::RX_REPORT_TYPE - { + if n >= video_bridge::RX_REPORT_LEN as usize && rx_buf[0] == video_bridge::RX_REPORT_TYPE { let cnt = video_bridge::frag_seq(rx_buf[1], rx_buf[2]) as u32; peer_rx.0.store(cnt, Ordering::Relaxed); peer_rx.1.fetch_add(1, Ordering::Relaxed); @@ -681,16 +723,18 @@ fn downlink( let data_len = n - header; let payload = &rx_buf[header..n]; - let state = reassembly.entry(frag_seq).or_insert_with(|| ReassemblyState { - expected_frags: frag_count, - received: vec![false; frag_count as usize], - data: vec![0u8; (frag_count as usize) * (video_bridge::MAX_FRAG_DATA as usize)], - last_len: None, - parity: HashMap::new(), - repaired: 0, - done: false, - last_update: Instant::now(), - }); + let state = reassembly + .entry(frag_seq) + .or_insert_with(|| ReassemblyState { + expected_frags: frag_count, + received: vec![false; frag_count as usize], + data: vec![0u8; (frag_count as usize) * (video_bridge::MAX_FRAG_DATA as usize)], + last_len: None, + parity: HashMap::new(), + repaired: 0, + done: false, + last_update: Instant::now(), + }); state.last_update = Instant::now(); if state.done { continue; // already delivered; this is a trailing parity diff --git a/tests/video_bridge_wire.rs b/tests/video_bridge_wire.rs index 87ceff6a..a41cba56 100644 --- a/tests/video_bridge_wire.rs +++ b/tests/video_bridge_wire.rs @@ -21,7 +21,11 @@ fn seq_packs_and_unpacks_over_the_whole_u16_range() { for seq in 0u16..=u16::MAX { let lo = vb::seq_lo(seq); let hi = vb::seq_hi(seq); - assert_eq!(vb::frag_seq(lo, hi), seq, "seq {seq} did not survive lo/hi split"); + assert_eq!( + vb::frag_seq(lo, hi), + seq, + "seq {seq} did not survive lo/hi split" + ); } } @@ -37,17 +41,29 @@ fn seq_edges_match_the_spec() { #[test] fn fragment_count_covers_every_nal_the_mesh_accepts() { - assert_eq!(vb::fragment_count(0), 1, "an empty NAL must still be one packet"); + assert_eq!( + vb::fragment_count(0), + 1, + "an empty NAL must still be one packet" + ); assert_eq!(vb::fragment_count(1), 1); assert_eq!(vb::fragment_count(70), 1, "exactly one full fragment"); - assert_eq!(vb::fragment_count(71), 2, "one byte over must spill into a second"); + assert_eq!( + vb::fragment_count(71), + 2, + "one byte over must spill into a second" + ); assert_eq!(vb::fragment_count(140), 2); assert_eq!(vb::fragment_count(17850), 255, "255 x 70 is the ceiling"); // The count must never disagree with a straight ceiling division, and must // never exceed the u8 frag_count field the wire header carries. for size in (0u16..=17850).step_by(7) { - let expect = if size == 0 { 1 } else { (size as u32).div_ceil(70) as u8 }; + let expect = if size == 0 { + 1 + } else { + (size as u32).div_ceil(70) as u8 + }; assert_eq!(vb::fragment_count(size), expect, "nal_size {size}"); } } @@ -59,7 +75,10 @@ fn nal_ceiling_is_exactly_what_the_header_can_address() { // undeliverable over the mesh — this is the number the encoder must respect. assert_eq!(vb::max_nal_size(), 255 * 70); assert!(vb::nal_fits(17850)); - assert!(!vb::nal_fits(17851), "one byte over the ceiling must be rejected"); + assert!( + !vb::nal_fits(17851), + "one byte over the ceiling must be rejected" + ); } // ---- packet geometry (spec: packet_size_basic/_empty, data_offset) ---- @@ -78,13 +97,21 @@ fn packet_geometry_holds() { fn first_and_last_fragment_predicates_agree_with_the_count() { assert!(vb::is_first_fragment(0)); assert!(!vb::is_first_fragment(1)); - assert!(vb::is_last_fragment(0, 1), "a single-fragment NAL is immediately last"); + assert!( + vb::is_last_fragment(0, 1), + "a single-fragment NAL is immediately last" + ); assert!(!vb::is_last_fragment(0, 2)); assert!(vb::is_last_fragment(1, 2)); // Exactly one index may be last, for every count the header can express. for count in 1u8..=255 { - let lasts = (0..count).filter(|&i| vb::is_last_fragment(i, count)).count(); - assert_eq!(lasts, 1, "frag_count {count} must have exactly one last fragment"); + let lasts = (0..count) + .filter(|&i| vb::is_last_fragment(i, count)) + .count(); + assert_eq!( + lasts, 1, + "frag_count {count} must have exactly one last fragment" + ); } } @@ -179,7 +206,12 @@ fn the_three_ports_are_distinct() { // port. If two collide, the class is ambiguous and audio silently inherits // the video pacer's head-of-line delay -- measured at p50 182ms behind a // keyframe, against 3ms on its own port. - let ports = [vb::VIDEO_IN_PORT, vb::VIDEO_OUT_PORT, vb::MESH_PORT, vb::AUDIO_IN_PORT]; + let ports = [ + vb::VIDEO_IN_PORT, + vb::VIDEO_OUT_PORT, + vb::MESH_PORT, + vb::AUDIO_IN_PORT, + ]; for (i, a) in ports.iter().enumerate() { for b in &ports[i + 1..] { assert_ne!(a, b, "ports must be distinct to demux by port"); @@ -192,11 +224,23 @@ fn the_three_ports_are_distinct() { #[test] fn fec_group_math_matches_the_spec() { assert_eq!(vb::fec_group_of(0, 129), 0); - assert_eq!(vb::fec_group_of(1, 129), 1, "interleaved: the next fragment is the next group"); - assert_eq!(vb::fec_group_of(9, 129), 0, "129 frags = 9 groups, so 9 rejoins group 0"); + assert_eq!( + vb::fec_group_of(1, 129), + 1, + "interleaved: the next fragment is the next group" + ); + assert_eq!( + vb::fec_group_of(9, 129), + 0, + "129 frags = 9 groups, so 9 rejoins group 0" + ); assert_eq!(vb::fec_group_count(0), 0, "no fragments, no parity"); assert_eq!(vb::fec_group_count(32), 2, "exactly two full groups"); - assert_eq!(vb::fec_group_count(33), 3, "the leftover needs its own parity"); + assert_eq!( + vb::fec_group_count(33), + 3, + "the leftover needs its own parity" + ); assert_eq!(vb::fec_group_count(129), 9, "a 9000B I-frame"); assert_eq!(vb::fec_packet_size(), 76, "6 header + 70 data"); } @@ -216,13 +260,23 @@ fn fec_groups_tile_every_nal_exactly_once() { assert!(len > 0, "group {g} of {count} covers nothing"); let mut seen = 0; for i in (first..count as usize).step_by(stride) { - assert_eq!(vb::fec_group_of(i as u8, count), g, "fragment {i} claims another group"); + assert_eq!( + vb::fec_group_of(i as u8, count), + g, + "fragment {i} claims another group" + ); seen += 1; } - assert_eq!(seen, len, "group {g} of {count}: fec_group_len disagrees with the stride walk"); + assert_eq!( + seen, len, + "group {g} of {count}: fec_group_len disagrees with the stride walk" + ); covered += len; } - assert_eq!(covered, count as usize, "groups must cover all {count} fragments"); + assert_eq!( + covered, count as usize, + "groups must cover all {count} fragments" + ); } } @@ -247,7 +301,8 @@ fn fec_absorbs_a_burst_as_long_as_the_stride() { let distinct = groups.len(); groups.dedup(); assert_eq!( - groups.len(), distinct, + groups.len(), + distinct, "count={count}: a {burst}-fragment burst at {start} put two losses in one group" ); } @@ -260,7 +315,9 @@ fn fec_recovers_any_single_lost_fragment() { // so one lost 70-byte packet used to destroy a whole NAL. Rebuild each // fragment in turn from its group's parity, exactly as the daemon does. let max_data = vb::MAX_FRAG_DATA as usize; - let nal: Vec = (0..9000u32).map(|i| (i.wrapping_mul(31) & 0xFF) as u8).collect(); + let nal: Vec = (0..9000u32) + .map(|i| (i.wrapping_mul(31) & 0xFF) as u8) + .collect(); let count = vb::fragment_count(nal.len() as u16); assert_eq!(count, 129, "9000B is the I-frame case"); @@ -298,7 +355,11 @@ fn fec_recovers_any_single_lost_fragment() { rebuilt[b] ^= byte; } } - assert_eq!(rebuilt, cell(lost), "fragment {lost} was not recovered from group {g}"); + assert_eq!( + rebuilt, + cell(lost), + "fragment {lost} was not recovered from group {g}" + ); } } @@ -306,7 +367,10 @@ fn fec_recovers_any_single_lost_fragment() { fn fec_cannot_recover_two_losses_and_says_so() { assert!(vb::fec_can_recover(1)); assert!(!vb::fec_can_recover(0), "nothing missing is not a repair"); - assert!(!vb::fec_can_recover(2), "one XOR cannot separate two unknowns"); + assert!( + !vb::fec_can_recover(2), + "one XOR cannot separate two unknowns" + ); assert!(!vb::fec_can_recover(16)); } @@ -331,8 +395,24 @@ fn seq_halves_are_disjoint_for_every_counter() { #[test] fn effective_rate_only_trusts_a_saturated_link() { assert_eq!(vb::fb_effective_rate(0, 0, 700), 700, "idle says nothing"); - assert_eq!(vb::fb_effective_rate(500, 495, 700), 700, "keeping up: no signal"); - assert_eq!(vb::fb_effective_rate(700, 300, 700), 300, "lossy: capacity is what arrived"); - assert_eq!(vb::fb_effective_rate(700, 630, 700), 700, "exactly 90% still keeps up"); - assert_eq!(vb::fb_effective_rate(700, 629, 700), 629, "below 90% is loss"); + assert_eq!( + vb::fb_effective_rate(500, 495, 700), + 700, + "keeping up: no signal" + ); + assert_eq!( + vb::fb_effective_rate(700, 300, 700), + 300, + "lossy: capacity is what arrived" + ); + assert_eq!( + vb::fb_effective_rate(700, 630, 700), + 700, + "exactly 90% still keeps up" + ); + assert_eq!( + vb::fb_effective_rate(700, 629, 700), + 629, + "below 90% is loss" + ); }