1pub use super::types::{DataLoaderConfig, SplitResult};
6pub use crate::data::types::Batch;
7use crate::{DType, Engine, Error, Matrix, Result, matrix};
8use std::sync::{Arc, mpsc};
9use std::thread::JoinHandle;
10
11pub struct Sample {
15 pub x: Matrix,
17 pub y: Option<Matrix>,
19}
20
21impl Sample {
22 pub fn new(x: Matrix) -> Self {
24 Self { x, y: None }
25 }
26
27 pub fn new_with_label(x: Matrix, y: Matrix) -> Self {
29 Self { x, y: Some(y) }
30 }
31
32 pub fn has_label(&self) -> bool {
34 self.y.is_some()
35 }
36}
37
38pub trait Dataset {
42 fn len(&self) -> i64;
44
45 fn is_empty(&self) -> bool {
47 self.len() == 0
48 }
49
50 fn get_sample(&self, index: i64) -> Result<Sample> {
55 Ok(Sample::new(self.get_item(index)?))
56 }
57
58 fn get_item(&self, index: i64) -> Result<Matrix>;
60
61 fn subset(&self, indices: Vec<i64>) -> Result<Subset<'_>>
69 where
70 Self: Sized,
71 {
72 Subset::new(self, indices)
73 }
74
75 fn shuffled_subset(&self, seed: u64) -> Result<Subset<'_>>
83 where
84 Self: Sized,
85 {
86 let mut indices = make_indices(checked_len(self)?)?;
87 shuffle(&mut indices, seed)?;
88 self.subset(indices)
89 }
90}
91
92pub struct MatrixDataset {
101 x: Matrix,
102 y: Matrix,
103}
104
105impl MatrixDataset {
106 pub fn new(x: Matrix, y: Matrix) -> Result<Self> {
118 if x.shape().is_empty() || y.shape().len() != 1 || x.shape()[0] != y.shape()[0] {
119 return Err(Error::invalid_argument(
120 "matrix dataset requires [N, ...] features and [N] labels with equal counts",
121 ));
122 }
123 if x.dtype() != crate::DType::F32 || y.dtype() != crate::DType::F32 {
124 return Err(Error::invalid_argument(
125 "matrix dataset requires F32 features and labels",
126 ));
127 }
128 if !x.same_engine(&y) {
129 return Err(Error::invalid_argument(
130 "matrix dataset features and labels must share one engine",
131 ));
132 }
133 Ok(Self { x, y })
134 }
135
136 #[must_use]
138 pub const fn x(&self) -> &Matrix {
139 &self.x
140 }
141
142 #[must_use]
144 pub const fn y(&self) -> &Matrix {
145 &self.y
146 }
147}
148
149impl Dataset for MatrixDataset {
150 fn len(&self) -> i64 {
151 i64::try_from(self.x.shape()[0]).unwrap_or(i64::MAX)
152 }
153
154 fn get_item(&self, index: i64) -> Result<Matrix> {
155 if index < 0 || index >= self.len() {
156 return Err(Error::out_of_range(
157 "matrix dataset index is outside the dataset",
158 ));
159 }
160 matrix::slice(&self.x, 0, index, index + 1)?.squeeze(0)
161 }
162
163 fn get_sample(&self, index: i64) -> Result<Sample> {
164 let x = self.get_item(index)?;
165 let y = matrix::slice(&self.y, 0, index, index + 1)?;
166 Ok(Sample::new_with_label(x, y))
167 }
168}
169
170pub struct Subset<'ds> {
177 parent: &'ds dyn Dataset,
178 indices: Vec<i64>,
179}
180
181impl<'ds> Subset<'ds> {
182 pub fn new(parent: &'ds dyn Dataset, indices: Vec<i64>) -> Result<Self> {
188 let count = checked_len(parent)?;
189 if indices.iter().any(|&index| index < 0 || index >= count) {
190 return Err(Error::out_of_range(
191 "subset index is outside the parent dataset",
192 ));
193 }
194 Ok(Self { parent, indices })
195 }
196
197 fn parent_index(&self, index: i64) -> Result<i64> {
198 usize::try_from(index)
199 .ok()
200 .and_then(|index| self.indices.get(index))
201 .copied()
202 .ok_or_else(|| Error::out_of_range("index is outside the subset"))
203 }
204
205 pub fn indices(&self) -> &[i64] {
207 &self.indices
208 }
209
210 pub fn parent(&self) -> &dyn Dataset {
212 self.parent
213 }
214}
215
216impl Dataset for Subset<'_> {
217 fn len(&self) -> i64 {
218 self.indices.len() as i64
219 }
220
221 fn get_item(&self, index: i64) -> Result<Matrix> {
222 self.parent.get_item(self.parent_index(index)?)
223 }
224
225 fn get_sample(&self, index: i64) -> Result<Sample> {
226 self.parent.get_sample(self.parent_index(index)?)
227 }
228}
229
230impl Batch {
231 pub fn is_valid(&self) -> bool {
233 self.x.num_elements() > 0
234 }
235}
236
237pub struct DataLoader<'ds> {
241 dataset: &'ds dyn Dataset,
242 config: DataLoaderConfig,
243 indices: Vec<i64>,
244 current_batch: i64,
245}
246
247impl<'ds> DataLoader<'ds> {
248 pub fn new(dataset: &'ds dyn Dataset, config: DataLoaderConfig) -> Result<Self> {
255 if config.batch_size <= 0 {
256 return Err(Error::invalid_argument(
257 "data loader batch size must be positive",
258 ));
259 }
260 let mut loader = Self {
261 dataset,
262 config,
263 indices: Vec::new(),
264 current_batch: 0,
265 };
266 loader.reset()?;
267 Ok(loader)
268 }
269
270 pub fn next_batch(&mut self) -> Result<Option<Batch>> {
277 if self.current_batch >= self.num_batches() {
278 return Ok(None);
279 }
280 let start = self.current_batch as usize * self.config.batch_size as usize;
282 let count = (self.config.batch_size as usize).min(self.indices.len() - start);
283 let samples = self.indices[start..start + count]
284 .iter()
285 .map(|&index| self.dataset.get_sample(index))
286 .collect::<Result<Vec<_>>>()?;
287 let batch = collate(&samples)?;
288 self.current_batch += 1;
289 Ok(Some(batch))
290 }
291
292 pub fn reset(&mut self) -> Result<()> {
301 let mut indices = make_indices(checked_len(self.dataset)?)?;
302 if self.config.shuffle {
303 shuffle(&mut indices, self.config.seed)?;
304 }
305 self.indices = indices;
306 self.current_batch = 0;
307 Ok(())
308 }
309
310 pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
320 let mut indices = make_indices(checked_len(self.dataset)?)?;
321 if self.config.shuffle {
322 shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
323 }
324 self.indices = indices;
325 self.current_batch = 0;
326 Ok(())
327 }
328
329 pub fn num_batches(&self) -> i64 {
331 let n = self.indices.len() as i64;
332 let b = i64::from(self.config.batch_size);
333 n / b + i64::from(!self.config.drop_last && n % b != 0)
334 }
335
336 pub fn current_batch(&self) -> i64 {
338 self.current_batch
339 }
340}
341
342pub fn shuffle(indices: &mut [i64], seed: u64) -> Result<()> {
351 if indices.len() < 2 {
352 return Ok(());
353 }
354 let seed = if seed == 0 {
355 use std::time::{SystemTime, UNIX_EPOCH};
356 SystemTime::now()
357 .duration_since(UNIX_EPOCH)
358 .map_err(|_| Error::failed_precondition("dataset shuffle clock precedes Unix epoch"))?
359 .as_nanos() as u64
360 } else {
361 seed
362 };
363 let mut rng = Pcg32::new(seed);
364 for count in (2..=indices.len()).rev() {
365 let range = count as u64;
366 let reject = range.wrapping_neg() % range;
367 let value = loop {
368 let value = rng.next_u64();
369 if value >= reject {
370 break value;
371 }
372 };
373 indices.swap(count - 1, (value % range) as usize);
374 }
375 Ok(())
376}
377
378pub fn random_split(
390 total_size: i64,
391 train_ratio: f32,
392 val_ratio: f32,
393 seed: u64,
394) -> Result<SplitResult> {
395 if !train_ratio.is_finite() || !val_ratio.is_finite() {
396 return Err(Error::invalid_argument(
397 "dataset split ratios must be finite",
398 ));
399 }
400 let mut all = make_indices(total_size)?;
401 let train_ratio = train_ratio.clamp(0.0, 1.0);
402 let val_ratio = val_ratio.clamp(0.0, 1.0 - train_ratio);
403 let n = all.len();
404 let train_count = ((n as f32 * train_ratio) as usize).min(n);
405 let val_count = ((n as f32 * val_ratio) as usize).min(n - train_count);
406 shuffle(&mut all, seed)?;
407 let test = all.split_off(train_count + val_count);
408 let val = all.split_off(train_count);
409 Ok(SplitResult {
410 train: all,
411 val,
412 test,
413 })
414}
415
416pub fn collate(samples: &[Sample]) -> Result<Batch> {
429 let first = samples
430 .first()
431 .ok_or_else(|| Error::invalid_argument("collate requires at least one sample"))?;
432 for sample in samples {
433 validate_component(&sample.x, &first.x)?;
434 match (&sample.y, &first.y) {
435 (Some(value), Some(reference)) => {
436 validate_component(value, reference)?;
437 if !value.engine_handle().same_as(first.x.engine_handle()) {
438 return Err(Error::invalid_argument(
439 "collate inputs and labels must share one engine",
440 ));
441 }
442 }
443 (None, None) => {}
444 _ => {
445 return Err(Error::invalid_argument(
446 "collate label presence must match for every sample",
447 ));
448 }
449 }
450 }
451 if let [only] = samples {
452 return Ok(Batch {
453 x: only.x.unsqueeze(0)?,
454 y: only
455 .y
456 .as_ref()
457 .map(|value| value.unsqueeze(0))
458 .transpose()?,
459 });
460 }
461 let x_views = samples
462 .iter()
463 .map(|sample| sample.x.unsqueeze(0))
464 .collect::<Result<Vec<_>>>()?;
465 let y_views = samples
466 .iter()
467 .filter_map(|sample| sample.y.as_ref())
468 .map(|value| value.unsqueeze(0))
469 .collect::<Result<Vec<_>>>()?;
470 let x = matrix::concat(&x_views, 0)?;
471 let y = if y_views.is_empty() {
472 None
473 } else {
474 Some(matrix::concat(&y_views, 0)?)
475 };
476 Ok(Batch { x, y })
477}
478
479fn validate_component(value: &Matrix, reference: &Matrix) -> Result<()> {
480 if value.shape().len() > 3 {
481 return Err(Error::invalid_argument(
482 "collate requires samples of rank at most three",
483 ));
484 }
485 if value.num_elements() == 0
486 || value.shape() != reference.shape()
487 || value.dtype() != reference.dtype()
488 || !value.engine_handle().same_as(reference.engine_handle())
489 {
490 return Err(Error::invalid_argument(
491 "collate requires nonempty, same-shape, same-dtype, same-engine components",
492 ));
493 }
494 Ok(())
495}
496
497fn checked_len(dataset: &dyn Dataset) -> Result<i64> {
498 let count = dataset.len();
499 if count < 0 {
500 return Err(Error::invalid_argument(
501 "dataset length must be nonnegative",
502 ));
503 }
504 Ok(count)
505}
506
507fn make_indices(count: i64) -> Result<Vec<i64>> {
508 let length = usize::try_from(count)
509 .map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
510 let mut indices = Vec::new();
511 indices
512 .try_reserve_exact(length)
513 .map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
514 indices.extend(0..count);
515 Ok(indices)
516}
517
518struct Pcg32 {
521 state: u64,
522}
523
524impl Pcg32 {
525 fn new(seed: u64) -> Self {
526 let mut rng = Self { state: 0 };
527 rng.next_u32();
528 rng.state = rng.state.wrapping_add(seed);
529 rng.next_u32();
530 rng
531 }
532
533 fn next_u32(&mut self) -> u32 {
534 let old = self.state;
535 self.state = old.wrapping_mul(6364136223846793005).wrapping_add(3);
536 let shifted = (((old >> 18) ^ old) >> 27) as u32;
538 shifted.rotate_right((old >> 59) as u32)
539 }
540
541 fn next_u64(&mut self) -> u64 {
542 (u64::from(self.next_u32()) << 32) | u64::from(self.next_u32())
543 }
544}
545
546#[derive(Clone, Debug)]
555pub enum HostValues {
556 F32(Vec<f32>),
558 U32(Vec<u32>),
560 I32(Vec<i32>),
562 U8(Vec<u8>),
564}
565
566impl HostValues {
567 fn dtype(&self) -> DType {
568 match self {
569 Self::F32(_) => DType::F32,
570 Self::U32(_) => DType::U32,
571 Self::I32(_) => DType::I32,
572 Self::U8(_) => DType::U8,
573 }
574 }
575
576 fn len(&self) -> usize {
577 match self {
578 Self::F32(values) => values.len(),
579 Self::U32(values) => values.len(),
580 Self::I32(values) => values.len(),
581 Self::U8(values) => values.len(),
582 }
583 }
584
585 fn slice(&self, start: usize, count: usize) -> Self {
586 match self {
587 Self::F32(values) => Self::F32(values[start..start + count].to_vec()),
588 Self::U32(values) => Self::U32(values[start..start + count].to_vec()),
589 Self::I32(values) => Self::I32(values[start..start + count].to_vec()),
590 Self::U8(values) => Self::U8(values[start..start + count].to_vec()),
591 }
592 }
593
594 fn concat(parts: &[&Self]) -> Result<Self> {
595 let first = parts
596 .first()
597 .ok_or_else(|| Error::invalid_argument("host concat requires a part"))?;
598 Ok(match first {
599 Self::F32(_) => {
600 let mut values = Vec::new();
601 for part in parts {
602 let Self::F32(part) = part else {
603 return Err(Error::invalid_argument(
604 "host concat requires one dtype across parts",
605 ));
606 };
607 values.extend_from_slice(part);
608 }
609 Self::F32(values)
610 }
611 Self::U32(_) => {
612 let mut values = Vec::new();
613 for part in parts {
614 let Self::U32(part) = part else {
615 return Err(Error::invalid_argument(
616 "host concat requires one dtype across parts",
617 ));
618 };
619 values.extend_from_slice(part);
620 }
621 Self::U32(values)
622 }
623 Self::I32(_) => {
624 let mut values = Vec::new();
625 for part in parts {
626 let Self::I32(part) = part else {
627 return Err(Error::invalid_argument(
628 "host concat requires one dtype across parts",
629 ));
630 };
631 values.extend_from_slice(part);
632 }
633 Self::I32(values)
634 }
635 Self::U8(_) => {
636 let mut values = Vec::new();
637 for part in parts {
638 let Self::U8(part) = part else {
639 return Err(Error::invalid_argument(
640 "host concat requires one dtype across parts",
641 ));
642 };
643 values.extend_from_slice(part);
644 }
645 Self::U8(values)
646 }
647 })
648 }
649}
650
651#[derive(Clone, Debug)]
656pub struct HostTensor {
657 pub shape: Vec<usize>,
659 pub values: HostValues,
661}
662
663impl HostTensor {
664 pub fn new(shape: impl Into<Vec<usize>>, values: HostValues) -> Result<Self> {
671 let tensor = Self {
672 shape: shape.into(),
673 values,
674 };
675 tensor.check_count()?;
676 Ok(tensor)
677 }
678
679 pub fn num_elements(&self) -> usize {
681 self.shape.iter().product()
682 }
683
684 pub fn dtype(&self) -> DType {
686 self.values.dtype()
687 }
688
689 fn check_count(&self) -> Result<()> {
690 if self.num_elements() != self.values.len() {
691 return Err(Error::invalid_argument(
692 "host tensor shape and value count disagree",
693 ));
694 }
695 Ok(())
696 }
697
698 pub fn to_matrix_on(&self, engine: &Engine) -> Result<Matrix> {
704 self.check_count()?;
705 match &self.values {
706 HostValues::F32(values) => Matrix::new_from_slice_on(engine, self.shape.clone(), values),
707 HostValues::U32(values) => Matrix::new_from_slice_on(engine, self.shape.clone(), values),
708 HostValues::I32(values) => Matrix::new_from_slice_on(engine, self.shape.clone(), values),
709 HostValues::U8(values) => Matrix::new_from_slice_on(engine, self.shape.clone(), values),
710 }
711 }
712}
713
714#[derive(Clone, Debug)]
717pub struct HostSample {
718 pub x: HostTensor,
720 pub y: Option<HostTensor>,
722}
723
724#[derive(Clone, Debug)]
726pub struct HostBatch {
727 pub x: HostTensor,
729 pub y: Option<HostTensor>,
731}
732
733impl HostBatch {
734 pub fn upload_on(&self, engine: &Engine) -> Result<Batch> {
740 Ok(Batch {
741 x: self.x.to_matrix_on(engine)?,
742 y: self
743 .y
744 .as_ref()
745 .map(|label| label.to_matrix_on(engine))
746 .transpose()?,
747 })
748 }
749}
750
751pub fn collate_host(samples: &[HostSample]) -> Result<HostBatch> {
760 let first = samples
761 .first()
762 .ok_or_else(|| Error::invalid_argument("collate_host requires at least one sample"))?;
763 for sample in samples {
764 validate_host_component(&sample.x, &first.x)?;
765 match (&sample.y, &first.y) {
766 (Some(value), Some(reference)) => validate_host_component(value, reference)?,
767 (None, None) => {}
768 _ => {
769 return Err(Error::invalid_argument(
770 "collate_host label presence must match for every sample",
771 ));
772 }
773 }
774 }
775 let stack = |tensors: Vec<&HostTensor>| -> Result<HostTensor> {
776 let mut shape = tensors[0].shape.clone();
777 shape.insert(0, tensors.len());
778 HostTensor::new(
779 shape,
780 HostValues::concat(
781 &tensors
782 .iter()
783 .map(|tensor| &tensor.values)
784 .collect::<Vec<_>>(),
785 )?,
786 )
787 };
788 Ok(HostBatch {
789 x: stack(samples.iter().map(|sample| &sample.x).collect())?,
790 y: samples
791 .iter()
792 .filter_map(|sample| sample.y.as_ref())
793 .collect::<Vec<_>>()
794 .split_first()
795 .map(|_| stack(samples.iter().filter_map(|s| s.y.as_ref()).collect()))
796 .transpose()?,
797 })
798}
799
800fn validate_host_component(value: &HostTensor, reference: &HostTensor) -> Result<()> {
801 if value.num_elements() == 0
802 || value.shape != reference.shape
803 || value.dtype() != reference.dtype()
804 {
805 return Err(Error::invalid_argument(
806 "collate_host requires nonempty, same-shape, same-dtype components",
807 ));
808 }
809 Ok(())
810}
811
812pub trait HostDataset: Send + Sync {
820 fn len(&self) -> i64;
822
823 fn is_empty(&self) -> bool {
825 self.len() == 0
826 }
827
828 fn get_host_sample(&self, index: i64) -> Result<HostSample>;
834}
835
836pub struct HostTensorDataset {
842 x: HostTensor,
843 y: HostTensor,
844}
845
846impl HostTensorDataset {
847 pub fn new(x: HostTensor, y: HostTensor) -> Result<Self> {
854 if x.shape.is_empty() || y.shape.len() != 1 || x.shape[0] != y.shape[0] {
855 return Err(Error::invalid_argument(
856 "host tensor dataset requires [N, ...] features and [N] labels with equal counts",
857 ));
858 }
859 Ok(Self { x, y })
860 }
861
862 pub fn from_f32_matrices(x: &Matrix, y: &Matrix) -> Result<Self> {
873 if x.shape().is_empty() || y.shape().len() != 1 || x.shape()[0] != y.shape()[0] {
874 return Err(Error::invalid_argument(
875 "host tensor dataset requires [N, ...] features and [N] labels with equal counts",
876 ));
877 }
878 Self::new(
879 HostTensor::new(x.shape().to_vec(), HostValues::F32(x.read_f32()?))?,
880 HostTensor::new(y.shape().to_vec(), HostValues::F32(y.read_f32()?))?,
881 )
882 }
883}
884
885impl HostDataset for HostTensorDataset {
886 fn len(&self) -> i64 {
887 i64::try_from(self.x.shape[0]).unwrap_or(i64::MAX)
888 }
889
890 fn get_host_sample(&self, index: i64) -> Result<HostSample> {
891 let count = self.len();
892 if index < 0 || index >= count {
893 return Err(Error::invalid_argument(
894 "host tensor dataset index out of range",
895 ));
896 }
897 let index = usize::try_from(index)
898 .map_err(|_| Error::invalid_argument("host tensor dataset index out of range"))?;
899 let stride: usize = self.x.shape[1..].iter().product();
900 Ok(HostSample {
901 x: HostTensor::new(
902 self.x.shape[1..].to_vec(),
903 self.x.values.slice(index * stride, stride),
904 )?,
905 y: Some(HostTensor::new(vec![1], self.y.values.slice(index, 1))?),
906 })
907 }
908}
909
910pub struct PrefetchDataLoader {
923 dataset: Arc<dyn HostDataset>,
924 config: DataLoaderConfig,
925 prefetch_batches: usize,
926 receiver: Option<mpsc::Receiver<Result<HostBatch>>>,
927 worker: Option<JoinHandle<()>>,
928 epoch: u64,
929}
930
931impl PrefetchDataLoader {
932 pub fn new(
939 dataset: Arc<dyn HostDataset>,
940 config: DataLoaderConfig,
941 prefetch_batches: usize,
942 ) -> Result<Self> {
943 if config.batch_size <= 0 {
944 return Err(Error::invalid_argument(
945 "prefetch data loader batch size must be positive",
946 ));
947 }
948 if prefetch_batches == 0 {
949 return Err(Error::invalid_argument(
950 "prefetch data loader requires at least one queued batch",
951 ));
952 }
953 let mut loader = Self {
954 dataset,
955 config,
956 prefetch_batches,
957 receiver: None,
958 worker: None,
959 epoch: 0,
960 };
961 loader.spawn_epoch(0)?;
962 Ok(loader)
963 }
964
965 pub fn next_batch(&mut self) -> Result<Option<HostBatch>> {
975 let Some(receiver) = &self.receiver else {
976 return Ok(None);
977 };
978 match receiver.recv() {
979 Ok(Ok(batch)) => Ok(Some(batch)),
980 Ok(Err(error)) => {
981 self.receiver = None;
982 Err(error)
983 }
984 Err(mpsc::RecvError) => {
985 self.receiver = None;
986 Ok(None)
987 }
988 }
989 }
990
991 pub fn next_batch_on(&mut self, engine: &Engine) -> Result<Option<Batch>> {
997 self
998 .next_batch()?
999 .map(|batch| batch.upload_on(engine))
1000 .transpose()
1001 }
1002
1003 pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
1012 self.spawn_epoch(epoch)
1013 }
1014
1015 pub fn num_batches(&self) -> i64 {
1017 let n = self.dataset.len().max(0);
1018 let b = i64::from(self.config.batch_size);
1019 n / b + i64::from(!self.config.drop_last && n % b != 0)
1020 }
1021
1022 fn spawn_epoch(&mut self, epoch: u64) -> Result<()> {
1023 let mut indices = make_indices_host(self.dataset.len())?;
1024 if self.config.shuffle {
1025 shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
1026 }
1027 let (sender, receiver) = mpsc::sync_channel(self.prefetch_batches);
1028 let dataset = Arc::clone(&self.dataset);
1029 let batch_size = usize::try_from(self.config.batch_size)
1030 .map_err(|_| Error::invalid_argument("batch size must fit usize"))?;
1031 let drop_last = self.config.drop_last;
1032 self.receiver = Some(receiver);
1033 self.worker = Some(std::thread::spawn(move || {
1034 let mut start = 0_usize;
1035 while start < indices.len() {
1036 let count = batch_size.min(indices.len() - start);
1037 if drop_last && count < batch_size {
1038 break;
1039 }
1040 let produced = indices[start..start + count]
1041 .iter()
1042 .map(|&index| dataset.get_host_sample(index))
1043 .collect::<Result<Vec<_>>>()
1044 .and_then(|samples| collate_host(&samples));
1045 let keep_going = produced.is_ok();
1046 if sender.send(produced).is_err() || !keep_going {
1047 return;
1048 }
1049 start += count;
1050 }
1051 }));
1052 self.epoch = epoch;
1053 Ok(())
1054 }
1055}
1056
1057fn make_indices_host(count: i64) -> Result<Vec<i64>> {
1058 let length = usize::try_from(count)
1059 .map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
1060 let mut indices = Vec::new();
1061 indices
1062 .try_reserve_exact(length)
1063 .map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
1064 indices.extend(0..count);
1065 Ok(indices)
1066}