Skip to main content

sabi_maker/
lib.rs

1//! Japanese chorus-hook generator used by the `sabi` command.
2
3/// Options for chorus generation.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Options {
6    pub theme: String,
7    pub mood: Mood,
8    pub lines: usize,
9    pub seed: u64,
10}
11
12impl Default for Options {
13    fn default() -> Self {
14        Self {
15            theme: "君".into(),
16            mood: Mood::Bright,
17            lines: 4,
18            seed: 1,
19        }
20    }
21}
22
23/// Emotional tone of the generated hook.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Mood {
26    Bright,
27    Emotional,
28    Cool,
29}
30
31impl Mood {
32    pub fn parse(value: &str) -> Option<Self> {
33        match value {
34            "bright" | "明るい" => Some(Self::Bright),
35            "emotional" | "エモい" => Some(Self::Emotional),
36            "cool" | "クール" => Some(Self::Cool),
37            _ => None,
38        }
39    }
40}
41
42/// Generate a chorus. The same options always produce the same result.
43pub fn generate(options: &Options) -> String {
44    let lines = options.lines.clamp(2, 12);
45    let mut rng = Rng(options.seed ^ hash(&options.theme));
46    let (starts, verbs, endings): (&[&str], &[&str], &[&str]) = match options.mood {
47        Mood::Bright => (
48            &["もっと", "きっと", "さあ", "何度でも", "まっすぐ"],
49            &[
50                "歌おう",
51                "駆け出そう",
52                "抱きしめよう",
53                "信じよう",
54                "飛び越えよう",
55            ],
56            &["光のほうへ", "明日を迎えに", "笑顔のままで", "空の向こうへ"],
57        ),
58        Mood::Emotional => (
59            &["今も", "ずっと", "もしも", "もう一度", "声が枯れても"],
60            &[
61                "忘れない",
62                "探してる",
63                "そばにいたい",
64                "届けたい",
65                "呼び続ける",
66            ],
67            &[
68                "夜が明けるまで",
69                "涙の向こうで",
70                "記憶の中へ",
71                "この胸のまま",
72            ],
73        ),
74        Mood::Cool => (
75            &["静かに", "鋭く", "真夜中", "迷わず", "限界まで"],
76            &[
77                "塗り替える",
78                "突き抜ける",
79                "踊り続ける",
80                "解き放つ",
81                "加速する",
82            ],
83            &[
84                "ノイズを裂いて",
85                "影をまとって",
86                "時代の先へ",
87                "誰も知らない場所へ",
88            ],
89        ),
90    };
91
92    let mut output = Vec::with_capacity(lines);
93    for index in 0..lines {
94        let line = if index == lines - 1 {
95            format!("{0}、{0}、{1}!", options.theme, pick(verbs, &mut rng))
96        } else if index % 2 == 0 {
97            format!(
98                "{} {}を{}",
99                pick(starts, &mut rng),
100                options.theme,
101                pick(verbs, &mut rng)
102            )
103        } else {
104            format!("{} {}", pick(starts, &mut rng), pick(endings, &mut rng))
105        };
106        output.push(line);
107    }
108    output.join("\n")
109}
110
111fn pick<'a>(values: &'a [&str], rng: &mut Rng) -> &'a str {
112    values[rng.next() as usize % values.len()]
113}
114
115fn hash(value: &str) -> u64 {
116    value.bytes().fold(0xcbf29ce484222325, |acc, byte| {
117        (acc ^ u64::from(byte)).wrapping_mul(0x100000001b3)
118    })
119}
120
121struct Rng(u64);
122
123impl Rng {
124    fn next(&mut self) -> u64 {
125        self.0 ^= self.0 << 13;
126        self.0 ^= self.0 >> 7;
127        self.0 ^= self.0 << 17;
128        self.0
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn output_has_requested_number_of_lines() {
138        let options = Options {
139            lines: 6,
140            ..Options::default()
141        };
142        assert_eq!(generate(&options).lines().count(), 6);
143    }
144
145    #[test]
146    fn generation_is_deterministic() {
147        let options = Options::default();
148        assert_eq!(generate(&options), generate(&options));
149    }
150
151    #[test]
152    fn theme_is_included() {
153        let options = Options {
154            theme: "東京".into(),
155            ..Options::default()
156        };
157        assert!(generate(&options).contains("東京"));
158    }
159}