distributed_physics_test/src/game/seed.rs

68 lines
1.4 KiB
Rust

use std::{
array::TryFromSliceError,
hash::{DefaultHasher, Hash, Hasher},
};
use bevy::prelude::*;
use rand::random;
/// Value with which to initialize the PRNG
#[derive(Resource, Debug, Clone, Copy)]
pub struct Seed(u64);
impl Seed {
/// Use a random integer as the seed
pub fn random() -> Self {
Self(random())
}
}
impl From<String> for Seed {
/// Attempt to parse as an integer, fall back to hashing string
fn from(value: String) -> Self {
Self(value.parse::<u64>().unwrap_or_else(|_| {
let mut state = DefaultHasher::new();
value.hash(&mut state);
state.finish()
}))
}
}
impl From<Seed> for [u8; 8] {
fn from(value: Seed) -> Self {
value.0.to_le_bytes()
}
}
impl From<[u8; 8]> for Seed {
fn from(value: [u8; 8]) -> Self {
u64::from_le_bytes(value).into()
}
}
impl From<Seed> for u64 {
fn from(value: Seed) -> Self {
value.0
}
}
impl From<u64> for Seed {
fn from(value: u64) -> Self {
Seed(value)
}
}
impl From<Seed> for Vec<u8> {
fn from(value: Seed) -> Self {
value.0.to_le_bytes().to_vec()
}
}
impl TryFrom<Vec<u8>> for Seed {
type Error = TryFromSliceError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
let bytes: [u8; 8] = value.as_slice().try_into()?;
Ok(bytes.into())
}
}