use std::{
collections::{HashMap, HashSet},
error::Error,
mem::take,
num::NonZero,
};
use thiserror::Error;
use crate::{depth::DepthMetric, Depth, Digest};
#[derive(Debug, Clone, Copy, Error, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[error("missing commit: {0}")]
pub struct MissingCommitError(Digest);
pub trait Parents {
fn parents(&self) -> HashSet<Digest>;
}
#[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) -> Result<Option<Self::Node>, Self::LookupError>;
fn fragment<D: DepthMetric>(
&self,
head_digest: Digest,
strategy: &D,
) -> Result<FragmentState<Self::Node>, FragmentError<'a, Self>> {
let min_depth = strategy.to_depth(head_digest);
let mut visited: HashSet<Digest> = HashSet::from([head_digest]);
let mut members: HashSet<Digest> = HashSet::from([head_digest]);
let mut boundary: HashMap<Digest, Self::Node> = HashMap::new();
let mut checkpoints: HashSet<Digest> = HashSet::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: HashSet<Digest> = 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> = Vec::new();
for (boundary_hash, boundary_change) in &boundary {
members.remove(boundary_hash);
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,
))
}
}
#[derive(Debug, Clone, Copy)]
pub struct CountLeadingZeroBytes;
impl DepthMetric for CountLeadingZeroBytes {
fn to_depth(&self, digest: Digest) -> 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) -> Depth {
let arr = digest.as_bytes();
let inner_depth: u8 = self.0.into();
let (_, bytes) = num::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 is big enough");
Depth(int)
}
}
#[derive(Debug, Clone)]
pub struct FragmentState<T> {
head_digest: Digest,
members: HashSet<Digest>,
checkpoints: HashSet<Digest>,
boundary: HashMap<Digest, T>,
}
impl<T> FragmentState<T> {
#[must_use]
pub const fn new(
head_digest: Digest,
members: HashSet<Digest>,
checkpoints: HashSet<Digest>,
boundary: HashMap<Digest, T>,
) -> Self {
Self {
head_digest,
members,
checkpoints,
boundary,
}
}
#[must_use]
pub const fn head_digest(&self) -> Digest {
self.head_digest
}
#[must_use]
pub const fn members(&self) -> &HashSet<Digest> {
&self.members
}
#[must_use]
pub const fn checkpoints(&self) -> &HashSet<Digest> {
&self.checkpoints
}
#[must_use]
pub const fn boundary(&self) -> &HashMap<Digest, T> {
&self.boundary
}
}