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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
MIT License

Copyright (c) 2017 Joshua Karns

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#![doc(html_root_url = "https://jkarns275.github.io/cfile/")]
#![feature(libc)]
extern crate libc;

pub use std::io::{ Seek, SeekFrom, Read, Write, Error, ErrorKind };
use libc::FILE;

use std::path::Path;
use std::ffi::CString;
use std::ptr::null_mut;
use std::os::unix::ffi::OsStrExt;

/// A utility function to pull the current value of errno and put it into an Error::Errno
fn get_error<T>() -> Result<T, Error> {
    Err(Error::last_os_error())
}

/// A utility function to change read/write/execute permissions of a file.
pub fn chmod<P: AsRef<Path>>(path: P, mode: u32) -> Result<(), Error> {
    let result = unsafe { libc::chmod(path.as_ref().as_os_str().as_bytes().as_ptr() as *const i8, mode) };
    if result == 0 {
        Ok(())
    } else {
        get_error()
    }

}

/// A utility function that creates a "buffer" of len bytes.
/// A Vec is used because it is memory safe and has a bunch of useful functionality (duh).
pub fn buffer(len: usize) -> Vec<u8> {
    vec![0u8; len]
}

/// A &'static str to be passed into the CFile::open method. It will open the file in a way that will allow
/// reading and writing, including overwriting old data. It will not create the file if it does not exist.
pub static RANDOM_ACCESS_MODE: &'static str = "rb+";
/// A &'static str to be passed into the CFile::open method. It will open the file in a way that will allow
/// reading and writing, including overwriting old data
pub static UPDATE: &'static str = "rb+";
/// A &'static str to be passed into the CFile::open method. It will only allow reading.
pub static READ_ONLY: &'static str = "r";
/// A &'static str to be passed into the CFile::open method. It will only allow writing.
pub static WRITE_ONLY: &'static str = "w";
/// A &'static str to be passed into the CFile::open method. It will only allow data to be appended to the
/// end of the file.
pub static APPEND_ONLY: &'static str = "a";
/// A &'static str to be passed into the CFile::open method. It will allow data to be appended to the end of
/// the file, and data to be read from the file. It will create the file if it doesn't exist.
pub static APPEND_READ: &'static str = "a+";
/// A &'static str to be passed into the CFile::open method. It will open the file in a way that will allow
/// reading and writing, including overwriting old data. It will create the file if it doesn't exist
pub static TRUNCATAE_RANDOM_ACCESS_MODE: &'static str = "wb+";


/// A wrapper around C's file type.
/// Attempts to mimic the functionality if rust's std::fs::File while still allowing complete
/// control of all I/O operations.
pub struct CFile {
    file_ptr: *mut FILE,
    pub path: CString
}

impl CFile {

    /// Attempts to open a file in random access mode (i.e. rb+). However, unlike rb+, if the file
    /// doesn't exist, it will be created. To avoid createion, simply call CFile::open(path, "rb+"),
    /// which will return an error if the file doesn't exist.
    /// # Failure
    /// This function will return Err for a whole bunch of reasons, the errno id will be returned
    /// as an Error::Errno(u64). For more information on what that number actually means see
    pub fn open_random_access<P: AsRef<Path>>(path: P) -> Result<CFile, Error> {
        let _ = Self::create_file(&path); // Ensure the file exists, create it if it doesn't
        Self::open(path, RANDOM_ACCESS_MODE)
    }

    /// Attempts to create a file, and then immedietly close it. If the file already exists, this
    /// function will not do anything. If the file does exist, then it will be created with no
    /// and nothing more (it will be empty).
    pub fn create_file<P: AsRef<Path>>(path: &P) -> Result<(), Error> {
        match Self::open(path, APPEND_READ) {
            Ok(file) => {
                file.close()
            },
            Err(e) => Err(e)
        }
    }

    /// Attempt to open the file with path p.
    /// # Examples
    /// ```
    /// use cfile_rs;
    /// use cfile_rs::*;
    /// use cfile_rs::CFile;
    /// use cfile_rs::TRUNCATAE_RANDOM_ACCESS_MODE;
    /// use std::str::from_utf8;
    ///
    /// // Truncate random access mode will overwrite the old "data.txt" file if it exists.
    /// let mut file = CFile::open("data.txt", TRUNCATAE_RANDOM_ACCESS_MODE).unwrap();
    /// ```
    pub fn open<P: AsRef<Path>>(path: P, mode: &str) -> Result<CFile, Error> {
        unsafe {
            if let Ok(path) = CString::new(path.as_ref().as_os_str().as_bytes()) {
                if let Ok(mode) = CString::new(mode) {
                    let file_ptr = libc::fopen(path.as_ptr(), mode.as_ptr());
                    if file_ptr.is_null() {
                        get_error()
                    } else {
                        Ok(
                            CFile {
                                file_ptr: file_ptr,
                                path: path
                            }
                        )
                    }
                } else {
                    get_error()
                }
            } else {
                get_error()
            }
        }
    }

    /// Deletes the file from the filesystem, and consumes the object.
    /// # Errors
    /// On error Error::Errno(errno) is returned.
    /// # Examples
    /// ```
    /// use cfile_rs;
    /// use cfile_rs::*;
    /// use cfile_rs::CFile;
    /// use cfile_rs::UPDATE;
    /// use std::str::from_utf8;
    ///
    /// // Truncate random access mode will overwrite the old "data.txt" file if it exists.
    /// let mut file = CFile::open("data.txt", UPDATE).unwrap();
    /// let _ = file.write_all("Howdy folks".as_bytes());   // Write some data!
    /// let _ = file.delete();                              // The file is gone!
    /// ```
    pub fn delete(self) -> Result<(), Error> {
        unsafe {
            let path = self.path.clone();
            drop(self);
            let result = libc::remove(path.as_ptr());
            if result == 0 {
                Ok(())
            } else {
                get_error()
            }
        }
    }

    /// Attempts to close the file. Consumes the file as well
    /// # Errors
    /// On error Error::Errno(errno) is returned.
    pub fn close(mut self) -> Result<(), Error> {
        unsafe {
            if !self.file_ptr.is_null() {
                let res = libc::fclose(self.file_ptr);
                if res == 0 {
                    self.file_ptr = null_mut::<libc::FILE>() ;
                    Ok(())
                } else {
                    get_error()
                }
            } else {
                Ok(())
            }
        }
    }

    /// Returns the underlying file pointer as a reference. It is returned as a reference to, in theory,
    /// prevent it from being used after the file is closed.
    pub unsafe fn file<'a>(&'a mut self) -> &'a mut libc::FILE {
        &mut (*self.file_ptr)
    }

    /// Returns the current position in the file.
    /// # Errors
    /// On error Error::Errno(errno) is returned.
    pub fn current_pos(&self) -> Result<u64, Error> {
        unsafe {
            let pos = libc::ftell(self.file_ptr);
            if pos != -1 {
                Ok(pos as u64)
            } else {
                get_error()
            }
        }
    }

    /// A utility function to expand a vector without increasing its capacity more than it needs
    /// to be expanded.
    fn expand_buffer(buff: &mut Vec<u8>, by: usize) {
        if buff.capacity() < buff.len() + by {
            buff.reserve(by);
        }
        for _ in 0..by {
            buff.push(0u8);
        }
    }
}

impl Write for CFile {

    /// Attempts to write all of the bytes in buf to the file.
    /// # Errors
    /// If an error occurs during writing, Error::WriteError(bytes_written, errno) will be
    /// returned.
    /// # Examples
    /// ```
    /// use cfile_rs;
    /// use cfile_rs::*;
    /// use cfile_rs::CFile;
    /// use cfile_rs::TRUNCATAE_RANDOM_ACCESS_MODE;
    /// use std::str::from_utf8;
    ///
    /// // Truncate random access mode will overwrite the old "data.txt" file if it exists.
    /// let mut file = CFile::open("data.txt", TRUNCATAE_RANDOM_ACCESS_MODE).unwrap();
    /// let _ = file.write_all("Howdy folks".as_bytes());   // Write some data!
    ///
    /// ```
    fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> {
        unsafe {
            let written_bytes = libc::fwrite(buf.as_ptr() as *const libc::c_void, 1, buf.len(), self.file_ptr);
            if written_bytes != buf.len() {
                get_error()
            } else {
                Ok(())
            }
        }
    }

    /// Attempts to write all of the bytes in buf to the file.
    /// # Errors
    /// If an error occurs during writing, Error::WriteError(bytes_written, errno) will be
    /// returned.
    /// # Examples
    /// ```
    /// use cfile_rs;
    /// use cfile_rs::*;
    /// use cfile_rs::CFile;
    /// use cfile_rs::TRUNCATAE_RANDOM_ACCESS_MODE;
    /// use std::str::from_utf8;
    ///
    /// // Truncate random access mode will overwrite the old "data.txt" file if it exists.
    /// let mut file = CFile::open("data.txt", TRUNCATAE_RANDOM_ACCESS_MODE).unwrap();
    /// let _ = file.write("Howdy folks".as_bytes());   // Write some data!
    ///
    /// ```
    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
        unsafe {
            let written_bytes = libc::fwrite(buf.as_ptr() as *const libc::c_void, 1, buf.len(), self.file_ptr);
            if written_bytes != buf.len() {
                get_error()
            } else {
                Ok(written_bytes)
            }
        }
    }

    /// Flushes the underlying output stream, meaning it actually writes everything to the
    /// filesystem.
    /// # Examples
    /// ```
    /// use cfile_rs;
    /// use cfile_rs::SeekFrom;
    /// use cfile_rs::CFile;
    /// use cfile_rs::TRUNCATAE_RANDOM_ACCESS_MODE;
    /// use cfile_rs::*;
    ///
    /// // Truncate random access mode will overwrite the old "data.txt" file if it exists.
    /// let mut file = CFile::open("data.txt", TRUNCATAE_RANDOM_ACCESS_MODE).unwrap();
    /// match file.write_all("Howdy folks!".as_bytes()) {
    ///     Ok(()) => println!("Successfully wrote to the file!"),
    ///     Err(err) => {
    ///         println!("Encountered error: {}", err);
    ///     }
    /// };
    /// let _ = file.flush();   // Upon this call, all data waiting in the output
    ///                         // stream will be written to the file
    /// ```
    fn flush(&mut self) -> Result<(), Error> {
        unsafe {
            let result = libc::fflush(self.file_ptr);
            if result == 0 {
                Ok(())
            } else {
                get_error()
            }
        }
    }
}

impl Read for CFile {
    /// Reads the entire file starting from the current position, expanding buf as needed. On a successful
    /// read, this function will return Ok(bytes_read).
    /// # Errors
    /// If an error occurs during reading, some varient of error will be returned.
    /// # Examples
    /// ```
    /// use cfile_rs;
    /// use cfile_rs::CFile;
    /// use cfile_rs::TRUNCATAE_RANDOM_ACCESS_MODE;
    /// use std::str::from_utf8;
    /// use std::io::{ Seek, SeekFrom, Read, Write };
    ///
    /// // Truncate random access mode will overwrite the old "data.txt" file if it exists.
    /// let mut file = CFile::open("data.txt", TRUNCATAE_RANDOM_ACCESS_MODE).unwrap();
    /// let _ = file.write_all("Howdy folks".as_bytes());   // Write some data!
    /// let _ = file.seek(SeekFrom::Start(0));              // Move back to the beginning of the file
    /// let mut buffer = cfile_rs::buffer(10);              // Create a buffer (a Vec<u8>) to read into
    /// match file.read_to_end(&mut buffer) {               // Read the entire file, expanding our buffer as needed
    ///     Ok(bytes_read) => {
    ///         // It is a bad idea to do this unless you know it is valid utf8
    ///         let as_str = from_utf8(&buffer[0..bytes_read]).unwrap();
    ///         println!("Read '{}' from the file.", as_str);
    ///     },
    ///     Err(err) => {
    ///         println!("Encountered error: {}", err);
    ///     }
    /// };
    /// ```
    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error> {
        let pos = self.current_pos();
        let _ = self.seek(SeekFrom::End(0));
        let end = self.current_pos();
        match pos {
            Ok(cur_pos) => {
                match end {
                    Ok(end_pos) => {
                        if end_pos == cur_pos { return Ok(0) }
                        let to_read = (end_pos - cur_pos) as usize;
                        println!("to_read {}", to_read);
                        if buf.len() < to_read {
                            let to_reserve = to_read - buf.len();
                            Self::expand_buffer(buf, to_reserve);
                        }
                        let _ = self.seek(SeekFrom::Start(cur_pos as u64));
                        match self.read_exact(buf) {
                            Ok(()) => {
                                Ok(to_read)
                            },
                            Err(e) => Err(e)
                        }
                    },
                    Err(e) => Err(e)
                }
            },
            Err(e) => Err(e)
        }
    }

    /// Reads exactly the number of bytes required to fill buf.
    /// # Errors
    /// If the end of the file is reached before buf is filled, Err(EndOfFile(bytes_read)) will be
    /// returned. The data that was read before that will still have been placed into buf.
    ///
    /// Upon some other error, Err(Errno(errno)) will be returned.
    /// # Examples
    /// ```
    ///
    /// ```
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        unsafe {
            let result = libc::fread(buf.as_ptr() as *mut libc::c_void, 1, buf.len(), self.file_ptr);
            if result != buf.len() {
                match get_error::<u8>() {
                    Err(err) => {
                        if err.kind() == ErrorKind::UnexpectedEof {
                            Ok(result)
                        } else {
                            Err(err)
                        }
                    },
                    Ok(_) => panic!("This is impossible")
                }
            } else {
                Ok(result)
            }
        }
    }

    /// Reads exactly the number of bytes required to fill buf.
    /// # Errors
    /// If the end of the file is reached before buf is filled, Err(EndOfFile(bytes_read)) will be
    /// returned. The data that was read before that will still have been placed into buf.
    ///
    /// Upon some other error, Err(Errno(errno)) will be returned.
    /// # Examples
    /// ```
    ///
    /// ```
    fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error> {
        unsafe {
            let result = libc::fread(buf.as_ptr() as *mut libc::c_void, 1, buf.len(), self.file_ptr);
            if result == buf.len() {
                Ok(())
            } else {
                // Check if we hit the end of the file
                if libc::feof(self.file_ptr) != 0 {
                    get_error()
                } else {
                    get_error()
                }
            }
        }
    }
}

impl Seek for CFile {
    /// Changes the current position in the file using the SeekFrom enum.
    ///
    /// To set relative to the beginning of the file (i.e. index is 0 + offset):
    /// ```
    /// SeekFrom::Start(offset)
    /// ```
    /// To set relative to the end of the file (i.e. index is file_lenth - 1 - offset):
    /// ```
    /// SeekFrom::End(offset)
    /// ```
    /// To set relative to the current position:
    /// ```
    /// SeekFrom::End(offset)
    /// ```
    /// # Errors
    /// On error Error::Errno(errno) is returned.
    fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
        unsafe {
            let result = match pos {
                SeekFrom::Start(from) =>
                    libc::fseek(self.file_ptr, from as libc::c_long, libc::SEEK_SET),
                SeekFrom::End(from) =>
                    libc::fseek(self.file_ptr, from as libc::c_long, libc::SEEK_END),
                SeekFrom::Current(delta) =>
                    libc::fseek(self.file_ptr, delta as libc::c_long, libc::SEEK_CUR)
            };
            if result == 0 {
                self.current_pos()
            } else {
                get_error()
            }
        }
    }
}

impl Drop for CFile {
    /// Ensures the file stream is closed before abandoning the data.
    fn drop(&mut self) {
        let _ = unsafe {
            if !self.file_ptr.is_null() {
                let res = libc::fclose(self.file_ptr);
                if res == 0 {
                    self.file_ptr = null_mut::<libc::FILE>() ;
                    Ok(())
                } else {
                    get_error()
                }
            } else {
                Ok(())
            }
        };
    }
}

#[cfg(test)]
mod tests {
    use std::str;
    use CFile;
    use SeekFrom;
    use Read;
    use Write;
    use Seek;
    use buffer;
    use TRUNCATAE_RANDOM_ACCESS_MODE;
    #[test]
    fn file_flush() {
        let mut file = CFile::open("data.txt", TRUNCATAE_RANDOM_ACCESS_MODE).unwrap();
        match file.write_all("Howdy folks!".as_bytes()) {
            Ok(()) => println!("Successfully wrote to the file!"),
            Err(e) => {
                // darn
            }
        };
        let _ = file.flush();                       // Probably unnecessary
        let buf_size = 20;
        let mut buf = buffer(buf_size);      // 20 will be more than enough to store our data
        let _ = file.seek(SeekFrom::Start(0));      // Move to 1 byte after the beginning of the file
        let result = file.read_exact(&mut buf);     // Read exactly 20 bytes
        match result {
            Ok(()) => {                             // This won't happen since we only wrote 12 bytes,
                let data = &buf[0..buf_size];       // but if it did this is how we could print the data
                                                    // as a string.
                let str = str::from_utf8(data).unwrap();
                println!("{}", str);
            },
            Err(e) => {
                // Oh no!
            },
        };
    }
}