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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 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.