smooth_reading/options.rs
1//! Algorithm options (`SmoothOptions` in SPEC §4).
2
3use std::fmt;
4use std::sync::Arc;
5
6use crate::segment::{Segmenter, SpecSegmenter};
7
8/// A custom fixation-length algorithm (SPEC §2, "Custom override").
9///
10/// It receives the word exactly as tokenized, its grapheme-cluster count and
11/// the options in force, and returns how many leading grapheme clusters to
12/// emphasise. The result is clamped to `0..=graphemes` by the caller.
13pub type FixationLengthFn = Arc<dyn Fn(&str, usize, &Options) -> usize + Send + Sync>;
14
15/// Fixation strength → percent of the word emphasised (SPEC §2), kept as
16/// integers so `floor((n * percent + 50) / 100)` is exact in every port.
17const PERCENT: [usize; 5] = [20, 35, 50, 65, 80];
18
19/// The default segmenter, shared by every [`Options`] that sets none.
20static SPEC_SEGMENTER: SpecSegmenter = SpecSegmenter;
21
22/// Algorithm options with the spec defaults (SPEC §4).
23///
24/// Build them with the chaining setters; every value is clamped into range
25/// rather than rejected, exactly as in every other port: `fixation` to `1..=5`,
26/// `saccade` to `>= 1`. Negative values cannot be expressed in the first place
27/// (`u8`/`usize`), which the spec allows a port whose type system excludes them
28/// to rely on.
29///
30/// The setters take `self` and return it, so a value can be configured in one
31/// expression; the getters carry a `get_` prefix (as on
32/// [`std::process::Command`]) because the plain names are taken by the setters.
33///
34/// `Options` implements [`Clone`] and [`Debug`](std::fmt::Debug) but not
35/// [`PartialEq`]: it can hold a closure and a segmenter, which have no useful
36/// notion of equality.
37///
38/// ```
39/// use smooth_reading::Options;
40///
41/// let options = Options::new().fixation(4).saccade(2);
42/// assert_eq!(options.get_fixation(), 4);
43/// assert_eq!(options.get_saccade(), 2);
44/// assert_eq!(Options::new().fixation(9).get_fixation(), 5); // clamped
45/// assert_eq!(Options::new().saccade(0).get_saccade(), 1); // clamped
46/// ```
47#[derive(Clone)]
48pub struct Options {
49 fixation: u8,
50 saccade: usize,
51 min_word_length: usize,
52 emphasize_numbers: bool,
53 locale: Option<String>,
54 fixation_length: Option<FixationLengthFn>,
55 segmenter: Option<Arc<dyn Segmenter>>,
56}
57
58impl Default for Options {
59 fn default() -> Self {
60 Self::new()
61 }
62}
63
64impl Options {
65 /// The spec defaults: strength `3`, every word, no minimum length, numbers
66 /// not emphasised, no locale, the built-in algorithm and segmenter.
67 #[must_use]
68 pub const fn new() -> Self {
69 Self {
70 fixation: 3,
71 saccade: 1,
72 min_word_length: 1,
73 emphasize_numbers: false,
74 locale: None,
75 fixation_length: None,
76 segmenter: None,
77 }
78 }
79
80 /// Sets the fixation strength, clamped to `1..=5`. Default `3`.
81 ///
82 /// The strength selects the proportion of each word that is emphasised:
83 /// `0.20, 0.35, 0.50, 0.65, 0.80`.
84 #[must_use]
85 pub const fn fixation(mut self, fixation: u8) -> Self {
86 self.fixation = if fixation < 1 {
87 1
88 } else if fixation > 5 {
89 5
90 } else {
91 fixation
92 };
93 self
94 }
95
96 /// Sets the saccade interval: emphasise every `saccade`-th word. Clamped to
97 /// `>= 1`. Default `1`.
98 #[must_use]
99 pub const fn saccade(mut self, saccade: usize) -> Self {
100 self.saccade = if saccade < 1 { 1 } else { saccade };
101 self
102 }
103
104 /// Words with fewer grapheme clusters than this get no fixation. Default `1`.
105 #[must_use]
106 pub const fn min_word_length(mut self, min_word_length: usize) -> Self {
107 self.min_word_length = min_word_length;
108 self
109 }
110
111 /// Whether words made only of decimal digits are emphasised. Default `false`.
112 #[must_use]
113 pub const fn emphasize_numbers(mut self, emphasize_numbers: bool) -> Self {
114 self.emphasize_numbers = emphasize_numbers;
115 self
116 }
117
118 /// Sets the BCP-47 language tag passed to the segmenter. The built-in
119 /// [`SpecSegmenter`] ignores it; a platform break iterator may use it.
120 #[must_use]
121 pub fn locale(mut self, locale: impl Into<String>) -> Self {
122 self.locale = Some(locale.into());
123 self
124 }
125
126 /// Replaces the built-in fixation algorithm (SPEC §2, "Custom override").
127 ///
128 /// [`fixation_length`](crate::fixation_length) honours this override, so
129 /// the closure must not call it with the same options (that would recurse).
130 ///
131 /// ```
132 /// use smooth_reading::{Options, to_markdown};
133 ///
134 /// // Always emphasise exactly one cluster (clamped to the word length).
135 /// let options = Options::new().fixation_length(|_word, _graphemes, _options| 1);
136 /// assert_eq!(to_markdown("Smooth reading", &options, "**"), "**S**mooth **r**eading");
137 /// ```
138 #[must_use]
139 pub fn fixation_length<F>(mut self, fixation_length: F) -> Self
140 where
141 F: Fn(&str, usize, &Options) -> usize + Send + Sync + 'static,
142 {
143 self.fixation_length = Some(Arc::new(fixation_length));
144 self
145 }
146
147 /// Supplies word boundaries and grapheme clusters (SPEC §3).
148 ///
149 /// The default is the spec's regular-expression scanner. Supply an
150 /// ICU-backed [`Segmenter`] for dictionary-based Chinese, Japanese and Thai
151 /// word breaks; the fixation algorithm itself never changes. The segmenter
152 /// is stored behind an [`Arc`]; use [`Options::shared_segmenter`] to share
153 /// one you already hold.
154 #[must_use]
155 pub fn segmenter(mut self, segmenter: impl Segmenter + 'static) -> Self {
156 self.segmenter = Some(Arc::new(segmenter));
157 self
158 }
159
160 /// Like [`Options::segmenter`], for a segmenter that is already shared
161 /// (for example one expensive to build and reused across many `Options`).
162 #[must_use]
163 pub fn shared_segmenter(mut self, segmenter: Arc<dyn Segmenter>) -> Self {
164 self.segmenter = Some(segmenter);
165 self
166 }
167
168 /// The fixation strength, `1..=5`.
169 #[must_use]
170 pub const fn get_fixation(&self) -> u8 {
171 self.fixation
172 }
173
174 /// The saccade interval, `>= 1`.
175 #[must_use]
176 pub const fn get_saccade(&self) -> usize {
177 self.saccade
178 }
179
180 /// The minimum word length (in grapheme clusters) that gets a fixation.
181 #[must_use]
182 pub const fn get_min_word_length(&self) -> usize {
183 self.min_word_length
184 }
185
186 /// Whether digit-only words are emphasised.
187 #[must_use]
188 pub const fn get_emphasize_numbers(&self) -> bool {
189 self.emphasize_numbers
190 }
191
192 /// The BCP-47 language tag, if one was set.
193 #[must_use]
194 pub fn get_locale(&self) -> Option<&str> {
195 self.locale.as_deref()
196 }
197
198 /// The custom fixation-length function, if one was set.
199 #[must_use]
200 pub const fn get_fixation_length(&self) -> Option<&FixationLengthFn> {
201 self.fixation_length.as_ref()
202 }
203
204 /// The custom segmenter, if one was set.
205 #[must_use]
206 pub const fn get_segmenter(&self) -> Option<&Arc<dyn Segmenter>> {
207 self.segmenter.as_ref()
208 }
209
210 /// Fraction of each word that is emphasised at this fixation strength.
211 ///
212 /// ```
213 /// use smooth_reading::Options;
214 ///
215 /// assert_eq!(Options::new().ratio(), 0.5);
216 /// assert_eq!(Options::new().fixation(5).ratio(), 0.8);
217 /// ```
218 #[must_use]
219 pub fn ratio(&self) -> f64 {
220 // `percent` is at most 80, so the conversion is exact.
221 #[allow(clippy::cast_precision_loss)]
222 let percent = self.percent() as f64;
223 percent / 100.0
224 }
225
226 /// Percent of the word emphasised at this strength (SPEC §2).
227 pub(crate) const fn percent(&self) -> usize {
228 PERCENT[(self.fixation - 1) as usize]
229 }
230
231 /// The segmenter in force: the custom one, or the spec scanner.
232 pub(crate) fn segmenter_impl(&self) -> &dyn Segmenter {
233 match &self.segmenter {
234 Some(segmenter) => segmenter.as_ref(),
235 None => &SPEC_SEGMENTER,
236 }
237 }
238}
239
240impl fmt::Debug for Options {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 f.debug_struct("Options")
243 .field("fixation", &self.fixation)
244 .field("saccade", &self.saccade)
245 .field("min_word_length", &self.min_word_length)
246 .field("emphasize_numbers", &self.emphasize_numbers)
247 .field("locale", &self.locale)
248 .field(
249 "fixation_length",
250 &self.fixation_length.as_ref().map(|_| "<custom>"),
251 )
252 .field("segmenter", &self.segmenter.as_ref().map(|_| "<custom>"))
253 .finish()
254 }
255}