Re: [PATCH 13/14] rust: add a small wrapper around the hashfile code
- From
Ezekiel Newren <ezekielnewren@gmail.com>
- Date
- Oct 28, 2025, 18:19 UTC
- Message-ID
- <CAH=ZcbBUw0Rm-O=Xc8835dWKYbmK0L1eksONAzRUa0fgdppb5A@mail.gmail.com>
- In-Reply-To
- <20251027004404.2152927-14-sandals@crustytoothpaste.net>
On Sun, Oct 26, 2025 at 6:44 PM brian m. carlson <sandals@crustytoothpaste.net> wrote:
> +use crate::hash::{HashAlgorithm, GIT_MAX_RAWSZ};
> +use std::ffi::CStr;
> +use std::io::{self, Write};
> +use std::os::raw::c_void;std::os::raw has been deprecated, only std::ffi should be used.
Show 17 quoted lines
> +/// A writer that can write files identified by their hash or containing a trailing hash.
> +pub struct HashFile {
> + ptr: *mut c_void,
> + algo: HashAlgorithm,
> +}
> +
> +impl HashFile {
> + /// Create a new HashFile.
> + ///
> + /// The hash used will be `algo`, its name should be in `name`, and an open file descriptor
> + /// pointing to that file should be in `fd`.
> + pub fn new(algo: HashAlgorithm, fd: i32, name: &CStr) -> HashFile {
> + HashFile {
> + ptr: unsafe { c::hashfd(algo.hash_algo_ptr(), fd, name.as_ptr()) },
> + algo,
> + }
> + }- pub fn new(algo: HashAlgorithm, fd: i32, name: &CStr) -> HashFile {
- HashFile {
+ pub fn new(algo: HashAlgorithm, fd: i32, name: &CStr) -> Self {
+ Self {Show 30 quoted lines
> + /// Finalize this HashFile instance.
> + ///
> + /// Returns the hash computed over the data.
> + pub fn finalize(self, component: u32, flags: u32) -> Vec<u8> {
> + let mut result = vec![0u8; GIT_MAX_RAWSZ];
> + unsafe { c::finalize_hashfile(self.ptr, result.as_mut_ptr(), component, flags) };
> + result.truncate(self.algo.raw_len());
> + result
> + }
> +}
> +
> +impl Write for HashFile {
> + fn write(&mut self, data: &[u8]) -> io::Result<usize> {
> + for chunk in data.chunks(u32::MAX as usize) {
> + unsafe {
> + c::hashwrite(
> + self.ptr,
> + chunk.as_ptr() as *const c_void,
> + chunk.len() as u32,
> + )
> + };
> + }
> + Ok(data.len())
> + }
> +
> + fn flush(&mut self) -> io::Result<()> {
> + unsafe { c::hashflush(self.ptr) };
> + Ok(())
> + }
> +}It's always nice to implement the _Write_ trait for any type that consumes &[u8] slices. It makes it easy to use a plethora of standard library functions.