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
//!This crate aims at safely wrapping PhysicsFs, a library that implements a virtual file system
//!mainly for moddable videogames. Still WIP.

use physfs_sys;
use std::fmt;

static mut INSTANCED: bool = false;

///Represents an error returned by PhysicsFs
pub struct PhysFsError {
    code: physfs_sys::PHYSFS_ErrorCode,
}

impl PhysFsError {
    pub(crate) fn new(code: physfs_sys::PHYSFS_ErrorCode) -> Self {
        Self { code }
    }

    pub fn get_text(&self) -> String {
        let v = unsafe {
            std::ffi::CStr::from_ptr(physfs_sys::PHYSFS_getErrorByCode(self.code))
                .to_bytes()
                .to_vec()
        };

        String::from_utf8(v).unwrap()
    }
}

impl fmt::Debug for PhysFsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PhysFsError")
            .field("code", &self.code)
            .field("text", &self.get_text())
            .finish()
    }
}

impl fmt::Display for PhysFsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.get_text())
    }
}

use std::error::Error;

impl Error for PhysFsError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

///A handle to a file opend through PhysicsFs
pub struct PhysFsHandle {
    handle: *mut physfs_sys::PHYSFS_File,
}

impl PhysFsHandle {
    pub(crate) fn new(handle: *mut physfs_sys::PHYSFS_File) -> Self {
        Self { handle }
    }

    pub fn file_length(&self) -> u64 {
        unsafe { physfs_sys::PHYSFS_fileLength(self.handle) as u64 }
    }

    pub fn read_to_vec(&mut self) -> std::io::Result<Vec<u8>> {
        let len = self.file_length() as usize;
        let mut v = Vec::with_capacity(len);
        v.resize(len, 0);
        std::io::Read::read(self, v.as_mut_slice())?;
        Ok(v)
    }

    pub fn close(self) {}
}

//PhysFs is supposed to manage concurrent access on its own
//through a global mutex so it should be thread safe
unsafe impl Send for PhysFsHandle {}
unsafe impl Sync for PhysFsHandle {}

impl std::io::Read for PhysFsHandle {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        Ok(unsafe {
            physfs_sys::PHYSFS_readBytes(
                self.handle,
                buf.as_mut_ptr() as *mut std::ffi::c_void,
                buf.len() as u64,
            ) as usize
        })
    }
}

impl std::io::Write for PhysFsHandle {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        Ok(unsafe {
            physfs_sys::PHYSFS_writeBytes(
                self.handle,
                buf.as_ptr() as *const std::ffi::c_void,
                buf.len() as u64,
            ) as usize
        })
    }

    fn flush(&mut self) -> std::io::Result<()> {
        unsafe {
            let ret = physfs_sys::PHYSFS_flush(self.handle);
            if ret != 0 {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    get_last_error().err().unwrap(),
                ));
            }
        }
        Ok(())
    }
}

use std::io::SeekFrom;
impl std::io::Seek for PhysFsHandle {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        match pos {
            SeekFrom::Start(pos) => unsafe {
                let ret = physfs_sys::PHYSFS_seek(self.handle, pos);
                if ret == 0 {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        get_last_error().err().unwrap(),
                    ))
                } else {
                    Ok(physfs_sys::PHYSFS_tell(self.handle) as u64)
                }
            },
            SeekFrom::Current(pos) => unsafe {
                let cpos = physfs_sys::PHYSFS_tell(self.handle);
                self.seek(SeekFrom::Start((cpos + pos) as u64))
            },
            SeekFrom::End(pos) => unsafe {
                let cpos = physfs_sys::PHYSFS_fileLength(self.handle);
                self.seek(SeekFrom::Start((cpos + pos) as u64))
            },
        }
    }
}

impl Drop for PhysFsHandle {
    fn drop(&mut self) {
        unsafe {
            let _res = physfs_sys::PHYSFS_close(self.handle);
            //TODO check error code?
        }
    }
}

fn get_last_error() -> Result<(), PhysFsError> {
    Err(unsafe { PhysFsError::new(physfs_sys::PHYSFS_getLastErrorCode()) })
}

///This struct doesn't store any state, his sole purpose is to ensure that all PhysicsFs calls
///are done after calling his init function. Only ine instance of it can exist at any given time.
///This is because PhysicsFs has a global state so this struct makes sure rust borrowing rules are
///enforced
pub struct PhysFs {}

fn create_ctsr(s: impl AsRef<str>) -> std::ffi::CString {
    std::ffi::CString::new(s.as_ref().as_bytes()).unwrap()
}

macro_rules! to_cstr {
    ($s:expr) => {
        create_ctsr($s).as_bytes().as_ptr() as *const i8
    };
}

impl PhysFs {
    fn new() -> Self {
        unsafe {
            physfs_sys::PHYSFS_init(std::ptr::null());
        }

        Self {}
    }

    ///When calling this method for the first time an instance of Self will be returned, if called
    ///again it will return None ensuring that no more than one instance exists
    pub fn get() -> Option<Self> {
        //TODO: make thread safe
        unsafe {
            let ret = if !INSTANCED { Some(Self::new()) } else { None };
            INSTANCED = true;

            ret
        }
    }

    ///Mounts `dir` to `mount_point`.
    ///`dir` can either be a path to an archive of a supported format or to a directory
    pub fn mount(
        &mut self,
        dir: impl AsRef<str>,
        mount_point: impl AsRef<str>,
        append: bool,
    ) -> Result<(), PhysFsError> {
        unsafe {
            if 0 == physfs_sys::PHYSFS_mount(
                to_cstr!(dir),
                to_cstr!(mount_point),
                if append { 1 } else { 0 },
            ) {
                get_last_error()?;
            }
        }

        Ok(())
    }

    unsafe fn make_handle(
        &self,
        handle: *mut physfs_sys::PHYSFS_File,
    ) -> Result<PhysFsHandle, PhysFsError> {
        if handle == std::ptr::null_mut() {
            get_last_error()?;
        }

        Ok(PhysFsHandle::new(handle))
    }

    ///Open file inside virtual fs for reading
    pub fn open_read(&self, path: impl AsRef<str>) -> Result<PhysFsHandle, PhysFsError> {
        unsafe { self.make_handle(physfs_sys::PHYSFS_openRead(to_cstr!(path))) }
    }

    ///Open file inside virtual fs for writing. If the file already exists it will be truncated
    pub fn open_write(&self, path: impl AsRef<str>) -> Result<PhysFsHandle, PhysFsError> {
        unsafe { self.make_handle(physfs_sys::PHYSFS_openWrite(to_cstr!(path))) }
    }

    ///Open file inside virtual fs for writing. If the file already exists new writes will be
    ///appended to the existing contents
    pub fn open_append(&self, path: impl AsRef<str>) -> Result<PhysFsHandle, PhysFsError> {
        unsafe { self.make_handle(physfs_sys::PHYSFS_openAppend(to_cstr!(path))) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::*;

    const TEST_TEXT: &'static str = "testing\n";
    #[test]
    fn it_works() {
        let mut fs = PhysFs::get().unwrap();
        fs.mount("alol.zip", "", true).err().unwrap(); //muest give none
        fs.mount("test.zip", "", true).unwrap();
        fs.mount("./", "", true).unwrap();
        let mut handle = fs.open_read("test").unwrap();

        assert_eq!(handle.file_length(), 8);
        let mut buf = [0; 8];
        handle.read(&mut buf).unwrap();
        assert_eq!(String::from_utf8_lossy(&buf), TEST_TEXT);
        handle.close();

        let mut handle = fs.open_read("test").unwrap();
        assert_eq!(handle.read_to_vec().unwrap(), TEST_TEXT.as_bytes().to_vec());

        assert!(PhysFs::get().is_none());
    }
}