use crate::collections::{Map, Set};
use alloc::vec::Vec;
use core::{error::Error, mem::take, num::NonZero};
use thiserror::Error;
use crate::{
blob::BlobMeta,
depth::{Depth, DepthMetric},
digest::Digest,
fragment::Fragment,
loose_commit::LooseCommit,
};
#[derive(Debug, Clone, Copy, Error, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[error("missing commit: {0}")]
pub struct MissingCommitError(Digest<LooseCommit>);
pub trait Parents {
fn parents(&self) -> Set<Digest<LooseCommit>>;
}
#[allow(clippy::implicit_hasher)]
impl Parents for Set<Digest<LooseCommit>> {
fn parents(&self) -> Set<Digest<LooseCommit>> {
self.clone()
}
}
#[derive(Debug, Error)]
pub enum FragmentError<'a, S: CommitStore<'a> + ?Sized> {
#[error(transparent)]
LookupError(S::LookupError),
#[error(transparent)]
MissingCommit(#[from] MissingCommitError),
}
pub trait CommitStore<'a> {
type Node: Parents;
type LookupError: Error;
fn lookup(&self, digest: Digest<LooseCommit>) -> Result<Option<Self::Node>, Self::LookupError>;
fn fragment<D: DepthMetric>(
&self,
head_digest: Digest<LooseCommit>,
known_fragment_states: &Map<Digest<LooseCommit>, FragmentState<Self::Node>>,
strategy: &D,
) -> Result<FragmentState<Self::Node>, FragmentError<'a, Self>> {
let min_depth = strategy.to_depth(head_digest);
let mut visited: Set<Digest<LooseCommit>> = Set::from([head_digest]);
let mut members: Set<Digest<LooseCommit>> = Set::from([head_digest]);
let mut boundary: Map<Digest<LooseCommit>, Self::Node> = Map::new();
let mut checkpoints: Set<Digest<LooseCommit>> = Set::new();
let head_change = self
.lookup(head_digest)
.map_err(|e| FragmentError::LookupError(e))?
.ok_or_else(|| FragmentError::MissingCommit(MissingCommitError(head_digest)))?;
let mut horizon: Set<Digest<LooseCommit>> = head_change.parents();
while !horizon.is_empty() {
let local_horizon = take(&mut horizon);
for &digest in &local_horizon {
let commit = self
.lookup(digest)
.map_err(|e| FragmentError::LookupError(e))?
.ok_or_else(|| FragmentError::MissingCommit(MissingCommitError(head_digest)))?;
let is_newly_visited = visited.insert(digest);
if !is_newly_visited {
continue;
}
members.insert(digest);
let depth = strategy.to_depth(digest);
if strategy.to_depth(digest) >= min_depth {
boundary.insert(digest, commit);
} else {
if depth > Depth(0) {
checkpoints.insert(digest);
}
horizon.extend(commit.parents().iter().filter(|&d| !visited.contains(d)));
}
}
}
let mut cleanup_horizon: Vec<Digest<LooseCommit>> = Vec::new();
for (boundary_hash, boundary_change) in &boundary {
members.remove(boundary_hash);
if let Some(fragment_state) = known_fragment_states.get(boundary_hash) {
for member in fragment_state.members() {
members.remove(member);
}
cleanup_horizon.extend(fragment_state.boundary().keys().copied());
} else {
let deps = boundary_change.parents();
cleanup_horizon.extend(deps);
}
}
while !cleanup_horizon.is_empty() {
let local_cleanup_horizon = take(&mut cleanup_horizon);
for digest in local_cleanup_horizon {
members.remove(&digest);
checkpoints.remove(&digest);
boundary.remove(&digest);
let is_newly_visited = visited.insert(digest);
if !is_newly_visited {
continue;
}
let commit = self
.lookup(digest)
.map_err(|e| FragmentError::LookupError(e))?
.ok_or_else(|| FragmentError::MissingCommit(MissingCommitError(head_digest)))?;
cleanup_horizon.extend(commit.parents().iter().filter(|&d| !visited.contains(d)));
}
}
Ok(FragmentState::new(
head_digest,
members,
checkpoints,
boundary,
))
}
fn build_fragment_store<'b, D: DepthMetric>(
&self,
head_digests: &[Digest<LooseCommit>],
known_fragment_states: &'b mut Map<Digest<LooseCommit>, FragmentState<Self::Node>>,
strategy: &D,
) -> Result<Vec<&'b FragmentState<Self::Node>>, FragmentError<'a, Self>> {
let mut fresh_heads = Vec::new();
let mut horizon = head_digests.to_vec();
while let Some(head) = horizon.pop() {
if let Some(state) = known_fragment_states.get(&head) {
horizon.extend(state.boundary().keys().copied());
continue;
}
let fragment_state = self.fragment(head, known_fragment_states, strategy)?;
fresh_heads.push(head);
horizon.extend(fragment_state.boundary().keys().copied());
known_fragment_states.insert(head, fragment_state);
}
let mut fresh = Vec::with_capacity(fresh_heads.len());
for head in fresh_heads {
#[allow(clippy::expect_used)]
let r = known_fragment_states.get(&head).expect("just inserted");
fresh.push(r);
}
Ok(fresh)
}
}
#[derive(Debug, Clone, Copy)]
pub struct CountLeadingZeroBytes;
impl DepthMetric for CountLeadingZeroBytes {
fn to_depth(&self, digest: Digest<LooseCommit>) -> Depth {
let mut acc = 0;
for &byte in digest.as_bytes() {
if byte == 0 {
acc += 1;
} else {
break;
}
}
Depth(acc)
}
}
#[derive(Debug, Clone, Copy)]
pub struct CountTrailingZerosInBase(NonZero<u8>);
impl CountTrailingZerosInBase {
#[must_use]
pub const fn new(base: NonZero<u8>) -> Self {
Self(base)
}
}
impl From<NonZero<u8>> for CountTrailingZerosInBase {
fn from(base: NonZero<u8>) -> Self {
Self::new(base)
}
}
impl From<CountTrailingZerosInBase> for NonZero<u8> {
fn from(strategy: CountTrailingZerosInBase) -> Self {
strategy.0
}
}
impl From<CountTrailingZerosInBase> for u8 {
fn from(strategy: CountTrailingZerosInBase) -> Self {
strategy.0.into()
}
}
impl DepthMetric for CountTrailingZerosInBase {
fn to_depth(&self, digest: Digest<LooseCommit>) -> Depth {
let arr = digest.as_bytes();
let inner_depth: u8 = self.0.into();
let (_, bytes) = num_bigint::BigInt::from_bytes_be(num_bigint::Sign::Plus, arr)
.to_radix_be(inner_depth.into());
#[allow(clippy::expect_used)]
let int = u32::try_from(bytes.into_iter().rev().take_while(|&i| i == 0).count())
.expect("u32 should be big enough, but isn't");
Depth(int)
}
}
#[derive(Debug, Clone)]
pub struct FragmentState<T> {
head_digest: Digest<LooseCommit>,
members: Set<Digest<LooseCommit>>,
checkpoints: Set<Digest<LooseCommit>>,
boundary: Map<Digest<LooseCommit>, T>,
}
impl<T> FragmentState<T> {
#[must_use]
pub const fn new(
head_digest: Digest<LooseCommit>,
members: Set<Digest<LooseCommit>>,
checkpoints: Set<Digest<LooseCommit>>,
boundary: Map<Digest<LooseCommit>, T>,
) -> Self {
Self {
head_digest,
members,
checkpoints,
boundary,
}
}
#[must_use]
pub const fn head_digest(&self) -> Digest<LooseCommit> {
self.head_digest
}
#[must_use]
pub const fn members(&self) -> &Set<Digest<LooseCommit>> {
&self.members
}
#[must_use]
pub const fn checkpoints(&self) -> &Set<Digest<LooseCommit>> {
&self.checkpoints
}
#[must_use]
pub const fn boundary(&self) -> &Map<Digest<LooseCommit>, T> {
&self.boundary
}
#[must_use]
pub fn to_fragment(self, blob_meta: BlobMeta) -> Fragment {
Fragment::new(
self.head_digest,
self.boundary.keys().copied().collect(),
self.checkpoints.iter().copied().collect(),
blob_meta,
)
}
}