use std::io::Write;
use std::path::Path;
#[derive(Debug)]
pub struct RenderedDocument {
bytes: Vec<u8>,
}
impl RenderedDocument {
pub(crate) fn new(bytes: Vec<u8>) -> Self {
Self { bytes }
}
pub fn write_to_file(self, path: impl AsRef<Path>) -> crate::Result<()> {
std::fs::write(path, self.bytes)?;
Ok(())
}
pub fn write_to_writer<W: Write>(self, mut writer: W) -> crate::Result<()> {
writer.write_all(&self.bytes)?;
Ok(())
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
impl AsRef<[u8]> for RenderedDocument {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
impl From<RenderedDocument> for Vec<u8> {
fn from(document: RenderedDocument) -> Self {
document.bytes
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use super::*;
#[test]
fn new_stores_bytes() {
let bytes = vec![1, 2, 3];
let doc = RenderedDocument::new(bytes.clone());
assert_eq!(doc.as_bytes(), &bytes);
}
#[test]
fn into_bytes_returns_ownership() {
let bytes = vec![1, 2, 3];
let doc = RenderedDocument::new(bytes.clone());
assert_eq!(doc.into_bytes(), bytes);
}
#[test]
fn as_ref_returns_the_bytes() {
let doc = RenderedDocument::new(vec![1, 2, 3]);
let bytes: &[u8] = doc.as_ref();
assert_eq!(bytes, &[1, 2, 3]);
}
#[test]
fn a_document_converts_into_a_byte_vector() {
let doc = RenderedDocument::new(vec![1, 2, 3]);
let bytes: Vec<u8> = doc.into();
assert_eq!(bytes, vec![1, 2, 3]);
}
}