rgsl/
utilities.rs

1//
2// A rust binding for the GSL library by Guillaume Gomez (guillaume1.gomez@gmail.com)
3//
4
5use std::ffi::CString;
6use std::io;
7use std::ops::Drop;
8use std::os::raw::c_char;
9use std::path::Path;
10
11use sys::libc::{fclose, fopen, FILE};
12
13#[allow(dead_code)]
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15enum Mode {
16    Write,
17    Read,
18}
19
20/// A wrapper to handle I/O operations between GSL and rust
21#[allow(clippy::upper_case_acronyms)]
22pub struct IOStream {
23    inner: *mut FILE,
24    mode: Mode,
25}
26
27impl IOStream {
28    /// Open a file in write mode.
29    pub fn fwrite_handle<P: AsRef<Path>>(file: &P) -> io::Result<IOStream> {
30        let path = CString::new(file.as_ref().to_str().unwrap()).unwrap();
31        let ptr = unsafe { fopen(path.as_ptr(), b"w\0".as_ptr() as *const c_char) };
32        if ptr.is_null() {
33            return Err(io::Error::new(
34                io::ErrorKind::Other,
35                "Failed to open file...",
36            ));
37        }
38        Ok(IOStream {
39            inner: ptr,
40            mode: Mode::Write,
41        })
42    }
43
44    pub fn write_mode(&self) -> bool {
45        self.mode == Mode::Write
46    }
47
48    #[doc(hidden)]
49    pub fn as_raw(&mut self) -> *mut FILE {
50        self.inner
51    }
52}
53
54impl Drop for IOStream {
55    fn drop(&mut self) {
56        unsafe {
57            fclose(self.inner);
58            self.inner = std::ptr::null_mut();
59        }
60    }
61}