generated from napi-rs/package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
272 lines (250 loc) · 7 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#![deny(clippy::all)]
use napi::bindgen_prelude::{AsyncTask, JsFunction, Result};
use napi::JsNumber;
use std::sync::{Arc, Mutex};
mod train_task;
use train_task::{ComputeParametersTask, ProgressData};
// https://github.com/rust-lang/rust-analyzer/issues/17429
use napi_derive::napi;
#[napi(js_name = "FSRS")]
#[derive(Debug)]
pub struct FSRS(Arc<Mutex<fsrs::FSRS>>);
#[napi]
/// directly use fsrs::DEFAULT_PARAMETERS will cause error.
/// referencing statics in constants is unstable
/// see issue #119618 <https://github.com/rust-lang/rust/issues/119618> for more information
/// `static` and `const` variables can refer to other `const` variables. A `const` variable, however, cannot refer to a `static` variable.
/// to fix this, the value can be extracted to a `const` and then used.
pub const DEFAULT_PARAMETERS: [f32; 19] = [
0.40255, 1.18385, 3.173, 15.69105, 7.1949, 0.5345, 1.4604, 0.0046, 1.54575, 0.1192, 1.01925,
1.9395, 0.11, 0.29605, 2.2698, 0.2315, 2.9898, 0.51655, 0.6621,
];
impl Default for FSRS {
fn default() -> Self {
Self::new(None)
}
}
#[napi]
impl FSRS {
#[napi(constructor)]
pub fn new(parameters: Option<Vec<JsNumber>>) -> Self {
let params: [f32; 19] = match parameters {
Some(parameters) => {
let mut array = [0.0; 19];
for (i, value) in parameters.iter().enumerate().take(19) {
array[i] = value.get_double().unwrap_or(0.0) as f32;
}
array
}
None => DEFAULT_PARAMETERS,
};
Self(Arc::new(Mutex::new(
fsrs::FSRS::new(Some(¶ms)).unwrap(),
)))
}
#[napi(ts_return_type = "Promise<Array<number>>")]
pub fn compute_parameters(
&self,
train_set: Vec<&FSRSItem>,
enable_short_term: bool,
#[napi(
ts_arg_type = "(err: null | Error, value: { current: number, total: number, percent: number }) => void"
)]
progress_js_fn: Option<JsFunction>,
#[napi(ts_arg_type = "number")] timeout: Option<JsNumber>,
) -> Result<AsyncTask<ComputeParametersTask>> {
// Convert your `JS` training items to owned `fsrs::FSRSItem`
let train_data = train_set
.into_iter()
.map(|item| item.0.clone())
.collect::<Vec<_>>();
// Turn `JsFunction` into a `ThreadsafeFunction`
let fn_form_js = if let Some(callback) = progress_js_fn {
Some(callback.create_threadsafe_function(0, |ctx| {
let progress_data: ProgressData = ctx.value;
let env = ctx.env;
let current = env.create_uint32(progress_data.current as u32)?;
let total = env.create_uint32(progress_data.total as u32)?;
let percent = env.create_double(progress_data.percent)?;
let mut progress_obj = env.create_object()?;
progress_obj.set_named_property("current", current)?;
progress_obj.set_named_property("total", total)?;
progress_obj.set_named_property("percent", percent)?;
Ok(vec![progress_obj])
})?)
} else {
None
};
let task = ComputeParametersTask {
model: Arc::clone(&self.0),
train_data,
enable_short_term,
progress_callback: fn_form_js,
progress_timeout: timeout
.map(|x| x.get_int64().unwrap_or(500) as u64)
.unwrap_or(500),
};
Ok(AsyncTask::new(task))
}
#[napi]
pub fn next_states(
&self,
current_memory_state: Option<&MemoryState>,
desired_retention: f64,
days_elapsed: u32,
) -> NextStates {
let locked_model = self.0.lock().unwrap();
NextStates(
locked_model
.next_states(
current_memory_state.map(|x| x.0),
desired_retention as f32,
days_elapsed,
)
.unwrap(),
)
}
#[napi]
pub fn benchmark(&self, train_set: Vec<&FSRSItem>) -> Vec<f32> {
let locked_model = self.0.lock().unwrap();
locked_model.benchmark(train_set.iter().map(|x| x.0.clone()).collect(), true)
}
#[napi]
pub fn memory_state_from_sm2(
&self,
ease_factor: f64,
interval: f64,
sm2_retention: f64,
) -> MemoryState {
let locked_model = self.0.lock().unwrap();
MemoryState(
locked_model
.memory_state_from_sm2(ease_factor as f32, interval as f32, sm2_retention as f32)
.unwrap(),
)
}
#[napi]
pub fn memory_state(&self, item: &FSRSItem, starting_state: Option<&MemoryState>) -> MemoryState {
let locked_model = self.0.lock().unwrap();
MemoryState(
locked_model
.memory_state(item.0.clone(), starting_state.map(|x| x.0))
.unwrap(),
)
}
}
#[napi(js_name = "FSRSReview")]
#[derive(Debug)]
pub struct FSRSReview(fsrs::FSRSReview);
#[napi]
impl FSRSReview {
#[napi(constructor)]
pub fn new(rating: u32, delta_t: u32) -> Self {
Self(fsrs::FSRSReview { rating, delta_t })
}
#[napi(getter)]
pub fn rating(&self) -> u32 {
self.0.rating
}
#[napi(getter)]
pub fn delta_t(&self) -> u32 {
self.0.delta_t
}
#[napi(js_name = "toJSON")]
pub fn to_json(&self) -> String {
format!("{:?}", self.0)
}
}
#[napi(js_name = "FSRSItem")]
#[derive(Debug)]
pub struct FSRSItem(fsrs::FSRSItem);
#[napi]
impl FSRSItem {
#[napi(constructor)]
pub fn new(reviews: Vec<&FSRSReview>) -> Self {
Self(fsrs::FSRSItem {
reviews: reviews.iter().map(|x| x.0).collect(),
})
}
#[napi(getter)]
pub fn reviews(&self) -> Vec<FSRSReview> {
self.0.reviews.iter().map(|x| FSRSReview(*x)).collect()
}
#[napi]
pub fn long_term_review_cnt(&self) -> u32 {
self.0.long_term_review_cnt() as u32
}
#[napi(js_name = "toJSON")]
pub fn to_json(&self) -> String {
format!("{:?}", self.0)
}
}
#[napi(js_name = "MemoryState")]
#[derive(Debug)]
pub struct MemoryState(fsrs::MemoryState);
#[napi]
impl MemoryState {
#[napi(constructor)]
pub fn new(stability: f64, difficulty: f64) -> Self {
Self(fsrs::MemoryState {
stability: stability as f32,
difficulty: difficulty as f32,
})
}
#[napi(getter)]
pub fn stability(&self) -> f64 {
self.0.stability as f64
}
#[napi(getter)]
pub fn difficulty(&self) -> f64 {
self.0.difficulty as f64
}
#[napi(js_name = "toJSON")]
pub fn to_json(&self) -> String {
format!("{:?}", self.0)
}
}
#[napi(js_name = "NextStates")]
#[derive(Debug)]
pub struct NextStates(fsrs::NextStates);
#[napi]
impl NextStates {
#[napi(getter)]
pub fn hard(&self) -> ItemState {
ItemState(self.0.hard.clone())
}
#[napi(getter)]
pub fn good(&self) -> ItemState {
ItemState(self.0.good.clone())
}
#[napi(getter)]
pub fn easy(&self) -> ItemState {
ItemState(self.0.easy.clone())
}
#[napi(getter)]
pub fn again(&self) -> ItemState {
ItemState(self.0.again.clone())
}
#[napi(js_name = "toJSON")]
pub fn to_json(&self) -> String {
format!("{:?}", self.0)
}
}
#[napi(js_name = "ItemState")]
#[derive(Debug)]
pub struct ItemState(fsrs::ItemState);
#[napi]
impl ItemState {
#[napi(getter)]
pub fn memory(&self) -> MemoryState {
MemoryState(self.0.memory)
}
#[napi(getter)]
pub fn interval(&self) -> f32 {
self.0.interval
}
#[napi(js_name = "toJSON")]
pub fn to_json(&self) -> String {
format!("{:?}", self.0)
}
}