Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add finish_into to write the hash to a user provided buffer. #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

calmofthestorm
Copy link

  • This avoids needing to allocate a vector for every hash on Windows and
    Linux. The CommonCrypto API will work but still allocates a vector.

  • The buffer must match the digest size exactly or panic. An undersized
    buffer would violate Rust safety guarantees, but an oversized buffer
    could also be problematic if, e.g., the user passed a 32 byte buffer
    into a 20 byte digest without zeroing it first.

  • The main benefit is performance when hashing enormous numbers of
    values, but this can also be more ergonomic in certain cases.
    Consider:

struct Oid {
  sha1: [u8 ; 20],
}

fn one() {
  let mut oid = Oid::default();
  // ...
  hasher.finalize_into(&mut oid.sha1);
}

// vs

fn two() {
  let mut oid = Oid::default();
  // ...
  let digest = hasher.finalize();
  oid.sha1.copy_from_slice(&digest);
}
  • Also fix a bug in the helpers in lib.rs which should call flush
    after writing to the Hasher.

* This avoids needing to allocate a vector for every hash on Windows and
  Linux. The CommonCrypto API will work but still allocates a vector.

* The buffer must match the digest size exactly or panic. An undersized
  buffer would violate Rust safety guarantees, but an oversized buffer
  could also be problematic if, e.g., the user passed a 32 byte buffer
  into a 20 byte digest without zeroing it first.

* The main benefit is performance when hashing enormous numbers of
  values, but this can also be more ergonomic in certain cases.
  Consider:

```
struct Oid {
  sha1: [u8 ; 20],
}

fn one() {
  let mut oid = Oid::default();
  // ...
  hasher.finalize_into(&mut oid.sha1);
}

// vs

fn two() {
  let mut oid = Oid::default();
  // ...
  let digest = hasher.finalize();
  oid.sha1.copy_from_slice(&digest);
}
```

* Also fix a bug in the helpers in `lib.rs` which should call `flush`
  after writing to the Hasher.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant