srs_sm2/lib.rs
1//! Pure implementation of the SuperMemo SM-2 spaced-repetition algorithm.
2//!
3//! `srs-sm2` is a tiny, lightweight, `#![no_std]`-compatible library that
4//! computes *when a flashcard should be reviewed next*. Given a card's current
5//! schedule and the quality of a recall, it returns the next schedule — with no
6//! I/O, no allocations beyond what the caller supplies, and no clock access.
7//! That makes it equally at home in a browser WASM bundle, an embedded device,
8//! or a server.
9//!
10//! # The algorithm
11//!
12//! SM-2 tracks two numbers per card:
13//!
14//! * `interval_days` — days until the next review.
15//! * `ease_factor` — a multiplier (`>=` [`MIN_EASE_FACTOR`]) controlling how
16//! fast the interval grows.
17//!
18//! On each review the caller supplies a `quality` in `0..=5`:
19//!
20//! * `quality < 3` is a failed recall: the interval resets to 1 day (the card is
21//! due again tomorrow) but the ease factor is still updated.
22//! * The first successful review seeds the interval to 1 day, the second to 6
23//! days, and every review after that multiplies the previous interval by the
24//! (updated) ease factor.
25//!
26//! The ease factor is updated every review with the classic SM-2 formula:
27//!
28//! ```text
29//! EF' = EF + (0.1 - (5 - q) * (0.08 + (5 - q) * 0.02))
30//! ```
31//!
32//! clamped to never drop below [`MIN_EASE_FACTOR`] (1.3).
33//!
34//! # Examples
35//!
36//! ```
37//! use srs_sm2::{Schedule, schedule_next, MIN_EASE_FACTOR};
38//!
39//! // A brand-new card, never reviewed.
40//! let card = Schedule { interval_days: 0, ease_factor: 2.5 };
41//!
42//! // Perfect recall (quality 5) → first interval is seeded to 1 day.
43//! let next = schedule_next(card, 5);
44//! assert_eq!(next.interval_days, 1);
45//!
46//! // A second good review seeds 6 days.
47//! let next = schedule_next(next, 4);
48//! assert_eq!(next.interval_days, 6);
49//!
50//! // A continued perfect streak grows the interval by the ease factor.
51//! let next = schedule_next(next, 5);
52//! assert_eq!(next.interval_days, 16); // 6 * 2.6, rounded
53//! assert!(next.ease_factor >= MIN_EASE_FACTOR);
54//! ```
55//!
56//! A failed recall (`quality < 3`) resets the interval without dropping the
57//! ease factor below the floor:
58//!
59//! ```
60//! use srs_sm2::{Schedule, schedule_next, MIN_EASE_FACTOR};
61//!
62//! let card = Schedule { interval_days: 30, ease_factor: 2.5 };
63//! let failed = schedule_next(card, 2);
64//! assert_eq!(failed.interval_days, 1);
65//! assert!(failed.ease_factor >= MIN_EASE_FACTOR);
66//! ```
67
68#![no_std]
69#![cfg_attr(docsrs, feature(doc_cfg))]
70
71use libm::{fmax, round};
72
73/// The lowest an ease factor may fall. Below this, intervals collapse toward
74/// daily review; SM-2 fixes the floor at 1.3.
75pub const MIN_EASE_FACTOR: f64 = 1.3;
76
77/// A card's schedule state, independent of storage or rendering.
78///
79/// `Schedule` is plain data: it carries the two numbers SM-2 needs and nothing
80/// else. Clone and copy it freely; the library never reaches back into your
81/// data structures.
82#[derive(Debug, Clone, Copy, PartialEq)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub struct Schedule {
85 /// Days until the next review.
86 pub interval_days: i32,
87 /// `SuperMemo` ease factor (`>=` [`MIN_EASE_FACTOR`]).
88 pub ease_factor: f64,
89}
90
91impl Default for Schedule {
92 /// A brand-new card, never reviewed: zero interval and the canonical
93 /// starting ease factor of 2.5 used throughout the SM-2 literature.
94 fn default() -> Self {
95 Self {
96 interval_days: 0,
97 ease_factor: 2.5,
98 }
99 }
100}
101
102/// Compute the next [`Schedule`] from the current one and a recall `quality`
103/// in `0..=5`.
104///
105/// Values outside `0..=5` are clamped to the nearest endpoint, so callers do
106/// not need to pre-validate slider/keyboard input.
107///
108/// * `quality < 3` is treated as a failed recall: the interval resets to 1 day.
109/// * The ease factor is always updated and clamped to [`MIN_EASE_FACTOR`].
110///
111/// The resulting `interval_days` is rounded to the nearest day. For intervals
112/// larger than `i32::MAX` days the value saturates at `i32::MAX` rather than
113/// overflowing or panicking.
114///
115/// # Examples
116///
117/// ```
118/// use srs_sm2::{Schedule, schedule_next};
119///
120/// // First successful review seeds a 1-day interval.
121/// let next = schedule_next(Schedule { interval_days: 0, ease_factor: 2.5 }, 5);
122/// assert_eq!(next.interval_days, 1);
123///
124/// // Out-of-range quality is clamped (99 behaves like 5).
125/// let hi = schedule_next(Schedule { interval_days: 6, ease_factor: 2.5 }, 99);
126/// let five = schedule_next(Schedule { interval_days: 6, ease_factor: 2.5 }, 5);
127/// assert_eq!(hi, five);
128/// ```
129#[must_use]
130pub fn schedule_next(current: Schedule, quality: i32) -> Schedule {
131 let q = f64::from(quality.clamp(0, 5));
132 let diff = 5.0 - q;
133 // EF' = EF + (0.1 - (5 - q) * (0.08 + (5 - q) * 0.02))
134 let delta = 0.1 - diff * (0.08 + diff * 0.02);
135 let ease_factor = fmax(current.ease_factor + delta, MIN_EASE_FACTOR);
136
137 let interval_days = if quality < 3 || current.interval_days == 0 {
138 1
139 } else if current.interval_days == 1 {
140 6
141 } else {
142 let raw = f64::from(current.interval_days) * ease_factor;
143 round(raw) as i32
144 };
145
146 Schedule {
147 interval_days,
148 ease_factor,
149 }
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 fn approx(a: f64, b: f64) -> bool {
157 (a - b).abs() < 1e-9
158 }
159
160 #[test]
161 fn failed_recall_resets_interval() {
162 let next = schedule_next(
163 Schedule {
164 interval_days: 30,
165 ease_factor: 2.5,
166 },
167 2,
168 );
169 assert_eq!(
170 next.interval_days, 1,
171 "failed recall must reset interval to 1"
172 );
173 }
174
175 #[test]
176 fn first_success_seeds_one_day() {
177 let next = schedule_next(
178 Schedule {
179 interval_days: 0,
180 ease_factor: 2.5,
181 },
182 5,
183 );
184 assert_eq!(next.interval_days, 1);
185 }
186
187 #[test]
188 fn second_success_seeds_six_days() {
189 let next = schedule_next(
190 Schedule {
191 interval_days: 1,
192 ease_factor: 2.5,
193 },
194 4,
195 );
196 assert_eq!(next.interval_days, 6);
197 }
198
199 #[test]
200 fn subsequent_success_multiplies_by_ease() {
201 // interval 6, perfect recall keeps EF at 2.6 -> 6 * 2.6 = 15.6 -> 16
202 let next = schedule_next(
203 Schedule {
204 interval_days: 6,
205 ease_factor: 2.5,
206 },
207 5,
208 );
209 assert!(
210 approx(next.ease_factor, 2.6),
211 "ease was {}",
212 next.ease_factor
213 );
214 assert_eq!(next.interval_days, 16);
215 }
216
217 #[test]
218 fn ease_factor_never_below_floor() {
219 let mut sched = Schedule {
220 interval_days: 10,
221 ease_factor: 1.3,
222 };
223 for _ in 0..20 {
224 sched = schedule_next(sched, 0);
225 assert!(
226 sched.ease_factor >= MIN_EASE_FACTOR,
227 "ease dropped below floor: {}",
228 sched.ease_factor
229 );
230 }
231 }
232
233 #[test]
234 fn perfect_recall_raises_ease() {
235 let next = schedule_next(
236 Schedule {
237 interval_days: 6,
238 ease_factor: 2.5,
239 },
240 5,
241 );
242 assert!(next.ease_factor > 2.5, "perfect recall should raise ease");
243 }
244
245 #[test]
246 fn quality_three_holds_ease_roughly_steady() {
247 // q=3: delta = 0.1 - 2*(0.08 + 2*0.02) = 0.1 - 2*0.12 = -0.14
248 let next = schedule_next(
249 Schedule {
250 interval_days: 6,
251 ease_factor: 2.5,
252 },
253 3,
254 );
255 assert!(
256 approx(next.ease_factor, 2.36),
257 "ease was {}",
258 next.ease_factor
259 );
260 }
261
262 #[test]
263 fn out_of_range_quality_is_clamped() {
264 let hi = schedule_next(
265 Schedule {
266 interval_days: 6,
267 ease_factor: 2.5,
268 },
269 99,
270 );
271 let five = schedule_next(
272 Schedule {
273 interval_days: 6,
274 ease_factor: 2.5,
275 },
276 5,
277 );
278 assert_eq!(hi, five, "quality above 5 should clamp to 5");
279 }
280}