hashavatar
hashavatar is a Rust crate for deterministic, procedural avatar generation. It is designed for services that need stable user or tenant avatars without bundled artwork, sprite sheets, external asset packs, or filesystem-side effects.
The crate starts conservative: validated avatar dimensions, bounded identity input, namespace-isolated hashing, safe Rust rendering, in-memory raster encoding, SVG string rendering, and a release process with dependency, audit, fuzz, package, SBOM, and reproducibility checks.
Current Status
The current development version is 0.10.0.
Implemented now:
- Pure library crate; no bundled demo server and no CLI binary.
- Deterministic avatars derived from SHA-512 identity hashes by default.
- Optional BLAKE3 and XXH3-128 identity derivation behind explicit Cargo features.
- Public enum variant lists use single-source
ALLslices and byte-to-variant helpers for deterministic option derivation. - Visual layer options for accessories, accent palettes, expressions, and
frame shapes through
AvatarStyleOptions. - Automatic style derivation uses distinct identity digest bytes for kind, background, accessory, color, expression, and shape.
- Namespace-aware identity derivation for tenant isolation and visual rollouts.
- Length-prefixed hash components to avoid delimiter ambiguity.
- Avatar families through
AvatarKind:cat,dog,robot,fox,alien,monster,ghost,slime,bird,wizard,skull,paws,planet,rocket,mushroom,cactus,frog,panda,cupcake,pizza,icecream,octopus, andknight. - Background modes through
AvatarBackground:themed,white,black,dark,light, andtransparent. - Visual layers through
AvatarAccessory,AvatarColor,AvatarExpression, andAvatarShape. - In-memory
WebP,PNG,JPEG, andGIFencoding throughAvatarOutputFormat. - Compact SVG string rendering.
- Typed errors for invalid dimensions and oversized identity inputs.
- Private
AvatarSpecfields so dimensions must pass construction-time validation. - No public path-writing helpers; callers own their storage and filesystem boundary.
#![forbid(unsafe_code)]in library code.- Golden visual regression fingerprints.
- Isolated fuzz harness for avatar identities, families, backgrounds, SVG rendering, and PNG encoding.
- Local release gates for formatting, clippy, tests, docs, dependency policy, RustSec advisories, package contents, SBOM generation, reproducible build checks, and crates.io publish dry runs.
Planned or intentionally external:
- HTTP serving, rate limits, cache headers, security headers, observability, and abuse controls live in
hashavatar-api. - Additional output formats such as AVIF or JPEG XL require dependency-policy review before admission.
- Larger identity inputs should be normalized or mapped by the application before calling this crate.
Trust Dashboard
| Area | Status |
|---|---|
| License | MIT OR Apache-2.0 |
| MSRV | Rust 1.95.0 |
| Crate shape | Library only |
| Runtime dependencies | image, palette, rand, sha2, subtle, zeroize; optional blake3, xxhash-rust |
| Unsafe policy | #![forbid(unsafe_code)] |
| Filesystem policy | No public path-writing APIs |
| Dimension limits | 64..=2048 pixels per side |
| Identity limits | 1024 bytes per identity input |
| Namespace limits | 128 bytes per tenant/style-version component |
| Hashing posture | SHA-512 default with length-prefixed domain, namespace, style, and identity components; optional BLAKE3 and non-cryptographic XXH3-128 |
| SVG posture | Generated numeric markup only; caller input is not inserted into SVG fragments |
| Release evidence | fmt, clippy, tests, docs, deny, audit, fuzz harness compile, package check, SBOM, reproducibility |
Security-control details live in docs/SECURITY_CONTROLS.md. Dependency policy lives in docs/DEPENDENCIES.md. Panic policy lives in docs/PANIC_POLICY.md.
Future version planning for visual layer polish, variant expansion, and 1.0 stabilization lives in
docs/VERSION_PLAN.md. hashavatar remains a single
image-generation crate; low-level core planning is kept internal unless a
future release has a concrete image-generation reason to split it.
Install
[]
= "0.10.0"
Optional identity hash algorithms are disabled by default:
[]
= { = "0.10.0", = ["blake3", "xxh3"] }
For a local checkout:
[]
= { = "../hashavatar" }
The crate is dual-licensed:
= "MIT OR Apache-2.0"
Limits
| Limit | Value |
|---|---|
| Minimum width/height | 64 |
| Maximum width/height | 2048 |
| Maximum raster pixels | 4,194,304 |
| Maximum raw RGBA buffer | 16,777,216 bytes |
| Maximum identity input | 1024 bytes |
| Maximum namespace tenant | 128 bytes |
| Maximum namespace style version | 128 bytes |
These limits are enforced by constructors and render entry points. They are intended to make the safe path the normal path for public web endpoints.
Public Option Catalog
All public option enums expose an ALL slice, from_byte, as_str,
Display, and FromStr support. Byte-to-variant mapping always indexes
through ALL, so adding variants does not require duplicated modulo constants
in caller code.
| Enum | Controls | Values |
|---|---|---|
AvatarKind |
Base avatar family | cat, dog, robot, fox, alien, monster, ghost, slime, bird, wizard, skull, paws, planet, rocket, mushroom, cactus, frog, panda, cupcake, pizza, icecream, octopus, knight |
AvatarBackground |
Canvas/background treatment | themed, white, black, dark, light, transparent |
AvatarAccessory |
Optional accessory layer | none, glasses, hat, headphones, crown, bowtie, eyepatch, scarf, halo, horns |
AvatarColor |
Optional accent palette | default, neon-mint, pastel-pink, crimson, gold, deep-sea-blue |
AvatarExpression |
Optional expression overlay | default, happy, grumpy, surprised, sleepy, winking, cool, crying |
AvatarShape |
Optional frame shape | square, circle, squircle, hexagon, octagon |
AvatarOutputFormat |
Raster encoding format | webp, png, jpg, gif |
AvatarOptions is the stable baseline option type for callers that only need
kind and background. AvatarStyleOptions carries the full 0.10.0 visual
style tuple: kind, background, accessory, color, expression, and
shape.
Accessories and expressions require face anchors. Face-like families have
calibrated anchors; non-face families such as paws, planet, and rocket
skip accessory/expression layers deterministically instead of placing them at
arbitrary canvas coordinates. Accent colors and frame shapes are canvas-level
layers and still apply.
Example: Encode WebP
use ;
let spec = new?;
let bytes = encode_avatar_for_id?;
assert!;
# Ok::
The returned bytes can be sent as an HTTP response, uploaded to object storage, written to a caller-selected path, or cached by a CDN.
Example: Render SVG
use ;
let spec = new?;
let svg = render_avatar_svg_for_id?;
assert!;
assert!;
# Ok::
Use SVG when you need vector output, easy inspection, text storage, or post-processing by application code.
Example: Namespaced Tenants
use ;
let namespace = new?;
let spec = new?;
let bytes = encode_avatar_for_namespace?;
assert!;
# Ok::
Use namespaces when the same user identifier must not collide visually across tenants, products, or style-version rollouts.
Example: Deterministic Options From Bytes
use ;
let digest_bytes = ;
let options = new;
assert!;
assert!;
The from_byte helpers use each enum's ALL slice, so new public variants do
not require duplicated modulo constants in caller code.
Example: Automatic Visual Layers
use ;
let spec = new?;
let image = render_avatar_auto_for_id?;
assert_eq!;
# Ok::
Automatic mode derives these top-level choices from distinct SHA-512 digest bytes:
| Choice | Digest byte |
|---|---|
AvatarKind |
AVATAR_STYLE_KIND_BYTE |
AvatarBackground |
AVATAR_STYLE_BACKGROUND_BYTE |
AvatarAccessory |
AVATAR_STYLE_ACCESSORY_BYTE |
AvatarColor |
AVATAR_STYLE_COLOR_BYTE |
AvatarExpression |
AVATAR_STYLE_EXPRESSION_BYTE |
AvatarShape |
AVATAR_STYLE_SHAPE_BYTE |
Example: Manual Visual Layers
use ;
let spec = new?;
let style = new;
let svg = render_avatar_svg_style_for_id?;
assert!;
assert!;
# Ok::
Existing AvatarOptions::new(kind, background) callers keep the old baseline
visual behavior. Use AvatarStyleOptions::from_options(options) when you want
to pass legacy options through a style-aware API without enabling extra layers.
Accessories and expressions are rendered only for avatar families with
calibrated face anchors. Non-face families such as paws, planet, and
rocket skip those layers deterministically instead of drawing them in
misleading positions. Color and frame-shape layers still apply.
Example: Optional Hash Algorithm
use ;
let namespace = new?;
let identity_options = new;
let spec = new?;
let image = render_avatar_with_identity_options?;
assert_eq!;
# Ok::
AvatarHashAlgorithm::Sha512 is always available and is the security-sensitive
default. AvatarHashAlgorithm::Blake3 is available with the blake3 feature.
AvatarHashAlgorithm::Xxh3_128 is available with the xxh3 feature and is
non-cryptographic. Do not use XXH3-128 for adversarial or user-controlled
identifiers unless the application first maps those identifiers through its own
cryptographic boundary.
BLAKE3 Feature Example
[]
= { = "0.10.0", = ["blake3"] }
use ;
let namespace = new?;
let spec = new?;
let svg = render_avatar_svg_with_identity_options?;
assert!;
# Ok::
XXH3-128 Feature Example
[]
= { = "0.10.0", = ["xxh3"] }
use ;
let namespace = new?;
let spec = new?;
let bytes = encode_avatar_with_identity_options?;
assert!;
# Ok::
XXH3-128 is fast and useful for non-adversarial distribution, but it is not a cryptographic hash. Keep SHA-512 or BLAKE3 for adversarial or user-controlled identity inputs.
Example: Raw Image Buffer
use ;
let spec = new?;
let image = render_avatar_for_id?;
assert_eq!;
assert_eq!;
# Ok::
Use raw buffers when the caller wants to composite, inspect pixels, run custom encoding, or integrate with an existing image pipeline.
Handling Untrusted Input
use ;
The crate rejects unsupported sizes and oversized identities. Applications
should still enforce their own routing, authentication, rate limiting, cache
policy, response headers, request body limits, and concurrency limits. A single
maximum-size raster render needs up to MAX_AVATAR_RGBA_BYTES raw RGBA bytes
before encoder overhead, so public services should bound simultaneous large
renders at the API layer.
Caller-Owned Output Cleanup
Encode APIs zeroize internal temporary raster buffers after encoding, but the
returned Vec<u8> belongs to the caller. Render APIs return an RgbaImage
owned by the caller. High-assurance applications that treat avatar output as
sensitive should clear those buffers after use:
use ;
use Zeroize;
let spec = new?;
let options = new;
let mut bytes = encode_avatar_for_id?;
// Send, store, or otherwise consume `bytes`.
bytes.zeroize;
let mut image = render_avatar_for_id?;
// Composite, inspect, or encode `image`.
image.as_mut.zeroize;
# Ok::
Concurrent Render Limits
This crate bounds each individual render, not process-wide memory pressure.
Public services should combine MAX_AVATAR_RGBA_BYTES with their own memory
budget and reject or queue excess work. For example, a Tokio-based API can use
a semaphore around render work:
use Arc;
use ;
use Semaphore;
async
For async web servers, run CPU-heavy rendering on an appropriate blocking worker pool when needed, and keep the semaphore at the service boundary so it accounts for all concurrent requests.
API Reference Summary
Important public entry points:
AvatarSpec::new(width, height, seed) -> Result<AvatarSpec, AvatarSpecError>AvatarIdentity::new(input) -> Result<AvatarIdentity, AvatarIdentityError>AvatarIdentity::new_with_options(options, input) -> Result<AvatarIdentity, AvatarIdentityError>AvatarIdentityOptions::new(namespace, algorithm)AvatarNamespace::new(tenant, style_version) -> Result<AvatarNamespace, AvatarIdentityError>AvatarOptions::new(kind, background)AvatarStyleOptions::new(kind, background, accessory, color, expression, shape)AvatarStyleOptions::from_identity(identity)encode_avatar_for_id(...)encode_avatar_style_for_id(...)encode_avatar_auto_for_id(...)encode_avatar_for_namespace(...)render_avatar_for_id(...)render_avatar_style_for_id(...)render_avatar_auto_for_id(...)render_avatar_for_namespace(...)render_avatar_with_identity_options(...)render_avatar_svg_for_id(...)render_avatar_svg_style_for_id(...)render_avatar_svg_auto_for_id(...)render_avatar_svg_for_namespace(...)render_avatar_svg_with_identity_options(...)
Lower-level identity-specific renderers are available for callers that want direct control over a specific avatar family.
Output Formats
| Format | API value | Notes |
|---|---|---|
| WebP | AvatarOutputFormat::WebP |
Recommended default for modern web delivery. |
| PNG | AvatarOutputFormat::Png |
Lossless and broadly compatible. |
| JPEG | AvatarOutputFormat::Jpeg |
Transparent pixels are composited over white. |
| GIF | AvatarOutputFormat::Gif |
Legacy-compatible single-frame output. |
| SVG | render_avatar_svg_* |
Returns a string rather than raster bytes. |
AVIF and JPEG XL are not exposed because they add dependency or encoder maturity tradeoffs that have not cleared the crate's dependency policy.
Determinism
The output is deterministic for the tuple:
identity hash algorithm + namespace tenant + namespace style version + identity bytes + avatar kind + background + dimensions + seed
This makes the crate suitable for stable CDN-backed avatar URLs and golden regression tests. Namespace hashing uses length-prefixed components, so embedded separator bytes cannot create tenant/style-version ambiguity. The default SHA-512 path keeps the pre-0.7 identity preimage stable; non-default algorithms are domain-separated.
For style-aware rendering, the deterministic tuple also includes
accessory, color, expression, and shape. Existing AvatarOptions
entry points keep those extra layer choices at none, default, default,
and square, so their default visual output is unchanged in 0.10.0.
Some family/layer combinations are deterministic no-ops when the layer has no
sensible anchor for that family.
The renderer uses floating-point geometry internally. The project tests golden fingerprints on the release platform, but it does not yet claim formal bit-identical raster output across every CPU architecture, compiler backend, and optimization mode. Future core-boundary work tracks fixed-point geometry as the path to a stricter cross-platform determinism contract.
The procedural cat renderer seeds its internal RNG from bytes 32..64 of the
identity digest and uses the lower digest bytes for direct visual parameters.
That keeps RNG state separate from directly observed parameter bytes. The
change intentionally updates cat-family golden fingerprints in 0.7.0.
AvatarIdentity equality uses constant-time digest comparison. Rendering and
encoding are not constant-time: shape counts, geometry, encoded size, and SVG
length can vary with identity digest bytes. Applications with strict side
channel requirements should not treat avatar render timing or output size as
secret-preserving signals.
When identity values are sensitive and an API must reduce render-time observability, add the mitigation at the service boundary where request timing is controlled:
use ;
use ;
For public web services, prefer CDN caching and stable cache keys so repeated requests for the same avatar do not repeatedly expose renderer timing. In async servers, use an async timer rather than blocking a runtime worker thread.
Encode APIs clear temporary raster buffers after encoding. Returned Vec<u8>
encoded bytes and RgbaImage render outputs are caller-owned; applications
with strict memory-sanitization requirements should clear those buffers after
use.
Testing And Release Evidence
The repository includes:
- same-input stability tests
- different-input divergence tests
- raster export round-trip tests
- SVG safety and compactness tests
- enum parsing tests
- automatic visual layer derivation tests
- style-aware raster and SVG layer tests
- transparent background checks
- golden visual fingerprint tests
- fuzz harness compilation
cargo denypolicy- RustSec advisory scanning
- reproducible package/build checks
- SBOM generation
- crates.io publish dry run
Run the standard local gate:
Run the fuller release gate:
Provenance
The repository is intended to remain code-generated and asset-free. For a direct statement of how the visuals are produced, see PROVENANCE.md.
Web API And Demo
The crate is focused on reusable rendering code. The public HTTP API and demo website live in the separate hashavatar-api project.
Changelog
See CHANGELOG.md and the release note files for version-by-version details.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)