zlob 1.3.3

SIMD optimized glob pattern matching library faster than glob crate
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
use crate::error::ZlobError;
use crate::ffi;
use crate::flags::ZlobFlags;
use std::ffi::{c_char, CString};
use std::ops::Index;
use std::slice;

/// Result of a `zlob()` call.
///
/// This type automatically frees the allocated memory when dropped.
/// It provides zero-copy access to matched paths via the `pathlen` array.
///
/// # Example
///
/// ```no_run
/// use zlob::{zlob, ZlobFlags};
///
/// if let Some(result) = zlob("**/*.rs", ZlobFlags::empty())? {
///     // Iterate over paths
///     for path in &result {
///         println!("{}", path);
///     }
///
///     // Index access
///     if !result.is_empty() {
///         println!("First: {}", &result[0]);
///     }
///
///     // Convert to Vec
///     let paths: Vec<String> = result.to_strings();
/// }
/// # Ok::<(), zlob::ZlobError>(())
/// ```
pub struct Zlob {
    inner: ffi::zlob_t,
}

impl Zlob {
    /// Returns the number of matched paths.
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.zlo_pathc
    }

    /// Returns `true` if no paths matched.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the path at the given index, or `None` if out of bounds.
    ///
    /// This is a zero-copy operation that uses `pathlen` to create
    /// a string slice without calling `strlen()`.
    #[inline]
    pub fn get(&self, index: usize) -> Option<&str> {
        if index >= self.len() {
            return None;
        }
        unsafe {
            let ptr = *self.inner.zlo_pathv.add(index) as *const u8;
            let len = *self.inner.zlo_pathlen.add(index);
            let bytes = slice::from_raw_parts(ptr, len);
            // SAFETY: zlob guarantees UTF-8 valid paths (they come from the filesystem)
            Some(std::str::from_utf8_unchecked(bytes))
        }
    }

    /// Returns an iterator over the matched paths.
    #[inline]
    pub fn iter(&self) -> ZlobIter<'_> {
        ZlobIter {
            zlob: self,
            front: 0,
            back: self.len(),
        }
    }

    /// Returns all paths as a vector of string slices.
    ///
    /// This is a zero-copy operation - the strings reference the internal buffer.
    pub fn as_strs(&self) -> Vec<&str> {
        self.iter().collect()
    }

    /// Converts to a vector of owned strings.
    ///
    /// This copies all path data into new `String` allocations.
    pub fn to_strings(&self) -> Vec<String> {
        self.iter().map(|s| s.to_string()).collect()
    }

    /// Returns raw pointers to path data for advanced zero-copy access.
    ///
    /// # Safety
    ///
    /// The returned slices are valid only while this `Zlob` instance exists.
    /// Do not use them after the `Zlob` is dropped.
    ///
    /// # Returns
    ///
    /// A tuple of `(pathv, pathlen)` where:
    /// - `pathv[i]` is a pointer to the i-th path (null-terminated)
    /// - `pathlen[i]` is the length of the i-th path (excluding null terminator)
    pub unsafe fn raw_parts(&self) -> (&[*mut c_char], &[usize]) {
        let pathv = slice::from_raw_parts(self.inner.zlo_pathv, self.len());
        let pathlen = slice::from_raw_parts(self.inner.zlo_pathlen, self.len());
        (pathv, pathlen)
    }
}

impl Drop for Zlob {
    fn drop(&mut self) {
        unsafe {
            ffi::zlobfree(&mut self.inner);
        }
    }
}

impl Index<usize> for Zlob {
    type Output = str;

    /// Returns the path at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `index >= self.len()`.
    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a> IntoIterator for &'a Zlob {
    type Item = &'a str;
    type IntoIter = ZlobIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

// SAFETY: Zlob owns its data and can be sent between threads
unsafe impl Send for Zlob {}
// SAFETY: Zlob's methods only take &self and don't mutate shared state
unsafe impl Sync for Zlob {}

/// Iterator over `Zlob` results.
///
/// This iterator yields `&str` references to each matched path.
/// It implements `ExactSizeIterator` and `DoubleEndedIterator`.
pub struct ZlobIter<'a> {
    zlob: &'a Zlob,
    front: usize,
    back: usize,
}

impl<'a> Iterator for ZlobIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        if self.front >= self.back {
            return None;
        }
        let item = self.zlob.get(self.front)?;
        self.front += 1;
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.back - self.front;
        (remaining, Some(remaining))
    }

    fn count(self) -> usize {
        self.back - self.front
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        if n >= self.back - self.front {
            self.front = self.back;
            return None;
        }
        self.front += n;
        self.next()
    }

    fn last(mut self) -> Option<Self::Item> {
        self.next_back()
    }
}

impl ExactSizeIterator for ZlobIter<'_> {
    fn len(&self) -> usize {
        self.back - self.front
    }
}

impl DoubleEndedIterator for ZlobIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.front >= self.back {
            return None;
        }
        self.back -= 1;
        self.zlob.get(self.back)
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        if n >= self.back - self.front {
            self.front = self.back;
            return None;
        }
        self.back -= n;
        self.next_back()
    }
}

impl std::iter::FusedIterator for ZlobIter<'_> {}

/// Perform glob pattern matching on the filesystem.
///
/// This function finds all files matching the given glob pattern.
///
/// # Arguments
///
/// * `pattern` - The glob pattern to match (e.g., `"**/*.rs"`, `"src/{lib,main}.rs"`)
/// * `flags` - Flags controlling the matching behavior
///
/// # Returns
///
/// * `Ok(Some(Zlob))` - Matches were found
/// * `Ok(None)` - No matches found (pattern is valid but no files match)
/// * `Err(ZlobError)` - An error occurred (out of memory, read error, etc.)
///
/// # Example
///
/// ```no_run
/// use zlob::{zlob, ZlobFlags};
///
/// // Find all Rust files recursively
/// if let Some(result) = zlob("**/*.rs", ZlobFlags::RECOMMENDED)? {
///     for path in &result {
///         println!("{}", path);
///     }
/// } else {
///     println!("No matches found");
/// }
///
/// // Enable git ignore support
/// let result = zlob("src/{lib,main}.rs", ZlobFlags::RECOMMENDED | ZlobFlags::GITIGNORE)?;
///
/// assert!(result.is_some());
/// # Ok::<(), zlob::ZlobError>(())
/// ```
///
/// # Supported Patterns
///
/// We support all the varieties of glob pattern supported by rust's `glob` crate, posix `glob(3)`,
/// glibc `glob()` implementation and many more.
///
/// Here are some of the most common patterns:
///
/// | Pattern | Description |
/// |---------|-------------|
/// | `*` | Matches any string (including empty) |
/// | `?` | Matches any single character |
/// | `[abc]` | Matches one character from the set |
/// | `[!abc]` | Matches one character NOT in the set |
/// | `[a-z]` | Matches one character in the range |
/// | `**` | Matches zero or more path components (recursive) |
/// | `{a,b}` | Matches alternatives (requires `BRACE` flag) |
/// | `~` | Home directory (requires `TILDE` flag) |
pub fn zlob(pattern: &str, flags: ZlobFlags) -> Result<Option<Zlob>, ZlobError> {
    let pattern_c = CString::new(pattern).map_err(|_| ZlobError::Aborted)?;
    let mut inner = ffi::zlob_t::default();

    let result = unsafe { ffi::zlob(pattern_c.as_ptr(), flags.bits(), None, &mut inner) };

    match ZlobError::from_code(result) {
        Ok(true) => Ok(Some(Zlob { inner })),
        Ok(false) => Ok(None), // No matches
        Err(err) => Err(err),
    }
}

/// Perform glob pattern matching within a specific base directory.
///
/// This function is similar to `zlob()` but operates relative to the specified
/// `base_path` instead of the current working directory.
///
/// # Arguments
///
/// * `base_path` - Absolute path to the base directory (must start with '/')
/// * `pattern` - The glob pattern to match (relative to base_path)
/// * `flags` - Flags controlling the matching behavior
///
/// # Returns
///
/// * `Ok(Some(Zlob))` - Matches were found
/// * `Ok(None)` - No matches found (pattern is valid but no files match)
/// * `Err(ZlobError::Aborted)` - base_path is not an absolute path, or another error occurred
/// * `Err(ZlobError::NoSpace)` - Out of memory
///
/// # Example
///
/// ```no_run
/// use zlob::{zlob_at, ZlobFlags};
///
/// // Find all Rust files in /home/user/project
/// if let Some(result) = zlob_at("/home/user/project", "**/*.rs", ZlobFlags::RECOMMENDED)? {
///     for path in &result {
///         println!("{}", path);  // Paths are relative to /home/user/project
///     }
/// }
/// # Ok::<(), zlob::ZlobError>(())
/// ```
pub fn zlob_at(
    base_path: &str,
    pattern: &str,
    flags: ZlobFlags,
) -> Result<Option<Zlob>, ZlobError> {
    let base_path_c = CString::new(base_path).map_err(|_| ZlobError::Aborted)?;
    let pattern_c = CString::new(pattern).map_err(|_| ZlobError::Aborted)?;
    let mut inner = ffi::zlob_t::default();

    let result = unsafe {
        ffi::zlob_at(
            base_path_c.as_ptr(),
            pattern_c.as_ptr(),
            flags.bits(),
            None,
            &mut inner,
        )
    };

    match ZlobError::from_code(result) {
        Ok(true) => Ok(Some(Zlob { inner })),
        Ok(false) => Ok(None), // No matches
        Err(err) => Err(err),
    }
}

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

    #[test]
    fn test_zlob_basic() {
        // this relies on the cwd being rust/ folder itself
        let result = zlob("Cargo.toml", ZlobFlags::empty());
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.is_some());
        let result = result.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(&result[0], "Cargo.toml");
    }

    #[test]
    fn test_zlob_no_match() {
        let result = zlob("nonexistent_file_12345.xyz", ZlobFlags::empty());
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_zlob_iterator() {
        let result = zlob("*.toml", ZlobFlags::empty()).unwrap().unwrap();
        let paths: Vec<&str> = result.iter().collect();
        assert!(paths.contains(&"Cargo.toml"));
    }

    #[test]
    fn test_zlob_double_ended_iterator() {
        let result = zlob("*.toml", ZlobFlags::empty()).unwrap().unwrap();
        let mut iter = result.iter();
        let first = iter.next();
        let last = iter.next_back();

        assert!(first.is_some());
        assert!(last.is_none()); // only single toml file

        let result = zlob("src/*.rs", ZlobFlags::empty()).unwrap().unwrap();
        let mut iter = result.iter();

        let first = iter.next().unwrap();
        let last = iter.next_back().unwrap();

        assert_ne!(first, last);
    }

    #[test]
    fn test_zlob_exact_size_iterator() {
        let result = zlob("*.toml", ZlobFlags::empty()).unwrap().unwrap();
        let iter = result.iter();
        assert_eq!(iter.len(), 1);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_zlob_brace_expansion() {
        // both individual and brace combination work correctly
        let result = zlob("*.toml", ZlobFlags::empty()).unwrap().unwrap();
        assert!(result.len() >= 1);

        let result = zlob("*.lock", ZlobFlags::empty()).unwrap().unwrap();
        assert!(result.len() >= 1);

        let result = zlob("*.{toml,lock}", ZlobFlags::empty()).unwrap();
        assert!(result.is_none());

        let result = zlob("*.{toml,lock}", ZlobFlags::BRACE).unwrap().unwrap();
        assert!(matches!(result.len(), 2));
    }

    #[test]
    fn test_recursive_globbing() {
        // based on the rust/ folder contents
        // Need DOUBLESTAR_RECURSIVE for ** to work recursively
        let result = zlob(
            "**/*.{rs,toml}",
            ZlobFlags::BRACE | ZlobFlags::DOUBLESTAR_RECURSIVE,
        )
        .unwrap()
        .unwrap();

        for path in &result {
            println!("{}", path);
        }

        // At least 8 files: Cargo.toml, build.rs, src/*.rs (5 files), Cargo.lock
        // May be more if examples exist
        assert!(result.len() >= 8);
    }

    #[test]
    fn test_extglob_filesystem_negation() {
        use std::fs::File;
        use tempfile::tempdir;

        // Create temp directory with test files
        let dir = tempdir().unwrap();
        let dir_path = dir.path();

        // Create test files: app.js, app.ts, app.css, app.html
        File::create(dir_path.join("app.js")).unwrap();
        File::create(dir_path.join("app.ts")).unwrap();
        File::create(dir_path.join("app.css")).unwrap();
        File::create(dir_path.join("app.html")).unwrap();

        // Test !(js|ts) - should match app.css and app.html but NOT app.js or app.ts
        let pattern = dir_path.join("app.!(js|ts)");
        let pattern_str = pattern.to_str().unwrap();

        let result = zlob(pattern_str, ZlobFlags::EXTGLOB).unwrap().unwrap();

        assert_eq!(result.len(), 2);
        let paths: Vec<&str> = result.iter().collect();

        // Should contain css and html
        assert!(paths.iter().any(|p| p.ends_with("app.css")));
        assert!(paths.iter().any(|p| p.ends_with("app.html")));

        // Should NOT contain js or ts
        assert!(!paths.iter().any(|p| p.ends_with("app.js")));
        assert!(!paths.iter().any(|p| p.ends_with("app.ts")));
    }

    #[test]
    fn test_extglob_filesystem_exactly_one() {
        use std::fs::File;
        use tempfile::tempdir;

        // Create temp directory with test files
        let dir = tempdir().unwrap();
        let dir_path = dir.path();

        // Create test files: foo.txt, bar.txt, baz.txt, qux.txt
        File::create(dir_path.join("foo.txt")).unwrap();
        File::create(dir_path.join("bar.txt")).unwrap();
        File::create(dir_path.join("baz.txt")).unwrap();
        File::create(dir_path.join("qux.txt")).unwrap();

        // Test @(foo|bar).txt - should match exactly foo.txt and bar.txt
        let pattern = dir_path.join("@(foo|bar).txt");
        let pattern_str = pattern.to_str().unwrap();

        let result = zlob(pattern_str, ZlobFlags::EXTGLOB).unwrap().unwrap();

        assert_eq!(result.len(), 2);
        let paths: Vec<&str> = result.iter().collect();

        // Should contain foo.txt and bar.txt
        assert!(paths.iter().any(|p| p.ends_with("foo.txt")));
        assert!(paths.iter().any(|p| p.ends_with("bar.txt")));

        // Should NOT contain baz.txt or qux.txt
        assert!(!paths.iter().any(|p| p.ends_with("baz.txt")));
        assert!(!paths.iter().any(|p| p.ends_with("qux.txt")));
    }
}