use alloc::boxed::Box;
use crate::loose_commit::id::CommitId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Depth(pub u32);
impl Depth {
#[must_use]
pub const fn is_boundary(&self) -> bool {
self.0 > 0
}
}
impl core::fmt::Display for Depth {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Depth({})", self.0)
}
}
pub trait DepthMetric {
fn to_depth(&self, id: CommitId) -> Depth;
}
impl<Idish: From<CommitId>, Depthish: Into<Depth>> DepthMetric for fn(Idish) -> Depthish {
fn to_depth(&self, id: CommitId) -> Depth {
self(Idish::from(id)).into()
}
}
impl<T: DepthMetric> DepthMetric for Box<T> {
fn to_depth(&self, id: CommitId) -> Depth {
T::to_depth(self, id)
}
}
#[derive(Debug, Clone, Copy)]
pub struct CountLeadingZeroBytes;
impl DepthMetric for CountLeadingZeroBytes {
fn to_depth(&self, id: CommitId) -> Depth {
let mut acc = 0;
for &byte in id.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()
}
}
use core::num::NonZero;
impl DepthMetric for CountTrailingZerosInBase {
fn to_depth(&self, id: CommitId) -> Depth {
let arr = id.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)
}
}