frozen-core 0.0.10

Custom implementations and core utilities for frozen codebases
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Custom implementation of `std::fs::File`
//!
//! ## Example
//!
//! ```
//! use frozen_core::ffile::{FrozenFile, FFCfg};
//!
//! let dir = tempfile::tempdir().unwrap();
//! let path = dir.path().join("tmp_frozen_file");
//!
//! let cfg = FFCfg {
//!     mid: 0x00,
//!     chunk_size: 0x10,
//!     path: path.to_path_buf(),
//!     initial_chunk_amount: 0x0A,
//! };
//!
//! let file = FrozenFile::new(cfg.clone()).unwrap();
//! assert_eq!(file.length().unwrap(), 0x10 * 0x0A);
//!
//! let mut data = vec![1u8; 0x10];
//! assert!(file.pwrite(data.as_mut_ptr(), 0).is_ok());
//! assert!(file.sync().is_ok());
//!
//! let mut buf = vec![0u8; data.len()];
//! assert!(file.pread(buf.as_mut_ptr(), 0).is_ok());
//! assert_eq!(buf, data);
//!
//! assert!(FrozenFile::new(cfg.clone()).is_err());
//!
//! assert!(file.delete().is_ok());
//! assert!(!path.exists());
//!
//! drop(file);
//! assert!(FrozenFile::new(cfg).is_ok());
//! ```

#[cfg(any(target_os = "linux", target_os = "macos"))]
mod posix;

use crate::error::{FrozenErr, FrozenRes};

/// file descriptor for [`FrozenFile`]
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub type FFId = libc::c_int;

#[cfg(any(target_os = "linux", target_os = "macos"))]
type TFile = posix::POSIXFile;

/// Domain Id for [`FrozenFile`] is **17**
const ERRDOMAIN: u8 = 0x11;

/// module id used for [`FrozenErr`]
static mut MODULE_ID: u8 = 0;

/// Error codes for [`FrozenFile`]
#[repr(u16)]
pub enum FFileErr {
    /// (256) internal fuck up (hault and catch fire)
    Hcf = 0x100,

    /// (257) unknown error (fallback)
    Unk = 0x101,

    /// (258) no more space available
    Nsp = 0x102,

    /// (259) syncing error
    Syn = 0x103,

    /// (260) no write/read perm
    Prm = 0x104,

    /// (261) invalid path
    Inv = 0x105,

    /// (262) corrupted file
    Cpt = 0x106,

    /// (265) unable to grow
    Grw = 0x107,

    /// (266) unable to lock
    Lck = 0x108,

    /// (267) locks exhausted (mainly on nfs)
    Lex = 0x109,
}

impl FFileErr {
    #[inline]
    fn default_message(&self) -> &'static [u8] {
        match self {
            Self::Inv => b"invalid file path",
            Self::Unk => b"unknown error type",
            Self::Hcf => b"hault and catch fire",
            Self::Grw => b"unable to grow the file",
            Self::Prm => b"missing write/read permissions",
            Self::Nsp => b"no space left on storage device",
            Self::Cpt => b"file is either invalid or corrupted",
            Self::Syn => b"failed to sync/flush data to storage device",
            Self::Lex => b"failed to obtain lock, as no more locks available",
            Self::Lck => b"failed to obtain exclusive lock, file may already be open",
        }
    }
}

#[inline]
pub(in crate::ffile) fn new_err<R>(res: FFileErr, message: Vec<u8>) -> FrozenRes<R> {
    let detail = res.default_message();
    let err = FrozenErr::new(unsafe { MODULE_ID }, ERRDOMAIN, res as u16, detail, message);
    Err(err)
}

#[inline]
pub(in crate::ffile) fn new_err_default<R>(res: FFileErr) -> FrozenRes<R> {
    let detail = res.default_message();
    let err = FrozenErr::new(
        unsafe { MODULE_ID },
        ERRDOMAIN,
        res as u16,
        detail,
        Vec::with_capacity(0),
    );
    Err(err)
}

/// Config for [`FrozenFile`]
#[derive(Debug, Clone)]
pub struct FFCfg {
    /// Module id used for error logging
    pub mid: u8,

    /// Path for the file
    ///
    /// *NOTE:* The caller must make sure that the parent directory exists
    pub path: std::path::PathBuf,

    /// Size (in bytes) of a single chunk on fs
    ///
    /// A chunk is a smalled fixed size allocation and addressing unit used by
    /// [`FrozenFile`] for all the write/read ops, which are operated by index
    /// of the chunk and not the offset of the byte
    pub chunk_size: usize,

    /// Number of chunks to pre-allocate when [`FrozenFile`] is initialized
    ///
    /// Initial file length will be `chunk_size * initial_chunk_amount` (bytes)
    pub initial_chunk_amount: usize,
}

/// Custom implementation of `std::fs::File`
///
/// ## Example
///
/// ```
/// use frozen_core::ffile::{FrozenFile, FFCfg};
///
/// let dir = tempfile::tempdir().unwrap();
/// let path = dir.path().join("tmp_frozen_file");
///
/// let cfg = FFCfg {
///     mid: 0x00,
///     chunk_size: 0x10,
///     path: path.to_path_buf(),
///     initial_chunk_amount: 0x0A,
/// };
///
/// let file = FrozenFile::new(cfg.clone()).unwrap();
/// assert_eq!(file.length().unwrap(), 0x10 * 0x0A);
///
/// let mut data = vec![1u8; 0x10];
/// assert!(file.pwrite(data.as_mut_ptr(), 0).is_ok());
/// assert!(file.sync().is_ok());
///
/// let mut buf = vec![0u8; data.len()];
/// assert!(file.pread(buf.as_mut_ptr(), 0).is_ok());
/// assert_eq!(buf, data);
///
/// assert!(FrozenFile::new(cfg.clone()).is_err());
///
/// assert!(file.delete().is_ok());
/// assert!(!path.exists());
///
/// drop(file);
/// assert!(FrozenFile::new(cfg).is_ok());
/// ```
#[derive(Debug)]
pub struct FrozenFile {
    cfg: FFCfg,
    file: core::cell::UnsafeCell<core::mem::ManuallyDrop<TFile>>,
}

unsafe impl Send for FrozenFile {}
unsafe impl Sync for FrozenFile {}

impl FrozenFile {
    /// Fetch config used for [`FrozenFile`]
    #[inline]
    pub fn cfg(&self) -> &FFCfg {
        &self.cfg
    }

    /// Read current length of [`FrozenFile`]
    #[inline]
    pub fn length(&self) -> FrozenRes<usize> {
        unsafe { self.get_file().length() }
    }

    /// Get file descriptor for [`FrozenFile`]
    #[inline]
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub fn fd(&self) -> i32 {
        self.get_file().fd()
    }

    /// Check if [`FrozenFile`] exists on the fs
    pub fn exists(&self) -> FrozenRes<bool> {
        unsafe { TFile::exists(&self.cfg.path) }
    }

    /// Create a new or open an existing [`FrozenFile`]
    ///
    /// ## [`FFCfg`]
    ///
    /// All configs for [`FrozenFile`] are stored in [`FFCfg`]
    ///
    /// ## Important
    ///
    /// The `cfg` must not change any of its properties for the entire life of [`FrozenFile`],
    /// one must use config stores like [`Rta`](https://crates.io/crates/rta) to store config
    ///
    /// ## Multiple Instances
    ///
    /// We acquire an exclusive lock for the entire file, this protects against operating with
    /// multiple simultenious instance of [`FrozenFile`], when trying to call [`FrozenFile::new`]
    /// when already called, [`FFileErr::Lck`] error will be thrown
    ///
    /// ## Example
    ///
    /// ```
    /// use frozen_core::ffile::{FrozenFile, FFCfg};
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("tmp_frozen_file");
    ///
    /// let cfg = FFCfg {
    ///     mid: 0x00,
    ///     chunk_size: 0x10,
    ///     path: path.to_path_buf(),
    ///     initial_chunk_amount: 0x0A,
    /// };
    ///
    /// let file = FrozenFile::new(cfg).unwrap();
    /// assert_eq!(file.length().unwrap(), 0x10 * 0x0A);
    ///```
    pub fn new(cfg: FFCfg) -> FrozenRes<Self> {
        let raw_file = unsafe { posix::POSIXFile::new(&cfg.path) }?;
        let slf = Self {
            cfg: cfg.clone(),
            file: core::cell::UnsafeCell::new(core::mem::ManuallyDrop::new(raw_file)),
        };

        let file = slf.get_file();

        // INFO: right after open is successful, we must obtain an exclusive lock on the
        // entire file, hence when another instance of [`FrozenFile`], when trying to access
        // the same file, would correctly fail, while again obtaining the lock
        unsafe { file.flock() }?;

        // NOTE: we only set it the module_id once, right after an exclusive lock for the entire file is
        // acquired, hence it'll be only set once per instance and is only used for error logging
        unsafe { MODULE_ID = cfg.mid };

        let curr_len = slf.length()?;
        let init_len = cfg.chunk_size * cfg.initial_chunk_amount;

        match curr_len {
            0 => slf.grow(cfg.initial_chunk_amount)?,
            _ => {
                // NOTE: we can treat this invariants as errors only because, our system guarantees,
                // whenever file size is updated, i.e. has grown, it'll always be a multiple of `chunk_size`,
                // and will have minimum of `chunk_size * initial_chunk_amount` (bytes) as the length, although
                // it only holds true when any of params in `cfg` are never updated after the file is created
                if (curr_len < init_len) || (curr_len % cfg.chunk_size != 0) {
                    // INFO:
                    // - close the file to avoid resource leaks
                    // - we supress the close error, as we are already in an errored state
                    let _ = unsafe { file.close() };
                    return new_err_default(FFileErr::Cpt);
                }
            }
        }

        Ok(slf)
    }

    /// Grow file size of [`FrozenFile`] by given `count` of chunks
    ///
    /// ## Example
    ///
    /// ```
    /// use frozen_core::ffile::{FrozenFile, FFCfg};
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("tmp_frozen_file");
    ///
    /// let cfg = FFCfg {
    ///     mid: 0x00,
    ///     chunk_size: 0x10,
    ///     path: path.to_path_buf(),
    ///     initial_chunk_amount: 0x0A,
    /// };
    ///
    /// let file = FrozenFile::new(cfg).unwrap();
    /// assert_eq!(file.length().unwrap(), 0x10 * 0x0A);
    ///
    /// file.grow(0x20).unwrap();
    /// assert_eq!(file.length().unwrap(), 0x10 * (0x0A + 0x20));
    ///```    
    pub fn grow(&self, count: usize) -> FrozenRes<()> {
        let curr_len = self.length()?;
        let len_to_add = self.cfg.chunk_size * count;

        unsafe { self.get_file().grow(curr_len, len_to_add) }
    }

    /// Syncs in-mem data on the storage device
    pub fn sync(&self) -> FrozenRes<()> {
        let file = self.get_file();
        unsafe { file.sync() }
    }

    /// Initiates writeback (best-effort) of dirty pages in the specified range
    #[cfg(target_os = "linux")]
    pub fn sync_range(&self, index: usize, count: usize) -> FrozenRes<()> {
        let offset = self.cfg.chunk_size * index;
        let len_to_sync = self.cfg.chunk_size * count;
        let file = self.get_file();

        unsafe { file.sync_range(offset, len_to_sync) }
    }

    /// Delete [`FrozenFile`] from fs
    ///
    /// ## Example
    ///
    /// ```
    /// use frozen_core::ffile::{FrozenFile, FFCfg};
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("tmp_frozen_file");
    ///
    /// let cfg = FFCfg {
    ///     mid: 0x00,
    ///     chunk_size: 0x10,
    ///     path: path.to_path_buf(),
    ///     initial_chunk_amount: 0x0A,
    /// };
    ///
    /// let file = FrozenFile::new(cfg).unwrap();
    /// assert!(file.exists().unwrap());
    ///
    /// file.delete().unwrap();
    /// assert!(!file.exists().unwrap());
    ///```
    pub fn delete(&self) -> FrozenRes<()> {
        let file = self.get_file();
        unsafe { file.unlink(&self.cfg.path) }
    }

    /// Read a single chunk at given `index` w/ `pread` syscall
    #[inline(always)]
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub fn pread(&self, buf: *mut u8, index: usize) -> FrozenRes<()> {
        let offset = self.cfg.chunk_size * index;
        let file = self.get_file();

        unsafe { file.pread(buf, offset, self.cfg.chunk_size) }
    }

    /// Write a single chunk at given `index` w/ `pwrite` syscall
    #[inline(always)]
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub fn pwrite(&self, buf: *mut u8, index: usize) -> FrozenRes<()> {
        let offset = self.cfg.chunk_size * index;
        let file = self.get_file();

        unsafe { file.pwrite(buf, offset, self.cfg.chunk_size) }
    }

    /// Read multiple chunks starting from given `index` till `bufs.len()` w/ `preadv` syscall
    #[inline(always)]
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub fn preadv(&self, bufs: &[*mut u8], index: usize) -> FrozenRes<()> {
        let offset = self.cfg.chunk_size * index;
        let file = self.get_file();

        unsafe { file.preadv(bufs, offset, self.cfg.chunk_size) }
    }

    /// Write multiple chunks starting from given `index` till `bufs.len()` w/ `pwritev` syscall
    #[inline(always)]
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub fn pwritev(&self, bufs: &[*mut u8], index: usize) -> FrozenRes<()> {
        let offset = self.cfg.chunk_size * index;
        let file = self.get_file();

        unsafe { file.pwritev(bufs, offset, self.cfg.chunk_size) }
    }

    #[inline]
    fn get_file(&self) -> &core::mem::ManuallyDrop<TFile> {
        unsafe { &*self.file.get() }
    }
}

impl Drop for FrozenFile {
    fn drop(&mut self) {
        // guard for when delete is called (or drop on drop if its somehow possible)
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        if self.fd() == posix::CLOSED_FD {
            return;
        }

        // sync if dirty & close
        let _ = self.sync();
        let _ = unsafe { self.get_file().close() };
    }
}

impl core::fmt::Display for FrozenFile {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "FrozenFile {{fd: {}, len: {}}}",
            self.fd(),
            self.length().unwrap_or(0),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::TEST_MID;
    use std::sync::Arc;

    const CHUNK_SIZE: usize = 0x10;
    const INIT_CHUNKS: usize = 0x0A;

    fn tmp_path() -> (tempfile::TempDir, FFCfg) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tmp_ff_file");
        let cfg = FFCfg {
            path,
            mid: TEST_MID,
            chunk_size: CHUNK_SIZE,
            initial_chunk_amount: INIT_CHUNKS,
        };

        (dir, cfg)
    }

    mod ff_lifecycle {
        use super::*;

        #[test]
        fn ok_new_with_init_len() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            let exists = file.exists().unwrap();
            assert!(exists);

            assert_eq!(file.length().unwrap(), CHUNK_SIZE * INIT_CHUNKS);
        }

        #[test]
        fn ok_new_existing() {
            let (_dir, cfg) = tmp_path();

            let file = FrozenFile::new(cfg.clone()).unwrap();
            assert_eq!(file.length().unwrap(), CHUNK_SIZE * INIT_CHUNKS);

            // must be dropped to release the exclusive lock
            drop(file);

            let reopened = FrozenFile::new(cfg.clone()).unwrap();
            assert_eq!(reopened.length().unwrap(), CHUNK_SIZE * INIT_CHUNKS);
        }

        #[test]
        fn err_new_when_file_smaller_than_init_len() {
            let (_dir, mut cfg) = tmp_path();

            let file = FrozenFile::new(cfg.clone()).unwrap();
            drop(file);

            // updated cfg
            cfg.chunk_size *= 2;

            let err = FrozenFile::new(cfg).unwrap_err();
            assert!(err.compare(FFileErr::Cpt as u16));
        }

        #[test]
        fn ok_exists_true_when_exists() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            let exists = file.exists().unwrap();
            assert!(exists);
        }

        #[test]
        fn ok_exists_false_when_missing() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();
            file.delete().unwrap();

            let exists = file.exists().unwrap();
            assert!(!exists);
        }

        #[test]
        fn ok_delete_file() {
            let (_dir, cfg) = tmp_path();

            let file = FrozenFile::new(cfg).unwrap();
            let exists = file.exists().unwrap();
            assert!(exists);

            file.delete().unwrap();
            let exists = file.exists().unwrap();
            assert!(!exists);
        }

        #[test]
        fn err_delete_after_delete() {
            let (_dir, cfg) = tmp_path();

            let file = FrozenFile::new(cfg).unwrap();
            file.delete().unwrap();

            let err = file.delete().unwrap_err();
            assert!(err.compare(FFileErr::Inv as u16));
        }

        #[test]
        fn ok_drop_persists_without_explicit_sync() {
            let mut data = [0x0Bu8; CHUNK_SIZE];
            let (_dir, cfg) = tmp_path();

            {
                let file = FrozenFile::new(cfg.clone()).unwrap();
                file.pwrite(data.as_mut_ptr(), 0).unwrap();
                drop(file);
            }

            {
                let reopened = FrozenFile::new(cfg).unwrap();
                let mut buf = [0u8; CHUNK_SIZE];

                reopened.pread(buf.as_mut_ptr(), 0).unwrap();
                assert_eq!(buf, data);
            }
        }
    }

    mod ff_lock {
        use super::*;

        #[test]
        fn err_new_when_already_open() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg.clone()).unwrap();

            let err = FrozenFile::new(cfg).unwrap_err();
            assert!(err.compare(FFileErr::Lck as u16));

            drop(file);
        }

        #[test]
        fn ok_drop_releases_exclusive_lock() {
            let (_dir, cfg) = tmp_path();

            let file = FrozenFile::new(cfg.clone()).unwrap();
            drop(file);

            let _ = FrozenFile::new(cfg).expect("must not fail after drop");
        }
    }

    mod ff_grow {
        use super::*;

        #[test]
        fn ok_grow_updates_length() {
            let (_dir, cfg) = tmp_path();

            let file = FrozenFile::new(cfg).unwrap();
            assert_eq!(file.length().unwrap(), CHUNK_SIZE * INIT_CHUNKS);

            file.grow(0x20).unwrap();
            assert_eq!(file.length().unwrap(), CHUNK_SIZE * (INIT_CHUNKS + 0x20));
        }

        #[test]
        fn ok_grow_sync_cycle() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            for _ in 0..0x0A {
                file.grow(0x100).unwrap();
                file.sync().unwrap();
            }

            assert_eq!(file.length().unwrap(), CHUNK_SIZE * (INIT_CHUNKS + (0x0A * 0x100)));
        }
    }

    mod ff_sync {
        use super::*;

        #[test]
        fn ok_sync_after_sync() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            file.sync().unwrap();
            file.sync().unwrap();
            file.sync().unwrap();
        }

        #[test]
        fn err_sync_after_delete() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();
            file.delete().unwrap();

            let err = file.sync().unwrap_err();
            assert!(err.compare(FFileErr::Hcf as u16));
        }
    }

    mod ff_write_read {
        use super::*;

        #[test]
        fn ok_single_write_read_cycle() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            let mut data = [0x0Bu8; CHUNK_SIZE];

            file.pwrite(data.as_mut_ptr(), 4).unwrap();
            file.sync().unwrap();

            let mut buf = [0u8; CHUNK_SIZE];
            file.pread(buf.as_mut_ptr(), 4).unwrap();
            assert_eq!(buf, data);
        }

        #[test]
        fn ok_vectored_write_read_cycle() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            let mut bufs = [[1u8; CHUNK_SIZE], [2u8; CHUNK_SIZE]];
            let bufs: Vec<*mut u8> = bufs.iter_mut().map(|b| b.as_mut_ptr()).collect();

            file.pwritev(&bufs, 0).unwrap();
            file.sync().unwrap();

            let mut read_bufs = [[0u8; CHUNK_SIZE], [0u8; CHUNK_SIZE]];
            let rbufs: Vec<*mut u8> = read_bufs.iter_mut().map(|b| b.as_mut_ptr()).collect();
            file.preadv(&rbufs, 0).unwrap();

            assert!(read_bufs[0].iter().all(|b| *b == 1));
            assert!(read_bufs[1].iter().all(|b| *b == 2));
        }

        #[test]
        fn ok_write_concurrent_non_overlapping() {
            let (_dir, mut cfg) = tmp_path();
            cfg.initial_chunk_amount = 0x100;
            let file = Arc::new(FrozenFile::new(cfg).unwrap());

            let mut handles = vec![];
            for i in 0..0x0A {
                let f = file.clone();
                handles.push(std::thread::spawn(move || {
                    let mut data = [i as u8; CHUNK_SIZE];
                    f.pwrite(data.as_mut_ptr(), i).unwrap();
                }));
            }

            for h in handles {
                h.join().unwrap();
            }

            file.sync().unwrap();

            for i in 0..0x0A {
                let mut buf = [0u8; CHUNK_SIZE];
                file.pread(buf.as_mut_ptr(), i).unwrap();
                assert!(buf.iter().all(|b| *b == i as u8));
            }
        }

        #[test]
        fn ok_concurrent_grow_and_write() {
            let (_dir, cfg) = tmp_path();
            let file = Arc::new(FrozenFile::new(cfg).unwrap());

            let writer = {
                let f = file.clone();
                std::thread::spawn(move || {
                    for i in 0..INIT_CHUNKS {
                        let mut data = [i as u8; CHUNK_SIZE];
                        f.pwrite(data.as_mut_ptr(), i).unwrap();
                    }
                })
            };

            let chunks_to_grow = 0x20;
            let grower = {
                let f = file.clone();
                std::thread::spawn(move || {
                    f.grow(chunks_to_grow).unwrap();
                })
            };

            writer.join().unwrap();
            grower.join().unwrap();

            file.sync().unwrap();
            assert_eq!(file.length().unwrap(), CHUNK_SIZE * (INIT_CHUNKS + chunks_to_grow));

            for i in 0..INIT_CHUNKS {
                let mut buf = [0u8; CHUNK_SIZE];
                file.pread(buf.as_mut_ptr(), i).unwrap();
                assert!(buf.iter().all(|b| *b == i as u8));
            }
        }

        #[test]
        fn ok_concurrent_sync_and_write() {
            let (_dir, cfg) = tmp_path();
            let file = Arc::new(FrozenFile::new(cfg).unwrap());

            let writer = {
                let f = file.clone();
                std::thread::spawn(move || {
                    for i in 0..INIT_CHUNKS {
                        let mut data = [i as u8; CHUNK_SIZE];
                        f.pwrite(data.as_mut_ptr(), i).unwrap();
                    }
                })
            };

            let syncer = {
                let f = file.clone();
                std::thread::spawn(move || {
                    for _ in 0..0x0A {
                        f.sync().unwrap();
                    }
                })
            };

            writer.join().unwrap();
            syncer.join().unwrap();

            file.sync().unwrap();

            for i in 0..INIT_CHUNKS {
                let mut buf = [0; CHUNK_SIZE];
                file.pread(buf.as_mut_ptr(), i).unwrap();
                assert!(buf.iter().all(|b| *b == i as u8));
            }
        }

        #[test]
        fn err_read_hcf_for_eof() {
            let (_dir, cfg) = tmp_path();
            let file = FrozenFile::new(cfg).unwrap();

            // index > curr_chunks
            let mut buf = [0; CHUNK_SIZE];
            let err = file.pread(buf.as_mut_ptr(), 0x100).unwrap_err();
            assert!(err.compare(FFileErr::Hcf as u16));
        }
    }
}