@@ -64,6 +64,24 @@ impl RegexCache {
6464 self . recency . push_back ( pattern. to_string ( ) ) ;
6565 }
6666
67+ pub ( crate ) fn capacity ( & self ) -> usize {
68+ self . capacity
69+ }
70+
71+ pub ( crate ) fn set_capacity ( & mut self , capacity : usize ) {
72+ self . capacity = capacity;
73+ while self . entries . len ( ) > capacity {
74+ let Some ( oldest) = self . recency . pop_front ( ) else {
75+ self . entries . clear ( ) ;
76+ break ;
77+ } ;
78+ self . entries . remove ( & oldest) ;
79+ }
80+ if capacity == 0 {
81+ self . recency . clear ( ) ;
82+ }
83+ }
84+
6785 pub ( crate ) fn len ( & self ) -> usize {
6886 self . entries . len ( )
6987 }
@@ -167,4 +185,35 @@ mod tests {
167185 assert_eq ! ( cache. len( ) , 2 ) ;
168186 assert_eq ! ( cache. compile_count( ) , 3 ) ;
169187 }
188+
189+ #[ test]
190+ fn vm_regex_cache_capacity_can_be_changed_and_shrinks_immediately ( ) {
191+ let mut vm = Vm :: new ( Program :: new ( Vec :: new ( ) , vec ! [ OpCode :: Ret as u8 ] ) ) ;
192+ assert_eq ! ( vm. regex_cache_capacity( ) , DEFAULT_REGEX_CACHE_CAPACITY ) ;
193+
194+ builtin_re_match_impl ( & mut vm, "a" , "a" ) . expect ( "pattern should compile" ) ;
195+ builtin_re_match_impl ( & mut vm, "b" , "b" ) . expect ( "pattern should compile" ) ;
196+ builtin_re_match_impl ( & mut vm, "c" , "c" ) . expect ( "pattern should compile" ) ;
197+ vm. set_regex_cache_capacity ( 1 ) ;
198+
199+ assert_eq ! ( vm. regex_cache_capacity( ) , 1 ) ;
200+ assert_eq ! ( vm. regex_cache_entry_count( ) , 1 ) ;
201+ builtin_re_match_impl ( & mut vm, "c" , "c" ) . expect ( "most recent pattern should remain" ) ;
202+ assert_eq ! ( vm. regex_cache_compile_count( ) , 3 ) ;
203+ assert_eq ! ( vm. regex_cache_hit_count( ) , 1 ) ;
204+ }
205+
206+ #[ test]
207+ fn zero_vm_regex_cache_capacity_disables_caching ( ) {
208+ let mut vm = Vm :: new ( Program :: new ( Vec :: new ( ) , vec ! [ OpCode :: Ret as u8 ] ) ) ;
209+ vm. set_regex_cache_capacity ( 0 ) ;
210+
211+ builtin_re_match_impl ( & mut vm, "same" , "same" ) . expect ( "pattern should compile" ) ;
212+ builtin_re_match_impl ( & mut vm, "same" , "same" ) . expect ( "pattern should compile again" ) ;
213+
214+ assert_eq ! ( vm. regex_cache_capacity( ) , 0 ) ;
215+ assert_eq ! ( vm. regex_cache_entry_count( ) , 0 ) ;
216+ assert_eq ! ( vm. regex_cache_compile_count( ) , 2 ) ;
217+ assert_eq ! ( vm. regex_cache_hit_count( ) , 0 ) ;
218+ }
170219}
0 commit comments