Generating UUID4 from custom random number generator (RNG) using rust

First you need to generate random seed:
It can be from any RNG generator, for example in near protocol sdk, 

pub fn random_seed() -> Vec<u8>
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();

    
    let mut randvec:Vec<u8> = Vec::new();
    let mut counter = 0;
    let result = loop {
        counter += 1;
        let n1: u8 = rng.gen();
        randvec.push(n1);

        if counter == 32 {
            break randvec;
        }
    };
    println!("{:?}", result);
}
Its generate vector, but you need an array to feed into from_seed function.

This is the complete code.
use rand::{rngs::StdRng, RngCore, SeedableRng, Rng};
use uuid::{Builder, Variant, Version};

fn main() {
    let mut rng = rand::thread_rng();

    
    let mut randvec:Vec<u8> = Vec::new();
    let mut counter = 0;
    let result_vec = loop {
        counter += 1;
        let n1: u8 = rng.gen();
        randvec.push(n1);

        if counter == 32 {
            break randvec;
        }
    };
    println!("{:?}", result_vec);
    
    // convert vector seed to array seed
    let mut seed = [0u8; 32];
    let mut counter = 0;
    for v in result_vec.iter() {
        seed[counter] = *v;
        counter += 1;

    }

    println!("{:?}", seed);
    // feed the array seed
    let mut rng: StdRng = SeedableRng::from_seed(seed);
    let mut bytes = [0u8; 16];
    rng.fill_bytes(&mut bytes);
    let uuid = Builder::from_bytes(bytes)
        .set_variant(Variant::RFC4122)
        .set_version(Version::Random)
        .build();
    println!("{:?}", uuid);
}
Output
[181, 127, 162, 178, 55, 217, 237, 166, 94, 82, 24, 25, 232, 11, 245, 41, 217, 227, 197, 179, 230, 106, 189, 82, 8, 177, 146, 76, 183, 228, 96, 76]
[181, 127, 162, 178, 55, 217, 237, 166, 94, 82, 24, 25, 232, 11, 245, 41, 217, 227, 197, 179, 230, 106, 189, 82, 8, 177, 146, 76, 183, 228, 96, 76]
e2f0388b-7abc-446d-aed8-df18d499ab17

Comments

Popular posts from this blog

App with fastapi, Arangodb and Graphql

Auto Cross covariance Python