# Objects

> ObjectId, ObjectKind, and reading or writing blobs, trees, and commits through Odb.

Git stores four object kinds grit-lib exposes as [`ObjectKind`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.ObjectKind.html). Every object is named by an [`ObjectId`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectId.html) (SHA-1 by default). Prefer [`Repository::objects`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) ([`Objects`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html)) for read/write/contains; it delegates to the pluggable [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) on the same [`Repository`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html).

## Writing

[`Objects::write`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html#method.write) takes a kind and payload bytes, stores a loose object under `objects/`, and returns the id. Tree, commit and tag payloads are checked first with the same rules as `git hash-object -t <kind>`: an unsorted tree, a duplicate entry, or an identity line without a timestamp fails with `InvalidObject` on [`Error`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html), which carries Git's fsck message id (`treeNotSorted`, `missingSpaceBeforeDate`, …), and nothing is written. [`Objects::write_literally`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html#method.write_literally) skips the checks, like `git hash-object --literally`; it exists to reproduce corrupt objects in tests. [`Odb::write`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write) is the unchecked internal path the engine uses for objects it has built itself. Use [`parse_tree`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_tree.html) and [`parse_commit`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_commit.html) when reading objects back.

## Big objects

[`Odb::write_stream`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write_stream) stores an object from any [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) of known size without holding it in memory. Objects of at least [`Odb::big_file_threshold`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.big_file_threshold) bytes (`core.bigFileThreshold`, 512 MiB unless configured) are hashed and deflated in fixed-size chunks straight into a new single-object pack at the pack compression level (`pack.compression` / `core.compression`), which is what Git does with big files; smaller objects are written loose as usual. If the object already exists, the new pack is discarded. [`Odb::hash_stream`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.hash_stream) computes the id the same way without storing anything. A reader that ends early fails with [`ObjectError::StreamTruncated`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.StreamTruncated).

Staging uses the same path: `add`, `commit` auto-staging and `status` stream every worktree file at or above the threshold whose content needs no clean conversion (no clean filter, `working-tree-encoding` or line-ending conversion), so their memory use does not grow with the file size. Files that need a conversion are read whole, as in Git.

Staging never stores content twice. Like Git, it freshens an existing copy instead of writing a new one: a blob already in a local pack (promisor packs included) or an alternate object directory gets its pack's mtime refreshed, and no loose object is written, so re-adding packed content (for example after `rm --cached -r .`) adds nothing to `objects/`. Only an object stored solely in a cruft pack, which cannot be freshened, is written loose again. Bulk staging sets [`WriteOptions::freshen_existing`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.WriteOptions.html#structfield.freshen_existing) only when the repository has a pack or an alternate, so writing into a repository without either skips the probe entirely. Callers of [`Odb::write_with`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.write_with) build the same options with `WriteOptions::default().with_freshen_existing(true)`; the loose-store hints in [`WriteOptions`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.WriteOptions.html) are ignored by custom object stores.

```rust
use std::fs::File;
use grit_lib::objects::ObjectKind;
use grit_lib::objects::odb::WriteOptions;

let mut file = File::open("dataset.bin")?;
let size = file.metadata()?.len();
let oid = repo.odb().write_stream(ObjectKind::Blob, size, &mut file, WriteOptions::default())?;
```

## Building trees and commits

A program that creates history without an index or work tree (a bare-repository tool, a changelog bot) should not assemble object bytes by hand. [`Objects::write_tree`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html#method.write_tree) takes [`TreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html) values ([`TreeEntry::new(name, mode, oid)`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html#method.new), with a typed [`FileMode`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.FileMode.html)) in any order, sorts them into Git's tree order, and refuses entries `git fsck` would reject with a typed [`TreeEntryError`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.TreeEntryError.html): an empty, `.`, `..` or `.git` name, a `/` or NUL in a name, a mode other than `100644`, `100755`, `120000`, `40000` or `160000`, the null id, an id of the other hash algorithm, a name over 4096 bytes, a name used twice (a file and a directory with the same name count), or a symlink to a reserved metadata file name (`.gitmodules`, `.gitattributes`, and related spellings). Each entry's object must exist in the repository with the kind implied by its mode (tree or blob; gitlink `160000` entries may name a commit that is not stored locally), matching `git mktree` without `--missing`; missing or wrong-kind oids return [`ObjectError::NotFound`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.NotFound) or [`ObjectError::UnexpectedKind`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.UnexpectedKind) (under [`Error::Object`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Object)). Pass [`WriteTreeOptions::allow_missing`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.WriteTreeOptions.html#structfield.allow_missing) to [`Objects::write_tree_with`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html#method.write_tree_with) when building trees bottom-up or referencing objects a partial clone has not fetched (wrong kinds are still rejected).

[`Objects::write_commit`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html#method.write_commit) takes a [`NewCommit`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.NewCommit.html): a tree, parents, message, and author and committer as typed [`Signature`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html) values. [`Signature::new`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html#method.new) takes a name, an email and an `OffsetDateTime` and rejects `<`, `>` and control characters, times before 1970 and offsets with a seconds part ([`SignatureError`](https://docs.rs/grit-lib/latest/grit_lib/ident/enum.SignatureError.html)), so the header line always has Git's `Name <email> <unix> <±HHMM>` shape. `write_commit` checks that the tree is a tree and each parent is a commit, as `git commit-tree` does. It adds a trailing newline to the message when missing. When `grit.changeIds` is on (the default) the commit gets a fresh `change-id` header; call [`NewCommit::with_change_id`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.NewCommit.html#method.with_change_id) to keep the id of a change you are rewriting. The commit is not signed and no ref moves. To commit the index onto the current branch, use [`CommitRequest`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitRequest.html) (as `grit commit` does) instead.

For hot paths that only need headers (tree, parents, identities) or a borrowed message body, prefer [`CommitRef::parse`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.CommitRef.html#method.parse). It borrows from the object bytes and decodes author, committer, and message on demand via [`CommitRef::author`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.CommitRef.html#method.author), [`CommitRef::committer`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.CommitRef.html#method.committer), and [`CommitRef::message`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.CommitRef.html#method.message). [`parse_commit`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_commit.html) is `CommitRef::parse(data)?.to_owned()` for callers that need an owning [`CommitData`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.CommitData.html).

[`Odb::hash`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) (or [`HashAlgo::hash_object`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.HashAlgo.html)) computes an id without writing—useful for dry runs and tests. The algorithm follows the repository’s configured object format (SHA-1 or SHA-256).

Object ids and file checksums share the same digest algorithms but serve different roles. [`ObjectHasher`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/struct.ObjectHasher.html) and [`HashAlgo::digest`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.HashAlgo.html) name Git objects (canonical `"<kind> <len>\\0<payload>"` bytes or raw payloads that become an [`ObjectId`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectId.html)). [`ChecksumHasher`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/struct.ChecksumHasher.html), [`HashAlgo::checksum_digest`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.HashAlgo.html), [`HashingWriter`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/struct.HashingWriter.html), and [`verify_trailer`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/fn.verify_trailer.html) cover pack, index, MIDX, and commit-graph trailers—integrity checks, not object identities.

## Collision detection

SHA-1 object ids are computed with collision detection (sha1dc). [`hash_object`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/fn.hash_object.html), [`HashAlgo::hash_object`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.HashAlgo.html#method.hash_object), [`HashAlgo::digest`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.HashAlgo.html#method.digest), [`ObjectHasher::finalize`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/struct.ObjectHasher.html#method.finalize), and [`Odb::hash`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.hash) return [`Result`](https://docs.rs/grit-lib/latest/grit_lib/error/type.Result.html) and surface [`ObjectError::HashCollision`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.HashCollision) (under [`Error::Object`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Object)) when a chosen-prefix collision is detected. Ingestion paths (`Odb::write`, pack indexing, worktree staging) propagate the same error instead of storing a colliding object.

```rust
use grit_lib::error::{Error, ObjectError};
use grit_lib::objects::{HashAlgo, ObjectKind};
use grit_lib::objects::hash::hash_object;

let payload = b"hello\n";
match hash_object(HashAlgo::Sha1, ObjectKind::Blob, payload) {
    Ok(oid) => println!("blob id {oid}"),
    Err(Error::Object(ObjectError::HashCollision { oid })) => {
        eprintln!("refusing colliding digest {}", oid.to_hex());
    }
    Err(e) => return Err(e.into()),
}
```

Patch ids, rerere ids, and pack/index trailers use [`ChecksumHasher`](https://docs.rs/grit-lib/latest/grit_lib/objects/hash/struct.ChecksumHasher.html)—same digests, not object identities, and no collision guard on those paths.

## Revision labels

[`Repository::revision_label`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.revision_label) returns an optional [`RevisionLabel`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/object_inspect/enum.RevisionLabel.html) for a short local branch or tag name. `HEAD` labels its symbolic local branch, including an unborn branch; detached `HEAD` has no label. Short branch names take precedence over equally named tags. It uses the repository's ref store, including injected backends. This is the classification used by `grit show`; resolve the revision separately when you need its object id.

`RevisionLabel::Tag` carries the tag ref's short name and an optional parsed annotation. Lightweight tags have no annotation. Annotated tags retain their original tag header, tagger, target, extra headers and untrimmed message; the target is not peeled. Missing labels return `None`, while unreadable tag objects and malformed annotations return library errors.

## Reading

[`Odb::read`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) returns an [`Object`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Object.html) with `kind` and uncompressed `data`. Packed and loose objects share the same API.

For hot loops (tree walks, batch cat-file), [`Odb::read_into`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.read_into) inflates into a caller-owned [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) and returns the [`ObjectKind`](https://docs.rs/grit-lib/latest/grit_lib/objects/enum.ObjectKind.html). Payload bytes stay in the buffer; wrap them with [`ObjectRef::from_buf`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectRef.html#method.from_buf) when you need a borrowed view. The same method exists on [`ObjectStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/store/trait.ObjectStore.html) backends (default: copy from `read`; native for loose files and packs).

When you only need type and size (for example listing objects without loading blob bodies), use [`Odb::read_info`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) (see `read_info` on [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html)). It returns [`ObjectInfo`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectInfo.html) and avoids inflating full payloads for loose objects and non-delta pack entries; delta chains are resolved from headers and delta size varints only.

## Streaming large objects

For user-facing object inspection, [`Repository::read_object_info_for_display`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.read_object_info_for_display) returns kind and size, and [`Repository::with_object_stream_for_display`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.with_object_stream_for_display) passes the payload reader to a callback. Both follow replace refs unless the repository environment disables them. `grit cat` uses these APIs to stream large blobs in human output; JSON and Markdown keep their documented content fields.

[`Odb::with_stream`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.with_stream) hands a callback an [`ObjectStream`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.ObjectStream.html) (kind, size and a reader over the payload) and returns the callback's result, or `None` when the object is missing. Loose objects and objects stored whole in a pack are inflated as you read, in fixed-size chunks, so copying a multi-gigabyte blob to a file takes a few hundred KiB of memory. Pack deltas are rebuilt in memory first, which Git also has to do. A truncated or corrupt object, including one whose zlib checksum fails, comes back as an `io::Error` from the reader. [`Odb::open_stream`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.open_stream) returns a stream that owns its payload, so it reads the whole object first. Use it only for small objects.

```rust
use std::io::{Read, Write};

let copied = odb.with_stream(&blob_id, |stream| {
    let mut reader = stream.reader;
    let mut buf = vec![0u8; 256 * 1024];
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        out.write_all(&buf[..n])?;
    }
    Ok(stream.size)
})?;
```

Checkout uses this path. `restore`, `switch`, `reset --hard` and clone stream any regular file larger than 1 MiB straight into the work tree when no content conversion applies to its path (no `ident`, `working-tree-encoding`, smudge filter or LF-to-CRLF setting; see `worktree_conversion_is_identity`). Files at or under 1 MiB, which is nearly all of them, are still read with one lookup: a loose object's header, or a whole pack entry's header, gives the size before the body is inflated, so the size check is part of the read. A file that does stream is looked up twice, once to size it and once to open the stream, and a whole pack entry's bytes are checked against the pack index CRC before streaming, so a corrupt copy is never streamed. Streamed data goes to a temporary file next to the destination, which is renamed into place only after the object's size and zlib checksum have been verified. A corrupt object fails the checkout and leaves the old file, or no file, in place. The check that a restored file matches its blob hashes large files in chunks too, when nothing would change the file on its way into Git (`git_conversion_is_identity`).

## Reading commits

[`Odb::read_commit`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.read_commit) (also on [`Objects`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html)) reads an id, checks it names a commit and returns the parsed [`CommitData`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.CommitData.html). When you only need the root tree, [`Odb::commit_tree`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.commit_tree) decodes just the commit headers. Neither follows annotated tags; peel first (see below) when the id may name one. An id that names a tree, blob or tag fails with `UnexpectedObjectKind` on [`Error`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html), which carries the id and both kinds, so callers can tell "wrong kind of object" from a missing or corrupt one without matching message text. Stash, merge, pull, the history engine and commit-graph Bloom filters read commits through these two methods.

One-line listings need less than a whole commit. [`Odb::read_commit_through_subject`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.read_commit_through_subject) returns the leading bytes of a commit's payload through the first non-blank line of its message: every header (tree, parents, author, committer, `change-id`, signatures) and the subject, so [`parse_commit`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_commit.html) and [`read_commit_subject_line`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.read_commit_subject_line.html) give the same values as for the whole commit. For a commit stored whole in a pack it stops inflating at that line, so a long message body is never decompressed (or checked); deltas, loose objects and other stores read the commit whole and cut it. A commit that declares a non-UTF-8 `encoding`, or whose message has no line with a printable ASCII character, comes back whole, since where its subject ends is only known after decoding.

## Looking up a path in a tree

[`Odb::tree_entry_at_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.tree_entry_at_path) returns the [`TreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html) at a `/`-separated path such as `b"src/lib.rs"` under a root tree, or `None` when a component is missing or a directory on the way is really a file. The last entry comes back whatever its mode (file, symlink, gitlink or subtree), so filter on `mode` when only files will do. Trees on the way go through the handle's bounded tree cache and are scanned without allocating an entry per name, so looking up many paths under the same directories stays cheap. Diff, stash, blame, the history engine and snapshot checkout all look up single paths this way.

## Tree iteration without copying names

[`parse_tree`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_tree.html) allocates an owning [`TreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html) for every name. For hot paths that only walk a tree once (object walks, pack enumeration, fsck), use [`TreeRefIter`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeRefIter.html): it yields [`TreeEntryRef`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntryRef.html) values that borrow name bytes from the tree blob. Pass the repository hash width with [`TreeRefIter::with_oid_len`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeRefIter.html#method.with_oid_len), or call [`TreeRefIter::infer_oid_len`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeRefIter.html#method.infer_oid_len) when the algorithm is not threaded through (same SHA-1-then-SHA-256 detection as [`parse_tree`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_tree.html)). Call [`TreeEntryRef::to_owned`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntryRef.html#method.to_owned) when you need a [`TreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html). The compiled example below reads a tree with both APIs.

## Peeling tags

A ref tip can name an annotated tag, or a tag of a tag. `Odb::peel_tags` (on [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html)) follows the chain and returns the id and kind of the first non-tag object; `Odb::peel_to_commit` returns `Some(commit)` when that object is a commit and `None` for a tree or blob. Only tag objects are read in full, and only their `object` header is parsed, so tags with non-UTF-8 messages peel fine; the final object's kind comes from `read_info`. Chains of any length are followed. A missing object, a tag without a valid `object` header, or a store that serves a tag cycle is an error, not `None`, so you can tell "not a commit" apart from a broken repository. Revision walks, fetch negotiation, bundles, commit-graph tips, `packed-refs` peel lines, tag listing and log decorations all peel through these two methods.

When you read a full annotated tag with [`parse_tag`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.parse_tag.html), the message body is stored as raw bytes like Git (there is no `encoding` header on tags). Invalid UTF-8 is decoded lossily into [`TagData::message`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TagData.html#structfield.message) (U+FFFD replacement characters), with the original bytes kept in [`TagData::raw_message`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TagData.html#structfield.raw_message) so [`serialize_tag`](https://docs.rs/grit-lib/latest/grit_lib/objects/fn.serialize_tag.html) round-trips the object id. This matches how grit treats commit messages without an `encoding` header.

## Pack read caching

[`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) owns a repository-scoped [`PackStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_store/struct.PackStore.html): pack directory listings, parsed `.idx` files, pack bytes, MIDX layers, and the delta-base LRU. Cloned [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) handles share the same store; alternate object directories get separate stores on the parent [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html). When the last handle to a [`PackStore`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_store/struct.PackStore.html) is dropped, thread-local pack and index mappings for that store are released on the dropping thread.

After repack, garbage collection, or installing a pack with [`install_pack_bytes`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.install_pack_bytes.html), call [`Odb::invalidate_packs`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) so the next read rescans `objects/pack/`. If another [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) in the same process still holds a stale listing, a lookup miss retriggers directory reprepare when the pack folder’s mtime changes.

For batch reads (`cat-file --batch`, `--batch-all-objects`), wrap the loop in [`Odb::with_pack_read_context`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) so pack indexes, mmap-backed pack bytes, and the delta-base LRU stay on one thread-local context instead of reinstalling it per object. [`Odb::read`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) detects an active matching context and skips nested setup.

When iterating a pack in offset order (unordered `--batch-all-objects`), prefer [`read_object_from_pack_at_offset`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack/index.html) with the entry offset from [`PackIndex`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack/struct.PackIndex.html) so the read path does not repeat index lookup by OID.

The reverse direction, from a pack offset to the object stored there (resolving an `OFS_DELTA` base, for example), is [`PackIndex::find_position_by_offset_sorted`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack/struct.PackIndex.html#method.find_position_by_offset_sorted). Each index decodes its offset table once, from Git's `.rev` reverse index when the pack has a valid one and by sorting the index rows otherwise, and clones of the index share it, so every later lookup is a binary search.

## Pack deltas (encoding)

When building new pack deltas (as opposed to reusing on-disk zlib), grit-lib indexes the base blob with [`DeltaIndex`](https://docs.rs/grit-lib/latest/grit_lib/objects/delta_encode/struct.DeltaIndex.html) and encodes targets with a rolling fingerprint matcher. Reuse one index across many targets in a pack-objects window; `encode` on that index accepts an optional `max_size` cap (zero means no limit). An empty target yields a valid delta (header varints only). [`encode_delta`](https://docs.rs/grit-lib/latest/grit_lib/objects/delta_encode/fn.encode_delta.html) is a convenience wrapper for one-off base/target pairs.

## Example

This example initializes a repository, writes a blob, then a tree and commit through the typed API, verifies structure in memory, and prints the commit id:

```rust
//! Write a blob, tree, and commit through [`grit_lib::objects::Objects`], then read them back.
//!
//! Source for the library guide "Objects" page (included in the docs site).

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::error::ObjectError;
use grit_lib::ident::Signature;
use grit_lib::objects::FileMode;
use grit_lib::objects::{parse_commit, parse_tree, NewCommit, ObjectKind, TreeEntry, TreeRefIter};
use grit_lib::repo::{InitOptions, Repository};
use std::path::{Path, PathBuf};
use time::OffsetDateTime;

fn write_demo_objects(
    repo: &Repository,
) -> Result<
    (
        grit_lib::objects::ObjectId,
        grit_lib::objects::ObjectId,
        grit_lib::objects::ObjectId,
    ),
    grit_lib::error::Error,
> {
    let blob_data = b"hello from the library guide\n";
    let blob_oid = repo.objects().write(ObjectKind::Blob, blob_data)?;

    let tree_oid =
        repo.objects()
            .write_tree([TreeEntry::new(b"README", FileMode::REGULAR, blob_oid)])?;

    let epoch = OffsetDateTime::UNIX_EPOCH;
    let ada = Signature::new("Ada Lovelace", "ada@example.com", epoch)?;
    let commit_oid = repo.objects().write_commit(&NewCommit::new(
        tree_oid,
        ada.clone(),
        ada,
        "Library guide objects example",
    ))?;

    let tree_obj = repo.objects().read(&tree_oid)?;
    let mut iter_entries = TreeRefIter::infer_oid_len(&tree_obj.data)?;
    let first = iter_entries.next().ok_or_else(|| {
        grit_lib::error::Error::Object(ObjectError::Corrupt {
            detail: "tree has no entries".into(),
        })
    })??;
    assert_eq!(first.oid, blob_oid);
    assert_eq!(parse_tree(&tree_obj.data)?[0].oid, blob_oid);

    let commit_obj = repo.objects().read(&commit_oid)?;
    let parsed = parse_commit(&commit_obj.data)?;
    assert_eq!(parsed.tree, tree_oid);

    Ok((blob_oid, tree_oid, commit_oid))
}

fn open_repo(root: &Path) -> Result<Repository, grit_lib::error::Error> {
    let git_dir = if root.join(".git").is_dir() {
        root.join(".git")
    } else {
        root.to_path_buf()
    };
    let work_tree = if root.join(".git").is_dir() {
        Some(root)
    } else {
        None
    };
    let mut opts = RepositoryOptions::empty();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Repository::open(&git_dir, &opts)
}

fn main() -> Result<(), grit_lib::error::Error> {
    let repo = if let Some(root) = std::env::args().nth(1).map(PathBuf::from) {
        open_repo(&root)?
    } else {
        let temp = tempfile::tempdir().map_err(grit_lib::error::Error::Io)?;
        Repository::init(
            temp.path(),
            &InitOptions::new()
                .with_initial_branch("main")
                .with_ref_storage(grit_lib::refs::ref_storage::RefStorageFormat::Files),
        )?;
        open_repo(temp.path())?
    };

    let (blob_oid, tree_oid, commit_oid) = write_demo_objects(&repo)?;
    println!("{commit_oid}");
    println!("blob={blob_oid} tree={tree_oid}");
    Ok(())
}
```

Objects land on disk in standard loose format. System Git can read them:

```bash
cargo run --bin guide_objects /path/to/repo
git -C /path/to/repo fsck --strict
```

When run without arguments the binary uses a temporary repository (fine for `cargo run`, not for fsck demos).
