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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
use std::ptr;
use std::ops;
use std::os::raw::{c_int,c_char,c_uint};
use std::ffi::CStr;
#[repr(C)]
struct LuaMatch {
start: c_int,
end: c_int
}
static LUA_MAXCAPTURES: usize = 32;
#[link(name = "lua-str", kind="static")]
extern {
fn str_match (
s: *const u8, ls: c_uint, p: *const u8, lp: c_uint,
err_msg: *mut *mut c_char,
mm: *mut LuaMatch
) -> c_int;
}
pub struct LuaPattern<'a> {
patt: &'a [u8],
matches: Vec<LuaMatch>,
n_match: usize
}
impl <'a> LuaPattern<'a> {
pub fn new(patt: &'a str) -> LuaPattern<'a> {
LuaPattern::from_bytes(patt.as_bytes())
}
pub fn from_bytes (bytes: &'a [u8]) -> LuaPattern<'a> {
let mut matches: Vec<LuaMatch> = Vec::with_capacity(LUA_MAXCAPTURES);
unsafe {matches.set_len(LUA_MAXCAPTURES);}
LuaPattern{patt: bytes, matches: matches, n_match: 0}
}
pub fn matches_bytes(&mut self, s: &[u8]) -> bool {
let c_ptr: *mut c_char = ptr::null_mut();
let pvoid = Box::into_raw(Box::new(c_ptr));
let err_msg : *mut *mut c_char = pvoid;
unsafe {
self.n_match = str_match(s.as_ptr(),s.len() as c_uint,
self.patt.as_ptr(),self.patt.len() as c_uint,
err_msg, self.matches.as_mut_ptr()) as usize;
let ep = *err_msg;
if ! ep.is_null() {
panic!(format!("lua-pattern {:?}",CStr::from_ptr(ep)));
}
}
self.n_match > 0
}
pub fn matches(&mut self, text: &str) -> bool {
self.matches_bytes(text.as_bytes())
}
pub fn match_maybe<'t>(&mut self, text: &'t str) -> Option<&'t str> {
if self.matches(text) {
Some(&text[self.first_capture()])
} else {
None
}
}
pub fn captures<'b>(&mut self, text: &'b str) -> Vec<&'b str> {
let mut res = Vec::new();
self.capture_into(text, &mut res);
res
}
pub fn match_captures<'b,'c>(&'c mut self, text: &'b str) -> Captures<'a,'b,'c> {
Captures {m: self, text: text}
}
pub fn capture_into<'b>(&mut self, text: &'b str, vec: &mut Vec<&'b str>) -> bool {
self.matches(text);
vec.clear();
for i in 0..self.n_match {
vec.push(&text[self.capture(i)]);
}
self.n_match > 0
}
pub fn range(&self) -> ops::Range<usize> {
self.capture(0)
}
pub fn capture(&self, i: usize) -> ops::Range<usize> {
ops::Range{
start: self.matches[i].start as usize,
end: self.matches[i].end as usize
}
}
pub fn first_capture(&self) -> ops::Range<usize> {
let idx = if self.n_match > 1 {1} else {0};
self.capture(idx)
}
pub fn gmatch<'b,'c>(&'c mut self, text: &'b str) -> GMatch<'a,'b,'c> {
GMatch{m: self, text: text}
}
pub fn gmatch_bytes<'b>(&'a mut self, bytes: &'b [u8]) -> GMatchBytes<'a,'b> {
GMatchBytes{m: self, bytes: bytes}
}
pub fn gsub_with <F> (&mut self, text: &str, lookup: F) -> String
where F: Fn(Captures)-> String {
let mut slice = text;
let mut res = String::new();
while self.matches(slice) {
let all = self.range();
res.push_str(&slice[0..all.start]);
let captures = Captures{m: self, text: slice};
let repl = lookup(captures);
res.push_str(&repl);
slice = &slice[all.end..];
}
res.push_str(slice);
res
}
pub fn gsub (&mut self, text: &str, repl: &str) -> String {
let repl = generate_gsub_patterns(repl);
let mut slice = text;
let mut res = String::new();
while self.matches(slice) {
let all = self.range();
res.push_str(&slice[0..all.start]);
let captures = Captures{m: self, text: slice};
for r in &repl {
match *r {
Subst::Text(ref s) => res.push_str(&s),
Subst::Capture(i) => res.push_str(captures.get(i))
}
}
slice = &slice[all.end..];
}
res.push_str(slice);
res
}
pub fn gsub_bytes_with <F> (&mut self, bytes: &[u8], lookup: F) -> Vec<u8>
where F: Fn(ByteCaptures)-> Vec<u8> {
let mut slice = bytes;
let mut res = Vec::new();
while self.matches_bytes(slice) {
let all = self.range();
let capture = &slice[0..all.start];
res.extend_from_slice(capture);
let captures = ByteCaptures{m: self, bytes: slice};
let repl = lookup(captures);
res.extend(repl);
slice = &slice[all.end..];
}
res.extend_from_slice(slice);
res
}
}
#[derive(Debug)]
enum Subst {
Text(String),
Capture(usize)
}
impl Subst {
fn new_text(text: &str) -> Subst {
Subst::Text(text.to_string())
}
}
fn generate_gsub_patterns(repl: &str) -> Vec<Subst> {
let mut m = LuaPattern::new("%%([%%%d])");
let mut res = Vec::new();
let mut slice = repl;
while m.matches(slice) {
let all = m.range();
let before = &slice[0..all.start];
if before != "" {
res.push(Subst::new_text(before));
}
let capture = &slice[m.capture(1)];
if capture == "%" {
res.push(Subst::new_text("%"));
} else {
let index: usize = capture.parse().unwrap();
res.push(Subst::Capture(index));
}
slice = &slice[all.end..];
}
res.push(Subst::new_text(slice));
res
}
pub struct Captures<'a,'b,'c> where 'a: 'c {
m: &'c LuaPattern<'a>,
text: &'b str
}
impl <'a,'b,'c> Captures<'a,'b,'c> {
pub fn get(&self, i: usize) -> &'b str {
&self.text[self.m.capture(i)]
}
pub fn num_matches(&self) -> usize {
self.m.n_match
}
}
pub struct ByteCaptures<'a,'b> {
m: &'a LuaPattern<'a>,
bytes: &'b [u8]
}
impl <'a,'b> ByteCaptures<'a,'b> {
pub fn get(&self, i: usize) -> &'b [u8] {
&self.bytes[self.m.capture(i)]
}
pub fn num_matches(&self) -> usize {
self.m.n_match
}
}
pub struct GMatch<'a,'b,'c> where 'a: 'c {
m: &'c mut LuaPattern<'a>,
text: &'b str
}
impl <'a,'b,'c>Iterator for GMatch<'a,'b,'c> {
type Item = &'b str;
fn next(&mut self) -> Option<Self::Item> {
if ! self.m.matches(self.text) {
None
} else {
let slice = &self.text[self.m.first_capture()];
self.text = &self.text[self.m.range().end..];
Some(slice)
}
}
}
pub struct GMatchBytes<'a,'b> {
m: &'a mut LuaPattern<'a>,
bytes: &'b [u8]
}
impl <'a,'b>Iterator for GMatchBytes<'a,'b> {
type Item = &'b [u8];
fn next(&mut self) -> Option<Self::Item> {
if ! self.m.matches_bytes(self.bytes) {
None
} else {
let slice = &self.bytes[self.m.first_capture()];
self.bytes = &self.bytes[self.m.range().end..];
Some(slice)
}
}
}
pub struct LuaPatternBuilder {
bytes: Vec<u8>
}
impl LuaPatternBuilder {
pub fn new() -> LuaPatternBuilder {
LuaPatternBuilder{bytes: Vec::new()}
}
pub fn text(&mut self, s: &str) -> &mut Self {
self.bytes.extend_from_slice(s.as_bytes());
self
}
pub fn text_lines(&mut self, lines: &str) -> &mut Self {
let mut text = String::new();
for line in lines.lines() {
if let Some(first) = line.split_whitespace().next() {
text.push_str(first);
}
}
self.text(&text)
}
pub fn bytes(&mut self, b: &[u8]) -> &mut Self {
let mut m = LuaPattern::new("[%-%.%+%[%]%(%)%$%^%%%?%*]");
let bb = m.gsub_bytes_with(b,|cc| {
let mut res = Vec::new();
res.push(b'%');
res.push(cc.get(0)[0]);
res
});
self.bytes.extend(bb);
self
}
pub fn bytes_as_hex(&mut self, bs: &str) -> &mut Self {
let bb = LuaPatternBuilder::hex_to_bytes(bs);
self.bytes(&bb)
}
pub fn build(&mut self) -> Vec<u8> {
let mut v = Vec::new();
std::mem::swap(&mut self.bytes, &mut v);
v
}
pub fn hex_to_bytes(s: &str) -> Vec<u8> {
let mut m = LuaPattern::new("%x%x");
m.gmatch(s).map(|pair| u8::from_str_radix(pair,16).unwrap()).collect()
}
pub fn bytes_to_hex(s: &[u8]) -> String {
s.iter().map(|b| format!("{:02X}",b)).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captures_and_matching() {
let mut m = LuaPattern::new("(one).+");
assert_eq!(m.captures(" one two"), &["one two","one"]);
let empty: &[&str] = &[];
assert_eq!(m.captures("four"), empty);
assert_eq!(m.matches("one dog"), true);
assert_eq!(m.matches("dog one "), true);
assert_eq!(m.matches("dog one"), false);
let text = "one dog";
let mut m = LuaPattern::new("^(%a+)");
assert_eq!(m.matches(text), true);
assert_eq!(&text[m.capture(1)], "one");
assert_eq!(m.matches(" one dog"), false);
m.matches(text);
let captures = m.match_captures(text);
assert_eq!(captures.get(0), "one");
assert_eq!(captures.get(1), "one");
let mut m = LuaPattern::new("(%S+)%s*=%s*(.+)");
let cc = m.captures(" hello= bonzo dog");
assert_eq!(cc[0], "hello= bonzo dog");
assert_eq!(cc[1], "hello");
assert_eq!(cc[2], "bonzo dog");
}
#[test]
fn gmatch() {
let mut m = LuaPattern::new("%a+");
let mut iter = m.gmatch("one two three");
assert_eq!(iter.next(), Some("one"));
assert_eq!(iter.next(), Some("two"));
assert_eq!(iter.next(), Some("three"));
assert_eq!(iter.next(), None);
let mut m = LuaPattern::new("(%a+)");
let mut iter = m.gmatch("one two three");
assert_eq!(iter.next(), Some("one"));
assert_eq!(iter.next(), Some("two"));
assert_eq!(iter.next(), Some("three"));
assert_eq!(iter.next(), None);
}
#[test]
fn gsub() {
use std::collections::HashMap;
let mut m = LuaPattern::new("%$(%S+)");
let res = m.gsub_with("hello $dolly you're so $fine!",
|cc| cc.get(1).to_uppercase()
);
assert_eq!(res, "hello DOLLY you're so FINE!");
let mut map = HashMap::new();
map.insert("dolly", "baby");
map.insert("fine", "cool");
map.insert("good-looking", "pretty");
let mut m = LuaPattern::new("%$%((.-)%)");
let res = m.gsub_with("hello $(dolly) you're so $(fine) and $(good-looking)",
|cc| map.get(cc.get(1)).unwrap_or(&"?").to_string()
);
assert_eq!(res, "hello baby you're so cool and pretty");
let mut m = LuaPattern::new("%s+");
let res = m.gsub("hello dolly you're so fine","");
assert_eq!(res, "hellodollyyou'resofine");
let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
assert_eq!(res,"'2':a '3':b '4':c ");
}
}