AzLearn

تمرين إعادة البناء

Password Generator

أعد كتابة مولد كلمات مرور بسيط باستخدام المكتبة القياسية فقط.

rust ~12 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
use std::env;
use std::time::{SystemTime, UNIX_EPOCH};

const CHARSET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";

fn main() {
    let length = env::args()
        .nth(1)
        .and_then(|text| text.parse::<usize>().ok())
        .unwrap_or(16);

    let mut seed = time_seed();
    let mut password = String::new();

    // ابنِ كلمة المرور حرفاً حرفاً — Build the password character by character
    for _ in 0..length {
        seed = next_seed(seed);
        let index = seed as usize % CHARSET.len();
        password.push(CHARSET[index] as char);
    }

    println!("{password}");
}

fn time_seed() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64
}

fn next_seed(seed: u64) -> u64 {
    seed.wrapping_mul(6364136223846793005).wrapping_add(1)
}
اكتب هنا