From 955abfeeab624ade79d695440bb73ada8b073bfc Mon Sep 17 00:00:00 2001 From: conrad Date: Wed, 5 Feb 2025 16:24:14 +1000 Subject: [PATCH] refactor to avoid using union --- include/armadillo_bits/arma_rng.hpp | 36 ++++++++++------------------- 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/include/armadillo_bits/arma_rng.hpp b/include/armadillo_bits/arma_rng.hpp index 186dda68..21857f7c 100644 --- a/include/armadillo_bits/arma_rng.hpp +++ b/include/armadillo_bits/arma_rng.hpp @@ -267,22 +267,14 @@ arma_rng::set_seed_random() { try { - // TODO: replace union-based conversion with method based on std::memcpy() or C++20 bit_cast - - union - { - seed_type a; - unsigned char b[sizeof(seed_type)]; - } tmp; - - tmp.a = seed_type(0); + char tmp[sizeof(seed_type)] = {}; std::ifstream f("/dev/urandom", std::ifstream::binary); - if(f.good()) { f.read((char*)(&(tmp.b[0])), sizeof(seed_type)); } + if(f.good()) { f.read(&(tmp[0]), sizeof(seed_type)); } + + if(f.good()) { std::memcpy(&seed2, &(tmp[0]), sizeof(seed_type)); } - if(f.good()) { seed2 = tmp.a; } - have_seed = (seed2 != seed_type(0)); } catch(...) {} @@ -299,21 +291,17 @@ arma_rng::set_seed_random() seed3 = static_cast( since_epoch_usec & 0xFFFF ); - // TODO: replace union-based conversion with method based on std::memcpy() or C++20 bit_cast + unsigned char* a = (unsigned char*)std::malloc(std::size_t(4096)); - union + unsigned char b[sizeof(unsigned char*)] = {}; + + if(a != nullptr) { - uword* a; - unsigned char b[sizeof(uword*)]; - } tmp; - - tmp.a = (uword*)malloc(sizeof(uword)); - - if(tmp.a != nullptr) - { - for(size_t i=0; i