Debian Codegraph @

debian/rust-vendor/fancy-regex/examples/compile_mem.rs

raw
1 // Copyright 2026 The Fancy Regex Authors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 //! Measures the memory cost of compiling patterns, via a counting global
22 //! allocator. For each pattern it reports:
23 //!
24 //! * `peak` – the high-water mark of *live* bytes during the compile
25 //! (transient working set).
26 //! * `retained` – bytes still live after the compile, i.e. the steady-state
27 //! size of the finished `Regex` / `RegexSet`.
28 //! * `total` – cumulative bytes requested during the compile (churn).
29 //!
30 //! Run with: `cargo run --release --example compile_mem`
31
32 use std::alloc::{GlobalAlloc, Layout, System};
33 use std::hint::black_box;
34 use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
35
36 use fancy_regex::{Regex, RegexSet};
37
38 struct Tracking;
39
40 static LIVE: AtomicUsize = AtomicUsize::new(0);
41 static PEAK: AtomicUsize = AtomicUsize::new(0);
42 static TOTAL: AtomicUsize = AtomicUsize::new(0);
43
44 unsafe impl GlobalAlloc for Tracking {
45 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
46 let ptr = System.alloc(layout);
47 if !ptr.is_null() {
48 let size = layout.size();
49 TOTAL.fetch_add(size, Relaxed);
50 let live = LIVE.fetch_add(size, Relaxed) + size;
51 // Bump the peak if we exceeded it (best-effort, racy under threads
52 // but this example is single-threaded during measurement).
53 PEAK.fetch_max(live, Relaxed);
54 }
55 ptr
56 }
57
58 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
59 System.dealloc(ptr, layout);
60 LIVE.fetch_sub(layout.size(), Relaxed);
61 }
62
63 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
64 let new_ptr = System.realloc(ptr, layout, new_size);
65 if !new_ptr.is_null() {
66 let old = layout.size();
67 if new_size >= old {
68 let delta = new_size - old;
69 TOTAL.fetch_add(delta, Relaxed);
70 let live = LIVE.fetch_add(delta, Relaxed) + delta;
71 PEAK.fetch_max(live, Relaxed);
72 } else {
73 LIVE.fetch_sub(old - new_size, Relaxed);
74 }
75 }
76 new_ptr
77 }
78 }
79
80 #[global_allocator]
81 static ALLOC: Tracking = Tracking;
82
83 /// Run `build` once with allocation tracking and print a labelled report.
84 /// The returned value is held until after measurement so `retained` reflects
85 /// the steady-state size of the compiled object.
86 fn measure<T>(label: &str, build: impl FnOnce() -> T) {
87 let live_before = LIVE.load(Relaxed);
88 let total_before = TOTAL.load(Relaxed);
89 PEAK.store(live_before, Relaxed);
90
91 let held = black_box(build());
92
93 let peak = PEAK.load(Relaxed).saturating_sub(live_before);
94 let retained = LIVE.load(Relaxed).saturating_sub(live_before);
95 let total = TOTAL.load(Relaxed) - total_before;
96
97 println!(
98 "{:<28} peak {:>9} B retained {:>9} B total {:>9} B",
99 label, peak, retained, total
100 );
101
102 drop(held);
103 }
104
105 const EASY_LITERAL: &str =
106 r"^\\([!-/:-@\[-`\{-~aftnrv]|[0-7]{1,3}|x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]{1,6}\})";
107 const EASY_EMAIL: &str = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}";
108 const DELEGATE_HEAVY: &str = r"(\d{3})(?=x)[a-z]+(?<=ab)\w+\1[A-Z]{2}(?!q)\s+foo";
109
110 fn delegate_stress() -> String {
111 let mut s = String::new();
112 for _ in 0..20 {
113 s.push_str("[a-z]{2}(?=x)");
114 }
115 s
116 }
117
118 fn large_alternation() -> String {
119 let mut s = String::from(r"\b(?:");
120 for i in 0..100 {
121 if i != 0 {
122 s.push('|');
123 }
124 s.push_str("word");
125 s.push_str(&i.to_string());
126 }
127 s.push_str(r")\b");
128 s
129 }
130
131 fn regexset_patterns() -> Vec<String> {
132 vec![
133 r"\d{4}-\d{2}-\d{2}".to_string(),
134 r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}".to_string(),
135 r"(?<=\$)\d+(?:\.\d{2})?".to_string(),
136 r"(\w+)\s+\1".to_string(),
137 r"(?:https?|ftp)://\S+".to_string(),
138 r"#[0-9a-fA-F]{6}\b".to_string(),
139 r"foo(?=bar)".to_string(),
140 r"\b[A-Z][a-z]+\b".to_string(),
141 ]
142 }
143
144 fn main() {
145 // Warm up any lazy globals so they don't pollute the first measurement.
146 drop(black_box(Regex::new("a").unwrap()));
147
148 let stress = delegate_stress();
149 let large_alt = large_alternation();
150 let set_pats = regexset_patterns();
151
152 println!("Compilation memory cost (release build recommended):\n");
153 measure("easy/literal", || Regex::new(EASY_LITERAL).unwrap());
154 measure("easy/email", || Regex::new(EASY_EMAIL).unwrap());
155 measure("large_alternation", || Regex::new(&large_alt).unwrap());
156 measure("delegate_heavy/realistic", || {
157 Regex::new(DELEGATE_HEAVY).unwrap()
158 });
159 measure("delegate_heavy/stress20", || Regex::new(&stress).unwrap());
160 measure("regexset/8", || RegexSet::new(&set_pats).unwrap());
161 }