Improves the handling of Header::from_record

The correct vector capacity is now automatically initialized
This commit is contained in:
Misha Vicha
2025-10-01 10:33:00 +02:00
parent 136fe97fb7
commit 1c56fdb5bd

View File

@@ -11,7 +11,7 @@ use crate::SignalFormat;
struct Record { struct Record {
name: String, name: String,
seg_num: Option<u64>, seg_num: Option<u64>,
signal_count: u64, signal_count: usize,
sampling_freq: u64, sampling_freq: u64,
counter_freq: Option<u64>, counter_freq: Option<u64>,
base_counter_val: Option<u64>, base_counter_val: Option<u64>,
@@ -33,7 +33,7 @@ impl Record {
} }
let name = args[0].to_string(); let name = args[0].to_string();
let seg_num: Option<u64>; let seg_num: Option<u64>;
let sig_count: u64; let sig_count: usize;
let sampling_freq: u64; let sampling_freq: u64;
// Everything else is initialized with None, this is for sake of me not getting a stroke // Everything else is initialized with None, this is for sake of me not getting a stroke
let mut counter_freq: Option<u64> = None; let mut counter_freq: Option<u64> = None;
@@ -59,7 +59,7 @@ impl Record {
} else { } else {
seg_num = None; seg_num = None;
} }
match seg_sig[0].parse::<u64>() { match seg_sig[0].parse::<usize>() {
Ok(value) => { Ok(value) => {
sig_count = value; sig_count = value;
} }
@@ -406,10 +406,13 @@ impl Header {
Header { record: None, signal_specs: vec![] } Header { record: None, signal_specs: vec![] }
} }
/// Creates a Header from a supplied Record struct. Initializes the /// Creates a Header from a supplied Record struct.
/// signal_specs vector ///
/// Initializes the signal_specs vector with the correct capacity provided
/// by the record.
fn from_record(record: Record) -> Header { fn from_record(record: Record) -> Header {
Header { record: Some(record), signal_specs: vec![] } let capacity = record.signal_count;
Header { record: Some(record), signal_specs: Vec::with_capacity(capacity) }
} }
fn add_signal_spec(&mut self, spec: SignalSpec) { fn add_signal_spec(&mut self, spec: SignalSpec) {
@@ -432,8 +435,8 @@ pub fn parse_header(header_data: &str) -> Result<Header, &str> {
let header_lines: Vec<&str> = header_data.split("\n").collect(); let header_lines: Vec<&str> = header_data.split("\n").collect();
let mut found_record: bool = false; let mut found_record: bool = false;
let mut header: Header = Header::new(); let mut header: Header = Header::new();
let mut specs_read: u64 = 0; let mut specs_read: usize = 0;
let mut specs_max: u64 = 0; let mut specs_max: usize = 0;
for line in header_lines { for line in header_lines {
// Ignore commented lines // Ignore commented lines
if line.starts_with("#") { if line.starts_with("#") {