Struct UpgradeChoices

Source
pub struct UpgradeChoices<const N: usize, const K: usize> { /* private fields */ }
Expand description

Optional bounded owner of ranks, earned points and one active choice set.

No Clone/Copy, mutable rank access, callbacks, event queue or storage I/O. Acceptance commits solely owned state under &mut self; it is not an external transaction. Snapshots and Self::upgrades are observations. The host owns award authority/deduplication: credit only a newly accepted award’s promotions, never preview/restore/replayed reports. Check balance capacity before committing an external award, or retain an explicit owed award if credit fails; this adapter cannot roll back external progression.

Storage is O(N + K) with 1 <= N <= 256 and 0 <= K <= N. Operations allocate nothing. Opening delegates to the existing Upgrades::offers (at most N eligibility visits and K draws); it adds no weighted algorithm. Caller-supplied RNG, clocks and event IDs remain outside the session.

use ferravex_play::gameplay::{
    loot::RewardRng,
    upgrades::{UpgradeChoices, UpgradeChoiceError, Upgrades},
};
let mut choices = UpgradeChoices::<3, 2>::new(Upgrades::new([2, 1, 1]).unwrap(), 7)
    .unwrap();
let mut rng = RewardRng::new(42);
assert_eq!(choices.open(&mut rng).unwrap(), None); // No earned point.
assert_eq!(choices.credit(2).unwrap(), 2); // Host accepted a new award.
let offer = choices.open(&mut rng).unwrap().unwrap();
assert_eq!(choices.pending(), Some(&offer));
assert_eq!(choices.open(&mut rng).unwrap(), Some(offer)); // Redraw, no RNG.
assert_eq!((offer.id().namespace(), offer.id().serial()), (7, 1));
let id = offer.choices()[0].unwrap();
let accepted = choices.choose(offer.id(), id).unwrap();
assert_eq!((accepted.rank_before, accepted.rank_after), (0, 1));
assert_eq!((accepted.points_before, accepted.points_after), (2, 1));
assert_eq!(choices.upgrades().rank(id), Some(1));
assert_eq!(choices.choose(offer.id(), id), Err(UpgradeChoiceError::StaleOffer));
let next = choices.open(&mut rng).unwrap().unwrap();
assert_eq!(choices.abandon(), Some(next)); // Point retained, serial consumed.
let pending = choices.open(&mut rng).unwrap().unwrap();
let reset = choices.reset();
assert_eq!((reset.discarded_points, reset.pending), (1, Some(pending)));
assert_eq!((choices.points(), choices.upgrades().rank(id)), (0, Some(0)));
choices.credit(1).unwrap();
let fresh = choices.open(&mut rng).unwrap().unwrap();
assert!(fresh.id().serial() > pending.id().serial());
assert_eq!(choices.choose(pending.id(), id), Err(UpgradeChoiceError::StaleOffer));

Implementations§

Source§

impl<const N: usize, const K: usize> UpgradeChoices<N, K>

Source

pub fn new( upgrades: Upgrades<N>, namespace: u64, ) -> Result<UpgradeChoices<N, K>, UpgradeChoiceError>

Own an existing valid rank set with zero points and serial 1 next.

Validate N, caps/ranks, K, and a nonzero namespace before construction. A namespace must be fresh relative to any surviving callbacks from other sessions. Reusing it is safe only after all old tokens are unreachable. No global registry, authenticated token or save/replay format is implied.

Source

pub fn upgrades(&self) -> &Upgrades<N>

Observe ranks; no mutable reference or live ownership copy is exposed.

Source

pub fn points(&self) -> u32

Unspent explicitly credited points.

Source

pub fn pending(&self) -> Option<&UpgradeOffer<K>>

Inspect the existing offer without touching RNG or balance.

Source

pub fn credit(&mut self, points: u32) -> Result<u32, UpgradeChoiceError>

Explicit checked earned-point credit, returning the new total.

Zero is a no-op; overflow changes nothing, including the offer. There is no award deduplication: repeated successful credits intentionally add again. Authority, replay/rollback consistency and event identity belong to the caller. Credit never rerolls or replaces a pending offer.

Source

pub fn open( &mut self, rng: &mut RewardRng, ) -> Result<Option<UpgradeOffer<K>>, UpgradeChoiceError>

Return the cached offer or generate one using Upgrades::offers.

Exact order: cached offer first; then zero points, K == 0 or all ranks capped return Ok(None); then check serial exhaustion; then select and publish. Every earlier return consumes zero RNG outputs and no serial. A new offer consumes exactly min(K, eligible_count) existing RNG outputs (including a sole eligible choice), and exactly one serial. Short offers have trailing None; empty offers are never published. Errors leave RNG and session intact. Constructor rejection of K > N occurs before any RNG can be supplied. Redraws must retain this offer; explicit Self::abandon permits a new draw on the next open.

Source

pub fn choose( &mut self, offer: UpgradeOfferId, upgrade: usize, ) -> Result<AcceptedUpgrade, UpgradeChoiceError>

Accept an offered upgrade, spending one point and adding one rank.

Check identity (including no offer), point balance, membership, then cap, in that order. Every rejection changes nothing. On acceptance the entire offer is consumed, even with points/other choices left. Repeated clicks, keypresses and delayed callbacks must submit the original token; they then fail stale, even after a new offer opens. No implicit next draw. Owned ranks cannot concurrently change through the public session API.

Source

pub fn abandon(&mut self) -> Option<UpgradeOffer<K>>

Explicitly abandon the offer, returning it for host cleanup.

No point is spent/refunded and the serial is never rewound. Any later open is a deliberate new draw; old callbacks are stale.

Source

pub fn reset(&mut self) -> UpgradeReset<K>

Reset all ranks and points, returning discarded points and pending offer.

Retains caps, namespace and monotonic serial state, including exhaustion. It neither resets the caller’s RNG nor credits a reward. A deterministic restart reseeds the caller RNG separately; reproduced choices still get fresh serials. Recreate with a fresh namespace to recover from exhaustion.

Trait Implementations§

Source§

impl<const N: usize, const K: usize> Debug for UpgradeChoices<N, K>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<const N: usize, const K: usize> Freeze for UpgradeChoices<N, K>

§

impl<const N: usize, const K: usize> RefUnwindSafe for UpgradeChoices<N, K>

§

impl<const N: usize, const K: usize> Send for UpgradeChoices<N, K>

§

impl<const N: usize, const K: usize> Sync for UpgradeChoices<N, K>

§

impl<const N: usize, const K: usize> Unpin for UpgradeChoices<N, K>

§

impl<const N: usize, const K: usize> UnwindSafe for UpgradeChoices<N, K>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.