rust
22 lines · 5 steps
Streaming a SHA-256 hash of a file in Rust
Compute a file's SHA-256 digest by reading it in fixed-size chunks so memory stays constant regardless of file size.
Explained by
highlit
1use std::fs::File;
2use std::io::{self, Read};
3use std::path::Path;
4
5use sha2::{Digest, Sha256};
6
7pub fn sha256_file(path: impl AsRef<Path>) -> io::Result<String> {
8 let mut file = File::open(path)?;
9 let mut hasher = Sha256::new();
10 let mut buffer = [0u8; 64 * 1024];
11
12 loop {
13 let read = file.read(&mut buffer)?;
14 if read == 0 {
15 break;
16 }
17 hasher.update(&buffer[..read]);
18 }
19
20 let digest = hasher.finalize();
21 Ok(hex::encode(digest))
22}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reading a file in a fixed buffer keeps memory flat no matter how large the file grows.
- 2Hashers accept data incrementally, so you never need the whole input in memory at once.
- 3Using `impl AsRef<Path>` lets callers pass strings, `PathBuf`, or `Path` interchangeably.
Related explainers
ruby
require "net/http" require "json" class UrlFetcher
A thread-pool URL fetcher in Ruby
concurrency
thread-pool
queues
Intermediate
8 steps
rust
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread;
A round-robin worker pool in Rust
concurrency
thread-pool
channels
Intermediate
7 steps
go
package auth import ( "errors"
Hashing and verifying passwords with bcrypt in Go
password-hashing
bcrypt
error-handling
Intermediate
7 steps
typescript
import { useState, useCallback } from 'react'; type Todo = { id: string;
Optimistic UI updates in a React hook
optimistic-updates
custom-hooks
error-handling
Intermediate
8 steps
go
package fsutil import ( "io/fs"
Walking a directory tree to find large files in Go
filesystem
recursion
closures
Intermediate
7 steps
rust
use axum::{ extract::State, http::StatusCode, Json,
Idempotent webhook handling in Axum
deduplication
idempotency
shared-state
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-a-sha-256-hash-of-a-file-in-rust-explained-rust-7da8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.