use std::io::Write;
use serde::{ser::Error, Serialize};
use crate::{
ser::{header_collector::HeaderCollector, ply_file::PlyReaderSerializer},
PlyFormat, SerializeError,
};
mod header_collector;
mod ply_file;
mod row;
pub(crate) mod val_writer;
pub fn to_writer<T>(
val: &T,
options: SerializeOptions,
mut writer: impl Write,
) -> Result<(), SerializeError>
where
T: Serialize,
{
let format = options.format;
val.serialize(&mut HeaderCollector::new(options, &mut writer))?;
val.serialize(&mut PlyReaderSerializer::new(format, &mut writer))?;
Ok(())
}
pub fn to_bytes<T>(val: &T, options: SerializeOptions) -> Result<Vec<u8>, SerializeError>
where
T: Serialize,
{
let mut buf = vec![];
to_writer(val, options, &mut buf)?;
Ok(buf)
}
pub fn to_string<T>(val: &T, options: SerializeOptions) -> Result<String, SerializeError>
where
T: Serialize,
{
if options.format != PlyFormat::Ascii {
return Err(SerializeError::custom(
"Cannot serialize binary PLY to string",
));
}
String::from_utf8(to_bytes(val, options)?).map_err(|e| SerializeError::custom(e.to_string()))
}
#[derive(Debug, Clone)]
pub struct SerializeOptions {
format: PlyFormat,
comments: Vec<String>,
obj_info: Vec<String>,
}
impl SerializeOptions {
pub fn new(format: PlyFormat) -> Self {
Self {
format,
comments: Vec::new(),
obj_info: Vec::new(),
}
}
pub fn ascii() -> Self {
Self::new(PlyFormat::Ascii)
}
pub fn binary_le() -> Self {
Self::new(PlyFormat::BinaryLittleEndian)
}
pub fn binary_be() -> Self {
Self::new(PlyFormat::BinaryBigEndian)
}
pub fn with_comments(mut self, comments: Vec<String>) -> Self {
self.comments.extend(comments);
self
}
pub fn with_obj_info(mut self, obj_info: Vec<String>) -> Self {
self.obj_info.extend(obj_info);
self
}
}