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
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
extern crate random_pick;

static NUMBERS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
static NUMBERS_EXCLUDE_SIMILAR: [char; 8] = ['2', '3', '4', '5', '6', '7', '8', '9'];

static LOWERCASE_LETTERS: [char; 26] = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x', 'y', 'z',
];
static LOWERCASE_LETTERS_EXCLUDE_SIMILAR: [char; 23] = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z',
];

static UPPERCASE_LETTERS: [char; 26] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
static UPPERCASE_LETTERS_EXCLUDE_SIMILAR: [char; 24] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U',
    'V', 'W', 'X', 'Y', 'Z',
];

static SYMBOLS: [char; 32] = [
    '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=',
    '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~',
];
static SYMBOLS_EXCLUDE_SIMILAR: [char; 28] = [
    '!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?',
    '@', '[', '\\', ']', '^', '_', '{', '}', '~',
];

static SPACE: [char; 1] = [' '];

/// This struct can help you continually generate passwords.
#[derive(Debug, Clone, PartialEq)]
pub struct PasswordGeneratorIter {
    pool: Vec<&'static [char]>,
    length: usize,
    target_mask: u8,
    strict: bool,
}

impl PasswordGeneratorIter {
    /// Generate random passwords.
    pub fn generate(&self, count: usize) -> Vec<String> {
        debug_assert_ne!(0, self.target_mask);

        if self.strict {
            let mut result = Vec::with_capacity(count);

            let random = random_pick::pick_multiple_from_multiple_slices(
                &self.pool,
                &[1],
                count * self.length,
            );

            let mut i = 0;

            while i < count {
                let start = i * self.length;

                let mut password = String::with_capacity(self.length);

                let handle = |random: &[&char], start: usize, end: usize, password: &mut String| {
                    let mut mask: u8 = 0;
                    let mut m = false;

                    for &c in random[start..end].iter() {
                        password.push(*c);

                        if !m {
                            if NUMBERS.contains(c) {
                                mask |= 0b0000_0001;
                            } else if LOWERCASE_LETTERS.contains(c) {
                                mask |= 0b0000_0010;
                            } else if UPPERCASE_LETTERS.contains(c) {
                                mask |= 0b0000_0100;
                            } else if SYMBOLS.contains(c) {
                                mask |= 0b0000_1000;
                            } else if ' '.eq(c) {
                                mask |= 0b0001_0000;
                            } else {
                                continue;
                            }
                            m = mask == self.target_mask;
                        }
                    }

                    m
                };

                if !handle(&random, start, start + self.length, &mut password) {
                    loop {
                        let random = random_pick::pick_multiple_from_multiple_slices(
                            &self.pool,
                            &[1],
                            self.length,
                        );

                        password.clear();

                        if handle(&random, 0, self.length, &mut password) {
                            break;
                        }
                    }
                }

                result.push(password);

                i += 1;
            }

            result
        } else {
            let mut result = Vec::with_capacity(count);

            let random = random_pick::pick_multiple_from_multiple_slices(
                &self.pool,
                &[1],
                count * self.length,
            );

            for i in 0..count {
                let start = i * self.length;
                let mut password = String::with_capacity(self.length);

                for &c in random[start..start + self.length].iter() {
                    password.push(*c);
                }

                result.push(password);
            }

            result
        }
    }

    /// Generate a random password.
    #[inline]
    pub fn generate_one(&self) -> String {
        self.generate(1).remove(0)
    }
}

impl Iterator for PasswordGeneratorIter {
    type Item = String;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.generate_one())
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (usize::max_value(), None)
    }

    #[inline]
    fn count(self) -> usize
    where
        Self: Sized, {
        usize::max_value()
    }

    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized, {
        Some(self.generate_one())
    }

    #[inline]
    fn nth(&mut self, mut _n: usize) -> Option<Self::Item> {
        Some(self.generate_one())
    }
}

/// This struct can help you generate passwords.
#[derive(Debug, Clone, PartialEq)]
pub struct PasswordGenerator {
    /// The length of the generated passwords.
    ///
    /// Default: `8`
    pub length: usize,
    /// Passwords are allowed to, or must if the strict is true, contain a number or numbers.
    ///
    /// Default: `true`
    pub numbers: bool,
    /// Passwords are allowed to, or must if the strict is true, contain a lowercase letter or lowercase letters.
    ///
    /// Default: `true`
    pub lowercase_letters: bool,
    /// Passwords are allowed to, or must if the strict is true, contain an uppercase letter or uppercase letters.
    ///
    /// Default: `false`
    pub uppercase_letters: bool,
    /// Passwords are allowed to, or must if the strict is true, contain a symbol or symbols.
    ///
    /// Default: `false`
    pub symbols: bool,
    /// Passwords are allowed to, or must if the strict is true, contain a space or spaces.
    ///
    /// Default: `false`
    pub spaces: bool,
    /// Whether to exclude similar characters, ``iI1loO0"'`|``.
    ///
    /// Default: `false`
    pub exclude_similar_characters: bool,
    /// Whether the password rules are strict.
    ///
    /// Default: `false`
    pub strict: bool,
}

impl PasswordGenerator {
    /// Create a `PasswordGenerator` instance.
    ///
    /// ```rust,ignore
    /// PasswordGenerator {
    ///     length: 8,
    ///     numbers: true,
    ///     lowercase_letters: true,
    ///     uppercase_letters: false,
    ///     symbols: false,
    ///     spaces: false,
    ///     exclude_similar_characters: false,
    ///     strict: false,
    /// }
    /// ```
    pub const fn new() -> PasswordGenerator {
        PasswordGenerator {
            length: 8,
            numbers: true,
            lowercase_letters: true,
            uppercase_letters: false,
            symbols: false,
            spaces: false,
            exclude_similar_characters: false,
            strict: false,
        }
    }

    /// The length of the generated passwords.
    pub const fn length(mut self, length: usize) -> PasswordGenerator {
        self.length = length;

        self
    }

    /// Passwords are allowed to, or must if the strict is true, contain a number or numbers.
    pub const fn numbers(mut self, numbers: bool) -> PasswordGenerator {
        self.numbers = numbers;

        self
    }

    /// Passwords are allowed to, or must if the strict is true, contain a lowercase letter or lowercase letters.
    pub const fn lowercase_letters(mut self, lowercase_letters: bool) -> PasswordGenerator {
        self.lowercase_letters = lowercase_letters;

        self
    }

    /// Passwords are allowed to, or must if the strict is true, contain an uppercase letter or uppercase letters.
    pub const fn uppercase_letters(mut self, uppercase_letters: bool) -> PasswordGenerator {
        self.uppercase_letters = uppercase_letters;

        self
    }

    /// Passwords are allowed to, or must if the strict is true, contain a symbol or symbols.
    pub const fn symbols(mut self, symbols: bool) -> PasswordGenerator {
        self.symbols = symbols;

        self
    }

    /// Passwords are allowed to, or must if the strict is true, contain a space or spaces.
    pub const fn spaces(mut self, space: bool) -> PasswordGenerator {
        self.spaces = space;

        self
    }

    /// Whether to exclude similar characters? The excluded similar characters set is ``iI1loO0"'`|``.
    pub const fn exclude_similar_characters(
        mut self,
        exclude_similar_characters: bool,
    ) -> PasswordGenerator {
        self.exclude_similar_characters = exclude_similar_characters;

        self
    }

    /// Whether the password rules are strict.
    pub const fn strict(mut self, strict: bool) -> PasswordGenerator {
        self.strict = strict;

        self
    }
}

impl PasswordGenerator {
    /// Generate random passwords.
    #[inline]
    pub fn generate(&self, count: usize) -> Result<Vec<String>, &'static str> {
        let iter = self.try_iter()?;

        Ok(iter.generate(count))
    }

    /// Generate a random password.
    #[inline]
    pub fn generate_one(&self) -> Result<String, &'static str> {
        let iter = self.try_iter()?;

        Ok(iter.generate_one())
    }

    /// Try to create an iterator for the purpose of reusing.
    pub fn try_iter(&self) -> Result<PasswordGeneratorIter, &'static str> {
        if self.length == 0 {
            return Err("The length of passwords cannot be 0.");
        }

        let mut pool: Vec<&[char]> = Vec::new();

        let mut sections_count = 0;

        let mut target_mask: u8 = 0;

        if self.numbers {
            if self.exclude_similar_characters {
                pool.push(&NUMBERS_EXCLUDE_SIMILAR);
            } else {
                pool.push(&NUMBERS);
            }

            sections_count += 1;
            target_mask |= 0b0000_0001;
        }

        if self.lowercase_letters {
            if self.exclude_similar_characters {
                pool.push(&LOWERCASE_LETTERS_EXCLUDE_SIMILAR);
            } else {
                pool.push(&LOWERCASE_LETTERS);
            }

            sections_count += 1;
            target_mask |= 0b0000_0010;
        }

        if self.uppercase_letters {
            if self.exclude_similar_characters {
                pool.push(&UPPERCASE_LETTERS_EXCLUDE_SIMILAR);
            } else {
                pool.push(&UPPERCASE_LETTERS);
            }

            sections_count += 1;
            target_mask |= 0b0000_0100;
        }

        if self.symbols {
            if self.exclude_similar_characters {
                pool.push(&SYMBOLS_EXCLUDE_SIMILAR);
            } else {
                pool.push(&SYMBOLS);
            }

            sections_count += 1;
            target_mask |= 0b0000_1000;
        }

        if self.spaces {
            pool.push(&SPACE);

            sections_count += 1;
            target_mask |= 0b0001_0000;
        }

        if !self.numbers
            && !self.lowercase_letters
            && !self.uppercase_letters
            && !self.symbols
            && !self.spaces
        {
            Err("You need to enable at least one kind of characters.")
        } else if self.strict && self.length < sections_count {
            Err("The length of passwords is too short.")
        } else {
            Ok(PasswordGeneratorIter {
                pool,
                length: self.length,
                target_mask,
                strict: self.strict,
            })
        }
    }
}

impl Default for PasswordGenerator {
    #[inline]
    fn default() -> PasswordGenerator {
        PasswordGenerator::new()
    }
}