|
6 | 6 |
|
7 | 7 | # NOTE: This code is carefully optimised. Do not tweak it (for readability or otherwise) without benchmarking |
8 | 8 | @inline function intern!(wkd::WeakKeyDict{K}, key)::K where K |
9 | | - kk::K = convert(K, key) |
10 | | - |
11 | 9 | lock(wkd.lock) |
12 | 10 | # hand positioning the locks and unlocks (rather than do block or try finally, seems to be faster) |
13 | | - index = Base.ht_keyindex2(wkd.ht, kk) # returns index if present, or -index if not |
| 11 | + index = Base.ht_keyindex2(wkd.ht, key) # returns index if present, or -index if not |
14 | 12 | # note hash of weakref is equal to the hash of value, so avoid constructing it if not required |
15 | 13 | if index > 0 |
16 | 14 | # found it |
|
20 | 18 | else |
21 | 19 | # Not found, so add it, |
22 | 20 | # and mark it as a reference we track to delete! |
| 21 | + kk::K = convert(K, key) |
23 | 22 | finalizer(kk, wkd.finalizer) # finalizer is set on the strong ref |
24 | 23 | @inbounds Base._setindex!(wkd.ht, nothing, WeakRef(kk), -index) |
25 | 24 | unlock(wkd.lock) |
|
40 | 39 |
|
41 | 40 | ################################### |
42 | 41 |
|
| 42 | +""" |
| 43 | + intern(s::T) |
| 44 | +
|
| 45 | +Return a reference to a interned instance of `s`, |
| 46 | +adding it to the interning pool if it did not already exist. |
| 47 | +""" |
43 | 48 | function intern(s::T)::T where T |
44 | | - intern!(get_pool(T), s) |
| 49 | + intern(T, s) |
45 | 50 | end |
46 | 51 |
|
47 | | -intern(s::String)=intern!(get_pool(String), s) # Break stack-overflow |
| 52 | +""" |
| 53 | + intern(::Type{T}, s) |
48 | 54 |
|
| 55 | +Intern `s` as if it were type `T`, converting it if required. |
| 56 | +Note that this will lead to unexpected behavour if the type of `s`, and `T`, |
| 57 | +do not have equivalent equality and hash functions |
| 58 | +(i.e. this is not safe if `hash(s) != hash(convert(T, s))`). |
| 59 | +""" |
| 60 | +function intern(::Type{T}, s)::T where T |
| 61 | + intern!(get_pool(T), s) |
| 62 | +end |
49 | 63 |
|
50 | 64 |
|
51 | 65 | """ |
52 | 66 | Substrings are interned as their parent string type |
53 | 67 | """ |
54 | 68 | function intern(substr::SubString{T})::T where T |
55 | | - intern(T(substr)) |
| 69 | + intern(T, substr) |
56 | 70 | end |
57 | 71 |
|
58 | 72 |
|
|
0 commit comments