Skip to content

Commit

Permalink
Fix to use rng.gen_range
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Dec 6, 2023
1 parent 8c99fb1 commit e893a53
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
9 changes: 8 additions & 1 deletion src/infrastructure/namegen.rs
Expand Up @@ -6,6 +6,7 @@ use std::{
use anyhow::{bail, ensure, Context};
use rand::{thread_rng, Rng};
use scraper::{Html, Selector};
use time::{Date, Month, OffsetDateTime};
use tokio::sync::Mutex;

use crate::{
Expand Down Expand Up @@ -146,6 +147,12 @@ impl GeneratePiUseCase for NamesCache {
KanaForm::Katakana => name.in_katakana(),
KanaForm::HalfwidthKana => name.in_halfwidth_kana(),
};
Ok(PI::from((name, sex, DateOfBirth::gen())))
let current_year = OffsetDateTime::now_utc().year();
let start =
Date::from_calendar_date(current_year - 120, Month::January, 1).expect("invalid date");
let end =
Date::from_calendar_date(current_year, Month::December, 31).expect("invalid date");
let date = rng.gen_range(DateOfBirth::from(start)..=DateOfBirth::from(end));
Ok(PI::from((name, sex, date)))
}
}
23 changes: 11 additions & 12 deletions src/model/date_of_birth.rs
Expand Up @@ -6,13 +6,8 @@ use time::{macros::format_description, Date, Duration, OffsetDateTime};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DateOfBirth(Date);

impl DateOfBirth {
pub fn gen() -> Self {
let mut rng = thread_rng();
let current_year = OffsetDateTime::now_utc().year();
let year = rng.gen_range(current_year - 120..=current_year);
let date = rng.gen::<Date>();
let date = Date::from_calendar_date(year, date.month(), date.day()).expect("invalid date");
impl From<Date> for DateOfBirth {
fn from(date: Date) -> Self {
Self(date)
}
}
Expand Down Expand Up @@ -90,6 +85,15 @@ mod tests {

use super::*;

#[test]
fn test_from_date() -> anyhow::Result<()> {
let date = Date::parse("2020-01-02", format_description!("[year]-[month]-[day]"))?;
let dob = DateOfBirth::from(date);
let s = serde_json::to_string(&dob)?;
assert_eq!(s, r#""2020-01-02""#);
Ok(())
}

#[test]
fn test_from_str() -> anyhow::Result<()> {
let dob: DateOfBirth = "2020-01-02".parse()?;
Expand All @@ -116,9 +120,4 @@ mod tests {

Ok(())
}

#[test]
fn test_gen() {
assert_ne!(DateOfBirth::gen(), DateOfBirth::gen());
}
}

0 comments on commit e893a53

Please sign in to comment.