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 crate::{
file::FileType,
sys::dir::{iter_impl, EntryImpl},
};
use std::convert::TryInto;
use std::io::{Error, Result};
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
#[cfg(target_os = "wasi")]
use std::os::wasi::io::{AsRawFd, IntoRawFd, RawFd};
use std::{ffi::CStr, io, ops::Deref, ptr};
pub use crate::sys::EntryExt;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Dir(ptr::NonNull<libc::DIR>);
impl Dir {
#[inline]
pub fn from<F: IntoRawFd>(fd: F) -> Result<Self> {
let fd = fd.into_raw_fd();
unsafe { Self::from_fd(fd) }
}
unsafe fn from_fd(fd: RawFd) -> Result<Self> {
let d = libc::fdopendir(fd);
if let Some(d) = ptr::NonNull::new(d) {
Ok(Self(d))
} else {
let e = io::Error::last_os_error();
libc::close(fd);
Err(e.into())
}
}
pub fn seek(&mut self, loc: SeekLoc) {
#[cfg(not(target_os = "android"))]
use libc::seekdir;
#[cfg(target_os = "android")]
extern "C" {
fn seekdir(dirp: *mut libc::DIR, loc: libc::c_long);
}
unsafe { seekdir(self.0.as_ptr(), loc.0) }
}
pub fn rewind(&mut self) {
unsafe { libc::rewinddir(self.0.as_ptr()) }
}
#[allow(dead_code)]
pub fn tell(&self) -> SeekLoc {
#[cfg(not(target_os = "android"))]
use libc::telldir;
#[cfg(target_os = "android")]
extern "C" {
fn telldir(dirp: *mut libc::DIR) -> libc::c_long;
}
let loc = unsafe { telldir(self.0.as_ptr()) };
SeekLoc(loc)
}
pub(crate) fn as_raw(&self) -> ptr::NonNull<libc::DIR> {
self.0
}
}
unsafe impl Send for Dir {}
impl AsRawFd for Dir {
fn as_raw_fd(&self) -> RawFd {
unsafe { libc::dirfd(self.0.as_ptr()) }
}
}
impl Drop for Dir {
fn drop(&mut self) {
unsafe { libc::closedir(self.0.as_ptr()) };
}
}
#[derive(Debug, Copy, Clone)]
pub struct Entry(pub(crate) EntryImpl);
impl Entry {
pub fn file_name(&self) -> &CStr {
unsafe { CStr::from_ptr(self.0.d_name.as_ptr()) }
}
pub fn file_type(&self) -> FileType {
FileType::from_dirent_d_type(self.0.d_type)
}
}
#[derive(Clone, Copy, Debug)]
pub struct SeekLoc(pub(crate) libc::c_long);
impl SeekLoc {
pub fn to_raw(&self) -> i64 {
self.0.into()
}
pub unsafe fn from_raw(loc: i64) -> Result<Self> {
let loc = loc
.try_into()
.map_err(|_| Error::from_raw_os_error(libc::EINVAL))?;
Ok(Self(loc))
}
}
#[derive(Debug)]
pub struct DirIter<T: Deref<Target = Dir>>(T);
impl<T> DirIter<T>
where
T: Deref<Target = Dir>,
{
pub fn new(dir: T) -> Self {
Self(dir)
}
}
impl<T> Iterator for DirIter<T>
where
T: Deref<Target = Dir>,
{
type Item = Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
iter_impl(&self.0).map(|x| x.map(Entry))
}
}