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
use std::mem::MaybeUninit;

use foreign_types::{foreign_type, ForeignType, ForeignTypeRef};

use crate::{
    common::{DatabaseRef, Streaming},
    error::AsResult,
    ffi,
    runtime::{MatchEventHandler, ScratchRef},
    Result,
};

impl DatabaseRef<Streaming> {
    /// Provides the size of the stream state allocated by a single stream opened against the given database.
    pub fn stream_size(&self) -> Result<usize> {
        let mut size = MaybeUninit::uninit();

        unsafe { ffi::hs_stream_size(self.as_ptr(), size.as_mut_ptr()).map(|_| size.assume_init()) }
    }

    /// Open and initialise a stream.
    pub fn open_stream(&self) -> Result<Stream> {
        let mut s = MaybeUninit::uninit();

        unsafe { ffi::hs_open_stream(self.as_ptr(), 0, s.as_mut_ptr()).map(|_| Stream::from_ptr(s.assume_init())) }
    }
}

foreign_type! {
    /// A pattern matching state can be maintained across multiple blocks of target data
    pub unsafe type Stream: Send {
        type CType = ffi::hs_stream_t;

        fn drop = drop_stream;
        fn clone = clone_stream;
    }
}

fn drop_stream(_s: *mut ffi::hs_stream_t) {}

/// Duplicate the given stream.
///
/// The new stream will have the same state as the original including the current stream offset.
unsafe fn clone_stream(s: *mut ffi::hs_stream_t) -> *mut ffi::hs_stream_t {
    let mut p = MaybeUninit::uninit();

    ffi::hs_copy_stream(p.as_mut_ptr(), s).expect("copy stream");

    p.assume_init()
}

impl StreamRef {
    /// Reset a stream to an initial state.
    ///
    /// Conceptually, this is equivalent to performing `Stream::close` on the given stream,
    /// followed by `StreamingDatabase::open_stream`.
    /// This new stream replaces the original stream in memory,
    /// avoiding the overhead of freeing the old stream and allocating the new one.
    ///
    /// Note: This operation may result in matches being returned (via calls to the match event callback)
    /// for expressions anchored to the end of the original data stream
    /// (for example, via the use of the `$` meta-character).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperscan::prelude::*;
    /// let db: StreamingDatabase = pattern! {"test"; SOM_LEFTMOST}.build().unwrap();
    ///
    /// let s = db.alloc_scratch().unwrap();
    /// let st = db.open_stream().unwrap();
    ///
    /// let data = vec!["foo t", "es", "t bar"];
    /// let mut matches = vec![];
    ///
    /// let mut callback = |_, from, to, _| {
    ///     matches.push((from, to));
    ///
    ///     Matching::Continue
    /// };
    ///
    /// for d in &data {
    ///     st.scan(d, &s, &mut callback).unwrap();
    /// }
    ///
    /// st.reset(&s, &mut callback).unwrap();
    ///
    /// for d in &data {
    ///     st.scan(d, &s, &mut callback).unwrap();
    /// }
    ///
    /// st.close(&s, callback).unwrap();
    ///
    /// assert_eq!(matches, vec![(4, 8), (4, 8)]);
    /// ```
    pub fn reset<F>(&self, scratch: &ScratchRef, mut on_match_event: F) -> Result<()>
    where
        F: MatchEventHandler,
    {
        unsafe {
            let (callback, userdata) = on_match_event.split();

            ffi::hs_reset_stream(self.as_ptr(), 0, scratch.as_ptr(), callback, userdata).ok()
        }
    }

    /// Duplicate the given `from` stream state onto the stream.
    ///
    /// The stream will first be reset (reporting any EOD matches if a `on_match_event` callback handler is provided).
    ///
    /// Note: the stream and the `from` stream must be open against the same database.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperscan::prelude::*;
    /// let db: StreamingDatabase = pattern! {"test"; SOM_LEFTMOST}.build().unwrap();
    ///
    /// let s = db.alloc_scratch().unwrap();
    /// let st = db.open_stream().unwrap();
    ///
    /// let mut matches = vec![];
    ///
    /// let mut callback = |_, from, to, _| {
    ///     matches.push((from, to));
    ///
    ///     Matching::Continue
    /// };
    ///
    /// st.scan("foo t", &s, &mut callback).unwrap();
    /// st.scan("es", &s, &mut callback).unwrap();
    ///
    /// let st2 = db.open_stream().unwrap();
    ///
    /// st2.scan("test", &s, &mut callback).unwrap();
    /// st2.reset_and_copy_stream(&st, &s, &mut callback).unwrap();
    /// st2.scan("t bar", &s, &mut callback).unwrap();
    /// st2.close(&s, &mut callback).unwrap();
    ///
    /// st.close(&s, Matching::Terminate).unwrap();
    ///
    /// assert_eq!(matches, vec![(0, 4), (4, 8)]);
    /// ```
    pub fn reset_and_copy_stream<F>(&self, from: &StreamRef, scratch: &ScratchRef, mut on_match_event: F) -> Result<()>
    where
        F: MatchEventHandler,
    {
        unsafe {
            let (callback, userdata) = on_match_event.split();

            ffi::hs_reset_and_copy_stream(self.as_ptr(), from.as_ptr(), scratch.as_ptr(), callback, userdata).ok()
        }
    }
}

impl Stream {
    /// Close a stream.
    ///
    /// This function completes matching on the given stream and frees the memory associated with the stream state.
    /// After this call, the stream is invalid and can no longer be used.
    /// To reuse the stream state after completion, rather than closing it, the `StreamRef::reset` function can be used.
    ///
    /// This function must be called for any stream created with `StreamingDatabase::open_stream`,
    /// even if scanning has been terminated by a non-zero return from the match callback function.
    pub fn close<F>(self, scratch: &ScratchRef, mut on_match_event: F) -> Result<()>
    where
        F: MatchEventHandler,
    {
        unsafe {
            let (callback, userdata) = on_match_event.split();

            ffi::hs_close_stream(self.as_ptr(), scratch.as_ptr(), callback, userdata).ok()
        }
    }
}

impl StreamRef {
    /// Creates a compressed representation of the provided stream in the buffer provided.
    ///
    /// This compressed representation can be converted back into a stream state by using `expand()`
    /// or `reset_and_expand()`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperscan::prelude::*;
    /// let db: StreamingDatabase = pattern! {"test"; SOM_LEFTMOST}.build().unwrap();
    ///
    /// let s = db.alloc_scratch().unwrap();
    /// let st = db.open_stream().unwrap();
    ///
    /// let mut matches = vec![];
    ///
    /// let mut callback = |_, from, to, _| {
    ///     matches.push((from, to));
    ///
    ///     Matching::Continue
    /// };
    ///
    /// st.scan("foo t", &s, &mut callback).unwrap();
    /// st.scan("es", &s, &mut callback).unwrap();
    ///
    /// let mut buf = [0; 8192];
    /// let len = st.compress(&mut buf).unwrap();
    /// st.close(&s, Matching::Terminate).unwrap();
    ///
    /// let st2 = db.expand_stream(&buf[..len]).unwrap();
    /// st2.scan("t bar", &s, &mut callback).unwrap();
    /// st2.close(&s, &mut callback).unwrap();
    ///
    /// assert_eq!(matches, vec![(4, 8)]);
    /// ```
    pub fn compress(&self, buf: &mut [u8]) -> Result<usize> {
        let mut size = MaybeUninit::uninit();

        unsafe {
            ffi::hs_compress_stream(self.as_ptr(), buf.as_mut_ptr() as *mut _, buf.len(), size.as_mut_ptr())
                .ok()
                .map(|_| size.assume_init())
        }
    }

    /// Decompresses a compressed representation created by `StreamRef::compress` on top of the stream.
    /// The stream will first be reset (reporting any EOD matches).
    ///
    /// Note: the stream must be opened against the same database as the compressed stream.
    ///
    /// Note: `buf` must correspond to a complete compressed representation created by `StreamRef::compress` of a stream
    /// that was opened against `db`. It is not always possible to detect misuse of this API and behaviour is undefined
    /// if these properties are not satisfied.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperscan::prelude::*;
    /// let db: StreamingDatabase = pattern! {"test"; SOM_LEFTMOST}.build().unwrap();
    ///
    /// let s = db.alloc_scratch().unwrap();
    /// let st = db.open_stream().unwrap();
    ///
    /// let mut matches = vec![];
    ///
    /// let mut callback = |_, from, to, _| {
    ///     matches.push((from, to));
    ///
    ///     Matching::Continue
    /// };
    ///
    /// st.scan("foo t", &s, &mut callback).unwrap();
    /// st.scan("es", &s, &mut callback).unwrap();
    ///
    /// let mut buf = [0; 8192];
    /// let len = st.compress(&mut buf).unwrap();
    /// st.scan("t bar", &s, &mut callback).unwrap();
    ///
    /// st.reset_and_expand(&buf[..len], &s, &mut callback).unwrap();
    /// st.scan("t bar", &s, &mut callback).unwrap();
    /// st.close(&s, &mut callback).unwrap();
    ///
    /// assert_eq!(matches, vec![(4, 8), (4, 8)]);
    /// ```
    pub fn reset_and_expand<F>(&self, buf: &[u8], scratch: &ScratchRef, mut on_match_event: F) -> Result<()>
    where
        F: MatchEventHandler,
    {
        unsafe {
            let (callback, userdata) = on_match_event.split();

            ffi::hs_reset_and_expand_stream(
                self.as_ptr(),
                buf.as_ptr() as *const _,
                buf.len(),
                scratch.as_ptr(),
                callback,
                userdata,
            )
            .ok()
        }
    }
}

impl DatabaseRef<Streaming> {
    /// Decompresses a compressed representation created by `StreamRef::compress()` into a new stream.
    ///
    /// Note: `buf` must correspond to a complete compressed representation created by `StreamRef::compress()` of a stream
    /// that was opened against `db`. It is not always possible to detect misuse of this API and behaviour is undefined
    /// if these properties are not satisfied.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use hyperscan::prelude::*;
    /// let db: StreamingDatabase = pattern! {"test"; SOM_LEFTMOST}.build().unwrap();
    ///
    /// let s = db.alloc_scratch().unwrap();
    /// let st = db.open_stream().unwrap();
    ///
    /// let mut matches = vec![];
    ///
    /// let mut callback = |_, from, to, _| {
    ///     matches.push((from, to));
    ///
    ///     Matching::Continue
    /// };
    ///
    /// st.scan("foo t", &s, &mut callback).unwrap();
    /// st.scan("es", &s, &mut callback).unwrap();
    ///
    /// let mut buf = [0; 8192];
    /// let len = st.compress(&mut buf).unwrap();
    /// st.close(&s, Matching::Terminate).unwrap();
    ///
    /// let st2 = db.expand_stream(&buf[..len]).unwrap();
    /// st2.scan("t bar", &s, &mut callback).unwrap();
    /// st2.close(&s, &mut callback).unwrap();
    ///
    /// assert_eq!(matches, vec![(4, 8)]);
    /// ```
    pub fn expand_stream(&self, buf: &[u8]) -> Result<Stream> {
        let mut stream = MaybeUninit::uninit();

        unsafe {
            ffi::hs_expand_stream(self.as_ptr(), stream.as_mut_ptr(), buf.as_ptr() as *const _, buf.len())
                .ok()
                .map(|_| Stream::from_ptr(stream.assume_init()))
        }
    }
}