Re: [PATCH 05/14] rust: add a hash algorithm abstraction
- From
Ezekiel Newren <ezekielnewren@gmail.com>
- Date
- Oct 28, 2025, 17:09 UTC
- Message-ID
- <CAH=ZcbACQt6a=8AtsRD3UUx+-6xB14HJM1p0XC4Nu9ZWKL4fkQ@mail.gmail.com>
- In-Reply-To
- <aQCKTFrmtlp9UEL6@pks.im>
On Tue, Oct 28, 2025 at 3:18 AM Patrick Steinhardt <ps@pks.im> wrote:
Show 41 quoted lines
>
> On Mon, Oct 27, 2025 at 12:43:55AM +0000, brian m. carlson wrote:
> > diff --git a/src/hash.rs b/src/hash.rs
> > index 0219391820..1b9f07489e 100644
> > --- a/src/hash.rs
> > +++ b/src/hash.rs
> > @@ -19,3 +19,145 @@ pub struct ObjectID {
> > pub hash: [u8; GIT_MAX_RAWSZ],
> > pub algo: u32,
> > }
> > +
> > +#[allow(dead_code)]
> > +impl ObjectID {
> > + pub fn as_slice(&self) -> &[u8] {
> > + match HashAlgorithm::from_u32(self.algo) {
> > + Some(algo) => &self.hash[0..algo.raw_len()],
> > + None => &self.hash,
> > + }
> > + }
> > +
> > + pub fn as_mut_slice(&mut self) -> &mut [u8] {
> > + match HashAlgorithm::from_u32(self.algo) {
> > + Some(algo) => &mut self.hash[0..algo.raw_len()],
> > + None => &mut self.hash,
> > + }
> > + }
> > +}
> > +
> > +/// A hash algorithm,
> > +#[repr(C)]
> > +#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
> > +pub enum HashAlgorithm {
> > + SHA1 = 1,
> > + SHA256 = 2,
> > +}
> > +
>
> Seeing all the `match` statements: we could alternatively implement this
> as a trait. This would have the added benefit that we cannot miss
> updating any of the functions if we ever were to add another hash
> function.match is more strict than switch. If another enum type is added then the current code will not compile. While I do like the idea of using traits the problem is that the hash algorithm used needs to be known on disk. We can still use traits, but in conjunction with this enum. The part where we need to be careful is HashAlgorithm::from_u32() because if _3_ ever becomes valid then this code (currently) will say it's not.