gondola_core/io/caraspace/
file_summary.rs1use crate::prelude::*;
7
8pub const CRFILESUMMARY_NAME : &str = "file_summary";
13
14pub const CRFILESUMMARY_MAGIC : [u8;4] = *b"CRFS";
18
19#[derive(Debug, Clone, PartialEq)]
35#[cfg_attr(feature="pybindings", pyclass)]
36pub struct CRFileSummary {
37 pub version : u8,
40 pub run_id : u32,
42 pub subrun : u64,
44 pub n_frames : u32,
47 pub min_evid : u32,
50 pub max_evid : u32,
53 pub first_gcutime : f64,
56 pub last_gcutime : f64,
59 pub first_gpstime : f64,
62 pub last_gpstime : f64,
65 pub data_sources : Vec<GapsDataSource>,
68 pub missing_evid : Vec<(u32, u32)>,
71 pub footer_len : u64,
74}
75
76impl CRFileSummary {
77
78 pub const TRAILER_SIZE : usize = 4 + 8 + 2 + 2 + 2;
81
82 const FIXED_SIZE : usize = 2 + 1 + 4 + 8 + 4 + 4 + 4 + 8 + 8 + 8 + 8 + 1 + 4 + 4 + 8 + 2;
85
86 pub fn new() -> Self {
87 Self {
88 version : 0,
89 run_id : 0,
90 subrun : 0,
91 n_frames : 0,
92 min_evid : 0,
93 max_evid : 0,
94 first_gcutime : 0.0,
95 last_gcutime : 0.0,
96 first_gpstime : 0.0,
97 last_gpstime : 0.0,
98 data_sources : Vec::<GapsDataSource>::new(),
99 missing_evid : Vec::<(u32, u32)>::new(),
100 footer_len : 0,
101 }
102 }
103
104 pub fn n_missing(&self) -> u64 {
106 self.missing_evid.iter().map(|gap| gap.1 as u64).sum()
107 }
108
109 pub fn to_footer(&self) -> Vec<u8> {
112 let mut summary = self.clone();
115 summary.footer_len = 0;
116 let mut frame = CRFrame::new();
117 frame.put(summary.clone(), CRFILESUMMARY_NAME);
118 summary.footer_len = frame.to_bytestream().len() as u64;
119 let mut frame = CRFrame::new();
120 frame.put(summary, CRFILESUMMARY_NAME);
121 frame.to_bytestream()
122 }
123
124 pub fn footer_len_from_trailer(trailer : &[u8]) -> Option<u64> {
134 if trailer.len() < Self::TRAILER_SIZE {
135 return None;
136 }
137 let tr = &trailer[trailer.len() - Self::TRAILER_SIZE..];
138 if tr[0..4] != CRFILESUMMARY_MAGIC {
139 return None;
140 }
141 if tr[12..18].iter().any(|b| *b != 0x55) {
142 return None;
143 }
144 let footer_len = parse_u64(&tr[4..12].to_vec(), &mut 0);
145 if footer_len < Self::FIXED_SIZE as u64 {
146 return None;
147 }
148 Some(footer_len)
149 }
150}
151
152impl Default for CRFileSummary {
153 fn default() -> Self {
154 Self::new()
155 }
156}
157
158impl fmt::Display for CRFileSummary {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160 let mut repr = format!("<CRFileSummary (version:{}):", self.version);
161 repr += &(format!("\n Run/Subrun : {}/{}", self.run_id, self.subrun));
162 repr += &(format!("\n Frames : {}", self.n_frames));
163 if self.n_frames > 0 {
164 repr += &(format!("\n Event ids : {} - {}", self.min_evid, self.max_evid));
165 }
166 repr += &(format!("\n GCU time : {} - {}", self.first_gcutime, self.last_gcutime));
167 repr += &(format!("\n GPS time : {} - {}", self.first_gpstime, self.last_gpstime));
168 repr += &(format!("\n Missing : {} event ids in {} gaps", self.n_missing(), self.missing_evid.len()));
169 if self.data_sources.len() > 0 {
170 repr += "\n Data sources : [";
171 for k in &self.data_sources {
172 repr += &(format!(" {} ", k));
173 }
174 repr += "]";
175 }
176 repr += ">";
177 write!(f, "{}", repr)
178 }
179}
180
181impl Serialization for CRFileSummary {
184
185 fn from_bytestream(stream : &Vec<u8>,
195 pos : &mut usize)
196 -> Result<Self, SerializationError> {
197 if stream.len() < *pos + Self::FIXED_SIZE {
198 return Err(SerializationError::StreamTooShort);
199 }
200 let head = parse_u16(stream, pos);
201 if head != Self::HEAD {
202 error!("Got wrong head bytes! Found {} instead of {}", head, Self::HEAD);
203 return Err(SerializationError::HeadInvalid);
204 }
205 let mut summary = Self::new();
206 summary.version = parse_u8 (stream, pos);
207 summary.run_id = parse_u32(stream, pos);
208 summary.subrun = parse_u64(stream, pos);
209 summary.n_frames = parse_u32(stream, pos);
210 summary.min_evid = parse_u32(stream, pos);
211 summary.max_evid = parse_u32(stream, pos);
212 summary.first_gcutime = parse_f64(stream, pos);
213 summary.last_gcutime = parse_f64(stream, pos);
214 summary.first_gpstime = parse_f64(stream, pos);
215 summary.last_gpstime = parse_f64(stream, pos);
216 let n_sources = parse_u8 (stream, pos) as usize;
217 if stream.len() < *pos + n_sources + 4 + 4 + 8 + 2 {
219 return Err(SerializationError::StreamTooShort);
220 }
221 for _ in 0..n_sources {
222 summary.data_sources.push(GapsDataSource::from(parse_u8(stream, pos)));
223 }
224 let n_gaps = parse_u32(stream, pos) as usize;
225 if stream.len() < *pos + 8*n_gaps + 4 + 8 + 2 {
226 return Err(SerializationError::StreamTooShort);
227 }
228 for _ in 0..n_gaps {
229 let first = parse_u32(stream, pos);
230 let count = parse_u32(stream, pos);
231 if count == 0 {
232 error!("Found a gap of 0 missing event ids at event id {}!", first);
233 return Err(SerializationError::InvalidByte);
234 }
235 summary.missing_evid.push((first, count));
236 }
237 if stream[*pos..*pos + 4] != CRFILESUMMARY_MAGIC {
238 error!("Got wrong magic bytes {:?}, expected {:?}!", &stream[*pos..*pos + 4], CRFILESUMMARY_MAGIC);
239 return Err(SerializationError::InvalidByte);
240 }
241 *pos += 4;
242 summary.footer_len = parse_u64(stream, pos);
243 let tail = parse_u16(stream, pos);
244 if tail != Self::TAIL {
245 error!("Got wrong tail bytes! Found {} instead of {}", tail, Self::TAIL);
246 return Err(SerializationError::TailInvalid);
247 }
248 Ok(summary)
249 }
250
251 fn to_bytestream(&self) -> Vec<u8> {
253 let n_sources = self.data_sources.len().min(u8::MAX as usize);
254 let mut stream = Vec::<u8>::with_capacity(Self::FIXED_SIZE + n_sources + 8*self.missing_evid.len());
255 stream.extend_from_slice(&Self::HEAD.to_le_bytes());
256 stream.push(self.version);
257 stream.extend_from_slice(&self.run_id.to_le_bytes());
258 stream.extend_from_slice(&self.subrun.to_le_bytes());
259 stream.extend_from_slice(&self.n_frames.to_le_bytes());
260 stream.extend_from_slice(&self.min_evid.to_le_bytes());
261 stream.extend_from_slice(&self.max_evid.to_le_bytes());
262 stream.extend_from_slice(&self.first_gcutime.to_le_bytes());
263 stream.extend_from_slice(&self.last_gcutime.to_le_bytes());
264 stream.extend_from_slice(&self.first_gpstime.to_le_bytes());
265 stream.extend_from_slice(&self.last_gpstime.to_le_bytes());
266 if self.data_sources.len() > u8::MAX as usize {
267 error!("Too many data sources ({}), only the first {} will be serialized!", self.data_sources.len(), u8::MAX);
268 }
269 stream.push(n_sources as u8);
270 for k in &self.data_sources[0..n_sources] {
271 stream.push(*k as u8);
272 }
273 stream.extend_from_slice(&(self.missing_evid.len() as u32).to_le_bytes());
274 for (first, count) in &self.missing_evid {
275 stream.extend_from_slice(&first.to_le_bytes());
276 stream.extend_from_slice(&count.to_le_bytes());
277 }
278 stream.extend_from_slice(&CRFILESUMMARY_MAGIC);
279 stream.extend_from_slice(&self.footer_len.to_le_bytes());
280 stream.extend_from_slice(&Self::TAIL.to_le_bytes());
281 stream
282 }
283}
284
285impl Frameable for CRFileSummary {
286 const CRFRAMEOBJECT_TYPE : CRFrameObjectType = CRFrameObjectType::CRFileSummary;
287}
288
289#[cfg(feature="pybindings")]
292#[pymethods]
293impl CRFileSummary {
294
295 #[getter]
297 fn get_version(&self) -> u8 {
298 self.version
299 }
300
301 #[getter]
303 fn get_run_id(&self) -> u32 {
304 self.run_id
305 }
306
307 #[getter]
309 fn get_subrun(&self) -> u64 {
310 self.subrun
311 }
312
313 #[getter]
315 fn get_n_frames(&self) -> u32 {
316 self.n_frames
317 }
318
319 #[getter]
321 fn get_min_evid(&self) -> u32 {
322 self.min_evid
323 }
324
325 #[getter]
327 fn get_max_evid(&self) -> u32 {
328 self.max_evid
329 }
330
331 #[getter]
333 fn get_first_gcutime(&self) -> f64 {
334 self.first_gcutime
335 }
336
337 #[getter]
339 fn get_last_gcutime(&self) -> f64 {
340 self.last_gcutime
341 }
342
343 #[getter]
345 fn get_first_gpstime(&self) -> f64 {
346 self.first_gpstime
347 }
348
349 #[getter]
351 fn get_last_gpstime(&self) -> f64 {
352 self.last_gpstime
353 }
354
355 #[getter]
357 fn get_data_sources(&self) -> Vec<GapsDataSource> {
358 self.data_sources.clone()
359 }
360
361 #[getter]
364 fn get_missing_evid(&self) -> Vec<(u32, u32)> {
365 self.missing_evid.clone()
366 }
367
368 #[getter]
370 #[pyo3(name="n_missing")]
371 fn get_n_missing_py(&self) -> u64 {
372 self.n_missing()
373 }
374
375 #[getter]
377 fn get_footer_len(&self) -> u64 {
378 self.footer_len
379 }
380
381 #[cfg(feature="random")]
382 #[staticmethod]
383 #[pyo3(name="from_random")]
384 fn from_random_py() -> Self {
385 Self::from_random()
386 }
387}
388
389#[cfg(feature="pybindings")]
390pythonize!(CRFileSummary);
391
392#[cfg(feature="random")]
395impl FromRandom for CRFileSummary {
396
397 fn from_random() -> Self {
398 let mut s = Self::new();
399 let mut rng = rand::rng();
400 s.version = rng.random::<u8>();
401 s.run_id = rng.random::<u32>();
402 s.subrun = rng.random::<u64>();
403 s.n_frames = rng.random::<u32>();
404 s.min_evid = rng.random::<u32>();
405 s.max_evid = rng.random::<u32>();
406 s.first_gcutime = rng.random::<f64>();
407 s.last_gcutime = rng.random::<f64>();
408 s.first_gpstime = rng.random::<f64>();
409 s.last_gpstime = rng.random::<f64>();
410 for source in GapsDataSource::iter() {
411 if rng.random::<bool>() {
412 s.data_sources.push(source);
413 }
414 }
415 let n_gaps = rng.random_range(0..20);
416 for _ in 0..n_gaps {
417 s.missing_evid.push((rng.random::<u32>(), rng.random_range(1..1000)));
418 }
419 s.footer_len = rng.random::<u64>();
420 s
421 }
422}
423
424#[cfg(test)]
427mod tests {
428 use super::*;
429
430 #[test]
431 #[cfg(feature="random")]
432 fn serialize_deserialize_crfilesummary() {
433 for _ in 0..100 {
434 let s = CRFileSummary::from_random();
435 let stream = s.to_bytestream();
436 assert_eq!(stream.len(), CRFileSummary::FIXED_SIZE + s.data_sources.len() + 8*s.missing_evid.len());
437 let mut pos = 0;
438 let test = CRFileSummary::from_bytestream(&stream, &mut pos).unwrap();
439 assert_eq!(s, test);
440 assert_eq!(pos, stream.len());
441 }
442 }
443
444 #[test]
445 #[cfg(feature="random")]
446 fn pack_crfilesummary() {
447 for _ in 0..100 {
448 let s = CRFileSummary::from_random();
449 let test : CRFileSummary = s.pack().extract().unwrap();
450 assert_eq!(s, test);
451 }
452 }
453
454 #[test]
455 #[cfg(feature="random")]
456 fn crfilesummary_stream_too_short() {
457 let s = CRFileSummary::from_random();
458 let stream = s.to_bytestream();
459 for k in 0..stream.len() {
460 let short = stream[0..k].to_vec();
461 assert!(CRFileSummary::from_bytestream(&short, &mut 0).is_err());
462 }
463 }
464
465 #[test]
466 fn crfilesummary_rejects_wrong_magic_and_empty_gaps() {
467 let mut s = CRFileSummary::new();
468 s.missing_evid.push((100, 5));
469 let good = s.to_bytestream();
470 let mut stream = good.clone();
472 let magic_pos = stream.len() - 2 - 8 - 4;
473 stream[magic_pos] = b'X';
474 assert!(CRFileSummary::from_bytestream(&stream, &mut 0).is_err());
475 s.missing_evid[0].1 = 0;
477 assert!(CRFileSummary::from_bytestream(&s.to_bytestream(), &mut 0).is_err());
478 }
479
480 #[test]
481 fn crfilesummary_time_fields() {
482 let mut s = CRFileSummary::new();
484 s.first_gcutime = 1.0;
485 s.last_gcutime = 2.0;
486 s.first_gpstime = 3.0;
487 s.last_gpstime = 4.0;
488 let stream = s.to_bytestream();
489 let mut pos = 2 + 1 + 4 + 8 + 4 + 4 + 4;
491 for expected in [1.0, 2.0, 3.0, 4.0] {
492 assert_eq!(parse_f64(&stream, &mut pos), expected);
493 }
494 let test = CRFileSummary::from_bytestream(&stream, &mut 0).unwrap();
495 assert_eq!((test.first_gpstime, test.last_gpstime), (3.0, 4.0));
496 }
497
498 #[test]
499 fn crfilesummary_n_missing() {
500 let mut s = CRFileSummary::new();
501 s.missing_evid = vec![(1000, 500), (1503, 1)];
502 assert_eq!(s.n_missing(), 501);
503 }
504
505 #[test]
506 #[cfg(feature="random")]
507 fn crfilesummary_footer() {
508 for _ in 0..100 {
509 let s = CRFileSummary::from_random();
510 let footer = s.to_footer();
511 let len = CRFileSummary::footer_len_from_trailer(&footer).unwrap();
513 assert_eq!(len as usize, footer.len());
514 let frame = CRFrame::from_bytestream(&footer, &mut 0).unwrap();
516 let test = frame.get::<CRFileSummary>(CRFILESUMMARY_NAME).unwrap();
517 assert_eq!(test.footer_len, len);
518 let mut expected = s.clone();
519 expected.footer_len = len;
520 assert_eq!(test, expected);
521 }
522 }
523
524 #[test]
525 fn crfilesummary_needs_magic_to_be_a_footer() {
526 let mut frame = CRFrame::new();
530 frame.put(TofPacket::new(), "TofPacket");
531 let stream = frame.to_bytestream();
532 assert!(stream[stream.len() - 6..].iter().all(|b| *b == 0x55));
533 assert_eq!(CRFileSummary::footer_len_from_trailer(&stream), None);
534 assert_eq!(CRFileSummary::footer_len_from_trailer(&stream[stream.len() - 6..]), None);
536 }
537}