easy_fs/
file.rs

1use std::{fs::OpenOptions, io::{Read, Seek, SeekFrom, Write}, path::Path};
2
3pub struct File {
4    file : std::fs::File,
5}
6
7impl File {
8    pub fn create(path : &String)->Self {
9        Self {
10            file : OpenOptions::new().
11                read(true).write(true).create(true).open(path).unwrap()
12        }
13    }
14    pub fn open(path : &String, option : Option)->Self {
15        Self {
16            file : OpenOptions::new().
17                read(option.read()).write(option.write()).open(path).unwrap(),
18        }
19    }
20
21    pub fn exists(path : &String)->bool {
22        Path::new(&path).exists()
23    }
24
25    pub fn is_file(path : &String)->bool {
26        Path::new(&path).is_file()
27    }
28}
29
30impl File {
31    pub fn size(&mut self)->usize {
32        let old = self.file.stream_position().unwrap();
33        let rt = self.file.seek(SeekFrom::End(0)).unwrap();
34        self.file.seek(SeekFrom::Start(old)).unwrap();
35        rt as usize
36    }
37
38    pub fn position(&mut self)->usize {
39        self.file.stream_position().unwrap() as usize
40    }
41
42    pub fn seek(&mut self, pos : SeekFrom)->usize {
43        self.file.seek(pos).unwrap() as usize
44    }
45
46    pub fn read(&mut self, buf : &mut [u8])->usize {
47        let n = self.file.read(buf).unwrap() as usize;
48        assert_ne!(n, 0);
49        n
50    }
51
52    pub fn write(&mut self, buf : &[u8])->usize {
53        let n = self.file.write(buf).unwrap() as usize;
54        assert_ne!(n, 0);
55        n
56    }
57}
58
59#[derive(Clone, Copy, PartialEq)]
60pub enum Option {
61    ReadOnly,
62    WriteOnly,
63    ReadWrite,
64}
65
66impl Option {
67    pub fn read(&self)->bool {
68        *self == Self::ReadOnly || *self == Self::ReadWrite
69    }
70
71    pub fn write(&self)->bool {
72        *self == Self::WriteOnly || *self == Self::ReadWrite
73    }
74}