cache_machines 0.1.4

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e553d28a185ae5660c769b7c59b71bb3732df57f3f118425b59d993db8fd75d0
4
+ data.tar.gz: 59cec0b71269767d0ede58db7cbb50c07421c341f99592c65ab4881b34d28e6e
5
+ SHA512:
6
+ metadata.gz: 293cb97172f6518e702ae1e5bdf888d297530cf0f57f6d19b304c81a6db074768dea581f24befef6da6bbac8d3998fe61115842cfa17e5cf15755cb8e18dc1ad
7
+ data.tar.gz: 103b95b31c494cb70106b06746854a1f50f4595160962d0414589e823fb72fd02ac6b7357f97e4defbddea2aaef4747bf28503100cc35434e252f0bf52207747
data/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Changelog
2
+
3
+ ## [0.1.4](https://github.com/seuros/cache_machines/compare/cache_machines/v0.1.3...cache_machines/v0.1.4) (2026-11-06)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * crates.io keywords and categories for the core ([03e3752](https://github.com/seuros/cache_machines/commit/03e375232563df5cf56b4bbe8435540048b3f2c7))
9
+
10
+ ## [0.1.3](https://github.com/seuros/cache_machines/compare/cache_machines/v0.1.2...cache_machines/v0.1.3) (2026-11-06)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * keep test sources out of the packaged gem and crate ([28635a4](https://github.com/seuros/cache_machines/commit/28635a4df2b2313914957f8cf8b068934bb35f7d))
16
+
17
+ ## [0.1.2](https://github.com/seuros/cache_machines/compare/cache_machines/v0.1.1...cache_machines/v0.1.2) (2026-11-06)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * cross builds no longer compile for the host ([33bc4f3](https://github.com/seuros/cache_machines/commit/33bc4f3fd1ba7bc19bda7930b9d998254d70f923))
23
+
24
+ ## [0.1.1](https://github.com/seuros/cache_machines/compare/cache_machines-v0.1.0...cache_machines/v0.1.1) (2026-11-06)
25
+
26
+
27
+ ### Features
28
+
29
+ * initial extraction ([3569bc6](https://github.com/seuros/cache_machines/commit/3569bc6ccda4ec7c7bc345ab7be84f92e8edcedd))
data/Cargo.toml ADDED
@@ -0,0 +1,23 @@
1
+ [workspace]
2
+ members = ["ext/cache_machines_native/core", "ext/cache_machines_native/ffi"]
3
+ default-members = ["ext/cache_machines_native/core"]
4
+ resolver = "3"
5
+ [workspace.package]
6
+ edition = "2024"
7
+ rust-version = "1.99"
8
+ license = "MIT"
9
+
10
+ [workspace.dependencies]
11
+ cache-machines = { path = "ext/cache_machines_native/core" }
12
+ magnus = { version = "0.9.3", default-features = false }
13
+ rb-sys = { version = "0.9.130", default-features = false, features = ["stable-api-compiled-fallback"] }
14
+
15
+ [workspace.lints.rust]
16
+ unsafe_code = "deny"
17
+ unused_must_use = "warn"
18
+ [workspace.lints.clippy]
19
+ all = { level = "warn", priority = -1 }
20
+ pedantic = { level = "warn", priority = -1 }
21
+ nursery = { level = "warn", priority = -1 }
22
+ unwrap_used = "deny"
23
+ expect_used = "deny"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdelkader Boudih
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,186 @@
1
+ # CacheMachines
2
+
3
+ > Sixty-four berths, and a hatch that asks what you've done to deserve one. 📦
4
+
5
+ An admission-controlled LRU for Ruby. It keeps the most recently used keys in order, names the one it would throw out next, and refuses to throw it out for a newcomer that isn't worth more. You store the payloads and count the hits. It decides what stays.
6
+
7
+ ## Quick Start
8
+
9
+ ```bash
10
+ gem 'cache_machines'
11
+ ```
12
+
13
+ ```ruby
14
+ bay = CacheMachines::Lru.new
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
21
+ ```
22
+
23
+ Keys are Integers. Pair them with your own storage, hand the decisions to the bay, and the bay tells you what to keep.
24
+
25
+ ## A Message to the Resistance
26
+
27
+ So you built an LRU cache. Hot rows stay, cold rows fall off the back, dashboards go green. Then the nightly export job runs. It reads every row in the table exactly once, and every one of those reads is a cache miss that inserts a key you will never ask for again.
28
+
29
+ By the time the export finishes, your working set is gone. The 64 keys that got hit ten thousand times each have been shoved out by 64 keys that got hit once. Monday morning is a cold start, and the LRU did exactly what you told it to do.
30
+
31
+ LRU answers "what was used least recently?" It never asks "does the newcomer deserve the slot?" This gem asks. When the bay is full, a candidate has to show up with a higher frequency than the key it would evict. Ties lose. The export job's keys never make it past the hatch.
32
+
33
+ ## Chapter 1: Stardate 2025.186, the AMS Denning
34
+
35
+ > **AMS Denning**, NCC-4203, *Denning*-class cache tender.
36
+ > The hold is finite. The universe of possible consignments is not.
37
+
38
+ The tender has 64 berths and no more. Every consignment that arrives is logged by key, and the manifest is kept in order of last use. When the bay is full and something new arrives, the quartermaster names the berth at the back, asks how often each has been requisitioned, and only swaps if the newcomer wins outright.
39
+
40
+ Somewhere in the fleet, a supply officer proposes:
41
+
42
+ ```ruby
43
+ def fetch(key)
44
+ @cache[key] ||= load(key) # Hash with 64 entries, oldest shifted off
45
+ end
46
+ ```
47
+
48
+ "That," says the quartermaster, "is how one inventory scan empties the bay."
49
+
50
+ ## The Flight Plan
51
+
52
+ What happens to a key offered to `admit`:
53
+
54
+ ```mermaid
55
+ stateDiagram-v2
56
+ [*] --> offered
57
+ offered --> hit: key already aboard, promoted to front
58
+ offered --> inserted: bay has a free berth
59
+ offered --> rejected: bay full, candidate frequency <= victim frequency
60
+ offered --> evicted: bay full, candidate frequency > victim frequency
61
+ evicted --> [*]: victim key returned
62
+ hit --> [*]
63
+ inserted --> [*]
64
+ rejected --> [*]
65
+ ```
66
+
67
+ And the night of the export job:
68
+
69
+ ```mermaid
70
+ sequenceDiagram
71
+ participant App
72
+ participant Bay as Lru (full)
73
+ participant Store as Your storage
74
+
75
+ App->>Bay: victim
76
+ Bay-->>App: 17 (seen 4000 times)
77
+ App->>Bay: admit(export row 9001, candidate 1, victim 4000)
78
+ Bay-->>App: [:rejected, nil]
79
+ Note over App: don't cache the row, serve it and move on
80
+
81
+ App->>Bay: access(17)
82
+ Bay-->>App: true, promoted
83
+
84
+ App->>Bay: victim
85
+ Bay-->>App: 23 (seen 2 times)
86
+ App->>Bay: admit(user 555, candidate 9, victim 2)
87
+ Bay-->>App: [:evicted, 23]
88
+ App->>Store: delete 23, store 555
89
+ ```
90
+
91
+ ## How the Bay Works
92
+
93
+ ### Admit
94
+
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
+
97
+ ```ruby
98
+ 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]
101
+ ```
102
+
103
+ 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.
104
+
105
+ ### When the bay is full
106
+
107
+ Fill all 64 berths and the frequencies start to count.
108
+
109
+ ```ruby
110
+ bay = CacheMachines::Lru.new
111
+ 64.times { |key| bay.admit(key, candidate_frequency: 0, victim_frequency: 0) }
112
+
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]
117
+ ```
118
+
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
+
121
+ ### Access
122
+
123
+ A hit promotes the key to the front and returns `true`. A miss returns `false` and inserts nothing. Reading is never admitting.
124
+
125
+ ```ruby
126
+ bay = CacheMachines::Lru.new
127
+ bay.admit(1, candidate_frequency: 0, victim_frequency: 0)
128
+ bay.admit(2, candidate_frequency: 0, victim_frequency: 0)
129
+
130
+ bay.keys # => [2, 1]
131
+ bay.access(1) # => true
132
+ bay.keys # => [1, 2]
133
+ bay.access(9) # => false
134
+ bay.size # => 2
135
+ ```
136
+
137
+ ### Victim
138
+
139
+ `victim` is the key at the back of the line, the one `admit` would evict. It is `nil` until the bay is full. Ask for it right before you admit, look up its frequency, and pass that in.
140
+
141
+ ```ruby
142
+ 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
146
+ bay.access(0)
147
+ bay.victim # => 1
148
+ ```
149
+
150
+ ### Remove and clear
151
+
152
+ ```ruby
153
+ bay = CacheMachines::Lru.new
154
+ bay.admit(1, candidate_frequency: 0, victim_frequency: 0)
155
+ bay.remove(1) # => true
156
+ bay.remove(1) # => false
157
+ bay.clear # => nil
158
+ bay.empty? # => true
159
+ ```
160
+
161
+ `keys` is a snapshot, most recent first. Mutate the array all you like; the bay doesn't notice.
162
+
163
+ ## The Rules of the Tender
164
+
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`.
168
+ - **Frequencies are yours.** The bay never counts hits. It compares the two numbers you give it and nothing else.
169
+ - **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
+
171
+ ## What You Think You're Doing vs Reality
172
+
173
+ ### You Think: "A bigger cache would have survived the export."
174
+ ### Reality: Any finite cache loses to a scan larger than itself.
175
+
176
+ The export touches more rows than you have berths. Doubling the bay means it takes twice as long to flush, then flushes anyway. The fix is not more room. The fix is a hatch that asks whether the newcomer has earned a berth, and the answer for a row read once is no.
177
+
178
+ ## What's Yours
179
+
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.
181
+
182
+ ## License
183
+
184
+ MIT License. See [LICENSE.txt](LICENSE.txt) for details.
185
+
186
+ **Remember: The export job will read every row once. Make sure once is not enough.**
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ ## [0.2.2](https://github.com/seuros/cache_machines/compare/cache-machines-v0.2.1...cache-machines-v0.2.2) (2026-11-06)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * crates.io keywords and categories for the core ([03e3752](https://github.com/seuros/cache_machines/commit/03e375232563df5cf56b4bbe8435540048b3f2c7))
9
+
10
+ ## [0.2.1](https://github.com/seuros/cache_machines/compare/cache-machines-v0.2.0...cache-machines-v0.2.1) (2026-11-06)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * keep test sources out of the packaged gem and crate ([28635a4](https://github.com/seuros/cache_machines/commit/28635a4df2b2313914957f8cf8b068934bb35f7d))
16
+
17
+ ## [0.2.0](https://github.com/seuros/cache_machines/compare/cache-machines-v0.1.0...cache-machines-v0.2.0) (2026-11-06)
18
+
19
+
20
+ ### Features
21
+
22
+ * initial extraction ([3569bc6](https://github.com/seuros/cache_machines/commit/3569bc6ccda4ec7c7bc345ab7be84f92e8edcedd))
@@ -0,0 +1,13 @@
1
+ [package]
2
+ name = "cache-machines"
3
+ version = "0.2.2"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ description = "Bounded LRU policy with caller-measured frequency admission"
8
+ readme = "README.md"
9
+ exclude = ["src/**/tests.rs", "tests/"]
10
+ keywords = ["cache", "lru", "admission", "eviction", "no-std"]
11
+ categories = ["no-std", "algorithms", "caching"]
12
+ [lints]
13
+ workspace = true
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdelkader Boudih
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ # cache-machines
2
+
3
+ > **AMS Denning**, NCC-4203, *Denning*-class cache tender.
4
+
5
+ Engine-room flight manual: choose which supplies deserve a berth in limited storage.
6
+
7
+ Allocation-free `no_std` fixed-capacity LRU key policy. Hits move a key to the
8
+ front; accepted new keys evict the least-recently-used key. When full, admission
9
+ requires candidate frequency to exceed the victim's frequency (ties retain the
10
+ incumbent). Frequencies are supplied by the caller, potentially using an existing
11
+ probabilistic sketch; this is not a complete TinyLFU/W-TinyLFU implementation.
12
+
13
+ Values, loading, eviction callbacks, TTLs, byte weights, synchronization, and sketch
14
+ aging are not owned by this policy. Coordinate key-policy mutations with storage
15
+ updates. A zero-capacity cache rejects every insertion.
@@ -0,0 +1,141 @@
1
+ #![no_std]
2
+ #![doc = include_str!("../README.md")]
3
+
4
+ /// Outcome for a key admission.
5
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6
+ #[non_exhaustive]
7
+ pub enum Admission<K> {
8
+ /// Existing key was promoted.
9
+ Hit,
10
+ /// New key was inserted into an empty slot.
11
+ Inserted,
12
+ /// The least-recently-used key was replaced.
13
+ Evicted(K),
14
+ /// Frequency policy or zero capacity rejected the candidate.
15
+ Rejected,
16
+ }
17
+
18
+ /// LRU keys in most-recent-first order.
19
+ #[derive(Debug, Clone, PartialEq, Eq)]
20
+ pub struct Lru<K, const N: usize> {
21
+ keys: [Option<K>; N],
22
+ len: usize,
23
+ }
24
+
25
+ impl<K: Copy + Eq, const N: usize> Default for Lru<K, N> {
26
+ fn default() -> Self {
27
+ Self::new()
28
+ }
29
+ }
30
+
31
+ impl<K: Copy + Eq, const N: usize> Lru<K, N> {
32
+ /// Start empty.
33
+ #[must_use]
34
+ pub const fn new() -> Self {
35
+ Self {
36
+ keys: [None; N],
37
+ len: 0,
38
+ }
39
+ }
40
+
41
+ /// Maximum number of keys this policy can retain.
42
+ #[must_use]
43
+ pub const fn capacity(&self) -> usize {
44
+ N
45
+ }
46
+
47
+ /// Number of retained keys.
48
+ #[must_use]
49
+ pub const fn len(&self) -> usize {
50
+ self.len
51
+ }
52
+
53
+ /// Whether there are no retained keys.
54
+ #[must_use]
55
+ pub const fn is_empty(&self) -> bool {
56
+ self.len == 0
57
+ }
58
+
59
+ /// Retained keys in most-recent-first order.
60
+ pub fn keys(&self) -> impl Iterator<Item = K> + '_ {
61
+ self.keys[..self.len].iter().flatten().copied()
62
+ }
63
+
64
+ /// Forget every key.
65
+ pub fn clear(&mut self) {
66
+ self.keys.fill(None);
67
+ self.len = 0;
68
+ }
69
+
70
+ fn index(&self, key: K) -> Option<usize> {
71
+ self.keys[..self.len]
72
+ .iter()
73
+ .position(|value| *value == Some(key))
74
+ }
75
+
76
+ /// 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;
81
+ };
82
+ self.keys[index..self.len].rotate_left(1);
83
+ self.len -= 1;
84
+ self.keys[self.len] = None;
85
+ true
86
+ }
87
+
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;
93
+ };
94
+ self.keys[..=index].rotate_right(1);
95
+ true
96
+ }
97
+
98
+ /// Admit a key; victim frequency refers to the current `victim()` key.
99
+ #[must_use]
100
+ pub fn admit(
101
+ &mut self,
102
+ key: K,
103
+ candidate_frequency: u64,
104
+ victim_frequency: u64,
105
+ ) -> Admission<K> {
106
+ if self.access(key) {
107
+ return Admission::Hit;
108
+ }
109
+ if N == 0 {
110
+ return Admission::Rejected;
111
+ }
112
+ let outcome = if self.len == N {
113
+ if candidate_frequency <= victim_frequency {
114
+ return Admission::Rejected;
115
+ }
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
123
+ };
124
+ self.keys[..self.len].rotate_right(1);
125
+ self.keys[0] = Some(key);
126
+ outcome
127
+ }
128
+
129
+ /// Current eviction candidate, when the cache is full and nonempty.
130
+ #[must_use]
131
+ pub const fn victim(&self) -> Option<K> {
132
+ if N > 0 && self.len == N {
133
+ self.keys[N - 1]
134
+ } else {
135
+ None
136
+ }
137
+ }
138
+ }
139
+
140
+ #[cfg(test)]
141
+ mod tests;
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ load File.expand_path('ffi/extconf.rb', __dir__)
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "cache_machines_native"
3
+ version = "0.1.3"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ description = "Ruby bindings for bounded LRU and caller-measured frequency admission"
8
+ publish = false
9
+
10
+ [lib]
11
+ crate-type = ["cdylib"]
12
+ test = false
13
+ doctest = false
14
+
15
+ [dependencies]
16
+ cache-machines.workspace = true
17
+ magnus.workspace = true
18
+ rb-sys.workspace = true
19
+
20
+ [lints]
21
+ workspace = true
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'mkmf'
4
+ require 'pathname'
5
+ require 'rb_sys/mkmf'
6
+
7
+ create_rust_makefile('cache_machines_native/cache_machines_native') do |extension|
8
+ extension.ext_dir = Pathname(__dir__).relative_path_from(Pathname(Dir.pwd)).to_s
9
+ extension.profile = ENV.fetch('RB_SYS_CARGO_PROFILE', :release).to_sym
10
+ end
11
+
12
+ # rake-compiler invokes extconf from tmp/, not the extension source directory.
13
+ makefile = File.join(Dir.pwd, 'Makefile')
14
+ File.write(
15
+ makefile,
16
+ File.read(makefile).gsub(
17
+ /^RB_SYS_CARGO_MANIFEST_DIR \?=.*$/,
18
+ "RB_SYS_CARGO_MANIFEST_DIR ?= #{File.expand_path(__dir__)}"
19
+ )
20
+ )
@@ -0,0 +1,116 @@
1
+ //! Thin native binding; all ordering and admission decisions belong to the core.
2
+
3
+ use std::cell::RefCell;
4
+
5
+ use cache_machines::{Admission, Lru};
6
+ use magnus::scan_args::{get_kwargs, scan_args};
7
+ use magnus::typed_data::Obj;
8
+ use magnus::{
9
+ Error, Integer, RHash, Ruby, Symbol, TryConvert, Value, function, method, prelude::*,
10
+ };
11
+
12
+ const CAPACITY: usize = 64;
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)
27
+ }
28
+ }
29
+
30
+ #[magnus::wrap(class = "CacheMachines::Lru", free_immediately, size)]
31
+ struct Wrapper(RefCell<Lru<u64, CAPACITY>>);
32
+
33
+ impl Wrapper {
34
+ const fn new() -> Self {
35
+ Self(RefCell::new(Lru::new()))
36
+ }
37
+
38
+ fn admit(
39
+ ruby: &Ruby,
40
+ rb_self: Obj<Self>,
41
+ args: &[Value],
42
+ ) -> Result<(Symbol, Option<u64>), Error> {
43
+ 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))
67
+ }
68
+
69
+ fn access(rb_self: Obj<Self>, key: Number) -> Result<bool, Error> {
70
+ rb_self.check_frozen()?;
71
+ Ok(rb_self.0.borrow_mut().access(key.0))
72
+ }
73
+
74
+ fn remove(rb_self: Obj<Self>, key: Number) -> Result<bool, Error> {
75
+ rb_self.check_frozen()?;
76
+ Ok(rb_self.0.borrow_mut().remove(key.0))
77
+ }
78
+
79
+ fn clear(rb_self: Obj<Self>) -> Result<(), Error> {
80
+ rb_self.check_frozen()?;
81
+ rb_self.0.borrow_mut().clear();
82
+ Ok(())
83
+ }
84
+
85
+ fn keys(&self) -> Vec<u64> {
86
+ self.0.borrow().keys().collect()
87
+ }
88
+
89
+ fn len(&self) -> usize {
90
+ self.0.borrow().len()
91
+ }
92
+
93
+ fn is_empty(&self) -> bool {
94
+ self.0.borrow().is_empty()
95
+ }
96
+
97
+ fn victim(&self) -> Option<u64> {
98
+ self.0.borrow().victim()
99
+ }
100
+ }
101
+
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))
116
+ }
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CacheMachines
4
+ VERSION = '0.1.4'
5
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'cache_machines/version'
4
+
5
+ # A missing extension is an installation error. There is no Ruby policy fallback.
6
+ require 'cache_machines_native/cache_machines_native'
@@ -0,0 +1,17 @@
1
+ module CacheMachines
2
+ VERSION: String
3
+
4
+ class Lru
5
+ CAPACITY: Integer
6
+
7
+ 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
11
+ def clear: () -> nil
12
+ def keys: () -> Array[Integer]
13
+ def size: () -> Integer
14
+ def empty?: () -> bool
15
+ def victim: () -> Integer?
16
+ end
17
+ end
metadata ADDED
@@ -0,0 +1,84 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cache_machines
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.4
5
+ platform: ruby
6
+ authors:
7
+ - Abdelkader Boudih
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rb_sys
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.9'
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 0.9.130
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '0.9'
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 0.9.130
32
+ description: A native binding to the allocation-free cache-machines Rust core. Tracks
33
+ numeric keys and caller-measured admission frequencies; payload storage and frequency
34
+ measurement remain with the caller.
35
+ email:
36
+ - oss@seuros.com
37
+ executables: []
38
+ extensions:
39
+ - ext/cache_machines_native/extconf.rb
40
+ extra_rdoc_files: []
41
+ files:
42
+ - CHANGELOG.md
43
+ - Cargo.toml
44
+ - LICENSE.txt
45
+ - README.md
46
+ - ext/cache_machines_native/core/CHANGELOG.md
47
+ - ext/cache_machines_native/core/Cargo.toml
48
+ - ext/cache_machines_native/core/LICENSE
49
+ - ext/cache_machines_native/core/README.md
50
+ - ext/cache_machines_native/core/src/lib.rs
51
+ - ext/cache_machines_native/extconf.rb
52
+ - ext/cache_machines_native/ffi/Cargo.toml
53
+ - ext/cache_machines_native/ffi/extconf.rb
54
+ - ext/cache_machines_native/ffi/src/lib.rs
55
+ - lib/cache_machines.rb
56
+ - lib/cache_machines/version.rb
57
+ - sig/cache_machines.rbs
58
+ homepage: https://github.com/seuros/cache_machines
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ source_code_uri: https://github.com/seuros/cache_machines
63
+ bug_tracker_uri: https://github.com/seuros/cache_machines/issues
64
+ rubygems_mfa_required: 'true'
65
+ cargo_crate_name: cache_machines_native
66
+ cargo_manifest_path: ext/cache_machines_native/ffi/Cargo.toml
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 4.0.0
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 4.0.20
82
+ specification_version: 4
83
+ summary: Bounded native LRU and admission policy for Ruby
84
+ test_files: []