use super::memmapf32::Mmapf32;
use crate::errors::PointCloudError;
use std::fs::OpenOptions;
use std::path::Path;
use super::DataSource;
#[derive(Debug)]
pub struct DataMemmap {
name: String,
data: Mmapf32,
dim: usize,
}
impl DataMemmap {
pub fn new(dim: usize, path: &Path) -> Result<DataMemmap, PointCloudError> {
let name = path.to_string_lossy().to_string();
if !path.exists() {
panic!("data file {:?} does not exist", path);
}
let file = match OpenOptions::new().read(true).write(true).open(&path) {
Ok(file) => file,
Err(er) => {
panic!("unable to open {:?} in from_proto, {:?}", path, er);
}
};
let data = unsafe { Mmapf32::map(&file).map_err(|e| PointCloudError::from(e)) }?;
Ok(DataMemmap { name, data, dim })
}
pub fn convert_to_ram(self) -> DataRam {
let dim = self.dim;
let name = self.name;
let mut data = Vec::with_capacity(self.data.len());
data.extend_from_slice(&*self.data);
DataRam { name, data: Box::from(data), dim }
}
}
impl DataSource for DataMemmap {
#[inline]
fn get(&self, i: usize) -> Result<&[f32], PointCloudError> {
match self.data.get(self.dim * i..(self.dim * i + self.dim)) {
None => Err(PointCloudError::data_access(i, self.name.clone())),
Some(x) => Ok(x),
}
}
#[inline]
fn dim(&self) -> usize {
self.dim
}
#[inline]
fn len(&self) -> usize {
self.data.len() / self.dim
}
#[inline]
fn name(&self) -> String {
self.name.clone()
}
}
#[derive(Debug)]
pub struct DataRam {
name: String,
data: Box<[f32]>,
dim: usize,
}
impl DataRam {
pub fn new(dim: usize, data: Box<[f32]>) -> Result<DataRam, PointCloudError> {
assert!(data.len()%dim == 0);
let name = "RAM".to_string();
Ok(DataRam { name, data, dim })
}
}
impl DataSource for DataRam {
#[inline]
fn get(&self, i: usize) -> Result<&[f32], PointCloudError> {
match self.data.get(self.dim * i..(self.dim * i + self.dim)) {
None => Err(PointCloudError::data_access(i, self.name.clone())),
Some(x) => Ok(x),
}
}
#[inline]
fn dim(&self) -> usize {
self.dim
}
#[inline]
fn len(&self) -> usize {
self.data.len() / self.dim
}
#[inline]
fn name(&self) -> String {
self.name.clone()
}
}