api: add prefix-mapping helper to BackupNamespace

given a namespace, a source prefix and a target prefix this helper
strips the source prefix and replaces it with the target one (erroring
out if the prefix doesn't match).

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
Fabian Grünbichler 2022-04-29 13:43:58 +02:00 committed by Thomas Lamprecht
parent c12a075b83
commit e687d1b8ee
1 changed files with 27 additions and 0 deletions

View File

@ -687,6 +687,33 @@ impl BackupNamespace {
pub fn components(&self) -> impl Iterator<Item = &str> + '_ { pub fn components(&self) -> impl Iterator<Item = &str> + '_ {
self.inner.iter().map(String::as_str) self.inner.iter().map(String::as_str)
} }
/// Map NS by replacing `source_prefix` with `target_prefix`
pub fn map_prefix(
&self,
source_prefix: &BackupNamespace,
target_prefix: &BackupNamespace,
) -> Result<Self, Error> {
let mut mapped = target_prefix.clone();
let mut source_iter = source_prefix.components();
let mut self_iter = self.components();
while let Some(comp) = self_iter.next() {
if let Some(source_comp) = source_iter.next() {
if source_comp != comp {
bail!(
"Failed to map namespace - {} is not a valid prefix of {}",
source_prefix,
self
);
}
continue;
}
mapped.push(comp.to_owned())?;
}
Ok(mapped)
}
} }
impl fmt::Display for BackupNamespace { impl fmt::Display for BackupNamespace {