Skip to main content

gondola_core/
io.rs

1//! gaps-online-software i/o system
2//!
3// This file is part of gaps-online-software and published 
4// under the GPLv3 license
5
6#[cfg(feature="tof-liftof")]
7pub mod ipbus;
8pub mod parsers;
9pub mod serialization;
10pub use serialization::Serialization;
11pub mod caraspace;
12#[cfg(feature="root")]
13pub mod root_reader;
14#[cfg(feature="root")]
15pub use root_reader::read_example;
16pub mod tof_reader;
17pub use tof_reader::TofPacketReader;
18pub mod tof_writer;
19pub use tof_writer::TofPacketWriter;
20pub mod telemetry_reader;
21pub use telemetry_reader::TelemetryPacketReader;
22pub mod telemetry_writer;
23pub use telemetry_writer::TelemetryPacketWriter;
24pub mod data_source;
25pub use data_source::DataSource;
26pub mod streamers;
27pub use streamers::*;
28
29
30#[cfg(feature="pybindings")]
31use std::path::PathBuf;
32
33use flate2::Compression;
34use flate2::write::GzEncoder;
35use flate2::read::GzDecoder;
36use diffy::{
37  apply_bytes,
38  Patch,
39  create_patch
40};
41use crate::prelude::*;
42
43//----------------------------------------------------------
44
45/// Types of files
46#[derive(Debug, Clone)]
47pub enum FileType {
48  Unknown,
49  /// Calibration file for specific RB with id
50  CalibrationFile(u8),
51  /// A regular run file with TofEvents (tof only)
52  RunFile(u32),
53  /// A file created from a file with TofEvents which 
54  /// contains only TofEventSummary
55  SummaryFile(String),
56}
57
58//----------------------------------------------------------
59
60/// Sort files given as (date, time, subrun, filename). 
61///
62/// Files can have the same timestamp (it has only a resolution 
63/// of seconds), then the subrun decides. The file name makes 
64/// the order unique, even if everything else is the same
65fn sort_by_time_and_subrun(entries : &mut Vec<(u32, u32, u64, String)>) {
66  entries.sort_by(|a, b| (a.0, a.1, a.2, &a.3).cmp(&(b.0, b.1, b.2, &b.3)));
67}
68
69/// Get all filenames in the current path sorted by timestamp if available
70/// If the given path is a file and not a directory, return only that 
71/// file instead
72///
73/// # Arguments:
74///
75///    * input   : name of the target directory
76///    * pattern : the regex pattern to look for. That the sorting works,
77///                the pattern needs to return a date for the first
78///                captured argument and a time for the second captured argument
79pub fn list_path_contents_sorted(input: &str, pattern: Option<Regex>) -> Result<Vec<String>, io::Error> {
80  let path = Path::new(input);
81  match fs::metadata(path) {
82    Ok(metadata) => {
83      if metadata.is_file() {
84        let fname = String::from(input);
85        return Ok(vec![fname]);
86      } 
87      if metadata.is_dir() {
88        let re : Regex;
89        match pattern {
90          None => {
91            // use a default pattern which matches mmost cases  
92            //re = Regex::new(r"Run\d+_\d+\.(\d{6})_(\d{6})UTC(\.tof)?\.gaps$").unwrap();
93            re = Regex::new(GENERIC_ONLINE_FILE_PATTERN).unwrap();
94          }
95          Some(_re) => {
96            re = _re;
97          }
98        }
99        // the subrun is not part of the (user given) pattern, 
100        // so it is taken from the file name separately
101        let re_subrun = Regex::new(r"Run\d+_(\d+)\.").unwrap();
102        let mut entries: Vec<(u32, u32, u64, String)> = fs::read_dir(path)?
103          .filter_map(Result::ok) // Ignore unreadable entries
104          .filter_map(|entry| {
105            let basename = entry.file_name().into_string().ok()?;
106            let filename = format!("{}/{}", path.display(), basename);
107            re.captures(&filename.clone()).map(|caps| {
108              let date = caps.get(1)?.as_str().parse::<u32>().ok()?;
109              let time = caps.get(2)?.as_str().parse::<u32>().ok()?;
110              // files which don't follow the RunX_Y naming get subrun 0
111              let subrun = re_subrun.captures(&basename)
112                .and_then(|c| c.get(1)?.as_str().parse::<u64>().ok())
113                .unwrap_or(0);
114              Some((date, time, subrun, filename))
115            })?
116          })
117          .collect();
118
119        sort_by_time_and_subrun(&mut entries);
120        // Return only filenames
121        return Ok(entries.into_iter().map(|(_, _, _, name)| name).collect());
122      } 
123      Err(io::Error::new(io::ErrorKind::Other, "Path exists but is neither a file nor a directory"))
124    }
125    Err(e) => Err(e),
126  }
127}
128
129//----------------------------------------------------------
130
131/// Get all filenames in the current path sorted by timestamp if available
132/// If the given path is a file and not a directory, return only that 
133/// file instead
134///
135/// # Arguments:
136///
137///    * input   : name of the target directory
138///    * pattern : the regex pattern to look for. That the sorting works,
139///                the pattern needs to return a date for the first
140///                captured argument and a time for the second captured argument
141#[cfg(feature="pybindings")]
142#[pyfunction]
143#[pyo3(name="list_path_contents_sorted")]
144#[pyo3(signature = ( input, pattern = None ))]
145pub fn list_path_contents_sorted_py(input: &str, pattern: Option<String>) -> PyResult<Option<Vec<String>>> {
146  let mut regex_pattern : Option<Regex> = None;
147  if let Some(pat_str) = pattern {
148    match Regex::new(&pat_str) {
149      Err(err) => {
150        let msg = format!("Unable to compile regex {}! {}. Check your regex syntax! Also try a raw string.", &pat_str, err); 
151        return Err(PyValueError::new_err(msg));
152      }
153      Ok(re) => {
154        regex_pattern = Some(re);
155      }
156    }
157  }
158  match list_path_contents_sorted(input, regex_pattern) {
159    Err(err) => {  
160      error!("Unable to get files! {err}");
161      return Err(PyValueError::new_err(err.to_string()));
162    }
163    Ok(files) => {
164      return Ok(Some(files));
165    }
166  }
167}
168
169//----------------------------------------------------------
170
171/// Get a human readable timestamp for NOW
172#[cfg_attr(feature="pybindings", pyfunction)]
173pub fn get_utc_timestamp() -> String {
174  let now: DateTime<Utc> = Utc::now();
175  //let timestamp_str = now.format("%Y_%m_%d-%H_%M_%S").to_string();
176  let timestamp_str = now.format(HUMAN_TIMESTAMP_FORMAT).to_string();
177  timestamp_str
178}
179
180//----------------------------------------------------------
181
182/// Convert a unix time to human readable timestamp 
183#[cfg_attr(feature="pybindings", pyfunction)]
184pub fn get_utc_timestamp_from_unix(unix_time : f64) -> Option<String> {
185  // Separate whole seconds and fractional seconds for precision
186  let seconds = unix_time.trunc() as i64;
187  let nanoseconds = (unix_time.fract() * 1_000_000_000.0) as u32;
188
189  // Create a DateTime object in UTC
190  // Returns None if the timestamp is out of range
191  if let Some(dt) = Utc.timestamp_opt(seconds, nanoseconds).single() {
192    Some(dt.format("%y%m%d_%H%M%S").to_string())
193  } else {
194    None
195  }
196}
197
198//----------------------------------------------------------
199
200/// Retrieve the utc timestamp from any telemetry (binary) file 
201#[cfg_attr(feature="pybindings", pyfunction)]
202pub fn get_unix_timestamp_from_telemetry(fname : &str) -> Option<u64> { 
203  let tformat_re = Regex::new(GENERIC_TELEMETRY_FILE_PATTERN_CAPTURE).unwrap();
204  let res = tformat_re.captures(fname).and_then(|caps| {
205    let map : HashMap<String, String> = tformat_re.capture_names()
206      .filter_map(|name| name)
207      .filter_map(|name| { 
208        //caps.name(name).map(|m| (m.as_str().to_string(), m.as_str().to_string()))
209        caps.name(name).map(|m| (name.to_string(), m.as_str().to_string()))
210      })
211      .collect();
212    Some(map)
213  });
214  return get_unix_timestamp(&res.unwrap()["utctime"], None); 
215}
216
217//----------------------------------------------------------
218
219/// Create date string in YYMMDD format
220#[cfg_attr(feature="pybindings", pyfunction)]
221pub fn get_utc_date() -> String {
222  let now: DateTime<Utc> = Utc::now();
223  //let timestamp_str = now.format("%Y_%m_%d-%H_%M_%S").to_string();
224  let timestamp_str = now.format("%y%m%d").to_string();
225  timestamp_str
226}
227
228//----------------------------------------------------------
229
230/// A standardized name for calibration files saved by 
231/// the liftof suite
232///
233/// # Arguments
234///
235/// * rb_id   : unique identfier for the 
236///             Readoutboard (1-50)
237/// * default : if default, just add 
238///             "latest" instead of 
239///             a timestamp
240#[cfg_attr(feature="pybindings", pyfunction)]
241pub fn get_califilename(rb_id : u8, latest : bool) -> String {
242  let ts = get_utc_timestamp();
243  if latest {
244    format!("RB{rb_id:02}_latest.cali.tof.gaps")
245  } else {
246    format!("RB{rb_id:02}_{ts}.cali.tof.gaps")
247  }
248}
249
250//----------------------------------------------------------
251/// A standardized name for regular run files saved by
252/// the liftof suite
253///
254/// # Arguments
255///
256/// * run       : run id (identifier)
257/// * subrun    :  subrun id (identifier of file # within
258///                the run
259/// * rb_id     :  in case this should be used on the rb, 
260///                a rb id can be specified as well
261/// * timestamp :  substitute the current time with this timestamp
262///                (or basically any other string) instead.
263/// * tof_only  :  if true, the filename will end with the suffix 
264///                .tof.gaps, if false it will end simply with .gaps 
265#[cfg_attr(feature="pybindings", pyfunction)]
266pub fn get_runfilename(run : u32, subrun : u64, rb_id : Option<u8>, timestamp : Option<String>, tof_only : bool) -> String {
267  let ts : String;
268  match timestamp {
269    Some(_ts) => {
270      ts = _ts;
271    }
272    None => {
273      ts = get_utc_timestamp();
274    }
275  }
276  let fname : String;
277  match rb_id {
278    None => {
279      if tof_only {
280        fname = format!("Run{run}_{subrun}.{ts}.tof.gaps"); 
281      } else {
282        fname = format!("Run{run}_{subrun}.{ts}.gaps");
283      }
284    }
285    Some(rbid) => {
286      fname = format!("Run{run}_{subrun}.{ts}.RB{rbid:02}.tof.gaps");
287    }
288  }
289  fname
290}
291
292//----------------------------------------------------------
293    
294/// Get the timestamp from a .tof.gaps file
295///
296/// # Arguments:
297///   * fname : Filename of .tof.gaps file
298#[cfg_attr(feature="pybindings", pyfunction)]
299#[cfg_attr(feature="pybindings", pyo3(signature = (fname , pattern = None)))]
300pub fn get_rundata_from_file(fname : &str, pattern : Option<String>) -> Option<HashMap<String,String>> {
301  let regex_pattern : Regex;
302  if let Some(pat_str) = pattern {
303    match Regex::new(&pat_str) {
304      Err(err) => {
305        let msg = format!("Unable to compile regex {}! {}. Check your regex syntax! Also try a raw string.", &pat_str, err); 
306        //return Err(PyValueError::new_err(msg));
307        //return Err(err);
308        error!("{}",msg);
309        return None;
310      }
311      Ok(re) => {
312        regex_pattern = re;
313      }
314    }
315  } else {
316    regex_pattern = Regex::new(GENERIC_ONLINE_FILE_PATTERN_CAPTURE).unwrap();
317  }
318  let res : Option<HashMap<String,String>>;
319  res = regex_pattern.captures(fname).and_then(|caps| {
320    let map : HashMap<String, String> = regex_pattern.capture_names()
321      .filter_map(|name| name)
322      .filter_map(|name| { 
323        //caps.name(name).map(|m| (m.as_str().to_string(), m.as_str().to_string()))
324        caps.name(name).map(|m| (name.to_string(), m.as_str().to_string()))
325      })
326      .collect();
327    Some(map)
328  });
329  //ts = pattern.search(str(fname)).groupdict()['tdate']
330  //#print (ts)
331  //ts = datetime.strptime(ts, '%y%m%d_%H%M%S')
332  //ts = ts.replace(tzinfo=timezone.utc)
333  //return ts
334  res
335}
336
337//----------------------------------------------------------
338
339/// Retrieve the DateTime object from a string as used in 
340/// the names of the run files
341///
342/// # Arguments:
343///
344///   * input  : The input string the datetime shall be extracted
345///              from 
346///   * format : The format of the date string. Something like 
347///              %y%m%d_%H%M%S
348#[cfg_attr(feature="pybindings", pyfunction)]
349#[cfg_attr(feature="pybindings", pyo3(signature = (input , tformat = None )))]
350pub fn get_datetime(input : &str, tformat : Option<String>) -> Option<DateTime<Utc>> {
351  // this is the default format 
352  let mut date_time_format = String::from("%y%m%d_%H%M%S");
353  if let Some(tform) = tformat {
354    date_time_format = tform.to_string(); 
355  }
356  if let Ok(ndtime) = NaiveDateTime::parse_from_str(input, &date_time_format) {
357    //let dt_utc : DateTime<Utc> = DateTime::<Utc>::from_utc(ndtime, Utc); 
358    let dt_utc : DateTime<Utc> = DateTime::<Utc>::from_naive_utc_and_offset(ndtime, Utc); 
359    return Some(dt_utc);
360  } else { 
361    error!("Unable to parse {} for format {}! You can specify formats trhough the tformat keyword", input, date_time_format);
362    return None;
363  }
364}
365
366//--------------------------------------------------------------
367
368/// Retrieve the UNIX timestamp from a string as used in 
369/// the names of the run files
370///
371/// # Arguments:
372///
373///   * input  : The input string the datetime shall be extracted
374///              from 
375///   * format : The format of the date string. Something like 
376///              %y%m%d_%H%M%S
377#[cfg_attr(feature="pybindings", pyfunction)]
378#[cfg_attr(feature="pybindings", pyo3(signature = (input , tformat = None )))]
379pub fn get_unix_timestamp(input : &str, tformat : Option<String>) -> Option<u64> {
380  let dt = get_datetime(input, tformat);
381  if let Some(dt_) = dt {
382    // FIXME - we are only supporting times later than 
383    //         the UNIX epoch!
384    return Some(dt_.timestamp() as u64);
385  } else {
386    return None;
387  }
388}
389
390//--------------------------------------------------------------
391
392/// Identifier for different data sources
393#[derive(Debug, Copy, Clone, PartialEq,FromRepr, AsRefStr, EnumIter)]
394#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
395#[repr(u8)]
396pub enum DataSourceKind {
397  Unknown            = 0,
398  /// The "classic" written to the TOF-CPU on disk in flight
399  /// season 24/25 style
400  TofFiles           = 10,
401  /// As TofFiles, but sent over the network
402  TofStream          = 11,
403  /// The files as written on disk when received by a GSE 
404  /// system
405  TelemetryFiles     = 20,
406  /// Flight telemetry stream as sent out directly by the 
407  /// instrument
408  TelemetryStream    = 21,
409  /// Caraspace is a comprehensive, highly efficient data 
410  /// format which is used to combine Telemetry + TofStream 
411  /// data. Data written in this format as stored on disk.
412  CaraspaceFiles     = 30,
413  /// The same as above, however, represented as a network
414  /// stream
415  CaraspaceStream    = 31,
416  /// Philip's SimpleDet ROOT files
417  ROOTFiles          = 40,
418}
419
420expand_and_test_enum!(DataSourceKind, test_datasourcekind_repr);
421
422//--------------------------------------------------------------
423
424// in case we have pybindings for this type, 
425// expand it so that it can be used as keys
426// in dictionaries
427#[cfg(feature = "pybindings")]
428#[pymethods]
429impl DataSourceKind {
430
431  #[getter]
432  fn __hash__(&self) -> usize {
433    (*self as u8) as usize
434  } 
435}
436
437#[cfg(feature="pybindings")]
438pythonize_display!(DataSourceKind);
439
440//--------------------------------------------------------------
441
442/// Implement the Reader trait and necessary getters/setters to 
443/// make a struct an actual reader
444#[macro_export]
445macro_rules! reader {
446  ($struct_name:ident, $element_type:ident) => {
447 
448    use crate::io::DataReader; 
449    use crate::io::Serialization;
450
451    impl Iterator for $struct_name {
452      type Item = $element_type;
453      fn next(&mut self) -> Option<Self::Item> {
454        self.read_next()
455      }
456    }
457
458    impl DataReader<$element_type> for $struct_name {
459      fn get_header0(&self) -> u8 {
460        ($element_type::HEAD & 0x1) as u8 
461      }
462
463      fn get_header1(&self) -> u8 {
464        ($element_type::HEAD & 0x2) as u8
465      }
466
467      fn get_file_idx(&self) -> usize {
468        self.file_idx // Setting the specified field
469      }
470    
471      fn set_file_idx(&mut self, file_idx : usize) {
472        self.file_idx = file_idx;
473      }
474      
475      fn get_filenames(&self) -> &Vec<String> {
476          &self.filenames
477      }
478      
479      fn set_cursor(&mut self, pos : usize) {
480        self.cursor = pos;
481      }
482 
483      fn set_file_reader(&mut self, reader : BufReader<File>) {
484        self.file_reader = reader;
485      }
486    
487      fn read_next(&mut self) -> Option<$element_type> {
488        self.read_next_item()
489      }
490    
491      /// Get the next file ready
492      fn prime_next_file(&mut self) -> Option<usize> {
493        if self.file_idx == self.filenames.len() -1 {
494          return None;
495        } else {
496          self.file_idx += 1;
497          let nextfilename : &str = self.filenames[self.file_idx].as_str();
498          let nextfile     = OpenOptions::new().create(false).append(false).read(true).open(nextfilename).expect("Unable to open file {nextfilename}");
499          self.file_reader = BufReader::new(nextfile);
500          self.cursor      = 0;
501          return Some(self.file_idx);
502        }
503      }
504    }
505  }
506}
507
508/// Generics for packet reading (TofPacket, Telemetry packet,...)
509/// FIXME - not implemented yet
510pub trait DataReader<T> 
511  where T : Default + Serialization {
512  ///// header bytes, e.g. 0xAAAA for TofPackets, first byte
513  //const HEADER0 : u8 = 0;
514  ///// header bytes, e.g. 0xAAAA for TofPackets, second byte
515  //const HEADER1 : u8 = 0;
516
517  fn get_header0(&self) -> u8;
518  fn get_header1(&self) -> u8;
519
520  /// Return all filenames the reader is primed with   
521  fn get_filenames(&self) -> &Vec<String>;
522
523  /// The current index corresponding to the file the 
524  /// reader is currently working on
525  fn get_file_idx(&self) -> usize;
526
527  /// Set a new file idx corresponding to a file the reader 
528  /// is currently working on
529  fn set_file_idx(&mut self, idx : usize);
530
531  /// reset a new reader
532  fn set_file_reader(&mut self, freader : BufReader<File>);
533  
534  /// Get the next file ready
535  fn prime_next_file(&mut self) -> Option<usize>;
536
537  /// The name of the file the reader is currently 
538  /// working on
539  fn get_current_filename(&self) -> Option<&str> {
540    // should only happen when it is empty
541    if self.get_filenames().len() <= self.get_file_idx() {
542      return None;
543    }
544    Some(self.get_filenames()[self.get_file_idx()].as_str())
545  }
546
547  /// Manage the internal cursor attribute
548  fn set_cursor(&mut self, pos : usize);
549
550  /// Get the next frame/packet from the stream. Can be used to 
551  /// implement iterators
552  fn read_next(&mut self) -> Option<T>; 
553
554  /// Get the first entry in all of the files the reader is 
555  /// primed with
556  fn first(&mut self)     -> Option<T> {
557      match self.rewind() {
558      Err(err) => {
559        error!("Error when rewinding files! {err}");
560        return None;
561      }
562      Ok(_) => ()
563    }
564    let pack = self.read_next();
565    match self.rewind() {
566      Err(err) => {
567        error!("Error when rewinding files! {err}");
568      }
569      Ok(_) => ()
570    }
571    return pack;
572  }
573
574  /// Get the last entry in all of the files the reader is 
575  /// primed with
576  fn last(&mut self)      -> Option<T> {
577    self.set_file_idx(self.get_filenames().len() - 1);
578    let lastfilename = self.get_filenames()[self.get_file_idx()].as_str();
579    let lastfile     = OpenOptions::new().create(false).append(false).read(true).open(lastfilename).expect("Unable to open file {nextfilename}");
580    self.set_file_reader(BufReader::new(lastfile));
581    self.set_cursor(0);
582    let mut tp    = T::default();
583    let mut idx = 0;
584    loop {
585      match self.read_next() {
586        None => {
587          match self.rewind() {
588            Err(err) => {
589              error!("Error when rewinding files! {err}");
590            }
591            Ok(_) => ()
592          }
593          if idx == 0 {
594            return None;
595          } else {
596            return Some(tp);
597          }
598        }
599        Some(pack) => {
600          idx += 1;
601          tp = pack;
602          continue;
603        }
604      }
605    }
606  }
607
608  /// Rewind the current file and set the file index to the 
609  /// first file, so data can be read again from the 
610  /// beginning
611  fn rewind(&mut self) -> io::Result<()> {
612    let firstfile = &self.get_filenames()[0];
613    let file = OpenOptions::new().create(false).append(false).read(true).open(&firstfile)?;
614    self.set_file_reader(BufReader::new(file));
615    self.set_cursor(0);
616    self.set_file_idx(0);
617    Ok(())
618  }
619}
620
621/// Create a compressed bytestream out of a .toml file, so that we can pack it and 
622/// send it as a TofPacket
623pub fn compress_toml(file_path: &Path) -> Result<Vec<u8>, io::Error> {
624  let mut input_file = File::open(file_path)?;
625  let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
626  io::copy(&mut input_file, &mut encoder)?;
627  encoder.finish()
628}
629
630/// Create a compressed bytestream out of a .toml file, so that we can pack it and 
631/// send it as a TofPacket
632#[cfg(feature="pybindings")]
633#[pyfunction]
634#[pyo3(name="compress_toml")]
635pub fn compress_toml_py(file_path: String) -> Result<Vec<u8>, io::Error> {
636  let path_buff = PathBuf::from(file_path);
637  compress_toml(&path_buff)
638}
639
640/// Unpack a bytestream to a .toml file 
641pub fn decompress_toml(compressed_data: &[u8], output_path: &Path) -> Result<(), io::Error> {
642  let mut decoder = GzDecoder::new(compressed_data);
643  let mut output_file = File::create(output_path)?;
644  io::copy(&mut decoder, &mut output_file)?;
645  Ok(())
646}
647
648/// Unpack a bytestream to a .toml file 
649#[cfg(feature="pybindings")]
650#[pyfunction]
651#[pyo3(name="decompress_toml")]
652pub fn decompress_toml_py(compressed_data: &[u8], output_path: String) -> Result<(), io::Error> {
653  let path_buff = PathBuf::from(output_path);
654  decompress_toml(compressed_data, &path_buff)
655}
656
657
658/// Computes the diff between two files, compresses the diff output, and returns it.
659///
660/// # Arguments
661/// * `old_path` - Path to the original file
662/// * `new_path` - Path to the modified file
663pub fn create_compressed_diff(old_path: &Path, new_path: &Path) -> Result<Vec<u8>, io::Error> {
664  let old_text    = fs::read_to_string(old_path)?;
665  let new_text    = fs::read_to_string(new_path)?;
666  let diff        = create_patch(&old_text, &new_text);
667  let diff_bytes  = diff.to_bytes();
668  let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
669  io::copy(&mut diff_bytes.as_slice(), &mut encoder)?;
670  encoder.finish()
671}
672
673/// Computes the diff between two files, compresses the diff output, and returns it.
674///
675/// # Arguments
676/// * `old_path` - Path to the original file
677/// * `new_path` - Path to the modified file
678#[cfg(feature="pybindings")]
679#[pyfunction]
680#[pyo3(name="create_compressed_diff")]
681pub fn create_compressed_diff_py(old_path: String, new_path: String) -> Result<Vec<u8>, io::Error> {
682  let old_file = PathBuf::from(old_path);
683  let new_file = PathBuf::from(new_path);
684  create_compressed_diff(&old_file, &new_file)
685}
686
687
688/// Applies a diff (patch) from a patch file to an original file,
689/// writing the result to a new file.
690///
691/// # Arguments
692/// * `original_file_path` - Path to the original file.
693/// * `patch_file_path` - Path to the file containing the diff (patch).
694///
695/// # Returns
696/// `Result<(), io::Error>` indicating success or failure.
697pub fn apply_diff_to_file(compressed_bytes : Vec<u8>, original_file_path: &str) -> io::Result<()> {
698  let mut decoder = GzDecoder::new(&compressed_bytes[..]); 
699  let mut uncompressed_data = Vec::new();
700  match decoder.read_to_end(&mut uncompressed_data) {
701    Ok(_)  => (),
702    Err(e) => {
703      error!("Unable to decompress the received bytes!");
704      return Err(e); 
705    }
706  }
707
708  // Read the original file content
709  let mut original_file = fs::File::open(original_file_path)?;
710  let mut original_content = String::new();
711  original_file.read_to_string(&mut original_content)?;
712  match Patch::from_bytes(&uncompressed_data.as_slice()) {
713    Ok(patch) => {
714      info!("Got patch {:?}", patch);
715      match apply_bytes(&original_content.as_bytes(), &patch) {
716        Ok(modified_content) => {
717          let mut output_file = fs::File::create(original_file_path)?;
718          output_file.write_all(&modified_content.as_slice())?;
719        }
720        Err(err) => {
721          error!("Unable to apply the patch {err}");
722        }
723      }
724    }
725    Err(err) => {
726      error!("Unable to apply the patch! {err}"); 
727    }
728  } 
729  Ok(())
730}
731
732/// Applies a diff (patch) from a patch file to an original file,
733/// writing the result to a new file.
734///
735/// # Arguments
736/// * `original_file_path` - Path to the original file.
737/// * `patch_file_path` - Path to the file containing the diff (patch).
738///
739/// # Returns
740/// `Result<(), io::Error>` indicating success or failure.
741#[cfg(feature="pybindings")]
742#[pyfunction]
743#[pyo3(name="apply_diff_to_file")]
744pub fn apply_diff_to_file_py(compressed_bytes : Vec<u8>, original_file_path: &str) -> io::Result<()> {
745  apply_diff_to_file(compressed_bytes, original_file_path)
746}
747//// blanket implementation: every `T` that implements Reader also implements Iterator
748//impl<T:std::default::Default + Serialization> Iterator for DataReader<T>  { 
749//  type Item = T;
750//  fn next(&mut self) -> Option<Self::Item> {
751//    self.read_next()
752//  }
753//}
754
755
756#[test]
757fn sort_files_with_the_same_timestamp_by_subrun() {
758  // independent of the order in which the file system lists the files
759  let mut entries = vec![(231114, 221320, 10, String::from("Run42_10")),
760                         (231114, 221320,  2, String::from("Run42_2")),
761                         (231114, 221321,  0, String::from("Run42_0_later")),
762                         (231114, 221320,  1, String::from("Run42_1")),
763                         (231113, 235959,  7, String::from("Run42_7_earlier"))];
764  sort_by_time_and_subrun(&mut entries);
765  let names : Vec<&str> = entries.iter().map(|e| e.3.as_str()).collect();
766  assert_eq!(names, vec!["Run42_7_earlier", "Run42_1", "Run42_2", "Run42_10", "Run42_0_later"]);
767}
768
769#[test]
770fn list_path_contents_sorted_by_subrun() {
771  let dir = tempfile::tempdir().unwrap();
772  // the same timestamp for several subruns, and the 
773  // subruns are sorted as numbers (2 before 10)
774  let names = ["Run42_10.231114_221320.gaps",
775               "Run42_2.231114_221320.gaps",
776               "Run42_1.231114_221320.gaps",
777               "Run42_0.231114_221319.gaps",
778               "Run42_11.231114_221321.gaps",
779               "NotARunFile.txt"];
780  for n in names {
781    fs::write(dir.path().join(n), b"").unwrap();
782  }
783  let files : Vec<String> = list_path_contents_sorted(dir.path().to_str().unwrap(), None).unwrap()
784    .iter().map(|f| Path::new(f).file_name().unwrap().to_str().unwrap().to_string()).collect();
785  assert_eq!(files, vec!["Run42_0.231114_221319.gaps",
786                         "Run42_1.231114_221320.gaps",
787                         "Run42_2.231114_221320.gaps",
788                         "Run42_10.231114_221320.gaps",
789                         "Run42_11.231114_221321.gaps"]);
790}