1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use std::{path::{Path, PathBuf}, io::{BufReader, BufRead}};

use hepmc2::reader::LineParseError;
use log::debug;
use thiserror::Error;

use crate::{traits::Rewind, file::File};

const ROOT_MAGIC_BYTES: [u8; 4] = [b'r', b'o', b'o', b't'];

pub struct FileReader (
    Box<dyn EventFileReader>
);

impl Rewind for FileReader {
    type Error = RewindError;

    fn rewind(&mut self) -> Result<(), Self::Error> {
        self.0.rewind()
    }
}

impl Iterator for FileReader {
    type Item = Result<hepmc2::Event, EventReadError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl FileReader {
    /// Returns an event reader for the file at `path`
    pub fn new<P: AsRef<Path>>(
        path: P
    ) -> Result<FileReader, CreateError> {
        use crate::hepmc2::FileReader as HepMCReader;
        let file = File::open(&path)?;
        let mut r = BufReader::new(file);
        let bytes = match r.fill_buf() {
            Ok(bytes) => bytes,
            Err(_) => {
                let file = File::open(&path)?;
                let reader = HepMCReader::new(file)?;
                return Ok(FileReader(Box::new(reader)))
            },
        };
        if bytes.starts_with(&ROOT_MAGIC_BYTES) {
            let path = path.as_ref().to_owned();
            if !cfg!(feature = "ntuple") {
                return Err(CreateError::RootUnsupported(path));
            }
            #[cfg(feature = "ntuple")]
            {
                debug!("Read {path:?} as ROOT ntuple");
                let reader = crate::ntuple::Reader::new(path)?;
                return Ok(FileReader(Box::new(reader)))
            }

        }
        debug!("Read {:?} as HepMC file", path.as_ref());
        let file = File::open(path)?;
        let reader = HepMCReader::new(file)?;
        Ok(FileReader(Box::new(reader)))
    }
}

#[derive(Debug, Error)]
pub enum CreateError {
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
    #[error("Failed to read from {0}")]
    FileError(PathBuf, #[source] Box<CreateError>),

    #[error("Cannot read ROOT ntuple event file `{0}`. Reinstall cres with `cargo install cres --features = ntuple`")]
    RootUnsupported(PathBuf),
}

#[derive(Debug, Error)]
pub enum RewindError {
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
    #[error("Source clone error: {0}")]
    CloneError(std::io::Error)
}

#[derive(Debug, Error)]
pub enum EventReadError {
    #[error("Error reading HepMC record: {0}")]
    HepMCError(#[from] LineParseError),
    #[cfg(feature = "ntuple")]
    #[error("Error reading ntuple event: {0}")]
    NTupleError(#[from] ::ntuple::reader::ReadError),
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Reader<R> {
    readers: Vec<R>,
    current: usize,
}

impl<R> Reader<R> {
    fn new(readers: Vec<R>) -> Self {
        Self{ readers, current: 0 }
    }
}

impl<R: Rewind> Rewind for Reader<R> {
    type Error = <R as Rewind>::Error;

    fn rewind(&mut self) -> Result<(), Self::Error> {
        for reader in &mut self.readers[..=self.current] {
            reader.rewind()?;
        }
        self.current = 0;
        Ok(())
    }
}

impl<R: Iterator> Iterator for Reader<R> {
    type Item = <R as Iterator>::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.readers[self.current].next();
        if next.is_some() {
            return next;
        }
        if self.current + 1 == self.readers.len() {
            return None;
        }
        self.current += 1;
        self.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.readers[self.current..].iter()
            .map(|r| r.size_hint())
            .reduce(|(accmin, accmax), (min, max)|  {
                let accmax = match (accmax, max) {
                    (Some(accmax), Some(max)) => Some(accmax + max),
                    _ => None
                };
                (accmin + min, accmax)
            }).unwrap_or_default()
    }
}

impl Reader<FileReader> {
    /// Construct a new reader reading from the files with the given names
    pub fn from_files<I, P>(
        files: I
    ) -> Result<Self, CreateError>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let readers: Result<_, _> = files.into_iter()
            .map(|f| FileReader::new(f.as_ref()).map_err(
                |err| CreateError::FileError(f.as_ref().to_path_buf(), Box::new(err))
            ))
            .collect();
        Ok(Self::new(readers?))
    }
}

pub trait EventFileReader:
    Iterator<Item = Result<hepmc2::Event, EventReadError>>
    + Rewind<Error = RewindError> {
    }

#[cfg(feature = "ntuple")]
impl EventFileReader for crate::ntuple::Reader {}

impl EventFileReader for crate::hepmc2::FileReader {}