Saving and Resuming
The save() method persists the current read position to disk and returns the saved State. The next time you open an iterator with the same state name, it resumes from where you left off
Position Semantics
The position field counts finished items only. An item counts as finished when you request the next one. While you are processing an item, it is not yet reflected in position
Checkpoint Pattern
You can save at regular intervals to create checkpoints. If the program crashes between checkpoints, the last checkpoint is the resume point
Rust
use preader::PReader;
let reader = PReader::default();
let mut lines = reader.lines("data.txt").state("job-1").build()?;
let mut count = 0;
while let Some(line) = lines.next() {
count += 1;
let line = line?;
println!("read {line}");
if count % 2 == 0 {
let state = lines.save()?;
println!("checkpoint at byte {}", state.position);
}
if count == 5 {
break;
}
}
// Second run, resumes from the last checkpoint, not from line 5
for line in reader.lines("data.txt").state("job-1").build()? {
println!("resumed: {}", line?);
}
Python
from preader import PReader
reader = PReader()
first = reader.lines("data.txt", state="job-1")
for count, line in enumerate(first, start=1):
print(f"read {line}")
if count % 2 == 0:
state = first.save()
print(f"checkpoint at byte {state.position}")
if count == 5:
break
# Second run, resumes from the last checkpoint
for line in reader.lines("data.txt", state="job-1"):
print(f"resumed: {line}")
Checkpoints are saved after lines 2 and 4. The first run stops at line 5 without saving. The second run resumes from the line 4 checkpoint, re-reads line 4, and continues with line 5
State Sources
There are several ways to supply a state when creating an iterator:
| Source | Rust | Python | Behavior |
|---|---|---|---|
| Named | .state("job-1") | state="job-1" | Loads the saved state by name, or starts fresh if none exists |
| Auto | omit .state() | state=None (default) | Derives a name from the SHA-256 hash of the file’s canonical path |
| Existing | .state(state) | state=state | Resumes from the position in the given State object |
By default (auto_load_state = false), the auto-named state is not loaded on the next run, so the iterator starts from byte 0. Set auto_load_state to true to resume from it automatically
Atomic Writes
State files are written atomically: preader writes to a temporary file first, syncs it to disk, and then renames it over the target path. You never see a half-written state file, even if the program crashes mid-save