Compact and efficient source file mapping and position tracking, written in Rust.
Register source files once, hand out stable numeric ids and pack every span — file id, line and column — into a single u64. Look paths up in O(1), navigate files byte-accurately, and keep diagnostics positions cheap enough to store by the million. Built for compilers, linters, formatters, language servers and code editors.
sourcier solves a small problem that diagnostics-heavy tools hit every day: positions must be cheap to build, compare, store and serialize, yet still resolve back to the exact bytes of the file they point at. Instead of dragging String paths and four usize fields through every diagnostic, sourcier packs the whole span into one u64 and keeps the heavy data in a single immutable registry.
- One
u64per span. File id, start line, start column, end line and end column are bit-packed together. Positions areCopy, cache-friendly, order naturally as integers and survive serialization round trips bit-exactly. - Constant-time lookups. After finalization, path to id, id to path and id to content are all O(1); line and column navigation is O(log n).
- Zero-allocation finalization. Paths up to 30 bytes live inline inside their entry (short-string optimization), so registering and finalizing typical source trees performs no per-path heap allocation at all.
- Verified, HashDoS-safe path index. A per-map seeded open-addressed index maps paths to entries with 4 bytes per slot; every probe is verified against the stored path bytes, so collisions can never produce a wrong answer and adversarial keys cannot be precomputed.
- Deterministic ids. Finalizing sorts files by path (with a registration-order tiebreak), deduplicates registrations and assigns one-based ids, so the same set of files always produces the same ids — and the first registration of a duplicate path always wins, even for hundreds of duplicates.
- Byte-accurate views. With the
viewfeature, a position resolves to the exact bytes it covers — including multi-line spans, line terminators and zero-width spans. - Typed, sealed API. The
FileIdtrait is sealed (u8andu16only), error enums are#[non_exhaustive], and the packed layouts are documented so raw values can be persisted safely. - No unsafe code. The whole workspace is
#![forbid(unsafe_code)].
[dependencies] sourcier = "2.0"
Or track the repository directly:
[dependencies] sourcier = { git = "https://github.com/elcoosp/sourcier", branch = "main" }
Tip
You only ever depend on sourcier. It re-exports the full API of the
sourcier-core engine crate, which exists so the implementation can stay
small and the facade stable.
use sourcier::{AbsolutePosition, SourceFilePosition, SourceFilesMap}; // 1. Register files (u8 ids support up to 255 files, u16 up to 65,535). let mut files = SourceFilesMap::<u8>::new(); files .add_file("src/main.rs", b"fn main() {\n println!(\"Hello\");\n}") .expect("capacity available"); files.add_file("src/lib.rs", b"pub mod utils;").expect("capacity available"); // 2. Finalize: sorts by path, deduplicates, assigns one-based ids. files.finalize().expect("no capacity issue"); // 3. Look up files and pack positions into a single u64. let id = files.get_id("src/main.rs").expect("file present"); assert_eq!(files.get_path(id), Some("src/main.rs")); let pos = AbsolutePosition::new(id, 2, 5, 2, 22); assert_eq!(pos.start_line(), 2); // 4. With the default `view` feature, extract the exact bytes of a span. assert_eq!(files.view(id, &pos), Some(&b"println!(\"Hello\");"[..]));
AbsolutePosition::new encodes values as-is — infallible and zero-cost. Use try_new when a span should be validated as a well-formed, one-based region:
use sourcier::AbsolutePosition; assert!(AbsolutePosition::<u8>::try_new(1, 2, 1, 1, 1).is_err()); assert!(AbsolutePosition::<u8>::try_new(1, 1, 1, 1, 1).is_ok());
The two-phase lifecycle is also available in a form the compiler enforces: SourceFilesBuilder only exposes registration, finalize consumes it and hands back the lookup-ready map, so MapError::Finalized and MapError::AlreadyFinalized cannot happen:
use sourcier::{SourceFilesBuilder, SourceFilePosition}; let files = SourceFilesBuilder::<u8>::new() .add_file("src/main.rs", b"fn main() {}") .expect("capacity available") .add_file("src/lib.rs", b"pub mod utils;") .expect("capacity available") .finalize() .expect("no capacity issue"); let id = files.get_id("src/main.rs").expect("file present"); let pos = files.position_from_offset(id, 4).expect("in range"); assert_eq!(pos.start_line(), 1); // Diagnostics render as `path:line:column` without allocating. assert_eq!(files.display_position(id, &pos).expect("present").to_string(), "src/main.rs:1:5");
Loops use add_file_mut; batches use add_files, which is all-or-nothing — a failed batch leaves the builder or map exactly as it was. remaining_capacity reports how many more files the id type can address.
With the default view feature, the map bridges between byte offsets and packed positions in O(log n) over the per-file line index, with no allocation:
position_from_offset(id, offset)maps a byte offset (including the end-of-file insertion anchor) to a point position.offset_from_position(id, &pos)maps the start of any span back to its byte offset.display_position(id, &pos)renderspath:line:columnlazily through a borrowedPositionDisplay.
Spans move between the packed encodings with AbsolutePosition::to_relative and RelativePosition::to_absolute; RelativePosition::new and from_raw are const fn, so spans can be built in const and static items.
add_file takes any AsRef<str>. Tools holding Path/PathBuf values register through add_path, which fails with MapError::PathNotUtf8 (carrying the lossy path) when the OS path is not valid UTF-8:
use sourcier::{SourceFilesBuilder, MapError}; use std::path::PathBuf; let files = SourceFilesBuilder::<u8>::new() .add_path(PathBuf::from("src/main.rs"), b"fn main() {}") .expect("utf-8 path") .finalize() .expect("no capacity issue"); assert_eq!(files.get_id("src/main.rs"), Some(1));
Positions are stable u64 encodings. The table shows the bit range of each field, most significant first:
| Id type | File id | Start line | Start col | End line | End col |
|---|---|---|---|---|---|
u8 |
56..64 |
40..56 |
32..40 |
16..32 |
0..8 |
u16 |
48..64 |
32..48 |
24..32 |
8..24 |
0..8 |
RelativePosition stores start line (32..48) | start col (24..32) | end line (8..24) | end col (0..8) without a file id. Ids are one-based: 0 is never assigned, which keeps the all-zero encoding reserved.
Warning
Lines are u16 (up to 65,535) and columns are u8 (1 to 255, byte
columns). The view feature indexes files of up to 4 GiB via compact
u32 offsets; larger files simply resolve no views.
All features are enabled by default and forwarded to sourcier-core.
| Feature | Default | Description |
|---|---|---|
serde |
yes | Serialize/Deserialize for maps, positions and line indexes. |
view |
yes | Line offset indexes plus view/view_str byte extraction. |
rt-feedback |
yes | Lock-free shared usage statistics (RuntimeFeedback). |
parallel |
no | Multi-threaded line-offset index construction with rayon for huge file sets. |
Trim them for a leaner build:
[dependencies] sourcier = { version = "2.0", default-features = false, features = ["view"] }
| Type / trait | Purpose |
|---|---|
SourceFilesMap<Id> |
Build phase: register files. Lookup phase: query by path or id. |
SourceFilesBuilder<Id> |
Type-state build phase: chaining registration, compile-time phase separation. |
FileId |
Sealed trait implemented by u8 and u16. |
AbsolutePosition<Id> |
Span bound to a file, packed into one u64. |
RelativePosition |
File-agnostic span packed into the low 48 bits of a u64. |
SourceFilePosition |
Uniform accessor trait over both position kinds. |
LineOffsets (view) |
Compact per-line byte offset index with line/col mapping. |
RuntimeFeedback (rt-feedback) |
Atomic counters shared across maps via Arc. |
line_offsets (view) |
Accessor over the per-file index behind view. |
position_from_offset (view) |
Byte offset → point position, O(log n), no allocation. |
offset_from_position (view) |
Span start → byte offset, O(log n), no allocation. |
display_position / PositionDisplay |
Zero-allocation path:line:column diagnostic rendering. |
MapError, PositionError |
Typed, non_exhaustive error enums. |
Measured with the bundled criterion suite (cargo bench -p sourcier-core) on the reference machine, comparing 2.0 against the 1.0 baseline in the same measurement window; treat the numbers as indicative:
| Scenario | 1.0 | 2.0 | Change |
|---|---|---|---|
| Finalize 100 files x 50 lines | ~64 us | ~41 us | -35% |
| Finalize 500 files x 100 lines | ~709 us | ~513 us | -28% |
| Finalize phase only, 2,000 x 200 lines | ~3.7 ms | ~2.8 ms | -25% |
1,000 multi-line view extractions |
~14.4 us | ~4.4 us | -70% |
| Line offsets for 100 files x 1,000 lines | ~0.79 ms | ~0.69 ms | -12% |
| 1,000 offset-to-(line, col) probes | - | ~8.2 us | new |
Single-line view_str span |
- | ~257 ns | new |
| 2,000 path-to-id lookups (hits) | ~34 us | ~41 us | see note |
| 2,000 path-to-id lookups (misses) | - | ~33 us | new |
The 2.0 path-to-id index trades a small amount of hit latency (~20%) for byte-exact verification, HashDoS-resistant per-map seeding, zero allocations at finalization and roughly half the lookup-state memory. Hits and misses both terminate on the first empty slot, so misses are as cheap as hits.
Design notes:
- Finalization is a single unstable sort with a registration-order tiebreak plus one O(n) pass; file contents are never copied during finalization, and no per-path string allocation happens (inline paths up to 30 bytes,
Box<str>beyond). - Line offsets use a single
memchr-accelerated scan (the 1.0 counting pre-pass is gone) and 4 bytes per line (u32offsets, files up to 4 GiB); opt intoparallelto spread the scan across cores withrayonon many-core build machines (on a 2-core reference VM the thread-pool overhead outweighed the scan savings, which is why the feature is opt-in). - Lookups run through a verified open-addressed index: seeded Fx-style hashing, linear probing at a load factor of 0.5, and hash-plus-bytes verification so any collision pattern still resolves exactly.
- Per-file line offsets live in a dense
Vec<Option<LineOffsets>>indexed by id —viewpays no hashing on its hot path. - Serialized map payloads carry only the raw entries and the phase flag; lookup state is rebuilt on load (v1 payloads with the redundant
path_to_idtable still deserialize). rt-feedbackuses atomics only; no locks are taken on the reporting path.- The DX additions (builder, offset⇄position bridge,
PositionDisplay, batch registration) are pure additions that delegate to the existing machinery: the builder is an inline newtype over the map, the offset bridge reuses the per-fileLineOffsetsindex, andPositionDisplayrenders lazily from borrowed data. Thebuilder/*,position_from_offset/*andoffset_from_position/*benchmark tracks pin their cost; the originalfinalize,get_id,viewandline_offsetstracks are unchanged.
The workspace ships a layered test suite — unit, integration, property-based (proptest), snapshot (insta) and doc tests. Coverage is measured with cargo-llvm-cov: 100% of functions are covered, and llvm-cov show confirms every line and every reachable region executes. The summary table reports 99.9% for lines and regions; the residual counts are uncallable compiler artifacts (definition-site copies of generic code), not missing tests:
cargo test --workspace --all-features # unit, integration, property, doc tests cargo nextest run --workspace --all-features cargo llvm-cov --workspace --all-features --summary-only cargo clippy --workspace --all-targets --all-features -- -D warnings cargo fmt --all -- --check RUSTDOCFLAGS="-D warnings" cargo doc --workspace --all-features --no-deps cargo deny check # licenses, advisories, bans, sources cargo bench -p sourcier-core # criterion benchmarks
Snapshot tests live in sourcier-core/src/tests/snapshots/ and are committed to the repository; regenerate them after an intentional change with INSTA_UPDATE=always cargo test.
Note
Property tests pin the round trips (position encoding, line/col to offset inverse mapping, map lookup consistency, first-registration-wins duplicate resolution at hundreds-of-files scale) against hundreds of generated cases, including adversarial deserialized maps that exceed the id capacity. The 4 GiB line-offset limit is exercised end to end with lazily committed allocations, so the oversized-file paths are tested for real.
Rust 1.99. The MSRV is verified in CI with cargo check across feature configurations.
This release is 2.0.0: the public API documented on docs.rs is stable and follows semantic versioning. Error enums are #[non_exhaustive], the FileId trait is sealed, and the packed u64 layouts are documented so raw values can be persisted.
The 2.0 wire format of SourceFilesMap dropped the redundant path_to_id table (it is derived from the sorted entries and rebuilt on load); 1.0 payloads that still carry the field deserialize without error and are ignored.