fair_machines 0.1.5 → 0.6.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.
@@ -1,105 +1,217 @@
1
- use crate::{Count, Positive, arg_error, integer, kwargs};
2
- use fair_machines::{KeyedFair, Lane};
3
- use magnus::{
4
- Error, RModule, Ruby, TryConvert, Value, function, method, prelude::*, typed_data::Obj,
1
+ //! Exact const-generic lane counts erased only for the host binding.
2
+
3
+ use crate::{done, range_error, refusal};
4
+ use fair_machines::{KeyedFair, Lane, Refusal};
5
+ use magnus::{Error, RModule, Ruby, Value, function, method, prelude::*, typed_data::Obj};
6
+ use matryona_machines::ruby::{
7
+ Class, Registry, exact_fields, integer, integer_in, keep, positive, sized,
5
8
  };
6
- use std::{cell::RefCell, num::NonZeroU32};
9
+ use std::{any::Any, cell::RefCell, num::NonZeroU32};
10
+
11
+ /// The `Data` class the binding builds and reads, resolved once at init.
12
+ struct Classes {
13
+ lane: Class,
14
+ }
15
+
16
+ static CLASSES: Registry<Classes> = Registry::new("fair_machines");
17
+
18
+ /// Largest `LANES` compiled into the binding: `KeyedFair<1>` to
19
+ /// `KeyedFair<256>`. The core takes any `LANES > 0`.
20
+ const MAX_LANES: usize = 256;
21
+
22
+ /// One lane count: the associated functions, and a constructor.
23
+ #[derive(Clone, Copy)]
24
+ struct Shape {
25
+ lane: fn(u64) -> usize,
26
+ lane_at: fn(usize) -> Option<usize>,
27
+ build: fn(NonZeroU32) -> Box<dyn Lanes>,
28
+ }
7
29
 
8
30
  trait Lanes: Send {
9
- fn admit(&mut self, hash: u64, cost: NonZeroU32) -> Option<usize>;
10
- fn release(&mut self, lane: usize, cost: NonZeroU32) -> bool;
11
- fn in_flight(&self, lane: usize) -> u32;
12
- fn lane(&self, hash: u64) -> usize;
31
+ fn copy(&self) -> Box<dyn Lanes>;
32
+ fn same(&self, other: &dyn Lanes) -> bool;
33
+ fn as_any(&self) -> &dyn Any;
34
+ fn admit(&mut self, hash: u64, cost: NonZeroU32) -> Result<Lane, Refusal>;
35
+ fn release(&mut self, lane: Lane, cost: NonZeroU32) -> Result<(), Refusal>;
36
+ fn lane_count(&self) -> usize;
37
+ fn in_flight(&self, lane: Lane) -> Option<u32>;
38
+ fn available(&self, lane: Lane) -> Option<u32>;
39
+ }
40
+
41
+ /// What clone-then-keep copies and compares: the erased core, by value.
42
+ impl Clone for Box<dyn Lanes> {
43
+ fn clone(&self) -> Self {
44
+ self.copy()
45
+ }
46
+ }
47
+
48
+ impl PartialEq for Box<dyn Lanes> {
49
+ fn eq(&self, other: &Self) -> bool {
50
+ self.same(&**other)
51
+ }
13
52
  }
14
53
 
15
54
  impl<const N: usize> Lanes for KeyedFair<N> {
16
- fn admit(&mut self, hash: u64, cost: NonZeroU32) -> Option<usize> {
17
- self.admit(hash, cost).map(Lane::index)
55
+ fn copy(&self) -> Box<dyn Lanes> {
56
+ Box::new(self.clone())
57
+ }
58
+ fn same(&self, other: &dyn Lanes) -> bool {
59
+ other.as_any().downcast_ref::<Self>() == Some(self)
18
60
  }
19
- fn release(&mut self, lane: usize, cost: NonZeroU32) -> bool {
20
- Self::lane_at(lane).is_some_and(|lane| self.release(lane, cost))
61
+ fn as_any(&self) -> &dyn Any {
62
+ self
21
63
  }
22
- fn in_flight(&self, lane: usize) -> u32 {
23
- Self::lane_at(lane).map_or(0, |lane| self.in_flight(lane))
64
+ fn admit(&mut self, hash: u64, cost: NonZeroU32) -> Result<Lane, Refusal> {
65
+ self.admit(hash, cost)
24
66
  }
25
- fn lane(&self, hash: u64) -> usize {
26
- Self::lane(hash).index()
67
+ fn release(&mut self, lane: Lane, cost: NonZeroU32) -> Result<(), Refusal> {
68
+ self.release(lane, cost)
69
+ }
70
+ fn lane_count(&self) -> usize {
71
+ self.lane_count()
72
+ }
73
+ fn in_flight(&self, lane: Lane) -> Option<u32> {
74
+ self.in_flight(lane)
75
+ }
76
+ fn available(&self, lane: Lane) -> Option<u32> {
77
+ self.available(lane)
27
78
  }
28
79
  }
29
80
 
30
- /// Any Integer, reduced to its low 64 bits, so `key.hash` works as is.
31
- #[derive(Clone, Copy)]
32
- struct Hash(u64);
81
+ /// The shape of `KeyedFair<lanes>`, or `RangeError` outside `1..=256`.
82
+ fn shape(ruby: &Ruby, lanes: Value) -> Result<Shape, Error> {
83
+ let lanes = integer_in(lanes, "lanes", 1..=MAX_LANES)?;
84
+ #[rustfmt::skip]
85
+ let shape = sized!(
86
+ lanes,
87
+ [
88
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
89
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
90
+ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
91
+ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
92
+ 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
93
+ 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
94
+ 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
95
+ 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160,
96
+ 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
97
+ 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
98
+ 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,
99
+ 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
100
+ 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
101
+ 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256
102
+ ],
103
+ |N| Shape {
104
+ lane: |hash| KeyedFair::<N>::lane(hash).index(),
105
+ lane_at: |index| KeyedFair::<N>::lane_at(index).map(Lane::index),
106
+ build: |capacity| Box::new(KeyedFair::<N>::new(capacity)),
107
+ },
108
+ _ => return Err(range_error(ruby, format!("lanes must be in 1..={MAX_LANES}"))),
109
+ );
110
+ Ok(shape)
111
+ }
33
112
 
34
- impl TryConvert for Hash {
35
- #[allow(clippy::cast_sign_loss)]
36
- fn try_convert(value: Value) -> Result<Self, Error> {
37
- let int = integer(value)?;
38
- int.to_i64()
39
- .map(|v| v as u64)
40
- .or_else(|_| int.to_u64())
41
- .map(Self)
42
- }
113
+ /// A `FairMachines::Lane` for `index`, through `Lane.new`.
114
+ fn lane_value(ruby: &Ruby, index: usize) -> Result<Value, Error> {
115
+ let class = CLASSES.get(ruby)?.lane.get(ruby);
116
+ class.funcall("new", (index,))
43
117
  }
44
118
 
45
- #[magnus::wrap(class = "FairMachines::KeyedFair", free_immediately, size)]
46
- struct Wrapper {
47
- core: RefCell<Box<dyn Lanes>>,
48
- lanes: usize,
119
+ /// The core `Lane` of a `FairMachines::Lane`: `TypeError` for anything but
120
+ /// an instance of exactly that class, and its member re-validated as
121
+ /// `Lane::new` holds it, so a forged value never reaches the core.
122
+ fn core_lane(ruby: &Ruby, lane: Value) -> Result<Lane, Error> {
123
+ let class = CLASSES.get(ruby)?.lane.get(ruby);
124
+ let [index] = exact_fields::<1>(ruby, lane, class, "lane must be a FairMachines::Lane")?;
125
+ integer(index, "lane index").map(Lane::new)
49
126
  }
50
127
 
128
+ /// `FairMachines.__lane`, the private hook `Lane.new` validates through:
129
+ /// the index as `Lane::new` holds it.
130
+ fn validated(position: Value) -> Result<usize, Error> {
131
+ integer(position, "index").map(|position| Lane::new(position).index())
132
+ }
133
+
134
+ #[magnus::wrap(class = "FairMachines::KeyedFair", free_immediately, size)]
135
+ struct Wrapper(RefCell<Box<dyn Lanes>>);
136
+
51
137
  impl Wrapper {
52
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
53
- let (Count(lanes), Positive(capacity)) = kwargs(args, &["lanes", "capacity"])?;
54
- macro_rules! sized {
55
- ($($n:literal),*) => {
56
- match lanes {
57
- $($n => Box::new(KeyedFair::<$n>::new(capacity)) as Box<dyn Lanes>,)*
58
- _ => {
59
- let message = "lanes must be 1, 2, 4, 8, 16, 32, 64, 128 or 256";
60
- return Err(arg_error(ruby, message));
61
- }
62
- }
63
- };
64
- }
65
- let core = sized!(1, 2, 4, 8, 16, 32, 64, 128, 256);
66
- Ok(Self {
67
- core: RefCell::new(core),
68
- lanes: lanes as usize,
69
- })
138
+ fn new(ruby: &Ruby, lanes: Value, capacity: Value) -> Result<Self, Error> {
139
+ let build = shape(ruby, lanes)?.build;
140
+ Ok(Self(RefCell::new(build(positive(capacity, "capacity")?))))
141
+ }
142
+
143
+ /// `KeyedFair::<LANES>::lane(hash)`: the lane count comes first.
144
+ fn lane(ruby: &Ruby, lanes: Value, hash: Value) -> Result<Value, Error> {
145
+ let lane = shape(ruby, lanes)?.lane;
146
+ lane_value(ruby, lane(integer(hash, "hash")?))
147
+ }
148
+
149
+ /// `KeyedFair::<LANES>::lane_at(index)`: the lane count comes first.
150
+ fn lane_at(ruby: &Ruby, lanes: Value, position: Value) -> Result<Option<Value>, Error> {
151
+ let lane_at = shape(ruby, lanes)?.lane_at;
152
+ lane_at(integer(position, "index")?)
153
+ .map(|position| lane_value(ruby, position))
154
+ .transpose()
70
155
  }
71
156
 
72
- fn admit(rb_self: Obj<Self>, args: &[Value]) -> Result<Option<usize>, Error> {
73
- rb_self.check_frozen()?;
74
- let (Hash(hash), Positive(cost)) = kwargs(args, &["hash", "cost"])?;
75
- Ok(rb_self.core.borrow_mut().admit(hash, cost))
157
+ /// Clone-then-keep: the core admits on a copy, the Lane is built, and
158
+ /// the copy is stored only if the receiver is still unfrozen and
159
+ /// unchanged; otherwise nothing is admitted. A frozen receiver raises
160
+ /// before the arguments are read.
161
+ fn admit(ruby: &Ruby, this: Obj<Self>, hash: Value, cost: Value) -> Result<Value, Error> {
162
+ this.check_frozen()?;
163
+ let (hash, cost) = (integer(hash, "hash")?, positive(cost, "cost")?);
164
+ keep(
165
+ ruby,
166
+ this,
167
+ &this.0,
168
+ |core| core.admit(hash, cost),
169
+ |admitted| match admitted {
170
+ Ok(lane) => lane_value(ruby, lane.index()),
171
+ Err(refused) => Ok(refusal(ruby, refused)),
172
+ },
173
+ )
76
174
  }
77
175
 
78
- fn release(rb_self: Obj<Self>, args: &[Value]) -> Result<bool, Error> {
79
- rb_self.check_frozen()?;
80
- let (Count(lane), Positive(cost)) = kwargs(args, &["lane", "cost"])?;
81
- Ok(rb_self.core.borrow_mut().release(lane as usize, cost))
176
+ fn release(ruby: &Ruby, this: Obj<Self>, lane: Value, cost: Value) -> Result<Value, Error> {
177
+ this.check_frozen()?;
178
+ let lane = core_lane(ruby, lane)?;
179
+ let cost = positive(cost, "cost")?;
180
+ let answer = this.0.borrow_mut().release(lane, cost);
181
+ Ok(done(ruby, answer, "released"))
82
182
  }
83
183
 
84
- fn in_flight(&self, lane: Count) -> u32 {
85
- self.core.borrow().in_flight(lane.0 as usize)
184
+ fn lane_count(&self) -> usize {
185
+ self.0.borrow().lane_count()
86
186
  }
87
187
 
88
- fn lane(&self, hash: Hash) -> usize {
89
- self.core.borrow().lane(hash.0)
188
+ fn in_flight(ruby: &Ruby, this: &Self, lane: Value) -> Result<Option<u32>, Error> {
189
+ let lane = core_lane(ruby, lane)?;
190
+ Ok(this.0.borrow().in_flight(lane))
90
191
  }
91
192
 
92
- const fn lane_count(&self) -> usize {
93
- self.lanes
193
+ fn available(ruby: &Ruby, this: &Self, lane: Value) -> Result<Option<u32>, Error> {
194
+ let lane = core_lane(ruby, lane)?;
195
+ Ok(this.0.borrow().available(lane))
94
196
  }
95
197
  }
96
198
 
97
199
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
200
+ let lane = Class::resolve(ruby, module, "Lane")?;
201
+ CLASSES.set(ruby, Classes { lane })?;
202
+ module.define_singleton_method("__lane", function!(validated, 1))?;
98
203
  let class = module.define_class("KeyedFair", ruby.class_object())?;
99
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
100
- class.define_method("admit", method!(Wrapper::admit, -1))?;
101
- class.define_method("release", method!(Wrapper::release, -1))?;
204
+ class.undef_default_alloc_func();
205
+ class.const_set("MAX_LANES", MAX_LANES)?;
206
+ class.define_singleton_method("new", function!(Wrapper::new, 2))?;
207
+ class.define_singleton_method("lane", function!(Wrapper::lane, 2))?;
208
+ class.define_singleton_method("lane_at", function!(Wrapper::lane_at, 2))?;
209
+ class.define_method("admit", method!(Wrapper::admit, 2))?;
210
+ class.define_method("release", method!(Wrapper::release, 2))?;
211
+ class.define_method("lane_count", method!(Wrapper::lane_count, 0))?;
102
212
  class.define_method("in_flight", method!(Wrapper::in_flight, 1))?;
103
- class.define_method("lane", method!(Wrapper::lane, 1))?;
104
- class.define_method("lane_count", method!(Wrapper::lane_count, 0))
213
+ class.define_method("available", method!(Wrapper::available, 1))?;
214
+ // `new` answers a KeyedFair: its class is fixed now, so building one
215
+ // never runs `Object.const_get`.
216
+ Class::pin_wrapped::<Wrapper>(ruby, class).map(drop)
105
217
  }
@@ -4,59 +4,51 @@ mod init;
4
4
  mod keyed;
5
5
  mod tenants;
6
6
 
7
- use magnus::{
8
- Error, Integer, RArray, RHash, Ruby, TryConvert, Value,
9
- scan_args::{get_kwargs, scan_args},
10
- };
7
+ use fair_machines::Refusal;
8
+ use magnus::{Error, RArray, Ruby, Value, prelude::*};
9
+ use matryona_machines::ruby::{Symbols, optional_positive, positive, symbol};
11
10
  use std::num::NonZeroU32;
12
11
 
13
- pub(crate) fn arg_error(ruby: &Ruby, message: &'static str) -> Error {
14
- Error::new(ruby.exception_arg_error(), message)
15
- }
16
-
17
- /// `value` as an Integer; Floats and numeric Strings raise `TypeError`.
18
- pub(crate) fn integer(value: Value) -> Result<Integer, Error> {
19
- Integer::from_value(value).ok_or_else(|| {
20
- Error::new(
21
- Ruby::get_with(value).exception_type_error(),
22
- "expected an Integer",
23
- )
24
- })
12
+ matryona_machines::symbols! {
13
+ /// The core's refusals as Symbols: the snake case of each variant.
14
+ pub(crate) Refusals for Refusal as "a refusal" {
15
+ UnknownTenant => "unknown_tenant",
16
+ UnknownLane => "unknown_lane",
17
+ Insufficient => "insufficient",
18
+ ExceedsInFlight => "exceeds_in_flight",
19
+ }
25
20
  }
26
21
 
27
- /// Exactly the two required keywords `keys`, converted in order.
28
- pub(crate) fn kwargs<A: TryConvert, B: TryConvert>(
29
- args: &[Value],
30
- keys: &[&str; 2],
31
- ) -> Result<(A, B), Error> {
32
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
33
- Ok(get_kwargs::<_, (A, B), (), ()>(args.keywords, keys, &[])?.required)
22
+ /// `RangeError`: the right type, a value the core cannot be built with.
23
+ pub(crate) fn range_error(ruby: &Ruby, message: impl Into<String>) -> Error {
24
+ Error::new(ruby.exception_range_error(), message.into())
34
25
  }
35
26
 
36
- /// Every element of `values`, converted in order.
37
- pub(crate) fn convert_all<T: TryConvert>(values: RArray) -> Result<Vec<T>, Error> {
38
- values.into_iter().map(T::try_convert).collect()
27
+ /// Ruby symbol of a refusal: the snake case of the core variant.
28
+ pub(crate) fn refusal(ruby: &Ruby, refused: Refusal) -> Value {
29
+ Refusals::symbol(ruby, refused).as_value()
39
30
  }
40
31
 
41
- /// A `u32` Integer.
42
- #[derive(Clone, Copy)]
43
- pub(crate) struct Count(pub(crate) u32);
44
-
45
- impl TryConvert for Count {
46
- fn try_convert(value: Value) -> Result<Self, Error> {
47
- integer(value)?.to_u32().map(Self)
32
+ /// The symbol `honoured` for `Ok(())`, the refusal's symbol otherwise.
33
+ pub(crate) fn done(ruby: &Ruby, answer: Result<(), Refusal>, honoured: &str) -> Value {
34
+ match answer {
35
+ Ok(()) => symbol(ruby, honoured).as_value(),
36
+ Err(refused) => refusal(ruby, refused),
48
37
  }
49
38
  }
50
39
 
51
- /// A positive `u32` Integer.
52
- #[derive(Clone, Copy)]
53
- pub(crate) struct Positive(pub(crate) NonZeroU32);
40
+ /// Every element of `values`, each a positive `u32`.
41
+ pub(crate) fn positives(values: RArray, name: &str) -> Result<Vec<NonZeroU32>, Error> {
42
+ values
43
+ .into_iter()
44
+ .map(|value| positive(value, name))
45
+ .collect()
46
+ }
54
47
 
55
- impl TryConvert for Positive {
56
- fn try_convert(value: Value) -> Result<Self, Error> {
57
- let Count(count) = Count::try_convert(value)?;
58
- NonZeroU32::new(count)
59
- .map(Self)
60
- .ok_or_else(|| arg_error(&Ruby::get_with(value), "expected a positive u32"))
61
- }
48
+ /// Head costs: each positive, or `nil` for a tenant with nothing waiting.
49
+ pub(crate) fn heads(values: RArray) -> Result<Vec<Option<NonZeroU32>>, Error> {
50
+ values
51
+ .into_iter()
52
+ .map(|value| optional_positive(value, "heads"))
53
+ .collect()
62
54
  }
@@ -1,102 +1,161 @@
1
1
  //! Exact const-generic tenant counts erased only for the host binding.
2
2
 
3
- use crate::{Count, Positive, arg_error, convert_all, kwargs};
4
- use fair_machines::TenantFair;
5
- use magnus::{Error, RArray, RModule, Ruby, Value, function, method, prelude::*, typed_data::Obj};
3
+ use crate::{done, positives, range_error, refusal};
4
+ use fair_machines::{Refusal, TenantFair};
5
+ use magnus::{Error, RModule, Ruby, Value, function, method, prelude::*, typed_data::Obj};
6
+ use matryona_machines::ruby::{Class, exact_array, integer, positive, sized};
6
7
  use std::{cell::RefCell, num::NonZeroU32};
7
8
 
9
+ /// Largest `N` compiled into the binding: `TenantFair<1>` to `TenantFair<16>`.
10
+ /// The core takes any `N`; Ruby picks one of these by the arrays' length.
11
+ const MAX_TENANTS: usize = 16;
12
+
8
13
  trait Tenants: Send {
9
- fn admit(&mut self, tenant: usize, cost: NonZeroU32) -> bool;
10
- fn cancel(&mut self, tenant: usize, cost: NonZeroU32) -> bool;
11
- fn select(&mut self, heads: &[Option<NonZeroU32>]) -> Option<usize>;
14
+ fn admit(&mut self, tenant: usize, cost: NonZeroU32) -> Result<(), Refusal>;
15
+ fn cancel(&mut self, tenant: usize, cost: NonZeroU32) -> Result<(), Refusal>;
16
+ fn select(&mut self, heads: &[Option<NonZeroU32>]) -> Result<Option<usize>, Refusal>;
17
+ fn tenant_count(&self) -> usize;
18
+ fn in_flight(&self, tenant: usize) -> Option<u32>;
19
+ fn available(&self, tenant: usize) -> Option<u32>;
12
20
  }
13
21
 
14
22
  impl<const N: usize> Tenants for TenantFair<N> {
15
- fn admit(&mut self, tenant: usize, cost: NonZeroU32) -> bool {
23
+ fn admit(&mut self, tenant: usize, cost: NonZeroU32) -> Result<(), Refusal> {
16
24
  self.admit(tenant, cost)
17
25
  }
18
- fn cancel(&mut self, tenant: usize, cost: NonZeroU32) -> bool {
26
+ fn cancel(&mut self, tenant: usize, cost: NonZeroU32) -> Result<(), Refusal> {
19
27
  self.cancel(tenant, cost)
20
28
  }
21
- fn select(&mut self, heads: &[Option<NonZeroU32>]) -> Option<usize> {
29
+ fn select(&mut self, heads: &[Option<NonZeroU32>]) -> Result<Option<usize>, Refusal> {
22
30
  self.select(&std::array::from_fn(|index| heads[index]))
23
31
  }
32
+ fn tenant_count(&self) -> usize {
33
+ self.tenant_count()
34
+ }
35
+ fn in_flight(&self, tenant: usize) -> Option<u32> {
36
+ self.in_flight(tenant)
37
+ }
38
+ fn available(&self, tenant: usize) -> Option<u32> {
39
+ self.available(tenant)
40
+ }
24
41
  }
25
42
 
43
+ /// A core call that admits or returns one tenant's cost.
44
+ type BudgetCall = fn(&mut Box<dyn Tenants>, usize, NonZeroU32) -> Result<(), Refusal>;
45
+
26
46
  #[magnus::wrap(class = "FairMachines::TenantFair", free_immediately, size)]
27
- struct Wrapper {
28
- core: RefCell<Box<dyn Tenants>>,
29
- count: usize,
30
- }
47
+ struct Wrapper(RefCell<Box<dyn Tenants>>);
31
48
 
32
49
  impl Wrapper {
33
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
34
- let (capacities, quanta): (RArray, RArray) = kwargs(args, &["capacities", "quanta"])?;
50
+ fn new(ruby: &Ruby, capacities: Value, quanta: Value) -> Result<Self, Error> {
51
+ let capacities = exact_array(ruby, capacities, "capacities must be an Array")?;
52
+ let quanta = exact_array(ruby, quanta, "quanta must be an Array")?;
35
53
  if capacities.len() != quanta.len() {
36
- return Err(arg_error(ruby, "capacities and quanta lengths must match"));
37
- }
38
- let capacities = convert_all::<Positive>(capacities)?;
39
- let quanta = convert_all::<Positive>(quanta)?;
40
- macro_rules! sized {
41
- ($($n:literal),*) => {
42
- match capacities.len() {
43
- $($n => Box::new(TenantFair::<$n>::new(
44
- std::array::from_fn(|i| capacities[i].0),
45
- std::array::from_fn(|i| quanta[i].0))) as Box<dyn Tenants>,)*
46
- _ => return Err(arg_error(ruby, "tenant count must be 1..16")),
47
- }
48
- };
54
+ return Err(range_error(
55
+ ruby,
56
+ "capacities and quanta lengths must match",
57
+ ));
49
58
  }
50
- let core = sized!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
51
- Ok(Self {
52
- core: RefCell::new(core),
53
- count: capacities.len(),
54
- })
59
+ let capacities = positives(capacities, "capacities")?;
60
+ let quanta = positives(quanta, "quanta")?;
61
+ let core = sized!(
62
+ capacities.len(),
63
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
64
+ |N| Box::new(TenantFair::<N>::new(
65
+ std::array::from_fn(|i| capacities[i]),
66
+ std::array::from_fn(|i| quanta[i]),
67
+ )) as Box<dyn Tenants>,
68
+ _ => {
69
+ return Err(range_error(
70
+ ruby,
71
+ format!("capacities must hold 1..={MAX_TENANTS} tenants"),
72
+ ));
73
+ },
74
+ );
75
+ Ok(Self(RefCell::new(core)))
55
76
  }
56
77
 
57
- /// Parse `tenant:`/`cost:` and apply `op` to the unfrozen core.
58
- fn with_cost(
59
- rb_self: Obj<Self>,
60
- args: &[Value],
61
- op: fn(&mut dyn Tenants, usize, NonZeroU32) -> bool,
62
- ) -> Result<bool, Error> {
63
- rb_self.check_frozen()?;
64
- let (Count(tenant), Positive(cost)) = kwargs(args, &["tenant", "cost"])?;
65
- Ok(op(&mut **rb_self.core.borrow_mut(), tenant as usize, cost))
78
+ fn admit(ruby: &Ruby, this: Obj<Self>, tenant: Value, cost: Value) -> Result<Value, Error> {
79
+ Self::apply(
80
+ ruby,
81
+ this,
82
+ (tenant, cost),
83
+ |core, tenant, cost| core.admit(tenant, cost),
84
+ "admitted",
85
+ )
66
86
  }
67
87
 
68
- fn admit(rb_self: Obj<Self>, args: &[Value]) -> Result<bool, Error> {
69
- Self::with_cost(rb_self, args, |core, tenant, cost| core.admit(tenant, cost))
88
+ fn cancel(ruby: &Ruby, this: Obj<Self>, tenant: Value, cost: Value) -> Result<Value, Error> {
89
+ Self::apply(
90
+ ruby,
91
+ this,
92
+ (tenant, cost),
93
+ |core, tenant, cost| core.cancel(tenant, cost),
94
+ "cancelled",
95
+ )
70
96
  }
71
97
 
72
- fn cancel(rb_self: Obj<Self>, args: &[Value]) -> Result<bool, Error> {
73
- Self::with_cost(rb_self, args, |core, tenant, cost| {
74
- core.cancel(tenant, cost)
75
- })
98
+ /// Check and convert everything that can raise, then call the core once.
99
+ fn apply(
100
+ ruby: &Ruby,
101
+ this: Obj<Self>,
102
+ (tenant, cost): (Value, Value),
103
+ operation: BudgetCall,
104
+ honoured: &str,
105
+ ) -> Result<Value, Error> {
106
+ this.check_frozen()?;
107
+ let tenant = integer(tenant, "tenant")?;
108
+ let cost = positive(cost, "cost")?;
109
+ let answer = operation(&mut this.0.borrow_mut(), tenant, cost);
110
+ Ok(done(ruby, answer, honoured))
76
111
  }
77
112
 
78
- fn select(ruby: &Ruby, rb_self: Obj<Self>, heads: RArray) -> Result<Option<usize>, Error> {
79
- rb_self.check_frozen()?;
80
- if heads.len() != rb_self.count {
81
- return Err(arg_error(ruby, "heads length must match tenant count"));
113
+ fn select(ruby: &Ruby, this: Obj<Self>, heads: Value) -> Result<Option<Value>, Error> {
114
+ this.check_frozen()?;
115
+ let heads = exact_array(ruby, heads, "heads must be an Array")?;
116
+ let tenants = this.0.borrow().tenant_count();
117
+ if heads.len() != tenants {
118
+ return Err(range_error(
119
+ ruby,
120
+ format!(
121
+ "heads must hold one entry per tenant: {} given, {tenants} tenants",
122
+ heads.len()
123
+ ),
124
+ ));
82
125
  }
83
- let heads: Vec<_> = convert_all::<Option<Positive>>(heads)?
84
- .into_iter()
85
- .map(|head| head.map(|Positive(cost)| cost))
86
- .collect();
87
- Ok(rb_self.core.borrow_mut().select(&heads))
126
+ let heads = crate::heads(heads)?;
127
+ let answer = this.0.borrow_mut().select(&heads);
128
+ Ok(match answer {
129
+ Ok(tenant) => tenant.map(|tenant| ruby.integer_from_u64(tenant as u64).as_value()),
130
+ Err(refused) => Some(refusal(ruby, refused)),
131
+ })
132
+ }
133
+
134
+ fn tenant_count(&self) -> usize {
135
+ self.0.borrow().tenant_count()
136
+ }
137
+
138
+ fn in_flight(&self, tenant: Value) -> Result<Option<u32>, Error> {
139
+ Ok(self.0.borrow().in_flight(integer(tenant, "tenant")?))
88
140
  }
89
141
 
90
- const fn tenant_count(&self) -> usize {
91
- self.count
142
+ fn available(&self, tenant: Value) -> Result<Option<u32>, Error> {
143
+ Ok(self.0.borrow().available(integer(tenant, "tenant")?))
92
144
  }
93
145
  }
94
146
 
95
147
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
96
148
  let class = module.define_class("TenantFair", ruby.class_object())?;
97
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
98
- class.define_method("admit", method!(Wrapper::admit, -1))?;
99
- class.define_method("cancel", method!(Wrapper::cancel, -1))?;
149
+ class.undef_default_alloc_func();
150
+ class.const_set("MAX_TENANTS", MAX_TENANTS)?;
151
+ class.define_singleton_method("new", function!(Wrapper::new, 2))?;
152
+ class.define_method("admit", method!(Wrapper::admit, 2))?;
153
+ class.define_method("cancel", method!(Wrapper::cancel, 2))?;
100
154
  class.define_method("select", method!(Wrapper::select, 1))?;
101
- class.define_method("tenant_count", method!(Wrapper::tenant_count, 0))
155
+ class.define_method("tenant_count", method!(Wrapper::tenant_count, 0))?;
156
+ class.define_method("in_flight", method!(Wrapper::in_flight, 1))?;
157
+ class.define_method("available", method!(Wrapper::available, 1))?;
158
+ // `new` answers a TenantFair: its class is fixed now, so building one
159
+ // never runs `Object.const_get`.
160
+ Class::pin_wrapped::<Wrapper>(ruby, class).map(drop)
102
161
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FairMachines
4
- VERSION = '0.1.5'
4
+ VERSION = '0.6.1'
5
5
  end