use nectar_primitives::SwarmAddress;
#[cfg(feature = "std")]
#[inline]
pub fn current_timestamp() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
}
#[cfg(not(feature = "std"))]
#[inline]
pub const fn current_timestamp() -> u64 {
0
}
#[inline]
pub fn calculate_bucket(address: &SwarmAddress, bucket_depth: u8) -> u32 {
let leading = u32::from_be_bytes(address.as_bytes()[0..4].try_into().unwrap());
leading >> (32 - bucket_depth)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PostageContext {
block: u64,
total_amount: u128,
}
impl PostageContext {
#[inline]
pub const fn new(block: u64, total_amount: u128) -> Self {
Self {
block,
total_amount,
}
}
#[inline]
pub const fn block(&self) -> u64 {
self.block
}
#[inline]
pub const fn total_amount(&self) -> u128 {
self.total_amount
}
#[inline]
pub const fn set_block(&mut self, block: u64) {
self.block = block;
}
#[inline]
pub const fn set_total_amount(&mut self, total_amount: u128) {
self.total_amount = total_amount;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calculate_bucket() {
let address = SwarmAddress::new([
0xCB, 0xE5, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
]);
assert_eq!(calculate_bucket(&address, 16), 0xCBE5);
assert_eq!(calculate_bucket(&address, 8), 0xCB);
assert_eq!(calculate_bucket(&address, 4), 0xC);
}
#[test]
fn test_chain_state() {
let mut state = PostageContext::new(100, 5000);
assert_eq!(state.block(), 100);
assert_eq!(state.total_amount(), 5000);
state.set_block(200);
state.set_total_amount(10000);
assert_eq!(state.block(), 200);
assert_eq!(state.total_amount(), 10000);
}
#[test]
fn test_chain_state_default() {
let state = PostageContext::default();
assert_eq!(state.block(), 0);
assert_eq!(state.total_amount(), 0);
}
}