Format with rustfmt

This commit is contained in:
Josh Mitchell
2020-11-07 20:03:05 +11:00
parent 042f0f82c6
commit e30a175d0d
9 changed files with 204 additions and 139 deletions

View File

@@ -1,5 +1,5 @@
pub mod xdr_seek;
#[allow(non_upper_case_globals)]
pub mod xdrfile;
pub mod xdrfile_trr;
pub mod xdrfile_xtc;
pub mod xdr_seek;

View File

@@ -103,12 +103,11 @@ extern "C" {
pub fn xdr_flush(xd: *mut XDRFILE) -> ::std::os::raw::c_int;
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::xdrfile_xtc::*;
use super::*;
use std::ffi::CString;
#[test]
@@ -129,10 +128,15 @@ mod tests {
let tell = xdr_tell(xdr);
assert!(tell == 0, "{}", tell);
read_xtc(xdr, num_atoms, &mut step, &mut time,
read_xtc(
xdr,
num_atoms,
&mut step,
&mut time,
box_vec.as_ptr() as *mut Matrix,
x_p,
&mut prec);
&mut prec,
);
let tell = xdr_tell(xdr);
assert!(tell > 0, "{}", tell);

View File

@@ -1,4 +1,3 @@
pub const DIM: u32 = 3;
#[repr(C)]
@@ -7,7 +6,6 @@ pub struct XDRFILE {
_unused: [u8; 0],
}
pub type BindgenTy1 = u32;
pub const exdrOK: BindgenTy1 = 0;
pub const exdrHEADER: BindgenTy1 = 1;

View File

@@ -1,6 +1,5 @@
use super::xdrfile::*;
extern "C" {
pub fn read_trr_natoms(
fn_: *const ::std::os::raw::c_char,
@@ -83,17 +82,23 @@ mod tests {
let box_vec: Matrix = [[1.0, 2.0, 3.0], [2.0, 1.0, 3.0], [3.0, 2.0, 1.0]];
let x: Vec<Rvec> = vec![[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]];
let v: Vec<Rvec> = vec![[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]];
let v: Vec<Rvec> = vec![[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]];
let f: Vec<Rvec> = vec![[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]];
unsafe {
let mode = CString::new("w").unwrap();
let xdr = xdrfile_open(tmp_path.as_ptr(), mode.as_ptr());
let write_code = write_trr(xdr, natoms, step, time, lambda,
let write_code = write_trr(
xdr,
natoms,
step,
time,
lambda,
box_vec.as_ptr() as *mut Matrix,
x.as_ptr() as *mut Rvec,
v.as_ptr() as *mut Rvec,
f.as_ptr() as *mut Rvec);
f.as_ptr() as *mut Rvec,
);
assert!(write_code as u32 == exdrOK);
xdrfile_close(xdr);
}
@@ -111,11 +116,17 @@ mod tests {
unsafe {
let mode = CString::new("r").unwrap();
let xdr = xdrfile_open(tmp_path.as_ptr(), mode.as_ptr());
let read_code = read_trr(xdr, natoms, &mut step2, &mut time2,
&mut lambda2, box_vec2.as_ptr() as *mut Matrix,
let read_code = read_trr(
xdr,
natoms,
&mut step2,
&mut time2,
&mut lambda2,
box_vec2.as_ptr() as *mut Matrix,
x2.as_ptr() as *mut Rvec,
v2.as_ptr() as *mut Rvec,
f2.as_ptr() as *mut Rvec);
f2.as_ptr() as *mut Rvec,
);
assert!(read_code as u32 == exdrOK);
xdrfile_close(xdr);
}
@@ -129,5 +140,4 @@ mod tests {
assert!(v2 == v);
assert!(f2 == f);
}
}

View File

@@ -1,6 +1,5 @@
use super::xdrfile::*;
extern "C" {
pub fn read_xtc_natoms(
fn_: *const ::std::os::raw::c_char,
@@ -81,9 +80,15 @@ mod tests {
unsafe {
let mode = CString::new("w").unwrap();
let xdr = xdrfile_open(tmp_path.as_ptr(), mode.as_ptr());
let write_code = write_xtc(xdr, natoms, step, time,
box_vec.as_ptr() as *mut Matrix, x.as_ptr() as *mut Rvec,
1000.0);
let write_code = write_xtc(
xdr,
natoms,
step,
time,
box_vec.as_ptr() as *mut Matrix,
x.as_ptr() as *mut Rvec,
1000.0,
);
assert!(write_code as u32 == exdrOK);
xdrfile_close(xdr);
}
@@ -98,9 +103,15 @@ mod tests {
unsafe {
let mode = CString::new("r").unwrap();
let xdr = xdrfile_open(tmp_path.as_ptr(), mode.as_ptr());
let read_code = read_xtc(xdr, natoms, &mut step2, &mut time2,
box_vec2.as_ptr() as *mut Matrix, x2.as_ptr() as *mut Rvec,
&mut prec);
let read_code = read_xtc(
xdr,
natoms,
&mut step2,
&mut time2,
box_vec2.as_ptr() as *mut Matrix,
x2.as_ptr() as *mut Rvec,
&mut prec,
);
assert!(read_code as u32 == exdrOK);
xdrfile_close(xdr);
}

View File

@@ -26,23 +26,28 @@ impl Default for Frame {
step: 0,
time: 0.0,
box_vector: [[0.0; 3]; 3],
coords: Vec::with_capacity(0)
coords: Vec::with_capacity(0),
}
}
}
impl fmt::Debug for Frame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Frame {{ atoms: {}, step: {}, time: {}, \
box: {:?}, coords: {:?} }}", self.num_atoms, self.step, self.time,
self.box_vector, self.coords)
write!(
f,
"Frame {{ atoms: {}, step: {}, time: {}, \
box: {:?}, coords: {:?} }}",
self.num_atoms, self.step, self.time, self.box_vector, self.coords
)
}
}
impl Frame {
/// Creates an empty frame with a capacity of 0
pub fn new() -> Frame {
Frame{ ..Default::default() }
Frame {
..Default::default()
}
}
/// Creates a frame with the given capacity
@@ -52,12 +57,13 @@ impl Frame {
coords: vec![[0.0, 0.0, 0.0]; num_atoms as usize],
..Default::default()
}
}
/// Filters the frame by removing all atoms not matching the given indeces.
pub fn filter_coords(self: &mut Frame, indeces: &[usize]) {
self.coords = self.coords.iter()
self.coords = self
.coords
.iter()
.map(|elem| elem.clone())
.enumerate()
.filter(|&(i, _)| indeces.contains(&i))
@@ -72,8 +78,6 @@ impl Frame {
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -91,7 +95,7 @@ mod tests {
frame.coords[0] = [1.0, 2.0, 3.0];
frame.coords[1] = [4.0, 5.0, 6.0];
frame.coords[2] = [7.0, 8.0, 9.0];
let filter: Vec<usize> = vec![1,2];
let filter: Vec<usize> = vec![1, 2];
let mut frame_new = frame.clone();
frame_new.filter_coords(&filter);
assert!(frame_new.num_atoms as usize == filter.len());

View File

@@ -1,5 +1,5 @@
use crate::*;
use crate::c_abi::xdrfile::exdrENDOFFILE;
use crate::*;
use failure::Error;
use std::rc::Rc;
@@ -13,7 +13,7 @@ impl IntoIterator for XTCTrajectory {
XTCTrajectoryIterator {
trajectory: self,
item: Rc::new(Frame::with_capacity(num_atoms)),
has_error: false
has_error: false,
}
}
}
@@ -32,18 +32,19 @@ pub struct XTCTrajectoryIterator {
impl Iterator for XTCTrajectoryIterator {
type Item = Result<Rc<Frame>, Error>;
fn next(&mut self) -> Option<Self::Item> { // Reuse old frame
fn next(&mut self) -> Option<Self::Item> {
// Reuse old frame
if self.has_error {
return None;
}
let item: &mut Frame = match Rc::get_mut(&mut self.item) {
Some(item) => item,
None => { // caller kept frame. Create new one
None => {
// caller kept frame. Create new one
self.item = Rc::new(Frame::with_capacity(self.item.num_atoms));
Rc::get_mut(&mut self.item).unwrap()
}
};
match self.trajectory.read(item) {
Ok(()) => Some(Ok(Rc::clone(&self.item))),
@@ -69,7 +70,7 @@ impl IntoIterator for TRRTrajectory {
TRRTrajectoryIterator {
trajectory: self,
item: Rc::new(Frame::with_capacity(num_atoms)),
has_error: false
has_error: false,
}
}
}
@@ -88,18 +89,19 @@ pub struct TRRTrajectoryIterator {
impl Iterator for TRRTrajectoryIterator {
type Item = Result<Rc<Frame>, Error>;
fn next(&mut self) -> Option<Self::Item> { // Reuse old frame
fn next(&mut self) -> Option<Self::Item> {
// Reuse old frame
if self.has_error {
return None;
}
let item: &mut Frame = match Rc::get_mut(&mut self.item) {
Some(item) => item,
None => { // caller kept frame. Create new one
None => {
// caller kept frame. Create new one
self.item = Rc::new(Frame::with_capacity(self.item.num_atoms));
Rc::get_mut(&mut self.item).unwrap()
}
};
match self.trajectory.read(item) {
Ok(()) => Some(Ok(Rc::clone(&self.item))),

View File

@@ -58,33 +58,33 @@
//! }
//! ```
#[cfg(test)]
#[macro_use] extern crate assert_approx_eq;
#[macro_use]
extern crate assert_approx_eq;
extern crate lazy_init;
pub mod c_abi;
mod frame;
mod iterator;
pub mod c_abi;
pub use frame::Frame;
pub use iterator::*;
use c_abi::xdr_seek;
use c_abi::xdrfile;
use c_abi::xdrfile::XDRFILE;
use c_abi::xdr_seek;
use c_abi::xdrfile_xtc;
use c_abi::xdrfile_trr;
use c_abi::xdrfile_xtc;
use failure::{err_msg, Error};
use lazy_init::Lazy;
use std::cell::Cell;
use std::ffi::CString;
use std::path::Path;
use failure::{Error,err_msg};
use std::cell::Cell;
use lazy_init::Lazy;
pub enum FileMode {
Write,
Append,
Read
Read,
}
impl FileMode {
@@ -98,8 +98,8 @@ impl FileMode {
}
fn path_to_cstring(path: &Path) -> CString {
CString::new(path.to_str().unwrap()).unwrap()
}
CString::new(path.to_str().unwrap()).unwrap()
}
/// A safe wrapper around the c implementation of an XDRFile
struct XDRFile {
@@ -109,7 +109,6 @@ struct XDRFile {
}
impl XDRFile {
pub fn open(path: &Path, filemode: FileMode) -> Result<XDRFile, Error> {
let path_p = path_to_cstring(path).into_raw();
let mode_p = CString::new(filemode.value()).unwrap().into_raw();
@@ -117,10 +116,15 @@ impl XDRFile {
unsafe {
let xdrfile = xdrfile::xdrfile_open(path_p, mode_p);
if ! xdrfile.is_null() {
if !xdrfile.is_null() {
let path = String::from(path.to_str().unwrap());
Ok(XDRFile { xdrfile, filemode, path })
} else { // Something went wrong. But the C api does not tell us what
Ok(XDRFile {
xdrfile,
filemode,
path,
})
} else {
// Something went wrong. But the C api does not tell us what
Err(err_msg("Failed to open trajectory file"))
}
}
@@ -138,7 +142,6 @@ impl Drop for XDRFile {
/// The trajectory trait defines shared methods for xtc and trr trajectories
pub trait Trajectory {
/// Read the next step of the trajectory into the frame object
fn read(&mut self, frame: &mut Frame) -> Result<(), Error>;
@@ -155,53 +158,65 @@ pub trait Trajectory {
/// Read/Write XTC Trajectories
pub struct XTCTrajectory {
handle: XDRFile,
precision: Cell<f32>, // internal mutability required for read method
num_atoms: Lazy<Result<u32, Error>>
precision: Cell<f32>, // internal mutability required for read method
num_atoms: Lazy<Result<u32, Error>>,
}
impl XTCTrajectory {
pub fn open(path: &Path, filemode: FileMode) -> Result<XTCTrajectory, Error> {
let xdr = XDRFile::open(path, filemode)?;
Ok(XTCTrajectory { handle: xdr, precision: Cell::new(1000.0), num_atoms: Lazy::new() })
Ok(XTCTrajectory {
handle: xdr,
precision: Cell::new(1000.0),
num_atoms: Lazy::new(),
})
}
}
impl Trajectory for XTCTrajectory {
fn read(&mut self, frame: &mut Frame) -> Result<(), Error> {
unsafe {
// C lib requires an i32 to be passed, but step is exposed it as u32
// (A step cannot be negative, can it?). So we need to create a step
// variable to pass to read_xtc and cast it afterwards to u32
let mut step: i32 = 0;
let code = xdrfile_xtc::read_xtc(self.handle.xdrfile,
let code = xdrfile_xtc::read_xtc(
self.handle.xdrfile,
frame.num_atoms as i32,
&mut step,
&mut frame.time,
&mut frame.box_vector,
frame.coords.as_ptr() as *mut [f32; 3],
&mut self.precision.get(),
) as u32;
) as u32;
frame.step = step as u32;
match code {
xdrfile::exdrOK => Ok(()),
_ => Err(err_msg(format!("Failed to read trajectory. Error code: {}", code))),
_ => Err(err_msg(format!(
"Failed to read trajectory. Error code: {}",
code
))),
}
}
}
fn write(&mut self, frame: &Frame) -> Result<(), Error> {
unsafe {
let code = xdrfile_xtc::write_xtc(self.handle.xdrfile,
let code = xdrfile_xtc::write_xtc(
self.handle.xdrfile,
frame.num_atoms as i32,
frame.step as i32,
frame.time,
frame.box_vector.as_ptr() as *mut [[f32; 3]; 3],
frame.coords[..].as_ptr() as *mut [f32; 3],
1000.0) as u32;
1000.0,
) as u32;
match code {
xdrfile::exdrOK => Ok(()),
_ => Err(err_msg(format!("Failed to write trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to write trajectory. Error code: {}",
code
))),
}
}
}
@@ -211,7 +226,10 @@ impl Trajectory for XTCTrajectory {
let code = xdr_seek::xdr_flush(self.handle.xdrfile) as u32;
match code {
xdrfile::exdrOK => Ok(()),
_ => Err(err_msg(format!("Failed to flush trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to flush trajectory. Error code: {}",
code
))),
}
}
}
@@ -222,37 +240,42 @@ impl Trajectory for XTCTrajectory {
unsafe {
let path = CString::new(self.handle.path.as_str()).unwrap();
let path_p = path.into_raw();
let code = xdrfile_xtc::read_xtc_natoms(path_p, &mut num_atoms as *const i32) as u32;
let code =
xdrfile_xtc::read_xtc_natoms(path_p, &mut num_atoms as *const i32) as u32;
match code {
xdrfile::exdrOK => Ok(num_atoms as u32),
_ => Err(err_msg(format!("Failed to read atom number from trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to read atom number from trajectory. Error code: {}",
code
))),
}
}
});
match result {
Ok(val) => Ok(*val),
// ugly hack because failure::Error is not "Clone"
Err(err) => Err(err_msg(format!("{}", err)))
Err(err) => Err(err_msg(format!("{}", err))),
}
}
}
/// Read/Write TRR Trajectories
pub struct TRRTrajectory {
handle: XDRFile,
num_atoms: Lazy<Result<u32, Error>>
num_atoms: Lazy<Result<u32, Error>>,
}
impl TRRTrajectory {
pub fn open(path: &Path, filemode: FileMode) -> Result<TRRTrajectory, Error> {
let xdr = XDRFile::open(path, filemode)?;
Ok(TRRTrajectory { handle: xdr, num_atoms: Lazy::new() })
Ok(TRRTrajectory {
handle: xdr,
num_atoms: Lazy::new(),
})
}
}
impl Trajectory for TRRTrajectory {
fn read(&mut self, frame: &mut Frame) -> Result<(), Error> {
unsafe {
// C lib requires an i32 to be passed, but step is exposed it as u32
@@ -261,7 +284,8 @@ impl Trajectory for TRRTrajectory {
// Similar for lambda.
let mut step: i32 = 0;
let mut lambda: f32 = 0.0;
let code = xdrfile_trr::read_trr(self.handle.xdrfile,
let code = xdrfile_trr::read_trr(
self.handle.xdrfile,
frame.num_atoms as i32,
&mut step,
&mut frame.time,
@@ -269,19 +293,23 @@ impl Trajectory for TRRTrajectory {
&mut frame.box_vector,
frame.coords.as_ptr() as *mut [f32; 3],
std::ptr::null_mut(),
std::ptr::null_mut()
) as u32;
std::ptr::null_mut(),
) as u32;
frame.step = step as u32;
match code {
xdrfile::exdrOK => Ok(()),
_ => Err(err_msg(format!("Failed to read trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to read trajectory. Error code: {}",
code
))),
}
}
}
fn write(&mut self, frame: &Frame) -> Result<(), Error> {
unsafe {
let code = xdrfile_trr::write_trr(self.handle.xdrfile,
let code = xdrfile_trr::write_trr(
self.handle.xdrfile,
frame.num_atoms as i32,
frame.step as i32,
frame.time,
@@ -289,10 +317,14 @@ impl Trajectory for TRRTrajectory {
frame.box_vector.as_ptr() as *mut [[f32; 3]; 3],
frame.coords[..].as_ptr() as *mut [f32; 3],
std::ptr::null_mut(),
std::ptr::null_mut()) as u32;
std::ptr::null_mut(),
) as u32;
match code {
xdrfile::exdrOK => Ok(()),
_ => Err(err_msg(format!("Failed to write trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to write trajectory. Error code: {}",
code
))),
}
}
}
@@ -302,7 +334,10 @@ impl Trajectory for TRRTrajectory {
let code = xdr_seek::xdr_flush(self.handle.xdrfile) as u32;
match code {
xdrfile::exdrOK => Ok(()),
_ => Err(err_msg(format!("Failed to flush trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to flush trajectory. Error code: {}",
code
))),
}
}
}
@@ -313,22 +348,25 @@ impl Trajectory for TRRTrajectory {
unsafe {
let path = CString::new(self.handle.path.as_str()).unwrap();
let path_p = path.into_raw();
let code = xdrfile_trr::read_trr_natoms(path_p, &mut num_atoms as *const i32) as u32;
let code =
xdrfile_trr::read_trr_natoms(path_p, &mut num_atoms as *const i32) as u32;
match code {
xdrfile::exdrOK => Ok(num_atoms as u32),
_ => Err(err_msg(format!("Failed to read atom number from trajectory. Error code: {}", code)))
_ => Err(err_msg(format!(
"Failed to read atom number from trajectory. Error code: {}",
code
))),
}
}
});
match result {
Ok(val) => Ok(*val),
// ugly hack because failure::Error is not "Clone"
Err(err) => Err(err_msg(format!("{}", err)))
Err(err) => Err(err_msg(format!("{}", err))),
}
}
}
#[cfg(test)]
mod tests {
@@ -413,4 +451,3 @@ mod tests {
assert_eq!(new_frame.coords, frame.coords);
}
}

View File

@@ -1,9 +1,9 @@
#[cfg(test)]
mod integration {
use std::path::Path;
use std::rc::Rc;
use xdrfile::*;
use std::path::Path;
#[test]
fn test_use_library() {
@@ -25,8 +25,7 @@ mod integration {
let trj = XTCTrajectory::open(path, FileMode::Read).unwrap();
let frames: Vec<Rc<Frame>> = trj.into_iter().filter_map(Result::ok).collect();
for (idx, frame) in frames.iter().enumerate() {
assert_eq!(frame.step as usize, idx+1);
assert_eq!(frame.step as usize, idx + 1);
}
}
}