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
use std::io;
use std::str;
use std::fmt;
use std::ffi::{CStr, CString};
use std::fs::Metadata;
use std::path::{Path, PathBuf};
use std::convert::AsRef;
use std::mem::forget;
use std::ops::{Deref, DerefMut, Drop};
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
use std::os::unix::ffi::OsStrExt;
use libc;
pub trait Stream: io::Read + io::Write + io::Seek {
fn position(&self) -> io::Result<u64>;
fn eof(&self) -> bool;
fn errno(&self) -> i32;
fn last_error(&self) -> Option<io::Error>;
fn clear_error(&self);
fn file_name(&self) -> io::Result<PathBuf>;
fn metadata(&self) -> io::Result<Metadata>;
}
pub trait ToStream: AsRawFd + Sized {
fn to_stream(&self, mode: &str) -> io::Result<CFile> {
open_stream(self, mode)
}
}
impl<S: AsRawFd + Sized> ToStream for S {}
macro_rules! cstr {
($s:expr) => (try!(CString::new($s)).as_ptr() as *const i8)
}
pub type RawFilePtr = *mut libc::FILE;
pub struct RawFile(RawFilePtr);
impl Drop for RawFile {
fn drop(&mut self) {
unsafe {
libc::fclose(self.0);
}
}
}
impl Deref for RawFile {
type Target = libc::FILE;
fn deref(&self) -> &Self::Target {
unsafe { &*self.0 }
}
}
impl DerefMut for RawFile {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.0 }
}
}
impl RawFile {
pub fn stream(&self) -> RawFilePtr {
self.0
}
}
extern "C" {
fn clearerr(file: RawFilePtr);
}
pub struct CFile {
inner: RawFile,
owned: bool,
}
unsafe impl Sync for CFile {}
unsafe impl Send for CFile {}
impl Deref for CFile {
type Target = RawFile;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for CFile {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl CFile {
pub fn from_raw(f: *mut libc::FILE, owned: bool) -> io::Result<CFile> {
if f.is_null() {
Err(io::Error::last_os_error())
} else {
Ok(CFile {
inner: RawFile(f),
owned: owned,
})
}
}
fn _open_fd(fd: RawFd, mode: &str, owned: bool) -> io::Result<CFile> {
Self::from_raw(unsafe { libc::fdopen(fd, cstr!(mode)) }, owned)
}
pub fn reopen(&self, filename: &str, mode: &str) -> io::Result<CFile> {
let f = unsafe { libc::freopen(cstr!(filename), cstr!(mode), self.stream()) };
Self::from_raw(f, true)
}
}
pub fn open<P: AsRef<Path>>(path: P, mode: &str) -> io::Result<CFile> {
CFile::from_raw(unsafe {
libc::fopen(cstr!(path.as_ref()
.as_os_str()
.as_bytes()),
cstr!(mode))
},
true)
}
pub fn stdin() -> io::Result<CFile> {
CFile::_open_fd(libc::STDIN_FILENO, "r", false)
}
pub fn stdout() -> io::Result<CFile> {
CFile::_open_fd(libc::STDOUT_FILENO, "w", false)
}
pub fn stderr() -> io::Result<CFile> {
CFile::_open_fd(libc::STDERR_FILENO, "w", false)
}
pub fn tmpfile() -> io::Result<CFile> {
CFile::from_raw(unsafe { libc::tmpfile() }, true)
}
pub fn open_stream<S: AsRawFd>(s: &S, mode: &str) -> io::Result<CFile> {
CFile::_open_fd(s.as_raw_fd(), mode, true)
}
impl Stream for CFile {
fn position(&self) -> io::Result<u64> {
let off = unsafe { libc::ftell(self.stream()) };
if off < 0 {
if let Some(err) = self.last_error() {
return Err(err);
}
}
Ok(off as u64)
}
#[inline]
fn eof(&self) -> bool {
unsafe { libc::feof(self.stream()) != 0 }
}
#[inline]
fn errno(&self) -> i32 {
unsafe { libc::ferror(self.stream()) }
}
fn last_error(&self) -> Option<io::Error> {
let errno = self.errno();
if errno != 0 {
return Some(io::Error::from_raw_os_error(errno));
}
let err = io::Error::last_os_error();
match err.raw_os_error() {
Some(errno) if errno != 0 => Some(err),
_ => None,
}
}
fn clear_error(&self) {
unsafe { clearerr(self.stream()) }
}
#[cfg(target_os = "linux")]
fn file_name(&self) -> io::Result<PathBuf> {
let s = format!("/proc/self/fd/{}", self.as_raw_fd());
let p = Path::new(&s);
if p.exists() {
p.read_link()
} else {
Err(io::Error::new(io::ErrorKind::NotFound, "fd not found"))
}
}
#[cfg(target_os = "macos")]
fn file_name(&self) -> io::Result<PathBuf> {
let mut buf = Vec::with_capacity(libc::PATH_MAX as usize);
let ret = unsafe { libc::fcntl(self.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
let filename = str::from_utf8(unsafe { CStr::from_ptr(buf.as_ptr()).to_bytes() }).unwrap();
println!("{}, {}", filename, ret);
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(PathBuf::from(filename))
}
}
fn metadata(&self) -> io::Result<Metadata> {
try!(self.file_name()).as_path().metadata()
}
}
impl AsRawFd for CFile {
fn as_raw_fd(&self) -> RawFd {
unsafe { libc::fileno(self.stream()) }
}
}
impl IntoRawFd for CFile {
fn into_raw_fd(self) -> RawFd {
let fd = unsafe { libc::fileno(self.stream()) };
forget(self);
fd
}
}
impl io::Read for CFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let read = unsafe {
libc::fread(buf.as_ptr() as *mut libc::c_void,
1,
buf.len(),
self.stream())
};
if let Some(err) = self.last_error() {
if read == 0 {
return Err(err);
}
}
Ok(read)
}
}
impl io::Write for CFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let wrote = unsafe {
libc::fwrite(buf.as_ptr() as *const libc::c_void,
1,
buf.len(),
self.stream())
};
if let Some(err) = self.last_error() {
if wrote == 0 {
return Err(err);
}
}
Ok(wrote)
}
fn flush(&mut self) -> io::Result<()> {
if unsafe { libc::fflush(self.stream()) } != 0 {
if let Some(err) = self.last_error() {
return Err(err);
}
}
Ok(())
}
}
impl io::Seek for CFile {
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
let ret = unsafe {
match pos {
io::SeekFrom::Start(off) => libc::fseek(self.stream(), off as i64, libc::SEEK_SET),
io::SeekFrom::End(off) => libc::fseek(self.stream(), off, libc::SEEK_END),
io::SeekFrom::Current(off) => libc::fseek(self.stream(), off, libc::SEEK_CUR),
}
};
if ret != 0 {
if let Some(err) = self.last_error() {
return Err(err);
}
}
self.position()
}
}
impl fmt::Debug for CFile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "CFile {{f: {:p}, owned: {}}}", self.stream(), self.owned)
}
}
#[cfg(test)]
mod tests {
use std::io::{Read, Write, Seek, SeekFrom};
use std::os::unix::io::AsRawFd;
use super::*;
#[test]
fn test_cfile() {
let mut f = tmpfile().unwrap();
assert!(!f.stream().is_null());
assert!(f.as_raw_fd() > 2);
assert_eq!(f.write(b"test").unwrap(), 4);
assert_eq!(f.seek(SeekFrom::Current(0)).unwrap(), 4);
let mut buf: [u8; 4] = [0; 4];
assert_eq!(f.read(&mut buf[..]).unwrap(), 0);
assert_eq!(f.seek(SeekFrom::Start(0)).unwrap(), 0);
f.flush().unwrap();
assert_eq!(f.read(&mut buf[..]).unwrap(), 4);
assert_eq!(buf, &b"test"[..]);
let filename = f.file_name().unwrap();
assert!(filename.is_absolute());
assert!(filename.parent().unwrap().is_dir());
}
}