Skip to content

Commit

Permalink
Add simple xor shifter.
Browse files Browse the repository at this point in the history
  • Loading branch information
q-uint committed Nov 19, 2021
1 parent fb5cff6 commit a2e8928
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ let (v, _) = feed.next();
// Iter
let iter = LFSR.toIter(feed);
```
## XorShift

Reference: [prng](https://vigna.di.unimi.it/ftp/papers/xorshift.pdf).
9 changes: 4 additions & 5 deletions src/LFSR.mo
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import Array "mo:base/Array";
import Int "mo:base/Int";
import IO "mo:io/IO";
import Iter "mo:base/Iter";
import Nat8 "mo:base/Nat8";
import Nat16 "mo:base/Nat16";
import Nat32 "mo:base/Nat32";
import Nat64 "mo:base/Nat64";
import Time "mo:base/Time";

import IO "mo:io/IO";

module {
public type LFSR<T> = {
next() : (T, Bool);
Expand All @@ -17,7 +16,7 @@ module {
// An 8-bit linear feedback shift register.
public class LFSR8(
s : ?Nat8, // Seed.
) {
) : LFSR<Nat8> {
private let seed : Nat8 = switch (s) {
case (null) { nat8(Int.abs(Time.now())); };
case (? s) { s; };
Expand All @@ -39,7 +38,7 @@ module {
// An 16-bit linear feedback shift register.
public class LFSR16(
s : ?Nat16, // Seed.
) {
) : LFSR<Nat16> {
private let seed : Nat16 = switch (s) {
case (null) { nat16(Int.abs(Time.now())); };
case (? s) { s; };
Expand All @@ -61,7 +60,7 @@ module {
// An 32-bit linear feedback shift register.
public class LFSR32(
s : ?Nat32, // Seed.
) {
) : LFSR<Nat32> {
private let seed : Nat32 = switch (s) {
case (null) { nat32(Int.abs(Time.now())); };
case (? s) { s; };
Expand Down
27 changes: 27 additions & 0 deletions src/XorShift.mo
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Int "mo:base/Int";
import IO "mo:io/IO";
import Nat64 "mo:base/Nat64";
import Time "mo:base/Time";

module {
public type XorShift = {
next() : Nat64;
};

public class XorShift64(
s : ?Nat64,
) : XorShift {
private let seed : Nat64 = switch (s) {
case (null) Nat64.fromNat(Int.abs(Time.now()));
case (? s) s;
};
var state = seed;

public func next() : Nat64 {
state ^= (state >> 12);
state ^= (state << 25);
state ^= (state >> 27);
state * 2685821657736338717;
};
};
};

0 comments on commit a2e8928

Please sign in to comment.