@@ -15,78 +15,65 @@ struct Pair {
15
15
type Entries = LRUCache :: < [ Entry < Pair > ; 1_024 ] > ;
16
16
17
17
struct Cache {
18
- enabled : Cell < bool > ,
19
- max_str_len : Cell < usize > ,
20
18
entries : RefCell < Entries > ,
21
19
}
22
20
23
21
// TODO figure out a good max_str_len
24
22
thread_local ! {
25
23
static CACHE : Cache = Cache {
26
- enabled: Cell :: new( true ) ,
27
- max_str_len: Cell :: new( 128 ) ,
28
24
entries: RefCell :: new( LRUCache :: default ( ) ) ,
29
25
} ;
30
26
}
31
27
32
- fn get_js_string ( cache : & mut Entries , key : & str ) -> JsValue {
33
- if let Some ( p) = cache. find ( |p| p. key == key) {
34
- p. value . clone ( )
35
-
36
- } else {
37
- let value = JsValue :: from ( key) ;
38
-
39
- cache. insert ( Pair {
40
- key : key. to_owned ( ) ,
41
- value : value. clone ( ) ,
42
- } ) ;
28
+ fn get_js_string < ' a > ( cache : & ' a mut Entries , key : & str ) -> Option < & ' a JsValue > {
29
+ cache. find ( |p| p. key == key) . map ( |x| & x. value )
30
+ }
43
31
44
- value
45
- }
32
+ fn insert_js_string ( cache : & mut Entries , key : & str , value : JsValue ) {
33
+ cache. insert ( Pair {
34
+ key : key. to_owned ( ) ,
35
+ value,
36
+ } ) ;
46
37
}
47
38
48
- fn cache_str ( s : & str ) -> JsValue {
39
+ fn get_str ( s : & str ) -> JsValue {
49
40
CACHE . with ( |cache| {
50
- let should_cache =
51
- cache. enabled . get ( ) &&
52
- s. len ( ) <= cache. max_str_len . get ( ) ;
41
+ let mut cache = cache. entries . borrow_mut ( ) ;
53
42
54
- if should_cache {
55
- get_js_string ( & mut cache . entries . borrow_mut ( ) , s )
43
+ if let Some ( value ) = get_js_string ( & mut cache , s ) {
44
+ value . clone ( )
56
45
57
46
} else {
58
47
JsValue :: from ( s)
59
48
}
60
49
} )
61
50
}
62
51
52
+ fn intern_str ( s : & str ) {
53
+ CACHE . with ( |cache| {
54
+ let mut cache = cache. entries . borrow_mut ( ) ;
55
+
56
+ if get_js_string ( & mut cache, s) . is_none ( ) {
57
+ insert_js_string ( & mut cache, s, JsValue :: from ( s) ) ;
58
+ }
59
+ } )
60
+ }
61
+
63
62
#[ inline]
64
- pub fn str ( s : & str ) -> JsValue {
63
+ pub ( crate ) fn str ( s : & str ) -> JsValue {
65
64
if cfg ! ( feature = "disable-interning" ) {
66
65
JsValue :: from ( s)
67
66
68
67
} else {
69
- cache_str ( s)
70
- }
71
- }
72
-
73
- #[ inline]
74
- pub fn set_max_str_len ( len : usize ) {
75
- if !cfg ! ( feature = "disable-interning" ) {
76
- CACHE . with ( |cache| cache. max_str_len . set ( len) ) ;
68
+ get_str ( s)
77
69
}
78
70
}
79
71
80
72
#[ inline]
81
- pub fn enable ( ) {
73
+ pub fn intern ( s : & str ) -> & str {
82
74
if !cfg ! ( feature = "disable-interning" ) {
83
- CACHE . with ( |cache| cache . enabled . set ( true ) ) ;
75
+ intern_str ( s ) ;
84
76
}
85
- }
86
77
87
- #[ inline]
88
- pub fn disable ( ) {
89
- if !cfg ! ( feature = "disable-interning" ) {
90
- CACHE . with ( |cache| cache. enabled . set ( false ) ) ;
91
- }
78
+ s
92
79
}
0 commit comments