Zig
Zig
Generating Repeatable Random Data for Testing/Debugging
See more PRNG Examples
Demonstrates how to use the Fortuna PRNG to generate random-looking but repeatable non-random data for the purpose of testing and debugging.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const fortuna = try chilkat.Prng.init();
defer fortuna.deinit();
// Normally an application would seed the PRNG with entropy from
// some real random source. However, sometimes we want the same
// random sequence of bytes for testing and debugging purposes.
// This a reason why GetEntropy and AddEntropy are two different methods.
// An application could omit the call to GetEntropy, and instead pass
// non-random data to AddEntropy. For example:
// Seed the PRNG with non-entropy, so we get a repeatable sequence.
// Note: AddEntropy can be called any number of times.
try fortuna.addEntropy("01020304", "hex");
try fortuna.addEntropy("hello world", "ascii");
// Generate some random data:
var str_rand_hex: [:0]const u8 = try fortuna.genRandom(alloc, 16, "hex");
var str_rand_base64: [:0]const u8 = try fortuna.genRandom(alloc, 22, "base64");
var str_rand_base58: [:0]const u8 = try fortuna.genRandom(alloc, 32, "base58");
std.debug.print("hex random bytes: {s}\n", .{str_rand_hex});
std.debug.print("base64 random bytes: {s}\n", .{str_rand_base64});
std.debug.print("base58 random bytes: {s}\n", .{str_rand_base58});
// Try it again with a different object to verify that the same results are obtained:
const fortuna2 = try chilkat.Prng.init();
defer fortuna2.deinit();
try fortuna2.addEntropy("01020304", "hex");
try fortuna2.addEntropy("hello world", "ascii");
str_rand_hex = try fortuna2.genRandom(alloc, 16, "hex");
str_rand_base64 = try fortuna2.genRandom(alloc, 22, "base64");
str_rand_base58 = try fortuna2.genRandom(alloc, 32, "base58");
std.debug.print("hex random bytes: {s}\n", .{str_rand_hex});
std.debug.print("base64 random bytes: {s}\n", .{str_rand_base64});
std.debug.print("base58 random bytes: {s}\n", .{str_rand_base58});
}