xous-core/services/trng/src/lib.rs

52 lines
1.8 KiB
Rust
Raw Normal View History

2021-01-13 07:04:14 +00:00
#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use xous::{CID, send_message};
2021-04-01 09:20:36 +00:00
use num_traits::ToPrimitive;
2021-01-13 07:04:14 +00:00
#[derive(Debug)]
2021-04-01 09:20:36 +00:00
pub struct Trng {
conn: CID,
2021-01-13 07:04:14 +00:00
}
2021-04-01 09:20:36 +00:00
impl Trng {
2021-04-03 18:17:14 +00:00
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
2021-04-01 09:20:36 +00:00
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);
2021-04-01 09:20:36 +00:00
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, )
2021-04-01 09:20:36 +00:00
).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, )
2021-04-01 09:20:36 +00:00
).expect("TRNG|LIB: can't get_u32");
2021-01-13 07:04:14 +00:00
if let xous::Result::Scalar2(lo, hi) = response {
2021-04-01 09:20:36 +00:00
Ok( lo as u64 | ((hi as u64) << 32) )
} else {
panic!("unexpected return value: {:#?}", response);
}
2021-01-13 07:04:14 +00:00
}
}
2021-04-02 14:01:40 +00:00
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
2021-04-02 14:01:40 +00:00
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();}
}
2021-04-02 14:01:40 +00:00
}
}