1use super::{LoopError, seconds};
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct ScoreAward {
39 pub base: u32,
41 pub tier: u32,
43 pub multiplier: u32,
45 pub chain: u32,
47 pub nominal_points: u64,
49 pub total_change: u64,
51 pub total_before: u64,
53 pub total_after: u64,
55 pub chain_saturated: bool,
57 pub total_saturated: bool,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub struct ScoreOverflow {
65 pub chain: bool,
67 pub total: bool,
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum ChainAdvance {
75 Idle,
77 Active,
79 Expired { chain: u32 },
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum ChainReset {
87 ChainOnly,
89 Run,
91 All,
93}
94
95#[derive(Clone, Copy, Debug)]
100pub struct ScoreChain {
101 window: f64,
102 remaining: f64,
103 chain: u32,
104 per_tier: u32,
105 maximum: u32,
106 total: u64,
107 best: u32,
108}
109impl ScoreChain {
110 pub fn new(window: f32, per_tier: u32, maximum: u32) -> Result<Self, LoopError> {
111 let window = seconds(window)?;
112 if window == 0. || per_tier == 0 || maximum == 0 || maximum > 100 {
113 return Err(LoopError::Invalid);
114 }
115 Ok(Self {
116 window,
117 remaining: 0.,
118 chain: 0,
119 per_tier,
120 maximum,
121 total: 0,
122 best: 0,
123 })
124 }
125 pub fn advance(&mut self, dt: f32) -> Result<(), LoopError> {
126 self.advance_with_outcome(dt).map(|_| ())
127 }
128 pub fn advance_with_outcome(&mut self, dt: f32) -> Result<ChainAdvance, LoopError> {
134 let dt = seconds(dt)?;
135 let chain = self.chain;
136 self.remaining = (self.remaining - dt).max(0.);
137 if self.remaining <= 1e-9 {
138 self.break_chain();
139 return Ok(if chain == 0 {
140 ChainAdvance::Idle
141 } else {
142 ChainAdvance::Expired { chain }
143 });
144 }
145 Ok(ChainAdvance::Active)
146 }
147 pub fn award(&mut self, base: u32) -> u64 {
150 self.award_with_receipt(base)
151 .map_or(0, |award| award.nominal_points)
152 }
153 pub fn preview_award(&self, base: u32) -> Option<ScoreAward> {
159 if base == 0 {
160 return None;
161 }
162 let chain = self.chain.saturating_add(1);
163 let tier = 1 + chain.saturating_sub(1) / self.per_tier;
164 let multiplier = tier.min(self.maximum);
165 let nominal_points = u64::from(base) * u64::from(multiplier);
166 let total_after = self.total.saturating_add(nominal_points);
167 Some(ScoreAward {
168 base,
169 tier,
170 multiplier,
171 chain,
172 nominal_points,
173 total_change: total_after - self.total,
174 total_before: self.total,
175 total_after,
176 chain_saturated: self.chain == u32::MAX,
177 total_saturated: self.total.checked_add(nominal_points).is_none(),
178 })
179 }
180 pub fn award_with_receipt(&mut self, base: u32) -> Option<ScoreAward> {
189 let award = self.preview_award(base)?;
190 self.apply_award(award);
191 Some(award)
192 }
193 pub fn try_award(&mut self, base: u32) -> Result<Option<ScoreAward>, ScoreOverflow> {
202 let Some(award) = self.preview_award(base) else {
203 return Ok(None);
204 };
205 if award.chain_saturated || award.total_saturated {
206 return Err(ScoreOverflow {
207 chain: award.chain_saturated,
208 total: award.total_saturated,
209 });
210 }
211 self.apply_award(award);
212 Ok(Some(award))
213 }
214 fn apply_award(&mut self, award: ScoreAward) {
215 self.chain = award.chain;
216 self.best = self.best.max(self.chain);
217 self.remaining = self.window;
218 self.total = award.total_after;
219 }
220 pub fn multiplier(&self) -> u32 {
221 (1 + self.chain.saturating_sub(1) / self.per_tier).min(self.maximum)
222 }
223 pub fn chain(&self) -> u32 {
224 self.chain
225 }
226 pub fn best(&self) -> u32 {
227 self.best
228 }
229 pub fn total(&self) -> u64 {
230 self.total
231 }
232 pub fn remaining_life(&self) -> Option<f64> {
236 (self.chain != 0).then_some(self.remaining)
237 }
238 pub fn reset(&mut self, mode: ChainReset) {
241 self.chain = 0;
242 self.remaining = 0.;
243 if mode != ChainReset::ChainOnly {
244 self.total = 0;
245 }
246 if mode == ChainReset::All {
247 self.best = 0;
248 }
249 }
250 pub fn break_chain(&mut self) {
252 self.reset(ChainReset::ChainOnly);
253 }
254}
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 fn state(c: &ScoreChain) -> (f64, f64, u32, u32, u32, u64, u32) {
260 (
261 c.window,
262 c.remaining,
263 c.chain,
264 c.per_tier,
265 c.maximum,
266 c.total,
267 c.best,
268 )
269 }
270
271 #[test]
272 fn actions_build_capped_multipliers_and_timeout_preserves_total() {
273 let mut c = ScoreChain::new(2., 2, 3).unwrap();
274 let awards: Vec<_> = (0..7).map(|_| c.award(100)).collect();
275 assert_eq!(awards, [100, 100, 200, 200, 300, 300, 300]);
276 assert_eq!(c.total(), 1500);
277 c.advance(1.).unwrap();
278 c.award(0);
279 c.advance(1.).unwrap();
280 assert_eq!((c.chain(), c.best(), c.multiplier()), (0, 7, 1));
281 assert_eq!(c.award(100), 100);
282 assert!(c.advance(-1.).is_err());
283 assert_eq!(c.chain(), 1);
284 }
285
286 #[test]
287 fn receipts_follow_post_action_tiers_and_cap_without_preview_mutation() {
288 let mut c = ScoreChain::new(2., 2, 3).unwrap();
289 for (i, multiplier) in [1, 1, 2, 2, 3, 3, 3, 3, 3].into_iter().enumerate() {
290 let before = state(&c);
291 let preview = c.preview_award(100).unwrap();
292 assert_eq!(state(&c), before);
293 assert_eq!(preview.base, 100);
294 assert_eq!(preview.chain, i as u32 + 1);
295 assert_eq!(preview.tier, 1 + i as u32 / 2);
296 assert_eq!(preview.multiplier, multiplier);
297 assert_eq!(preview.nominal_points, 100 * u64::from(multiplier));
298 assert_eq!(preview.total_change, preview.nominal_points);
299 assert_eq!(preview.total_before, before.5);
300 assert_eq!(preview.total_after, before.5 + preview.nominal_points);
301 assert!(!preview.chain_saturated && !preview.total_saturated);
302 assert_eq!(c.try_award(100), Ok(Some(preview)));
303 assert_eq!(c.total(), preview.total_after);
304 assert_eq!(c.multiplier(), multiplier);
305 assert_eq!(c.best(), preview.chain);
306 assert_eq!(c.remaining_life(), Some(2.));
307 }
308 let mut widest = ScoreChain::new(3600., u32::MAX, 100).unwrap();
310 widest.chain = u32::MAX - 1;
311 let last = widest.try_award(u32::MAX).unwrap().unwrap();
312 assert_eq!((last.chain, last.tier, last.multiplier), (u32::MAX, 1, 1));
313 assert!(!last.chain_saturated);
314 for (window, per_tier, maximum) in [
315 (0., 1, 1),
316 (1., 0, 1),
317 (1., 1, 0),
318 (1., 1, 101),
319 (f32::NAN, 1, 1),
320 ] {
321 assert!(matches!(
322 ScoreChain::new(window, per_tier, maximum),
323 Err(LoopError::Invalid)
324 ));
325 }
326 }
327
328 #[test]
329 fn zero_and_inspection_never_refresh_even_at_counter_bounds() {
330 for bounded in [false, true] {
331 let mut c = ScoreChain::new(0.125, 1, 100).unwrap();
332 c.award(1);
333 c.advance(0.03125).unwrap();
334 if bounded {
335 c.chain = u32::MAX;
336 c.best = u32::MAX;
337 c.total = u64::MAX;
338 }
339 let before = state(&c);
340 for _ in 0..3 {
341 assert_eq!(c.preview_award(0), None);
342 assert_eq!(c.award_with_receipt(0), None);
343 assert_eq!(c.try_award(0), Ok(None));
344 assert_eq!(c.award(0), 0);
345 assert_eq!(c.remaining_life(), Some(0.09375));
346 let _ = (
347 c.preview_award(1),
348 c.multiplier(),
349 c.chain(),
350 c.total(),
351 c.best(),
352 );
353 assert_eq!(state(&c), before);
354 }
355 assert_eq!(
356 c.advance_with_outcome(0.09375),
357 Ok(ChainAdvance::Expired { chain: before.2 })
358 );
359 assert_eq!((c.total(), c.best()), (before.5, before.6));
360 assert_eq!(c.remaining_life(), None);
361 assert_eq!(c.advance_with_outcome(0.), Ok(ChainAdvance::Idle));
362 }
363 }
364
365 #[test]
366 fn expiry_is_inclusive_at_exact_epsilon_and_f32_neighbors() {
367 let below = 1e-9_f32;
368 let above = f32::from_bits(below.to_bits() + 1);
369 assert!(f64::from(below) < 1e-9);
370 assert!(f64::from(above) > 1e-9);
371 for window in [f32::from_bits(1), below] {
372 let mut c = ScoreChain::new(window, 2, 3).unwrap();
373 c.award(1);
374 assert_eq!(c.remaining_life(), Some(f64::from(window)));
375 assert_eq!(c.chain(), 1); assert_eq!(
377 c.advance_with_outcome(0.),
378 Ok(ChainAdvance::Expired { chain: 1 })
379 );
380 }
381 let mut c = ScoreChain::new(above, 2, 3).unwrap();
382 c.award(1);
383 assert_eq!(c.advance_with_outcome(0.), Ok(ChainAdvance::Active));
384 assert_eq!(
385 c.advance_with_outcome(below),
386 Ok(ChainAdvance::Expired { chain: 1 })
387 );
388 c.award(1);
389 c.remaining = 1e-9;
391 let before = state(&c);
392 assert_eq!(c.remaining_life(), Some(1e-9));
393 c.preview_award(1).unwrap();
394 assert_eq!(state(&c), before);
395 assert_eq!(
396 c.advance_with_outcome(-0.),
397 Ok(ChainAdvance::Expired { chain: 1 })
398 );
399 c.award(1);
400 c.remaining = f64::from_bits(1e-9_f64.to_bits() + 1);
401 assert_eq!(c.advance_with_outcome(0.), Ok(ChainAdvance::Active));
402 assert_eq!(
403 c.advance_with_outcome(3600.),
404 Ok(ChainAdvance::Expired { chain: 1 })
405 );
406 assert_eq!(c.advance_with_outcome(3600.), Ok(ChainAdvance::Idle));
407 }
408
409 #[test]
410 fn invalid_delta_leaves_every_field_unchanged_active_or_idle() {
411 let mut c = ScoreChain::new(3600., 3, 4).unwrap();
412 for active in [false, true] {
413 if active {
414 c.award(100);
415 c.advance(0.25).unwrap();
416 }
417 let before = state(&c);
418 for dt in [
419 f32::NAN,
420 f32::INFINITY,
421 f32::NEG_INFINITY,
422 -0.001,
423 f32::from_bits(3600_f32.to_bits() + 1),
424 ] {
425 assert_eq!(c.advance_with_outcome(dt), Err(LoopError::Invalid));
426 assert_eq!(state(&c), before);
427 assert_eq!(c.advance(dt), Err(LoopError::Invalid));
428 assert_eq!(state(&c), before);
429 }
430 }
431 }
432
433 #[test]
434 fn total_boundary_distinguishes_exact_fit_rejection_and_explicit_saturation() {
435 let mut c = ScoreChain::new(2., 1, 100).unwrap();
436 c.chain = 99;
437 c.best = 99;
438 let nominal = u64::from(u32::MAX) * 100;
439 c.total = u64::MAX - nominal;
440 let exact = c.try_award(u32::MAX).unwrap().unwrap();
441 assert_eq!((exact.tier, exact.multiplier), (100, 100));
442 assert_eq!(
443 (exact.nominal_points, exact.total_change),
444 (nominal, nominal)
445 );
446 assert_eq!(exact.total_after, u64::MAX);
447 assert!(!exact.total_saturated);
448
449 c.advance(1.).unwrap();
451 let before = state(&c);
452 assert_eq!(
453 c.try_award(1),
454 Err(ScoreOverflow {
455 chain: false,
456 total: true
457 })
458 );
459 assert_eq!(state(&c), before);
460 let receipt = c.award_with_receipt(1).unwrap();
461 assert_eq!((receipt.nominal_points, receipt.total_change), (100, 0));
462 assert!(receipt.total_saturated && !receipt.chain_saturated);
463 assert_eq!(
464 (c.chain(), c.best(), c.remaining_life()),
465 (101, 101, Some(2.))
466 );
467
468 c.total = u64::MAX - 25;
469 let before = state(&c);
470 let preview = c.preview_award(u32::MAX).unwrap();
471 assert_eq!(state(&c), before);
472 assert_eq!(
473 c.try_award(u32::MAX),
474 Err(ScoreOverflow {
475 chain: false,
476 total: true
477 })
478 );
479 assert_eq!(state(&c), before);
480 assert_eq!(c.award_with_receipt(u32::MAX), Some(preview));
481 assert_eq!(
482 (preview.nominal_points, preview.total_change),
483 (nominal, 25)
484 );
485 assert!(preview.total_saturated);
486 }
487
488 #[test]
489 fn chain_boundary_and_simultaneous_overflows_are_explicit_and_atomic() {
490 let mut c = ScoreChain::new(2., 1, 100).unwrap();
491 c.chain = u32::MAX - 1;
492 c.best = u32::MAX - 1;
493 let exact = c.try_award(1).unwrap().unwrap();
494 assert_eq!(
495 (exact.chain, exact.tier, exact.multiplier),
496 (u32::MAX, u32::MAX, 100)
497 );
498 assert!(!exact.chain_saturated);
499 c.advance(1.).unwrap();
500 for (total, total_overflow) in [(c.total(), false), (u64::MAX, true)] {
501 c.total = total;
502 let before = state(&c);
503 let preview = c.preview_award(1).unwrap();
504 assert_eq!(state(&c), before);
505 assert_eq!(
506 c.try_award(1),
507 Err(ScoreOverflow {
508 chain: true,
509 total: total_overflow
510 })
511 );
512 assert_eq!(state(&c), before);
513 assert_eq!(c.award_with_receipt(1), Some(preview));
514 assert!(preview.chain_saturated);
515 assert_eq!(preview.total_saturated, total_overflow);
516 assert_eq!(preview.total_change, if total_overflow { 0 } else { 100 });
517 assert_eq!(
518 (c.chain(), c.best(), c.remaining_life()),
519 (u32::MAX, u32::MAX, Some(2.))
520 );
521 }
522 }
523
524 #[test]
525 fn each_reset_mode_is_idempotent_and_retains_authoring_configuration() {
526 let mut initial = ScoreChain::new(0.125, 2, 3).unwrap();
527 for _ in 0..9 {
528 initial.award(10);
529 }
530 initial.advance(0.03125).unwrap();
531 for (mode, total, best) in [
532 (ChainReset::ChainOnly, initial.total(), 9),
533 (ChainReset::Run, 0, 9),
534 (ChainReset::All, 0, 0),
535 ] {
536 let mut c = initial;
537 for _ in 0..2 {
538 c.reset(mode);
539 assert_eq!(state(&c), (0.125, 0., 0, 2, 3, total, best));
540 assert_eq!(c.multiplier(), 1);
541 assert_eq!(c.remaining_life(), None);
542 assert_eq!(c.advance_with_outcome(0.), Ok(ChainAdvance::Idle));
543 }
544 let receipts: Vec<_> = (0..7).map(|_| c.award_with_receipt(10).unwrap()).collect();
545 assert_eq!(
546 receipts.iter().map(|r| r.multiplier).collect::<Vec<_>>(),
547 [1, 1, 2, 2, 3, 3, 3]
548 );
549 assert_eq!(c.remaining_life(), Some(0.125));
550 assert_eq!(c.total(), total + 150);
551 assert_eq!(c.best(), best.max(7));
552 }
553 let mut broken = initial;
554 broken.break_chain();
555 initial.reset(ChainReset::ChainOnly);
556 assert_eq!(state(&broken), state(&initial));
557 }
558
559 #[test]
560 fn legacy_wrappers_match_original_policy_and_receipt_path_in_all_fields() {
561 fn original_award(c: &mut ScoreChain, base: u32) -> u64 {
563 if base == 0 {
564 return 0;
565 }
566 c.chain = c.chain.saturating_add(1);
567 c.best = c.best.max(c.chain);
568 c.remaining = c.window;
569 let multiplier = (1 + c.chain.saturating_sub(1) / c.per_tier).min(c.maximum);
570 let points = u64::from(base) * u64::from(multiplier);
571 c.total = c.total.saturating_add(points);
572 points
573 }
574 for (chain, total) in [(0, 0), (u32::MAX - 1, u64::MAX - 1), (u32::MAX, u64::MAX)] {
575 let mut seed = ScoreChain::new(0.125, 2, 3).unwrap();
576 seed.chain = chain;
577 seed.best = chain;
578 seed.total = total;
579 for base in [0, 100, 100, u32::MAX, 0, 1, 10, 100] {
580 let mut original = seed;
581 let mut legacy = seed;
582 let mut receipt = seed;
583 let expected = original_award(&mut original, base);
584 assert_eq!(legacy.award(base), expected);
585 assert_eq!(
586 receipt
587 .award_with_receipt(base)
588 .map_or(0, |r| r.nominal_points),
589 expected
590 );
591 assert_eq!(state(&legacy), state(&original));
592 assert_eq!(state(&receipt), state(&original));
593 for dt in [0., 0.03125, 0.09375, 1e-9_f32, 3600.] {
594 original.remaining = (original.remaining - f64::from(dt)).max(0.);
595 if original.remaining <= 1e-9 {
596 original.chain = 0;
597 original.remaining = 0.;
598 }
599 assert_eq!(legacy.advance(dt), Ok(()));
600 receipt.advance_with_outcome(dt).unwrap();
601 assert_eq!(state(&legacy), state(&original));
602 assert_eq!(state(&receipt), state(&original));
603 }
604 }
605 }
606 }
607}