libmosh/
ops.rs

1//! File operations
2
3use png::{BitDepth, ColorType, Encoder};
4
5use std::{
6    fs::File,
7    io::{BufReader, BufWriter, Read},
8    path::Path,
9};
10
11use crate::MoshError;
12
13/// Reads provided file
14///
15/// # Errors
16///
17/// It may fail if input format is not supported.
18pub fn read_file(file: impl AsRef<Path>) -> Result<Vec<u8>, MoshError> {
19    let input = File::open(file)?;
20    let mut reader = BufReader::new(input);
21    let mut buffer = Vec::new();
22
23    reader.read_to_end(&mut buffer)?;
24
25    Ok(buffer)
26}
27
28/// Writes a new file from the provided buffer
29///
30/// # Errors
31///
32/// It may fail if parameters are invalid or due I/O error.
33pub fn write_file(
34    dest: &str,
35    buf: &[u8],
36    width: u32,
37    height: u32,
38    color_type: ColorType,
39    bit_depth: BitDepth,
40) -> Result<(), MoshError> {
41    let path = Path::new(&dest);
42    let output = File::create(path)?;
43    let buf_writer = &mut BufWriter::new(output);
44    let mut encoder = Encoder::new(buf_writer, width, height);
45
46    encoder.set_color(color_type);
47    encoder.set_depth(bit_depth);
48
49    let mut writer = encoder.write_header()?;
50    writer.write_image_data(buf)?;
51
52    Ok(())
53}