use std::path::{Path, PathBuf};
const NEEDLES: &[&str] = &[
"fs::write(",
"File::create(",
".create_new(",
"create_dir_all(",
"create_dir(",
"mkdirat(",
"openat(",
"fs::set_permissions(",
"fs::rename(",
"renameat(",
"renameat_with(",
"fs::linkat(",
"unlinkat(",
"remove_file(",
"fs::copy(",
"hard_link(",
"remove_dir(",
"remove_dir_all(",
"tempfile_in(",
"make_in(",
".persist(",
"persist_noclobber(",
"fs::symlink(",
"symlinkat(",
"soft_link(",
"symlink_file(",
"symlink_dir(",
];
const ALLOWED_RAW_WRITES: &[(&str, &str, usize, &str)] = &[
(
"watch.rs",
".create_new(",
1,
"the readiness marker a debug build creates for the test suite, in `mod \
ready_trigger` (#390): created new at <path>.tmp, never through an entry already \
there, then renamed — already atomic",
),
(
"watch.rs",
"fs::rename(",
1,
"the readiness marker a debug build creates for the test suite, in `mod \
ready_trigger` (#390): <path>.tmp, created new, renamed onto the marker path an \
absolute environment variable names — the rename is its atomic step",
),
(
"watch.rs",
"remove_file(",
1,
"the readiness marker a debug build creates for the test suite, in `mod \
ready_trigger` (#390): an entry already at <path>.tmp — a leftover, or a planted \
link, the entry itself and never what a link points to — removed before the \
marker is created new once more; no file mds writes",
),
(
"write.rs",
"create_dir_all(",
2,
"the primitive creates a missing anchor by path, as the user typed it, in its unix \
and its Windows arm (#160); nothing below the anchor is created this way",
),
(
"write.rs",
"create_dir(",
1,
"the primitive's Windows arm creates a missing directory below the anchor by path, \
once its parent is checked not to be a link — the residual SECURITY.md documents \
(#160)",
),
(
"write.rs",
"mkdirat(",
1,
"the primitive's unix walk creates a missing directory below the anchor in the one \
above it (#160)",
),
(
"write.rs",
"openat(",
6,
"the primitive's unix walk: the anchor, and each directory below it without \
following a symlink — one call each, made again once the directory is created, \
or to read where a search-only open is refused — the directory a rewrite's \
rename was made in, opened again to read so it can be synced, the temporary \
file, created new without following one, the file a rewrite reads again before \
it replaces it, or a removal's proof reads before it is removed, opened \
read-only without following one, and the file a new file's commit writes in \
place on a filesystem without hard links, created new without following one \
(#160)",
),
(
"write.rs",
"renameat(",
1,
"the primitive's unix tail: the temporary file renamed over the target in the \
directory the walk opened (#160)",
),
(
"write.rs",
"renameat_with(",
1,
"a new file's commit (`mds init` without `--force`): the temporary file renamed \
onto the target in the directory the walk opened, never over a file there \
(#160)",
),
(
"write.rs",
"fs::linkat(",
1,
"a new file's commit where no rename that never replaces is to be had: the \
temporary file linked to the target in the directory the walk opened, which \
fails on a file there (#160)",
),
(
"write.rs",
"unlinkat(",
3,
"the temporary file's guard: a temporary file not renamed over its target — a \
failed write's, or a linked one's — removed from the directory the walk opened; \
`remove_proven`'s unix arm: a file proven, removed from the directory the walk \
opened while its name is still that file; and a new file written in place whose \
write failed part-way, removed from that directory while its name is still the \
file it created (#160)",
),
(
"write.rs",
"remove_file(",
1,
"`remove_proven`'s Windows arm: a file proven, removed by path once each directory \
below the anchor is checked not to be a link — the residual SECURITY.md documents \
(#160)",
),
(
"write.rs",
"make_in(",
1,
"the primitive's Windows arm: the temporary file, given a name of tempfile's beside \
the target in the directory the walk checked (#160)",
),
(
"write.rs",
".create_new(",
1,
"the primitive's Windows arm: the temporary file `make_in` names, created new — a \
plain file, never one tempfile marks temporary, which a rename by std would leave \
marked (#160)",
),
(
"write.rs",
"fs::rename(",
1,
"the primitive's Windows arm: the temporary file renamed over the target by path, \
once the target is checked, when the commit may replace it — std's rename, which \
replaces a file another program holds open where tempfile's `persist` fails; the \
primitive pin holds it in `mod windows` (#160)",
),
(
"write.rs",
"persist_noclobber(",
1,
"a new file's commit on Windows: the temporary file moved onto the target by path \
without replacing, which fails on a file there (#160)",
),
];
const LICENCE_SCOPES: &[(&str, &str)] = &[("watch.rs", "ready_trigger")];
#[test]
fn write_sites_are_funnelled() {
let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let files = rust_files(&src_dir);
assert!(
files.len() >= 5,
"non-vacuity: expected to walk at least 5 source files under {}, found {}",
src_dir.display(),
files.len()
);
let mut violations: Vec<String> = Vec::new();
let mut allowed_seen = vec![0usize; ALLOWED_RAW_WRITES.len()];
let mut durability_pin_checked = false;
for file in &files {
let name = file
.file_name()
.and_then(|n| n.to_str())
.expect("source file names are UTF-8");
let raw = std::fs::read_to_string(file).expect("source must be readable");
let code = blank_cfg_test_items(&mask_comments_and_strings(&raw));
if name == "write.rs" {
let pins = primitive_pin_violations(&code);
assert!(
pins.is_empty(),
"the write primitive's tail moved — the funnel guard is pointless if the \
choke point stops being durable or anchored:\n{}",
pins.join("\n")
);
durability_pin_checked = true;
}
violations.extend(file_violations(name, &code, &mut allowed_seen));
}
assert!(
durability_pin_checked,
"non-vacuity: write.rs was never scanned — the walk did not reach the choke point"
);
let dead: Vec<String> = ALLOWED_RAW_WRITES
.iter()
.zip(&allowed_seen)
.filter(|((_, _, max, _), seen)| *seen != max)
.map(|((f, n, max, _), seen)| format!(" {f}: `{n}` expected {max} hit(s), found {seen}"))
.collect();
assert!(
dead.is_empty(),
"allow-list entry is dead or drifted ({} entr(ies)). Update ALLOWED_RAW_WRITES \
to match reality — a stale entry is a licence for a raw write nobody reviewed.\n{}",
dead.len(),
dead.join("\n")
);
assert!(
violations.is_empty(),
"raw write sites outside the atomic funnel ({} found).\n{}\n\n\
Route the write through `crate::write::atomic_write_file` — `Parents::Create` \
makes it create the directories an output goes in. If a site genuinely must \
stay raw, add it to ALLOWED_RAW_WRITES with a written justification.",
violations.len(),
violations.join("\n")
);
}
fn file_violations(name: &str, code: &str, allowed_seen: &mut [usize]) -> Vec<String> {
let mut violations = Vec::new();
let (licensed, unlicensed, scope) = licensed_split(name, code);
for needle in NEEDLES {
for line in needle_lines(&unlicensed, needle) {
violations.push(format!(
" {name}:{line}: raw `{needle}` outside `mod {scope}`, which alone this \
file's licences cover"
));
}
let hits = needle_lines(&licensed, needle);
if hits.is_empty() {
continue;
}
let allowed = match ALLOWED_RAW_WRITES
.iter()
.position(|(f, n, _, _)| *f == name && n == needle)
{
Some(idx) => {
allowed_seen[idx] += hits.len();
ALLOWED_RAW_WRITES[idx].2
}
None => 0,
};
for line in hits.iter().skip(allowed) {
violations.push(format!(
" {name}:{line}: raw `{needle}` ({allowed} allow-listed for this file)"
));
}
}
violations
}
#[test]
fn the_guard_flags_a_planted_raw_write() {
assert_eq!(
scan_violation_count("fn f(p: &Path, s: &str) { std::fs::write(&p, s).unwrap(); }"),
1,
"a planted std::fs::write in a plain fn must be flagged"
);
assert_eq!(
scan_violation_count(
"fn f() {}\n#[cfg(test)]\nmod tests {\n fn t(p: &Path) { std::fs::write(&p, \"x\").unwrap(); }\n}\n"
),
0,
"a write inside #[cfg(test)] mod tests must not be flagged"
);
for planted in [
"#[cfg(test)]\nfn h() {}\nfn prod(p: &Path) { std::fs::write(p, \"x\").unwrap(); }\n#[cfg(test)]\nmod tests {}\n",
"impl S {\n #[cfg(test)]\n fn h(&self) -> &[u8] { &self.0 }\n}\nfn prod(p: &Path) { std::fs::write(p, \"x\").unwrap(); }\n#[cfg(test)]\nmod tests {}\n",
"#[cfg(test)]\nmod tests;\nfn prod(p: &Path) { std::fs::write(p, \"x\").unwrap(); }\n",
] {
assert_eq!(
scan_violation_count(planted),
1,
"a raw write after a test-only item must be flagged: {planted:?}"
);
}
assert_eq!(
scan_violation_count(
"#[cfg(test)]\nfn h(p: &Path) { std::fs::write(p, \"x\").unwrap(); }\nfn prod() {}\n"
),
0,
"a write inside a #[cfg(test)] fn must not be flagged"
);
assert_eq!(
scan_violation_count("fn f() {\n // std::fs::write(&p, s);\n}\n"),
0,
"a needle inside a // comment must not be flagged"
);
assert_eq!(
scan_violation_count("fn f() -> &'static str { \"std::fs::write(&p, s)\" }"),
0,
"a needle inside a string literal must not be flagged"
);
assert_eq!(
scan_violation_count("fn f(p: &Path) { let _ = std::fs::File::create(p); }"),
1,
"a planted File::create in a plain fn must be flagged"
);
assert_eq!(
scan_violation_count(
"fn f(p: &Path) { let _ = OpenOptions::new().write(true).create_new(true).open(p); }"
),
1,
"a planted create_new open in a plain fn must be flagged"
);
for planted in [
"fn f(p: &Path) { let _ = std::fs::create_dir_all(p); }",
"fn f(p: &Path) { let _ = std::fs::create_dir(p); }",
"fn f(d: BorrowedFd, n: &OsStr) { let _ = rustix::fs::mkdirat(d, n, Mode::from_raw_mode(0o777)); }",
"fn f(d: BorrowedFd, n: &OsStr) { let _ = rustix::fs::openat(d, n, OFlags::RDONLY, Mode::empty()); }",
"fn f(p: &Path) { let _ = std::fs::set_permissions(p, Permissions::from_mode(0o600)); }",
"fn f(a: &Path, b: &Path) { let _ = std::fs::rename(a, b); }",
"fn f(a: &Path, b: &Path) { let _ = rustix::fs::rename(a, b); }",
"fn f(d: BorrowedFd, a: &OsStr, b: &OsStr) { let _ = rustix::fs::renameat(d, a, d, b); }",
"fn f(d: BorrowedFd, a: &OsStr, b: &OsStr) { let _ = fs::renameat_with(d, a, d, b, RenameFlags::NOREPLACE); }",
"fn f(d: BorrowedFd, a: &OsStr, b: &OsStr) { let _ = rustix::fs::linkat(d, a, d, b, AtFlags::empty()); }",
"fn f(d: BorrowedFd, a: &OsStr) { let _ = rustix::fs::unlinkat(d, a, AtFlags::empty()); }",
"fn f(p: &Path) { let _ = std::fs::remove_file(p); }",
"fn f(p: &Path) { let _ = fs::remove_file(p); }",
"fn f(a: &Path, b: &Path) { let _ = std::fs::copy(a, b); }",
"fn f(a: &Path, b: &Path) { let _ = std::fs::hard_link(a, b); }",
"fn f(p: &Path) { let _ = std::fs::remove_dir(p); }",
"fn f(p: &Path) { let _ = std::fs::remove_dir_all(p); }",
"fn f(d: &Path) { let _ = tempfile::Builder::new().tempfile_in(d); }",
"fn f(d: &Path) { let _ = tempfile::tempfile_in(d); }",
"fn f(d: &Path) { let _ = tempfile::Builder::new().make_in(d, |p| File::open(p)); }",
"fn f(t: NamedTempFile, p: &Path) { let _ = t.persist(p); }",
"fn f(t: NamedTempFile, p: &Path) { let _ = t.persist_noclobber(p); }",
"fn f(a: &Path, b: &Path) { let _ = std::os::unix::fs::symlink(a, b); }",
"fn f(a: &Path, b: &Path) { let _ = rustix::fs::symlink(a, b); }",
"fn f(a: &Path, d: BorrowedFd, b: &OsStr) { let _ = rustix::fs::symlinkat(a, d, b); }",
"fn f(a: &Path, b: &Path) { let _ = std::fs::soft_link(a, b); }",
"fn f(a: &Path, b: &Path) { let _ = std::os::windows::fs::symlink_file(a, b); }",
"fn f(a: &Path, b: &Path) { let _ = std::os::windows::fs::symlink_dir(a, b); }",
] {
assert_eq!(scan_violation_count(planted), 1, "must be flagged: {planted}");
}
assert_eq!(
scan_violation_count(
"fn f(p: &Path) -> bool { p.is_symlink() || std::fs::symlink_metadata(p).is_ok() \
|| mds::NativeFs::check_symlink(p).is_ok() || make_symlink(p, p) }"
),
0,
"`is_symlink(`, `symlink_metadata(`, `check_symlink(` and `make_symlink(` make no link"
);
assert_eq!(
scan_violation_count("fn f(e: Errno) -> bool { no_hard_links(e) }"),
0,
"`no_hard_links(` is not `hard_link(`"
);
assert_eq!(
scan_violation_count(
"fn f(file: &File, p: Permissions) { let _ = file.set_permissions(p); }"
),
0,
"File::set_permissions works on the open file"
);
}
#[test]
fn a_licence_scoped_to_a_module_covers_that_module_alone() {
let rename = "fn f(a: &Path, b: &Path) { let _ = std::fs::rename(a, b); }";
let violations = |name: &str, code: &str| {
let masked = blank_cfg_test_items(&mask_comments_and_strings(code));
file_violations(name, &masked, &mut vec![0usize; ALLOWED_RAW_WRITES.len()])
};
let inside = format!("#[cfg(debug_assertions)]\nmod ready_trigger {{\n {rename}\n}}\n");
assert_eq!(
violations("watch.rs", &inside),
Vec::<String>::new(),
"the marker's rename inside its module is licensed"
);
let beside = format!("{inside}{rename}\n");
assert_eq!(
violations("watch.rs", &beside).len(),
1,
"a rename beside the module is not"
);
let renamed = inside.replace("mod ready_trigger", "mod elsewhere");
assert_eq!(
violations("watch.rs", &renamed).len(),
1,
"a rename in a module of another name is not"
);
let unscoped = "fn f(p: &Path) { let _ = std::fs::remove_file(p); }";
assert_eq!(
violations("write.rs", unscoped),
Vec::<String>::new(),
"write.rs's licences have no scope"
);
}
#[test]
fn the_primitive_pins_flag_a_tail_that_stopped_syncing() {
let unix = |body: &str| {
format!("mod unix {{ fn w() {{ {body} }} }}\nmod windows {{ fn w() {{ t.as_file().sync_all(); std::fs::rename(t.path(), p); }} }}")
};
let complete =
unix("fs::fchmod(&f, m); f.sync_all(); fs::renameat(d, t, d, n); dir.sync_all();");
assert_eq!(primitive_pin_violations(&complete), Vec::<String>::new());
for (dropped, body) in [
(
"the directory sync",
"fs::fchmod(&f, m); f.sync_all(); fs::renameat(d, t, d, n);",
),
(
"renameat",
"fs::fchmod(&f, m); f.sync_all(); std::fs::rename(t, n); dir.sync_all();",
),
(
"fchmod",
"f.sync_all(); fs::renameat(d, t, d, n); dir.sync_all();",
),
] {
assert_eq!(
primitive_pin_violations(&unix(body)).len(),
1,
"dropping {dropped} must be flagged"
);
}
let windows = complete.replace("t.as_file().sync_all();", "");
assert_eq!(
primitive_pin_violations(&windows).len(),
1,
"the Windows sync"
);
let windows = complete.replace("std::fs::rename(t.path(), p);", "");
assert_eq!(
primitive_pin_violations(&windows).len(),
1,
"the Windows rename"
);
let windows = complete.replace("std::fs::rename(t.path(), p);", "t.persist(p);");
assert_eq!(
primitive_pin_violations(&windows).len(),
1,
"tempfile's persist in place of the Windows rename"
);
let windows = complete.replace(
"std::fs::rename(t.path(), p);",
"std::fs::rename(t.path(), p); std::fs::rename(p, q);",
);
assert_eq!(
primitive_pin_violations(&windows).len(),
1,
"a second Windows rename"
);
assert_eq!(
primitive_pin_violations("fn f() {}").len(),
2,
"a primitive with neither arm"
);
}
fn primitive_pin_violations(code: &str) -> Vec<String> {
let mut missed = Vec::new();
match module_block(code, "unix") {
Some(unix) => {
let syncs = count_occurrences(unix, ".sync_all()");
if syncs != 2 {
missed.push(format!(
" mod unix: {syncs} .sync_all() call(s); the temporary file and its \
directory need one each"
));
}
for (needle, why) in [
(
"renameat(",
"the rename relative to the directory it walked to",
),
(
"fchmod(",
"the mode restored on the temporary file's own descriptor",
),
] {
if !unix.contains(needle) {
missed.push(format!(" mod unix: no {needle}: {why}"));
}
}
}
None => missed.push(" no mod unix".to_owned()),
}
match module_block(code, "windows") {
Some(windows) => {
let syncs = count_occurrences(windows, ".sync_all()");
let renames = count_occurrences(windows, "fs::rename(");
if syncs != 1 || renames != 1 {
missed.push(format!(
" mod windows: {syncs} .sync_all() call(s) and {renames} fs::rename( \
call(s); the temporary file needs one sync, and one rename by std, which \
replaces a file another program holds open"
));
}
}
None => missed.push(" no mod windows".to_owned()),
}
missed
}
fn module_block<'a>(code: &'a str, name: &str) -> Option<&'a str> {
module_range(code, name).map(|range| &code[range])
}
fn module_range(code: &str, name: &str) -> Option<std::ops::Range<usize>> {
let header = format!("mod {name} {{");
let start = code.find(&header)?;
let close = match_brace(code, start + header.len() - 1)?;
Some(start..close + 1)
}
fn licensed_split(name: &str, code: &str) -> (String, String, &'static str) {
let Some(&(_, module)) = LICENCE_SCOPES.iter().find(|(file, _)| *file == name) else {
return (code.to_owned(), String::new(), "");
};
match module_range(code, module) {
Some(range) => (
blank_ranges(code, &[0..range.start, range.end..code.len()]),
blank_ranges(code, &[range]),
module,
),
None => (String::new(), code.to_owned(), module),
}
}
#[test]
fn every_allowlist_entry_is_live() {
let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
for (file, needle, max, why) in ALLOWED_RAW_WRITES {
let path = src_dir.join(file);
assert!(
path.is_file(),
"allow-list names {file}, which does not exist under {} (justification: {why})",
src_dir.display()
);
let raw = std::fs::read_to_string(&path).expect("source must be readable");
let code = blank_cfg_test_items(&mask_comments_and_strings(&raw));
let (licensed, _, _) = licensed_split(file, &code);
let hits = count_occurrences(&licensed, needle);
assert_eq!(
hits, *max,
"allow-list expects {max} raw `{needle}` in {file}, found {hits} \
(justification: {why})"
);
}
}
fn scan_violation_count(src: &str) -> usize {
let code = blank_cfg_test_items(&mask_comments_and_strings(src));
NEEDLES.iter().map(|n| count_occurrences(&code, n)).sum()
}
fn needle_lines(code: &str, needle: &str) -> Vec<usize> {
let mut lines = Vec::new();
let mut start = 0usize;
while let Some(pos) = code[start..].find(needle) {
let abs = start + pos;
lines.push(code[..abs].matches('\n').count() + 1);
start = abs + needle.len();
}
lines
}
fn count_occurrences(haystack: &str, needle: &str) -> usize {
let mut count = 0;
let mut start = 0;
while let Some(pos) = haystack[start..].find(needle) {
count += 1;
start += pos + needle.len();
}
count
}
fn duplicate_basenames(paths: &[PathBuf]) -> Vec<String> {
let mut seen = std::collections::BTreeSet::new();
let mut duplicates = std::collections::BTreeSet::new();
for path in paths {
let name = path
.file_name()
.and_then(|name| name.to_str())
.expect("source file names are UTF-8");
if !seen.insert(name) {
duplicates.insert(name);
}
}
duplicates.into_iter().map(str::to_owned).collect()
}
#[test]
#[should_panic(expected = "duplicate Rust source basenames: [\"x.rs\"]")]
fn rust_files_refuses_duplicate_basenames() {
let dir = tempfile::tempdir().unwrap();
for file in ["a/x.rs", "b/y.rs"] {
let path = dir.path().join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
assert_eq!(rust_files(dir.path()).len(), 2);
std::fs::rename(dir.path().join("b/y.rs"), dir.path().join("b/x.rs")).unwrap();
rust_files(dir.path());
}
fn rust_files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for entry in rd.flatten() {
let p = entry.path();
let Ok(ft) = entry.file_type() else { continue };
if ft.is_dir() {
stack.push(p);
} else if ft.is_file() && p.extension().and_then(|e| e.to_str()) == Some("rs") {
out.push(p);
}
}
}
out.sort();
let duplicates = duplicate_basenames(&out);
assert!(
duplicates.is_empty(),
"duplicate Rust source basenames: {duplicates:?}"
);
out
}
fn mask_comments_and_strings(src: &str) -> String {
let b = src.as_bytes();
let mut out = vec![b' '; b.len()];
for (i, &c) in b.iter().enumerate() {
if c == b'\n' {
out[i] = b'\n';
}
}
let mut i = 0usize;
while i < b.len() {
if b[i] == b'/' && b.get(i + 1) == Some(&b'/') {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
continue;
}
if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
i += 2;
while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) {
i += 1;
}
i = (i + 2).min(b.len());
continue;
}
if b[i] == b'r'
&& matches!(b.get(i + 1), Some(&b'"') | Some(&b'#'))
&& !prev_is_ident_byte(b, i)
{
let mut hashes = 0usize;
let mut j = i + 1;
while b.get(j) == Some(&b'#') {
hashes += 1;
j += 1;
}
if b.get(j) == Some(&b'"') {
j += 1;
while j < b.len() {
if b[j] == b'"' && (0..hashes).all(|k| b.get(j + 1 + k) == Some(&b'#')) {
j += 1 + hashes;
break;
}
j += 1;
}
i = j.min(b.len());
continue;
}
}
if b[i] == b'"' {
let mut j = i + 1;
while j < b.len() {
if b[j] == b'\\' {
j += 2;
continue;
}
if b[j] == b'"' {
j += 1;
break;
}
j += 1;
}
i = j.min(b.len());
continue;
}
if b[i] == b'\'' {
let mut j = i + 1;
let mut closed = false;
let mut steps = 0;
while j < b.len() && steps < 8 {
if b[j] == b'\\' {
j += 2;
steps += 1;
continue;
}
if b[j] == b'\'' {
closed = true;
j += 1;
break;
}
j += 1;
steps += 1;
}
if closed {
i = j.min(b.len());
continue;
}
}
out[i] = b[i];
i += 1;
}
String::from_utf8(out).expect("masking preserves UTF-8 boundaries on ASCII delimiters")
}
fn blank_cfg_test_items(code: &str) -> String {
blank_ranges(code, &cfg_test_ranges(code))
}
fn cfg_test_ranges(code: &str) -> Vec<std::ops::Range<usize>> {
const ATTR: &str = "#[cfg(test)]";
let mut ranges = Vec::new();
let mut from = 0usize;
while let Some(rel) = code[from..].find(ATTR) {
let attr = from + rel;
let item = attr + ATTR.len();
from = item;
let end = match (code[item..].find('{'), code[item..].find(';')) {
(Some(bo), semi) if semi.is_none_or(|s| bo < s) => {
match_brace(code, item + bo).map(|close| close + 1)
}
(_, Some(so)) => Some(item + so + 1),
_ => None,
};
if let Some(end) = end {
ranges.push(attr..end);
from = end;
}
}
ranges
}
fn blank_ranges(text: &str, ranges: &[std::ops::Range<usize>]) -> String {
let mut out = text.as_bytes().to_vec();
for range in ranges {
for byte in &mut out[range.clone()] {
if *byte != b'\n' {
*byte = b' ';
}
}
}
String::from_utf8(out).expect("blanking with ASCII spaces keeps UTF-8 valid")
}
fn prev_is_ident_byte(b: &[u8], i: usize) -> bool {
i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')
}
fn match_brace(text: &str, open: usize) -> Option<usize> {
let b = text.as_bytes();
let mut depth = 0i32;
let mut i = open;
while i < b.len() {
match b[i] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}