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
/// Utilities for interfacing with GSL/C
use std::ffi::CString;
use std::io;
use std::ops::Drop;
use std::os::raw::c_char;
use std::path::Path;

use sys::libc::{fclose, fopen, FILE};

#[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
    Write,
    Read,
}

/// A wrapper to handle I/O operations between GSL and rust
#[allow(clippy::upper_case_acronyms)]
pub struct IOStream {
    inner: *mut FILE,
    mode: Mode,
}

impl IOStream {
    /// Open a file in write mode.
    pub fn fwrite_handle<P: AsRef<Path>>(file: &P) -> io::Result<IOStream> {
        let path = CString::new(file.as_ref().to_str().unwrap()).unwrap();
        let ptr = unsafe { fopen(path.as_ptr(), b"w\0".as_ptr() as *const c_char) };
        if ptr.is_null() {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Failed to open file...",
            ));
        }
        Ok(IOStream {
            inner: ptr,
            mode: Mode::Write,
        })
    }

    pub fn write_mode(&self) -> bool {
        self.mode == Mode::Write
    }

    #[doc(hidden)]
    pub fn as_raw(&mut self) -> *mut FILE {
        self.inner
    }
}

impl Drop for IOStream {
    fn drop(&mut self) {
        unsafe {
            fclose(self.inner);
            self.inner = ::std::ptr::null_mut();
        }
    }
}