passgen/
lib.rs

1extern crate rand;
2use std::io::{Error, ErrorKind};
3
4pub fn generate<I>(charset: I, length: usize) -> Result<String, Error>
5        where I: Iterator<Item=char> {
6    use rand::{Rng, OsRng};
7
8    let mut r = try!(OsRng::new());
9
10    let charset_vec: Vec<char> = charset.collect();
11    let mut result = String::with_capacity(length);
12
13    for _ in 0..length {
14        result.push(*try!(
15            r.choose(&charset_vec)
16                .ok_or(Error::new(ErrorKind::InvalidInput,
17                                  "no charset specified"))
18        ));
19    }
20
21    Ok(result)
22}