use anyhow::Result;
use std::collections::BTreeMap;
use crate::dtb::{self, Node};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
Label(String),
Path(String),
Unknown,
}
#[derive(Debug, Clone)]
pub struct Fragment {
pub path: String,
pub target: Target,
pub node: Node,
}
#[derive(Debug, Clone, Default)]
pub struct Overlay {
pub fragments: Vec<Fragment>,
fixups: BTreeMap<(String, String, usize), String>,
}
impl Overlay {
pub fn parse(blob: &[u8]) -> Result<Self> {
let root = dtb::parse(blob)?;
let mut fixups = BTreeMap::new();
if let Some(node) = root.child("__fixups__") {
for (label, value) in &node.props {
for entry in dtb::strings(value) {
let mut parts = entry.rsplitn(3, ':');
let (Some(offset), Some(prop), Some(path)) =
(parts.next(), parts.next(), parts.next())
else {
continue;
};
if let Ok(offset) = offset.parse::<usize>() {
fixups.insert((path.to_owned(), prop.to_owned(), offset), label.clone());
}
}
}
}
let mut fragments = Vec::new();
for fragment in &root.children {
let Some(overlay) = fragment.child("__overlay__") else {
continue;
};
let fragment_path = format!("/{}", fragment.name);
let target =
if let Some(label) = fixups.get(&(fragment_path.clone(), "target".to_owned(), 0)) {
Target::Label(label.clone())
} else if let Some(path) = fragment.string("target-path") {
Target::Path(path)
} else {
Target::Unknown
};
fragments.push(Fragment {
path: format!("{fragment_path}/__overlay__"),
target,
node: overlay.clone(),
});
}
Ok(Self { fragments, fixups })
}
pub fn label_at(&self, path: &str, prop: &str, cell: usize) -> Option<&str> {
self.fixups
.get(&(path.to_owned(), prop.to_owned(), cell * 4))
.map(String::as_str)
}
}