Skip to content

Commit

Permalink
remove some panics
Browse files Browse the repository at this point in the history
  • Loading branch information
daniellga committed Apr 9, 2024
1 parent d5f88b6 commit 6e3891e
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 38 deletions.
Empty file removed .nojekyll
Empty file.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
"harmonium-core",
"harmonium-io",
Expand Down
9 changes: 8 additions & 1 deletion r-harmonium/src/rust/src/conversions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use savvy::{Sexp, TypedSexp};
use savvy::{OwnedIntegerSexp, Sexp, TypedSexp};

pub(crate) trait Conversions<T> {
fn to_scalar(self: Self) -> savvy::Result<T>;
Expand Down Expand Up @@ -58,3 +58,10 @@ impl Conversions<bool> for Sexp {
}
}
}

pub fn try_from_usize_to_int_sexp(n: usize) -> savvy::Result<OwnedIntegerSexp> {
let n: i32 = n
.try_into()
.map_err(|_| savvy::Error::new("Cannot convert usize to i32."))?;
n.try_into()
}
25 changes: 25 additions & 0 deletions r-harmonium/src/rust/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use harmonium_core::errors::HError;

#[derive(Debug)]
pub struct HErrorR(HError);

impl From<HError> for HErrorR {
fn from(error: HError) -> Self {
Self(error)
}
}

impl From<HErrorR> for savvy::Error {
fn from(error: HErrorR) -> Self {
match error.0 {
HError::IoError(err) => Self::new(err.as_str()),
HError::DecodeError(err) => Self::new(err.as_str()),
HError::SeekError(err) => Self::new(err.as_str()),
HError::LimitError(err) => Self::new(err.as_str()),
HError::ResampleError(err) => Self::new(err.as_str()),
HError::OutOfSpecError(err) => Self::new(err.as_str()),
HError::PlayError(err) => Self::new(err.as_str()),
HError::OtherError(err) => Self::new(err.as_str()),
}
}
}
38 changes: 20 additions & 18 deletions r-harmonium/src/rust/src/harray.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{harrayr::HArrayR, hdatatype::HDataType};
use crate::{errors::HErrorR, harrayr::HArrayR, hdatatype::HDataType};
use ndarray::{IxDyn, ShapeError, SliceInfo, SliceInfoElem};
use num_complex::Complex;
use savvy::{
Expand Down Expand Up @@ -54,13 +54,15 @@ impl HArray {
(TypedSexp::Real(arr), HDataType::Float32) => {
let slice: &[f64] = arr.as_slice();
let v: Vec<f32> = slice.iter().map(|x| *x as f32).collect();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v).unwrap();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v)
.map_err(|err| HErrorR::from(err))?;
let data = Arc::new(harray);
Ok(HArray(data))
}
(TypedSexp::Real(arr), HDataType::Float64) => {
let v: Vec<f64> = arr.as_slice().to_vec();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v).unwrap();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v)
.map_err(|err| HErrorR::from(err))?;
let data = Arc::new(harray);
Ok(HArray(data))
}
Expand All @@ -70,20 +72,22 @@ impl HArray {
.iter()
.map(|z| Complex::new(z.re as f32, z.im as f32))
.collect();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v).unwrap();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v)
.map_err(|err| HErrorR::from(err))?;
let data = Arc::new(harray);
Ok(HArray(data))
}
(TypedSexp::Complex(arr), HDataType::Complex64) => {
let v: Vec<Complex<f64>> = arr.as_slice().to_vec();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v).unwrap();
let harray = harmonium_core::array::HArray::new_from_shape_vec(dim, v)
.map_err(|err| HErrorR::from(err))?;
let data = Arc::new(harray);
Ok(HArray(data))
}
_ => panic!("not valid input types"),
_ => Err("not valid input types".into()),
}
} else {
panic!("arr must be of array type.");
Err("arr must be of array type.".into())
}
}

Expand All @@ -110,7 +114,11 @@ impl HArray {
/// _________
///
fn len(&self) -> savvy::Result<Sexp> {
let len: i32 = self.0.len().try_into().unwrap();
let len: i32 = self
.0
.len()
.try_into()
.map_err(|_| savvy::Error::new("Cannot convert usize to i32."))?;
let integer_sexp: OwnedIntegerSexp = len.try_into()?;
integer_sexp.into()
}
Expand Down Expand Up @@ -214,17 +222,15 @@ impl HArray {
let list_len = range.len();

if list_len != self.0.ndim() {
return savvy::Result::Err(
"The list must have the same length as the number of dimensions.".into(),
);
return Err("The list must have the same length as the number of dimensions.".into());
}

let mut vec_ranges: Vec<SliceInfoElem> = Vec::with_capacity(list_len);
for obj in range.values_iter() {
match obj.into_typed() {
TypedSexp::Integer(integer_sexp) => {
if integer_sexp.len() != 3 {
return savvy::Result::Err("Each element must have a length of 3.".into());
return Err("Each element must have a length of 3.".into());
}
let slice: &[i32] = integer_sexp.as_slice();
let slice_info_elem = SliceInfoElem::Slice {
Expand All @@ -234,17 +240,13 @@ impl HArray {
};
vec_ranges.push(slice_info_elem);
}
_ => {
return savvy::Result::Err(
"Each element in the list must be a vector of integers.".into(),
)?;
}
_ => return Err("Each element in the list must be a vector of integers.".into()),
}
}

let slice_info: SliceInfo<Vec<SliceInfoElem>, IxDyn, IxDyn> = vec_ranges
.try_into()
.map_err(|err: ShapeError| err.to_string())?;
.map_err(|err: ShapeError| savvy::Error::new(err.to_string().as_str()))?;

Ok(HArray(self.0.slice(slice_info)))
}
Expand Down
22 changes: 12 additions & 10 deletions r-harmonium/src/rust/src/harrayr.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::hdatatype::HDataType;
use crate::{errors::HErrorR, hdatatype::HDataType};
use harmonium_core::haudioop::HAudioOpDyn;
use harmonium_fft::fft::{FftComplex, FftFloat};
use ndarray::{IxDyn, SliceInfo, SliceInfoElem};
Expand All @@ -24,7 +24,7 @@ pub trait HArrayR: Send + Sync {
fn nchannels(&self) -> usize;
fn nframes(&self) -> usize;
fn db_to_amplitude(&mut self, reference: f64, power: f64);
fn to_mono(&mut self);
fn to_mono(&mut self) -> savvy::Result<()>;
}

impl HArrayR for harmonium_core::array::HArray<f32, IxDyn> {
Expand Down Expand Up @@ -116,8 +116,9 @@ impl HArrayR for harmonium_core::array::HArray<f32, IxDyn> {
HAudioOpDyn::db_to_amplitude(self, reference as f32, power as f32);
}

fn to_mono(&mut self) {
*self = HAudioOpDyn::to_mono(self).unwrap();
fn to_mono(&mut self) -> savvy::Result<()> {
*self = HAudioOpDyn::to_mono(self).map_err(|err| HErrorR::from(err))?;
Ok(())
}
}

Expand Down Expand Up @@ -209,8 +210,9 @@ impl HArrayR for harmonium_core::array::HArray<f64, IxDyn> {
HAudioOpDyn::db_to_amplitude(self, reference, power);
}

fn to_mono(&mut self) {
*self = HAudioOpDyn::to_mono(self).unwrap();
fn to_mono(&mut self) -> savvy::Result<()> {
*self = HAudioOpDyn::to_mono(self).map_err(|err| HErrorR::from(err))?;
Ok(())
}
}

Expand Down Expand Up @@ -303,8 +305,8 @@ impl HArrayR for harmonium_core::array::HArray<Complex<f32>, IxDyn> {
panic!("Operation only allowed for float HArrays.");
}

fn to_mono(&mut self) {
panic!("Operation only allowed for float HArrays.");
fn to_mono(&mut self) -> savvy::Result<()> {
Err("Operation only allowed for float HArrays.".into())
}
}

Expand Down Expand Up @@ -396,7 +398,7 @@ impl HArrayR for harmonium_core::array::HArray<Complex<f64>, IxDyn> {
panic!("Operation only allowed for float HArrays.");
}

fn to_mono(&mut self) {
panic!("Operation only allowed for float HArrays.");
fn to_mono(&mut self) -> savvy::Result<()> {
Err("Operation only allowed for float HArrays.".into())
}
}
19 changes: 10 additions & 9 deletions r-harmonium/src/rust/src/haudioop.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::{conversions::Conversions, harray::HArray};
use savvy::{savvy, OwnedIntegerSexp, Sexp};
use crate::{
conversions::{try_from_usize_to_int_sexp, Conversions},
harray::HArray,
};
use savvy::{savvy, Sexp};

/// HAudioOp
///
Expand Down Expand Up @@ -38,8 +41,8 @@ impl HAudioOp {
/// _________
///
fn nchannels(harray: &HArray) -> savvy::Result<Sexp> {
let nchannels: i32 = harray.0.nchannels().try_into().unwrap();
let integer_sexp: OwnedIntegerSexp = nchannels.try_into()?;
let nchannels = harray.0.nchannels();
let integer_sexp = try_from_usize_to_int_sexp(nchannels)?;
integer_sexp.into()
}

Expand Down Expand Up @@ -68,8 +71,8 @@ impl HAudioOp {
/// _________
///
fn nframes(harray: &HArray) -> savvy::Result<Sexp> {
let nframes: i32 = harray.0.nframes().try_into().unwrap();
let integer_sexp: OwnedIntegerSexp = nframes.try_into()?;
let nframes = harray.0.nframes();
let integer_sexp = try_from_usize_to_int_sexp(nframes)?;
integer_sexp.into()
}

Expand Down Expand Up @@ -104,11 +107,9 @@ impl HAudioOp {
///
fn db_to_amplitude(harray: &mut HArray, reference: Sexp, power: Sexp) -> savvy::Result<()> {
let inner_mut = harray.get_inner_mut();

let reference: f64 = reference.to_scalar()?;
let power: f64 = power.to_scalar()?;
inner_mut.db_to_amplitude(reference, power);

Ok(())
}

Expand Down Expand Up @@ -138,7 +139,7 @@ impl HAudioOp {
///
fn to_mono(harray: &mut HArray) -> savvy::Result<()> {
let inner_mut = harray.get_inner_mut();
inner_mut.to_mono();
inner_mut.to_mono()?;
Ok(())
}
}
1 change: 1 addition & 0 deletions r-harmonium/src/rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod conversions;
mod errors;
mod harray;
mod harrayr;
mod haudioop;
Expand Down

0 comments on commit 6e3891e

Please sign in to comment.