tc-collection 0.5.0

TinyChain's collection types
Documentation
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
use std::marker::PhantomData;
use std::sync::Arc;
use std::{fmt, io};

use async_trait::async_trait;
use destream::de;
use freqfs::*;
use futures::stream::{StreamExt, TryStreamExt};
use ha_ndarray::{
    AccessBuf, Array, ArrayBuf, ArrayOp, Buffer, BufferInstance, BufferMut, CType, Constant,
    Convert, NDArrayMathScalar, NDArrayRead, PlatformInstance, StackVec,
};
use itertools::Itertools;
use safecast::{AsType, CastFrom};

use tc_error::*;
use tc_transact::{fs, TxnId};
use tc_value::{DType, Number, NumberClass, NumberType};
use tcgeneric::ThreadSafe;

use crate::tensor::{offset_of, Coord, Shape, TensorInstance};

use super::access::DenseAccess;
use super::stream::BlockResize;
use super::{
    block_axis_for, block_map_for, block_shape_for, ideal_block_size_for, BlockShape, BlockStream,
    DenseCacheFile, DenseInstance, DenseWrite, DenseWriteGuard, DenseWriteLock,
};

pub struct DenseFile<FE, T> {
    dir: DirLock<FE>,
    block_map: ArrayBuf<u64, StackVec<u64>>,
    block_size: usize,
    shape: Shape,
    dtype: PhantomData<T>,
}

impl<FE, T> Clone for DenseFile<FE, T> {
    fn clone(&self) -> Self {
        Self {
            dir: self.dir.clone(),
            block_map: self.block_map.clone(),
            block_size: self.block_size,
            shape: self.shape.clone(),
            dtype: PhantomData,
        }
    }
}

impl<FE, T> DenseFile<FE, T>
where
    FE: DenseCacheFile + AsType<Buffer<T>>,
    T: CType + DType,
    Buffer<T>: de::FromStream<Context = ()>,
{
    pub async fn constant(dir: DirLock<FE>, shape: Shape, value: T) -> TCResult<Self> {
        shape.validate()?;

        let (block_size, num_blocks) = ideal_block_size_for(&shape);

        assert_ne!(block_size, 0);

        {
            let dtype_size = T::dtype().size();
            debug_assert_ne!(dtype_size, 0);

            let mut dir = dir.write().await;

            let platform = ha_ndarray::Platform::select(block_size);
            let last_block_id = num_blocks - 1;
            for block_id in 0..last_block_id {
                dir.create_file::<Buffer<T>>(
                    block_id.to_string(),
                    platform.constant(value, block_size)?,
                    block_size * dtype_size,
                )?;
            }

            let last_block_size = (shape.iter().product::<u64>() % block_size as u64) as usize;
            let last_block_size = if last_block_size == 0 {
                block_size
            } else {
                last_block_size
            };

            let platform = ha_ndarray::Platform::select(last_block_size);
            dir.create_file::<Buffer<T>>(
                last_block_id.to_string(),
                platform.constant(value, last_block_size)?,
                block_size * dtype_size,
            )?;
        };

        let block_axis = block_axis_for(&shape, block_size);
        let block_shape = block_shape_for(block_axis, &shape, block_size);
        let block_map = block_map_for(num_blocks as u64, &shape, &block_shape)?;

        Ok(Self {
            dir,
            block_map,
            block_size,
            shape,
            dtype: PhantomData,
        })
    }

    pub async fn copy_from<O>(dir: DirLock<FE>, txn_id: TxnId, other: O) -> TCResult<Self>
    where
        O: DenseInstance<DType = T>,
    {
        let shape = other.shape().clone();
        let (block_size, num_blocks) = ideal_block_size_for(&shape);
        let block_axis = block_axis_for(&shape, block_size);
        let block_shape = block_shape_for(block_axis, &shape, block_size);
        let block_map = block_map_for(num_blocks as u64, shape.as_slice(), &block_shape)?;

        let source_blocks = other.read_blocks(txn_id).await?;
        let mut source_blocks = BlockResize::new(source_blocks, block_shape)?;

        let mut dir_guard = dir.write().await;

        let mut block_id = 0;
        while let Some(block) = source_blocks.try_next().await? {
            let buffer = block.into_access().into_inner();

            if block_id == num_blocks - 1 {
                assert_ne!(buffer.len(), 0);
                assert_eq!(block_size % buffer.len(), 0);
            } else {
                assert_eq!(block_size, buffer.len());
            }

            let platform = ha_ndarray::Platform::select(buffer.len());
            let buffer = platform.convert(buffer.into())?;
            let size_in_bytes = buffer.len() * T::dtype().size();
            dir_guard.create_file(block_id.to_string(), buffer, size_in_bytes)?;
            block_id += 1;
        }

        if block_id != num_blocks {
            return Err(bad_request!("cannot create a tensor of shape {shape:?} from {num_blocks} blocks of size {block_size}"));
        }

        std::mem::drop(dir_guard);

        Ok(Self {
            dir,
            block_map,
            block_size,
            shape,
            dtype: PhantomData,
        })
    }

    pub async fn from_values(dir: DirLock<FE>, shape: Shape, values: Vec<Number>) -> TCResult<Self>
    where
        T: CastFrom<Number>,
    {
        shape.validate()?;

        if values.len() as u64 != shape.size() {
            return Err(bad_request!(
                "cannot construct a tensor of shape {shape:?} from {len} values",
                len = values.len()
            ));
        }

        let (block_size, num_blocks) = ideal_block_size_for(&shape);
        let block_axis = block_axis_for(&shape, block_size);
        let block_shape = block_shape_for(block_axis, &shape, block_size);
        let block_map = block_map_for(num_blocks as u64, shape.as_slice(), &block_shape)?;

        let blocks = values
            .into_iter()
            .map(|n| T::cast_from(n))
            .chunks(block_size);

        let mut dir_guard = dir.write().await;

        for (block_id, block) in blocks.into_iter().enumerate() {
            let buffer = block.collect::<Vec<T>>();
            let platform = ha_ndarray::Platform::select(buffer.len());
            let buffer = platform.convert(buffer.into())?;
            let size_in_bytes = buffer.len() * T::dtype().size();
            dir_guard.create_file(block_id.to_string(), buffer, size_in_bytes)?;
        }

        std::mem::drop(dir_guard);

        Ok(Self {
            dir,
            block_map,
            block_size,
            shape,
            dtype: PhantomData,
        })
    }

    pub async fn load(dir: DirLock<FE>, shape: Shape) -> TCResult<Self> {
        let contents = dir.write().await;

        if contents.is_empty() {
            #[cfg(debug_assertions)]
            panic!(
                "cannot load a dense tensor from an empty directory {}",
                contents.path().display()
            );

            #[cfg(not(debug_assertions))]
            return Err(bad_request!(
                "cannot load a dense tensor from an empty directory",
            ));
        }

        let mut size = 0u64;

        let block_size = {
            let block = contents
                .get_file(&0)
                .ok_or_else(|| internal!("tensor missing block 0"))?;

            let block: FileReadGuard<Buffer<T>> = block.read().await?;
            size += block.len() as u64;
            block.len()
        };

        let num_blocks = shape.size().div_ceil(block_size as u64);
        let block_axis = block_axis_for(&shape, block_size);
        let block_shape = block_shape_for(block_axis, &shape, block_size);

        for block_id in 1..(num_blocks - 1) {
            let block = contents
                .get_file(&block_id)
                .ok_or_else(|| internal!("tensor missing block {block_id}"))?;

            let block: FileReadGuard<Buffer<T>> = block.read().await?;
            if block.len() == block_size {
                size += block.len() as u64;
            } else {
                return Err(bad_request!(
                    "block {} has incorrect size {} (expected {})",
                    block_id,
                    block.len(),
                    block_size
                ));
            }
        }

        if num_blocks > 1 {
            let block_id = num_blocks - 1;
            let block = contents
                .get_file(&block_id)
                .ok_or_else(|| internal!("tensor missing block {block_id}"))?;

            let block: FileReadGuard<Buffer<T>> = block.read().await?;
            size += block.len() as u64;
        }

        std::mem::drop(contents);

        if size != shape.size() {
            return Err(bad_request!(
                "tensor blocks have incorrect total length {} (expected {} for shape {:?})",
                size,
                shape.size(),
                shape
            ));
        }

        let block_map = block_map_for(num_blocks as u64, shape.as_slice(), &block_shape)?;

        Ok(Self {
            dir,
            block_map,
            block_size,
            shape,
            dtype: PhantomData,
        })
    }

    pub async fn range(dir: DirLock<FE>, shape: Shape, start: T, stop: T) -> TCResult<Self>
    where
        T: fmt::Display,
    {
        Self::construct_with_op(dir, shape, |block_shape| {
            let arr = ArrayOp::range(start, stop, block_shape)?;
            let buf = arr.buffer()?.into_buffer()?;
            Ok(buf)
        })
        .await
    }

    async fn construct_with_op<Ctr>(
        dir: DirLock<FE>,
        shape: Shape,
        block_ctr: Ctr,
    ) -> TCResult<Self>
    where
        Ctr: Fn(BlockShape) -> TCResult<Buffer<T>> + Copy,
    {
        shape.validate()?;

        let size = shape.size();
        let (block_size, num_blocks) = ideal_block_size_for(&shape);
        let block_axis = block_axis_for(&shape, block_size);
        let block_shape = block_shape_for(block_axis, &shape, block_size);

        let mut blocks = futures::stream::iter(0..num_blocks as u64)
            .map(|block_id| {
                let mut block_shape = block_shape.clone();

                async move {
                    if (block_id + 1) * (block_size as u64) > size {
                        let block_size = (size - (block_id * block_size as u64)) as usize;
                        block_shape[0] = block_size / block_shape.iter().skip(1).product::<usize>();
                    }

                    block_ctr(block_shape).map(|buffer| (block_id, buffer))
                }
            })
            .buffered(num_cpus::get());

        let mut dir_guard = dir.write().await;

        let dtype_size = T::dtype().size();
        while let Some((block_id, buffer)) = blocks.try_next().await? {
            let size_in_bytes = dtype_size * buffer.len();
            dir_guard.create_file(block_id.to_string(), buffer, size_in_bytes)?;
        }

        std::mem::drop(dir_guard);

        let block_map = block_map_for(num_blocks as u64, &shape, &block_shape)?;

        Ok(Self {
            dir,
            block_map,
            block_size,
            shape,
            dtype: PhantomData,
        })
    }

    pub(super) async fn commit(&self)
    where
        FE: for<'en> fs::FileSave<'en>,
    {
        self.dir.sync().await.expect("commit")
    }
}

impl<FE> DenseFile<FE, f32>
where
    FE: DenseCacheFile + AsType<Buffer<f32>>,
{
    pub async fn random_normal(
        dir: DirLock<FE>,
        shape: Shape,
        mean: f32,
        std: f32,
    ) -> TCResult<Self> {
        Self::construct_with_op(dir, shape, |block_shape| {
            let arr = ArrayOp::random_normal(block_shape.iter().product())?
                .mul_scalar(std)?
                .add_scalar(mean)?;

            let buf = arr.buffer()?.into_buffer()?;

            Ok(buf)
        })
        .await
    }

    pub async fn random_uniform(dir: DirLock<FE>, shape: Shape) -> TCResult<Self> {
        Self::construct_with_op(dir, shape, |block_shape| {
            let arr = ArrayOp::random_uniform(block_shape.iter().product())?;
            let buf = arr.buffer()?.into_buffer()?;
            Ok(buf)
        })
        .await
    }
}

impl<FE, T> TensorInstance for DenseFile<FE, T>
where
    FE: ThreadSafe,
    T: DType + ThreadSafe,
{
    fn dtype(&self) -> NumberType {
        T::dtype()
    }

    fn shape(&self) -> &Shape {
        &self.shape
    }
}

#[async_trait]
impl<FE, T> DenseInstance for DenseFile<FE, T>
where
    FE: AsType<Buffer<T>> + ThreadSafe,
    T: CType + DType + 'static,
    Buffer<T>: de::FromStream<Context = ()>,
{
    type Block = AccessBuf<FileReadGuardOwned<FE, Buffer<T>>>;
    type DType = T;

    fn block_size(&self) -> usize {
        self.block_size
    }

    async fn read_block(
        &self,
        _txn_id: TxnId,
        block_id: u64,
    ) -> TCResult<Array<Self::DType, Self::Block>> {
        let dir = self.dir.read().await;

        let file = dir
            .get_file(&block_id)
            .ok_or_else(|| internal!("tensor missing block {block_id}"))?;

        let buffer = file.read_owned().await?;
        let block_axis = block_axis_for(self.shape(), self.block_size);
        let block_shape = block_shape_for(block_axis, &self.shape, buffer.len());
        ArrayBuf::new(buffer, block_shape).map_err(TCError::from)
    }

    async fn read_blocks(self, _txn_id: TxnId) -> TCResult<BlockStream<Self::DType, Self::Block>> {
        let shape = self.shape;
        let block_axis = block_axis_for(&shape, self.block_size);
        let block_map = self.block_map.into_access().into_inner();
        let dir = self.dir.into_read().await;

        log::debug!("read blocks {block_map:?} from dense file");

        let blocks = futures::stream::iter(block_map)
            .map(move |block_id| {
                dir.get_file(&block_id).cloned().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::NotFound, format!("tensor block {block_id}"))
                })
            })
            .map_ok(|block| block.into_read())
            .try_buffered(num_cpus::get())
            .map(move |result| {
                let buffer = result?;
                let block_shape = block_shape_for(block_axis, &shape, buffer.len());
                ArrayBuf::new(buffer, block_shape).map_err(TCError::from)
            });

        Ok(Box::pin(blocks))
    }

    async fn read_value(&self, txn_id: TxnId, coord: Coord) -> TCResult<Self::DType> {
        self.shape().validate_coord(&coord)?;

        let offset = offset_of(coord, self.shape());
        let block_id = offset / self.block_size() as u64;
        let block_offset = (offset % self.block_size() as u64) as usize;

        let block = self.read_block(txn_id, block_id).await?;
        let buffer = block.buffer()?;
        Ok(buffer.to_slice()?.as_ref()[block_offset])
    }
}

#[async_trait]
impl<'a, FE, T> DenseWrite for DenseFile<FE, T>
where
    FE: AsType<Buffer<T>> + ThreadSafe,
    T: CType + DType + 'static,
    Buffer<T>: de::FromStream<Context = ()>,
{
    type BlockWrite = AccessBuf<FileWriteGuardOwned<FE, Buffer<T>>>;

    async fn write_block(
        &self,
        _txn_id: TxnId,
        block_id: u64,
    ) -> TCResult<Array<Self::DType, Self::BlockWrite>> {
        let dir = self.dir.read().await;
        let file = dir
            .get_file(&block_id)
            .ok_or_else(|| internal!("tensor missing block {block_id}"))?;

        let buffer = file.write_owned().await?;
        let block_axis = block_axis_for(self.shape(), self.block_size);
        let block_shape = block_shape_for(block_axis, &self.shape, buffer.len());
        ArrayBuf::new(buffer, block_shape).map_err(TCError::from)
    }

    async fn write_blocks(
        self,
        _txn_id: TxnId,
    ) -> TCResult<BlockStream<Self::DType, Self::BlockWrite>> {
        let shape = self.shape;
        let block_axis = block_axis_for(&shape, self.block_size);
        let dir = self.dir.into_read().await;

        let blocks = futures::stream::iter(self.block_map.into_access().into_inner())
            .map(move |block_id| {
                dir.get_file(&block_id).cloned().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::NotFound, format!("tensor block {block_id}"))
                })
            })
            .map_ok(|block| block.into_write())
            .try_buffered(num_cpus::get())
            .map(move |result| {
                let buffer = result?;
                let block_shape = block_shape_for(block_axis, &shape, buffer.len());
                ArrayBuf::new(buffer, block_shape).map_err(TCError::from)
            });

        Ok(Box::pin(blocks))
    }
}

#[async_trait]
impl<'a, FE, T> DenseWriteLock<'a> for DenseFile<FE, T>
where
    FE: AsType<Buffer<T>> + ThreadSafe,
    T: CType + DType,
    Buffer<T>: de::FromStream<Context = ()>,
{
    type WriteGuard = DenseFileWriteGuard<'a, FE>;

    async fn write(&'a self) -> Self::WriteGuard {
        let dir = self.dir.read().await;

        DenseFileWriteGuard {
            dir: Arc::new(dir),
            block_size: self.block_size,
            shape: &self.shape,
        }
    }
}

macro_rules! impl_from_stream {
    ($t:ty, $decode:ident) => {
        #[async_trait]
        impl<FE> de::FromStream for DenseFile<FE, $t>
        where
            FE: AsType<Buffer<$t>> + ThreadSafe,
        {
            type Context = (DirLock<FE>, Shape);

            async fn from_stream<D: de::Decoder>(
                cxt: Self::Context,
                decoder: &mut D,
            ) -> Result<Self, D::Error> {
                let (dir, shape) = cxt;
                decoder.$decode(DenseVisitor::new(dir, shape)).await
            }
        }
    };
}

impl_from_stream!(f32, decode_array_f32);
impl_from_stream!(f64, decode_array_f64);
impl_from_stream!(i16, decode_array_i16);
impl_from_stream!(i32, decode_array_i32);
impl_from_stream!(i64, decode_array_i64);
impl_from_stream!(u8, decode_array_u8);
impl_from_stream!(u16, decode_array_u16);
impl_from_stream!(u32, decode_array_u32);
impl_from_stream!(u64, decode_array_u64);

impl<Txn, FE, T: CType> From<DenseFile<FE, T>> for DenseAccess<Txn, FE, T> {
    fn from(file: DenseFile<FE, T>) -> Self {
        Self::File(file)
    }
}

impl<FE, T> fmt::Debug for DenseFile<FE, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "dense tensor with shape {:?}", self.shape)
    }
}

pub struct DenseFileWriteGuard<'a, FE> {
    dir: Arc<DirReadGuard<'a, FE>>,
    block_size: usize,
    shape: &'a Shape,
}

impl<'a, FE> DenseFileWriteGuard<'a, FE> {
    pub async fn merge<T>(&self, other: DirLock<FE>) -> TCResult<()>
    where
        FE: AsType<Buffer<T>> + ThreadSafe,
        T: CType + DType + 'static,
        Buffer<T>: de::FromStream<Context = ()>,
    {
        let num_blocks = self.shape.size().div_ceil(self.block_size as u64);
        futures::stream::iter(0..num_blocks)
            .map(move |block_id| {
                let that = other.clone();

                async move {
                    let that = that.read().await;
                    if that.contains(&block_id) {
                        let mut this = self.dir.write_file(&block_id).await?;
                        let that = that.read_file(&block_id).await?;
                        this.write(that.read()).map_err(TCError::from)
                    } else {
                        Ok(())
                    }
                }
            })
            .buffer_unordered(num_cpus::get())
            .try_fold((), |(), _| futures::future::ready(Ok(())))
            .await
    }
}

#[async_trait]
impl<'a, FE, T> DenseWriteGuard<T> for DenseFileWriteGuard<'a, FE>
where
    FE: AsType<Buffer<T>> + ThreadSafe,
    T: CType + DType + 'static,
    Buffer<T>: de::FromStream<Context = ()>,
{
    async fn overwrite<O: DenseInstance<DType = T>>(
        &self,
        txn_id: TxnId,
        other: O,
    ) -> TCResult<()> {
        let block_axis = block_axis_for(&self.shape, self.block_size);
        let block_shape = block_shape_for(block_axis, &self.shape, self.block_size);

        let blocks = other.read_blocks(txn_id).await?;
        let blocks = BlockResize::new(blocks, block_shape)?;

        blocks
            .enumerate()
            .map(|(block_id, result)| {
                let dir = self.dir.clone();

                async move {
                    let mut block = dir.write_file(&block_id).await?;

                    let data = result?;
                    let data = data.buffer()?;
                    debug_assert_eq!(block.len(), data.len());
                    block.write(data)?;

                    Result::<(), TCError>::Ok(())
                }
            })
            .buffered(num_cpus::get())
            .try_fold((), |(), ()| futures::future::ready(Ok(())))
            .await
    }

    async fn overwrite_value(&self, _txn_id: TxnId, value: T) -> TCResult<()> {
        let num_blocks = self.shape.size().div_ceil(self.block_size as u64);

        futures::stream::iter(0..num_blocks)
            .map(|block_id| async move {
                let mut block = self.dir.write_file(&block_id).await?;
                block.write_value(value).map_err(TCError::from)
            })
            .buffered(num_cpus::get())
            .try_fold((), |(), _| futures::future::ready(Ok(())))
            .await
    }

    async fn write_value(&self, _txn_id: TxnId, coord: Coord, value: T) -> TCResult<()> {
        self.shape.validate_coord(&coord)?;

        let offset = offset_of(coord, &self.shape);
        let block_id = offset / self.block_size as u64;

        let mut block = self.dir.write_file(&block_id).await?;
        block.write_value_at((offset % self.block_size as u64) as usize, value)?;

        Ok(())
    }
}

struct DenseVisitor<FE, T> {
    dir: DirLock<FE>,
    shape: Shape,
    dtype: PhantomData<T>,
}

impl<FE, T> DenseVisitor<FE, T> {
    fn new(dir: DirLock<FE>, shape: Shape) -> Self {
        Self {
            dir,
            shape,
            dtype: PhantomData,
        }
    }
}

macro_rules! impl_visitor {
    ($t:ty, $visit:ident) => {
        #[async_trait]
        impl<FE> de::Visitor for DenseVisitor<FE, $t>
        where
            FE: AsType<Buffer<$t>> + ThreadSafe,
        {
            type Value = DenseFile<FE, $t>;

            fn expecting() -> &'static str {
                "dense tensor data"
            }

            async fn $visit<A: de::ArrayAccess<$t>>(
                self,
                mut array: A,
            ) -> Result<Self::Value, A::Error> {
                let size = self.shape.iter().product::<u64>();
                let mut contents = self.dir.write().await;

                let (block_size, num_blocks) = ideal_block_size_for(&self.shape);

                let zero = <$t>::ZERO;
                let type_size = <$t>::dtype().size();
                let mut buffer = vec![zero; block_size];
                for block_id in 0..num_blocks {
                    let buffered = array.buffer(&mut buffer).await?;

                    let buffer = if block_id == num_blocks - 1 {
                        let expected_block_size =
                            (size - (block_size as u64 * block_id as u64)) as usize;

                        if buffered == expected_block_size {
                            Ok(buffer.drain(..).collect::<Vec<$t>>())
                        } else {
                            Err(de::Error::invalid_length(
                                buffered,
                                format!(
                                    "a trailing Tensor block of {expected_block_size} elements"
                                ),
                            ))
                        }
                    } else if buffer.len() == block_size {
                        Ok(buffer.drain(..).collect::<Vec<$t>>())
                    } else {
                        Err(de::Error::invalid_length(
                            buffered,
                            format!("a Tensor block of {block_size} elements"),
                        ))
                    }?;

                    let platform = ha_ndarray::Platform::select(buffer.len());
                    let buffer = platform.convert(buffer.into()).map_err(de::Error::custom)?;

                    contents
                        .create_file(block_id.to_string(), buffer, buffered * type_size)
                        .map_err(de::Error::custom)?;
                }

                std::mem::drop(contents);

                let block_axis = block_axis_for(&self.shape, block_size);
                let block_shape = block_shape_for(block_axis, &self.shape, block_size);
                let block_map = block_map_for(num_blocks as u64, &self.shape, &block_shape)
                    .map_err(de::Error::custom)?;

                Ok(DenseFile {
                    dir: self.dir,
                    block_map,
                    block_size,
                    shape: self.shape,
                    dtype: PhantomData,
                })
            }
        }
    };
}

impl_visitor!(f32, visit_array_f32);
impl_visitor!(f64, visit_array_f64);
impl_visitor!(i16, visit_array_i16);
impl_visitor!(i32, visit_array_i32);
impl_visitor!(i64, visit_array_i64);
impl_visitor!(u8, visit_array_u8);
impl_visitor!(u16, visit_array_u16);
impl_visitor!(u32, visit_array_u32);
impl_visitor!(u64, visit_array_u64);