squeeze-lib 1.0.0

Finders for URLs, emails, IPs, hashes, TODOs, and more in free-form text
Documentation
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
use super::{Anchor, ByteSet, Finder, Memo, RunClass, RunRule};
use std::ops::Range;

#[derive(Default)]
pub struct Cidr {}

impl Cidr {
    fn try_ipv4_cidr(input: &[u8], idx: usize) -> Option<Range<usize>> {
        if !input[idx].is_ascii_digit() {
            return None;
        }

        // Boundary before: not preceded by digit or dot, nor by ':' — a quad
        // after a colon is the leftover interior of a failed IPv6 candidate
        // (`1::2::1.2.3.4/24`) and must not be mined.
        if idx > 0
            && (input[idx - 1].is_ascii_digit() || input[idx - 1] == b'.' || input[idx - 1] == b':')
        {
            return None;
        }

        let start = idx;
        let mut pos = idx;

        // Parse 4 octets
        for octet_idx in 0..4 {
            if octet_idx > 0 {
                if pos >= input.len() || input[pos] != b'.' {
                    return None;
                }
                pos += 1;
            }

            let octet_start = pos;
            while pos < input.len() && input[pos].is_ascii_digit() {
                pos += 1;
            }
            let octet_len = pos - octet_start;
            if octet_len == 0 || octet_len > 3 {
                return None;
            }

            if octet_len > 1 && input[octet_start] == b'0' {
                return None;
            }

            let mut value: u16 = 0;
            for &b in &input[octet_start..pos] {
                value = value * 10 + (b - b'0') as u16;
            }
            if value > 255 {
                return None;
            }
        }

        // Must have /prefix
        if pos >= input.len() || input[pos] != b'/' {
            return None;
        }
        pos += 1;

        let prefix_start = pos;
        while pos < input.len() && input[pos].is_ascii_digit() {
            pos += 1;
        }
        let prefix_len = pos - prefix_start;
        if prefix_len == 0 || prefix_len > 2 {
            return None;
        }

        // No leading zeros in prefix
        if prefix_len > 1 && input[prefix_start] == b'0' {
            return None;
        }

        let mut prefix: u8 = 0;
        for &b in &input[prefix_start..pos] {
            prefix = prefix * 10 + (b - b'0');
        }
        if prefix > 32 {
            return None;
        }

        // Boundary after: a digit would extend the prefix; a '.' only vetoes
        // when followed by a digit (`/24.5`). A bare '.' is sentence
        // punctuation (`10.0.0.0/8. done`) — a valid CIDR cannot continue
        // with '.' + non-digit.
        if pos < input.len() {
            if input[pos].is_ascii_digit() {
                return None;
            }
            if input[pos] == b'.' && pos + 1 < input.len() && input[pos + 1].is_ascii_digit() {
                return None;
            }
        }

        Some(start..pos)
    }

    fn try_ipv6_cidr(input: &[u8], idx: usize, memo: &mut Memo) -> Option<Range<usize>> {
        // Look for IPv6 addresses followed by /prefix
        // Handle both bare and bracketed forms
        let (ip_start, ip_end) = if input[idx] == b'[' {
            // Bounded like the ip finder: a farther bracket cannot close a
            // valid address.
            let window = &input[idx..input.len().min(idx + 47)];
            let close = window.iter().position(|&b| b == b']')?;
            let close_pos = idx + close;
            let inner = &input[idx + 1..close_pos];
            if !crate::ipv6::is_valid_ipv6(inner) {
                return None;
            }
            (idx, close_pos + 1)
        } else {
            if !input[idx].is_ascii_hexdigit() && input[idx] != b':' {
                return None;
            }
            // Boundary before
            if idx > 0 && (input[idx - 1].is_ascii_alphanumeric() || input[idx - 1] == b':') {
                return None;
            }

            let start = idx;
            // '.' is part of the charset so embedded IPv4 tails
            // (`::ffff:0.0.0.0/96`, `64:ff9b::192.0.2.33/24`) are consumed
            // whole instead of leaving a bogus v4 leftover. The run is
            // shared through the memo with every candidate inside it.
            let (_, mut end) = crate::ip::Ip::run_bounds(input, idx, memo);

            // Strip trailing colons (except ::)
            while end > start && input[end - 1] == b':' && !(end >= 2 && input[end - 2] == b':') {
                end -= 1;
            }

            // Longer than any address: reject before scanning the candidate.
            if end - start > crate::ipv6::MAX_IPV6_LEN {
                return None;
            }
            let candidate = &input[start..end];
            if !candidate.contains(&b':') {
                return None;
            }
            if !crate::ipv6::is_valid_ipv6(candidate) {
                return None;
            }
            (start, end)
        };

        // Must have /prefix
        if ip_end >= input.len() || input[ip_end] != b'/' {
            return None;
        }
        let mut pos = ip_end + 1;

        let prefix_start = pos;
        while pos < input.len() && input[pos].is_ascii_digit() {
            pos += 1;
        }
        let prefix_len = pos - prefix_start;
        if prefix_len == 0 || prefix_len > 3 {
            return None;
        }

        if prefix_len > 1 && input[prefix_start] == b'0' {
            return None;
        }

        let mut prefix: u16 = 0;
        for &b in &input[prefix_start..pos] {
            prefix = prefix * 10 + (b - b'0') as u16;
        }
        if prefix > 128 {
            return None;
        }

        // Boundary after: same rule as the IPv4 prefix — reject a digit or a
        // '.' followed by a digit, allow a sentence dot (`2001:db8::/32.`).
        if pos < input.len() {
            if input[pos].is_ascii_digit() {
                return None;
            }
            if input[pos] == b'.' && pos + 1 < input.len() && input[pos + 1].is_ascii_digit() {
                return None;
            }
        }

        Some(ip_start..pos)
    }
}

impl Finder for Cidr {
    fn line_agnostic(&self) -> bool {
        // Matches never contain a line terminator and `\n`/`\r` end every
        // walk exactly like the end of the input does.
        true
    }

    fn id(&self) -> &'static str {
        "cidr"
    }

    fn dispatchable(&self) -> bool {
        true
    }

    fn could_start_at(&self, byte: u8) -> bool {
        byte.is_ascii_hexdigit() || byte == b':' || byte == b'['
    }

    fn could_start_after(&self, prev: u8, cur: u8) -> bool {
        if cur == b'[' {
            return true;
        }
        let v6 = (cur.is_ascii_hexdigit() || cur == b':')
            && !(prev.is_ascii_alphanumeric() || prev == b':');
        let v4 = cur.is_ascii_digit() && !(prev.is_ascii_digit() || prev == b'.' || prev == b':');
        v6 || v4
    }

    fn could_continue_with(&self, cur: u8, next: u8) -> bool {
        cur == b'[' || next.is_ascii_hexdigit() || next == b':' || next == b'.'
    }

    fn anchor(&self) -> Option<Anchor> {
        // The whole address precedes the `/`, brackets included.
        Some(Anchor::new(
            ByteSet::from_bytes(b"/"),
            ByteSet::from_fn(|b| b.is_ascii_hexdigit() || matches!(b, b'.' | b':' | b'[' | b']')),
        ))
    }

    fn run_rules(&self) -> Vec<RunRule> {
        vec![
            RunRule::new(RunClass::Digit, 1, 3)
                .followed_by(b".")
                .then(RunClass::Digit, 1, 3)
                .followed_by(b"."),
            RunRule::new(RunClass::Hex, 1, 4)
                .followed_by(b":")
                .then(RunClass::Hex, 1, 4)
                .followed_by(b":")
                .then(RunClass::Hex, 0, 4)
                .followed_by(b":")
                .or_end(),
            RunRule::new(RunClass::Hex, 1, 4)
                .followed_by(b":")
                .then(RunClass::Hex, 0, 0)
                .followed_by(b":"),
        ]
    }

    fn try_at(&self, input: &[u8], pos: usize) -> Option<Range<usize>> {
        self.try_at_memo(input, pos, &mut Memo::default())
    }

    fn try_at_memo(&self, input: &[u8], pos: usize, memo: &mut Memo) -> Option<Range<usize>> {
        if input[pos].is_ascii_digit()
            && let Some(range) = Self::try_ipv4_cidr(input, pos)
        {
            return Some(range);
        }
        if (input[pos] == b'[' || input[pos].is_ascii_hexdigit() || input[pos] == b':')
            && let Some(range) = Self::try_ipv6_cidr(input, pos, memo)
        {
            return Some(range);
        }
        None
    }

    fn find(&self, s: &str) -> Option<Range<usize>> {
        let input = s.as_bytes();
        let mut idx = 0;

        while idx < input.len() {
            if input[idx].is_ascii_digit()
                && let Some(range) = Self::try_ipv4_cidr(input, idx)
            {
                return Some(range);
            }

            if (input[idx] == b'[' || input[idx].is_ascii_hexdigit() || input[idx] == b':')
                && let Some(range) = Self::try_ipv6_cidr(input, idx, &mut Memo::default())
            {
                return Some(range);
            }

            idx += 1;
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn id_should_return_cidr() {
        let finder = Cidr::default();
        assert_eq!("cidr", finder.id());
    }

    // IPv4 CIDR
    #[test]
    fn find_should_extract_ipv4_cidr() {
        let finder = Cidr::default();
        let input = "network 192.168.1.0/24 is local";
        let range = finder.find(input).unwrap();
        assert_eq!("192.168.1.0/24", &input[range]);
    }

    #[test]
    fn find_should_extract_class_a() {
        let finder = Cidr::default();
        let input = "10.0.0.0/8";
        let range = finder.find(input).unwrap();
        assert_eq!("10.0.0.0/8", &input[range]);
    }

    #[test]
    fn find_should_extract_host_route() {
        let finder = Cidr::default();
        let input = "host 10.0.0.1/32 route";
        let range = finder.find(input).unwrap();
        assert_eq!("10.0.0.1/32", &input[range]);
    }

    #[test]
    fn find_should_extract_default_route() {
        let finder = Cidr::default();
        let input = "0.0.0.0/0";
        let range = finder.find(input).unwrap();
        assert_eq!("0.0.0.0/0", &input[range]);
    }

    #[test]
    fn find_should_reject_prefix_over_32() {
        let finder = Cidr::default();
        assert!(finder.find("192.168.1.0/33").is_none());
    }

    #[test]
    fn find_should_reject_no_prefix() {
        let finder = Cidr::default();
        assert!(finder.find("only 192.168.1.0 here").is_none());
    }

    #[test]
    fn find_should_reject_invalid_octet() {
        let finder = Cidr::default();
        assert!(finder.find("256.168.1.0/24").is_none());
    }

    #[test]
    fn find_should_reject_leading_zero_octet() {
        let finder = Cidr::default();
        assert!(finder.find("192.168.01.0/24").is_none());
    }

    #[test]
    fn find_should_reject_leading_zero_prefix() {
        let finder = Cidr::default();
        assert!(finder.find("192.168.1.0/08").is_none());
    }

    #[test]
    fn find_should_reject_preceded_by_digit() {
        let finder = Cidr::default();
        assert!(finder.find("x1192.168.1.0/24").is_none());
    }

    #[test]
    fn find_should_reject_followed_by_digit() {
        let finder = Cidr::default();
        assert!(finder.find("192.168.1.0/245").is_none());
    }

    // IPv6 CIDR
    #[test]
    fn find_should_extract_ipv6_cidr() {
        let finder = Cidr::default();
        let input = "network 2001:db8::/32 configured";
        let range = finder.find(input).unwrap();
        assert_eq!("2001:db8::/32", &input[range]);
    }

    #[test]
    fn find_should_extract_ipv6_full_cidr() {
        let finder = Cidr::default();
        let input = "2001:0db8:85a3:0000:0000:8a2e:0370:7334/64";
        let range = finder.find(input).unwrap();
        assert_eq!("2001:0db8:85a3:0000:0000:8a2e:0370:7334/64", &input[range]);
    }

    #[test]
    fn find_should_extract_ipv6_loopback_cidr() {
        let finder = Cidr::default();
        let input = "::1/128";
        let range = finder.find(input).unwrap();
        assert_eq!("::1/128", &input[range]);
    }

    #[test]
    fn find_should_extract_ipv6_default_cidr() {
        let finder = Cidr::default();
        let input = "::/0";
        let range = finder.find(input).unwrap();
        assert_eq!("::/0", &input[range]);
    }

    #[test]
    fn find_should_reject_ipv6_prefix_over_128() {
        let finder = Cidr::default();
        assert!(finder.find("2001:db8::/129").is_none());
    }

    // Multiple
    #[test]
    fn find_should_extract_multiple_cidrs_iteratively() {
        let finder = Cidr::default();
        let input = "10.0.0.0/8 and 192.168.1.0/24";

        let mut results = Vec::new();
        let mut idx = 0;
        while idx < input.len() {
            if let Some(range) = finder.find(&input[idx..]) {
                results.push(&input[idx + range.start..idx + range.end]);
                idx += range.end;
            } else {
                break;
            }
        }

        assert_eq!(vec!["10.0.0.0/8", "192.168.1.0/24"], results);
    }

    #[test]
    fn find_should_handle_empty_input() {
        let finder = Cidr::default();
        assert!(finder.find("").is_none());
    }

    #[test]
    fn find_should_extract_cidr_at_start() {
        let finder = Cidr::default();
        let input = "10.0.0.0/8 is class A";
        let range = finder.find(input).unwrap();
        assert_eq!("10.0.0.0/8", &input[range]);
    }

    #[test]
    fn find_should_extract_cidr_at_end() {
        let finder = Cidr::default();
        let input = "subnet is 172.16.0.0/12";
        let range = finder.find(input).unwrap();
        assert_eq!("172.16.0.0/12", &input[range]);
    }

    #[test]
    fn try_at_ipv4_cidr() {
        let finder = Cidr::default();
        let input = b"192.168.1.0/24 rest";
        assert_eq!(finder.try_at(input, 0), Some(0..14));
    }

    #[test]
    fn try_at_ipv6_cidr() {
        let finder = Cidr::default();
        let input = b"2001:db8::/32 rest";
        assert_eq!(finder.try_at(input, 0), Some(0..13));
    }

    #[test]
    fn try_at_no_prefix() {
        let finder = Cidr::default();
        let input = b"192.168.1.0 no prefix";
        assert!(finder.try_at(input, 0).is_none());
    }

    #[test]
    fn try_at_non_digit() {
        let finder = Cidr::default();
        assert!(finder.try_at(b"abc", 0).is_none());
    }

    #[test]
    fn try_at_single_digit() {
        let finder = Cidr::default();
        assert!(finder.try_at(b"1", 0).is_none());
    }

    #[test]
    fn find_prefix_zero() {
        let finder = Cidr::default();
        let input = "0.0.0.0/0";
        let range = finder.find(input).unwrap();
        assert_eq!("0.0.0.0/0", &input[range]);
    }

    #[test]
    fn find_prefix_32() {
        let finder = Cidr::default();
        let input = "10.0.0.1/32";
        let range = finder.find(input).unwrap();
        assert_eq!("10.0.0.1/32", &input[range]);
    }

    #[test]
    fn find_rejects_prefix_with_leading_zero() {
        let finder = Cidr::default();
        assert!(finder.find("10.0.0.0/08").is_none());
    }

    #[test]
    fn find_ipv6_prefix_128() {
        let finder = Cidr::default();
        let input = "::1/128";
        let range = finder.find(input).unwrap();
        assert_eq!("::1/128", &input[range]);
    }

    #[test]
    fn find_ipv6_prefix_zero() {
        let finder = Cidr::default();
        let input = "::/0";
        let range = finder.find(input).unwrap();
        assert_eq!("::/0", &input[range]);
    }

    // --- Regression: could_start_at without redundant digit check ---

    #[test]
    fn could_start_at_digit() {
        let finder = Cidr::default();
        for b in b'0'..=b'9' {
            assert!(
                finder.could_start_at(b),
                "should start at digit {}",
                b as char
            );
        }
    }

    #[test]
    fn could_start_at_hex_alpha() {
        let finder = Cidr::default();
        for b in b'a'..=b'f' {
            assert!(finder.could_start_at(b), "should start at {}", b as char);
        }
        for b in b'A'..=b'F' {
            assert!(finder.could_start_at(b), "should start at {}", b as char);
        }
    }

    #[test]
    fn could_start_at_colon_bracket() {
        let finder = Cidr::default();
        assert!(finder.could_start_at(b':'));
        assert!(finder.could_start_at(b'['));
    }

    #[test]
    fn could_not_start_at_non_hex() {
        let finder = Cidr::default();
        assert!(!finder.could_start_at(b'g'));
        assert!(!finder.could_start_at(b' '));
        assert!(!finder.could_start_at(b'/'));
    }
}