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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! A generic, thread-safe dataset container with lazy loading and caching.
//!
//! `dataset-core` provides [`Dataset<T, E>`], a lightweight wrapper that pairs a storage
//! directory with a lazily-initialized value of any type `T`. The actual downloading
//! and parsing logic is supplied by the caller through a loader closure stored at
//! construction time, making `Dataset<T, E>` suitable for any data source — local
//! files, remote URLs, databases, or in-memory generation.
//!
//! On top of this core type, the crate offers an **optional** feature-gated module:
//!
//! - **`utils`** — helper functions for downloading files, extracting archives,
//! verifying SHA-256 hashes, and managing temporary directories.
//!
//! Ready-to-use loaders for classic ML datasets (Iris, Boston Housing, Diabetes,
//! Titanic, Wine Quality) live in the companion crate
//! [`dataset-ml`](https://crates.io/crates/dataset-ml), which depends on
//! `dataset-core` with the `utils` feature enabled and serves as the reference
//! implementation for wrapping `Dataset<T, E>`.
//!
//! # Feature Flags
//!
//! | Feature | What it enables |
//! |---------|------------------------------------------------------------------|
//! | `utils` | `download_to`, `unzip`, `acquire_dataset`, and the `error` module |
//!
//! With no features enabled, only `Dataset<T, E>` is available — depending only on
//! `std::sync::OnceLock`.
//!
//! # Quick Start — `Dataset<T, E>`
//!
//! ```rust
//! use dataset_core::Dataset;
//!
//! fn my_loader(dir: &str) -> Result<Vec<String>, std::io::Error> {
//! // In a real use case you would read/download files from `dir`.
//! Ok(vec!["hello".to_string(), "world".to_string()])
//! }
//!
//! // The loader is supplied once, at construction time.
//! let mut ds: Dataset<Vec<String>, std::io::Error> = Dataset::new("./my_data", my_loader);
//!
//! // First call runs the loader; subsequent calls return the cached reference.
//! let data = ds.load().unwrap();
//! assert_eq!(data.len(), 2);
//!
//! let data_again = ds.load().unwrap();
//! assert!(std::ptr::eq(data, data_again)); // same reference, no reload
//!
//! // `get` borrows the cached value without ever running the loader;
//! // `get_mut` edits it in place (no clone, no reload — the change stays cached).
//! assert!(ds.get().is_some());
//! if let Some(v) = ds.get_mut() {
//! v[0] = "HELLO".to_string();
//! }
//! assert_eq!(ds.get().unwrap()[0], "HELLO");
//!
//! // Move the cached value out without cloning. `take` leaves `ds` reusable
//! // (a later `load` re-runs the loader); `into_inner` consumes `ds`.
//! let owned = ds.take().unwrap();
//! assert_eq!(owned.len(), 2);
//! assert!(!ds.is_loaded());
//!
//! ds.load().unwrap(); // `take` reset the cache, so this reloads
//! let owned = ds.into_inner().unwrap();
//! assert_eq!(owned.len(), 2);
//! ```
//!
//! # Swapping the loader
//!
//! Because the loader lives inside the `Dataset`, you change *how* the data is
//! parsed with [`Dataset::set_loader`], which also invalidates the cache so the
//! next access re-parses with the new loader. To re-run the **same** loader
//! (e.g. the file on disk changed), use [`Dataset::invalidate`].
//!
//! ```rust
//! use dataset_core::Dataset;
//!
//! let mut ds: Dataset<i32, std::convert::Infallible> = Dataset::new("./data", |_| Ok(1));
//! assert_eq!(*ds.load().unwrap(), 1);
//!
//! ds.set_loader(|_| Ok(2)); // swap the loader; old cache is dropped
//! assert!(!ds.is_loaded());
//! assert_eq!(*ds.load().unwrap(), 2); // next load uses the new loader
//! ```
//!
//! # Utility Functions (feature `utils`)
//!
//! - `download_to` — download a remote file into a directory
//! - `unzip` — extract a ZIP archive
//! - `acquire_dataset` — cache-aware dataset acquisition workflow
//! (temp dir → prepare → optional hash check → move to final location)
//!
//! `acquire_dataset` is the single entry point for caching a dataset file; temp-dir
//! creation and SHA-256 verification are internal steps it performs for you.
pub use ;
use OnceLock;
pub use ;
/// The boxed loader stored inside a [`Dataset`].
///
/// A loader takes the storage directory path and returns the parsed dataset (or
/// an error). It is stored behind a `Box<dyn Fn ...>` so the concrete closure
/// type does not leak into `Dataset`'s type parameters. The `Send + Sync` bound
/// keeps `Dataset<T, E>` shareable across threads (matching the guarantee given
/// by the internal `OnceLock`); the implied `'static` bound means the loader may
/// not borrow from its environment — capture by value or clone instead.
type Loader<T, E> = ;
/// A generic, thread-safe dataset container with lazy loading and in-memory caching.
///
/// `Dataset<T, E>` is a thin caching wrapper that holds a `storage_dir` (the directory
/// where dataset files are stored on disk), a loader closure, and a lazily-initialized
/// value of type `T`. The downloading and parsing logic is provided by the caller
/// through the loader passed to [`Dataset::new`] and run on first access by
/// [`Dataset::load`].
///
/// This struct is designed to be the building block for both the built-in datasets
/// shipped with this crate and any custom datasets defined by external users.
///
/// # Type Parameters
///
/// - `T` - The type of the parsed dataset. Can be any type, such as
/// `(Array2<f64>, Array1<f64>)`, a custom struct, or any other data representation.
/// `T` must implement `Send + Sync` for `Dataset<T, E>` to be shared across threads.
/// - `E` - The error type returned by the loader. Callers choose it freely (e.g.
/// `std::io::Error`, a crate-specific `DatasetError`, or `std::convert::Infallible`
/// for loaders that cannot fail).
///
/// # Thread Safety
///
/// `Dataset<T, E>` is `Send + Sync` when `T` is `Send + Sync` (the stored loader is
/// always `Send + Sync`). The internal `OnceLock` ensures that the loader runs at
/// most once, even when multiple threads call [`Dataset::load`] concurrently.
///
/// # Example
///
/// ```rust
/// use dataset_core::Dataset;
///
/// // Define a simple loader that reads a value from the storage directory path.
/// // The loader can return any error type you choose.
/// fn my_loader(dir: &str) -> Result<Vec<String>, std::io::Error> {
/// // In a real use case, you would download/read files from `dir`.
/// // Here we just demonstrate the caching behavior.
/// Ok(vec!["hello".to_string(), "world".to_string()])
/// }
///
/// // The loader is bound to the dataset at construction time.
/// let mut dataset: Dataset<Vec<String>, std::io::Error> = Dataset::new("./my_data", my_loader);
///
/// // The first call to `load` triggers the loader
/// let data = dataset.load().unwrap();
/// assert_eq!(data.len(), 2);
///
/// // Subsequent calls return the cached reference instantly
/// let data_again = dataset.load().unwrap();
/// assert!(std::ptr::eq(data, data_again)); // same reference, no re-load
///
/// // Check whether data has been loaded
/// assert!(dataset.is_loaded());
///
/// // Borrow the cached value without reloading, or edit it in place via `get_mut`.
/// if let Some(v) = dataset.get_mut() {
/// v[0] = "HELLO".to_string();
/// }
/// assert_eq!(dataset.get().unwrap()[0], "HELLO");
///
/// // Move the cached value out without cloning.
/// // `take` leaves `dataset` reusable; `into_inner` consumes it.
/// let owned = dataset.take().unwrap();
/// assert_eq!(owned.len(), 2);
/// assert!(!dataset.is_loaded()); // `take` reset it to unloaded
///
/// dataset.load().unwrap(); // reloads, since `take` cleared the cache
/// let owned = dataset.into_inner().unwrap();
/// assert_eq!(owned.len(), 2);
/// ```
/// Error handling module.
///
/// Provides structured error types for dataset loading operations including
/// download failures, validation errors, I/O errors, and detailed data format
/// errors with line numbers and contextual information for debugging.
/// Utility functions for dataset authors.
///
/// Provides helpers for downloading files, extracting archives, verifying
/// SHA256 hashes, and managing the dataset acquisition workflow.