]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / libstd / sys / unix / fs.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Blocking posix-based file I/O
12
13 use libc::{mod, c_int, c_void};
14 use c_str::CString;
15 use mem;
16 use io;
17
18 use prelude::*;
19
20 use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
21 use io::{IoResult, FileStat, SeekStyle, Reader};
22 use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
23 use result::Result::{Ok, Err};
24 use sys::retry;
25 use sys_common::{keep_going, eof, mkerr_libc};
26
27 pub use path::PosixPath as Path;
28
29 pub type fd_t = libc::c_int;
30
31 pub struct FileDesc {
32     /// The underlying C file descriptor.
33     fd: fd_t,
34
35     /// Whether to close the file descriptor on drop.
36     close_on_drop: bool,
37 }
38
39 impl FileDesc {
40     pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
41         FileDesc { fd: fd, close_on_drop: close_on_drop }
42     }
43
44     pub fn read(&self, buf: &mut [u8]) -> IoResult<uint> {
45         let ret = retry(|| unsafe {
46             libc::read(self.fd(),
47                        buf.as_mut_ptr() as *mut libc::c_void,
48                        buf.len() as libc::size_t)
49         });
50         if ret == 0 {
51             Err(eof())
52         } else if ret < 0 {
53             Err(super::last_error())
54         } else {
55             Ok(ret as uint)
56         }
57     }
58     pub fn write(&self, buf: &[u8]) -> IoResult<()> {
59         let ret = keep_going(buf, |buf, len| {
60             unsafe {
61                 libc::write(self.fd(), buf as *const libc::c_void,
62                             len as libc::size_t) as i64
63             }
64         });
65         if ret < 0 {
66             Err(super::last_error())
67         } else {
68             Ok(())
69         }
70     }
71
72     pub fn fd(&self) -> fd_t { self.fd }
73
74     pub fn seek(&self, pos: i64, whence: SeekStyle) -> IoResult<u64> {
75         let whence = match whence {
76             SeekSet => libc::SEEK_SET,
77             SeekEnd => libc::SEEK_END,
78             SeekCur => libc::SEEK_CUR,
79         };
80         let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
81         if n < 0 {
82             Err(super::last_error())
83         } else {
84             Ok(n as u64)
85         }
86     }
87
88     pub fn tell(&self) -> IoResult<u64> {
89         let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
90         if n < 0 {
91             Err(super::last_error())
92         } else {
93             Ok(n as u64)
94         }
95     }
96
97     pub fn fsync(&self) -> IoResult<()> {
98         mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
99     }
100
101     pub fn datasync(&self) -> IoResult<()> {
102         return mkerr_libc(os_datasync(self.fd()));
103
104         #[cfg(any(target_os = "macos", target_os = "ios"))]
105         fn os_datasync(fd: c_int) -> c_int {
106             unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
107         }
108         #[cfg(target_os = "linux")]
109         fn os_datasync(fd: c_int) -> c_int {
110             retry(|| unsafe { libc::fdatasync(fd) })
111         }
112         #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
113         fn os_datasync(fd: c_int) -> c_int {
114             retry(|| unsafe { libc::fsync(fd) })
115         }
116     }
117
118     pub fn truncate(&self, offset: i64) -> IoResult<()> {
119         mkerr_libc(retry(|| unsafe {
120             libc::ftruncate(self.fd(), offset as libc::off_t)
121         }))
122     }
123
124     pub fn fstat(&self) -> IoResult<FileStat> {
125         let mut stat: libc::stat = unsafe { mem::zeroed() };
126         match unsafe { libc::fstat(self.fd(), &mut stat) } {
127             0 => Ok(mkstat(&stat)),
128             _ => Err(super::last_error()),
129         }
130     }
131
132     /// Extract the actual filedescriptor without closing it.
133     pub fn unwrap(self) -> fd_t {
134         let fd = self.fd;
135         unsafe { mem::forget(self) };
136         fd
137     }
138 }
139
140 impl Drop for FileDesc {
141     fn drop(&mut self) {
142         // closing stdio file handles makes no sense, so never do it. Also, note
143         // that errors are ignored when closing a file descriptor. The reason
144         // for this is that if an error occurs we don't actually know if the
145         // file descriptor was closed or not, and if we retried (for something
146         // like EINTR), we might close another valid file descriptor (opened
147         // after we closed ours.
148         if self.close_on_drop && self.fd > libc::STDERR_FILENO {
149             let n = unsafe { libc::close(self.fd) };
150             if n != 0 {
151                 println!("error {} when closing file descriptor {}", n, self.fd);
152             }
153         }
154     }
155 }
156
157 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
158     let flags = match fm {
159         Open => 0,
160         Append => libc::O_APPEND,
161         Truncate => libc::O_TRUNC,
162     };
163     // Opening with a write permission must silently create the file.
164     let (flags, mode) = match fa {
165         Read => (flags | libc::O_RDONLY, 0),
166         Write => (flags | libc::O_WRONLY | libc::O_CREAT,
167                         libc::S_IRUSR | libc::S_IWUSR),
168         ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
169                             libc::S_IRUSR | libc::S_IWUSR),
170     };
171
172     let path = path.to_c_str();
173     match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
174         -1 => Err(super::last_error()),
175         fd => Ok(FileDesc::new(fd, true)),
176     }
177 }
178
179 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
180     let p = p.to_c_str();
181     mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
182 }
183
184 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
185     use libc::{dirent_t};
186     use libc::{opendir, readdir_r, closedir};
187
188     fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
189         let root = unsafe { CString::new(root.as_ptr(), false) };
190         let root = Path::new(root);
191
192         dirs.into_iter().filter(|path| {
193             path.as_vec() != b"." && path.as_vec() != b".."
194         }).map(|path| root.join(path)).collect()
195     }
196
197     extern {
198         fn rust_dirent_t_size() -> libc::c_int;
199         fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
200     }
201
202     let size = unsafe { rust_dirent_t_size() };
203     let mut buf = Vec::<u8>::with_capacity(size as uint);
204     let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
205
206     let p = p.to_c_str();
207     let dir_ptr = unsafe {opendir(p.as_ptr())};
208
209     if dir_ptr as uint != 0 {
210         let mut paths = vec!();
211         let mut entry_ptr = 0 as *mut dirent_t;
212         while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
213             if entry_ptr.is_null() { break }
214             let cstr = unsafe {
215                 CString::new(rust_list_dir_val(entry_ptr), false)
216             };
217             paths.push(Path::new(cstr));
218         }
219         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
220         Ok(prune(&p, paths))
221     } else {
222         Err(super::last_error())
223     }
224 }
225
226 pub fn unlink(p: &Path) -> IoResult<()> {
227     let p = p.to_c_str();
228     mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
229 }
230
231 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
232     let old = old.to_c_str();
233     let new = new.to_c_str();
234     mkerr_libc(unsafe {
235         libc::rename(old.as_ptr(), new.as_ptr())
236     })
237 }
238
239 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
240     let p = p.to_c_str();
241     mkerr_libc(retry(|| unsafe {
242         libc::chmod(p.as_ptr(), mode as libc::mode_t)
243     }))
244 }
245
246 pub fn rmdir(p: &Path) -> IoResult<()> {
247     let p = p.to_c_str();
248     mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
249 }
250
251 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
252     let p = p.to_c_str();
253     mkerr_libc(retry(|| unsafe {
254         libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
255     }))
256 }
257
258 pub fn readlink(p: &Path) -> IoResult<Path> {
259     let c_path = p.to_c_str();
260     let p = c_path.as_ptr();
261     let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
262     if len == -1 {
263         len = 1024; // FIXME: read PATH_MAX from C ffi?
264     }
265     let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
266     match unsafe {
267         libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
268                        len as libc::size_t) as libc::c_int
269     } {
270         -1 => Err(super::last_error()),
271         n => {
272             assert!(n > 0);
273             unsafe { buf.set_len(n as uint); }
274             Ok(Path::new(buf))
275         }
276     }
277 }
278
279 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
280     let src = src.to_c_str();
281     let dst = dst.to_c_str();
282     mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
283 }
284
285 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
286     let src = src.to_c_str();
287     let dst = dst.to_c_str();
288     mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
289 }
290
291 fn mkstat(stat: &libc::stat) -> FileStat {
292     // FileStat times are in milliseconds
293     fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
294
295     #[cfg(not(any(target_os = "linux", target_os = "android")))]
296     fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
297     #[cfg(any(target_os = "linux", target_os = "android"))]
298     fn flags(_stat: &libc::stat) -> u64 { 0 }
299
300     #[cfg(not(any(target_os = "linux", target_os = "android")))]
301     fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
302     #[cfg(any(target_os = "linux", target_os = "android"))]
303     fn gen(_stat: &libc::stat) -> u64 { 0 }
304
305     FileStat {
306         size: stat.st_size as u64,
307         kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
308             libc::S_IFREG => io::FileType::RegularFile,
309             libc::S_IFDIR => io::FileType::Directory,
310             libc::S_IFIFO => io::FileType::NamedPipe,
311             libc::S_IFBLK => io::FileType::BlockSpecial,
312             libc::S_IFLNK => io::FileType::Symlink,
313             _ => io::FileType::Unknown,
314         },
315         perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
316         created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
317         modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
318         accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
319         unstable: UnstableFileStat {
320             device: stat.st_dev as u64,
321             inode: stat.st_ino as u64,
322             rdev: stat.st_rdev as u64,
323             nlink: stat.st_nlink as u64,
324             uid: stat.st_uid as u64,
325             gid: stat.st_gid as u64,
326             blksize: stat.st_blksize as u64,
327             blocks: stat.st_blocks as u64,
328             flags: flags(stat),
329             gen: gen(stat),
330         },
331     }
332 }
333
334 pub fn stat(p: &Path) -> IoResult<FileStat> {
335     let p = p.to_c_str();
336     let mut stat: libc::stat = unsafe { mem::zeroed() };
337     match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
338         0 => Ok(mkstat(&stat)),
339         _ => Err(super::last_error()),
340     }
341 }
342
343 pub fn lstat(p: &Path) -> IoResult<FileStat> {
344     let p = p.to_c_str();
345     let mut stat: libc::stat = unsafe { mem::zeroed() };
346     match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
347         0 => Ok(mkstat(&stat)),
348         _ => Err(super::last_error()),
349     }
350 }
351
352 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
353     let p = p.to_c_str();
354     let buf = libc::utimbuf {
355         actime: (atime / 1000) as libc::time_t,
356         modtime: (mtime / 1000) as libc::time_t,
357     };
358     mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
359 }
360
361 #[cfg(test)]
362 mod tests {
363     use super::FileDesc;
364     use libc;
365     use os;
366     use prelude::*;
367
368     #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
369     #[test]
370     fn test_file_desc() {
371         // Run this test with some pipes so we don't have to mess around with
372         // opening or closing files.
373         let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
374         let mut reader = FileDesc::new(reader, true);
375         let mut writer = FileDesc::new(writer, true);
376
377         writer.write(b"test").ok().unwrap();
378         let mut buf = [0u8, ..4];
379         match reader.read(&mut buf) {
380             Ok(4) => {
381                 assert_eq!(buf[0], 't' as u8);
382                 assert_eq!(buf[1], 'e' as u8);
383                 assert_eq!(buf[2], 's' as u8);
384                 assert_eq!(buf[3], 't' as u8);
385             }
386             r => panic!("invalid read: {}", r),
387         }
388
389         assert!(writer.read(&mut buf).is_err());
390         assert!(reader.write(&buf).is_err());
391     }
392 }