weak 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +15 -0
- data/CODE_OF_CONDUCT.md +134 -0
- data/LICENSE.txt +21 -0
- data/README.md +232 -0
- data/lib/weak/map/abstract_strong_keys.rb +87 -0
- data/lib/weak/map/deletable.rb +65 -0
- data/lib/weak/map/strong_keys.rb +186 -0
- data/lib/weak/map/strong_secondary_keys.rb +229 -0
- data/lib/weak/map/weak_keys.rb +134 -0
- data/lib/weak/map/weak_keys_with_delete.rb +126 -0
- data/lib/weak/map.rb +714 -0
- data/lib/weak/set/strong_keys.rb +123 -0
- data/lib/weak/set/strong_secondary_keys.rb +154 -0
- data/lib/weak/set/weak_keys.rb +107 -0
- data/lib/weak/set/weak_keys_with_delete.rb +94 -0
- data/lib/weak/set.rb +749 -0
- data/lib/weak/version.rb +14 -0
- data/lib/weak.rb +45 -0
- metadata +65 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 0d9cec118afb4ce760b9f1881b0489f9e9b1954ad5c20727d8d1124f9d80027d
|
4
|
+
data.tar.gz: f0fd0cef1c7ce6403fb12630b880cb262063bc759100cfc4a6c7896cd0721e98
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: c91a2284ad2a25a96ede2f44fcb2e6ed94d08342d83fefe3096c867385369b5ad48977fea610f611894ed763e981cb1b424dd84c23471ba9fb9bc3c19941b8c4
|
7
|
+
data.tar.gz: 2bfd81fc7bb755ee7156a30527478c745dd10e8fff4b5865af823b3726c7105302d446aea9afc3e8c5d4e51ce612e28005c98cb8af5b0a76f98891aa0313cf36
|
data/CHANGELOG.md
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
# Changelog
|
2
|
+
|
3
|
+
## [0.1.0] - 2025-03-14
|
4
|
+
|
5
|
+
- Initial version of `Weak::Set` to store an unordered collection of objects.
|
6
|
+
- Initial version of `Weak::Map` to store key-value pairs of objects.
|
7
|
+
|
8
|
+
- Support for Ruby 3.0 using the following impementations
|
9
|
+
- Ruby (aka. MRI, aka. YARV) >= 3.0
|
10
|
+
- JRuby >= 9.4
|
11
|
+
- TruffleRuby >= 22
|
12
|
+
|
13
|
+
## [0.0.1.pre] - 2025-02-05
|
14
|
+
|
15
|
+
- First blank slate
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,134 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
https://github.com/meineerde/weak/issues/new or privately by contacting
|
64
|
+
Holger Just using the communication methods mentioned at
|
65
|
+
https://holgerjust.de/contact/.
|
66
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
67
|
+
|
68
|
+
All community leaders are obligated to respect the privacy and security of the
|
69
|
+
reporter of any incident.
|
70
|
+
|
71
|
+
## Enforcement Guidelines
|
72
|
+
|
73
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
74
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
75
|
+
|
76
|
+
### 1. Correction
|
77
|
+
|
78
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
79
|
+
unprofessional or unwelcome in the community.
|
80
|
+
|
81
|
+
**Consequence**: A private, written warning from community leaders, providing
|
82
|
+
clarity around the nature of the violation and an explanation of why the
|
83
|
+
behavior was inappropriate. A public apology may be requested.
|
84
|
+
|
85
|
+
### 2. Warning
|
86
|
+
|
87
|
+
**Community Impact**: A violation through a single incident or series of
|
88
|
+
actions.
|
89
|
+
|
90
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
91
|
+
interaction with the people involved, including unsolicited interaction with
|
92
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
93
|
+
includes avoiding interactions in community spaces as well as external channels
|
94
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
95
|
+
ban.
|
96
|
+
|
97
|
+
### 3. Temporary Ban
|
98
|
+
|
99
|
+
**Community Impact**: A serious violation of community standards, including
|
100
|
+
sustained inappropriate behavior.
|
101
|
+
|
102
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
103
|
+
communication with the community for a specified period of time. No public or
|
104
|
+
private interaction with the people involved, including unsolicited interaction
|
105
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
106
|
+
Violating these terms may lead to a permanent ban.
|
107
|
+
|
108
|
+
### 4. Permanent Ban
|
109
|
+
|
110
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
111
|
+
standards, including sustained inappropriate behavior, harassment of an
|
112
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
113
|
+
|
114
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
115
|
+
community.
|
116
|
+
|
117
|
+
## Attribution
|
118
|
+
|
119
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
120
|
+
version 2.1, available at
|
121
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
122
|
+
|
123
|
+
Community Impact Guidelines were inspired by
|
124
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
125
|
+
|
126
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
127
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
128
|
+
[https://www.contributor-covenant.org/translations][translations].
|
129
|
+
|
130
|
+
[homepage]: https://www.contributor-covenant.org
|
131
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
132
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
133
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
134
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 Holger Just
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,232 @@
|
|
1
|
+
# Weak
|
2
|
+
|
3
|
+
[](https://rubygems.org/gems/weak)
|
4
|
+
[](https://github.com/meineerde/weak/actions/workflows/ci.yml)
|
5
|
+
[](https://coveralls.io/github/meineerde/weak?branch=main)
|
6
|
+
|
7
|
+
Weak is a Ruby library which implements collections of unordered values without strong object references.
|
8
|
+
|
9
|
+
We provide multiple classes which behave similar to their standard-library counterparts. However, all elements are only weakly referenced. That way, all elements can be garbage collected and silently removed from the collection unless they are still referenced from some other live object.
|
10
|
+
|
11
|
+
## Weak::Set
|
12
|
+
|
13
|
+
`Weak::Set` behaves similar to the [Set](https://docs.ruby-lang.org/en/3.4/Set.html) class of the Ruby standard library, but all values are only weakly referenced. That way, all values can be garbage collected and silently removed from the set unless they are still referenced from some other live object.
|
14
|
+
|
15
|
+
Compared to the `Set` class however, there are a few differences:
|
16
|
+
|
17
|
+
- All element references are weak, allowing each element to be garbage collected unless there is a strong reference to it somwhere else.
|
18
|
+
- We do not necessarily retain the order of elements as they are inserted into the `Weak::Set`. You should not rely on a specific order.
|
19
|
+
- Set membership is governed by object identity rather than by using the `hash` and `eql?` methods of the elements. A `Weak::Set` thus works similat to a `Set` marked as [compare_by_identity](https://docs.ruby-lang.org/en/3.4/Set.html#method-i-compare_by_identity).
|
20
|
+
- You can freely change any objects added to the `Weak::Set`.
|
21
|
+
|
22
|
+
```ruby
|
23
|
+
require "weak/set"
|
24
|
+
set = Weak::Set.new
|
25
|
+
|
26
|
+
set << "some string"
|
27
|
+
# => #<Weak::Set {"some string"}>
|
28
|
+
|
29
|
+
# Do some work, wait a bit, or force a garbage collection run
|
30
|
+
3.times { GC.start }
|
31
|
+
|
32
|
+
set
|
33
|
+
# => #<Weak::Set {}>
|
34
|
+
```
|
35
|
+
|
36
|
+
## Weak::Map
|
37
|
+
|
38
|
+
`Weak::Map` behaves similar to a `Hash` or an `ObjectSpace::WeakMap` in Ruby (aka. MRI, aka. YARV).
|
39
|
+
Both keys and values are weak references, allowing either of them to be garbage collected. If either the key or the value of a pair is garbage collected, the entire pair will be removed from the `Weak::Map`.
|
40
|
+
|
41
|
+
Compared to the `Set` class however, there are a few differences:
|
42
|
+
|
43
|
+
- Key and value references are weak, allowing each key-value pair to be garbage collected unless there is a strong reference to boith the key and the value somewhere else.
|
44
|
+
- We do not necessarily retain the order of elements as they are inserted into the `Weak::Map`. You should not rely on a specific order.
|
45
|
+
- Map membership is governed by object identity of the key rather than by using the `hash` and `eql?` methods of the elements. A `Weak::Map` thus works similat to a `Hash` marked as [compare_by_identity](https://docs.ruby-lang.org/en/3.4/Hash.html#method-i-compare_by_identity).
|
46
|
+
- You can freely change both keys and values added to the `Weak::Map`.
|
47
|
+
|
48
|
+
```ruby
|
49
|
+
require "weak/map"
|
50
|
+
map = Weak::Map.new
|
51
|
+
|
52
|
+
map["some key"] = "a value"
|
53
|
+
# => #<Weak::Map {"some key" => "a value"}>
|
54
|
+
|
55
|
+
# Do some work, wait a bit, or force a garbage collection run
|
56
|
+
3.times { GC.start }
|
57
|
+
|
58
|
+
map
|
59
|
+
# => #<Weak::Map {}>
|
60
|
+
```
|
61
|
+
|
62
|
+
## Usage
|
63
|
+
|
64
|
+
Please refer to the documentation at:
|
65
|
+
|
66
|
+
- [📘 Documentation](https://www.rubydoc.info/gems/weak)
|
67
|
+
- [💥 Development Documentation](https://www.rubydoc.info/github/meineerde/weak/main) of the [main branch](https://github.com/meineerde/weak/tree/main)
|
68
|
+
|
69
|
+
> [!WARNING]
|
70
|
+
> The Weak collections are not inherently thread-safe. When accessing a collection from multiple threads or fibers, you MUST use a mutex or another locking mechanism.
|
71
|
+
|
72
|
+
The Weak collections use Ruby's [ObjectSpace::WeakMap](https://docs.ruby-lang.org/en/3.4/ObjectSpace/WeakMap.html) under the hood. Unfortunately, different Ruby implementations and versions such as Ruby (aka. MRI, aka. YARV), JRuby, or TruffleRuby show quite diverse behavior in their respective `ObjectSpace::WeakMap` implementations. To provide a unified behavior on all supported Rubies, we use multiple different storage strategies.
|
73
|
+
|
74
|
+
The appropriate strategy is selected automatically. Their exposed behavior should be identical across all implementations. If you experience diverging behavior, we consider this a bug. Please [open an issue](https://github.com/meineerde/weak/issues/new) and describe the diverging or unexpected behavior.
|
75
|
+
|
76
|
+
## Installation
|
77
|
+
|
78
|
+
Weak supports the following Ruby implementation:
|
79
|
+
|
80
|
+
- Ruby (aka. MRI, aka. YARV) >= 3.0
|
81
|
+
- JRuby >= 9.4
|
82
|
+
- TruffleRuby >= 22
|
83
|
+
|
84
|
+
Add the `weak` gem to the application's `Gemfile` and install it by executing:
|
85
|
+
|
86
|
+
```sh
|
87
|
+
bundle add weak
|
88
|
+
```
|
89
|
+
|
90
|
+
If [bundler](https://bundler.io/) is not being used to manage dependencies, install the gem manually by executing:
|
91
|
+
|
92
|
+
```sh
|
93
|
+
gem install weak
|
94
|
+
```
|
95
|
+
|
96
|
+
## Examples
|
97
|
+
|
98
|
+
### Weak::Set Example
|
99
|
+
|
100
|
+
A Weak::Set can be used as a cache or for validation purposes were it is not desirable to keep a full object reference. For example, it can be used with a basic `ConnectionPool` as follows
|
101
|
+
|
102
|
+
```ruby
|
103
|
+
require "weak/set"
|
104
|
+
|
105
|
+
class Connection
|
106
|
+
# A sample connection class.
|
107
|
+
# Our ConnectionPool will return objects from this class.
|
108
|
+
end
|
109
|
+
|
110
|
+
class ConnectionPool
|
111
|
+
def initialize
|
112
|
+
@pool = []
|
113
|
+
@outstanding = Weak::Set.new
|
114
|
+
@mutex = Mutex.new
|
115
|
+
end
|
116
|
+
|
117
|
+
# Fetch or create a connection object. The connection object can (but does not
|
118
|
+
# have to) be returned to the pool again with `checkin`.
|
119
|
+
def checkout
|
120
|
+
@mutex.synchronize do
|
121
|
+
connection = @pool.pop || Connection.new
|
122
|
+
@outstanding << connection
|
123
|
+
|
124
|
+
connection
|
125
|
+
end
|
126
|
+
end
|
127
|
+
|
128
|
+
# Allows to return a previously checked-out connection object back to the pool
|
129
|
+
# for later re-use. Only connection objects which were previously checked-out
|
130
|
+
# can be returned to the pool.
|
131
|
+
def checkin(connection)
|
132
|
+
@mutex.synchronize do
|
133
|
+
if @outstanding.delete?(connection)
|
134
|
+
@pool.push connection
|
135
|
+
else
|
136
|
+
raise ArgumentError, "connection was not checked out before"
|
137
|
+
end
|
138
|
+
end
|
139
|
+
|
140
|
+
nil
|
141
|
+
end
|
142
|
+
|
143
|
+
# Fetch or create a connection object and yield it to the given block. After
|
144
|
+
# the block completes, the connection is automatically checked-in again for
|
145
|
+
# later re-use. The method returns the return value of the block.
|
146
|
+
def with
|
147
|
+
connection = checkout
|
148
|
+
begin
|
149
|
+
yield connection
|
150
|
+
ensure
|
151
|
+
checkin(connection)
|
152
|
+
end
|
153
|
+
end
|
154
|
+
end
|
155
|
+
```
|
156
|
+
|
157
|
+
During `checkout` we remember a reference to the returned connection object in the `@outstanding` weak set. The caller is free to do whatever they like with the connection. Specifically, they are not required to return the connection to the pool.
|
158
|
+
|
159
|
+
If the caller just "forgets" the connection, our pool will also forget it during the next Ruby garbage collection run.
|
160
|
+
|
161
|
+
If the caller returns the connection by calling `checkin` again, we can verify that we have in fact created the object by deleting it from the `@outstanding` list. That way, the a checked-out connection can be checked-in again only once and only if it was initially created by the `ConnectionPool`.
|
162
|
+
|
163
|
+
### Weak::Map Example
|
164
|
+
|
165
|
+
Conversely a `Weak::Map` can be used to store references to other objects. In the example below, we use a single `Mutex` for each `obj` wrapped in a `LockedObject` instance.
|
166
|
+
|
167
|
+
Even if a single object is wrapped in multiple `LockedObject` instances, we still use the same shared mutex in each of these instances, ensuring that the `obj` is only every accessed while holding the mutex. Different objects use different mutexes.
|
168
|
+
|
169
|
+
If all LockedObject instances for an `obj` and the `obj` itself vanish by being garbage collected, the associated mutex will also be garbage collected without requiring any external coordination.
|
170
|
+
|
171
|
+
```ruby
|
172
|
+
class LockedObject < BasicObject
|
173
|
+
LOCKS = Weak::Map.new
|
174
|
+
LOCKS_MUTEX = Mutex.new
|
175
|
+
|
176
|
+
def initialize(obj)
|
177
|
+
@obj = obj
|
178
|
+
|
179
|
+
# Assigning the obj mutex must itself be wrapped in a different mutex as a Weak::Map
|
180
|
+
# is not thread-safe. We retain the mutex for obj in @mutex for the LockedObject
|
181
|
+
# instance.
|
182
|
+
LOCKS_MUTEX.synchronize do
|
183
|
+
@mutex = (LOCKS[obj] ||= Mutex.new)
|
184
|
+
end
|
185
|
+
end
|
186
|
+
|
187
|
+
private
|
188
|
+
|
189
|
+
def method_missing(m, *args, **kwargs, &block)
|
190
|
+
@mutex.synchronize do
|
191
|
+
obj.public_send(m, *args, **kwargs, &block)
|
192
|
+
end
|
193
|
+
end
|
194
|
+
|
195
|
+
def respond_to_missing?(m)
|
196
|
+
obj.respond_to?(m)
|
197
|
+
end
|
198
|
+
end
|
199
|
+
|
200
|
+
string = "foo"
|
201
|
+
|
202
|
+
# As an example, we simulate concurrent access to the string from multiple Threads.
|
203
|
+
# Especially on JRuby, you would likely see data corruptions without the mutex here.
|
204
|
+
5.times do
|
205
|
+
Thread.new do
|
206
|
+
locked = Locked.new(string)
|
207
|
+
("a".."z").each do |char|
|
208
|
+
locked << char*2
|
209
|
+
end
|
210
|
+
end
|
211
|
+
end
|
212
|
+
```
|
213
|
+
|
214
|
+
## Development
|
215
|
+
|
216
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
217
|
+
|
218
|
+
[](https://github.com/standardrb/standard)
|
219
|
+
|
220
|
+
We follow the Standard Ruby style. Please make sure that all code is formatted according to the Standard rules. This is enforced by the CI. Please try to keep all code lines at or below 100 characters in length.
|
221
|
+
|
222
|
+
## Contributing
|
223
|
+
|
224
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/meineerde/weak. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/meineerde/weak/blob/main/CODE_OF_CONDUCT.md).
|
225
|
+
|
226
|
+
## License
|
227
|
+
|
228
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
229
|
+
|
230
|
+
## Code of Conduct
|
231
|
+
|
232
|
+
Everyone interacting in the Weak project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/meineerde/weak/blob/main/CODE_OF_CONDUCT.md).
|
@@ -0,0 +1,87 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# Copyright (c) Holger Just
|
4
|
+
#
|
5
|
+
# This software may be modified and distributed under the terms
|
6
|
+
# of the MIT license. See the LICENSE.txt file for details.
|
7
|
+
|
8
|
+
require "weak/map/deletable"
|
9
|
+
|
10
|
+
##
|
11
|
+
module Weak
|
12
|
+
class Map
|
13
|
+
# @abstract This module implements a common subset of (helper-)methods
|
14
|
+
# for a {Weak::Map} with an `ObjectSpace::WeakMap` with strong keys, i.e.,
|
15
|
+
# {StrongKeys} and {StrongSecondaryKeys}.
|
16
|
+
module AbstractStrongKeys
|
17
|
+
include Deletable
|
18
|
+
|
19
|
+
# @!macro weak_map_method_keys
|
20
|
+
def keys
|
21
|
+
each_key.to_a
|
22
|
+
end
|
23
|
+
|
24
|
+
# @!macro weak_map_method_size
|
25
|
+
def size
|
26
|
+
each_key.count
|
27
|
+
end
|
28
|
+
|
29
|
+
# @!macro weak_map_method_values
|
30
|
+
def values
|
31
|
+
each_value.to_a
|
32
|
+
end
|
33
|
+
|
34
|
+
private
|
35
|
+
|
36
|
+
# This method is called during {#_get}. It generally needs to be
|
37
|
+
# overwritten in a "sub"-mdule to automatically cleanup any internal data.
|
38
|
+
# The implemented `auto_prune` method should quickly check if a prune is
|
39
|
+
# necessary and then either call the `prune` method or return.
|
40
|
+
#
|
41
|
+
# @return [void]
|
42
|
+
def auto_prune
|
43
|
+
end
|
44
|
+
|
45
|
+
def _delete(id)
|
46
|
+
if have?(@keys[id])
|
47
|
+
@keys[id] = DeletedEntry.new
|
48
|
+
has_key = true
|
49
|
+
end
|
50
|
+
|
51
|
+
raw_value = @values[id]
|
52
|
+
if have?(raw_value)
|
53
|
+
@values[id] = DeletedEntry.new
|
54
|
+
return value!(raw_value) if has_key
|
55
|
+
end
|
56
|
+
|
57
|
+
yield
|
58
|
+
end
|
59
|
+
|
60
|
+
def _get(id)
|
61
|
+
raw_value = @values[id]
|
62
|
+
has_key = have?(@keys[id])
|
63
|
+
|
64
|
+
auto_prune
|
65
|
+
if have?(raw_value)
|
66
|
+
if has_key
|
67
|
+
# We have a stored key AND a stored value. This is the positive case
|
68
|
+
# where we return the stored value
|
69
|
+
value!(raw_value)
|
70
|
+
else
|
71
|
+
# Here, we have a stored value but a missing key which likely was
|
72
|
+
# garbage collected. Thus, we explicitly delete the now invalid
|
73
|
+
# value and act as if it was already removed.
|
74
|
+
@values[id] = DeletedEntry.new
|
75
|
+
yield
|
76
|
+
end
|
77
|
+
else
|
78
|
+
# Here, we do not have a stored value (e.g. because it was garbage
|
79
|
+
# collected or is generally absent). If we have found a valid key
|
80
|
+
# earlier, this key is thus invalid and we explicitly delete it.
|
81
|
+
@keys[id] = DeletedEntry.new if has_key
|
82
|
+
yield
|
83
|
+
end
|
84
|
+
end
|
85
|
+
end
|
86
|
+
end
|
87
|
+
end
|
@@ -0,0 +1,65 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# Copyright (c) Holger Just
|
4
|
+
#
|
5
|
+
# This software may be modified and distributed under the terms
|
6
|
+
# of the MIT license. See the LICENSE.txt file for details.
|
7
|
+
|
8
|
+
##
|
9
|
+
module Weak
|
10
|
+
class Map
|
11
|
+
# Utility methods used in {Weak::Map} strategies to emulate deletion when
|
12
|
+
# the `ObjectSpace:WeakMap` does not directly allow to delete elements.
|
13
|
+
module Deletable
|
14
|
+
# A class to create objects from to mark deleted entries. These objects
|
15
|
+
# can be garbage collected. When reading values, we handle DeletedEntry
|
16
|
+
# instances the same way we would handle `nil` values.
|
17
|
+
# @see #mising?
|
18
|
+
class DeletedEntry; end
|
19
|
+
private_constant :DeletedEntry
|
20
|
+
|
21
|
+
# A special marker value to store `nil` in the WeakMap. We use this
|
22
|
+
# constant to distinguish the user-provided `nil` value (which is stored
|
23
|
+
# as `NIL`) from the absent value.
|
24
|
+
NIL = Object.new
|
25
|
+
private_constant :NIL
|
26
|
+
|
27
|
+
private
|
28
|
+
|
29
|
+
# Checks if an object gathered from an `ObjectSpace::WeakMap` is present,
|
30
|
+
# i.e., if it is not `missing?`
|
31
|
+
#
|
32
|
+
# @param obj [Object] an object to check
|
33
|
+
# @return [Bool] `true` if the `obj` is a present value, i.e. it is
|
34
|
+
# neither `nil` nor a `DeletedEntry`; false otherwise
|
35
|
+
def have?(obj)
|
36
|
+
!missing?(obj)
|
37
|
+
end
|
38
|
+
|
39
|
+
# Checks if an object gathered from an `ObjectSpace::WeakMap` is missing.
|
40
|
+
# It is missing if it is either `nil` (if no value was present in the map)
|
41
|
+
# or if it is a `DeletedEntry` and was thus marked as deleted.
|
42
|
+
#
|
43
|
+
# The allowed `nil` value is represented with the special `NIL` constant
|
44
|
+
# which is not `missing?`.
|
45
|
+
#
|
46
|
+
# @param obj [Object] an object to check
|
47
|
+
# @return [Bool] `true` if the `obj` is absent, i.e. it is either `nil`
|
48
|
+
# or a `DeletedEntry`; false otherwise
|
49
|
+
def missing?(obj)
|
50
|
+
obj.nil? || DeletedEntry === obj
|
51
|
+
end
|
52
|
+
|
53
|
+
# Get the final value for a retreived raw value. This convertes the
|
54
|
+
# special `NIL` value back to `nil`.
|
55
|
+
# @param obj [Object, NIL] an object retreived from an
|
56
|
+
# `ObjectSpace::WeakMap`
|
57
|
+
# @return [Object, nil] the object or `nil` if `NIL` was given.
|
58
|
+
def value!(obj)
|
59
|
+
NIL.equal?(obj) ? nil : obj
|
60
|
+
end
|
61
|
+
end
|
62
|
+
|
63
|
+
private_constant :Deletable
|
64
|
+
end
|
65
|
+
end
|