xous-core/services/trng/src/lib.rs
bunnie 58edcc56f2 sha512 tests fully implemented, working through sus/res
note: sha512 will fail if a suspend is forced upon it!! but
it will vociferously complain if this happens.
2021-05-21 15:56:58 +08:00

52 lines
No EOL
1.8 KiB
Rust

#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use xous::{CID, send_message};
use num_traits::ToPrimitive;
#[derive(Debug)]
pub struct Trng {
conn: CID,
}
impl Trng {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
let conn = xns.request_connection_blocking(api::SERVER_NAME_TRNG).expect("Can't connect to TRNG server");
REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
Ok(Trng {
conn
})
}
pub fn get_u32(&self) -> Result<u32, xous::Error> {
let response = send_message(self.conn,
xous::Message::new_blocking_scalar(api::Opcode::GetTrng.to_usize().unwrap(),
1 /* count */, 0, 0, 0, )
).expect("TRNG|LIB: can't get_u32");
if let xous::Result::Scalar2(trng, _) = response {
Ok(trng as u32)
} else {
panic!("unexpected return value: {:#?}", response);
}
}
pub fn get_u64(&self) -> Result<u64, xous::Error> {
let response = send_message(self.conn,
xous::Message::new_blocking_scalar(api::Opcode::GetTrng.to_usize().unwrap(),
2 /* count */, 0, 0, 0, )
).expect("TRNG|LIB: can't get_u32");
if let xous::Result::Scalar2(lo, hi) = response {
Ok( lo as u64 | ((hi as u64) << 32) )
} else {
panic!("unexpected return value: {:#?}", response);
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Trng {
fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
if REFCOUNT.load(Ordering::Relaxed) == 0 {
unsafe{xous::disconnect(self.conn).unwrap();}
}
}
}