decmpfs 0.1.3

Apply OS-level transparent filesystem compression (APFS decmpfs / btrfs / NTFS) to a file in place.
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
//! The install-time gate: decide whether a given file should be OS-compressed.
//!
//! A `Gate` is a glob AND/OR a size predicate. The PM helper calls
//! `gate.matches(name, len)` after it knows the addon's name + decoded length and
//! only hands the bytes to `compress_bytes` when both predicates pass. Both halves
//! are optional; a `Gate::default()` matches the fleet default `**/*.node` with no
//! size floor.
//!
//! The size predicate parses a human string (`">"`/`">="` + a number with an
//! optional unit) so a manifest can carry `compress = ">= 1MB"` verbatim. Units are
//! case-insensitive and cover both the decimal (`KB`/`MB`/`GB` = 1000ⁿ) and binary
//! (`KiB`/`MiB`/`GiB` = 1024ⁿ) families; a bare number is bytes.

/// A `>`/`>=` comparison against a byte threshold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizePredicate {
  /// `len > threshold`.
  GreaterThan(u64),
  /// `len >= threshold`.
  AtLeast(u64),
}

impl SizePredicate {
  /// True when `len` satisfies the comparison.
  pub fn matches(&self, len: u64) -> bool {
    match *self {
      SizePredicate::GreaterThan(t) => len > t,
      SizePredicate::AtLeast(t) => len >= t,
    }
  }

  /// Parse `"> 1MB"` / `">=1024"` / `"> 4 KiB"` into a predicate. Whitespace is
  /// optional everywhere; the operator must be `>` or `>=`; the unit (if any) is
  /// case-insensitive.
  pub fn parse(spec: &str) -> Result<SizePredicate, GateParseError> {
    let trimmed = spec.trim();
    let (at_least, rest) = if let Some(rest) = trimmed.strip_prefix(">=") {
      (true, rest)
    } else if let Some(rest) = trimmed.strip_prefix('>') {
      (false, rest)
    } else {
      return Err(GateParseError::Operator);
    };
    let bytes = parse_size(rest.trim())?;
    Ok(if at_least {
      SizePredicate::AtLeast(bytes)
    } else {
      SizePredicate::GreaterThan(bytes)
    })
  }
}

/// Parse a size literal (`"1MB"`, `"4 KiB"`, `"512"`) into a byte count. A bare
/// number is bytes; a unit suffix scales it. Decimal units are powers of 1000,
/// binary units (the `i` forms) powers of 1024.
fn parse_size(spec: &str) -> Result<u64, GateParseError> {
  let spec = spec.trim();
  if spec.is_empty() {
    return Err(GateParseError::Number);
  }
  // Split the leading digit run from the trailing unit.
  let split = spec
    .find(|c: char| !c.is_ascii_digit() && c != '_')
    .unwrap_or(spec.len());
  let (digits, unit) = spec.split_at(split);
  let number: u64 = digits
    .replace('_', "")
    .parse()
    .map_err(|_| GateParseError::Number)?;
  let multiplier = match unit.trim().to_ascii_lowercase().as_str() {
    "" | "b" => 1,
    "kb" => 1_000,
    "mb" => 1_000_000,
    "gb" => 1_000_000_000,
    "kib" => 1024,
    "mib" => 1024 * 1024,
    "gib" => 1024 * 1024 * 1024,
    _ => return Err(GateParseError::Unit),
  };
  number
    .checked_mul(multiplier)
    .ok_or(GateParseError::Overflow)
}

/// Why a `Gate` / `SizePredicate` string failed to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GateParseError {
  /// The size predicate did not start with `>` or `>=`.
  Operator,
  /// The numeric portion was missing or not an integer.
  Number,
  /// The unit suffix was not one of B/KB/MB/GB/KiB/MiB/GiB.
  Unit,
  /// The number × unit overflowed u64.
  Overflow,
}

impl std::fmt::Display for GateParseError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let msg = match self {
      GateParseError::Operator => "size predicate must start with '>' or '>='",
      GateParseError::Number => "size predicate needs an integer (e.g. '> 1MB')",
      GateParseError::Unit => "unknown size unit (use B/KB/MB/GB/KiB/MiB/GiB)",
      GateParseError::Overflow => "size predicate overflows a 64-bit byte count",
    };
    f.write_str(msg)
  }
}

impl std::error::Error for GateParseError {}

/// The install-time gate: an optional glob AND an optional size predicate. A file
/// matches only if BOTH present predicates pass (an absent half is vacuously true).
/// `Gate::default()` is the fleet default — glob `**/*.node`, no size floor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Gate {
  glob: Option<String>,
  size: Option<SizePredicate>,
}

impl Default for Gate {
  fn default() -> Self {
    Gate {
      glob: Some(DEFAULT_GLOB.to_string()),
      size: None,
    }
  }
}

/// The fleet default — every native addon, regardless of size.
pub const DEFAULT_GLOB: &str = "**/*.node";

impl Gate {
  /// A gate that matches everything (no glob, no size floor). Useful when the
  /// caller has already selected the file and just wants the one-pass writer.
  pub fn any() -> Self {
    Gate {
      glob: None,
      size: None,
    }
  }

  /// Build a gate from an optional glob and an optional size-predicate string. A
  /// `None` glob matches any name; a `None`/empty size string applies no floor.
  pub fn new(glob: Option<&str>, size: Option<&str>) -> Result<Gate, GateParseError> {
    let size = match size {
      None => None,
      Some(s) if s.trim().is_empty() => None,
      Some(s) => Some(SizePredicate::parse(s)?),
    };
    Ok(Gate {
      glob: glob.map(str::to_string),
      size,
    })
  }

  /// Replace the glob (chainable builder).
  pub fn with_glob(mut self, glob: &str) -> Self {
    self.glob = Some(glob.to_string());
    self
  }

  /// Replace the size predicate (chainable builder).
  pub fn with_size(mut self, size: SizePredicate) -> Self {
    self.size = Some(size);
    self
  }

  /// The glob pattern, if any.
  pub fn glob(&self) -> Option<&str> {
    self.glob.as_deref()
  }

  /// The size predicate, if any.
  pub fn size(&self) -> Option<SizePredicate> {
    self.size
  }

  /// True when `name` matches the glob (if set) AND `len` satisfies the size
  /// predicate (if set). The name is matched against the full path the caller
  /// passes — pass a `/`-normalized path so `**` segments line up.
  pub fn matches(&self, name: &str, len: u64) -> bool {
    if let Some(glob) = &self.glob {
      if !glob_match(glob, name) {
        return false;
      }
    }
    if let Some(size) = &self.size {
      if !size.matches(len) {
        return false;
      }
    }
    true
  }
}

/// A small glob matcher covering the subset the gate needs: `*` (any run within a
/// path segment, no `/`), `**` (any run across segments, including `/`), and `?`
/// (one non-`/` char). Literal bytes match themselves. No char classes — the gate
/// patterns are simple suffix/segment globs like `**/*.node`.
pub fn glob_match(pattern: &str, text: &str) -> bool {
  glob_inner(pattern.as_bytes(), text.as_bytes())
}

/// Recursive matcher — clean handling of nested stars (a `*` inside a `**` tail,
/// like `**/*.node`) that a single backtrack slot can't express. The pattern set
/// is small (suffix/segment globs), so the recursion depth is the number of stars,
/// not the input length.
fn glob_inner(pat: &[u8], text: &[u8]) -> bool {
  // Pattern exhausted: match iff text is too.
  let Some(&pc) = pat.first() else {
    return text.is_empty();
  };
  match pc {
    b'*' => {
      let double = pat.get(1) == Some(&b'*');
      if double {
        // `**` matches any run including `/`. If immediately followed by `/`, that
        // slash may also collapse to nothing (a/**/b ⊇ a/b).
        let after = &pat[2..];
        let collapsed = after.strip_prefix(b"/").unwrap_or(after);
        // Zero-width match (with the optional `/` collapse), then every longer run.
        if glob_inner(collapsed, text) || glob_inner(after, text) {
          return true;
        }
        for i in 0..text.len() {
          if glob_inner(after, &text[i + 1..]) || glob_inner(collapsed, &text[i + 1..]) {
            return true;
          }
        }
        false
      } else {
        // `*` matches a run within one path segment — never a `/`.
        let rest = &pat[1..];
        if glob_inner(rest, text) {
          return true;
        }
        for i in 0..text.len() {
          if text[i] == b'/' {
            break;
          }
          if glob_inner(rest, &text[i + 1..]) {
            return true;
          }
        }
        false
      }
    }
    b'?' => match text.first() {
      Some(&c) if c != b'/' => glob_inner(&pat[1..], &text[1..]),
      _ => false,
    },
    c => match text.first() {
      Some(&t) if t == c => glob_inner(&pat[1..], &text[1..]),
      _ => false,
    },
  }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
  use proptest::prelude::*;

  use super::*;

  proptest! {
    // Tier 1 — the size-predicate parser never panics on ANY string. `spec` is a
    // manifest-supplied value (`compress = ">= 1MB"`), so arbitrary text reaches it;
    // a graceful `Err(GateParseError)` is the only non-`Ok` outcome.
    #[test]
    fn size_predicate_parse_never_panics(s in ".*") {
      let _ = SizePredicate::parse(&s);
    }

    // Round-trip: a bare-number spec parses back to the exact threshold under both
    // operators (formatting the struct's value then reparsing is the identity).
    #[test]
    fn bare_number_spec_round_trips(n in any::<u64>()) {
      prop_assert_eq!(
        SizePredicate::parse(&format!(">{n}")),
        Ok(SizePredicate::GreaterThan(n))
      );
      prop_assert_eq!(
        SizePredicate::parse(&format!(">= {n}")),
        Ok(SizePredicate::AtLeast(n))
      );
    }

    // Oracle: a decimal-unit literal equals `number * 1000^k` whenever it can't
    // overflow (bounded so the product stays inside u64).
    #[test]
    fn decimal_unit_scales_like_the_oracle(n in 0u64..=1_000_000) {
      prop_assert_eq!(parse_size(&format!("{n}KB")), Ok(n * 1_000));
      prop_assert_eq!(parse_size(&format!("{n}MB")), Ok(n * 1_000_000));
      prop_assert_eq!(parse_size(&format!("{n}kib")), Ok(n * 1024));
    }

    // `Gate::matches` never panics on an untrusted path text of any bytes/length —
    // the path segment can carry a downloaded package's name.
    #[test]
    fn gate_matches_never_panics(text in ".*", len in any::<u64>()) {
      let _ = Gate::default().matches(&text, len);
      let _ = Gate::any().matches(&text, len);
    }

    // Oracle: a metachar-free pattern is a plain literal — it matches iff the text
    // is byte-identical.
    #[test]
    fn literal_glob_matches_iff_equal(
      lit in "[a-zA-Z0-9._-]{0,32}",
      text in "[a-zA-Z0-9._-]{0,32}",
    ) {
      prop_assert_eq!(glob_match(&lit, &text), lit == text);
    }

    // `**` is the match-everything pattern: it accepts any path text, including one
    // that spans separators.
    #[test]
    fn double_star_matches_any_path(text in ".*") {
      prop_assert!(glob_match("**", &text));
    }

    // The matcher terminates and never panics on arbitrary pattern AND text. The
    // pattern alphabet is bounded (few metachars, short) so this Tier-1 property
    // can't wander into the algorithmic-complexity search that Tier 2 (the
    // `gate_glob` fuzz target) owns.
    #[test]
    fn glob_match_never_panics(
      pattern in "[a-z/.?*]{0,12}",
      text in "[a-z/.]{0,24}",
    ) {
      let _ = glob_match(&pattern, &text);
    }
  }

  #[test]
  fn parses_units_case_insensitively() {
    assert_eq!(parse_size("512"), Ok(512));
    assert_eq!(parse_size("512B"), Ok(512));
    assert_eq!(parse_size("1kb"), Ok(1_000));
    assert_eq!(parse_size("1KB"), Ok(1_000));
    assert_eq!(parse_size("2MB"), Ok(2_000_000));
    assert_eq!(parse_size("3gb"), Ok(3_000_000_000));
    assert_eq!(parse_size("1KiB"), Ok(1024));
    assert_eq!(parse_size("1mib"), Ok(1024 * 1024));
    assert_eq!(parse_size("1GiB"), Ok(1024 * 1024 * 1024));
    // Whitespace + digit separators tolerated.
    assert_eq!(parse_size("1 MB"), Ok(1_000_000));
    assert_eq!(parse_size("1_000"), Ok(1_000));
  }

  #[test]
  fn rejects_bad_size_literals() {
    assert_eq!(parse_size(""), Err(GateParseError::Number));
    assert_eq!(parse_size("MB"), Err(GateParseError::Number));
    assert_eq!(parse_size("10PB"), Err(GateParseError::Unit));
    assert_eq!(
      parse_size("99999999999999999999GB"),
      Err(GateParseError::Number)
    );
    assert_eq!(
      parse_size("18446744073709551615KB"),
      Err(GateParseError::Overflow)
    );
  }

  #[test]
  fn parses_predicate_operators() {
    assert_eq!(
      SizePredicate::parse("> 1MB"),
      Ok(SizePredicate::GreaterThan(1_000_000))
    );
    assert_eq!(
      SizePredicate::parse(">=1MB"),
      Ok(SizePredicate::AtLeast(1_000_000))
    );
    assert_eq!(
      SizePredicate::parse("  >=  4 KiB "),
      Ok(SizePredicate::AtLeast(4096))
    );
    assert_eq!(SizePredicate::parse("1MB"), Err(GateParseError::Operator));
    assert_eq!(SizePredicate::parse("< 1MB"), Err(GateParseError::Operator));
  }

  #[test]
  fn predicate_comparison_is_exact_at_the_boundary() {
    let gt = SizePredicate::GreaterThan(1000);
    assert!(!gt.matches(1000));
    assert!(gt.matches(1001));
    let ge = SizePredicate::AtLeast(1000);
    assert!(ge.matches(1000));
    assert!(!ge.matches(999));
  }

  #[test]
  fn glob_matches_node_addons_anywhere() {
    assert!(glob_match(
      "**/*.node",
      "node_modules/foo/build/Release/addon.node"
    ));
    assert!(glob_match("**/*.node", "addon.node"));
    assert!(glob_match("*.node", "addon.node"));
    // A single * must not cross a path separator.
    assert!(!glob_match("*.node", "dir/addon.node"));
    assert!(!glob_match("**/*.node", "addon.so"));
  }

  #[test]
  fn glob_handles_question_and_literal_and_double_star_edges() {
    assert!(glob_match("a?c", "abc"));
    assert!(!glob_match("a?c", "a/c"));
    assert!(glob_match("**", "any/deep/path"));
    assert!(glob_match("a/**/b", "a/x/y/b"));
    assert!(glob_match("a/**/b", "a/b"));
    assert!(glob_match("exact", "exact"));
    assert!(!glob_match("exact", "exacted"));
    // Trailing star eats the rest.
    assert!(glob_match("pre*", "prefix"));
  }

  #[test]
  fn gate_default_is_node_glob_no_floor() {
    let g = Gate::default();
    assert_eq!(g.glob(), Some("**/*.node"));
    assert_eq!(g.size(), None);
    assert!(g.matches("build/Release/x.node", 10));
    assert!(!g.matches("build/Release/x.so", 10));
  }

  #[test]
  fn gate_requires_both_halves() {
    let g = Gate::new(Some("**/*.node"), Some(">= 1MB")).unwrap();
    assert!(g.matches("a/b.node", 2_000_000));
    // Right name, too small.
    assert!(!g.matches("a/b.node", 500_000));
    // Big enough, wrong name.
    assert!(!g.matches("a/b.so", 2_000_000));
  }

  #[test]
  fn gate_any_matches_everything() {
    let g = Gate::any();
    assert!(g.matches("whatever.xyz", 0));
    assert_eq!(g.glob(), None);
    assert_eq!(g.size(), None);
  }

  #[test]
  fn gate_new_treats_empty_size_as_no_floor() {
    let g = Gate::new(None, Some("   ")).unwrap();
    assert_eq!(g.size(), None);
    assert!(g.matches("anything", 0));
  }

  #[test]
  fn gate_builders_chain() {
    let g = Gate::any()
      .with_glob("**/*.dylib")
      .with_size(SizePredicate::GreaterThan(100));
    assert!(g.matches("a/b.dylib", 200));
    assert!(!g.matches("a/b.dylib", 50));
  }

  #[test]
  fn gate_new_propagates_parse_errors() {
    assert_eq!(Gate::new(None, Some("nope")), Err(GateParseError::Operator));
  }

  #[test]
  fn gate_new_with_a_glob_and_no_size_applies_no_floor() {
    // The `None` size arm of Gate::new — a glob with no size predicate.
    let g = Gate::new(Some("**/*.node"), None).unwrap();
    assert_eq!(g.size(), None);
    assert!(g.matches("a/b.node", 1));
    assert!(!g.matches("a/b.so", 1));
  }

  #[test]
  fn single_star_never_spans_a_separator() {
    // A single `*` matches a run within one segment and must stop at a `/`.
    let g = Gate::new(Some("a*c"), None).unwrap();
    assert!(g.matches("ac", 0), "the star matches a zero-width run");
    assert!(g.matches("abc", 0), "matches within one segment");
    assert!(!g.matches("ab/c", 0), "a single * never crosses a /");
  }

  #[test]
  fn parse_error_display_is_distinct() {
    let msgs: Vec<String> = [
      GateParseError::Operator,
      GateParseError::Number,
      GateParseError::Unit,
      GateParseError::Overflow,
    ]
    .iter()
    .map(ToString::to_string)
    .collect();
    // All four messages are non-empty and unique.
    assert!(msgs.iter().all(|m| !m.is_empty()));
    let mut sorted = msgs.clone();
    sorted.sort();
    sorted.dedup();
    assert_eq!(sorted.len(), 4);
  }
}