use core::ptr::{null_mut, NonNull};
use std::io::{Error, ErrorKind, Read, Seek, SeekFrom};
use libc::{
c_long, c_void, fclose, fread, fseek, ftell, SEEK_CUR, SEEK_END, SEEK_SET,
};
#[allow(clippy::upper_case_acronyms)]
pub type FILE_NC = crate::ffi::FILE;
#[allow(clippy::upper_case_acronyms)]
pub type FILE_LIBC = libc::FILE;
pub static RANDOM_ACCESS_MODE: &str = "rb+";
pub static UPDATE: &str = "rb+";
pub static READ_ONLY: &str = "r";
pub static WRITE_ONLY: &str = "w";
pub static APPEND_ONLY: &str = "a";
pub static APPEND_READ: &str = "a+";
pub static TRUNCATE_RANDOM_ACCESS_MODE: &str = "wb+";
fn get_error<T>() -> Result<T, Error> {
Err(Error::last_os_error())
}
#[derive(Debug)]
pub struct NcFile {
file_ptr: NonNull<FILE_LIBC>,
}
impl NcFile {
pub fn from_nc(file: *mut FILE_NC) -> Self {
NcFile {
file_ptr: unsafe { NonNull::new_unchecked(NcFile::nc2libc(file)) },
}
}
#[allow(clippy::missing_safety_doc)]
pub unsafe fn from_libc(file: *mut FILE_LIBC) -> Self {
NcFile {
file_ptr: NonNull::new_unchecked(file),
}
}
#[inline]
pub fn as_libc_ptr(&self) -> *mut FILE_LIBC {
self.file_ptr.as_ptr()
}
#[inline]
pub fn as_nc_ptr(&self) -> *mut FILE_NC {
Self::libc2nc(self.file_ptr.as_ptr())
}
pub fn current_pos(&self) -> Result<u64, Error> {
unsafe {
let pos = ftell(self.as_libc_ptr());
if pos != -1 {
Ok(pos as u64)
} else {
get_error()
}
}
}
#[inline]
pub fn read_all(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error> {
let _ = self.seek(SeekFrom::Start(0));
self.read_to_end(buf)
}
#[inline]
fn nc2libc(file: *mut FILE_NC) -> *mut FILE_LIBC {
file as *mut _ as *mut FILE_LIBC
}
#[inline]
fn libc2nc(file: *mut FILE_LIBC) -> *mut FILE_NC {
file as *mut _ as *mut FILE_NC
}
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 Read for NcFile {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
unsafe {
let result = fread(
buf.as_ptr() as *mut c_void,
1,
buf.len(),
self.as_libc_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)
}
}
}
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;
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),
}
}
fn read_to_string(&mut self, strbuf: &mut String) -> Result<usize, Error> {
let mut bytes_read = 0_usize;
let mut buffer = vec![0u8];
let result = self.read_all(&mut buffer);
if let Ok(bytes) = result {
bytes_read = bytes;
}
if let Err(e) = result {
return Err(e);
}
let result = std::str::from_utf8(&buffer);
if let Ok(strslice) = result {
*strbuf = strslice.to_string();
Ok(bytes_read)
} else {
get_error()
}
}
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error> {
unsafe {
let result = fread(
buf.as_ptr() as *mut c_void,
1,
buf.len(),
self.as_libc_ptr(),
);
if result == buf.len() {
Ok(())
} else {
get_error()
}
}
}
}
impl Seek for NcFile {
fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
unsafe {
let result = match pos {
SeekFrom::Start(from) => fseek(self.as_libc_ptr(), from as c_long, SEEK_SET),
SeekFrom::End(from) => fseek(self.as_libc_ptr(), from as c_long, SEEK_END),
SeekFrom::Current(delta) => fseek(self.as_libc_ptr(), delta as c_long, SEEK_CUR),
};
if result == 0 {
self.current_pos()
} else {
get_error()
}
}
}
}
impl Drop for NcFile {
fn drop(&mut self) {
let _ = unsafe {
if !(self.as_libc_ptr()).is_null() {
let res = fclose(self.as_libc_ptr());
if res == 0 {
self.file_ptr = NonNull::new_unchecked(null_mut::<FILE_LIBC>());
Ok(())
} else {
get_error()
}
} else {
Ok(())
}
};
}
}