Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

preader is a file reader that tracks read progress and manages read state. You can read a file in chunks, lines, bytes, or delimited segments, save your position at any point, and resume later from exactly where you left off, even after a restart

The library is available as a Rust crate and as a Python package (via PyO3 bindings). Both APIs expose the same features with the same semantics

Features

  • πŸ› οΈ Multiple Iterators: Read files using lines(), bytes(), chunks(), or segments() depending on your use case
  • ▢️ Resumable Reads: Persist your read position to disk using save(), then resume from the same state whenever you want
  • 🏁 Read Percentage: Track how far you have read through the file with the percent() method
  • πŸ’Ύ Autosave: Automatically saves your state at a configurable byte interval so you don’t lose progress if the program crashes
  • πŸ“ State Management: Manage saved states through the registry with names(), load(), search(), delete(), resync() and more
  • πŸ”’ State Verification: Checks file size, path, modification time, and fingerprint before resuming to detect changes
  • πŸŽ›οΈ Windowing: Control the read range with start, end, skip, and limit parameters
  • πŸ’» Cross Platform: Works on Linux, macOS, and Windows with portable state naming rules

Who Is This For?

preader is useful when you process large files and need to:

  • Resume after an interruption without starting over
  • Track how much of a file you have processed
  • Manage read state for multiple files or multiple jobs on the same file
  • Detect when a file has changed since you last read it

Common use cases include log processing, data pipelines, ETL jobs, and any batch work over large files

Getting Started

Head to the Quickstart to read your first file and save your position in a few lines of code

Getting Started

This chapter walks you through installing preader and reading your first file

Installation

Rust

πŸ¦€ Add preader to your project with Cargo

cargo add preader

Or add it manually to your Cargo.toml

[dependencies]
preader = "1"

Python

🐍 Install with pip

pip install preader

⚑ Or with uv

uv add preader

Quickstart

This page shows how to read a file line by line, track progress, and save your position

Rust

use preader::{Config, PReader};

fn main() -> preader::Result<()> {
    let config = Config {
        state_dir: "/tmp/states".into(),
        ..Config::default()
    };

    let reader = PReader::from(config);
    let mut lines = reader.lines("data.txt").state("job-1").build()?;

    while let Some(line) = lines.next() {
        let line = line?;

        println!("{line}, {:.1}% done", lines.percent());
    }

    let state = lines.save()?;

    println!("saved at byte {}", state.position);

    Ok(())
}

Python

from preader import Config, PReader

config = Config(state_dir="/tmp/states")
reader = PReader(config=config)

for line in (lines := reader.lines("data.txt", state="job-1")):
    print(f"{line}, {lines.percent():.1f}% done")

print(f"saved at byte {(state := lines.save()).position}")

What Happens Here

  1. You create a Config that tells preader where to store state files. The remaining fields keep their defaults
  2. You create a PReader from that config
  3. You open a line iterator on data.txt with the state name "job-1". If a saved state with that name exists, the iterator resumes from the saved position. Otherwise it starts from the beginning
  4. You iterate through lines, checking percent() after each one
  5. You call save() to persist the final position to disk

Resuming

The next time you run the same code, the iterator picks up from the saved position:

Rust

// Second run, resumes from where "job-1" left off
let mut lines = reader.lines("data.txt").state("job-1").build()?;

while let Some(line) = lines.next() {
    let line = line?;

    println!("resumed: {line}");
}

Python

# Second run, resumes from where "job-1" left off
for line in reader.lines("data.txt", state="job-1"):
    print(f"resumed: {line}")

If you call save() during iteration, the item being processed is not included in the saved position and will be delivered again on resume. See Saving and Resuming for details

Managing States

Every PReader has a state registry for listing, loading, and deleting saved states. Access it with reader.states() in Rust or reader.states in Python

Rust

let registry = reader.states();

for name in registry.names()? {
    let name = name?;
    let state = registry.load(&name)?;

    println!("{name}: byte {}", state.position);
}

registry.delete("job-1")?;

Python

registry = reader.states

for name in registry.names():
    state = registry.load(name)

    print(f"{name}: byte {state.position}")

registry.delete("job-1")

See State Registry for the full API including search(), find(), exists(), clear(), and more

Iterators

preader has several iterator types, each for a different kind of file content:

IteratorYieldsUse When
LinesUTF-8 stringsThe file is text with newline-separated records
BytesSingle bytesYou need byte-level control
ChunksByte slicesYou want to process raw data in even blocks
SegmentsDelimiter separated byte slicesThe file uses a custom delimiter (e.g. CSV fields)

All iterators share a common interface:

  • state / state() returns a snapshot of the current read position and file metadata
  • percent() returns progress through the file as a floating-point percentage
  • save() persists the current position to disk and returns the saved state

They differ in what they yield and which options they accept. Each page below covers one type with its options and examples in both Rust and Python

Lines

The line iterator reads a file as UTF-8 text, yielding one line at a time. In Rust it yields Result<String>; in Python it yields str

Basic Usage

Rust

use preader::PReader;

let reader = PReader::default();
let lines = reader.lines("data.txt").build()?;

for line in lines {
    println!("{}", line?);
}

Python

from preader import PReader

reader = PReader()

for line in reader.lines("data.txt"):
    print(line)

Lines are split on \n only. A bare \r is not treated as a line separator. A \r\n sequence is treated as a single line ending

Invalid UTF-8 bytes cause a Utf8 error in Rust and a ValueError in Python. The iterator does not silently skip invalid data

Options

OptionRust Builder MethodPython Keyword
Keep line endingskeepends(true)keepends=True
Skip empty linesskip_empty(true)skip_empty=True
Align startalign(true)align_start=True

Keeping Line Endings

By default, line terminators are stripped from the yielded strings. Set keepends to preserve them

Given a file containing "hello\nworld\n":

  • Without keepends: yields "hello", "world"
  • With keepends: yields "hello\n", "world\n"

Rust

let lines = reader.lines("data.txt").keepends(true).build()?;

for line in lines {
    let line = line?;
    // line includes the trailing \n or \r\n
    print!("{line}");
}

Python

for line in reader.lines("data.txt", keepends=True):
    # line includes the trailing \n or \r\n
    print(line, end="")

Skipping Empty Lines

When skip_empty is enabled, lines that are empty after stripping the terminator are not yielded

Given a file containing "line-0\n\nline-2\n":

  • Without skip_empty: yields "line-0", "", "line-2"
  • With skip_empty: yields "line-0", "line-2"

Rust

let lines = reader.lines("data.txt")
    .skip_empty(true)
    .build()?
    .collect::<preader::Result<Vec<_>>>()?;

// ["line-0", "line-2"]

Python

lines = list(reader.lines("data.txt", skip_empty=True))
# ["line-0", "line-2"]

Empty lines still count toward the skip option but not toward limit. If you set skip(1) and skip_empty(true) on a file starting with a blank line, the blank line is counted as the skipped item even though it would not have been yielded

Aligning the Start

When you set a start byte offset that lands in the middle of a line, align (Rust) / align_start (Python) skips the partial first line and begins reading at the next complete line

Given a file containing "abcd\nefgh\n" and start set to 2 (which lands on c inside "abcd"):

  • Without align: yields "cd", "efgh"
  • With align: yields "efgh"

Rust

let lines = reader.lines("data.txt")
    .start(2)
    .align(true)
    .build()?;

Python

from preader import IteratorOptions

options = IteratorOptions(start=2)
lines = reader.lines("data.txt", align_start=True, options=options)

Bytes

The byte iterator reads a file one byte at a time. In Rust it yields Result<u8>; in Python it yields single-byte bytes objects

This iterator has no extra options beyond the common ones (state, start, end, skip, limit). It is useful for binary protocols or when you need byte-level control

Basic Usage

Rust

use preader::PReader;

let reader = PReader::default();
let bytes: Vec<u8> = reader.bytes("data.bin")
    .build()?
    .collect::<preader::Result<_>>()?;

println!("read {} bytes", bytes.len());

Python

from preader import PReader

reader = PReader()
data = b"".join(reader.bytes("data.bin"))
print(f"read {len(data)} bytes")

Reading a Window

You can combine skip and limit to read a specific range of bytes

Rust

// Read 4 bytes starting from the 4th byte (skip first 3)
let window = reader.bytes("data.bin")
    .skip(3)
    .limit(4)
    .build()?
    .collect::<preader::Result<Vec<_>>>()?;

Python

from preader import IteratorOptions

options = IteratorOptions(skip=3, limit=4)
window = b"".join(reader.bytes("data.bin", options=options))

For the byte iterator, skip and limit count individual bytes. The skip value is folded into the start offset at build time, so skipped bytes are never read from disk

Chunks

ChunkIterator reads a file in fixed-size byte blocks. Each chunk is exactly size bytes, except the last one, which may be shorter

In Rust, each item is a Result<Vec<u8>>. In Python, each item is a bytes object

Basic Usage

Rust

use preader::PReader;

let reader = PReader::default();
let chunks: Vec<Vec<u8>> = reader.chunks("data.bin")
    .size(7)
    .build()?
    .collect::<preader::Result<_>>()?;

Python

from preader import PReader

reader = PReader()
chunks = list(reader.chunks("data.bin", chunk_size=7))

For a 26-byte file (abcdefghijklmnopqrstuvwxyz) with a chunk size of 7, the iterator yields four chunks: abcdefg, hijklmn, opqrstu, and vwxyz. The last chunk is only 5 bytes

Options

OptionRust Builder MethodPython Keyword
Chunk sizesize(7)chunk_size=7
Drop partialdrop_partial(true)drop_partial=True

Chunk Size

The default chunk size is 1024 bytes. You set a custom size with size() in Rust or chunk_size= in Python

Dropping Partial Chunks

When drop_partial is enabled, the iterator discards the final chunk if it is shorter than the requested size

Rust

use preader::PReader;

let reader = PReader::default();

// All chunks, including a shorter last one
let all: Vec<Vec<u8>> = reader.chunks("data.bin")
    .size(7)
    .build()?
    .collect::<preader::Result<_>>()?;
// 4 chunks: 7, 7, 7, 5 bytes

// Only full-sized chunks
let full: Vec<Vec<u8>> = reader.chunks("data.bin")
    .size(7)
    .drop_partial(true)
    .build()?
    .collect::<preader::Result<_>>()?;
// 3 chunks: 7, 7, 7 bytes

Python

from preader import PReader

reader = PReader()

all_chunks = list(reader.chunks("data.bin", chunk_size=7))
# 4 chunks: 7, 7, 7, 5 bytes

full_chunks = list(reader.chunks("data.bin", chunk_size=7, drop_partial=True))
# 3 chunks: 7, 7, 7 bytes

Segments

SegmentIterator splits a file on a single-byte delimiter. It works with raw bytes and does not require the file to be valid UTF-8

In Rust, each item is a Result<Vec<u8>>. In Python, each item is a bytes object. The default delimiter is b','

Basic Usage

Rust

use preader::PReader;

let reader = PReader::default();
let segments: Vec<Vec<u8>> = reader.segments("data.bin")
    .delimiter(b',')
    .build()?
    .collect::<preader::Result<_>>()?;

Python

from preader import PReader

reader = PReader()
segments = list(reader.segments("data.bin", delimiter=b","))

For the input seg-0,,seg-2, the iterator yields three segments: seg-0, "", and seg-2. A trailing delimiter does not produce an extra empty segment

The delimiter must be a single byte. In Python, pass a one-byte bytes value such as b",". Multi-byte delimiters are not supported

Options

OptionRust Builder MethodPython Keyword
Delimiterdelimiter(b',')delimiter=b","
Keep delimiterkeep(true)keep_delimiter=True
Skip emptyskip_empty(true)skip_empty=True
Align startalign(true)align_start=True

Skipping Empty Segments

When skip_empty is enabled, zero-length segments are not yielded. For the same input seg-0,,seg-2,, the iterator yields only seg-0 and seg-2

Rust

use preader::PReader;

let reader = PReader::default();
let segments: Vec<Vec<u8>> = reader.segments("data.bin")
    .delimiter(b',')
    .skip_empty(true)
    .build()?
    .collect::<preader::Result<_>>()?;
// ["seg-0", "seg-2"]

Python

from preader import PReader

reader = PReader()
segments = list(reader.segments("data.bin", delimiter=b",", skip_empty=True))
# [b"seg-0", b"seg-2"]

Keeping the Delimiter

When keep (Rust) or keep_delimiter (Python) is enabled, the delimiter byte is appended to each yielded segment. For the input seg-0,,seg-2,, the iterator yields seg-0,, ,, and seg-2,

Rust

let segments: Vec<Vec<u8>> = reader.segments("data.bin")
    .delimiter(b',')
    .keep(true)
    .build()?
    .collect::<preader::Result<_>>()?;
// ["seg-0,", ",", "seg-2,"]

Python

segments = list(reader.segments("data.bin", delimiter=b",", keep_delimiter=True))
# [b"seg-0,", b",", b"seg-2,"]

Alignment

When align (Rust) or align_start (Python) is enabled and start falls in the middle of a segment, the partial first segment is skipped and reading begins at the next complete segment. See Alignment for details

State Management

preader’s main feature is saving your read position and resuming later. This chapter covers how state works, from manual saves to autosave and file change detection

A state captures everything needed to resume a read:

  • Name: A string identifier you choose (e.g. "job-1") or one derived automatically from the file path
  • Position: The byte offset just past the last finished item
  • File Metadata: The tracked file’s path, size, modification time, and fingerprint
  • Timestamps: When the state was created and last updated
  • Checksum: A SHA-256 seal that detects tampering

States are saved as JSON files in the configured state_dir. The file name is <name>.state.json, and a / in the name creates subdirectories

When you call save(), the item you are currently processing is not included. On resume, that item will be read again. This way you never accidentally skip data

The pages below walk through each part of the state lifecycle

  • ▢️ Saving and Resuming: Manual saves, checkpoints, and the resume flow
  • πŸ’Ύ Autosave: Periodic saves that protect against crashes
  • πŸ”’ State Verification: How preader detects file changes before resuming
  • πŸ”„ Resync: Updating a state after a file moved or grew

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:

SourceRustPythonBehavior
Named.state("job-1")state="job-1"Loads the saved state by name, or starts fresh if none exists
Autoomit .state()state=None (default)Derives a name from the SHA-256 hash of the file’s canonical path
Existing.state(state)state=stateResumes 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

Autosave

Autosave periodically saves your read position without explicit save() calls. Turn it on in Config to protect against crashes and interruptions

Enabling Autosave

Set auto_save_state to true. You can adjust auto_save_state_bytes to control how often saves happen (default: every 100 MiB). Set auto_load_state to true to resume auto-named states on the next run

Rust

use std::num::NonZeroU64;
use preader::{Config, PReader};

let config = Config {
    state_dir: "/tmp/states".into(),
    auto_save_state: true,
    auto_save_state_bytes: NonZeroU64::new(1024).unwrap(),
    auto_load_state: true,
    ..Config::default()
};
let reader = PReader::from(config);

// First run, read 300 lines, autosave happens automatically
let count = reader.lines("data.txt").build()?.take(300).count();

// Second run, resumes from the last autosave
let mut resumed = reader.lines("data.txt").build()?;
println!("resumes at {:.1}%", resumed.percent());

Python

from itertools import islice
from preader import Config, PReader

config = Config(
    state_dir="/tmp/states",
    auto_save_state=True,
    auto_save_state_bytes=1024,
    auto_load_state=True,
)

reader = PReader(config=config)
first = reader.lines("data.txt")

list(islice(first, 300))
del first  # triggers autosave on drop

resumed = reader.lines("data.txt")
print(f"resumes at {resumed.percent():.1f}%")

When Autosave Triggers

Autosave fires at the following points during an iterator’s lifetime:

  1. Threshold: When the number of bytes read since the last save crosses a multiple of auto_save_state_bytes
  2. Finalize: When the iterator is fully consumed
  3. Drop: When the iterator goes out of scope or is explicitly deleted

At each trigger, preader checks whether any progress was made since the last save and skips the write if nothing changed

Failure Behavior

If an autosave fails during iteration, the error is returned as Err(...) in Rust or raised as an exception in Python, and the iterator stops. If the failure happens during drop, the error is printed to stderr as "preader: save failed: ..."

Auto-Load Behavior

auto_load_state only affects auto-named states (when state is None or omitted). Named states like state="job-1" are always loaded if they exist, regardless of this setting

When auto_load_state is false (the default), omitting the state name always starts a fresh read even if an auto-named state exists on disk

State Verification

When verify_state is true (the default), preader checks the file against the saved state before resuming. This catches file changes that happened between runs

What Is Checked

Verification runs the following checks in order:

  1. Checksum: The state file’s internal SHA-256 seal. Detects manual edits to the JSON file
  2. File Existence: The tracked file must still be on disk
  3. Fingerprint: SHA-256 of the first 4096 bytes of the tracked file. Detects content replacement
  4. File Size: Must match the size recorded when the state was last saved
  5. Modification Time: Must match the recorded mtime

File Path is checked separately. If the state tracks a different file than the one you are opening, preader raises Mismatch::Path regardless of the verify_state setting. If the state file was edited and its internal checksum no longer matches, Mismatch::Checksum takes priority

Each check failure produces a specific error:

CheckRust VariantPython ExceptionMeaning
File pathMismatch::PathStateOutdatedErrorState tracks a different file (always checked)
ChecksumMismatch::ChecksumStateCorruptErrorState file was edited outside preader
File missingMismatch::MissingStateOutdatedErrorFile was deleted
FingerprintMismatch::IdentityStateMismatchErrorFile content was replaced
File sizeMismatch::SizeStateOutdatedErrorFile grew or shrank
Modification timeMismatch::MtimeStateOutdatedErrorFile was touched

The fingerprint is the SHA-256 hash of the first 4096 bytes of the file. It detects content replacement even when the file size and modification time happen to be unchanged

Disabling Verification

Set verify_state to false in your config to skip file metadata checks:

Rust

use preader::Config;

let config = Config {
    verify_state: false,
    ..Config::default()
};

Python

from preader import Config

config = Config(verify_state=False)

When verification is off, only the file path is checked. Checksum, size, mtime, and fingerprint checks are skipped entirely

With verify_state set to false, file modifications go undetected. Use this only when you know the file has not changed and want to skip the fingerprint read

Additional Integrity Checks

One more mismatch type can occur regardless of the verify_state setting:

Rust VariantPython ExceptionMeaning
Mismatch::StaleStateConflictErrorAnother process or iterator saved to the same state file since you last loaded it

When verify_state is true, passing a State object that has unsaved modifications raises Mismatch::Unsealed (StateMismatchError in Python)

These protect against concurrent access (two writers to the same state) and programming errors (using a modified State object)

See Recovery Patterns for how to handle each of these errors

Resync

When a file moves, grows, or is otherwise modified, the saved state becomes outdated and opening an iterator fails with a mismatch error. resync updates the state’s file metadata to match the current file, so you can continue reading

The Resync Pattern

The standard approach is to catch the mismatch error, resync, and retry:

Rust

use preader::{Error, LineIterator, Mismatch, PReader};

fn resume(reader: &PReader, file: &std::path::Path) -> preader::Result<LineIterator> {
    match reader.lines(file).state("job-1").build() {
        Err(error @ Error::Mismatch {
            kind: Mismatch::Path | Mismatch::Size | Mismatch::Mtime | Mismatch::Missing,
            ..
        }) => {
            eprintln!("{error}, resyncing");
            reader.states().resync("job-1", file)?;
            reader.lines(file).state("job-1").build()
        }
        result => result,
    }
}

Python

from preader import LineIterator, PReader, StateOutdatedError


def resume(reader: PReader, file) -> LineIterator:
    try:
        return reader.lines(file, state="job-1")
    except StateOutdatedError as error:
        print(f"{error}, resyncing")
        reader.states.resync(error.name, file)
        return reader.lines(file, state="job-1")

In Rust, you match on the specific Mismatch variants that indicate a recoverable change. In Python, the same variants are grouped under StateOutdatedError

What Resync Does

resync(name, file) updates the saved state’s file metadata:

  • Path is set to the canonical path of the new file
  • Size is updated to the current file size
  • Mtime is updated to the current modification time
  • Fingerprint is recomputed from the first 4096 bytes

The read position is clamped to the new file size. If the file shrank below the saved position, the position is set to the new end of file

resync only updates the file metadata in the saved state. It does not re-read or revalidate file content beyond the first 4096 bytes used for the fingerprint

Complete Example

This example reads a file, saves state, moves the file, resyncs, appends data, and reads again:

Rust

use std::io::Write;
use preader::PReader;

let file = std::path::PathBuf::from("data.txt");
let moved = std::path::PathBuf::from("moved.txt");

std::fs::write(&file, "line-0\nline-1\n")?;

let reader = PReader::default();

// Read all lines and save
let mut lines = reader.lines(&file).state("job-1").build()?;

for line in lines.by_ref() {
    println!("read {}", line?);
}

lines.save()?;

// Move the file
std::fs::rename(&file, &moved)?;

// Resume after the move, triggers resync
let lines = resume(&reader, &moved)?;
println!("resumes at {:.1}% after the file moved", lines.percent());

// Append new data
std::fs::OpenOptions::new()
    .append(true)
    .open(&moved)?
    .write_all(b"line-2\nline-3\n")?;

// Resume after the file grew, triggers resync again
for line in resume(&reader, &moved)? {
    println!("read {} after the file grew", line?);
}

Python

from pathlib import Path
from preader import PReader

file = Path("data.txt")
moved = Path("moved.txt")

file.write_text("line-0\nline-1\n")

reader = PReader()

# Read all lines and save
lines = reader.lines(file, state="job-1")

for line in lines:
    print(f"read {line}")

lines.save()
# Move the file
file.rename(moved)

# Resume after the move
lines = resume(reader, moved)
print(f"resumes at {lines.percent():.1f}% after the file moved")

# Append new data
with moved.open("ab") as f:
    f.write(b"line-2\nline-3\n")

# Resume after the file grew
for line in resume(reader, moved):
    print(f"read {line} after the file grew")

The first resync updates the path to the new location. The second updates the file size and mtime after the append, and reading continues from where it left off

State Registry

The state registry is the interface for managing saved states on disk. You access it through reader.states() in Rust or reader.states in Python

The registry operates on the state_dir configured in Config. Every method that accepts a name validates it against the state name rules before touching the file system

The pages below cover the registry API from basic lookups to bulk operations

  • πŸ“– Basics: Load, find, check existence, list, and count saved states
  • πŸ” Search: Filter states by regex pattern, auto-generated names, and file paths
  • πŸ“ Management: Delete, clear, and resync states

Basics

You access the state registry through reader.states() in Rust or reader.states in Python. From there you can load, find, list, and count saved states

Loading a State

load reads a state file from disk and returns the State. When verify_state is true (the default), it also verifies the state file’s internal checksum and checks the tracked file’s size, mtime, and fingerprint. It raises an error if the state does not exist

Rust

let state = reader.states().load("job-1")?;
println!("position: {}", state.position);

Python

state = reader.states.load("job-1")
# or equivalently:
state = reader.states["job-1"]
print(f"position: {state.position}")

load raises Error::NotFound in Rust and KeyError in Python when the state does not exist

Finding a State

find works like load but returns None instead of raising an error. Unlike load, it catches all errors (not just missing states), so a corrupt or unreadable state file also returns None

Rust

if let Some(state) = reader.states().find("job-1") {
    println!("found at byte {}", state.position);
} else {
    println!("no saved state");
}

Python

state = reader.states.find("job-1")

if state is not None:
    print(f"found at byte {state.position}")
else:
    print("no saved state")

Checking Existence

exists returns a boolean indicating whether a state file is present on disk. It does not parse the file; it only checks that the path exists

Rust

if reader.states().exists("job-1") {
    println!("state exists");
}

Python

if "job-1" in reader.states:
    print("state exists")

Listing States

names returns a StateIterator that yields the name of every saved state

Rust

for name in reader.states().names()? {
    println!("{}", name?);
}

Python

for name in reader.states:
    print(name)

Counting States

Rust

let count = reader.states().count()?;
println!("{count} saved states");

Python

print(f"{len(reader.states)} saved states")

Loading All States

all loads every saved state at once

Rust

let states = reader.states().all()?;

for state in &states {
    println!("{}: {} bytes", state.name, state.position);
}

Python

for state in reader.states.all():
    print(f"{state.name}: {state.position} bytes")

Python Dunder Protocols

In Python, the StateRegistry supports standard container protocols:

OperationPython SyntaxEquivalent Method
Loadregistry["name"]registry.load("name")
Check existence"name" in registryregistry.exists("name")
Deletedel registry["name"]registry.delete("name")
Countlen(registry)registry.count() (Rust only)
Iteratefor name in registryregistry.names()

Search

The registry can filter states by pattern and look up state file paths

Searching by Pattern

search returns a StateIterator that yields only the names of states that match a regular expression

Rust

// Find all states starting with "batch-"
for name in reader.states().search("^batch-")? {
    println!("{}", name?);
}

Python

for name in reader.states.search("^batch-"):
    print(name)

The search pattern is a regular expression, not a glob. Use "^batch-" to match names starting with β€œbatch-”, not "batch-*"

Auto-Generated Names

When you create an iterator without specifying a state name (or with state=None in Python), preader auto-generates a name from the SHA-256 hash of the file’s canonical path. You can look up what that name would be with autoname

Rust

let name = reader.states().autoname(&file);
println!("auto-name for data.txt: {name}");

autoname is available in Rust only. In Python, the auto-name is computed internally when state is None

State File Path

path returns the filesystem path where a state file would be stored. It does not check whether the file actually exists

Rust

let path = reader.states().path("job-1")?;
println!("state file: {}", path.display());

Python

path = reader.states.path("job-1")
print(f"state file: {path}")

You can use this for debugging or to inspect the raw state JSON on disk

Management

The registry can delete individual states, clear all states, and resync a state after a file change

Deleting a State

delete removes a single state file from disk

Rust

reader.states().delete("job-1")?;

Python

reader.states.delete("job-1")
# or:
del reader.states["job-1"]

delete raises Error::NotFound in Rust and KeyError in Python when the state does not exist

Clearing All States

clear removes every state file in the state_dir

Rust

reader.states().clear()?;

Python

reader.states.clear()

clear() removes every state file in the state_dir. Use it with caution, there is no undo

Resyncing a State

resync updates a saved state’s file metadata to match the current file on disk. Use it after a file moves, grows, or is otherwise modified. The read position is clamped to the new file size so it never points past the end

Rust

reader.states().resync("job-1", &new_path)?;

Python

reader.states.resync("job-1", new_path)

See Resync for the full catch-resync-retry pattern

Windowing

Windowing lets you control which portion of a file an iterator reads. You can set a byte range, skip a number of items, limit how many items to yield, or align the start to an item boundary

In Rust, these options are set through builder methods:

reader.lines("data.txt")
    .start(100)
    .end(500)
    .skip(2)
    .limit(10)
    .build()?;

In Python, you pass an IteratorOptions object:

from preader import IteratorOptions

options = IteratorOptions(start=100, end=500, skip=2, limit=10)

reader.lines("data.txt", options=options)

When you use multiple windowing options together, they are applied in this order:

  1. Byte range (start, end) restricts the file region
  2. Alignment (align / align_start) skips the partial first item at start
  3. Skip discards the first N complete items within the range
  4. Limit caps how many items are yielded after skipping

This means skip and limit operate within the byte range, not across the entire file

// Read bytes 100-500, skip the first 2 lines in that range, yield at most 10
reader.lines("data.txt")
    .start(100)
    .end(500)
    .align(true)
    .skip(2)
    .limit(10)
    .build()?;
from preader import IteratorOptions

options = IteratorOptions(start=100, end=500, skip=2, limit=10)

reader.lines("data.txt", align_start=True, options=options)

The following pages explain each option and how they interact

  • ↔️ Byte Range: start and end byte offsets
  • πŸ”’ Pagination: skip and limit for item-level control
  • πŸ“ Alignment: Handling a start offset that falls mid-item

Byte Range

The start and end options define a byte range within the file. Only items that begin within this range are yielded

start

The byte offset where reading begins. Default: 0

When resuming from a saved state, if start is beyond the saved position, the position moves forward to start. If the saved position is already past start, the saved position wins

end

The byte offset at which no new item starts. For line and segment iterators, an item that begins before end is yielded in full even if it extends past end. For chunk iterators, the last chunk is truncated to fit within the remaining range. Default: u64::MAX (no limit)

Examples

Rust

let lines = reader.lines("data.txt")
    .start(100)
    .end(500)
    .build()?;

for line in lines {
    println!("{}", line?);
}

Python

from preader import IteratorOptions

options = IteratorOptions(start=100, end=500)

for line in reader.lines("data.txt", options=options):
    print(line)

Setting start greater than end raises an InvalidRange error in Rust and a ValueError in Python

Pagination

The skip and limit options control how many items the iterator yields, independent of byte offsets

skip

The number of items to skip before yielding the first result. Default: 0

How skipping works depends on the iterator type:

  • Bytes and chunks: skip is folded into the start offset as pure arithmetic. No data is read and discarded
  • Lines and segments: skipped items are read and discarded at runtime, because their byte length is not known in advance

limit

The maximum number of items to yield. Default: u64::MAX (no limit). Once the limit is reached, the iterator stops

Examples

Rust

// Skip the first 10 lines, then read the next 5
let lines = reader.lines("data.txt")
    .skip(10)
    .limit(5)
    .build()?;

for line in lines {
    println!("{}", line?);
}

Python

from preader import IteratorOptions

options = IteratorOptions(skip=10, limit=5)

for line in reader.lines("data.txt", options=options):
    print(line)

You can combine skip and limit with start and end. The byte range is applied first, then skip and limit operate within that range

For line iterators, skipped content is not UTF-8 validated. Only yielded items go through validation

Alignment

When start falls in the middle of a line or segment, the align option (called align_start in Python) skips the partial first item and begins reading at the next complete item

Without Alignment

A line iterator starting at byte 4 in "hello\nworld\n" yields "o" (the tail of "hello") followed by "world". The first yielded item is a fragment

With Alignment

The same iterator with alignment enabled skips the partial "o\n" and yields only "world", a complete line

Examples

Rust

let lines = reader.lines("data.txt")
    .start(4)
    .align(true)
    .build()?;

Python

from preader import IteratorOptions

options = IteratorOptions(start=4)
lines = reader.lines("data.txt", align_start=True, options=options)

The same option is available on the segment iterator:

Rust

let segments = reader.segments("data.bin")
    .start(10)
    .delimiter(b',')
    .align(true)
    .build()?;

Python

options = IteratorOptions(start=10)
segments = reader.segments(
    "data.bin", delimiter=b",", align_start=True, options=options
)

Alignment applies only to line and segment iterators. Byte and chunk iterators do not have item boundaries to align to

OptionRust Builder MethodPython Keyword
Align startalign(true)align_start=True

Error Handling

preader uses a single Error enum in Rust and a small exception hierarchy in Python. Both report the same conditions through each language’s idiomatic error mechanism: Result<T, Error> in Rust and raised exceptions in Python

Most errors you will encounter in practice fall into two categories: state mismatches (the file changed since you saved your position) and I/O errors (permissions, missing files). State mismatches are recoverable with a resync or a fresh start; I/O errors are usually environmental

Every exception in Python carries a name property with the state name involved, so you can decide what to do per state

The pages below cover every error variant, how they map across languages, and the standard recovery patterns

  • ⚠️ Error Types: Every error variant and exception class, with the Rust-to-Python mapping
  • πŸ› οΈ Recovery Patterns: How to handle outdated, corrupt, and mismatched states
  • 🏷️ State Names: Validation rules for state names and what triggers a name error

Error Types

Rust

All errors are variants of the Error enum. Functions return preader::Result<T>, which is an alias for std::result::Result<T, Error>

VariantMeaning
Error::Io(e)An I/O error from the operating system
Error::Serde(e)Failed to parse or serialize a state file
Error::Regex(e)Invalid regex pattern in search()
Error::Utf8(e)A line contained invalid UTF-8
Error::Name(NameError)A state name violates the naming rules
Error::Mismatch { name, kind }File or state metadata does not match
Error::Corrupt { name, error }A state file is damaged or was edited
Error::Alias { name }A part of the state name is a symlink, case alias, or Unicode alias
Error::NotFound(name)No saved state with that name
Error::InvalidRangestart is greater than end
Error::InvalidMtimeThe file’s modification time cannot be represented as a UTC datetime

Mismatch Variants

The Mismatch enum describes what specifically does not match:

VariantMeaningHint In Error Message
Mismatch::PathFile path changedβ€œ(resync the state if the file moved)”
Mismatch::SizeFile size changedβ€œ(resync the state if this is expected)”
Mismatch::MtimeModification time changedβ€œ(resync the state if this is expected)”
Mismatch::MissingTracked file no longer existsβ€œ(resync the state if the file moved)”
Mismatch::IdentityFirst bytes don’t match fingerprintβ€œ(start over under a new state)”
Mismatch::ChecksumState file was modified outside preader
Mismatch::UnsealedState object has unsaved changesβ€œ(pass the state returned by save())”
Mismatch::StaleState was saved elsewhere since last loadβ€œ(open a new iterator to continue)”
Mismatch::NameState file belongs to a different name

NameError Variants

VariantMeaning
NameError::EmptyThe name is an empty string
NameError::EscapesThe name starts with / or contains ..
NameError::InvalidThe name is too long, uses bad characters, or is a Windows device name

Python

Python Exceptions form a hierarchy:

Exception
  └── StateError
        β”œβ”€β”€ StateMismatchError
        β”‚     └── StateOutdatedError
        β”œβ”€β”€ StateCorruptError
        └── StateConflictError

All exception classes have a name property that holds the state name involved

Rust to Python Mapping

Rust ErrorPython Exception
Error::IoOSError (or a subclass like PermissionError)
Error::NotFoundKeyError
Error::AliasStateError
Error::CorruptStateCorruptError
Mismatch::PathStateOutdatedError
Mismatch::SizeStateOutdatedError
Mismatch::MtimeStateOutdatedError
Mismatch::MissingStateOutdatedError
Mismatch::ChecksumStateCorruptError
Mismatch::NameStateCorruptError
Mismatch::IdentityStateMismatchError
Mismatch::UnsealedStateMismatchError
Mismatch::StaleStateConflictError
Error::NameValueError
Error::InvalidRangeValueError
Error::InvalidMtimeValueError
Error::Utf8ValueError
Error::SerdeValueError
Error::RegexValueError

See Recovery Patterns for how to handle each error family

Recovery Patterns

This page shows how to handle each family of errors that can occur when resuming a read

Outdated State

Rust Error::Mismatch with Mismatch::Path, Size, Mtime, or Missing Python StateOutdatedError

The file changed in a way that is typically benign: it moved, grew, or was touched. Resync the state and retry:

Rust

use preader::{Error, Mismatch};

match reader.lines(file).state("job-1").build() {
    Err(
        error @ Error::Mismatch {
            kind: Mismatch::Path | Mismatch::Size | Mismatch::Mtime | Mismatch::Missing,
            ..
        },
    ) => {
        eprintln!("{error}, resyncing");
        reader.states().resync("job-1", file)?;
        reader.lines(file).state("job-1").build()
    }
    result => result,
}

Python

from preader import StateOutdatedError

try:
    lines = reader.lines(file, state="job-1")
except StateOutdatedError as error:
    print(f"{error}, resyncing")
    reader.states.resync(error.name, file)
    lines = reader.lines(file, state="job-1")

See Resync for the full pattern including file moves and growth

Replaced File

Rust Error::Mismatch with Mismatch::Identity Python StateMismatchError

The file content has been replaced. The first 4096 bytes no longer match the saved fingerprint, so the saved position is meaningless. Delete the state and start over:

Rust

use preader::{Error, Mismatch};

match reader.lines(file).state("job-1").build() {
    Err(Error::Mismatch { kind: Mismatch::Identity, .. }) => {
        reader.states().delete("job-1")?;
        reader.lines(file).state("job-1").build()
    }
    result => result,
}

Python

from preader import StateMismatchError, StateOutdatedError

try:
    lines = reader.lines(file, state="job-1")
except StateOutdatedError:
    raise  # handle separately, see Outdated State above
except StateMismatchError:
    reader.states.delete("job-1")
    lines = reader.lines(file, state="job-1")

Corrupt State

Rust Error::Corrupt Python StateCorruptError

The state file was manually edited or is damaged. Delete it and start over:

Rust

use preader::Error;

match reader.lines(file).state("job-1").build() {
    Err(Error::Corrupt { .. }) => {
        reader.states().delete("job-1")?;
        reader.lines(file).state("job-1").build()
    }
    result => result,
}

Python

from preader import StateCorruptError

try:
    lines = reader.lines(file, state="job-1")
except StateCorruptError:
    reader.states.delete("job-1")
    lines = reader.lines(file, state="job-1")

Stale State

Rust Error::Mismatch with Mismatch::Stale Python StateConflictError

Another process or iterator saved the state since you last loaded it. Your save would overwrite those changes:

Rust

use preader::{Error, Mismatch};

match lines.save() {
    Err(Error::Mismatch { kind: Mismatch::Stale, .. }) => {
        let fresh = reader.states().load("job-1")?;

        eprintln!("conflict: state was updated to byte {}", fresh.position);
    }
    result => { result?; }
}

Python

from preader import StateConflictError

try:
    lines.save()
except StateConflictError:
    fresh = reader.states.load("job-1")
    print(f"conflict: state was updated to byte {fresh.position}")

StateConflictError is raised by save(), not by iterator creation. It means your save would overwrite changes made by another writer

State Names

State names are validated at every entry point: when you create an iterator with a name, load a state, delete a state, or call any other registry method. A name that violates the rules raises a NameError in Rust and a ValueError in Python

Rules

  • Names must not be empty
  • Names must not start with / or contain .. (path traversal)
  • Maximum total length: 512 UTF-8 bytes
  • Maximum filename part length: 219 UTF-8 bytes
  • Maximum directory part length: 255 UTF-8 bytes
  • Directory parts cannot end with . or a space
  • Parts cannot be . or Windows reserved device names: CON, PRN, AUX, NUL, CONIN$, CONOUT$, COM1-COM9, COMΒΉ-COMΒ³, LPT1-LPT9, LPTΒΉ-LPTΒ³
  • The characters \ : * ? " < > | are not allowed

These rules apply on all platforms, not just Windows. A state file created on Linux can be read on macOS or Windows without issues

Hierarchical Names

A / in a state name creates subdirectories in the state directory. For example, the name "batch/2024/job-1" stores the state file at <state_dir>/batch/2024/job-1.state.json

Rust

let lines = reader.lines("data.txt")
    .state("batch/2024/job-1")
    .build()?;

Python

lines = reader.lines("data.txt", state="batch/2024/job-1")

You can organize states by project, date, or any other grouping

Examples of Invalid Names

NameReason
""Empty
"../secret"Path traversal (..)
"/absolute"Starts with /
"CON"Windows reserved device name
"job:1"Contains reserved character :
"aaa...a" (513 bytes)Exceeds 512-byte limit

Configuration

A Config controls how a PReader behaves: where states are stored, whether autosave is on, and how file verification works. Every field has a sensible default, so you only need to set the ones you want to change

In Rust, you create a Config with struct syntax and use ..Config::default() for the rest:

use std::path::PathBuf;
use preader::Config;

let config = Config {
    state_dir: PathBuf::from("/tmp/states"),
    auto_save_state: true,
    ..Config::default()
};

In Python, you use keyword arguments. Unspecified fields keep their defaults:

from preader import Config

config = Config(state_dir="/tmp/states", auto_save_state=True)

The pages below cover every field and their default values across platforms

  • πŸ“‹ Fields: All Config fields with types and descriptions
  • πŸ“Š Defaults: Default values, platform-specific paths, iterator option defaults, and constants

Fields

FieldRust TypePython TypeDefaultDescription
buffer_capacityusizeint65536 (64 KiB)Read buffer size in bytes
state_dirPathBufPathplatform cache dirDirectory for state files
auto_save_stateboolboolfalseEnable periodic autosave
auto_save_state_bytesNonZeroU64int104857600 (100 MiB)Bytes between autosaves
auto_load_stateboolboolfalseAuto-resume auto-named states
verify_stateboolbooltrueVerify file metadata on resume

A buffer_capacity of 0 is treated as 1. An auto_save_state_bytes of 0 raises an error because the value must be nonzero

Defaults

Config Defaults

FieldDefault
buffer_capacity65536 (64 KiB)
state_dirPlatform cache directory (see below)
auto_save_statefalse
auto_save_state_bytes104857600 (100 MiB)
auto_load_statefalse
verify_statetrue

Platform State Directories

The default state_dir is <cache_dir>/preader, where <cache_dir> is:

PlatformPath
Linux$XDG_CACHE_HOME/preader or ~/.cache/preader
macOS~/Library/Caches/preader
Windows{FOLDERID_LocalAppData}/preader

Iterator Options Defaults

FieldDefault
start0
end18446744073709551615 (u64::MAX)
skip0
limit18446744073709551615 (u64::MAX)

Iterator Specific Defaults

OptionDefault
Chunk Size1024 bytes
Segment Delimiterb',' (comma, 0x2C)
keependsfalse
skip_emptyfalse
align / align_startfalse
drop_partialfalse
keep / keep_delimiterfalse

Constants

ConstantValueDescriptionRustPython
DEFAULT_BUFFER_CAPACITY65536Read buffer size in bytesβœ“βœ—
DEFAULT_AUTO_SAVE_STATE_BYTES104857600Autosave byte thresholdβœ“βœ—
DEFAULT_VERIFY_STATEtrueVerify file metadata on resumeβœ“βœ—
DEFAULT_CHUNK_SIZE1024Default chunk sizeβœ“βœ“
DEFAULT_DELIMITERb','Default segment delimiterβœ“βœ“
FINGERPRINT_SAMPLE_BYTES4096Bytes read for fingerprintβœ“βœ“
STATE_DIR_NAME"preader"Subdirectory under cache dirβœ“βœ—
STATE_FILE_EXTENSION"state.json"Extension for state filesβœ“βœ—
TMP_FILE_EXTENSION"tmp"Temp file extension for atomic writesβœ“βœ—

Python also exposes DEFAULT_CONFIG and DEFAULT_OPTIONS as pre-built instances with all defaults applied

Advanced Topics

This chapter covers behaviors and features that go beyond basic reading and state management. You will find information about tracking read progress with a progress bar, understanding how iterators handle files that grow while being read, and using zero-copy reads in Rust for performance-critical code

  • πŸ“ˆ Progress Tracking: How percent() works and how to build a progress bar
  • πŸ“‚ Growing Files: What happens when a file is appended to while you are reading it
  • ⚑ Zero-Copy Reads: The IteratorRead trait for allocation-free reads in Rust

Progress Tracking

How Percent Works

percent() returns the read progress as a floating-point number from 0.0 to 100.0:

percent = position Γ— 100 / max(file_size, 1)
  • position reflects only finished items. The item you are currently processing is not counted
  • An empty file always reports 0.0 because the position stays at 0 and max(file_size, 1) is 1
  • percent() reaches 100.0 only when the iterator is fully consumed

Several factors can prevent percent() from reaching 100.0: an end offset before the file end, a limit, drop_partial, or breaking out of the loop early

Progress Bar with Indicatif (Rust)

use indicatif::{ProgressBar, ProgressStyle};
use preader::PReader;

let reader = PReader::default();
let mut lines = reader.lines("data.txt").build()?;
let bar = ProgressBar::new(100);

bar.set_style(
    ProgressStyle::with_template("{percent:>3}%|{bar:20}| {msg}")
        .unwrap()
        .progress_chars("β–ˆβ–‰β–Šβ–‹β–Œβ–β–Žβ– "),
);

while let Some(line) = lines.next() {
    let _line = line?;
    let pct = lines.percent();
    bar.set_position(pct.round() as u64);
    bar.set_message(format!("{pct:.1}%"));
}

bar.abandon();

Progress Bar with Tqdm (Python)

from tqdm import tqdm
from preader import PReader

reader = PReader()
lines = reader.lines("data.txt")

bar = tqdm(total=100, bar_format="{l_bar}{bar}| {n:.1f}%")

for line in lines:
    bar.update(lines.percent() - bar.n)

bar.close()

Use bar.abandon() in Rust instead of bar.finish(). Calling finish() jumps the bar to 100% regardless of the actual position

Growing Files

An iterator captures the file size when it is created and reads up to that recorded size, even if the file grows while you are reading

Held-Back Items

When a line or segment iterator reaches the recorded file size without finding a terminator and the file has grown beyond that size, it holds the item back instead of yielding it incomplete. If the file has not grown, the final unterminated item is yielded normally

This matters for files being appended to: the last line might not have its \n yet. Yielding it would give you a partial line that changes later. Instead, preader holds the item back and ends iteration

Seeing New Data

To read data that was appended after the iterator was created, resync the state and open a new iterator:

Rust

reader.states().resync("job-1", &file)?;
let lines = reader.lines(&file).state("job-1").build()?;

Python

reader.states.resync("job-1", file)
lines = reader.lines(file, state="job-1")

Data appended after the iterator was created is invisible until you resync and open a new iterator

Zero-Copy Reads

This feature is available in Rust only. The Python bindings always return owned values

The IteratorRead trait provides a read() method that returns a borrowed reference instead of an owned value, avoiding one allocation per item

pub trait IteratorRead {
    type Borrowed<'a> where Self: 'a;
    type Owned: for<'a> From<Self::Borrowed<'a>>;

    fn read(&mut self) -> Result<Option<Self::Borrowed<'_>>>;
}

Borrowed vs Owned Types

IteratorBorrowedOwned
ByteIteratoru8u8
ChunkIterator&[u8]Vec<u8>
LineIterator&strString
SegmentIterator&[u8]Vec<u8>

Usage

Call read() in a loop instead of using the Iterator trait:

use preader::{IteratorRead, PReader};

let reader = PReader::default();
let mut lines = reader.lines("data.txt").build()?;

while let Some(line) = lines.read()? {
    // `line` is a &str borrowed from the iterator's internal buffer
    println!("{line}");
}

The borrowed reference is valid until the next call to read() or next(). Do not store it across iterations

When to Use This

Use read() when you process each item immediately without collecting them. The standard Iterator trait (via next()) is simpler and sufficient for most use cases

API Reference

Full API documentation for each language is hosted separately