Skip to main content

rhai_data_quality/
lib.rs

1//! Rhai packages for cleaning business data: contact and company records, dates, numbers and
2//! money, and text.
3//!
4//! Every function is written in plain Rhai, is pure, and uses only core Rhai, so it behaves the
5//! same in any engine. The packages compile the bundled scripts once; register a package with as
6//! many engines as you like.
7//!
8//! # Quick start
9//!
10//! ```
11//! use rhai::Engine;
12//! use rhai::packages::Package;
13//! use rhai_data_quality::DataQualityPackage;
14//!
15//! let mut engine = Engine::new();
16//! DataQualityPackage::new().register_into_engine(&mut engine);
17//!
18//! let email: String = engine.eval(r#"normalize_email(" Jane.Doe@Example.COM ")"#).unwrap();
19//! assert_eq!(email, "jane.doe@example.com");
20//!
21//! let date: String = engine.eval(r#"to_iso_date("April 3rd, 2026", "mdy")"#).unwrap();
22//! assert_eq!(date, "2026-04-03");
23//! ```
24//!
25//! # One module, under a namespace
26//!
27//! ```
28//! use rhai::Engine;
29//! use rhai::packages::Package;
30//! use rhai_data_quality::{ContactsPackage, NumbersPackage};
31//!
32//! let mut engine = Engine::new();
33//! ContactsPackage::new().register_into_engine_as(&mut engine, "contacts");
34//! NumbersPackage::new().register_into_engine_as(&mut engine, "num");
35//!
36//! let phone: String = engine.eval(r#"contacts::phone_e164("(415) 555-0123", "1")"#).unwrap();
37//! assert_eq!(phone, "+14155550123");
38//!
39//! let cents: i64 = engine.eval(r#"num::to_cents("1.234,56 €", "auto")"#).unwrap();
40//! assert_eq!(cents, 123456);
41//! ```
42//!
43//! # Packages
44//!
45//! | Package | Script | What it does |
46//! |---|---|---|
47//! | [`DataQualityPackage`] | all four | everything below |
48//! | [`ContactsPackage`] | `data-quality.rhai` | emails, phone numbers, names, company names, domains, URLs, postcodes, states, countries, Luhn check digits, match keys for finding duplicates, missing fields |
49//! | [`DatesPackage`] | `dates.rhai` | dates in mixed formats to `YYYY-MM-DD`, Excel serial dates, Unix timestamps, business days, ISO weeks, fiscal periods, months and ages |
50//! | [`NumbersPackage`] | `numbers.rhai` | amounts in US or European formats, percentages, currency codes, banker's rounding, display formatting, durations, amounts in words |
51//! | [`TextPackage`] | `text.rhai` | accents, slugs, truncation, masking, padding, HTML snippets, title, snake, camel and kebab case |
52//!
53//! The full function list, with examples and limits, is in the
54//! [README](https://github.com/rhaiscript/rhai-data-quality#readme).
55//!
56//! # Requirements
57//!
58//! The scripts use floating-point numbers, arrays, object maps and functions, so the engine must
59//! not use Rhai's `no_float`, `no_index`, `no_object`, `no_function` or `no_module` features. If
60//! your engine uses `unchecked`, turn on this crate's `unchecked` feature as well.
61//!
62//! The script sources are also available in [`sources`], to load them another way (for example,
63//! as files for a module resolver).
64
65#![warn(missing_docs)]
66
67use rhai::packages::Package;
68use rhai::{Engine, Module, Scope, Shared, AST};
69
70/// The bundled Rhai scripts, as source text.
71pub mod sources {
72    /// `data-quality.rhai`: contact and company records.
73    pub const DATA_QUALITY: &str = include_str!("../data-quality/data-quality.rhai");
74    /// `dates.rhai`: dates.
75    pub const DATES: &str = include_str!("../dates/dates.rhai");
76    /// `numbers.rhai`: numbers and money.
77    pub const NUMBERS: &str = include_str!("../numbers/numbers.rhai");
78    /// `text.rhai`: text.
79    pub const TEXT: &str = include_str!("../text/text.rhai");
80    /// Every script, in load order.
81    pub const ALL: [&str; 4] = [DATA_QUALITY, DATES, NUMBERS, TEXT];
82}
83
84/// Compiles the scripts into one module whose functions can call each other.
85fn build_module(scripts: &[&str]) -> Module {
86    let mut engine = Engine::new();
87    // Debug builds of Rhai default to half the nesting depth of release builds, which is too
88    // shallow for some of the scripts. These are the release defaults.
89    #[cfg(not(feature = "unchecked"))]
90    engine.set_max_expr_depths(64, 32);
91
92    let ast = scripts.iter().fold(AST::empty(), |ast, script| {
93        ast.merge(&engine.compile(script).expect("bundled script should compile"))
94    });
95    Module::eval_ast_as_new(Scope::new(), &ast, &engine).expect("bundled script should load")
96}
97
98macro_rules! script_package {
99    ($(#[$attr:meta])* $name:ident, $id:literal, [$($script:expr),+]) => {
100        $(#[$attr])*
101        #[derive(Debug, Clone)]
102        pub struct $name(Shared<Module>);
103
104        impl $name {
105            /// Compiles the bundled scripts into a new package.
106            ///
107            /// Compiling takes a few milliseconds; create the package once and clone it, or
108            /// register it with each engine, rather than creating it per engine.
109            #[must_use]
110            pub fn new() -> Self {
111                let mut module = Module::new();
112                <Self as Package>::init(&mut module);
113                module.set_id($id);
114                module.build_index();
115                Self(module.into())
116            }
117        }
118
119        impl Default for $name {
120            fn default() -> Self {
121                Self::new()
122            }
123        }
124
125        impl Package for $name {
126            fn init(module: &mut Module) {
127                module.combine(build_module(&[$($script),+]));
128            }
129
130            fn as_shared_module(&self) -> Shared<Module> {
131                self.0.clone()
132            }
133        }
134    };
135}
136
137script_package!(
138    /// Every function in this crate: [`ContactsPackage`], [`DatesPackage`], [`NumbersPackage`]
139    /// and [`TextPackage`] together.
140    DataQualityPackage,
141    "rhai_data_quality",
142    [sources::DATA_QUALITY, sources::DATES, sources::NUMBERS, sources::TEXT]
143);
144
145script_package!(
146    /// Contact and company records (`data-quality.rhai`): emails, phone numbers, names, company
147    /// names, domains, URLs, US ZIP codes and states, Canadian and UK postcodes, country codes,
148    /// Luhn check digits, match keys for finding duplicates, and missing fields.
149    ContactsPackage,
150    "rhai_data_quality::contacts",
151    [sources::DATA_QUALITY]
152);
153
154script_package!(
155    /// Dates (`dates.rhai`): dates written in common formats to `YYYY-MM-DD`, Excel serial dates,
156    /// Unix timestamps, days and business days between and added, weekdays, ISO weeks, month
157    /// ends, quarters, fiscal years and quarters, months and ages.
158    DatesPackage,
159    "rhai_data_quality::dates",
160    [sources::DATES]
161);
162
163script_package!(
164    /// Numbers and money (`numbers.rhai`): numbers and amounts in US or European formats,
165    /// percentages, currency codes, banker's rounding, display formatting, percent change, safe
166    /// division, durations, currency rounding, amounts in words and clamping.
167    NumbersPackage,
168    "rhai_data_quality::numbers",
169    [sources::NUMBERS]
170);
171
172script_package!(
173    /// Text (`text.rhai`): accents, slugs, truncation at a word, initials, masking, left padding,
174    /// HTML snippets, word counts, title, snake, camel and kebab case, hashtags and mentions, and
175    /// typographic quotes and dashes.
176    TextPackage,
177    "rhai_data_quality::text",
178    [sources::TEXT]
179);