Skip to main content

enryo_gagger/
lib.rs

1//! Deterministic, policy-guarded generation of restrained Japanese gags.
2//!
3//! The generator follows three structural rules:
4//!
5//! - the topic remains visible;
6//! - audience text selects a variation but is never placed in the punch line;
7//! - enryo level controls how softly the punch line lands.
8//!
9//! ```
10//! use enryo_gagger::{EnryoGagger, EnryoLevel, GagRequest};
11//!
12//! let request = GagRequest::new("月曜の会議")
13//!     .for_audience("仕事仲間")
14//!     .with_level(EnryoLevel::Deep);
15//! let gag = EnryoGagger::default().generate(&request)?;
16//!
17//! assert!(gag.text().contains("月曜の会議"));
18//! assert!(!gag.text().contains("仕事仲間"));
19//! # Ok::<(), enryo_gagger::GagError>(())
20//! ```
21
22use std::error::Error;
23use std::fmt::{self, Display, Formatter};
24
25const VARIANTS: u8 = 3;
26
27/// How strongly the generated gag holds itself back.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum EnryoLevel {
30    /// Maximum restraint and the softest landing.
31    Deep,
32    /// A visible but still considerate punch line.
33    #[default]
34    Moderate,
35    /// A brighter punch line that still avoids targeting the audience.
36    Light,
37}
38
39/// Surface voice used for the setup.
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
41pub enum GagStyle {
42    /// Courteous and indirect.
43    #[default]
44    Polite,
45    /// Short and understated.
46    Dry,
47    /// A gentle Japanese-style retort.
48    Tsukkomi,
49}
50
51/// Input context for one gag.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct GagRequest {
54    topic: String,
55    audience: Option<String>,
56    level: EnryoLevel,
57    style: GagStyle,
58}
59
60impl GagRequest {
61    /// Starts a request about a topic.
62    pub fn new(topic: impl Into<String>) -> Self {
63        Self {
64            topic: topic.into(),
65            audience: None,
66            level: EnryoLevel::default(),
67            style: GagStyle::default(),
68        }
69    }
70
71    /// Adds audience context used only for deterministic variation selection.
72    pub fn for_audience(mut self, audience: impl Into<String>) -> Self {
73        self.audience = Some(audience.into());
74        self
75    }
76
77    /// Chooses the restraint level.
78    pub const fn with_level(mut self, level: EnryoLevel) -> Self {
79        self.level = level;
80        self
81    }
82
83    /// Chooses the setup voice.
84    pub const fn with_style(mut self, style: GagStyle) -> Self {
85        self.style = style;
86        self
87    }
88
89    /// Requested topic.
90    pub fn topic(&self) -> &str {
91        &self.topic
92    }
93
94    /// Audience context, when supplied.
95    pub fn audience(&self) -> Option<&str> {
96        self.audience.as_deref()
97    }
98
99    /// Requested restraint level.
100    pub const fn level(&self) -> EnryoLevel {
101        self.level
102    }
103
104    /// Requested style.
105    pub const fn style(&self) -> GagStyle {
106        self.style
107    }
108}
109
110/// Application-level boundaries for generation.
111#[derive(Clone, Debug, PartialEq, Eq)]
112pub struct EnryoPolicy {
113    blocked_terms: Vec<String>,
114    max_chars: usize,
115}
116
117impl EnryoPolicy {
118    /// Creates a policy with no blocked terms and a 140-character limit.
119    pub const fn new() -> Self {
120        Self {
121            blocked_terms: Vec::new(),
122            max_chars: 140,
123        }
124    }
125
126    /// Adds a case-insensitive blocked term.
127    ///
128    /// Empty and whitespace-only terms are ignored.
129    pub fn block_term(mut self, term: impl Into<String>) -> Self {
130        let term = term.into();
131        let term = term.trim();
132        if !term.is_empty() {
133            self.blocked_terms.push(term.to_lowercase());
134            self.blocked_terms.sort();
135            self.blocked_terms.dedup();
136        }
137        self
138    }
139
140    /// Changes the maximum Unicode character count.
141    pub fn with_max_chars(mut self, max_chars: usize) -> Result<Self, GagError> {
142        if max_chars == 0 {
143            return Err(GagError::ZeroMaxChars);
144        }
145        self.max_chars = max_chars;
146        Ok(self)
147    }
148
149    /// Normalized blocked terms.
150    pub fn blocked_terms(&self) -> &[String] {
151        &self.blocked_terms
152    }
153
154    /// Maximum Unicode character count.
155    pub const fn max_chars(&self) -> usize {
156        self.max_chars
157    }
158}
159
160impl Default for EnryoPolicy {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166/// One generated gag and its reproducibility metadata.
167#[derive(Clone, Debug, PartialEq, Eq)]
168pub struct Gag {
169    text: String,
170    level: EnryoLevel,
171    style: GagStyle,
172    variant: u8,
173}
174
175impl Gag {
176    /// Generated Japanese text.
177    pub fn text(&self) -> &str {
178        &self.text
179    }
180
181    /// Restraint level used.
182    pub const fn level(&self) -> EnryoLevel {
183        self.level
184    }
185
186    /// Style used.
187    pub const fn style(&self) -> GagStyle {
188        self.style
189    }
190
191    /// Stable template variation, from zero through two.
192    pub const fn variant(&self) -> u8 {
193        self.variant
194    }
195}
196
197impl Display for Gag {
198    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
199        f.write_str(&self.text)
200    }
201}
202
203/// Deterministic restrained-gag generator.
204#[derive(Clone, Debug, Default, PartialEq, Eq)]
205pub struct EnryoGagger {
206    policy: EnryoPolicy,
207}
208
209impl EnryoGagger {
210    /// Creates a generator with an explicit policy.
211    pub const fn with_policy(policy: EnryoPolicy) -> Self {
212        Self { policy }
213    }
214
215    /// Returns the current policy.
216    pub const fn policy(&self) -> &EnryoPolicy {
217        &self.policy
218    }
219
220    /// Generates one stable variation for a request.
221    pub fn generate(&self, request: &GagRequest) -> Result<Gag, GagError> {
222        validate_request(request)?;
223        self.check_blocked(request.topic())?;
224        if let Some(audience) = request.audience() {
225            self.check_blocked(audience)?;
226        }
227
228        let variant = stable_variant(request);
229        let opener = match request.style() {
230            GagStyle::Polite => format!("恐れ入ります、{}の件ですが、", request.topic().trim()),
231            GagStyle::Dry => format!("{}。", request.topic().trim()),
232            GagStyle::Tsukkomi => format!("{}って、", request.topic().trim()),
233        };
234        let ending = ending(request.level(), variant);
235        let text = format!("{opener}{ending}");
236        self.check_blocked(&text)?;
237
238        let actual = text.chars().count();
239        if actual > self.policy.max_chars {
240            return Err(GagError::TooLong {
241                actual,
242                max: self.policy.max_chars,
243            });
244        }
245        Ok(Gag {
246            text,
247            level: request.level(),
248            style: request.style(),
249            variant,
250        })
251    }
252
253    fn check_blocked(&self, text: &str) -> Result<(), GagError> {
254        let normalized = text.to_lowercase();
255        if let Some(term) = self
256            .policy
257            .blocked_terms
258            .iter()
259            .find(|term| normalized.contains(term.as_str()))
260        {
261            return Err(GagError::BlockedTerm(term.clone()));
262        }
263        Ok(())
264    }
265}
266
267fn validate_request(request: &GagRequest) -> Result<(), GagError> {
268    if request.topic.trim().is_empty() {
269        return Err(GagError::EmptyTopic);
270    }
271    if request
272        .audience
273        .as_ref()
274        .is_some_and(|audience| audience.trim().is_empty())
275    {
276        return Err(GagError::EmptyAudience);
277    }
278    Ok(())
279}
280
281fn stable_variant(request: &GagRequest) -> u8 {
282    let mut hash = 0xcbf29ce484222325u64;
283    for byte in request
284        .topic
285        .bytes()
286        .chain([0xff])
287        .chain(request.audience.as_deref().unwrap_or("").bytes())
288        .chain([request.level as u8, request.style as u8])
289    {
290        hash ^= u64::from(byte);
291        hash = hash.wrapping_mul(0x100000001b3);
292    }
293    (hash % u64::from(VARIANTS)) as u8
294}
295
296fn ending(level: EnryoLevel, variant: u8) -> &'static str {
297    let choices = match level {
298        EnryoLevel::Deep => [
299            "笑いは控えめに、口角だけ参加でお願いします。",
300            "オチは遠慮して、入口で待っています。",
301            "面白さには本日、静音モードをお願いしました。",
302        ],
303        EnryoLevel::Moderate => [
304            "小さなオチをご用意しました。小さすぎて、ただいま捜索中です。",
305            "笑ってよい範囲を測ったら、定規のほうが緊張しました。",
306            "ひとまずクスッを置きました。不要でしたら持ち帰ります。",
307        ],
308        EnryoLevel::Light => [
309            "オチより先にお辞儀するんかい。",
310            "勢いはあるのに、笑いだけ一歩ゆずるんかい。",
311            "そこまで遠慮したら、ギャグも席を譲るわ。",
312        ],
313    };
314    choices[usize::from(variant % VARIANTS)]
315}
316
317/// Validation, policy, or size failure.
318#[derive(Clone, Debug, PartialEq, Eq)]
319#[non_exhaustive]
320pub enum GagError {
321    /// The topic is empty or whitespace-only.
322    EmptyTopic,
323    /// Supplied audience context is empty or whitespace-only.
324    EmptyAudience,
325    /// Topic, audience, or generated text matched this normalized term.
326    BlockedTerm(String),
327    /// A zero-character output limit was requested.
328    ZeroMaxChars,
329    /// Generated text exceeded the policy limit.
330    TooLong {
331        /// Actual Unicode character count.
332        actual: usize,
333        /// Policy maximum.
334        max: usize,
335    },
336}
337
338impl Display for GagError {
339    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
340        match self {
341            Self::EmptyTopic => f.write_str("gag topic cannot be empty"),
342            Self::EmptyAudience => f.write_str("audience context cannot be empty"),
343            Self::BlockedTerm(term) => write!(f, "content matched blocked term: {term}"),
344            Self::ZeroMaxChars => f.write_str("maximum character count must be greater than zero"),
345            Self::TooLong { actual, max } => {
346                write!(f, "generated gag has {actual} characters; maximum is {max}")
347            }
348        }
349    }
350}
351
352impl Error for GagError {}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn same_request_always_generates_same_gag() {
360        let request = GagRequest::new("月曜").for_audience("チーム");
361        let generator = EnryoGagger::default();
362        assert_eq!(
363            generator.generate(&request).unwrap(),
364            generator.generate(&request).unwrap()
365        );
366    }
367
368    #[test]
369    fn audience_selects_but_is_not_inserted() {
370        let request = GagRequest::new("会議").for_audience("秘密の聞き手");
371        let gag = EnryoGagger::default().generate(&request).unwrap();
372        assert!(gag.text().contains("会議"));
373        assert!(!gag.text().contains("秘密の聞き手"));
374    }
375
376    #[test]
377    fn styles_and_levels_are_preserved() {
378        let request = GagRequest::new("コーヒー")
379            .with_style(GagStyle::Tsukkomi)
380            .with_level(EnryoLevel::Light);
381        let gag = EnryoGagger::default().generate(&request).unwrap();
382        assert_eq!(gag.style(), GagStyle::Tsukkomi);
383        assert_eq!(gag.level(), EnryoLevel::Light);
384        assert!(gag.text().starts_with("コーヒーって、"));
385    }
386
387    #[test]
388    fn blocked_terms_are_case_insensitive() {
389        let policy = EnryoPolicy::new().block_term("Spoiler");
390        let generator = EnryoGagger::with_policy(policy);
391        let error = generator
392            .generate(&GagRequest::new("SPOILER の話"))
393            .unwrap_err();
394        assert_eq!(error, GagError::BlockedTerm("spoiler".to_string()));
395    }
396
397    #[test]
398    fn invalid_context_is_rejected() {
399        let generator = EnryoGagger::default();
400        assert_eq!(
401            generator.generate(&GagRequest::new(" ")).unwrap_err(),
402            GagError::EmptyTopic
403        );
404        assert_eq!(
405            generator
406                .generate(&GagRequest::new("話題").for_audience(""))
407                .unwrap_err(),
408            GagError::EmptyAudience
409        );
410    }
411
412    #[test]
413    fn unicode_character_limit_is_enforced() {
414        let policy = EnryoPolicy::new().with_max_chars(5).unwrap();
415        let error = EnryoGagger::with_policy(policy)
416            .generate(&GagRequest::new("猫"))
417            .unwrap_err();
418        assert!(matches!(error, GagError::TooLong { max: 5, .. }));
419        assert_eq!(
420            EnryoPolicy::new().with_max_chars(0).unwrap_err(),
421            GagError::ZeroMaxChars
422        );
423    }
424}