serde_hkx_features/serde/
ser.rs

1//! Serialize/Deserialize ClassMap
2use crate::ClassMap;
3use crate::{
4    convert::OutFormat,
5    error::{Result, SerSnafu},
6};
7use serde_hkx::{HavokSort, bytes::serde::hkx_header::HkxHeader, to_string};
8use snafu::ResultExt as _;
9use std::path::Path;
10
11/// Serialize bytes(file contents) to a file.
12///
13/// # Errors
14/// If the information required for serialization is missing.
15///
16/// See `serde_hkx::errors::ser::Error` for possible errors that may occur.
17///
18/// # Panics
19/// If `format` is not `XML`, `Amd64`, or `WIn32`.
20/// That means the API is being used incorrectly.
21pub fn to_bytes<I>(input: I, format: OutFormat, classes: &mut ClassMap<'_>) -> Result<Vec<u8>>
22where
23    I: AsRef<Path>,
24{
25    let input = input.as_ref();
26
27    // Serialize
28    if format == OutFormat::Xml {
29        let top_ptr = classes.sort_for_xml().with_context(|_| SerSnafu {
30            input: input.to_path_buf(),
31        })?;
32        let xml = to_string(classes, top_ptr).with_context(|_| SerSnafu {
33            input: input.to_path_buf(),
34        })?;
35        Ok(xml.into_bytes())
36    } else {
37        classes.sort_for_bytes();
38        let binary_data = match format {
39            OutFormat::Win32 => serde_hkx::to_bytes(classes, &HkxHeader::new_skyrim_le()),
40            OutFormat::Amd64 => serde_hkx::to_bytes(classes, &HkxHeader::new_skyrim_se()),
41            _ => unreachable!(),
42        }
43        .with_context(|_| SerSnafu {
44            input: input.to_path_buf(),
45        })?;
46        Ok(binary_data)
47    }
48}