navid/veins / ac26a51bd7b5f4a22beb0ca203a433857c68b337b79aa5ce14683290ab9ae3a7 / veinsrs/src/object/tree.rs

tree.rs

← veinsrs/src/object · 4731 bytes · raw · download

use crate::encoding::{Reader, Writer};
use crate::error::{Error, Result};
use crate::object::id::Id;
use crate::object::path::valid_name;
use crate::object::{MAX_NAME_LEN, MAX_TREE_DEPTH, MAX_TREE_ENTRIES, TYPE_TREE};
use crate::store::reader::Store;

pub const KIND_FILE: u8 = 1;
pub const KIND_EXECUTABLE: u8 = 2;
pub const KIND_SYMLINK: u8 = 3;
pub const KIND_SUBTREE: u8 = 4;
pub const KIND_SUBMODULE: u8 = 5;
pub const KIND_CONFLICT: u8 = 6;
pub const KIND_MISSING: u8 = 0;

#[derive(Clone)]
pub struct TreeEntry {
    pub name: Vec<u8>,
    pub kind: u8,
    pub target: Id,
}

#[derive(Clone)]
pub struct Tree {
    pub entries: Vec<TreeEntry>,
}

#[derive(Clone)]
pub struct FlatEntry {
    pub path: Vec<u8>,
    pub kind: u8,
    pub target: Id,
}

fn valid_kind(kind: u8) -> bool {
    (KIND_FILE..=KIND_CONFLICT).contains(&kind)
}

fn valid_submodule_target(id: Id) -> bool {
    id.0[20..].iter().all(|byte| *byte == 0)
}

pub fn encode(entries: &[TreeEntry]) -> Result<Vec<u8>> {
    let mut writer = Writer::with_capacity(entries.len() * 48 + 8);
    writer.varint(entries.len() as u64);
    let mut previous: Option<&[u8]> = None;
    for entry in entries {
        if !valid_name(&entry.name) {
            return Err(Error::new("invalid tree entry name"));
        }
        if previous.is_some_and(|name| name >= entry.name.as_slice()) {
            return Err(Error::new("tree entries are not sorted"));
        }
        if !valid_kind(entry.kind) {
            return Err(Error::new("invalid tree entry kind"));
        }
        if entry.kind == KIND_SUBMODULE && !valid_submodule_target(entry.target) {
            return Err(Error::new("invalid submodule target"));
        }
        writer.bytes(&entry.name);
        writer.u8(entry.kind);
        writer.id(entry.target);
        previous = Some(&entry.name);
    }
    Ok(writer.into_vec())
}

pub fn decode(body: &[u8]) -> Result<Tree> {
    let mut reader = Reader::new(body);
    let count = reader.varint()?;
    let count = usize::try_from(count).map_err(|_| Error::new("tree too large"))?;
    if count > MAX_TREE_ENTRIES {
        return Err(Error::new("tree entry limit exceeded"));
    }
    let mut entries = Vec::with_capacity(count);
    let mut previous: Option<Vec<u8>> = None;
    for _ in 0..count {
        let name = reader.bytes(MAX_NAME_LEN)?.to_vec();
        if !valid_name(&name) {
            return Err(Error::new("invalid tree entry name"));
        }
        if previous.as_ref().is_some_and(|value| value >= &name) {
            return Err(Error::new("tree entries are not sorted"));
        }
        let kind = reader.u8()?;
        if !valid_kind(kind) {
            return Err(Error::new("invalid tree entry kind"));
        }
        let target = reader.id()?;
        if kind == KIND_SUBMODULE && !valid_submodule_target(target) {
            return Err(Error::new("invalid submodule target"));
        }
        entries.push(TreeEntry { name, kind, target });
        previous = Some(entries.last().unwrap().name.clone());
    }
    reader.finish()?;
    Ok(Tree { entries })
}

fn flatten_into(
    store: &mut Store,
    tree_id: Id,
    prefix: &mut Vec<u8>,
    output: &mut Vec<FlatEntry>,
    depth: usize,
) -> Result<()> {
    if depth > MAX_TREE_DEPTH {
        return Err(Error::new("tree nesting too deep"));
    }
    let body = store
        .body(tree_id, TYPE_TREE)?
        .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?;
    let tree = decode(&body)?;
    for entry in tree.entries {
        let old_length = prefix.len();
        if !prefix.is_empty() {
            prefix.push(b'/');
        }
        prefix.extend_from_slice(&entry.name);
        if entry.kind == KIND_SUBTREE {
            flatten_into(store, entry.target, prefix, output, depth + 1)?;
        } else {
            output.push(FlatEntry {
                path: prefix.clone(),
                kind: entry.kind,
                target: entry.target,
            });
        }
        prefix.truncate(old_length);
    }
    Ok(())
}

pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {
    let mut output = Vec::new();
    let mut prefix = Vec::new();
    flatten_into(store, tree_id, &mut prefix, &mut output, 0)?;
    output.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(output)
}

pub fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {
    entries
        .binary_search_by(|entry| entry.path.as_slice().cmp(path))
        .ok()
        .map(|index| &entries[index])
}

pub fn find_entry(tree: &Tree, name: &[u8]) -> Option<usize> {
    tree.entries
        .binary_search_by(|entry| entry.name.as_slice().cmp(name))
        .ok()
}