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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! The rawfile parser and AST data structures.
use std::str;

use nom::branch::alt;
use nom::bytes::complete::{tag_no_case, take, take_till1, take_while, take_while1};
use nom::character::complete::{line_ending, space0, space1};
use nom::combinator::opt;
use nom::error::{Error, ErrorKind};
use nom::multi::many0;
use nom::number::complete::{be_f64, le_f64};
use nom::sequence::{delimited, tuple};
use nom::{Err, IResult};
use serde::{Deserialize, Serialize};

use crate::{ByteOrder, Options};

#[cfg(test)]
mod tests;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Data stored by a single analysis.
pub struct Analysis<'a> {
    /// The title of the analysis.
    pub title: Option<&'a str>,
    /// The date on which the analysis was performed.
    pub date: Option<&'a str>,
    /// Plot name.
    pub plotname: &'a str,
    /// Flags.
    pub flags: &'a str,
    /// The number of saved variables.
    pub num_variables: usize,
    /// The number of points saved.
    pub num_points: usize,
    /// The saved variable names.
    pub variables: Vec<Variable<'a>>,
    /// The saved variable values.
    pub data: AnalysisData,
}

/// Data saved by an [`Analysis`].
pub type AnalysisData = Data<Vec<RealSignal>, Vec<ComplexSignal>>;

/// Data saved by an [`Analysis`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[enumify::enumify]
pub enum Data<R, C> {
    /// A set of real signals.
    Real(R),
    /// A set of complex signals.
    Complex(C),
}

/// A real data vector.
pub type RealSignal = Vec<f64>;

/// A complex data vector.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComplexSignal {
    /// The real part.
    pub real: Vec<f64>,
    /// The imaginary part.
    pub imag: Vec<f64>,
}

impl ComplexSignal {
    fn with_capacity(cap: usize) -> Self {
        Self {
            real: Vec::with_capacity(cap),
            imag: Vec::with_capacity(cap),
        }
    }
}

/// A variable saved in an [`Analysis`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Variable<'a> {
    /// The index of this variable in the list of saved data vectors.
    pub idx: usize,
    /// The name of the signal.
    pub name: &'a str,
    /// The signal units.
    pub unit: &'a str,
}

fn is_newline(c: u8) -> bool {
    c == b'\n' || c == b'\r'
}

fn is_space_or_line(c: u8) -> bool {
    c == b'\n' || c == b'\r' || c == b' ' || c == b'\t'
}

fn header<'a, 'b>(key: &'b str) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a str> + 'b {
    move |input| {
        let tag = tag_no_case(key);
        let (input, _) = space0(input)?;
        let header_value = take_till1(is_newline);
        let (input, value) = delimited(tag, header_value, line_ending)(input)?;
        let value = from_utf8(value)?;
        Ok((input, value))
    }
}

fn from_utf8(input: &[u8]) -> Result<&str, Err<Error<&[u8]>>> {
    let value = std::str::from_utf8(input)
        .map_err(|_| Err::Failure(Error::new(input, ErrorKind::Permutation)))?;
    Ok(value)
}

fn parse_usize(input: &[u8]) -> Result<usize, Err<Error<&[u8]>>> {
    let string = from_utf8(input)?;
    let value = string
        .trim()
        .parse::<usize>()
        .map_err(|_| Err::Failure(Error::new(input, ErrorKind::Fail)))?;
    Ok(value)
}

fn parse_usize_str(input: &str) -> Result<usize, Err<Error<&[u8]>>> {
    let value = input
        .trim()
        .parse::<usize>()
        .map_err(|_| Err::Failure(Error::new(input.as_bytes(), ErrorKind::TagClosure)))?;
    Ok(value)
}

fn parse_f64(input: &[u8]) -> Result<f64, Err<Error<&[u8]>>> {
    let string = from_utf8(input)?;
    let value = string
        .trim()
        .parse::<f64>()
        .map_err(|_| Err::Failure(Error::new(input, ErrorKind::TagClosure)))?;
    Ok(value)
}

fn variable(input: &[u8]) -> IResult<&[u8], Variable> {
    let value = take_till1(is_space_or_line);
    // In AC analysis, may have a `grid=X` declaration
    let kwargs = opt(take_till1(is_newline));
    let (input, (_, idx, _, name, _, unit, _, _, _, _)) = tuple((
        space0,
        &value,
        space1,
        &value,
        space1,
        &value,
        space0,
        kwargs,
        space0,
        line_ending,
    ))(input)?;
    let idx = parse_usize(idx)?;
    let name = from_utf8(name)?;
    let unit = from_utf8(unit)?;
    Ok((input, Variable { idx, name, unit }))
}

fn variables(input: &[u8]) -> IResult<&[u8], Vec<Variable>> {
    let (input, _) = tuple((tag_no_case("Variables:"), space0, opt(line_ending), space0))(input)?;
    let (input, vars) = many0(variable)(input)?;
    Ok((input, vars))
}

fn real_data_binary(
    vars: usize,
    points: usize,
    opts: Options,
) -> impl Fn(&[u8]) -> IResult<&[u8], AnalysisData> {
    move |input| {
        let (mut input, _) = tuple((tag_no_case("Binary:"), space0, line_ending))(input)?;
        let mut out = vec![Vec::with_capacity(points); vars];
        for _ in 0..points {
            for item in out.iter_mut().take(vars) {
                let val: f64;
                (input, val) = match opts.endianness {
                    ByteOrder::BigEndian => be_f64(input)?,
                    ByteOrder::LittleEndian => le_f64(input)?,
                };
                item.push(val);
            }
        }

        Ok((input, AnalysisData::Real(out)))
    }
}

fn real_data_ascii(vars: usize, points: usize) -> impl Fn(&[u8]) -> IResult<&[u8], AnalysisData> {
    move |input| {
        let (mut input, _) = tuple((tag_no_case("Values:"), space0, line_ending))(input)?;
        (input, _) = take_while(is_space_or_line)(input)?;

        let mut out = vec![Vec::with_capacity(points); vars];
        for _ in 0..points {
            (input, _) = take_till1(is_space_or_line)(input)?;
            for item in out.iter_mut().take(vars) {
                let val;
                (input, _) = take_while1(is_space_or_line)(input)?;
                (input, val) = take_till1(is_space_or_line)(input)?;
                item.push(parse_f64(val)?);
            }
            (input, _) = take_while1(is_space_or_line)(input)?;
        }

        Ok((input, AnalysisData::Real(out)))
    }
}

fn real_data(
    input: &[u8],
    vars: usize,
    points: usize,
    opts: Options,
) -> IResult<&[u8], AnalysisData> {
    alt((
        real_data_binary(vars, points, opts),
        real_data_ascii(vars, points),
    ))(input)
}

fn complex_data_binary(
    vars: usize,
    points: usize,
    opts: Options,
) -> impl Fn(&[u8]) -> IResult<&[u8], AnalysisData> {
    move |input| {
        let (mut input, _) = tuple((tag_no_case("Binary:"), space0, line_ending))(input)?;

        let mut out = vec![ComplexSignal::with_capacity(points); vars];
        for _ in 0..points {
            for item in out.iter_mut().take(vars) {
                let val: f64;
                (input, val) = match opts.endianness {
                    ByteOrder::BigEndian => be_f64(input)?,
                    ByteOrder::LittleEndian => le_f64(input)?,
                };
                item.real.push(val);
                let val: f64;
                (input, val) = match opts.endianness {
                    ByteOrder::BigEndian => be_f64(input)?,
                    ByteOrder::LittleEndian => le_f64(input)?,
                };
                item.imag.push(val);
            }
        }

        Ok((input, AnalysisData::Complex(out)))
    }
}

fn complex_data_ascii(
    vars: usize,
    points: usize,
) -> impl Fn(&[u8]) -> IResult<&[u8], AnalysisData> {
    move |input| {
        let (mut input, _) = tuple((tag_no_case("Values:"), space0, line_ending))(input)?;
        (input, _) = take_while(is_space_or_line)(input)?;

        let mut out = vec![ComplexSignal::with_capacity(points); vars];
        for _ in 0..points {
            (input, _) = take_till1(is_space_or_line)(input)?;
            for item in out.iter_mut().take(vars) {
                (input, _) = take_while1(is_space_or_line)(input)?;
                let val;
                (input, val) = take_till1(|c| c == b',')(input)?;
                item.real.push(parse_f64(val)?);
                (input, _) = take(1u64)(input)?;
                let val;
                (input, val) = take_till1(is_space_or_line)(input)?;
                item.imag.push(parse_f64(val)?);
            }
            (input, _) = take_while1(is_space_or_line)(input)?;
        }

        Ok((input, AnalysisData::Complex(out)))
    }
}

fn complex_data(
    input: &[u8],
    vars: usize,
    points: usize,
    opts: Options,
) -> IResult<&[u8], AnalysisData> {
    alt((
        complex_data_binary(vars, points, opts),
        complex_data_ascii(vars, points),
    ))(input)
}

fn analysis(opts: Options) -> impl Fn(&[u8]) -> IResult<&[u8], Analysis> {
    move |input: &[u8]| -> IResult<&[u8], Analysis> {
        let (input, _) = take_while(is_space_or_line)(input)?;
        let (input, title) = opt(header("Title:"))(input)?;
        let (input, date) = opt(header("Date:"))(input)?;
        let (input, plotname) = header("Plotname:")(input)?;
        let (input, flags) = header("Flags:")(input)?;
        let (input, num_variables) = header("No. Variables:")(input)?;
        let num_variables = parse_usize_str(num_variables)?;
        let (input, num_points) = header("No. Points:")(input)?;
        let num_points = parse_usize_str(num_points)?;
        let (input, variables) = variables(input)?;

        let (input, data) = if flags.contains("complex") {
            complex_data(input, num_variables, num_points, opts)?
        } else {
            real_data(input, num_variables, num_points, opts)?
        };

        Ok((
            input,
            Analysis {
                title,
                date,
                plotname,
                flags,
                num_variables,
                num_points,
                variables,
                data,
            },
        ))
    }
}

pub(crate) fn analyses(input: &[u8], opts: Options) -> IResult<&[u8], Vec<Analysis>> {
    many0(analysis(opts))(input)
}