dta
A pure Rust library for reading and writing Stata data formats.
This crate covers two related-but-distinct file formats:
- DTA — the binary format Stata uses to persist datasets. Every released version is supported (102 through 119), including XML-framed releases (117+), tagged missing values, value-label sets, and long-string (
strL) storage. - DCT — Stata's plain-text dictionary format, used to describe fixed-width or free-format
.dat/.rawdata files. Common when importing into Stata from external systems.
Both formats sit under Stata, still the dominant interchange format in academic economics, public health, and social science research — often the only format that downstream collaborators can actually open.
The DTA API is built around a typestate chain, so you can't accidentally write a schema before a header, or read data bytes before the schema has been parsed. Each phase borrows the underlying I/O handle and hands it to the next phase, keeping the pipeline zero-copy where possible.
The DCT API is a two-step builder — parse the dictionary into a Schema, then pair the schema with a data source to read records.
Usage — DTA
Reading a file
The reader walks through the sections of a DTA file in order. Each phase returns the next phase when you're done with it.
use DtaReader;
use Result;
Each reader exposes header() and schema() accessors, so you can inspect metadata without threading them through yourself.
Lazy records
RecordReader::read_record() eagerly decodes every cell in the row. If you only need a subset of columns — or you want to defer parsing until you know whether you care — use read_lazy_record() instead. LazyRecord hands back raw byte slices that you decode one cell at a time.
while let Some = record_reader.read_lazy_record?
Writing a file
The writer is the mirror image of the reader: a typestate chain that locks in the ordering of the header, schema, characteristics, data, long strings, and value labels. The <map> offsets and the header's K/N placeholders are patched in place as each section closes, which is why the writer requires Write + Seek.
use ByteOrder;
use DtaWriter;
use Header;
use Release;
use Schema;
use Value;
use Variable;
use VariableType;
use StataDouble;
use StataLong;
use Result;
RecordWriter::write_record validates arity and per-column types against the schema, so a mismatch is caught at the call site rather than producing a malformed file.
Usage — DCT
A .dct dictionary describes the schema of a plain-text data file: where each variable starts, how wide it is, what type it is, what its name is, and (optionally) a label. The associated data may live in a separate .dat/.raw file (the dictionary's using clause) or inline after the closing }.
use DctReader;
use DctSource;
use Result;
Lazy DCT records
If you only need a subset of columns per row, read_lazy_record() defers value decoding until you ask for it. Useful for skipping the parse work on the columns you don't care about.
while let Some = reader.read_lazy_record?
What's supported
The DCT parser supports the directives you'll see in real-world dictionary files:
_column(#)— absolute byte position (1-based; stored 0-based internally)_skip(#)and bare_skip— per-variable column-pointer modifier (relative to the running cursor; combines with_column(#)when both are present)_newline— multi-line observations;_column(#)references restart at 1 after eachlrecl(#)andfirstlineoffile(#)directives- All Stata storage types (
byte,int,long,float,double,str,str#) - All read formats (
%w.df,%w.dg,%w.de,%wf,%f,%ws,%s) - Both single-line and multi-line records
- Both fixed-width and free-format reads
- The
using FILEclause and the optionalinfileprefix - Comments (
*lines)
Per-record diagnostics surface as DctWarning values on the reader: blank short-line fields treated as system missing, integer values auto-promoted to a wider storage type when they fall in the missing-marker range, declared using paths the library doesn't act on, and unrecognized directives.
A note on real-world coverage: the rarer directives (lrecl(#), firstlineoffile(#), _newline, free-format reads) are implemented against Stata's documentation but I haven't found a .dct file in the wild that uses them — every public dictionary I sampled had been cleaned up to the common subset. If you hit a bug with one of these, please file an issue with a small representative .dct file and the matching data file so I can reproduce.
If you don't intend to inspect warnings() — for example, in a tight read loop where you only care about values — disable warning collection on the options builder so the reader can skip building the diagnostic structs entirely:
let mut reader = options
.record_warnings
.from_path?;
Feature Flags
chrono — date/time helpers
Disabled by default. Stata stores dates and timestamps as plain numeric values whose meaning is encoded in the variable's display format (%td, %tc, %tm, …). Enabling chrono adds typed conversions to chrono types so you don't have to track the 1960 epoch, the milliseconds-vs-days distinction, or the legacy %d alias yourself.
[]
= { = "0.6", = ["chrono"] }
= "0.4"
The module is layered. The lower layers ship without any time-crate dependency and are always available — only the typed adapters live behind the feature flag:
dta::stata::temporal::conversion— pure numeric helpers (td_days_to_unix_days,tc_millis_to_unix_millis, plus(year, sub-period)decomposers for%tw/%tm/%tq/%th). Useful as-is for consumers usingjiff,time, or raw Unix timestamps.dta::stata::temporal::TemporalKind::from_format— classify a Stata format string intoDate,DateTime,Year,Week, etc. Recognizes the eight%t*prefixes plus the legacy%dalias, and ignores display suffixes (%tdCCYY-NN-DDclassifies the same as bare%td).dta::stata::temporal::chrono_adapter(feature-gated) —NaiveDate/NaiveDateTimeadapters,Value-aware helpers that handle storage-type widening and Stata missing-value sentinels, and atemporal_from_value(&Value, &str) -> Option<StataTemporal>dispatcher that picks the right path from a column's format string.
use DtaReader;
use Result;
use ;
temporal_from_value returns None for non-temporal columns, Stata missing-value sentinels (. and .a–.z), storage/format mismatches (e.g., a %tc cell stored as Long), and the leap-second-adjusted %tC format (chrono can't model leap seconds; drop to the Layer 1 tc_millis_to_unix_millis helper if you need to make a policy decision yourself).
The feature also enables StataTimestamp::to_naive_date_time, which converts the file-header timestamp directly to a NaiveDateTime.
tokio — async I/O
Disabled by default. Enable it for async reading and writing with tokio.
[]
= { = "0.6", = ["tokio"] }
= { = "1", = ["fs", "io-util", "rt", "macros"] }
This unlocks async terminals on every options builder:
- DTA:
DtaReader::from_tokio_*returns anAsyncHeaderReaderthat mirrors the sync chain with.awaitat each step;DtaWriter::from_tokio_*returns anAsyncHeaderWriter. The async writer requiresAsyncWrite + AsyncSeek + Unpinso that the XML<map>and header placeholders can still be patched in place. - DCT:
DctSource::options().from_tokio_*returns aDctSource<R>;DctReader::options(schema).from_tokio_*returns anAsyncDctReader<R>whoseread_record/read_lazy_recordmethods are.awaited.
let mut reader = options.from_tokio_path.await?;
while let Some = reader.read_record.await?
The sync and async DCT paths share the same pure parsing state — only the I/O loop differs.
use DtaReader;
use Result;
async
Character encoding
encoding_rs is a hard dependency, not a feature flag. The reader and writer pick an encoding from the release number by default: Windows-1252 for pre-118 files and UTF-8 for 118+. If you need to override that — for example, reading a pre-118 file produced by a locale that wasn't Windows-1252 — pass an explicit encoding:
use DtaReader;
let reader = new
.encoding
.from_path?;
Benchmarks
The project ships Criterion benchmarks that exercise sync and async read/write throughput against a synthetic panel-style file:
# Sync benchmarks only (no optional features)
# Include the async (tokio) benchmarks
Results are saved to target/criterion/ with HTML reports. To run a single benchmark by name:
The first run generates benches/data/bench_large.dta (~100K rows) and caches it for subsequent runs.
Profiling
The repository includes a profiling workflow built on samply. One-time setup:
# Install samply (Linux / macOS / Windows)
# On Linux, samply needs perf_event_open access:
|
Then run the profiling script:
# Default: 1M records, top 10 functions
# Customize record count and report depth
On Windows, use .\profile.ps1 with the same options (-Records, -Top). samply uses ETW on Windows, so the script must run from an elevated PowerShell window.
The script builds optimized binaries with debug symbols, records separate samply profiles for the sync write, sync read, async write, and async read phases, and prints a table of the hottest functions from this crate by inclusive and self time.
About
This is a passion project that I maintain on my own time. I care deeply about its quality and want it to be genuinely useful, but I also want to keep it fun and sustainable. To that end:
- Bug reports are always welcome. Please file issues for anything that isn't working correctly.
- Feature requests are best expressed as pull requests. I'm much more likely to engage with a well-crafted PR than a request for new work.
- Timelines are my own. I'll get to things when I can, and I may close issues or PRs that don't align with the project's direction – nothing personal.
If you find this library valuable, the best way to support it is to contribute or share it with others.