diskit 0.1.5

Utilities for intercepting disk requests.
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
use std::{
    collections::HashMap,
    ffi::OsString,
    io::{Error, ErrorKind, SeekFrom},
    mem,
    path::{Component, Path, PathBuf},
};

use crate::{
    dir_entry::DirEntry,
    file::{File, FileInner},
    metadata::{FileType, Metadata},
    open_options::OpenOptions,
    virtual_diskit::VirtualDiskit,
    walkdir::{WalkDir, WalkdirIterator, WalkdirIteratorInner},
};

macro_rules! try_nested {
    ($val: expr, $self: expr, $inner: expr) => {
        loop
        {
            let error;
            match $val
            {
                Ok(x) => break x,
                Err(err) =>
                {
                    error = err;
                }
            }
            $self.walkdirs[$inner.val].fused = true;
            return Some(Err(error));
        }
    };
}

// The `Empty` variant is only used if something is deleted and since
// there is no deleting without the `trash` feature, it's dead code
// then.
#[cfg_attr(not(feature = "trash"), allow(dead_code))]
#[derive(Debug, PartialEq, Eq)]
pub enum InodeInner
{
    File(Vec<u8>),
    Dir(HashMap<OsString, usize>),
    Empty,
}

#[derive(Debug)]
pub struct Inode
{
    pub inner: InodeInner,
    pub id: usize,
}

// This pedantic lint is supposed to guard against implementing state
// machines as structs with a `bool` for every state instead of using
// enums.  This is not a state machine, so it's actually completely
// fine.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug)]
pub struct OpenedFile
{
    pub inode_id: usize,
    pub pos: usize,
    pub read: bool,
    pub write: bool,
    pub append: bool,
    pub closed: bool,
}

#[derive(Debug)]
pub struct WalkingDir
{
    pub pos: Vec<usize>,
    pub fused: bool,
}

#[derive(Debug)]
pub struct VirtualDiskitInner
{
    pub content: Vec<Inode>,
    pub files: Vec<OpenedFile>,
    pub walkdirs: Vec<WalkingDir>,
    pub pwd: PathBuf,
}

impl VirtualDiskitInner
{
    pub fn new() -> Self
    {
        Self {
            content: vec![Inode {
                inner: InodeInner::Dir(
                    [(OsString::from("."), 0), (OsString::from(".."), 0)].into(),
                ),
                id: 0,
            }],
            files: vec![],
            walkdirs: vec![],
            pwd: PathBuf::from("/"),
        }
    }

    pub fn open_with_options(
        &mut self,
        path: &Path,
        options: OpenOptions,
        diskit: &VirtualDiskit,
    ) -> Result<File<VirtualDiskit>, Error>
    {
        // Checks for disallowed combinations:
        // * truncating without writing
        // * create(_new)ing without also writing/appending
        if (options.truncate && !options.write)
            || ((options.create || options.create_new) && !(options.write || options.append))
        {
            return Err(From::from(ErrorKind::InvalidInput));
        }

        let inode = self.get_inode_by_full_path(path)?;

        if let Err(inode) = inode
        {
            if !(options.create || options.create_new)
            {
                return Err(From::from(ErrorKind::NotFound));
            }

            let len = self.content.len();

            match &mut self.get_mut_inode_by_id(inode.id)?.inner
            {
                InodeInner::Dir(dir) =>
                {
                    dir.insert(
                        path.file_name().ok_or(ErrorKind::InvalidInput)?.to_owned(),
                        len,
                    )
                    .ok_or(())
                    .expect_err("The directory shouldn't have this file already");

                    self.files.push(OpenedFile {
                        inode_id: len,
                        pos: 0,
                        read: options.read,
                        write: options.write,
                        append: options.append,
                        closed: false,
                    });

                    self.content.push(Inode {
                        inner: InodeInner::File(vec![]),
                        id: self.content.len(),
                    });

                    Ok(File {
                        inner: FileInner {
                            file: None,
                            val: self.files.len() - 1,
                        },
                        diskit: diskit.clone(),
                    })
                }
                InodeInner::File(_) => Err(From::from(ErrorKind::NotADirectory)),
                InodeInner::Empty => panic!("Empty inode found"),
            }
        }
        else if options.create_new
        // Implicitly: `&& ! let Err(_) = inode`
        {
            Err(From::from(ErrorKind::AlreadyExists))
        }
        else
        {
            let inode_id = inode.unwrap().id;
            let inode = self.get_mut_inode_by_id(inode_id)?;

            match &mut inode.inner
            {
                InodeInner::File(file) =>
                {
                    if options.truncate
                    {
                        file.truncate(0);
                    }

                    let pos = if options.append { file.len() } else { 0 };

                    self.files.push(OpenedFile {
                        inode_id,
                        pos,
                        read: options.read,
                        write: options.write,
                        append: options.append,
                        closed: false,
                    });

                    Ok(File {
                        inner: FileInner {
                            file: None,
                            val: self.files.len() - 1,
                        },
                        diskit: diskit.clone(),
                    })
                }
                InodeInner::Dir(_) => Err(From::from(ErrorKind::IsADirectory)),
                InodeInner::Empty => panic!("Empty inode found"),
            }
        }
    }

    pub fn read(&mut self, file: &FileInner, buf: &mut [u8]) -> Result<usize, Error>
    {
        let opened_file = &self.files[file.val];

        debug_assert!(!opened_file.closed, "Attempted to use closed file");

        if !opened_file.read
        {
            return Err(From::from(ErrorKind::PermissionDenied));
        }

        let inode = &self.get_inode_by_id(opened_file.inode_id)?.inner;
        let pos = opened_file.pos;

        match inode
        {
            InodeInner::File(content) =>
            {
                if pos >= content.len()
                {
                    return Ok(0);
                }

                let mut amount = content.len() - pos;

                if amount > buf.len()
                {
                    amount = buf.len();
                }

                buf[0..amount].copy_from_slice(&content[pos..(pos + amount)]);

                self.files[file.val].pos += amount;

                Ok(amount)
            }
            InodeInner::Dir(_) => Err(From::from(ErrorKind::IsADirectory)),
            InodeInner::Empty => panic!("Empty inode found"),
        }
    }

    // Even though formally a shared reference would suffice here,
    // logically a exlusive one is necessary.
    #[allow(clippy::needless_pass_by_ref_mut)]
    pub fn read_to_end(&mut self, file: &mut FileInner, buf: &mut Vec<u8>) -> Result<usize, Error>
    {
        let opened_file = &self.files[file.val];

        debug_assert!(!opened_file.closed, "Attempted to use closed file");

        if !opened_file.read
        {
            return Err(From::from(ErrorKind::PermissionDenied));
        }

        let inode = &self.get_inode_by_id(opened_file.inode_id)?.inner;
        let pos = opened_file.pos;

        match inode
        {
            InodeInner::File(content) =>
            {
                if pos >= content.len()
                {
                    return Ok(0);
                }

                buf.extend_from_slice(&content[pos..]);

                let amount = content.len() - pos;

                self.files[file.val].pos += content.len();

                Ok(amount)
            }
            InodeInner::Dir(_) => Err(From::from(ErrorKind::IsADirectory)),
            InodeInner::Empty => panic!("Empty inode found"),
        }
    }

    pub fn read_to_string(&mut self, file: &mut FileInner, buf: &mut String)
        -> Result<usize, Error>
    {
        let mut vec = vec![];

        let amount = self.read_to_end(file, &mut vec)?;

        buf.push_str(std::str::from_utf8(&vec).map_err(|_| ErrorKind::InvalidData)?);

        Ok(amount)
    }

    pub fn write(&mut self, file: &mut FileInner, buf: &[u8]) -> Result<usize, Error>
    {
        self.write_all(file, buf)?;

        Ok(buf.len())
    }

    // Even though formally a shared reference would suffice here,
    // logically a exlusive one is necessary.
    #[allow(clippy::needless_pass_by_ref_mut)]
    pub fn write_all(&mut self, file: &mut FileInner, buf: &[u8]) -> Result<(), Error>
    {
        let opened_file = &self.files[file.val];
        let mut pos = opened_file.pos;
        let append = opened_file.append;

        debug_assert!(!opened_file.closed, "Attempted to use closed file");

        if !(opened_file.write || opened_file.append)
        {
            return Err(From::from(ErrorKind::PermissionDenied));
        }

        let inode = &mut self.get_mut_inode_by_id(opened_file.inode_id)?.inner;

        match inode
        {
            InodeInner::File(content) =>
            {
                if append
                {
                    pos = content.len();
                }

                if pos + buf.len() > content.len()
                {
                    content.append(&mut vec![0; pos + buf.len() - content.len()]);
                }

                content[pos..(pos + buf.len())].copy_from_slice(buf);

                self.files[file.val].pos = pos + buf.len();

                Ok(())
            }
            InodeInner::Dir(_) => Err(From::from(ErrorKind::IsADirectory)),
            InodeInner::Empty => panic!("Empty inode found"),
        }
    }

    pub fn metadata_inner(&self, file: &FileInner) -> Result<Metadata, Error>
    {
        match &self.get_inode_by_id(self.files[file.val].inode_id)?.inner
        {
            InodeInner::File(content) => Ok(Metadata {
                file_type: FileType::File,
                len: content.len() as _,
            }),
            InodeInner::Dir(_) => Ok(Metadata {
                file_type: FileType::Dir,
                len: 0,
            }),
            InodeInner::Empty => panic!("Empty inode found"),
        }
    }

    // Even though formally a shared reference would suffice here,
    // logically a exlusive one is necessary.
    #[allow(clippy::needless_pass_by_ref_mut)]
    pub fn seek(&mut self, file: &mut FileInner, pos: SeekFrom) -> Result<u64, Error>
    {
        let len = self.metadata_inner(file)?.len;

        let file = &mut self.files[file.val];

        debug_assert!(!file.closed, "Attempted to use closed file");

        match pos
        {
            SeekFrom::Start(x) => file.pos = x as _,
            SeekFrom::End(x) =>
            {
                file.pos = ((len as i64) + x) as _;
            }
            SeekFrom::Current(x) => file.pos = ((file.pos as i64) + x) as _,
        }

        Ok(file.pos as _)
    }

    pub fn create_dir(&mut self, path: &Path) -> Result<(), Error>
    {
        if path == Path::new("/")
        {
            return Err(ErrorKind::AlreadyExists.into());
        }

        let Component::Normal(filename) = path
            .components()
            .next_back()
            .ok_or(ErrorKind::InvalidInput)?
        else
        {
            return Err(From::from(ErrorKind::InvalidInput));
        };

        let old_content_len = self.content.len();

        let inode = self.get_mut_inode_by_id(
            self.get_inode_by_full_path(path)?
                .err()
                .ok_or(ErrorKind::AlreadyExists)?
                .id,
        )?;

        let old_inode_id = inode.id;

        match &mut inode.inner
        {
            InodeInner::Dir(dir) =>
            {
                dir.insert(filename.to_owned(), old_content_len)
                    .ok_or(())
                    .expect_err("The directory shouldn't have this file already");

                self.content.push(Inode {
                    inner: InodeInner::Dir(
                        [
                            (OsString::from("."), old_content_len),
                            (OsString::from(".."), old_inode_id),
                        ]
                        .into(),
                    ),
                    id: old_content_len,
                });

                Ok(())
            }
            InodeInner::File(_) => Err(From::from(ErrorKind::NotADirectory)),
            InodeInner::Empty => panic!("Empty inode found"),
        }
    }

    pub fn create_dir_all(&mut self, path: &Path) -> Result<(), Error>
    {
        let mut full_path = PathBuf::from(".");

        for component in path.components()
        {
            full_path.push(component);

            self.create_dir(&full_path).or_else(|err| {
                if err.kind() == ErrorKind::AlreadyExists
                {
                    Ok(())
                }
                else
                {
                    Err(err)
                }
            })?;
        }

        Ok(())
    }

    // Even though formally a shared reference would suffice here,
    // logically a exlusive one is necessary.
    #[allow(clippy::needless_pass_by_ref_mut)]
    pub fn close(&mut self, file: &mut FileInner)
    {
        let files = &mut self.files;
        files[file.val].closed = true;

        while !files.is_empty() && files[files.len() - 1].closed
        {
            files.pop();
        }
    }

    // This is a false positive, because the value that gets
    // "`into`-ed" is not `self`, but `walkdir` and that is actually
    // taken by value.
    #[allow(clippy::wrong_self_convention)]
    pub fn into_walkdir_iterator(
        &mut self,
        walkdir: WalkDir<VirtualDiskit>,
    ) -> WalkdirIterator<VirtualDiskit>
    {
        let pos = match self
            .get_first_walkdir_pos(&walkdir.options.path, walkdir.options.contents_first)
        {
            Ok(pos) => pos,
            Err(err) => return WalkdirIterator { inner: Err(err) },
        };
        self.walkdirs.push(WalkingDir { pos, fused: false });

        WalkdirIterator {
            inner: Ok((
                WalkdirIteratorInner {
                    walkdir: None,
                    val: self.walkdirs.len() - 1,
                    original: walkdir.options,
                },
                walkdir.diskit,
            )),
        }
    }

    // I don't see any way to shorten it yet.  TODO: Fix!
    #[allow(clippy::too_many_lines)]
    // Even though formally a shared reference would suffice here,
    // logically a exlusive one is necessary.
    #[allow(clippy::needless_pass_by_ref_mut)]
    fn walkdir_next_helper(
        &mut self,
        inner: &mut WalkdirIteratorInner,
    ) -> Option<Result<DirEntry, Error>>
    {
        let walkdir = &self.walkdirs[inner.val];

        if walkdir.fused
        {
            return None;
        }

        let root_inode = try_nested!(
            try_nested!(
                self.get_inode_by_full_path(&inner.original.path),
                self,
                inner
            )
            .map_err(|_| ErrorKind::NotFound.into()),
            self,
            inner
        );

        let InodeInner::Dir(root_dir) = &root_inode.inner
        else
        {
            self.walkdirs[inner.val].fused = true;
            return Some(Err(ErrorKind::NotADirectory.into()));
        };

        if walkdir.pos.is_empty()
        {
            let ino = root_inode.id as _;

            if inner.original.contents_first
            {
                let len = root_dir.len();
                self.walkdirs[inner.val].pos.push(len);
            }
            else
            {
                self.walkdirs[inner.val].pos.push(0);
            }

            return Some(Ok(DirEntry {
                path: inner.original.path.clone(),
                metadata: Metadata {
                    file_type: FileType::Dir,
                    len: 0,
                },
                follow_link: false,
                depth: 0,
                ino,
            }));
        }

        let mut path = inner.original.path.clone();
        let mut inode = root_inode;

        for index in &walkdir.pos
        {
            let (content_path, &content_inode) =
                try_nested!(Self::get_dir_as_iterator(inode), self, inner).nth(*index)?;
            path.push(content_path);

            inode = try_nested!(self.get_inode_by_id(content_inode), self, inner);
        }

        let metadata = match &inode.inner
        {
            InodeInner::File(file) => Metadata {
                file_type: FileType::File,
                len: file.len() as _,
            },
            InodeInner::Dir(_) => Metadata {
                file_type: FileType::Dir,
                len: 0,
            },
            InodeInner::Empty => panic!("Empty inode found"),
        };

        let rv = DirEntry {
            path,
            metadata,
            follow_link: false,
            depth: walkdir.pos.len(),
            ino: inode.id as _,
        };

        let mut pos = self.walkdirs[inner.val].pos.clone();

        if inner.original.contents_first
        {
            let len = pos.len();

            pos[len - 1] += 1;
            while self.check_pos_path(root_inode, &pos).is_some()
            {
                pos.push(0);
            }
            pos.pop();
        }
        else
        {
            pos.push(0);

            if self.check_pos_path(root_inode, &pos).is_none()
            {
                pos.pop();
                loop
                {
                    let len = pos.len();

                    if len == 0
                    {
                        self.walkdirs[inner.val].fused = true;
                        break;
                    }

                    pos[len - 1] += 1;
                    if self.check_pos_path(root_inode, &pos).is_none()
                    {
                        pos.pop();
                        continue;
                    }
                    break;
                }
            }
        }

        drop(mem::replace(&mut self.walkdirs[inner.val].pos, pos));

        Some(Ok(rv))
    }

    pub fn walkdir_next_inner(
        &mut self,
        inner: &mut WalkdirIteratorInner,
    ) -> Option<Result<DirEntry, Error>>
    {
        let options = inner.original.clone();

        loop
        {
            match self.walkdir_next_helper(inner)
            {
                Some(Ok(dir_entry)) =>
                {
                    if dir_entry.depth() >= options.min_depth
                        && dir_entry.depth() <= options.max_depth
                    {
                        return Some(Ok(dir_entry));
                    }
                }
                other => return other,
            }
        }
    }

    #[cfg(feature = "trash")]
    pub fn trash_delete(&mut self, path: &Path) -> Result<(), Error>
    {
        fn get_parent_dir<'a>(
            self_: &'a mut VirtualDiskitInner,
            parent_path: &Path,
        ) -> Result<&'a mut HashMap<OsString, usize>, Error>
        {
            VirtualDiskitInner::get_mut_dir_from_inode(
                self_.get_mut_inode_by_full_path(parent_path)?,
            )
        }

        let path = self.pwd.join(path);
        let parent_path = path.parent().ok_or(ErrorKind::PermissionDenied)?.to_owned();

        if path.ends_with("..") || path.ends_with(".")
        {
            return self.trash_delete(&parent_path);
        }

        let file_inode_id = *get_parent_dir(self, &parent_path)?
            .get(path.file_name().expect("Path should have a file name"))
            .ok_or(ErrorKind::NotFound)?;

        let mut all_inodes = vec![file_inode_id];
        if self.get_dir_by_id(file_inode_id).is_ok()
        {
            self.collect_inodes(self.get_inode_by_id(file_inode_id)?, &mut all_inodes)?;
        }
        if all_inodes
            .iter()
            .any(|&id| self.files.iter().any(|file| id == file.inode_id))
        {
            return Err(ErrorKind::ResourceBusy.into());
        }

        get_parent_dir(self, &parent_path)?
            .remove(path.file_name().expect("Path should have a file name"))
            .expect("Value was proven to exist, but doesn't");

        for inode_id in all_inodes
        {
            drop(mem::replace(
                self.get_mut_inode_by_id(inode_id)?,
                Inode {
                    inner: InodeInner::Empty,
                    id: inode_id,
                },
            ));
        }

        while !self.content.is_empty()
            && self.content[self.content.len() - 1].inner == InodeInner::Empty
        {
            self.content.pop();
        }

        Ok(())
    }
}