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
329
330
331
332
333
334
335
use std::ffi::CString;
use std::fmt::{self, Write};
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::str::FromStr;

use bitflags::bitflags;
use derive_more::{From, Into};
use foreign_types::{foreign_type, ForeignType, ForeignTypeRef};
use libc::c_char;
use thiserror::Error;

use crate::{
    compile::{AsCompileResult, Pattern},
    ffi, Result,
};

/// Hyperscan Error Codes
#[derive(Debug, Error, PartialEq, Eq)]
pub enum Error {
    #[error("missing parameter")]
    MissingParameter,

    #[error("missing value")]
    MissingValue,

    #[error("unexpected parameter {0}")]
    UnexpectedParameter(String),
}

bitflags! {
    /// These flags are used in `hs_expr_ext_t::flags` to indicate which fields are used.
    #[derive(Default)]
    struct Flags: u64 {
        const MIN_OFFSET = ffi::HS_EXT_FLAG_MIN_OFFSET as u64;
        const MAX_OFFSET = ffi::HS_EXT_FLAG_MAX_OFFSET as u64;
        const MIN_LENGTH = ffi::HS_EXT_FLAG_MIN_LENGTH as u64;
        const EDIT_DISTANCE = ffi::HS_EXT_FLAG_EDIT_DISTANCE as u64;
        const HAMMING_DISTANCE = ffi::HS_EXT_FLAG_HAMMING_DISTANCE as u64;
    }
}

/// A structure containing additional parameters related to an expression.
#[repr(transparent)]
#[derive(Clone, Copy, Default, PartialEq, Eq, From, Into)]
pub struct ExprExt(ffi::hs_expr_ext_t);

impl fmt::Debug for ExprExt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("ExprExt");
        let flags = self.flags();
        if flags.contains(Flags::MIN_OFFSET) {
            s.field("min_offset", &self.0.min_offset);
        }
        if flags.contains(Flags::MAX_OFFSET) {
            s.field("max_offset", &self.0.max_offset);
        }
        if flags.contains(Flags::MIN_LENGTH) {
            s.field("min_length", &self.0.min_length);
        }
        if flags.contains(Flags::EDIT_DISTANCE) {
            s.field("edit_distance", &self.0.edit_distance);
        }
        if flags.contains(Flags::HAMMING_DISTANCE) {
            s.field("hamming_distance", &self.0.hamming_distance);
        }
        s.finish()
    }
}

impl fmt::Display for ExprExt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let flags = self.flags();
        let mut fields = vec![];

        if flags.contains(Flags::MIN_OFFSET) {
            fields.push(format!("min_offset={}", self.0.min_offset));
        }
        if flags.contains(Flags::MAX_OFFSET) {
            fields.push(format!("max_offset={}", self.0.max_offset));
        }
        if flags.contains(Flags::MIN_LENGTH) {
            fields.push(format!("min_length={}", self.0.min_length));
        }
        if flags.contains(Flags::EDIT_DISTANCE) {
            fields.push(format!("edit_distance={}", self.0.edit_distance));
        }
        if flags.contains(Flags::HAMMING_DISTANCE) {
            fields.push(format!("hamming_distance={}", self.0.hamming_distance));
        }

        f.write_char('{')?;
        f.write_str(&fields.join(","))?;
        f.write_char('}')
    }
}

impl FromStr for ExprExt {
    type Err = crate::Error;

    fn from_str(mut s: &str) -> Result<Self> {
        if s.starts_with('{') && s.ends_with('}') {
            s = &s[1..s.len() - 1];
        }

        s.split(',')
            .map(|kv| kv.splitn(2, '='))
            .fold(Ok(ExprExt::default()), |ext, mut kv| {
                ext.and_then(|mut ext| {
                    let key = kv.next().ok_or(Error::MissingParameter)?;
                    let value = kv.next().ok_or(Error::MissingValue)?;

                    match key {
                        "min_offset" => {
                            ext.set_min_offset(value.parse()?);
                        }
                        "max_offset" => {
                            ext.set_max_offset(value.parse()?);
                        }
                        "min_length" => {
                            ext.set_min_length(value.parse()?);
                        }
                        "edit_distance" => {
                            ext.set_edit_distance(value.parse()?);
                        }
                        "hamming_distance" => {
                            ext.set_hamming_distance(value.parse()?);
                        }
                        _ => return Err(Error::UnexpectedParameter(key.into()).into()),
                    }

                    Ok(ext)
                })
            })
    }
}

impl ExprExt {
    fn flags(&self) -> Flags {
        Flags::from_bits_truncate(self.0.flags)
    }

    fn set_flags(&mut self, flags: Flags) {
        self.0.flags |= flags.bits();
    }

    /// Returns true if the expression contains no additional parameters.
    pub fn is_empty(&self) -> bool {
        self.flags().is_empty()
    }

    /// The minimum end offset in the data stream at which this expression should match successfully.
    pub fn min_offset(&self) -> Option<u64> {
        if self.flags().contains(Flags::MIN_OFFSET) {
            Some(self.0.min_offset)
        } else {
            None
        }
    }

    /// The maximum end offset in the data stream at which this expression should match successfully.
    pub fn max_offset(&self) -> Option<u64> {
        if self.flags().contains(Flags::MAX_OFFSET) {
            Some(self.0.max_offset)
        } else {
            None
        }
    }

    /// The minimum match length (from start to end) required to successfully match this expression.
    pub fn min_length(&self) -> Option<u64> {
        if self.flags().contains(Flags::MIN_LENGTH) {
            Some(self.0.min_length)
        } else {
            None
        }
    }

    /// Allow patterns to approximately match within this edit distance.
    pub fn edit_distance(&self) -> Option<u32> {
        if self.flags().contains(Flags::EDIT_DISTANCE) {
            Some(self.0.edit_distance)
        } else {
            None
        }
    }

    /// Allow patterns to approximately match within this Hamming distance.
    pub fn hamming_distance(&self) -> Option<u32> {
        if self.flags().contains(Flags::HAMMING_DISTANCE) {
            Some(self.0.hamming_distance)
        } else {
            None
        }
    }

    /// Sets the value for the minimum end offset in the data stream at which this expression should match successfully.
    pub fn set_min_offset(&mut self, min_offset: u64) -> &mut Self {
        self.set_flags(Flags::MIN_OFFSET);
        self.0.min_offset = min_offset;
        self
    }

    /// Sets the value for the maximum end offset in the data stream at which this expression should match successfully.
    pub fn set_max_offset(&mut self, max_offset: u64) -> &mut Self {
        self.set_flags(Flags::MAX_OFFSET);
        self.0.max_offset = max_offset;
        self
    }

    /// Sets the value for the minimum match length (from start to end) required to successfully match this expression.
    pub fn set_min_length(&mut self, min_length: u64) -> &mut Self {
        self.set_flags(Flags::MIN_LENGTH);
        self.0.min_length = min_length;
        self
    }

    /// Sets the value that allow patterns to approximately match within this edit distance.
    pub fn set_edit_distance(&mut self, edit_distance: u32) -> &mut Self {
        self.set_flags(Flags::EDIT_DISTANCE);
        self.0.edit_distance = edit_distance;
        self
    }

    /// Sets the value that allow patterns to approximately match within this Hamming distance.
    pub fn set_hamming_distance(&mut self, hamming_distance: u32) -> &mut Self {
        self.set_flags(Flags::HAMMING_DISTANCE);
        self.0.hamming_distance = hamming_distance;
        self
    }
}

foreign_type! {
    /// A type containing information related to an expression
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperscan::prelude::*;
    /// let pattern: Pattern = r"(\d{4})-(\d{2})-(\d{2,4})".parse().unwrap();
    /// let info = pattern.info().unwrap();
    ///
    /// assert_eq!(info.min_width(), 10);
    /// assert_eq!(info.max_width(), 12);
    /// assert!(!info.unordered_matches());
    /// assert!(!info.matches_at_eod());
    /// assert!(!info.matches_only_at_eod());
    /// ```
    pub unsafe type ExprInfo: Send + Sync {
        type CType = ffi::hs_expr_info;

        fn drop = drop_expr_info;
    }
}

unsafe fn drop_expr_info(info: *mut ffi::hs_expr_info) {
    libc::free(info as *mut _);
}

impl Deref for ExprInfoRef {
    type Target = ffi::hs_expr_info;

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.as_ptr() }
    }
}

impl fmt::Debug for ExprInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExprInfo")
            .field("min_width", &self.min_width)
            .field("max_width", &self.max_width)
            .field("unordered_matches", &self.unordered_matches())
            .field("matches_at_eod", &self.matches_at_eod())
            .field("matches_only_at_eod", &self.matches_only_at_eod())
            .finish()
    }
}

impl ExprInfoRef {
    /// The minimum length in bytes of a match for the pattern.
    pub fn min_width(&self) -> usize {
        self.min_width as usize
    }

    /// The maximum length in bytes of a match for the pattern.
    pub fn max_width(&self) -> usize {
        self.max_width as usize
    }

    /// Whether this expression can produce matches that are not returned in order,
    /// such as those produced by assertions.
    pub fn unordered_matches(&self) -> bool {
        self.unordered_matches != 0
    }

    /// Whether this expression can produce matches at end of data (EOD).
    pub fn matches_at_eod(&self) -> bool {
        self.matches_at_eod != 0
    }

    /// Whether this expression can *only* produce matches at end of data (EOD).
    pub fn matches_only_at_eod(&self) -> bool {
        self.matches_only_at_eod != 0
    }
}

impl Pattern {
    ///
    /// Utility function providing information about a regular expression.
    ///
    /// The information provided in ExpressionInfo
    /// includes the minimum and maximum width of a pattern match.
    ///
    pub fn info(&self) -> Result<ExprInfo> {
        let expr = CString::new(self.expression.as_str())?;
        let mut info = MaybeUninit::uninit();
        let mut err = MaybeUninit::uninit();

        let info = unsafe {
            ffi::hs_expression_ext_info(
                expr.as_ptr() as *const c_char,
                self.flags.bits(),
                &self.ext.0 as *const _,
                info.as_mut_ptr(),
                err.as_mut_ptr(),
            )
            .ok_or_else(|| err.assume_init())?;

            ExprInfo::from_ptr(info.assume_init())
        };

        Ok(info)
    }
}