use toml_edit::DocumentMut;
use crate::error::{Malformed, Result};
use crate::{PAYLOAD_FILE_KEY, VERSION_KEY};
pub(crate) struct Keys {
pub version: String,
pub payload_file: String,
}
pub(crate) fn parse(bytes: &[u8]) -> Result<(DocumentMut, Keys)> {
let text = std::str::from_utf8(bytes).map_err(|_| Malformed::MetadataNotUtf8)?;
let doc: DocumentMut = text
.parse()
.map_err(|e: toml_edit::TomlError| Malformed::MetadataNotToml(e.to_string()))?;
let keys = Keys {
version: required_string(&doc, VERSION_KEY)?.to_owned(),
payload_file: required_string(&doc, PAYLOAD_FILE_KEY)?.to_owned(),
};
Ok((doc, keys))
}
pub(crate) fn required_string<'d>(doc: &'d DocumentMut, key: &'static str) -> Result<&'d str> {
let item = key
.split('.')
.try_fold(doc.as_item(), |item, part| item.get(part))
.ok_or(Malformed::MissingKey(key))?;
item.as_str()
.ok_or_else(|| Malformed::KeyNotAString(key).into())
}