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
use alloc::string::String;
use axio::Result;
use core::fmt;

use super::FileType;
use crate::fops;

/// Iterator over the entries in a directory.
pub struct ReadDir<'a> {
    path: &'a str,
    inner: fops::Directory,
    buf_pos: usize,
    buf_end: usize,
    end_of_stream: bool,
    dirent_buf: [fops::DirEntry; 31],
}

/// Entries returned by the [`ReadDir`] iterator.
pub struct DirEntry<'a> {
    dir_path: &'a str,
    entry_name: String,
    entry_type: FileType,
}

/// A builder used to create directories in various manners.
#[derive(Default, Debug)]
pub struct DirBuilder {
    recursive: bool,
}

impl<'a> ReadDir<'a> {
    pub(super) fn new(path: &'a str) -> Result<Self> {
        let mut opts = fops::OpenOptions::new();
        opts.read(true);
        let inner = fops::Directory::open_dir(path, &opts)?;
        const EMPTY: fops::DirEntry = fops::DirEntry::default();
        let dirent_buf = [EMPTY; 31];
        Ok(ReadDir {
            path,
            inner,
            end_of_stream: false,
            buf_pos: 0,
            buf_end: 0,
            dirent_buf,
        })
    }
}

impl<'a> Iterator for ReadDir<'a> {
    type Item = Result<DirEntry<'a>>;

    fn next(&mut self) -> Option<Result<DirEntry<'a>>> {
        if self.end_of_stream {
            return None;
        }

        loop {
            if self.buf_pos >= self.buf_end {
                match self.inner.read_dir(&mut self.dirent_buf) {
                    Ok(n) => {
                        if n == 0 {
                            self.end_of_stream = true;
                            return None;
                        }
                        self.buf_pos = 0;
                        self.buf_end = n;
                    }
                    Err(e) => {
                        self.end_of_stream = true;
                        return Some(Err(e));
                    }
                }
            }
            let entry = &self.dirent_buf[self.buf_pos];
            self.buf_pos += 1;
            let name_bytes = entry.name_as_bytes();
            if name_bytes == b"." || name_bytes == b".." {
                continue;
            }
            let entry_name = unsafe { core::str::from_utf8_unchecked(name_bytes).into() };
            let entry_type = entry.entry_type();

            return Some(Ok(DirEntry {
                dir_path: self.path,
                entry_name,
                entry_type,
            }));
        }
    }
}

impl<'a> DirEntry<'a> {
    /// Returns the full path to the file that this entry represents.
    ///
    /// The full path is created by joining the original path to `read_dir`
    /// with the filename of this entry.
    pub fn path(&self) -> String {
        String::from(self.dir_path.trim_end_matches('/')) + "/" + &self.entry_name
    }

    /// Returns the bare file name of this directory entry without any other
    /// leading path component.
    pub fn file_name(&self) -> String {
        self.entry_name.clone()
    }

    /// Returns the file type for the file that this entry points at.
    pub fn file_type(&self) -> FileType {
        self.entry_type
    }
}

impl fmt::Debug for DirEntry<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("DirEntry").field(&self.path()).finish()
    }
}

impl DirBuilder {
    /// Creates a new set of options with default mode/security settings for all
    /// platforms and also non-recursive.
    pub fn new() -> Self {
        Self { recursive: false }
    }

    /// Indicates that directories should be created recursively, creating all
    /// parent directories. Parents that do not exist are created with the same
    /// security and permissions settings.
    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
        self.recursive = recursive;
        self
    }

    /// Creates the specified directory with the options configured in this
    /// builder.
    pub fn create(&self, path: &str) -> Result<()> {
        if self.recursive {
            self.create_dir_all(path)
        } else {
            crate::root::create_dir(None, path)
        }
    }

    fn create_dir_all(&self, _path: &str) -> Result<()> {
        axerrno::ax_err!(
            Unsupported,
            "Recursive directory creation is not supported yet"
        )
    }
}