PII Redactor — Rust source
Paste text and automatically detect and mask personal data — emails, phone numbers, IP addresses, SSNs, credit card numbers, and dates.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! pii-redactor — PII detection & redaction (email, phone, IPs, SSN, cards, dates).
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `pii-redactor` tool, ported from
//! src/lib/pii-redactor.ts (the canonical TypeScript implementation).
//!
//! Rust's standard library has no regex engine, so each detector is a
//! hand-rolled cursor scanner producing the same candidate spans as the
//! reference patterns (greedy/backtracking order included); every candidate
//! still passes the same structural validator (octet ranges, Luhn checksum,
//! month/day bounds, E.164 digit count), and overlaps resolve by type
//! priority. Never panics on any input.
//!
//! display source — part of CosmoDev's polyglot tool pages.
#![allow(non_snake_case)]
/// The seven PII types the detector knows, in display order.
pub const PII_TYPES: [&str; 7] = ["email", "phone", "ipv4", "ipv6", "ssn", "credit-card", "date"];
/// One detected personal-data item: where it is (byte offsets) and what it was.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PiiMatch {
pub kind: &'static str,
/// Index of the first byte in the input.
pub start: usize,
/// Index one past the last byte.
pub end: usize,
}
fn isWord(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn digitRun(t: &[u8], i: usize) -> usize {
let mut n = 0;
while t.get(i + n).map_or(false, |b| b.is_ascii_digit()) { n += 1; }
n
}
fn hexRun(t: &[u8], i: usize) -> usize {
let mut n = 0;
while t.get(i + n).map_or(false, |b| b.is_ascii_hexdigit()) { n += 1; }
n
}
/// Luhn checksum. `digits` must be a non-empty string of 0-9 (any separators
/// make it invalid - strip them first). Returns false otherwise.
pub fn isValidLuhn(digits: &str) -> bool {
let d = digits.as_bytes();
if d.is_empty() || !d.iter().all(|b| b.is_ascii_digit()) {
return false;
}
let (mut sum, mut double) = (0u32, false);
for &b in d.iter().rev() {
let mut v = u32::from(b - b'0');
if double {
v *= 2;
if v > 9 { v -= 9; }
}
sum += v;
double = !double;
}
sum % 10 == 0
}
// --- Per-type structural validators (scanner candidates pass through these) ---
/// Octets 0-255 each; the scanner already bounds the shape to a dotted quad.
fn isValidIpv4(candidate: &str) -> bool {
candidate.split('.').all(|o| o.parse::<u32>().map_or(false, |n| n <= 255))
}
fn isHexGroup(g: &str) -> bool {
let b = g.as_bytes();
!b.is_empty() && b.len() <= 4 && b.iter().all(|c| c.is_ascii_hexdigit())
}
/// Full 8-group form, or a compressed `::` form expanding to exactly 8.
fn isValidIpv6(candidate: &str) -> bool {
if !candidate.bytes().any(|b| b.is_ascii_hexdigit()) {
return false; // lone ":" / "::" (URL scheme separators) carry no hex digits
}
let groups: Vec<&str> = candidate.split(':').collect();
if !groups.iter().any(|g| g.is_empty()) {
return groups.len() == 8 && groups.iter().all(|g| isHexGroup(g));
}
let parts: Vec<&str> = candidate.split("::").collect(); // compressed: at most one "::", sides hold < 8 groups
if parts.len() > 2 {
return false;
}
let left: Vec<&str> = if parts[0].is_empty() { Vec::new() } else { parts[0].split(':').collect() };
let right: Vec<&str> =
if parts.len() > 1 && !parts[1].is_empty() { parts[1].split(':').collect() } else { Vec::new() };
left.len() + right.len() <= 7 && left.iter().chain(right.iter()).all(|g| isHexGroup(g))
}
/// ISO calendar plausibility: month 01-12, day 01-31.
fn isValidDate(candidate: &str) -> bool {
let b = candidate.as_bytes();
if b.len() != 10 || b[4] != b'-' || b[7] != b'-'
|| !b.iter().enumerate().all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit())
{
return false;
}
let month: u32 = candidate[5..7].parse().unwrap_or(0);
let day: u32 = candidate[8..10].parse().unwrap_or(0);
(1..=12).contains(&month) && (1..=31).contains(&day)
}
/// `\d{1,3}(?:\.\d{1,3}){3}` across the whole candidate.
fn dottedQuad(b: &[u8]) -> bool {
let parts: Vec<&[u8]> = b.split(|c| *c == b'.').collect();
parts.len() == 4
&& parts.iter().all(|p| !p.is_empty() && p.len() <= 3 && p.iter().all(|c| c.is_ascii_digit()))
}
/// `\d{4}-\d{2}-\d{2}` across the whole candidate.
fn isoShape(b: &[u8]) -> bool {
b.len() == 10 && b[4] == b'-' && b[7] == b'-'
&& b.iter().enumerate().all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit())
}
/// E.164 digit budget (7-15) and structural guards for the fuzzy phone shape.
fn isValidPhone(candidate: &str) -> bool {
if !(7..=15).contains(&candidate.bytes().filter(|c| c.is_ascii_digit()).count()) {
return false;
}
let b = candidate.as_bytes();
// A dotted quad is IP-shaped: if it were a valid IP it was already claimed
// by the ipv4 detector; an invalid one (999.x) is likelier a version string.
if dottedQuad(b) {
return false;
}
// YYYY-MM-DD shaped (even an impossible date) is never a phone number.
!isoShape(b)
}
/// 13-19 digits with optional space/dash grouping, plus a Luhn checksum.
fn isValidCard(candidate: &str) -> bool {
let digits: String = candidate.chars().filter(|c| c.is_ascii_digit()).collect();
(13..=19).contains(&digits.len()) && isValidLuhn(&digits)
}
// --- Detectors: a hand-rolled scanner + an optional structural validator.
type Finder = fn(&[u8], usize) -> Option<(usize, usize)>;
type Validator = fn(&str) -> bool;
/// RFC 5322 simplified: `[local]+@[domain]+\.[A-Za-z]{2,}`. Greedy local run,
/// then the domain backtracks to the last dot with a 2+ letter run after it.
fn domainEnd(t: &[u8], d: usize) -> Option<usize> {
let mut e = d;
while e < t.len() && (t[e].is_ascii_alphanumeric() || t[e] == b'.' || t[e] == b'-') {
e += 1;
}
let mut q = e;
while q > d {
q -= 1;
if t[q] != b'.' {
continue;
}
let mut l = q + 1;
while l < t.len() && t[l].is_ascii_alphabetic() {
l += 1;
}
if l - (q + 1) >= 2 {
return Some(l);
}
}
None
}
fn isLocal(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'%' | b'+' | b'-')
}
fn findEmail(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p < t.len() {
if isLocal(t[p]) {
let mut e = p;
while e < t.len() && isLocal(t[e]) {
e += 1;
}
if t.get(e) == Some(&b'@') {
if let Some(end) = domainEnd(t, e + 1) {
return Some((p, end));
}
p = e + 1; // no shorter local run reaches this '@' either
continue;
}
p = e; // no later position inside this run sees an '@' either
} else {
p += 1;
}
}
None
}
/// `\d(?:[ -]?\d){11,}` — a maximal run of digits with single space/dash
/// separators; isValidCard then enforces 13-19 digits + Luhn on the run.
fn findCard(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p < t.len() {
if t[p].is_ascii_digit() {
let mut e = p + 1;
let mut digits = 1usize;
loop {
if matches!(t.get(e), Some(b' ' | b'-'))
&& t.get(e + 1).map_or(false, |c| c.is_ascii_digit())
{
e += 2;
} else if t.get(e).map_or(false, |c| c.is_ascii_digit()) {
e += 1;
} else {
break;
}
digits += 1;
}
if digits >= 12 {
return Some((p, e));
}
p = e; // nothing inside a too-short run can match either
} else {
p += 1;
}
}
None
}
/// `\b\d{3}-\d{2}-\d{4}\b`
fn findSsn(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p + 11 <= t.len() {
let digits = |o: usize, n: usize| (0..n).all(|i| t[p + o + i].is_ascii_digit());
let end = p + 11;
if digits(0, 3) && t[p + 3] == b'-' && digits(4, 2) && t[p + 6] == b'-' && digits(7, 4)
&& (p == 0 || !isWord(t[p - 1])) && (end == t.len() || !isWord(t[end]))
{
return Some((p, end));
}
p += 1;
}
None
}
/// `(?<![:\w])[A-Fa-f0-9]{0,4}(?::[A-Fa-f0-9]{0,4}){1,7}(?![:\w])`. Greedy
/// throughout; when the greedy pass fails the trailing guard, every shorter
/// group count also ends in front of a ':' or word char, so no backtracking.
fn findIpv6(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p < t.len() {
if p > 0 && (t[p - 1] == b':' || isWord(t[p - 1])) {
p += 1;
continue;
}
let mut q = p + hexRun(t, p).min(4);
let mut groups = 0;
while groups < 7 && t.get(q) == Some(&b':') {
q += 1;
q += hexRun(t, q).min(4);
groups += 1;
}
let afterOk = match t.get(q) {
None => true,
Some(&c) => c != b':' && !isWord(c),
};
if groups >= 1 && afterOk {
return Some((p, q));
}
p += 1;
}
None
}
/// `(?:\d{1,3}\.){groups-1}` then the final `\d{1,3}` with its `(?!\.?\d)(?!\w)`
/// guards — greedy with backtracking, rightmost quantifier varying fastest,
/// exactly like the reference regex engine.
fn quadTail(t: &[u8], p: usize, groups: u32) -> Option<usize> {
for len in (1..=digitRun(t, p).min(3)).rev() {
if t.get(p + len) != Some(&b'.') {
continue;
}
let next = p + len + 1;
if groups > 1 {
if let Some(end) = quadTail(t, next, groups - 1) {
return Some(end);
}
} else {
for flen in (1..=digitRun(t, next).min(3)).rev() {
let end = next + flen;
let ok = match t.get(end) {
None => true,
Some(&c) => {
!(c == b'.' && matches!(t.get(end + 1), Some(&d) if d.is_ascii_digit()))
&& !isWord(c)
}
};
if ok {
return Some(end);
}
}
}
}
None
}
/// `(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?!\.?\d)(?!\w)` — guards keep it out of
/// versions ("v1.2.3.4") and longer quintets ("1.2.3.4.5").
fn findIpv4(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p < t.len() {
if p > 0 && (isWord(t[p - 1]) || t[p - 1] == b'.') {
p += 1;
continue;
}
if let Some(end) = quadTail(t, p, 3) {
return Some((p, end));
}
p += 1;
}
None
}
/// `(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)`
fn findDate(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p + 10 <= t.len() {
let digits = |o: usize, n: usize| (0..n).all(|i| t[p + o + i].is_ascii_digit());
let end = p + 10;
if digits(0, 4) && t[p + 4] == b'-' && digits(5, 2) && t[p + 7] == b'-' && digits(8, 2)
&& (p == 0 || !t[p - 1].is_ascii_digit())
&& (end == t.len() || !t[end].is_ascii_digit())
{
return Some((p, end));
}
p += 1;
}
None
}
/// `(?:[ .-]?\d{2,4}){1,4}` greedy with full backtracking, then `(?!\d)`:
/// per group the separator variant is tried before the separator-less one,
/// longer digit runs before shorter, more groups before fewer.
fn phoneGroups(t: &[u8], p: usize, done: u32) -> Option<usize> {
if done < 4 {
if matches!(t.get(p), Some(b' ' | b'.' | b'-')) {
let base = p + 1;
for len in (2..=digitRun(t, base).min(4)).rev() {
if let Some(end) = phoneGroups(t, base + len, done + 1) {
return Some(end);
}
}
}
for len in (2..=digitRun(t, p).min(4)).rev() {
if let Some(end) = phoneGroups(t, p + len, done + 1) {
return Some(end);
}
}
}
if done >= 1 && !t.get(p).map_or(false, |c| c.is_ascii_digit()) {
return Some(p); // the group chain ends here
}
None
}
/// `(?:\(\d{1,4}\)|\d{1,4})` — alternation, each branch greedy with backtracking.
fn phoneMain(t: &[u8], p: usize) -> Option<usize> {
if t.get(p) == Some(&b'(') {
for len in (1..=digitRun(t, p + 1).min(4)).rev() {
if t.get(p + 1 + len) == Some(&b')') {
if let Some(end) = phoneGroups(t, p + len + 2, 0) {
return Some(end);
}
}
}
return None; // '(' cannot start the bare-digits branch either
}
for len in (1..=digitRun(t, p).min(4)).rev() {
if let Some(end) = phoneGroups(t, p + len, 0) {
return Some(end);
}
}
None
}
/// Fuzziest pattern — lowest priority: optional +country, optional (area),
/// then 1-4 groups of 2-4 digits separated by spaces, dashes, or dots:
/// `(?<![\d(])(?:\+\d{1,3}[ .-]?)?(?:\(\d{1,4}\)|\d{1,4})(?:[ .-]?\d{2,4}){1,4}(?!\d)`.
fn findPhone(t: &[u8], from: usize) -> Option<(usize, usize)> {
let mut p = from;
while p < t.len() {
if p > 0 && (t[p - 1].is_ascii_digit() || t[p - 1] == b'(') {
p += 1;
continue;
}
if t.get(p) == Some(&b'+') {
for len in (1..=digitRun(t, p + 1).min(3)).rev() {
let after = p + 1 + len;
if matches!(t.get(after), Some(b' ' | b'.' | b'-')) {
if let Some(end) = phoneMain(t, after + 1) {
return Some((p, end));
}
}
if let Some(end) = phoneMain(t, after) {
return Some((p, end));
}
}
}
if let Some(end) = phoneMain(t, p) {
return Some((p, end));
}
p += 1;
}
None
}
/// Detectors: a hand-rolled scanner + an optional structural validator.
/// Array order IS the overlap priority (index 0 claims spans first). Phone is
/// deliberately last - a date, SSN, IP, or card number can all masquerade as one.
const DETECTORS: [(&str, Finder, Option<Validator>); 7] = [
("email", findEmail, None),
("credit-card", findCard, Some(isValidCard)),
("ssn", findSsn, None),
("ipv6", findIpv6, Some(isValidIpv6)),
("ipv4", findIpv4, Some(isValidIpv4)),
("date", findDate, Some(isValidDate)),
("phone", findPhone, Some(isValidPhone)),
];
/**
* Detect personal data in `text`. Pass `types` to scan for a subset (the
* per-type toggles); pass `None` to scan for everything. Returns matches in
* document order, non-overlapping, with exact `start`/`end` byte offsets.
*/
pub fn detectPii(text: &str, types: Option<&[&str]>) -> Vec<PiiMatch> {
let t = text.as_bytes();
let mut candidates: Vec<PiiMatch> = Vec::new();
for &(kind, finder, validator) in DETECTORS.iter() {
if let Some(active) = types {
if !active.contains(&kind) {
continue;
}
}
let mut from = 0usize;
while let Some((s, e)) = finder(t, from) {
if validator.map_or(true, |v| v(&text[s..e])) {
candidates.push(PiiMatch { kind, start: s, end: e });
}
from = if e > s { e } else { s + 1 }; // zero-length safety
}
}
// Highest-priority (lowest index) candidates claim their span first.
candidates.sort_by_key(|c| {
(
DETECTORS.iter().position(|d| d.0 == c.kind).unwrap_or(usize::MAX),
c.start,
)
});
let mut kept: Vec<PiiMatch> = Vec::new();
for c in candidates {
if kept.iter().any(|k| c.start < k.end && k.start < c.end) {
continue;
}
kept.push(c);
}
kept.sort_by_key(|c| c.start);
kept
}
/// Redact personal data from `text`, replacing every detected span with
/// `mask` (default "[REDACTED]"). Accepts the same `types` subset as detectPii.
pub fn redactPii(text: &str, mask: &str, types: Option<&[&str]>) -> String {
let mut out = text.to_string();
for m in detectPii(text, types).iter().rev() {
out.replace_range(m.start..m.end, mask); // right-to-left keeps indices valid
}
out
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →