aboutsummaryrefslogtreecommitdiff
path: root/rand.rs
blob: f8dd25b463dab8295f2359f319f0169e955a41f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::libc::c_int;
use std::vec;

mod libcrypto {
    use std::libc::c_int;

    #[link_args = "-lcrypto"]
    extern {
        pub fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int;
    }
}

pub fn rand_bytes(len: uint) -> ~[u8] {
    let mut out = vec::with_capacity(len);

    out.as_mut_buf(|out_buf, len| {
        let r = unsafe { libcrypto::RAND_bytes(out_buf, len as c_int) };
        if r != 1 as c_int { fail!() }
    });

    unsafe { vec::raw::set_len(&mut out, len); }

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rand_bytes() {
        let bytes = rand_bytes(32u);
        println!("{:?}", bytes);
    }
}