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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
|
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::ops::Deref;
use std::ptr;
use std::slice;
use std::str;
use libc::{c_char, size_t};
use regex::bytes;
use crate::error::{Error, ErrorKind};
const RURE_FLAG_CASEI: u32 = 1 << 0;
const RURE_FLAG_MULTI: u32 = 1 << 1;
const RURE_FLAG_DOTNL: u32 = 1 << 2;
const RURE_FLAG_SWAP_GREED: u32 = 1 << 3;
const RURE_FLAG_SPACE: u32 = 1 << 4;
const RURE_FLAG_UNICODE: u32 = 1 << 5;
const RURE_DEFAULT_FLAGS: u32 = RURE_FLAG_UNICODE;
pub struct Regex {
re: bytes::Regex,
capture_names: HashMap<String, i32>,
}
pub struct Options {
size_limit: usize,
dfa_size_limit: usize,
}
// The `RegexSet` is not exposed with option support or matching at an
// arbitrary position with a crate just yet. To circumvent this, we use
// the `Exec` structure directly.
pub struct RegexSet {
re: bytes::RegexSet,
}
#[repr(C)]
pub struct rure_match {
pub start: size_t,
pub end: size_t,
}
pub struct Captures(bytes::Locations);
pub struct Iter {
re: *const Regex,
last_end: usize,
last_match: Option<usize>,
}
pub struct IterCaptureNames {
capture_names: bytes::CaptureNames<'static>,
name_ptrs: Vec<*mut c_char>,
}
impl Deref for Regex {
type Target = bytes::Regex;
fn deref(&self) -> &bytes::Regex {
&self.re
}
}
impl Deref for RegexSet {
type Target = bytes::RegexSet;
fn deref(&self) -> &bytes::RegexSet {
&self.re
}
}
impl Default for Options {
fn default() -> Options {
Options { size_limit: 10 * (1 << 20), dfa_size_limit: 2 * (1 << 20) }
}
}
ffi_fn! {
fn rure_compile_must(pattern: *const c_char) -> *const Regex {
let len = unsafe { CStr::from_ptr(pattern).to_bytes().len() };
let pat = pattern as *const u8;
let mut err = Error::new(ErrorKind::None);
let re = rure_compile(
pat, len, RURE_DEFAULT_FLAGS, ptr::null(), &mut err);
if err.is_err() {
let _ = writeln!(&mut io::stderr(), "{}", err);
let _ = writeln!(
&mut io::stderr(), "aborting from rure_compile_must");
unsafe { abort() }
}
re
}
}
ffi_fn! {
fn rure_compile(
pattern: *const u8,
length: size_t,
flags: u32,
options: *const Options,
error: *mut Error,
) -> *const Regex {
let pat = unsafe { slice::from_raw_parts(pattern, length) };
let pat = match str::from_utf8(pat) {
Ok(pat) => pat,
Err(err) => {
unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Str(err));
}
return ptr::null();
}
}
};
let mut builder = bytes::RegexBuilder::new(pat);
if !options.is_null() {
let options = unsafe { &*options };
builder.size_limit(options.size_limit);
builder.dfa_size_limit(options.dfa_size_limit);
}
builder.case_insensitive(flags & RURE_FLAG_CASEI > 0);
builder.multi_line(flags & RURE_FLAG_MULTI > 0);
builder.dot_matches_new_line(flags & RURE_FLAG_DOTNL > 0);
builder.swap_greed(flags & RURE_FLAG_SWAP_GREED > 0);
builder.ignore_whitespace(flags & RURE_FLAG_SPACE > 0);
builder.unicode(flags & RURE_FLAG_UNICODE > 0);
match builder.build() {
Ok(re) => {
let mut capture_names = HashMap::new();
for (i, name) in re.capture_names().enumerate() {
if let Some(name) = name {
capture_names.insert(name.to_owned(), i as i32);
}
}
let re = Regex {
re: re,
capture_names: capture_names,
};
Box::into_raw(Box::new(re))
}
Err(err) => {
unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Regex(err));
}
ptr::null()
}
}
}
}
}
ffi_fn! {
fn rure_free(re: *const Regex) {
unsafe { drop(Box::from_raw(re as *mut Regex)); }
}
}
ffi_fn! {
fn rure_is_match(
re: *const Regex,
haystack: *const u8,
len: size_t,
start: size_t,
) -> bool {
let re = unsafe { &*re };
let haystack = unsafe { slice::from_raw_parts(haystack, len) };
re.is_match_at(haystack, start)
}
}
ffi_fn! {
fn rure_find(
re: *const Regex,
haystack: *const u8,
len: size_t,
start: size_t,
match_info: *mut rure_match,
) -> bool {
let re = unsafe { &*re };
let haystack = unsafe { slice::from_raw_parts(haystack, len) };
re.find_at(haystack, start).map(|m| unsafe {
if !match_info.is_null() {
(*match_info).start = m.start();
(*match_info).end = m.end();
}
}).is_some()
}
}
ffi_fn! {
fn rure_find_captures(
re: *const Regex,
haystack: *const u8,
len: size_t,
start: size_t,
captures: *mut Captures,
) -> bool {
let re = unsafe { &*re };
let haystack = unsafe { slice::from_raw_parts(haystack, len) };
let slots = unsafe { &mut (*captures).0 };
re.read_captures_at(slots, haystack, start).is_some()
}
}
ffi_fn! {
fn rure_shortest_match(
re: *const Regex,
haystack: *const u8,
len: size_t,
start: size_t,
end: *mut usize,
) -> bool {
let re = unsafe { &*re };
let haystack = unsafe { slice::from_raw_parts(haystack, len) };
match re.shortest_match_at(haystack, start) {
None => false,
Some(i) => {
if !end.is_null() {
unsafe {
*end = i;
}
}
true
}
}
}
}
ffi_fn! {
fn rure_capture_name_index(
re: *const Regex,
name: *const c_char,
) -> i32 {
let re = unsafe { &*re };
let name = unsafe { CStr::from_ptr(name) };
let name = match name.to_str() {
Err(_) => return -1,
Ok(name) => name,
};
re.capture_names.get(name).map(|&i|i).unwrap_or(-1)
}
}
ffi_fn! {
fn rure_iter_capture_names_new(
re: *const Regex,
) -> *mut IterCaptureNames {
let re = unsafe { &*re };
Box::into_raw(Box::new(IterCaptureNames {
capture_names: re.re.capture_names(),
name_ptrs: Vec::new(),
}))
}
}
ffi_fn! {
fn rure_iter_capture_names_free(it: *mut IterCaptureNames) {
unsafe {
let it = &mut *it;
while let Some(ptr) = it.name_ptrs.pop() {
drop(CString::from_raw(ptr));
}
drop(Box::from_raw(it));
}
}
}
ffi_fn! {
fn rure_iter_capture_names_next(
it: *mut IterCaptureNames,
capture_name: *mut *mut c_char,
) -> bool {
if capture_name.is_null() {
return false;
}
let it = unsafe { &mut *it };
let cn = match it.capture_names.next() {
// Top-level iterator ran out of capture groups
None => return false,
Some(val) => {
let name = match val {
// inner Option didn't have a name
None => "",
Some(name) => name
};
name
}
};
unsafe {
let cs = match CString::new(cn.as_bytes()) {
Result::Ok(val) => val,
Result::Err(_) => return false
};
let ptr = cs.into_raw();
it.name_ptrs.push(ptr);
*capture_name = ptr;
}
true
}
}
ffi_fn! {
fn rure_iter_new(
re: *const Regex,
) -> *mut Iter {
Box::into_raw(Box::new(Iter {
re: re,
last_end: 0,
last_match: None,
}))
}
}
ffi_fn! {
fn rure_iter_free(it: *mut Iter) {
unsafe { drop(Box::from_raw(it)); }
}
}
ffi_fn! {
fn rure_iter_next(
it: *mut Iter,
haystack: *const u8,
len: size_t,
match_info: *mut rure_match,
) -> bool {
let it = unsafe { &mut *it };
let re = unsafe { &*it.re };
let text = unsafe { slice::from_raw_parts(haystack, len) };
if it.last_end > text.len() {
return false;
}
let (s, e) = match re.find_at(text, it.last_end) {
None => return false,
Some(m) => (m.start(), m.end()),
};
if s == e {
// This is an empty match. To ensure we make progress, start
// the next search at the smallest possible starting position
// of the next match following this one.
it.last_end += 1;
// Don't accept empty matches immediately following a match.
// Just move on to the next match.
if Some(e) == it.last_match {
return rure_iter_next(it, haystack, len, match_info);
}
} else {
it.last_end = e;
}
it.last_match = Some(e);
if !match_info.is_null() {
unsafe {
(*match_info).start = s;
(*match_info).end = e;
}
}
true
}
}
ffi_fn! {
fn rure_iter_next_captures(
it: *mut Iter,
haystack: *const u8,
len: size_t,
captures: *mut Captures,
) -> bool {
let it = unsafe { &mut *it };
let re = unsafe { &*it.re };
let slots = unsafe { &mut (*captures).0 };
let text = unsafe { slice::from_raw_parts(haystack, len) };
if it.last_end > text.len() {
return false;
}
let (s, e) = match re.read_captures_at(slots, text, it.last_end) {
None => return false,
Some(m) => (m.start(), m.end()),
};
if s == e {
// This is an empty match. To ensure we make progress, start
// the next search at the smallest possible starting position
// of the next match following this one.
it.last_end += 1;
// Don't accept empty matches immediately following a match.
// Just move on to the next match.
if Some(e) == it.last_match {
return rure_iter_next_captures(it, haystack, len, captures);
}
} else {
it.last_end = e;
}
it.last_match = Some(e);
true
}
}
ffi_fn! {
fn rure_captures_new(re: *const Regex) -> *mut Captures {
let re = unsafe { &*re };
let captures = Captures(re.locations());
Box::into_raw(Box::new(captures))
}
}
ffi_fn! {
fn rure_captures_free(captures: *const Captures) {
unsafe { drop(Box::from_raw(captures as *mut Captures)); }
}
}
ffi_fn! {
fn rure_captures_at(
captures: *const Captures,
i: size_t,
match_info: *mut rure_match,
) -> bool {
let locs = unsafe { &(*captures).0 };
match locs.pos(i) {
Some((start, end)) => {
if !match_info.is_null() {
unsafe {
(*match_info).start = start;
(*match_info).end = end;
}
}
true
}
_ => false
}
}
}
ffi_fn! {
fn rure_captures_len(captures: *const Captures) -> size_t {
unsafe { (*captures).0.len() }
}
}
ffi_fn! {
fn rure_options_new() -> *mut Options {
Box::into_raw(Box::new(Options::default()))
}
}
ffi_fn! {
fn rure_options_free(options: *mut Options) {
unsafe { drop(Box::from_raw(options)); }
}
}
ffi_fn! {
fn rure_options_size_limit(options: *mut Options, limit: size_t) {
let options = unsafe { &mut *options };
options.size_limit = limit;
}
}
ffi_fn! {
fn rure_options_dfa_size_limit(options: *mut Options, limit: size_t) {
let options = unsafe { &mut *options };
options.dfa_size_limit = limit;
}
}
ffi_fn! {
fn rure_compile_set(
patterns: *const *const u8,
patterns_lengths: *const size_t,
patterns_count: size_t,
flags: u32,
options: *const Options,
error: *mut Error
) -> *const RegexSet {
let (raw_pats, raw_patsl) = unsafe {
(
slice::from_raw_parts(patterns, patterns_count),
slice::from_raw_parts(patterns_lengths, patterns_count)
)
};
let mut pats = Vec::with_capacity(patterns_count);
for (&raw_pat, &raw_patl) in raw_pats.iter().zip(raw_patsl) {
let pat = unsafe { slice::from_raw_parts(raw_pat, raw_patl) };
pats.push(match str::from_utf8(pat) {
Ok(pat) => pat,
Err(err) => {
unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Str(err));
}
return ptr::null();
}
}
});
}
let mut builder = bytes::RegexSetBuilder::new(pats);
if !options.is_null() {
let options = unsafe { &*options };
builder.size_limit(options.size_limit);
builder.dfa_size_limit(options.dfa_size_limit);
}
builder.case_insensitive(flags & RURE_FLAG_CASEI > 0);
builder.multi_line(flags & RURE_FLAG_MULTI > 0);
builder.dot_matches_new_line(flags & RURE_FLAG_DOTNL > 0);
builder.swap_greed(flags & RURE_FLAG_SWAP_GREED > 0);
builder.ignore_whitespace(flags & RURE_FLAG_SPACE > 0);
builder.unicode(flags & RURE_FLAG_UNICODE > 0);
match builder.build() {
Ok(re) => {
Box::into_raw(Box::new(RegexSet { re: re }))
}
Err(err) => {
unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Regex(err))
}
ptr::null()
}
}
}
}
}
ffi_fn! {
fn rure_set_free(re: *const RegexSet) {
unsafe { drop(Box::from_raw(re as *mut RegexSet)); }
}
}
ffi_fn! {
fn rure_set_is_match(
re: *const RegexSet,
haystack: *const u8,
len: size_t,
start: size_t
) -> bool {
let re = unsafe { &*re };
let haystack = unsafe { slice::from_raw_parts(haystack, len) };
re.is_match_at(haystack, start)
}
}
ffi_fn! {
fn rure_set_matches(
re: *const RegexSet,
haystack: *const u8,
len: size_t,
start: size_t,
matches: *mut bool
) -> bool {
let re = unsafe { &*re };
let mut matches = unsafe {
slice::from_raw_parts_mut(matches, re.len())
};
let haystack = unsafe { slice::from_raw_parts(haystack, len) };
// read_matches_at isn't guaranteed to set non-matches to false
for item in matches.iter_mut() {
*item = false;
}
re.read_matches_at(&mut matches, haystack, start)
}
}
ffi_fn! {
fn rure_set_len(re: *const RegexSet) -> size_t {
unsafe { (*re).len() }
}
}
ffi_fn! {
fn rure_escape_must(pattern: *const c_char) -> *const c_char {
let len = unsafe { CStr::from_ptr(pattern).to_bytes().len() };
let pat = pattern as *const u8;
let mut err = Error::new(ErrorKind::None);
let esc = rure_escape(pat, len, &mut err);
if err.is_err() {
let _ = writeln!(&mut io::stderr(), "{}", err);
let _ = writeln!(
&mut io::stderr(), "aborting from rure_escape_must");
unsafe { abort() }
}
esc
}
}
/// A helper function that implements fallible escaping in a way that returns
/// an error if escaping failed.
///
/// This should ideally be exposed, but it needs API design work. In
/// particular, this should not return a C string, but a `const uint8_t *`
/// instead, since it may contain a NUL byte.
fn rure_escape(
pattern: *const u8,
length: size_t,
error: *mut Error,
) -> *const c_char {
let pat: &[u8] = unsafe { slice::from_raw_parts(pattern, length) };
let str_pat = match str::from_utf8(pat) {
Ok(val) => val,
Err(err) => unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Str(err));
}
return ptr::null();
},
};
let esc_pat = regex::escape(str_pat);
let c_esc_pat = match CString::new(esc_pat) {
Ok(val) => val,
Err(err) => unsafe {
if !error.is_null() {
*error = Error::new(ErrorKind::Nul(err));
}
return ptr::null();
},
};
c_esc_pat.into_raw() as *const c_char
}
ffi_fn! {
fn rure_cstring_free(s: *mut c_char) {
unsafe { drop(CString::from_raw(s)); }
}
}
|