navid/veins / bc0b02d957b7af60232a5b91bf4caefba5dfba19c68970ec43e5c39830934f19 / veinsrs/src/object/id.rs

id.rs

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

use crate::error::{Error, Result};

#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Id(pub [u8; 32]);

const HEX: &[u8; 16] = b"0123456789abcdef";

impl Id {
    pub fn to_hex(self) -> String {
        let mut text = String::with_capacity(64);
        for byte in self.0 {
            text.push(HEX[(byte >> 4) as usize] as char);
            text.push(HEX[(byte & 0x0f) as usize] as char);
        }
        text
    }

    pub fn short(self) -> String {
        self.to_hex()[..12].to_string()
    }

    pub fn from_hex(text: &str) -> Result<Self> {
        if text.len() != 64 {
            return Err(Error::new("object id must contain 64 hex digits"));
        }
        let bytes = text.as_bytes();
        let mut value = [0u8; 32];
        for index in 0..32 {
            let high = hex_value(bytes[index * 2])?;
            let low = hex_value(bytes[index * 2 + 1])?;
            value[index] = (high << 4) | low;
        }
        Ok(Self(value))
    }
}

impl std::fmt::Debug for Id {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.to_hex())
    }
}

fn hex_value(byte: u8) -> Result<u8> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        _ => Err(Error::new("invalid hex digit")),
    }
}

pub fn hash_bytes(data: &[u8]) -> [u8; 32] {
    *blake3::hash(data).as_bytes()
}

pub fn object_id(kind: u8, body: &[u8]) -> Id {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"veins/1\0");
    hasher.update(&[kind]);
    hasher.update(body);
    Id(*hasher.finalize().as_bytes())
}

pub fn prefix_matches(full: &str, prefix: &str) -> bool {
    if prefix.is_empty() || prefix.len() > full.len() {
        return false;
    }
    full.as_bytes()
        .iter()
        .zip(prefix.as_bytes())
        .all(|(left, right)| left.eq_ignore_ascii_case(right))
}

pub fn is_hex_prefix(text: &str) -> bool {
    (4..=64).contains(&text.len()) && text.bytes().all(|byte| byte.is_ascii_hexdigit())
}