Skip to content

Utilities

Teodor Đurić edited this page Dec 18, 2022 · 6 revisions

Helpers

constants

  • EULER_NUMBER: f64 = 2.71828

functions

modulo

pub fn modulo(num: u128, divisor: u128) -> usize

  • This function requires divisor to be a power of 2.
  • Takes a number num, does some bit twiddling, and returns the remainder as a usize.
  • The computation exploits the fact that a remainder operation can be performed using only a bit-wise AND if the divisor is a power of 2. This is due to the fact that integer division (essentially repeated subtraction), will only affect bits bigger than the divisor i.e. bits at and to the left of the set bit in divisor and what remains is the bits to the right of it.
  • The calculation of the remainder r can be described using the formula: $$\Huge{r = n \wedge(d-1) }$$ Animation of what the formula is actually doing: animation of the formula

closest_pow

pub fn closest_pow(n: u64) -> u64

  • Takes a number n, does some bit twiddling, and returns c, the nearest power of 2 to n, such that c >= n.
  • The return value, c, is calculated by finding the most significant bit that is set to 1, then a 1 is shifted into the spot left of that bit. In the case where n is a power of 2, to avoid branching, the 1 is shifted one time less, resulting in the same number as n.
  • The calculation can be described using the formulae:

$$\large{\text{$l$ - the number of leading zeros in the binary representation of $n$}}$$

$$\Huge{p = \begin{cases} 1, & \text{if $n$ is a power of 2} \\ 0, & \text{if $n$ is not a power of 2} \end{cases}}$$

$$\Huge{c = 1 << (64 - l - p)}$$

load_seeds

pub fn load_seeds(filename: &str) -> Option<Vec<u32>>

  • Takes a filename and returns a vector of the seeds inside the file wrapped in an Option

write_seeds

pub fn write_seeds(seeds: &Vec<u32>, filename: &str) -> ()

  • Takes an immutable reference to a vector of seeds and writes them to a file determined by filename.

Clone this wiki locally