cache_machines 0.1.4 → 0.4.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e553d28a185ae5660c769b7c59b71bb3732df57f3f118425b59d993db8fd75d0
4
- data.tar.gz: 59cec0b71269767d0ede58db7cbb50c07421c341f99592c65ab4881b34d28e6e
3
+ metadata.gz: e6bcb239c5b3bb5711228f31b9e5c067ff86d39da7473fd77e402e3be57d67a4
4
+ data.tar.gz: 2289c4c426769390e832b632cd585fba153f2d3bdee423796b6da6a1468fd881
5
5
  SHA512:
6
- metadata.gz: 293cb97172f6518e702ae1e5bdf888d297530cf0f57f6d19b304c81a6db074768dea581f24befef6da6bbac8d3998fe61115842cfa17e5cf15755cb8e18dc1ad
7
- data.tar.gz: 103b95b31c494cb70106b06746854a1f50f4595160962d0414589e823fb72fd02ac6b7357f97e4defbddea2aaef4747bf28503100cc35434e252f0bf52207747
6
+ metadata.gz: 2e5a2ab97fdba759ade7aa2066caeb05e717af30fa11d8ccbab6ea71d64e635b86fadcf5032980b46ceb04409e5d90f8f423767af882187081d6258e8dcae991
7
+ data.tar.gz: 12030fbe8ca278901ba5bb786084b00af50e314ca9f65b2f2d70b1de82a8745b0a5cd68fefa98b22549e3eecb7f6e7cbaf61f037234c1a01655d1f78d894abfe
data/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.1](https://github.com/seuros/cache_machines/compare/cache_machines/v0.4.0...cache_machines/v0.4.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * fix wrapped classes at load so building a value runs no Ruby ([7d9ee47](https://github.com/seuros/cache_machines/commit/7d9ee47c4a37b5cc3081df9c4971f21c8211e217))
9
+
10
+ ## [0.4.0](https://github.com/seuros/cache_machines/compare/cache_machines/v0.3.2...cache_machines/v0.4.0) (2026-11-16)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * seal CacheMachines::Lru and drop the Default bound on Lru keys
16
+
17
+ ### Features
18
+
19
+ * seal CacheMachines::Lru and drop the Default bound on Lru keys ([078344c](https://github.com/seuros/cache_machines/commit/078344cbf653eb4891322caa936e9cbe3834f49b))
20
+
21
+ ## [0.3.2](https://github.com/seuros/cache_machines/compare/cache_machines/v0.3.1...cache_machines/v0.3.2) (2026-11-14)
22
+
23
+
24
+ ### Bug Fixes
25
+
26
+ * **deps:** require matryona-machines >= 0.4 ([9ca18ea](https://github.com/seuros/cache_machines/commit/9ca18eacb4125b68fc3acbbd55630146fbb8ddef))
27
+
28
+ ## [0.3.1](https://github.com/seuros/cache_machines/compare/cache_machines/v0.3.0...cache_machines/v0.3.1) (2026-11-14)
29
+
30
+
31
+ ### Bug Fixes
32
+
33
+ * **deps:** require matryona-machines >= 0.3 ([8457b36](https://github.com/seuros/cache_machines/commit/8457b3615d15c5c9cb4cbda2b5036a276d4628aa))
34
+
35
+ ## [0.3.0](https://github.com/seuros/cache_machines/compare/cache_machines/v0.2.0...cache_machines/v0.3.0) (2026-11-14)
36
+
37
+
38
+ ### ⚠ BREAKING CHANGES
39
+
40
+ * adopt matryona-machines 0.2 (symbols! tables, frozen-first)
41
+
42
+ ### Features
43
+
44
+ * adopt matryona-machines 0.2 (symbols! tables, frozen-first) ([7556afb](https://github.com/seuros/cache_machines/commit/7556afb823a70c16417c22390ceb5b955990ebfd))
45
+
46
+ ## [0.2.0](https://github.com/seuros/cache_machines/compare/cache_machines/v0.1.4...cache_machines/v0.2.0) (2026-11-14)
47
+
48
+
49
+ ### ⚠ BREAKING CHANGES
50
+
51
+ * answer Refusal/Access/Removal, admit never loses an eviction, Evicted validated, sealed and resolved at load
52
+
53
+ ### Features
54
+
55
+ * answer Refusal/Access/Removal, admit never loses an eviction, Evicted validated, sealed and resolved at load ([adac5a9](https://github.com/seuros/cache_machines/commit/adac5a9939b9e2468e7a9a99aed1db283fe96f94))
56
+
3
57
  ## [0.1.4](https://github.com/seuros/cache_machines/compare/cache_machines/v0.1.3...cache_machines/v0.1.4) (2026-11-06)
4
58
 
5
59
 
data/Cargo.lock ADDED
@@ -0,0 +1,307 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "aho-corasick"
7
+ version = "1.1.5"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
10
+ dependencies = [
11
+ "memchr",
12
+ ]
13
+
14
+ [[package]]
15
+ name = "bindgen"
16
+ version = "0.72.1"
17
+ source = "registry+https://github.com/rust-lang/crates.io-index"
18
+ checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
19
+ dependencies = [
20
+ "bitflags",
21
+ "cexpr",
22
+ "clang-sys",
23
+ "itertools",
24
+ "proc-macro2",
25
+ "quote",
26
+ "regex",
27
+ "rustc-hash",
28
+ "shlex",
29
+ "syn",
30
+ ]
31
+
32
+ [[package]]
33
+ name = "bitflags"
34
+ version = "2.13.2"
35
+ source = "registry+https://github.com/rust-lang/crates.io-index"
36
+ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
37
+
38
+ [[package]]
39
+ name = "bytes"
40
+ version = "1.12.1"
41
+ source = "registry+https://github.com/rust-lang/crates.io-index"
42
+ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
43
+
44
+ [[package]]
45
+ name = "cache-machines"
46
+ version = "0.5.0"
47
+ dependencies = [
48
+ "matryona-machines",
49
+ ]
50
+
51
+ [[package]]
52
+ name = "cache_machines_native"
53
+ version = "0.1.6"
54
+ dependencies = [
55
+ "cache-machines",
56
+ "magnus",
57
+ "matryona-machines",
58
+ "rb-sys",
59
+ ]
60
+
61
+ [[package]]
62
+ name = "cexpr"
63
+ version = "0.6.0"
64
+ source = "registry+https://github.com/rust-lang/crates.io-index"
65
+ checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
66
+ dependencies = [
67
+ "nom",
68
+ ]
69
+
70
+ [[package]]
71
+ name = "cfg-if"
72
+ version = "1.0.5"
73
+ source = "registry+https://github.com/rust-lang/crates.io-index"
74
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
75
+
76
+ [[package]]
77
+ name = "clang-sys"
78
+ version = "1.9.1"
79
+ source = "registry+https://github.com/rust-lang/crates.io-index"
80
+ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
81
+ dependencies = [
82
+ "glob",
83
+ "libc",
84
+ "libloading",
85
+ ]
86
+
87
+ [[package]]
88
+ name = "either"
89
+ version = "1.19.0"
90
+ source = "registry+https://github.com/rust-lang/crates.io-index"
91
+ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
92
+
93
+ [[package]]
94
+ name = "glob"
95
+ version = "0.3.4"
96
+ source = "registry+https://github.com/rust-lang/crates.io-index"
97
+ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
98
+
99
+ [[package]]
100
+ name = "itertools"
101
+ version = "0.13.0"
102
+ source = "registry+https://github.com/rust-lang/crates.io-index"
103
+ checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
104
+ dependencies = [
105
+ "either",
106
+ ]
107
+
108
+ [[package]]
109
+ name = "lazy_static"
110
+ version = "1.5.1"
111
+ source = "registry+https://github.com/rust-lang/crates.io-index"
112
+ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
113
+
114
+ [[package]]
115
+ name = "libc"
116
+ version = "0.2.191"
117
+ source = "registry+https://github.com/rust-lang/crates.io-index"
118
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
119
+
120
+ [[package]]
121
+ name = "libloading"
122
+ version = "0.8.9"
123
+ source = "registry+https://github.com/rust-lang/crates.io-index"
124
+ checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
125
+ dependencies = [
126
+ "cfg-if",
127
+ "windows-link",
128
+ ]
129
+
130
+ [[package]]
131
+ name = "magnus"
132
+ version = "0.9.3"
133
+ source = "registry+https://github.com/rust-lang/crates.io-index"
134
+ checksum = "40ef424404d166cbb71c8b8d19c9c589c748c4547c1afa1928c5504299f6c713"
135
+ dependencies = [
136
+ "bytes",
137
+ "magnus-macros",
138
+ "rb-sys",
139
+ "rb-sys-env",
140
+ "seq-macro",
141
+ ]
142
+
143
+ [[package]]
144
+ name = "magnus-macros"
145
+ version = "0.9.1"
146
+ source = "registry+https://github.com/rust-lang/crates.io-index"
147
+ checksum = "9dafde2eeb66f090e0f326112323eb8324b12cb32b5d1210e541d3df6b0ce77e"
148
+ dependencies = [
149
+ "proc-macro2",
150
+ "quote",
151
+ "syn",
152
+ ]
153
+
154
+ [[package]]
155
+ name = "matryona-machines"
156
+ version = "0.6.0"
157
+ source = "registry+https://github.com/rust-lang/crates.io-index"
158
+ checksum = "cf8a06ab02efd767270815a1f515a40bbf3bfc77038e9360676ebe8d47833b07"
159
+ dependencies = [
160
+ "magnus",
161
+ ]
162
+
163
+ [[package]]
164
+ name = "memchr"
165
+ version = "2.8.3"
166
+ source = "registry+https://github.com/rust-lang/crates.io-index"
167
+ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
168
+
169
+ [[package]]
170
+ name = "minimal-lexical"
171
+ version = "0.2.1"
172
+ source = "registry+https://github.com/rust-lang/crates.io-index"
173
+ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
174
+
175
+ [[package]]
176
+ name = "nom"
177
+ version = "7.1.3"
178
+ source = "registry+https://github.com/rust-lang/crates.io-index"
179
+ checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
180
+ dependencies = [
181
+ "memchr",
182
+ "minimal-lexical",
183
+ ]
184
+
185
+ [[package]]
186
+ name = "proc-macro2"
187
+ version = "1.0.107"
188
+ source = "registry+https://github.com/rust-lang/crates.io-index"
189
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
190
+ dependencies = [
191
+ "unicode-ident",
192
+ ]
193
+
194
+ [[package]]
195
+ name = "quote"
196
+ version = "1.0.47"
197
+ source = "registry+https://github.com/rust-lang/crates.io-index"
198
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
199
+ dependencies = [
200
+ "proc-macro2",
201
+ ]
202
+
203
+ [[package]]
204
+ name = "rb-sys"
205
+ version = "0.9.130"
206
+ source = "registry+https://github.com/rust-lang/crates.io-index"
207
+ checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
208
+ dependencies = [
209
+ "rb-sys-build",
210
+ ]
211
+
212
+ [[package]]
213
+ name = "rb-sys-build"
214
+ version = "0.9.130"
215
+ source = "registry+https://github.com/rust-lang/crates.io-index"
216
+ checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
217
+ dependencies = [
218
+ "bindgen",
219
+ "lazy_static",
220
+ "proc-macro2",
221
+ "quote",
222
+ "regex",
223
+ "shell-words",
224
+ "syn",
225
+ ]
226
+
227
+ [[package]]
228
+ name = "rb-sys-env"
229
+ version = "0.2.3"
230
+ source = "registry+https://github.com/rust-lang/crates.io-index"
231
+ checksum = "cca7ad6a7e21e72151d56fe2495a259b5670e204c3adac41ee7ef676ea08117a"
232
+
233
+ [[package]]
234
+ name = "regex"
235
+ version = "1.13.1"
236
+ source = "registry+https://github.com/rust-lang/crates.io-index"
237
+ checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
238
+ dependencies = [
239
+ "aho-corasick",
240
+ "memchr",
241
+ "regex-automata",
242
+ "regex-syntax",
243
+ ]
244
+
245
+ [[package]]
246
+ name = "regex-automata"
247
+ version = "0.4.18"
248
+ source = "registry+https://github.com/rust-lang/crates.io-index"
249
+ checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
250
+ dependencies = [
251
+ "aho-corasick",
252
+ "memchr",
253
+ "regex-syntax",
254
+ ]
255
+
256
+ [[package]]
257
+ name = "regex-syntax"
258
+ version = "0.8.11"
259
+ source = "registry+https://github.com/rust-lang/crates.io-index"
260
+ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
261
+
262
+ [[package]]
263
+ name = "rustc-hash"
264
+ version = "2.1.3"
265
+ source = "registry+https://github.com/rust-lang/crates.io-index"
266
+ checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
267
+
268
+ [[package]]
269
+ name = "seq-macro"
270
+ version = "0.3.6"
271
+ source = "registry+https://github.com/rust-lang/crates.io-index"
272
+ checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
273
+
274
+ [[package]]
275
+ name = "shell-words"
276
+ version = "1.1.1"
277
+ source = "registry+https://github.com/rust-lang/crates.io-index"
278
+ checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
279
+
280
+ [[package]]
281
+ name = "shlex"
282
+ version = "1.3.0"
283
+ source = "registry+https://github.com/rust-lang/crates.io-index"
284
+ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
285
+
286
+ [[package]]
287
+ name = "syn"
288
+ version = "2.0.119"
289
+ source = "registry+https://github.com/rust-lang/crates.io-index"
290
+ checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
291
+ dependencies = [
292
+ "proc-macro2",
293
+ "quote",
294
+ "unicode-ident",
295
+ ]
296
+
297
+ [[package]]
298
+ name = "unicode-ident"
299
+ version = "1.0.27"
300
+ source = "registry+https://github.com/rust-lang/crates.io-index"
301
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
302
+
303
+ [[package]]
304
+ name = "windows-link"
305
+ version = "0.2.1"
306
+ source = "registry+https://github.com/rust-lang/crates.io-index"
307
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
data/Cargo.toml CHANGED
@@ -9,12 +9,14 @@ license = "MIT"
9
9
 
10
10
  [workspace.dependencies]
11
11
  cache-machines = { path = "ext/cache_machines_native/core" }
12
+ matryona-machines = { version = ">=0.6", default-features = false }
12
13
  magnus = { version = "0.9.3", default-features = false }
13
14
  rb-sys = { version = "0.9.130", default-features = false, features = ["stable-api-compiled-fallback"] }
14
15
 
15
16
  [workspace.lints.rust]
16
17
  unsafe_code = "deny"
17
18
  unused_must_use = "warn"
19
+ missing_docs = "warn"
18
20
  [workspace.lints.clippy]
19
21
  all = { level = "warn", priority = -1 }
20
22
  pedantic = { level = "warn", priority = -1 }
data/README.md CHANGED
@@ -13,11 +13,12 @@ gem 'cache_machines'
13
13
  ```ruby
14
14
  bay = CacheMachines::Lru.new
15
15
 
16
- bay.admit(42, candidate_frequency: 1, victim_frequency: 0) # => [:inserted, nil]
17
- bay.admit(7, candidate_frequency: 1, victim_frequency: 0) # => [:inserted, nil]
18
- bay.access(42) # => true
19
- bay.keys # => [42, 7]
20
- bay.remove(7) # => true
16
+ # key, candidate frequency, victim frequency: positional, like the Rust core.
17
+ bay.admit(42, 1, 0) # => :inserted
18
+ bay.admit(7, 1, 0) # => :inserted
19
+ bay.access(42) # => :hit
20
+ bay.keys # => [42, 7]
21
+ bay.remove(7) # => :removed
21
22
  ```
22
23
 
23
24
  Keys are Integers. Pair them with your own storage, hand the decisions to the bay, and the bay tells you what to keep.
@@ -56,12 +57,12 @@ stateDiagram-v2
56
57
  [*] --> offered
57
58
  offered --> hit: key already aboard, promoted to front
58
59
  offered --> inserted: bay has a free berth
59
- offered --> rejected: bay full, candidate frequency <= victim frequency
60
+ offered --> outranked: bay full, candidate frequency <= victim frequency (refused)
60
61
  offered --> evicted: bay full, candidate frequency > victim frequency
61
- evicted --> [*]: victim key returned
62
+ evicted --> [*]: Evicted carries the victim key
62
63
  hit --> [*]
63
64
  inserted --> [*]
64
- rejected --> [*]
65
+ outranked --> [*]: nothing changed
65
66
  ```
66
67
 
67
68
  And the night of the export job:
@@ -74,17 +75,17 @@ sequenceDiagram
74
75
 
75
76
  App->>Bay: victim
76
77
  Bay-->>App: 17 (seen 4000 times)
77
- App->>Bay: admit(export row 9001, candidate 1, victim 4000)
78
- Bay-->>App: [:rejected, nil]
78
+ App->>Bay: admit(export row 9001, 1, 4000)
79
+ Bay-->>App: :outranked
79
80
  Note over App: don't cache the row, serve it and move on
80
81
 
81
82
  App->>Bay: access(17)
82
- Bay-->>App: true, promoted
83
+ Bay-->>App: :hit, promoted
83
84
 
84
85
  App->>Bay: victim
85
86
  Bay-->>App: 23 (seen 2 times)
86
- App->>Bay: admit(user 555, candidate 9, victim 2)
87
- Bay-->>App: [:evicted, 23]
87
+ App->>Bay: admit(user 555, 9, 2)
88
+ Bay-->>App: Evicted(key 23)
88
89
  App->>Store: delete 23, store 555
89
90
  ```
90
91
 
@@ -92,12 +93,12 @@ sequenceDiagram
92
93
 
93
94
  ### Admit
94
95
 
95
- `admit` takes the key, how often the candidate has been requested, and how often the current victim has. It returns a status and, only when something was displaced, the evicted key.
96
+ `admit(key, candidate_frequency, victim_frequency)` takes the key, how often the candidate has been requested, and how often the current victim has. It answers `:inserted`, `:hit`, or, only when something was displaced, an `Evicted` carrying the evicted key. A key that didn't get in is a refusal symbol.
96
97
 
97
98
  ```ruby
98
99
  bay = CacheMachines::Lru.new
99
- bay.admit(1, candidate_frequency: 5, victim_frequency: 0) # => [:inserted, nil]
100
- bay.admit(1, candidate_frequency: 5, victim_frequency: 0) # => [:hit, nil]
100
+ bay.admit(1, 5, 0) # => :inserted
101
+ bay.admit(1, 5, 0) # => :hit
101
102
  ```
102
103
 
103
104
  While there's a free berth, frequencies don't matter. The candidate gets in. A key already aboard is a `:hit` and moves to the front.
@@ -108,29 +109,29 @@ Fill all 64 berths and the frequencies start to count.
108
109
 
109
110
  ```ruby
110
111
  bay = CacheMachines::Lru.new
111
- 64.times { |key| bay.admit(key, candidate_frequency: 0, victim_frequency: 0) }
112
+ 64.times { |key| bay.admit(key, 0, 0) }
112
113
 
113
- bay.victim # => 0
114
- bay.admit(100, candidate_frequency: 9, victim_frequency: 9) # => [:rejected, nil]
115
- bay.admit(100, candidate_frequency: 8, victim_frequency: 9) # => [:rejected, nil]
116
- bay.admit(100, candidate_frequency: 10, victim_frequency: 9) # => [:evicted, 0]
114
+ bay.victim # => 0
115
+ bay.admit(100, 9, 9) # => :outranked
116
+ bay.admit(100, 8, 9) # => :outranked
117
+ bay.admit(100, 10, 9) # => #<data CacheMachines::Evicted key=0>
117
118
  ```
118
119
 
119
- Equal loses. Lower loses. Only strictly higher gets a berth, and then you are told exactly which key just left so you can drop its payload.
120
+ Equal loses. Lower loses. A refused candidate changes nothing: the victim is still the victim. Only strictly higher gets a berth, and then you are told exactly which key just left so you can drop its payload.
120
121
 
121
122
  ### Access
122
123
 
123
- A hit promotes the key to the front and returns `true`. A miss returns `false` and inserts nothing. Reading is never admitting.
124
+ A hit promotes the key to the front and answers `:hit`. A miss answers `:miss`, inserts nothing, and changes nothing. Reading is never admitting. Both are answers, not refusals, and both are truthy: compare with `==`, don't test with `if`.
124
125
 
125
126
  ```ruby
126
127
  bay = CacheMachines::Lru.new
127
- bay.admit(1, candidate_frequency: 0, victim_frequency: 0)
128
- bay.admit(2, candidate_frequency: 0, victim_frequency: 0)
128
+ bay.admit(1, 0, 0)
129
+ bay.admit(2, 0, 0)
129
130
 
130
131
  bay.keys # => [2, 1]
131
- bay.access(1) # => true
132
+ bay.access(1) # => :hit
132
133
  bay.keys # => [1, 2]
133
- bay.access(9) # => false
134
+ bay.access(9) # => :miss
134
135
  bay.size # => 2
135
136
  ```
136
137
 
@@ -140,9 +141,9 @@ bay.size # => 2
140
141
 
141
142
  ```ruby
142
143
  bay = CacheMachines::Lru.new
143
- bay.victim # => nil
144
- 64.times { |key| bay.admit(key, candidate_frequency: 0, victim_frequency: 0) }
145
- bay.victim # => 0
144
+ bay.victim # => nil
145
+ 64.times { |key| bay.admit(key, 0, 0) }
146
+ bay.victim # => 0
146
147
  bay.access(0)
147
148
  bay.victim # => 1
148
149
  ```
@@ -151,9 +152,9 @@ bay.victim # => 1
151
152
 
152
153
  ```ruby
153
154
  bay = CacheMachines::Lru.new
154
- bay.admit(1, candidate_frequency: 0, victim_frequency: 0)
155
- bay.remove(1) # => true
156
- bay.remove(1) # => false
155
+ bay.admit(1, 0, 0)
156
+ bay.remove(1) # => :removed
157
+ bay.remove(1) # => :absent, already gone: nothing changes
157
158
  bay.clear # => nil
158
159
  bay.empty? # => true
159
160
  ```
@@ -162,9 +163,26 @@ bay.empty? # => true
162
163
 
163
164
  ## The Rules of the Tender
164
165
 
165
- - **Capacity is 64**, exposed as `CacheMachines::Lru::CAPACITY`. The constructor takes no arguments.
166
- - **Keys and frequencies are Integers** in `0..2**64-1`. Floats, strings, nil, and objects with `to_int` raise `TypeError`. Negative or too large raises `RangeError`. Bad input is rejected before anything changes.
167
- - **Both frequencies are keyword arguments** and both are required. Missing or extra keywords raise `ArgumentError`.
166
+ - **Ruby mirrors the Rust core.** `admit(key, candidate_frequency, victim_frequency)` is positional, in the order of `Lru::admit`. `access`, `remove`, `clear`, `keys`, `victim` and `capacity` are the core's methods under the core's names; `size` and `empty?` are `len` and `is_empty`.
167
+ - **Capacity is 64**, exposed as `CacheMachines::Lru::CAPACITY` and `#capacity`. The constructor takes no arguments.
168
+ - **Keys and frequencies are Integers** in `0..2**64-1`. Floats, strings, nil, and objects with `to_int` raise `TypeError`. Negative or too large raises `RangeError`. Bad input is rejected before anything changes. `ArgumentError` is only ever Ruby's own, for the wrong number of arguments.
169
+ - **Refusals don't raise and don't change anything.** `admit` is the only call that refuses: `:outranked` when the bay is full and the candidate's frequency doesn't exceed the victim's, `:zero_capacity` for a policy with no berths at all (the Rust core can be built that way; this gem's bay never is). Every reason has its own symbol, the snake case of the core's `Refusal` variant; there is no catch-all.
170
+ - **Repeats are honoured.** `remove` of a key that isn't aboard is `:absent`: the effect you asked for already holds, and nothing changes. `admit` or `access` of the key already at the front is `:hit` and moves nothing.
171
+ - **`Evicted` is a value, and values are valid or don't exist.** `CacheMachines::Evicted.new(key)` is checked by the native extension whether the bay built it or you did: a non-Integer raises `TypeError`, a key outside `0..2**64-1` `RangeError`. `==` compares it by value. It is sealed: subclassing it raises `TypeError` and `allocate` is gone. Sealing stops accidents, not reflection (a named `class X < Evicted` still binds `X` before raising, and `Data#initialize` can be bound directly), but the bay reads no `Evicted` from you, so a forged one reaches nothing and never equals a real answer. `Lru` is sealed too: it wraps native state, and subclassing it raises `TypeError`.
172
+ - **An eviction is never lost.** `admit` decides on a copy of the bay and keeps it only once the answer exists: if building the `Evicted` raises, nothing was admitted or evicted. If building it changed the bay (a redefined `Evicted.new` calling back in), `admit` raises `RuntimeError` and is not applied; the inner change stands. If building it froze the bay, `admit` raises `FrozenError` and is not applied. The `Evicted` class is resolved once, when the extension loads: reassigning the constant later changes nothing the bay builds.
173
+ - **No scopes, no restarts to plan for.** The bay issues no ids or handles; keys are yours. A new bay is empty.
174
+ - **No clock.** Frequencies are counts you measured, not times. The bay reads no clock and records none.
175
+ - **Every answer, by method.**
176
+
177
+ | Method | Honoured | Refused | Records the clock |
178
+ | --- | --- | --- | --- |
179
+ | `admit(key, candidate_frequency, victim_frequency)` | `:hit` (promoted), `:inserted`, an `Evicted` | `:outranked`, `:zero_capacity` | no clock, nothing recorded |
180
+ | `access(key)` | `:hit` (promoted), `:miss` (nothing changes) | never refuses | no clock, nothing recorded |
181
+ | `remove(key)` | `:removed`, `:absent` (a repeat: nothing changes) | never refuses | no clock, nothing recorded |
182
+ | `clear` | `nil` | never refuses | no clock, nothing recorded |
183
+ | `keys`, `size`, `empty?`, `victim`, `capacity` | a fresh Array, Integer, `true`/`false`, the victim key or `nil`, Integer | never refuses | no clock, nothing recorded |
184
+ | `Evicted.new(key)` | the value | never refuses; an invalid key raises `RangeError` (`TypeError` for a non-Integer) | no clock, nothing recorded |
185
+
168
186
  - **Frequencies are yours.** The bay never counts hits. It compares the two numbers you give it and nothing else.
169
187
  - **Frozen means frozen.** After `freeze`, every mutator raises `FrozenError`, including a miss on `access` and a `remove` of a key that isn't there.
170
188
 
@@ -177,7 +195,7 @@ The export touches more rows than you have berths. Doubling the bay means it tak
177
195
 
178
196
  ## What's Yours
179
197
 
180
- The bay holds keys and order, nothing else. Payloads live in your store, and when `admit` returns `:evicted` you delete that payload yourself. Frequency counting is yours too, whether that's a counter per key, a sketch, or a column you already have. Treat `victim` then `admit` as one step in your code; the bay won't stop another thread from slipping in between.
198
+ The bay holds keys and order, nothing else. Payloads live in your store, and when `admit` answers an `Evicted` you delete that payload yourself. Frequency counting is yours too, whether that's a counter per key, a sketch, or a column you already have. Treat `victim` then `admit` as one step in your code; the bay won't stop another thread from slipping in between.
181
199
 
182
200
  ## License
183
201
 
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.0](https://github.com/seuros/cache_machines/compare/cache-machines-v0.4.0...cache-machines-v0.5.0) (2026-11-16)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * seal CacheMachines::Lru and drop the Default bound on Lru keys
9
+
10
+ ### Features
11
+
12
+ * seal CacheMachines::Lru and drop the Default bound on Lru keys ([078344c](https://github.com/seuros/cache_machines/commit/078344cbf653eb4891322caa936e9cbe3834f49b))
13
+
14
+ ## [0.4.0](https://github.com/seuros/cache_machines/compare/cache-machines-v0.3.0...cache-machines-v0.4.0) (2026-11-14)
15
+
16
+
17
+ ### ⚠ BREAKING CHANGES
18
+
19
+ * adopt matryona-machines 0.2 (symbols! tables, frozen-first)
20
+
21
+ ### Features
22
+
23
+ * adopt matryona-machines 0.2 (symbols! tables, frozen-first) ([7556afb](https://github.com/seuros/cache_machines/commit/7556afb823a70c16417c22390ceb5b955990ebfd))
24
+
25
+ ## [0.3.0](https://github.com/seuros/cache_machines/compare/cache-machines-v0.2.2...cache-machines-v0.3.0) (2026-11-14)
26
+
27
+
28
+ ### ⚠ BREAKING CHANGES
29
+
30
+ * answer Refusal/Access/Removal, admit never loses an eviction, Evicted validated, sealed and resolved at load
31
+
32
+ ### Features
33
+
34
+ * answer Refusal/Access/Removal, admit never loses an eviction, Evicted validated, sealed and resolved at load ([adac5a9](https://github.com/seuros/cache_machines/commit/adac5a9939b9e2468e7a9a99aed1db283fe96f94))
35
+
3
36
  ## [0.2.2](https://github.com/seuros/cache_machines/compare/cache-machines-v0.2.1...cache-machines-v0.2.2) (2026-11-06)
4
37
 
5
38
 
@@ -1,13 +1,15 @@
1
1
  [package]
2
2
  name = "cache-machines"
3
- version = "0.2.2"
3
+ version = "0.5.0"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
7
7
  description = "Bounded LRU policy with caller-measured frequency admission"
8
8
  readme = "README.md"
9
- exclude = ["src/**/tests.rs", "tests/"]
9
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
10
10
  keywords = ["cache", "lru", "admission", "eviction", "no-std"]
11
11
  categories = ["no-std", "algorithms", "caching"]
12
+ [dev-dependencies]
13
+ matryona-machines = { workspace = true, features = ["testing"] }
12
14
  [lints]
13
15
  workspace = true
@@ -12,4 +12,28 @@ probabilistic sketch; this is not a complete TinyLFU/W-TinyLFU implementation.
12
12
 
13
13
  Values, loading, eviction callbacks, TTLs, byte weights, synchronization, and sketch
14
14
  aging are not owned by this policy. Coordinate key-policy mutations with storage
15
- updates. A zero-capacity cache rejects every insertion.
15
+ updates. A zero-capacity cache refuses every insertion.
16
+
17
+ ## Contract
18
+
19
+ - **Refusals.** `admit` returns `Result<Admission<K>, Refusal>`; `Refusal` is
20
+ the crate's one refusal type: `Outranked` (full, and
21
+ `candidate_frequency <= victim_frequency`: ties keep the incumbent) and
22
+ `ZeroCapacity` (`N == 0`). A refusal changes nothing: no key moves, none is
23
+ inserted or evicted.
24
+ - **Honoured answers.** `Admission::{Hit, Inserted, Evicted(K)}`;
25
+ `access -> Access::{Hit, Miss}`; `remove -> Removal::{Removed, Absent}`.
26
+ `access` and `remove` never refuse. A miss is an answer ("not retained"), not
27
+ a refusal: reading is never admitting, and a miss changes nothing.
28
+ - **Repeats.** `remove` of a key that is not retained is `Removal::Absent`: the
29
+ effect already holds, provably, and nothing changes. `admit` or `access` of
30
+ the most recent key is `Hit` and moves nothing.
31
+ - **Keys.** `K: Copy + Eq`, no `Default`: free slots hold no key, so caches
32
+ retaining the same keys in the same order compare equal, and `Lru::new` is a
33
+ `const fn` (an empty cache can be a `const` or a `static`).
34
+ - **Exhaustive.** `Admission`, `Access`, `Removal` and `Refusal` carry no
35
+ `#[non_exhaustive]`; a new variant is a breaking change.
36
+ - **Scopes and restarts.** The policy issues no ids; keys are the caller's. A
37
+ new cache is empty.
38
+ - **Time.** None. Frequencies are caller-measured counts (`u64`), not clocks;
39
+ the policy reads and records no time.
@@ -1,21 +1,65 @@
1
1
  #![no_std]
2
2
  #![doc = include_str!("../README.md")]
3
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
3
4
 
4
- /// Outcome for a key admission.
5
+ use core::fmt;
6
+
7
+ /// Honoured answer to [`Lru::admit`].
5
8
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6
- #[non_exhaustive]
7
9
  pub enum Admission<K> {
8
- /// Existing key was promoted.
10
+ /// The key was already retained and is now the most recent.
9
11
  Hit,
10
- /// New key was inserted into an empty slot.
12
+ /// The key took a free slot and is now the most recent.
11
13
  Inserted,
12
- /// The least-recently-used key was replaced.
14
+ /// The key replaced the least-recently-used key, carried here so the
15
+ /// caller drops its payload.
13
16
  Evicted(K),
14
- /// Frequency policy or zero capacity rejected the candidate.
15
- Rejected,
16
17
  }
17
18
 
18
- /// LRU keys in most-recent-first order.
19
+ /// Answer to [`Lru::access`]. Reading is never admitting: a miss inserts
20
+ /// nothing and changes nothing.
21
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22
+ pub enum Access {
23
+ /// The key is retained and is now the most recent.
24
+ Hit,
25
+ /// The key is not retained.
26
+ Miss,
27
+ }
28
+
29
+ /// Honoured answer to [`Lru::remove`].
30
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31
+ pub enum Removal {
32
+ /// The key was retained and is gone; the others keep their order.
33
+ Removed,
34
+ /// The key was not retained: the effect already holds, nothing changed.
35
+ Absent,
36
+ }
37
+
38
+ /// Why [`Lru::admit`] did not admit a key. A refusal changes nothing: no key
39
+ /// moves, none is inserted or evicted.
40
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
41
+ pub enum Refusal {
42
+ /// The cache is full and the candidate's frequency does not exceed the
43
+ /// victim's: ties keep the incumbent.
44
+ Outranked,
45
+ /// The cache has no slot at all (`N == 0`).
46
+ ZeroCapacity,
47
+ }
48
+
49
+ impl fmt::Display for Refusal {
50
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51
+ f.write_str(match self {
52
+ Self::Outranked => "the candidate does not outrank the victim",
53
+ Self::ZeroCapacity => "the cache has no capacity",
54
+ })
55
+ }
56
+ }
57
+
58
+ impl core::error::Error for Refusal {}
59
+
60
+ /// LRU keys in most-recent-first order. Slots before `len` hold `Some`,
61
+ /// slots at and past it `None`, so two caches retaining the same keys in the
62
+ /// same order compare equal and no placeholder key is needed.
19
63
  #[derive(Debug, Clone, PartialEq, Eq)]
20
64
  pub struct Lru<K, const N: usize> {
21
65
  keys: [Option<K>; N],
@@ -58,7 +102,7 @@ impl<K: Copy + Eq, const N: usize> Lru<K, N> {
58
102
 
59
103
  /// Retained keys in most-recent-first order.
60
104
  pub fn keys(&self) -> impl Iterator<Item = K> + '_ {
61
- self.keys[..self.len].iter().flatten().copied()
105
+ self.live().iter().flatten().copied()
62
106
  }
63
107
 
64
108
  /// Forget every key.
@@ -67,72 +111,102 @@ impl<K: Copy + Eq, const N: usize> Lru<K, N> {
67
111
  self.len = 0;
68
112
  }
69
113
 
70
- fn index(&self, key: K) -> Option<usize> {
71
- self.keys[..self.len]
72
- .iter()
73
- .position(|value| *value == Some(key))
114
+ /// The retained slots, `keys[..len]`. `len <= N` always holds (it only
115
+ /// grows while `len < N`); were it ever broken the live run reads as
116
+ /// empty, so every operation answers as for a key that is not retained.
117
+ fn live(&self) -> &[Option<K>] {
118
+ self.keys.get(..self.len).unwrap_or_default()
119
+ }
120
+
121
+ fn live_mut(&mut self) -> &mut [Option<K>] {
122
+ self.keys.get_mut(..self.len).unwrap_or_default()
123
+ }
124
+
125
+ /// The retained run up to and including `key`, so its last slot holds
126
+ /// `key`; `None` when `key` is not retained.
127
+ fn through(&mut self, key: K) -> Option<&mut [Option<K>]> {
128
+ let live = self.live_mut();
129
+ let index = live.iter().position(|value| *value == Some(key))?;
130
+ live.get_mut(..=index)
74
131
  }
75
132
 
76
133
  /// Remove a key without changing the relative order of the others.
77
- #[must_use]
78
- pub fn remove(&mut self, key: K) -> bool {
79
- let Some(index) = self.index(key) else {
80
- return false;
134
+ /// Removing a key that is not retained is an honoured repeat,
135
+ /// [`Removal::Absent`], and changes nothing.
136
+ pub fn remove(&mut self, key: K) -> Removal {
137
+ let live = self.live_mut();
138
+ let Some(index) = live.iter().position(|value| *value == Some(key)) else {
139
+ return Removal::Absent;
81
140
  };
82
- self.keys[index..self.len].rotate_left(1);
83
- self.len -= 1;
84
- self.keys[self.len] = None;
85
- true
141
+ if let Some(tail) = live.get_mut(index..) {
142
+ tail.rotate_left(1);
143
+ if let Some(last) = tail.last_mut() {
144
+ *last = None;
145
+ }
146
+ }
147
+ // `index < len`, so `len >= 1`.
148
+ self.len = self.len.saturating_sub(1);
149
+ Removal::Removed
86
150
  }
87
151
 
88
- /// Promote a hit; misses leave the ordering unchanged.
89
- #[must_use]
90
- pub fn access(&mut self, key: K) -> bool {
91
- let Some(index) = self.index(key) else {
92
- return false;
152
+ /// Promote a hit to most recent; a miss answers [`Access::Miss`] and
153
+ /// leaves the ordering unchanged.
154
+ pub fn access(&mut self, key: K) -> Access {
155
+ let Some(head) = self.through(key) else {
156
+ return Access::Miss;
93
157
  };
94
- self.keys[..=index].rotate_right(1);
95
- true
158
+ head.rotate_right(1);
159
+ Access::Hit
96
160
  }
97
161
 
98
- /// Admit a key; victim frequency refers to the current `victim()` key.
99
- #[must_use]
162
+ /// Admit a key; `victim_frequency` refers to the current [`Lru::victim`]
163
+ /// key and is only consulted when the cache is full.
164
+ ///
165
+ /// # Errors
166
+ ///
167
+ /// [`Refusal::Outranked`] when the cache is full and
168
+ /// `candidate_frequency <= victim_frequency`; [`Refusal::ZeroCapacity`]
169
+ /// when `N == 0`. Nothing changes.
100
170
  pub fn admit(
101
171
  &mut self,
102
172
  key: K,
103
173
  candidate_frequency: u64,
104
174
  victim_frequency: u64,
105
- ) -> Admission<K> {
106
- if self.access(key) {
107
- return Admission::Hit;
108
- }
109
- if N == 0 {
110
- return Admission::Rejected;
175
+ ) -> Result<Admission<K>, Refusal> {
176
+ if self.access(key) == Access::Hit {
177
+ return Ok(Admission::Hit);
111
178
  }
112
- let outcome = if self.len == N {
113
- if candidate_frequency <= victim_frequency {
114
- return Admission::Rejected;
179
+ let (outcome, len) = match self.victim() {
180
+ Some(_) if candidate_frequency <= victim_frequency => {
181
+ return Err(Refusal::Outranked);
115
182
  }
116
- let Some(victim) = self.keys[N - 1] else {
117
- return Admission::Rejected;
118
- };
119
- Admission::Evicted(victim)
120
- } else {
121
- self.len += 1;
122
- Admission::Inserted
183
+ Some(victim) => (Admission::Evicted(victim), self.len),
184
+ // `len < N <= usize::MAX`, so this cannot overflow.
185
+ None if self.len < N => (Admission::Inserted, self.len.saturating_add(1)),
186
+ None => return Err(Refusal::ZeroCapacity),
187
+ };
188
+ // `1 <= len <= N`: a victim exists only when the cache is full and
189
+ // nonempty, an insertion only below capacity.
190
+ let slots = self.keys.get_mut(..len).unwrap_or_default();
191
+ // Shift every retained key down one place, the last falling off (it
192
+ // is the evicted victim, or the empty slot just claimed). On an empty
193
+ // run the rotation is a no-op, so the arm below changes nothing.
194
+ slots.rotate_right(1);
195
+ let Some(first) = slots.first_mut() else {
196
+ debug_assert!(false, "an admission always has a slot below N");
197
+ return Err(Refusal::ZeroCapacity);
123
198
  };
124
- self.keys[..self.len].rotate_right(1);
125
- self.keys[0] = Some(key);
126
- outcome
199
+ *first = Some(key);
200
+ self.len = len;
201
+ Ok(outcome)
127
202
  }
128
203
 
129
204
  /// Current eviction candidate, when the cache is full and nonempty.
130
205
  #[must_use]
131
206
  pub const fn victim(&self) -> Option<K> {
132
- if N > 0 && self.len == N {
133
- self.keys[N - 1]
134
- } else {
135
- None
207
+ match self.keys.last() {
208
+ Some(slot) if self.len == N => *slot,
209
+ _ => None,
136
210
  }
137
211
  }
138
212
  }
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "cache_machines_native"
3
- version = "0.1.3"
3
+ version = "0.1.6"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
@@ -16,6 +16,7 @@ doctest = false
16
16
  cache-machines.workspace = true
17
17
  magnus.workspace = true
18
18
  rb-sys.workspace = true
19
+ matryona-machines = { workspace = true, features = ["ruby"] }
19
20
 
20
21
  [lints]
21
22
  workspace = true
@@ -0,0 +1,29 @@
1
+ use magnus::{Error, Ruby, function, method, prelude::*};
2
+ use matryona_machines::ruby::Class;
3
+
4
+ use crate::{CAPACITY, CLASSES, Classes, Wrapper, checked_evicted};
5
+
6
+ /// Defines `CacheMachines::Lru` and resolves the classes the gem defined.
7
+ #[magnus::init]
8
+ fn init(ruby: &Ruby) -> Result<(), Error> {
9
+ let module = ruby.define_module("CacheMachines")?;
10
+ // Held for good: removing the constant must not let the GC take it.
11
+ let evicted = Class::resolve(ruby, module, "Evicted")?;
12
+ CLASSES.set(ruby, Classes { evicted })?;
13
+ module.define_singleton_method("__evicted", function!(checked_evicted, 1))?;
14
+ let class = module.define_class("Lru", ruby.class_object())?;
15
+ class.undef_default_alloc_func();
16
+ class.const_set("CAPACITY", CAPACITY)?;
17
+ class.define_singleton_method("new", function!(Wrapper::new, 0))?;
18
+ class.define_method("admit", method!(Wrapper::admit, 3))?;
19
+ class.define_method("access", method!(Wrapper::access, 1))?;
20
+ class.define_method("remove", method!(Wrapper::remove, 1))?;
21
+ class.define_method("clear", method!(Wrapper::clear, 0))?;
22
+ class.define_method("keys", method!(Wrapper::keys, 0))?;
23
+ class.define_method("size", method!(Wrapper::len, 0))?;
24
+ class.define_method("empty?", method!(Wrapper::is_empty, 0))?;
25
+ class.define_method("victim", method!(Wrapper::victim, 0))?;
26
+ class.define_method("capacity", method!(Wrapper::capacity, 0))?;
27
+ // `new` answers a Wrapper: fix its class now, so building one runs no Ruby.
28
+ Class::pin_wrapped::<Wrapper>(ruby, class).map(drop)
29
+ }
@@ -1,32 +1,58 @@
1
1
  //! Thin native binding; all ordering and admission decisions belong to the core.
2
2
 
3
+ mod init;
4
+
3
5
  use std::cell::RefCell;
4
6
 
5
- use cache_machines::{Admission, Lru};
6
- use magnus::scan_args::{get_kwargs, scan_args};
7
+ use cache_machines::{Access, Admission, Lru, Refusal, Removal};
7
8
  use magnus::typed_data::Obj;
8
- use magnus::{
9
- Error, Integer, RHash, Ruby, Symbol, TryConvert, Value, function, method, prelude::*,
10
- };
9
+ use magnus::{Error, Ruby, Value, prelude::*};
10
+ use matryona_machines::ruby::{Class, Registry, Symbols, integer, keep, symbol};
11
11
 
12
12
  const CAPACITY: usize = 64;
13
13
 
14
- /// Reject implicit conversions, especially Float truncation in Magnus integers.
15
- #[derive(Clone, Copy)]
16
- struct Number(u64);
17
-
18
- impl TryConvert for Number {
19
- fn try_convert(value: Value) -> Result<Self, Error> {
20
- if Integer::from_value(value).is_none() {
21
- return Err(Error::new(
22
- Ruby::get_with(value).exception_type_error(),
23
- "key and frequency must be Integers",
24
- ));
25
- }
26
- u64::try_convert(value).map(Self)
14
+ matryona_machines::symbols! {
15
+ /// The core's refusals as Symbols: the snake case of each variant.
16
+ Refusals for Refusal as "a refusal" {
17
+ Outranked => "outranked",
18
+ ZeroCapacity => "zero_capacity",
19
+ }
20
+ }
21
+
22
+ matryona_machines::symbols! {
23
+ /// The core's `access` answers as Symbols.
24
+ Accesses for Access as "an access" {
25
+ Hit => "hit",
26
+ Miss => "miss",
27
27
  }
28
28
  }
29
29
 
30
+ matryona_machines::symbols! {
31
+ /// The core's `remove` answers as Symbols.
32
+ Removals for Removal as "a removal" {
33
+ Removed => "removed",
34
+ Absent => "absent",
35
+ }
36
+ }
37
+
38
+ /// Ruby symbol of a refusal: the snake case of the core variant.
39
+ fn refusal(ruby: &Ruby, refused: Refusal) -> Value {
40
+ Refusals::symbol(ruby, refused).as_value()
41
+ }
42
+
43
+ /// `CacheMachines::Evicted`, resolved once at init: reassigning the constant
44
+ /// later changes nothing the cache builds.
45
+ struct Classes {
46
+ evicted: Class,
47
+ }
48
+
49
+ static CLASSES: Registry<Classes> = Registry::new("cache_machines");
50
+
51
+ /// What `Evicted.new` stores: the key, validated as the core's `u64`.
52
+ fn checked_evicted(key: Value) -> Result<u64, Error> {
53
+ integer(key, "key")
54
+ }
55
+
30
56
  #[magnus::wrap(class = "CacheMachines::Lru", free_immediately, size)]
31
57
  struct Wrapper(RefCell<Lru<u64, CAPACITY>>);
32
58
 
@@ -38,42 +64,45 @@ impl Wrapper {
38
64
  fn admit(
39
65
  ruby: &Ruby,
40
66
  rb_self: Obj<Self>,
41
- args: &[Value],
42
- ) -> Result<(Symbol, Option<u64>), Error> {
67
+ key: Value,
68
+ candidate_frequency: Value,
69
+ victim_frequency: Value,
70
+ ) -> Result<Value, Error> {
71
+ // Frozen first, then the arguments: everything that can raise
72
+ // happens before the core decides.
43
73
  rb_self.check_frozen()?;
44
- let args = scan_args::<(Number,), (), (), (), RHash, ()>(args)?;
45
- let (key,) = args.required;
46
- let (candidate, victim) = get_kwargs::<_, (Number, Number), (), ()>(
47
- args.keywords,
48
- &["candidate_frequency", "victim_frequency"],
49
- &[],
50
- )?
51
- .required;
52
- // Only native values cross the borrow; Ruby allocations happen afterwards.
53
- let outcome = rb_self.0.borrow_mut().admit(key.0, candidate.0, victim.0);
54
- let (status, evicted) = match outcome {
55
- Admission::Hit => ("hit", None),
56
- Admission::Inserted => ("inserted", None),
57
- Admission::Evicted(key) => ("evicted", Some(key)),
58
- Admission::Rejected => ("rejected", None),
59
- _ => {
60
- return Err(Error::new(
61
- ruby.exception_runtime_error(),
62
- "unknown admission",
63
- ));
64
- }
65
- };
66
- Ok((ruby.to_symbol(status), evicted))
74
+ let key = integer(key, "key")?;
75
+ let candidate = integer(candidate_frequency, "candidate_frequency")?;
76
+ let victim = integer(victim_frequency, "victim_frequency")?;
77
+ let evicted = CLASSES.get(ruby)?.evicted.get(ruby);
78
+ // The core decides on a copy; the copy is kept only once the answer
79
+ // exists, so a raise in `Evicted.new` loses no evicted key.
80
+ keep(
81
+ ruby,
82
+ rb_self,
83
+ &rb_self.0,
84
+ |cache| cache.admit(key, candidate, victim),
85
+ |admission| match admission {
86
+ Ok(Admission::Hit) => Ok(symbol(ruby, "hit").as_value()),
87
+ Ok(Admission::Inserted) => Ok(symbol(ruby, "inserted").as_value()),
88
+ Ok(Admission::Evicted(key)) => evicted.funcall("new", (key,)),
89
+ Err(refused) => Ok(refusal(ruby, refused)),
90
+ },
91
+ )
67
92
  }
68
93
 
69
- fn access(rb_self: Obj<Self>, key: Number) -> Result<bool, Error> {
94
+ fn access(ruby: &Ruby, rb_self: Obj<Self>, key: Value) -> Result<Value, Error> {
70
95
  rb_self.check_frozen()?;
71
- Ok(rb_self.0.borrow_mut().access(key.0))
96
+ let key = integer(key, "key")?;
97
+ let access = rb_self.0.borrow_mut().access(key);
98
+ Ok(Accesses::symbol(ruby, access).as_value())
72
99
  }
73
100
 
74
- fn remove(rb_self: Obj<Self>, key: Number) -> Result<bool, Error> {
101
+ fn remove(ruby: &Ruby, rb_self: Obj<Self>, key: Value) -> Result<Value, Error> {
75
102
  rb_self.check_frozen()?;
76
- Ok(rb_self.0.borrow_mut().remove(key.0))
103
+ let key = integer(key, "key")?;
104
+ let removal = rb_self.0.borrow_mut().remove(key);
105
+ Ok(Removals::symbol(ruby, removal).as_value())
77
106
  }
78
107
 
79
108
  fn clear(rb_self: Obj<Self>) -> Result<(), Error> {
@@ -97,20 +126,8 @@ impl Wrapper {
97
126
  fn victim(&self) -> Option<u64> {
98
127
  self.0.borrow().victim()
99
128
  }
100
- }
101
129
 
102
- #[magnus::init]
103
- fn init(ruby: &Ruby) -> Result<(), Error> {
104
- let module = ruby.define_module("CacheMachines")?;
105
- let class = module.define_class("Lru", ruby.class_object())?;
106
- class.const_set("CAPACITY", CAPACITY)?;
107
- class.define_singleton_method("new", function!(Wrapper::new, 0))?;
108
- class.define_method("admit", method!(Wrapper::admit, -1))?;
109
- class.define_method("access", method!(Wrapper::access, 1))?;
110
- class.define_method("remove", method!(Wrapper::remove, 1))?;
111
- class.define_method("clear", method!(Wrapper::clear, 0))?;
112
- class.define_method("keys", method!(Wrapper::keys, 0))?;
113
- class.define_method("size", method!(Wrapper::len, 0))?;
114
- class.define_method("empty?", method!(Wrapper::is_empty, 0))?;
115
- class.define_method("victim", method!(Wrapper::victim, 0))
130
+ fn capacity(&self) -> usize {
131
+ self.0.borrow().capacity()
132
+ }
116
133
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CacheMachines
4
- VERSION = '0.1.4'
4
+ VERSION = '0.4.1'
5
5
  end
@@ -2,5 +2,32 @@
2
2
 
3
3
  require_relative 'cache_machines/version'
4
4
 
5
- # A missing extension is an installation error. There is no Ruby policy fallback.
5
+ module CacheMachines
6
+ # The core's `Admission::Evicted`: the admitted key replaced `key`, the least
7
+ # recently used one; drop its payload. Like every key the core holds, `key`
8
+ # is an Integer in 0..2**64-1: anything else raises RangeError (TypeError for
9
+ # a non-Integer).
10
+ Evicted = Data.define(:key) do
11
+ def initialize(key:)
12
+ key = CacheMachines.__send__(:__evicted, key)
13
+ super
14
+ end
15
+ end
16
+ end
17
+
18
+ # A missing extension is an installation error. There is no Ruby policy
19
+ # fallback. It validates and builds the Data value above.
6
20
  require 'cache_machines_native/cache_machines_native'
21
+
22
+ module CacheMachines
23
+ private_class_method :__evicted
24
+
25
+ # Sealed: no subclass can skip the check by overriding `initialize`, and no
26
+ # bare `allocate` builds a value that never ran it.
27
+ Evicted.singleton_class.undef_method(:allocate)
28
+ Evicted.define_singleton_method(:inherited) { |_| raise TypeError, "#{Evicted} cannot be subclassed" }
29
+
30
+ # Lru wraps native state and has no allocator: a subclass's `new` would
31
+ # build an Lru anyway, so subclassing raises too.
32
+ Lru.define_singleton_method(:inherited) { |_| raise TypeError, "#{Lru} cannot be subclassed" }
33
+ end
@@ -1,17 +1,46 @@
1
1
  module CacheMachines
2
2
  VERSION: String
3
3
 
4
+ # Refusals of `admit`: the key was not admitted and nothing changed. Every
5
+ # reason has its own symbol; there is no catch-all.
6
+ type refusal = :outranked | :zero_capacity
7
+
8
+ # The key `admit` evicted. `key` is an Integer in 0..2**64-1: RangeError
9
+ # otherwise (TypeError for a non-Integer), whether the cache built it or you did.
10
+ # Sealed: subclassing raises TypeError and `allocate` is undefined.
11
+ class Evicted < Data
12
+ attr_reader key: Integer
13
+ def self.new: (Integer key) -> Evicted
14
+ | (key: Integer) -> Evicted
15
+ end
16
+
17
+ # Sealed: no allocator, and subclassing raises TypeError.
4
18
  class Lru
19
+ # The capacity compiled into the gem: the same as `#capacity`.
5
20
  CAPACITY: Integer
6
21
 
7
22
  def self.new: () -> Lru
8
- def admit: (Integer key, candidate_frequency: Integer, victim_frequency: Integer) -> [Symbol, Integer?]
9
- def access: (Integer key) -> bool
10
- def remove: (Integer key) -> bool
23
+ # Positional, like `Lru::admit(key, candidate_frequency, victim_frequency)`.
24
+ # Honoured: :hit (promoted), :inserted, Evicted. Refused: :outranked (full,
25
+ # and the candidate's frequency does not exceed the victim's), :zero_capacity.
26
+ # RuntimeError, not applied, when building the answer changed the cache;
27
+ # FrozenError, not applied, when it froze the cache.
28
+ def admit: (Integer key, Integer candidate_frequency, Integer victim_frequency) -> (:hit | :inserted | Evicted | :outranked | :zero_capacity)
29
+ # :hit promotes the key; :miss inserts nothing and changes nothing. Never refuses.
30
+ def access: (Integer key) -> (:hit | :miss)
31
+ # :removed, or :absent when the key was not retained (a repeat: nothing
32
+ # changes). Never refuses.
33
+ def remove: (Integer key) -> (:removed | :absent)
11
34
  def clear: () -> nil
35
+ # A fresh Array, most recent first.
12
36
  def keys: () -> Array[Integer]
13
37
  def size: () -> Integer
14
38
  def empty?: () -> bool
39
+ # The key `admit` would evict; nil until the cache is full.
15
40
  def victim: () -> Integer?
41
+ def capacity: () -> Integer
16
42
  end
43
+
44
+ # Private native hook `Evicted#initialize` validates its key through.
45
+ private def self.__evicted: (Integer key) -> Integer
17
46
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cache_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.4
4
+ version: 0.4.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -40,6 +40,7 @@ extensions:
40
40
  extra_rdoc_files: []
41
41
  files:
42
42
  - CHANGELOG.md
43
+ - Cargo.lock
43
44
  - Cargo.toml
44
45
  - LICENSE.txt
45
46
  - README.md
@@ -51,6 +52,7 @@ files:
51
52
  - ext/cache_machines_native/extconf.rb
52
53
  - ext/cache_machines_native/ffi/Cargo.toml
53
54
  - ext/cache_machines_native/ffi/extconf.rb
55
+ - ext/cache_machines_native/ffi/src/init.rs
54
56
  - ext/cache_machines_native/ffi/src/lib.rs
55
57
  - lib/cache_machines.rb
56
58
  - lib/cache_machines/version.rb