pub const SPRINT_UUID: u128 = 0x662a6b8d_da3e_4c1c_8813_96ea6097278d;
pub const SPRINT_AMOUNT: f64 = 0.3f32 as f64;
const CAPACITY: usize = 8;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Modifier {
pub uuid: u128,
pub amount: f64,
pub operation: u8,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Modifiers {
list: [Modifier; CAPACITY],
len: usize,
}
#[inline]
fn uuid_hash(u: u128) -> i32 {
let hilo = ((u >> 64) as u64) ^ (u as u64);
((hilo >> 32) as i32) ^ (hilo as i32)
}
#[inline]
fn bucket(h: i32) -> u32 {
let h = h as u32;
(h ^ (h >> 16)) & 15
}
impl Modifiers {
pub const NONE: Modifiers = Modifiers {
list: [Modifier {
uuid: 0,
amount: 0.0,
operation: 0,
}; CAPACITY],
len: 0,
};
#[must_use]
pub fn as_slice(&self) -> &[Modifier] {
&self.list[..self.len]
}
pub fn clear(&mut self) {
self.len = 0;
}
pub fn insert(&mut self, uuid: u128, amount: f64, operation: u8) {
self.remove(uuid);
if self.len < CAPACITY {
self.list[self.len] = Modifier {
uuid,
amount,
operation,
};
self.len += 1;
}
}
pub fn push(&mut self, amount: f64, operation: u8) {
if self.len < CAPACITY {
self.list[self.len] = Modifier {
uuid: 0,
amount,
operation,
};
self.len += 1;
}
}
pub fn remove(&mut self, uuid: u128) -> bool {
let Some(i) = self.as_slice().iter().position(|m| m.uuid == uuid) else {
return false;
};
self.list.copy_within(i + 1..self.len, i);
self.len -= 1;
true
}
#[must_use]
pub fn contains(&self, uuid: u128) -> bool {
self.as_slice().iter().any(|m| m.uuid == uuid)
}
pub fn set_sprint(&mut self, sprinting: bool) {
self.remove(SPRINT_UUID);
if sprinting {
self.insert(SPRINT_UUID, SPRINT_AMOUNT, 2);
}
}
fn ordered(&self, operation: u8) -> impl Iterator<Item = &Modifier> {
let mut idx: [usize; CAPACITY] = [0; CAPACITY];
let mut n = 0;
for (i, m) in self.as_slice().iter().enumerate() {
if m.operation == operation {
idx[n] = i;
n += 1;
}
}
idx[..n].sort_by_key(|&i| bucket(uuid_hash(self.list[i].uuid)));
(0..n).map(move |k| &self.list[idx[k]])
}
#[must_use]
pub fn value(&self, base: f64) -> f64 {
let mut d = base;
for m in self.ordered(0) {
d += m.amount;
}
let mut e = d;
for m in self.ordered(1) {
e += d * m.amount;
}
for m in self.ordered(2) {
e *= 1.0 + m.amount;
}
e.clamp(0.0, 1024.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn java_uuid_hash() {
let hilo: u64 = 0x662a_6b8d_da3e_4c1c ^ 0x8813_96ea_6097_278d;
assert_eq!(
uuid_hash(SPRINT_UUID),
((hilo >> 32) as i32) ^ (hilo as i32)
);
}
#[test]
fn sprint_toggle() {
let mut m = Modifiers::NONE;
m.set_sprint(true);
assert_eq!(m.value(0.1), 0.1 * (1.0 + SPRINT_AMOUNT));
m.set_sprint(false);
assert_eq!(m.value(0.1), 0.1);
}
}