Skip to main content

ja_colloquial/
lib.rs

1//! Allocation-free access to the Japanese Colloquial Bible.
2//!
3//! Book lookup uses the full Japanese names returned by [`Bible::book_names`].
4//! Source-data abbreviations are intentionally not part of the public API.
5//! Random selection is deterministic until the caller supplies an
6//! unpredictable 128-bit key with [`seed`].
7
8#![no_std]
9#![deny(missing_docs)]
10#![deny(unsafe_code)]
11#![deny(unsafe_op_in_unsafe_fn)]
12#![allow(long_running_const_eval)]
13#![doc = include_str!("../README.md")]
14
15#[cfg(all(ja_colloquial_c_artifact, not(panic = "abort")))]
16compile_error!("C artifacts require panic=abort; use `cargo rustc --profile capi ...`");
17
18#[cfg(test)]
19extern crate std;
20
21use core::ffi::CStr;
22
23mod random;
24mod verses;
25
26#[cfg(ja_colloquial_c_artifact)]
27#[allow(unsafe_code)]
28mod c_api;
29
30pub use verses::BIBLE;
31
32/// An immutable view of the generated Bible corpus.
33#[derive(Clone, Copy, Debug)]
34pub struct Bible {
35    verses: &'static [Verse],
36    books: &'static [Book],
37    chapters: &'static [Chapter],
38    book_names: &'static [&'static str],
39}
40
41#[derive(Clone, Copy, Debug)]
42struct Book {
43    first_chapter_idx: u16,
44    chapter_count: u8,
45}
46
47#[derive(Clone, Copy, Debug)]
48struct Chapter {
49    first_verse_idx: u16,
50    verse_count: u8,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54struct Text {
55    rust: &'static str,
56    c: &'static CStr,
57}
58
59impl Text {
60    const fn new(c: &'static CStr) -> Self {
61        let rust = match c.to_str() {
62            Ok(text) => text,
63            Err(_) => panic!("generated verse text is not UTF-8"),
64        };
65        Self { rust, c }
66    }
67}
68
69/// One verse from the Japanese Colloquial Bible.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub struct Verse {
72    text: Text,
73    book_idx: u8,
74    chapter: u8,
75    verse: u8,
76}
77
78impl Bible {
79    /// Returns every verse record in canonical source order.
80    pub fn verses(&self) -> &[Verse] {
81        self.verses
82    }
83
84    /// Returns full Japanese book names in canonical order.
85    ///
86    /// Name lookup is exact UTF-8 equality. It performs no normalization and
87    /// accepts no abbreviations or aliases.
88    pub fn book_names(&self) -> &[&str] {
89        self.book_names
90    }
91
92    /// Returns the number of chapters in a Japanese-named book.
93    pub fn chapter_count(&self, book_name: &str) -> Option<usize> {
94        self.book_index(book_name)
95            .and_then(|index| self.chapter_count_by_index(index))
96    }
97
98    /// Returns every present verse record in a 1-based chapter.
99    pub fn chapter(&self, book_name: &str, chapter: usize) -> Option<&[Verse]> {
100        let book_idx = self.book_index(book_name)?;
101        self.chapter_by_index(book_idx, chapter)
102    }
103
104    /// Returns the number of records present in a 1-based chapter.
105    ///
106    /// This is not necessarily the highest verse label because the source
107    /// contains intentional numbering gaps.
108    pub fn verse_count(&self, book_name: &str, chapter: usize) -> Option<usize> {
109        self.chapter(book_name, chapter).map(<[Verse]>::len)
110    }
111
112    /// Looks up an exact 1-based chapter and verse number.
113    ///
114    /// Returns `None` for an unknown name, zero, an out-of-range value, or a
115    /// verse number absent from the source.
116    pub fn verse(&self, book_name: &str, chapter: usize, verse: usize) -> Option<Verse> {
117        let book_idx = self.book_index(book_name)?;
118        self.verse_by_index(book_idx, chapter, verse)
119    }
120
121    /// Uniformly selects one verse with the crate-global ChaCha20 generator.
122    ///
123    /// # Security
124    ///
125    /// Always call [`seed`] with an independently generated, unpredictable key
126    /// whenever the target environment can provide one. The default stream is
127    /// deterministic and publicly predictable.
128    pub fn random_verse(&self) -> Verse {
129        self.verses[random::random_index(self.verses.len())]
130    }
131
132    fn book_index(&self, book_name: &str) -> Option<usize> {
133        let index = verses::book_index(book_name)?;
134        (index < self.books.len()).then_some(index)
135    }
136
137    fn book(&self, book_idx: usize) -> Option<&Book> {
138        self.books.get(book_idx)
139    }
140
141    pub(crate) fn chapter_count_by_index(&self, book_idx: usize) -> Option<usize> {
142        self.book(book_idx)
143            .map(|book| usize::from(book.chapter_count))
144    }
145
146    fn chapter_metadata(&self, book_idx: usize, chapter: usize) -> Option<&Chapter> {
147        let book = self.book(book_idx)?;
148        let offset = chapter.checked_sub(1)?;
149        if offset >= usize::from(book.chapter_count) {
150            return None;
151        }
152        self.chapters
153            .get(usize::from(book.first_chapter_idx) + offset)
154    }
155
156    pub(crate) fn chapter_by_index(&self, book_idx: usize, chapter: usize) -> Option<&[Verse]> {
157        let metadata = self.chapter_metadata(book_idx, chapter)?;
158        let first = usize::from(metadata.first_verse_idx);
159        let end = first + usize::from(metadata.verse_count);
160        self.verses.get(first..end)
161    }
162
163    pub(crate) fn verse_by_index(
164        &self,
165        book_idx: usize,
166        chapter: usize,
167        verse: usize,
168    ) -> Option<Verse> {
169        if verse == 0 || verse > usize::from(u8::MAX) {
170            return None;
171        }
172        let verses = self.chapter_by_index(book_idx, chapter)?;
173        let number = verse as u8;
174        let index = verses
175            .binary_search_by_key(&number, |candidate| candidate.verse)
176            .ok()?;
177        verses.get(index).copied()
178    }
179}
180
181impl Verse {
182    /// Returns the full Japanese book name.
183    pub fn book_name(&self) -> &'static str {
184        verses::BOOK_NAMES[usize::from(self.book_idx)]
185    }
186
187    /// Returns the 1-based chapter number.
188    pub fn chapter(&self) -> usize {
189        usize::from(self.chapter)
190    }
191
192    /// Returns the 1-based verse number recorded by the source.
193    pub fn number(&self) -> usize {
194        usize::from(self.verse)
195    }
196
197    /// Returns the Japanese verse text.
198    pub fn text(&self) -> &'static str {
199        self.text.rust
200    }
201
202    #[cfg(ja_colloquial_c_artifact)]
203    pub(crate) fn book_index(&self) -> usize {
204        usize::from(self.book_idx)
205    }
206
207    #[cfg(any(test, ja_colloquial_c_artifact))]
208    pub(crate) fn c_text(&self) -> &'static CStr {
209        self.text.c
210    }
211}
212
213/// Installs the crate-global 128-bit random key if it is still unset.
214///
215/// Returns `true` when this call installed the key. Once any call succeeds,
216/// every later call is a no-op and returns `false`. The key bytes are
217/// interpreted as four little-endian words. Call this as early as possible so
218/// another caller cannot install a weaker key first.
219#[must_use = "check whether this call installed the one-time random seed"]
220pub fn seed(seed: [u8; 16]) -> bool {
221    random::seed(seed)
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn corpus_and_lookup() {
230        assert_eq!(BIBLE.book_names().len(), 66);
231        assert_eq!(BIBLE.verses().len(), 31_086);
232        assert_eq!(BIBLE.book_names().first(), Some(&"創世記"));
233        assert_eq!(BIBLE.book_names().get(16), Some(&"エステル記"));
234        assert_eq!(BIBLE.chapter_count("詩篇"), Some(150));
235
236        let verse = BIBLE.verse("創世記", 4, 13).expect("Genesis 4:13");
237        assert_eq!(verse.book_name(), "創世記");
238        assert_eq!(verse.chapter(), 4);
239        assert_eq!(verse.number(), 13);
240        assert_eq!(
241            verse.text(),
242            "カインは主に言った、「わたしの罰は重くて負いきれません。"
243        );
244        assert_eq!(verse.c_text().to_bytes(), verse.text().as_bytes());
245
246        assert_eq!(BIBLE.verse("民数記", 15, 4), None);
247        assert_eq!(
248            BIBLE.verse("民数記", 15, 5).map(|item| item.number()),
249            Some(5)
250        );
251        assert_eq!(BIBLE.verse_count("民数記", 15), Some(40));
252        assert_eq!(BIBLE.verse("ge", 1, 1), None);
253        assert_eq!(BIBLE.verse("創世記", 0, 1), None);
254        assert_eq!(BIBLE.verse("創世記", 1, 0), None);
255        assert_eq!(BIBLE.verse("創世記", usize::MAX, 1), None);
256        assert_eq!(BIBLE.verse("創世記", 1, usize::MAX), None);
257    }
258}