use writeln! macro; replace unsafe with expect

This commit is contained in:
Hantao Hui 2022-02-25 17:59:50 +01:00
parent 9e0dfd14de
commit 0cae584262
1 changed files with 55 additions and 41 deletions

View File

@ -508,9 +508,9 @@ mod internal {
/// When matrix is a Hermitian matrix, it will convert itself to its conjugate.
fn conjugate(self) -> Result<Self, MatrixMarketError>;
/// Returns the name of SupportedMatrixMarketScalar, used when write the matrix
fn typename() -> &'static [u8];
/// Convert the data to bytes
fn to_matrixmarket_bytes(&self) -> Vec<u8>;
fn typename() -> &'static str;
/// Write the data self to w
fn write_matrix_market<W: std::fmt::Write>(&self, w: W) -> Result<(), std::fmt::Error>;
}
pub trait SupportedMatrixMarketExport<T: SupportedMatrixMarketScalar> {
@ -574,12 +574,15 @@ macro_rules! mm_int_impl {
Ok(-self)
}
#[inline]
fn typename() -> &'static [u8] {
b"integer"
fn typename() -> &'static str {
"integer"
}
#[inline]
fn to_matrixmarket_bytes(&self) -> Vec<u8> {
self.to_string().into_bytes()
fn write_matrix_market<W: std::fmt::Write>(
&self,
mut w: W,
) -> Result<(), std::fmt::Error> {
write!(w, "{}", self)
}
}
};
@ -627,12 +630,15 @@ macro_rules! mm_real_impl {
Ok(-self)
}
#[inline]
fn typename() -> &'static [u8] {
b"real"
fn typename() -> &'static str {
"real"
}
#[inline]
fn to_matrixmarket_bytes(&self) -> Vec<u8> {
self.to_string().into_bytes()
fn write_matrix_market<W: std::fmt::Write>(
&self,
mut w: W,
) -> Result<(), std::fmt::Error> {
write!(w, "{}", self)
}
}
};
@ -681,12 +687,15 @@ macro_rules! mm_complex_impl {
Ok(-self)
}
#[inline]
fn typename() -> &'static [u8] {
b"complex"
fn typename() -> &'static str {
"complex"
}
#[inline]
fn to_matrixmarket_bytes(&self) -> Vec<u8> {
(self.re.to_string() + " " + &self.im.to_string()).into_bytes()
fn write_matrix_market<W: std::fmt::Write>(
&self,
mut w: W,
) -> Result<(), std::fmt::Error> {
write!(w, "{} {}", self.re, self.im)
}
}
};
@ -738,12 +747,15 @@ macro_rules! mm_pattern_impl {
))
}
#[inline]
fn typename() -> &'static [u8] {
b"pattern"
fn typename() -> &'static str {
"pattern"
}
#[inline]
fn to_matrixmarket_bytes(&self) -> Vec<u8> {
Vec::<u8>::new()
fn write_matrix_market<W: std::fmt::Write>(
&self,
mut _w: W,
) -> Result<(), std::fmt::Error> {
Ok(())
}
}
};
@ -1448,9 +1460,9 @@ pub fn write_to_matrix_market_str<T: MatrixMarketScalar, S: MatrixMarketExport<T
// The vector will grow as needed.
// So, unwrap here won't cause any issue.
write_to_matrix_market(&mut bytes, sparse_matrix).unwrap();
// safety issue is because 'from_utf8_unchecked' does not check that the bytes passed to it are valid UTF-8.
// Since 'bytes' created here is valid UTF-8 data, so it will not cause any problem.
unsafe { String::from_utf8_unchecked(bytes) }
String::from_utf8(bytes)
.expect("Unexpected non UTF-8 data was generated when export to matrix market string")
}
/// Write a sparse matrix into Matrix Market format file.
@ -1486,7 +1498,7 @@ pub fn write_to_matrix_market_file<
>(
sparse_matrix: &S,
path: P,
) -> Result<(), MatrixMarketError> {
) -> Result<(), std::io::Error> {
let mut file = File::create(path)?;
write_to_matrix_market(&mut file, sparse_matrix)?;
Ok(())
@ -1494,33 +1506,35 @@ pub fn write_to_matrix_market_file<
/// low level implementation of writing sparse matrix into any [std::io::Write] object
fn write_to_matrix_market<T: MatrixMarketScalar, S: MatrixMarketExport<T>, W: Write>(
w: &mut W,
mut w: W,
sparse_matrix: &S,
) -> Result<(), MatrixMarketError> {
) -> Result<(), std::io::Error> {
// write header
w.write_all(b"%%matrixmarket matrix coordinate ")?;
w.write_all(T::typename())?;
w.write_all(b" general\n")?;
writeln!(
w,
"%%matrixmarket matrix coordinate {} general",
T::typename()
)?;
//write comment
w.write_all(b"% matrixmarket file generated by nalgebra-sparse.\n")?;
writeln!(w, "% matrixmarket file generated by nalgebra-sparse.")?;
// write shape information
w.write_all(sparse_matrix.nrows().to_string().as_bytes())?;
w.write_all(b" ")?;
w.write_all(sparse_matrix.ncols().to_string().as_bytes())?;
w.write_all(b" ")?;
w.write_all(sparse_matrix.nnz().to_string().as_bytes())?;
w.write_all(b"\n")?;
writeln!(
w,
"{} {} {}",
sparse_matrix.nrows(),
sparse_matrix.ncols(),
sparse_matrix.nnz()
)?;
//write triplets
let mut buffer = String::new();
for (r, c, d) in sparse_matrix.triplet_iter() {
w.write_all((r + 1).to_string().as_bytes())?;
w.write_all(b" ")?;
w.write_all((c + 1).to_string().as_bytes())?;
w.write_all(b" ")?;
w.write_all(&d.to_matrixmarket_bytes())?;
w.write_all(b"\n")?;
buffer.clear();
d.write_matrix_market(&mut buffer)
.expect("Unexpected format error was generated when write to String");
writeln!(w, "{} {} {} ", r + 1, c + 1, buffer)?;
}
Ok(())
}