diff --git a/Makefile b/Makefile index 21e79a5..75b62c1 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,13 @@ +all: uninstall build install + + install: cp -f libsrng.so /usr/local/lib/libsrng.so ln -sf /usr/local/lib/libsrng.so /usr/lib/libsrng.so uninstall: rm -f /usr/local/lib/libsrng.so - rm /usr/lib/libsrng.so + rm -f /usr/lib/libsrng.so build: cd libsrng && cargo build --release diff --git a/crandom.lisp b/crandom.lisp index fb747fd..a82d363 100644 --- a/crandom.lisp +++ b/crandom.lisp @@ -30,6 +30,15 @@ (apply '%crandom-list (cons range params)) (apply '%crandom-vector (cons range params)))) +(defun crandom-bytes (len &key (transform #'identity) (type :vector)) + (multiple-value-bind (vec ok) (cl-rng-ffi:ffi-bytes len) + (and ok + (if (eq type :vector) + (progn + (loop for i from 0 below len do (setf (aref vec i) (funcall transform (aref vec i)))) + vec) + (loop for i from 0 below len collect (funcall transform (aref vec i))))))) (export 'crandom) (export 'crandom-range) +(export 'crandom-bytes) diff --git a/ffi.lisp b/ffi.lisp index ff20c5c..97d007b 100644 --- a/ffi.lisp +++ b/ffi.lisp @@ -8,6 +8,9 @@ (use-foreign-library libsrng) (defcfun "sample" :int (to :pointer)) +(defcfun "bytes" :int + (to :pointer) + (size :int)) (defun ffi-sample () (with-foreign-pointer (value 8) @@ -16,4 +19,16 @@ (mem-ref value :double 0) (= rval 1))))) +(defun ffi-bytes (size) + (with-foreign-pointer (value size) + (let ((rval (bytes value size)) + (output (make-array size))) + (and (= rval 1) + (loop for x from 0 below size + do (setf (aref output x) (mem-aref value :unsigned-char x)))) + (values + output + (= rval 1))))) + (export 'ffi-sample) +(export 'ffi-bytes) diff --git a/libsrng.so b/libsrng.so index 2be0346..7f0dc92 100755 Binary files a/libsrng.so and b/libsrng.so differ diff --git a/libsrng.so.gpg b/libsrng.so.gpg index bbd462f..d3e3227 100644 Binary files a/libsrng.so.gpg and b/libsrng.so.gpg differ diff --git a/libsrng/src/lib.rs b/libsrng/src/lib.rs index 480dbad..6348bd6 100644 --- a/libsrng/src/lib.rs +++ b/libsrng/src/lib.rs @@ -10,6 +10,13 @@ mod tests { let mut f: f64 = 0.0; assert_eq!(sample(&mut f as *mut f64), 1); } + + #[test] + fn bytes_works() { + let mut buf: [u8; 16] = [0; 16]; + + assert_eq!(bytes(&mut buf[0] as *mut u8, 16), 1); + } } fn get() -> Result @@ -54,3 +61,22 @@ pub extern "C" fn sample(value: *mut f64) -> i32 } } +#[no_mangle] +pub extern "C" fn bytes(value: *mut u8, size: i32) -> i32 +{ + let mut buf: &mut [u8]; + + if size < 0 { + return 0 + } + + unsafe { + buf = std::slice::from_raw_parts_mut(value, size as usize); + } + + match getrandom(&mut buf) { + Ok(_) => 1, + Err(_) => 0, + } +} +