A Rust implementation of Google's libphonenumber (metadata 9.0.44), with a
Python package whose API and results match
phonenumbers
for everything it implements.
pip install phonenumbers-rsimport phonenumbers_rs as phonenumbers
number = phonenumbers.parse("+390612345678", None)
phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)phonenumbers_rs.patch() makes a later import phonenumbers resolve to
phonenumbers_rs (patch(force=True) swaps out an already-imported
phonenumbers in place).
Implemented, with results checked against python-phonenumbers: parsing,
validation and number types, all formatting functions, AsYouTypeFormatter,
PhoneNumberMatcher / find_numbers, is_number_match, and the geocoder,
carrier and timezone modules. Parameter names match upstream, so keyword
calls work, and PhoneNumber pickles.
Not implemented yet — code using these needs the pure-Python package:
- the short-number API (
shortnumberinfo:is_valid_short_number,is_emergency_number,expected_cost, …); FrozenPhoneNumber,PhoneMetadata/PhoneNumberDesc/NumberFormatobjects and the raw metadata modules;format_by_pattern,is_number_geographical,length_of_geographical_area_code,length_of_national_destination_code,invalid_example_number,supported_types_for_region,country_mobile_token, and a few constants (COUNTRY_CODE_TO_REGION_CODE,UNKNOWN_REGION, …).
Most of the speedup over python comes from the Rust port itself. The
pn-simd kernels and per-pattern digit lookup tables add to it in validation
and digit normalisation (see Performance). Phone numbers are
short, so these kernels mostly run their scalar paths; the vector paths only
kick in on longer input such as free text.
| Path | Contents |
|---|---|
crates/pn-metadata (crate phonenumbers-rs-metadata) |
Static metadata: generated tables (src/generated/), memoised regex engine, runtime structs |
crates/pn-simd (crate phonenumbers-rs-simd) |
SIMD digit kernels (digit tables, extraction, run scanning, integer parsing) with scalar fallbacks |
crates/pn-core (crate phonenumbers-rs) |
The engine: parse / format / validate / match, mirroring python-phonenumbers behaviour |
crates/pn-py (unpublished) |
PyO3 bindings (abi3-py310), built into phonenumbers_rs._native by maturin |
xtask |
Metadata compiler: parses vendor/libphonenumber XML + prefix datasets into Rust source (cargo run -p xtask -- sync-metadata) |
tools/ |
Parity checker (check_vs_upstream.py) and supplement generator (gen_geo_supplement.py) |
vendor/ |
Pinned upstream inputs: libphonenumber v9.0.44 XML + geocoding/carrier/timezone data, python-phonenumbers sources, and the transifex-derived geo supplement |
Rust stable ≥ 1.88 (edition 2021). Python ≥ 3.10.
# regenerate metadata if vendor/ changed (must stay deterministic):
cargo run -p xtask -- sync-metadata
cargo run -p xtask -- verify-metadata # fails if generated files drift
# Rust tests (includes LUT superset + generated-table smoke tests):
cargo test --workspace
# Python extension (into an activated venv):
maturin develop --release
python -c "import phonenumbers_rs; print(phonenumbers_rs.__version__)"All tables under crates/pn-metadata/src/generated/ are machine-generated
from the vendored libphonenumber XML with the exact semantics of the
python-phonenumbers generator (including \1-style format references and
length handling). Parity with the upstream python data is enforced by:
python3 tools/gen_geo_supplement.py # one-time; derives transifex-only geo entries
python3 tools/check_vs_upstream.py # exits non-zero on any mismatchThe checker compares every region (main, testing, short, alternate formats), the country-code maps, and the full geocoding (287k prefixes), carrier and timezone prefix datasets against the vendored python-phonenumbers package — currently all checks pass.
LUTs (per-pattern digit prefilters) are validated at build time against
regex-automata probe semantics; a pattern whose derived LUT cannot be
verified ships regex-only, so LUT results are always a sound superset.
On top of the table checks, behaviour is pinned by two differential suites that run the vendored python-phonenumbers as ground truth:
- Vector replay (
tests/vectors/vectors.jsonl→cargo test -p pn-core): 5103 golden vectors covering parse (all fields + error codes), every format function, AS-you-type digit sequences, geocoder/carrier/timezone lookups and free-textfind_numbers(spans, raw strings, E164 of each match) across all leniencies. - Hypothesis fuzzing (
tests/python_difftest/test_parity.py): random unicode/prose × 13 regions compared field-by-field against upstream —PHONES_FUZZ_EXAMPLES=5000 pytest tests/python_difftestis the release gate (green).
python3 benchmarks/run_bench.py (release build, pinned to one core of an
AMD EPYC 7601; upstream phonenumbers loaded from vendor/):
| benchmark | python | native | speedup |
|---|---|---|---|
| parse + validate + format (single call) | 54.7 µs | 7.3 µs | 7.5× |
PhoneNumberMatcher over ~10 KB blob |
3189 µs | 418 µs | 7.6× |
AsYouTypeFormatter (10 digits) |
124.9 µs | 15.5 µs | 8.1× |
| parse + validate 100 000 numbers | 4368 ms | 557 ms | 7.8× |
| cold import: time / RSS growth | 31–67 ms / 3.2–7.3 MB | 2.5–3.9 ms / 4.7–6.5 MB | ~10–20× faster / not smaller |
Cold-import figures are ranges over three runs; python's own import time and memory vary a lot between runs, and the native module does not reliably use less memory than pure python.
cargo bench -p phonenumbers-rs --bench engine covers the same operations
directly. Compare two saved runs with tools/bench_compare.py:
cargo bench -p phonenumbers-rs --bench engine -- --save-baseline before
# ...change code...
cargo bench -p phonenumbers-rs --bench engine -- --save-baseline after
python3 tools/bench_compare.py before afterEffect of wiring the pn-simd kernels into the engine (same machine and
core; only differences that held across three alternating before/after
rounds are counted; run-to-run noise on this host is about ±10%):
| benchmark | before | after | change |
|---|---|---|---|
is_valid_number ×23 |
97–103 µs | 75–81 µs | 1.26–1.34× |
number_type ×23 |
96–98 µs | 73–76 µs | 1.26–1.34× |
normalize_digits_only, short number |
304 ns | 56 ns | 5.4× |
normalize_digits_only, 10 KB text |
76 µs | 1.4 µs | 55× |
| parse, format, matcher, as-you-type | no change (within noise) |
Where each kernel is used:
lut_accepts+all_ascii_digits: before any regex check of a number against a type pattern, the pattern's digit table rejects numbers whose first digits can't match (matching::match_national_number).crates/pn-core/tests/lut_soundness.rschecks that every table accepts everything its regex accepts.extract_digits: the ASCII path ofnormalize_digits_only.ascii_digits_to_u64: the national number inparse.digit_runs: the ASCII path of the matcher's digit-group splitting (strict and exact grouping leniencies).
Effect of the regex-layer rework (two alternating before/after rounds on 8 cores of the same machine; ranges are the two rounds):
| benchmark | before | after | change |
|---|---|---|---|
parse international ×12 |
107 µs | 30–31 µs | 3.5–3.6× |
parse national ×12 |
119–121 µs | 39 µs | 3.0–3.1× |
is_valid_number ×23 |
75 µs | 30 µs | 2.5× |
number_type ×23 |
70–73 µs | 28–29 µs | 2.5× |
format_number international ×23 |
52–53 µs | 34–36 µs | 1.45–1.53× |
| parse + validate + format | 15–16 µs | 6.7–6.8 µs | 2.2–2.4× |
| matcher, 10 KB text | 1.14–1.20 ms | 426–447 µs | 2.7× |
| matcher, 10 KB text, strict grouping | 1.25–1.32 ms | 510–545 µs | 2.4–2.5× |
| as-you-type, 10 digits | 16–17 µs | 11.7–11.9 µs | 1.4× |
is_valid_number, 8 threads at once |
148–149 ms | 9.5–10.5 ms | 14–16× |
What changed:
- Compiled regexes are cached per thread in front of a shared
compile-once map, so a warm lookup takes no lock, hashes with FxHash
instead of SipHash, and allocates nothing. Before, every call took one
global mutex and built a
Stringkey; with several threads (python batch calls release the GIL) they all queued on that mutex. fullmatchpatterns are compiled once in their^(?:…)$form instead of being re-wrapped withformat!on every call.- Number-pattern checks run one match instead of two (an anchored match and then a full match), and "does it match here" checks no longer compute capture groups.
- Engine patterns built from constants (the matcher's candidate pattern, the extension patterns, and others) are built once instead of on every call.
- The matcher keeps its text as UTF-8 once instead of rebuilding it on
every
find, and maps between byte and character offsets directly for ASCII text instead of rescanning from the start.
workspace.package.version in Cargo.toml is the single version for all
three crates and the Python package. To release:
- Bump
workspace.package.versionand the threeversion = "=X.Y.Z"pins under[workspace.dependencies], then merge tomain. - Tag and push:
git tag vX.Y.Z && git push origin vX.Y.Z.
.github/workflows/release.yml checks the tag against the version, builds
abi3 wheels (manylinux/musllinux x86_64 + aarch64, macOS arm64 + x86_64,
Windows x64) and the sdist, runs the parity suite against every artifact, then
publishes to PyPI and crates.io with trusted publishing (no stored tokens).
Running the workflow manually (workflow_dispatch) does everything except
publish.
- PyPI: add a pending trusted publisher for project
phonenumbers-rs: ownerMasonLyons, repositoryphonenumbers-rs, workflowrelease.yml, environmentpypi. - crates.io: trusted publishing only applies to crates that already
exist, so publish 0.1.0 once by hand with an API token (in dependency order:
cargo publish -p phonenumbers-rs-simd, then-metadata, thenphonenumbers-rs). Then, for each of the three crates, add a trusted publisher (repositoryMasonLyons/phonenumbers-rs, workflowrelease.yml, environmentcrates-io) and revoke the token. - GitHub: create the
pypiandcrates-ioenvironments, restricted tov*tags (optionally with a required reviewer).
Apache-2.0 (same as libphonenumber and python-phonenumbers). Vendored
upstream data retains its original licenses and provenance notes under
vendor/.