Slug 1.0.1
dotnet add package Slug --version 1.0.1
NuGet\Install-Package Slug -Version 1.0.1
<PackageReference Include="Slug" Version="1.0.1" />
<PackageVersion Include="Slug" Version="1.0.1" />
<PackageReference Include="Slug" />
paket add Slug --version 1.0.1
#r "nuget: Slug, 1.0.1"
#:package Slug@1.0.1
#addin nuget:?package=Slug&version=1.0.1
#tool nuget:?package=Slug&version=1.0.1
Slug 
by Stan Drapkin
<img src="https://raw.githubusercontent.com/sdrapkin/SecurityDriven.Slug/refs/heads/master/assets/Slug%20256.png" alt="Slug Logo">
16 characters. 16 bytes. One canonical representation.
Slug gives you short, human-friendly IDs like 8k3mPq9xVr2nWz7B with the 16-byte value-type efficiency and native database UUID/Guid storage of System.Guid.
Guid.NewGuid() Slug.NewId()
------------------------------------ ----------------
f47ac10b-58cc-4372-a567-0e02b2c3d479 8k3mPq9xVr2nWz7B
9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d RwjJ5FaMETnVcpYc
109156be-c4fb-41ea-b1b4-efe1671c5836 Wg8vKYFWWhuY8jcQ
6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b Aq9wv7v9SHiAS3Aj
c56a4180-65aa-42ec-a945-5fd21dec0538 HbrnWmcSuYGF1t9V
Slug.Parse("123456789ABCDEFG").Guid Slug.Parse("123456789ABCDEFG")
------------------------------------ ----------------
31323334-3536-3738-3941-424344454647 123456789ABCDEFG
Instead of storing 128 opaque bits and encoding/decoding them on every API, JSON, or URL boundary, Slug stores 16 URL-safe Base57 ASCII characters directly as its 16-byte binary value. The bytes in memory are the UTF-8 string:
Slug (characters): [1 2 3 4] [5 6] [7 8] [9 A] [B C D E F G]
Bytes (hex): 31323334 3536 3738 3941 424344454647
Guid (hex): 31323334 -3536 -3738 -3941 -424344454647
- Half the length of a
Guidstring: 16 double-click-selectable, URL-safe characters (~93.3 bits of entropy; ~50 years at 10,000 IDs/sec before a 1% collision chance, or stronger than an unretriedGuidwith a single DB retry). - Zero-allocation & radically fast: 3× faster generation, 10× to 25× faster parsing, 2× faster hashing, and zero-copy UTF-8 serialization via
AsUtf8(). - Drop-in
UUID/Guidstorage: Losslessly converts to a big-endianSystem.Guid(id.Guid) for nativeuuid/uniqueidentifier/BINARY(16)database columns, with zero heap string allocations in .NET.
Installation
Requires .NET 10+
dotnet add package Slug
Then:
using SecurityDriven;
Quick Start
// Generate a cryptographically random 16-character Base57 slug
Slug id = Slug.NewId(); // e.g., "8k3mPq9xVr2nWz7B"
// Store natively in a Guid / PostgreSQL uuid / SQL Server uniqueidentifier column
Guid dbId = id.Guid;
Slug fromDb = Slug.FromGuid(dbId);
// Zero-copy 16-byte UTF-8 view for JSON, HTTP, or binary protocols
ReadOnlySpan<byte> utf8 = id.AsUtf8();
// Very fast validation & parsing (UTF-16 or UTF-8, 0 B allocated)
if (Slug.TryParse("123456789ABCDEFG", out Slug parsed))
{
Console.WriteLine(parsed);
}
Design Philosophy: Representation Isomorphism
Most identifier implementations follow one of two approaches:
Binary-canonical identifiers (e.g. System.Guid) store an opaque binary value, typically 128 bits in 16 bytes. When a textual representation is required, the value must be encoded into hexadecimal, Base32, Base58, Base62, Base64/Url or similar textual format. Parsing text to bytes reverses that transformation.
String-canonical identifiers (e.g. Nanoid) generate human-friendly identifiers directly as strings. They exist as strings, tend to avoid any text-to-binary conversion, but each identifier remains a separately allocated heap object in runtimes such as .NET.
Slug takes a different approach by making the canonical binary representation identical to the canonical textual representation:
| Property | Slug |
|---|---|
| Text length | 16 characters |
| Binary size | 16 bytes |
| Alphabet | Base57 |
| Maximum entropy | ~93.33 bits |
| In-memory representation | 16 ASCII bytes |
| Canonical text representation | The same 16 bytes in UTF-8 |
| Parsing | SIMD-accelerated validation |
| UTF-8 formatting | Direct byte access / store |
| Managed string allocation | Only when a string is explicitly requested<br>(and faster than Guid.ToString()) |
With Slug there is no separate binary value that needs to be encoded into Base57 every time it crosses an API or serialization boundary. The identifier is already represented by its canonical characters.
Why This Matters
In a conventional binary-canonical implementation, the conceptual data flow is:
128-bit binary identifier
|
v
Hex / Base32 / Base58 / Base62 / Base64 text encoding
|
v
Text representation
|
v
JSON / URL
Parsing performs the inverse radix conversion.
With Slug:
Random entropy (128 bits)
|
v
Base57 generation of 16 ASCII bytes (drops entropy to ~93 bits)
|
|
+-----+------+
| |
v v
16-byte UTF-8 / JSON / URL
value type
The 16 generated ASCII bytes are the identifier itself.
This has several practical consequences:
- Compact value semantics: A
Slugoccupies 16 bytes inline in arrays, structs, and collections without a separate string object or object reference. - No
Base57formatting conversion: The canonical UTF-8 representation is already present in memory. - Fast parsing: Parsing validates the input alphabet in a single pass instead of reconstructing a 128-bit integer from
Base57digits. - Zero-copy UTF-8 serialization: JSON writers and network pipelines can read the underlying 16 bytes directly.
- Consistent ordinal comparison: Values compare in ordinal ASCII order without allocating strings.
In .NET, a 16-character string occupies 56 bytes on a typical 64-bit CoreCLR runtime (object header, method table pointer, length field, UTF-16 characters, and alignment), not even counting the 8-byte reference held by a containing collection or field. A Slug occupies 16 bytes directly.
Slug deliberately trades excess theoretical entropy for representation isomorphism, rather than incurring memory and transcoding overhead on every boundary to preserve bits an application may not need.
Why Base57?
Slug uses the following case-sensitive, ASCII-sorted alphabet:
123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz
It contains 57 characters, excluding 5 visually ambiguous characters:
I(uppercase i)l(lowercase L)0(zero)O(uppercase o)o(lowercase o)
Because the alphabet contains only unreserved ASCII alphanumeric characters, identifiers are URL-, path-, and filename-safe without percent-encoding, and select cleanly on double-click.
A 16-character Base57 identifier has:
$$57^{16} \approx 1.2416 \times 10^{28}$$
possible values. Its Shannon capacity is:
$$H = 16 \times \log_2(57) \approx 93.32624 \text{ bits}$$
This retains ~73% of the theoretical capacity of a 128-bit binary value within the same 16-byte footprint, trading ~34.67 bits of capacity to eliminate binary-to-text conversion entirely.
Uniqueness and Collision Probability
Slug generates identifiers using .NET's cryptographically secure random number generator (RandomNumberGenerator).
NewId() consumes 128 bits (two 64-bit words) of CSPRNG output and extracts 8 Base57 digits from each 64-bit word using multiply-high radix extraction (Math.BigMul, based on Daniel Lemire's fast-range reduction), avoiding 64-bit division/modulo entirely. Rejection sampling is intentionally omitted for branchless, constant-time execution.
Mapping $2^{64}$ uniformly onto $57^8 = 111,429,157,112,001$ outcomes means each 8-character half appears either $165,546$ or $165,547$ times. Across the full 16-character ID, the resulting bias is negligible:
- Max relative probability difference: $\approx 1.21 \times 10^{-5}$ (~0.0012%)
- Total variation distance from uniform: $1.40 \times 10^{-6}$ ($\approx 2^{-19.45}$)
- Shannon entropy loss: $7.32 \times 10^{-12}\text{ bits}$
- Collision probability increase: $+1.01 \times 10^{-11}$ (1 in 100 billion)
Birthday-Bound Estimates & WolframAlpha Calculators
Assuming independent generation in a single global namespace, the probability of at least 1 collision after generating $n$ identifiers is:
$$P(\text{collision}) \approx 1 - \exp\left(-\frac{n(n - 1)}{2 \times 57^{16}}\right)$$
Solving for the number of identifiers $n$ - or the elapsed time $t$ at a constant Slug generation rate $R$ (in IDs/second) - before reaching a target collision probability $P$:
$$n \approx \sqrt{2 \cdot A^N \cdot \ln\left(\frac{1}{1 - P}\right)}, \qquad t = \frac{n}{R} \text{ seconds} \quad (\text{alphabet } A = 57, N = 16)$$
The table below shows how many Slug values can be created, and how long a system can generate them continuously at 10,000 IDs/second, before reaching a given collision probability $P$ (click any WolframAlpha link to customize $R$ or $P$):
| Target collision probability ($P$) | Safe Slug count ($n$) |
Time at 10,000 IDs/sec | Interactive calculator |
|---|---|---|---|
| $10^{-9}$ (1 in 1 billion) | ~4.98 billion | ~5.8 days | WolframAlpha |
| $10^{-6}$ (1 in 1 million) | ~158 billion | ~182 days | WolframAlpha |
| 0.01% ($10^{-4}$) | ~1.58 trillion | ~5.0 years | WolframAlpha |
| 1% ($10^{-2}$) | ~15.8 trillion | ~50 years | WolframAlpha |
| 50% ($0.5$) | ~131 trillion | ~416 years | WolframAlpha |
For smaller batches in a single namespace:
| Generated identifiers ($n$) | Approximate collision probability |
|---|---|
| 1 million | $4.03 \times 10^{-17}$ |
| 1 billion | $4.03 \times 10^{-11}$ |
| 100 billion | $4.03 \times 10^{-7}$ |
| 1 trillion | $4.03 \times 10^{-5}$ |
Uniqueness remains probabilistic rather than guaranteed; systems requiring strict uniqueness should enforce a database unique constraint, and check for collisions against the pre-existing Slug set.
Let $M = 57^{16}$ be the total
Slugkeyspace. When inserting into a uniqueness-enforcing store, adding a single retry (regenerating a newSlugonce on collision) shifts the collision-failure bound from $M^{1/2}$ (~93.33/2=46.7bits) to $M^{2/3}$ (~93.33*2/3=62.2bits), exceeding the unretried birthday bound ofGuid.NewGuid()(61bits).
Security note:
Slugis an identifier, not an authentication token or capability secret.<br/> Access control must not rely solely on possession of an identifier.
Generation and Performance Design
Buffered thread-local CSPRNG
NewId() fills a thread-local buffer of 128 EntropyPair values (2 KB per active thread) via RandomNumberGenerator.Fill, amortizing OS CSPRNG calls across 128 generated IDs with zero cross-thread contention and zero per-call heap allocations after thread initialization.
SIMD-accelerated validation and parsing
TryParse validates all 16 characters in parallel using 128-bit hardware intrinsics (Vector128<byte>) and two nibble-classification lookup tables via Vector128.ShuffleNative (PSHUFB on x86-64, TBL on ARM64):
- Classifies all 16 bytes simultaneously without per-character branches.
- Rejects non-ASCII UTF-16 code units in a single instruction using signed saturating narrowing (
Vector128.NarrowWithSaturation→PACKSSWB/SQXTN). - Supports both
ReadOnlySpan<char>andReadOnlySpan<byte>directly.
Allocation-free formatting and hardware-accelerated hashing
- In-memory layout:
Slugstores twoulongfields in native memory order, enabling RyuJIT 2-register scalar promotion while keeping the 16-byte memory image identical to the 16 ASCII bytes on all CPU architectures. - UTF-8:
AsUtf8()exposes a zero-copyReadOnlySpan<byte>over the struct's memory;CopyTo(Span<byte>)andTryFormat(Span<byte>, ...)perform a single 128-bit vector store. - UTF-16:
CopyTo(Span<char>),TryFormat(Span<char>, ...), andToString()widen the 16 ASCII bytes into 16 UTF-16 chars usingVector256.WidenLoweron AVX2+ CPUs (falling back toVector128.Widenon ARM64 NEON and SSE2).ToString()usesstring.Createwhen a managedstringis explicitly needed. - Dictionary hashing:
GetHashCode()computes a fast, hardware-accelerated CRC32C (BitOperations.Crc32C) over the two 64-bit halves. Note that this hash is deterministic rather than randomly seeded per process; if inserting large volumes of untrustedSlugvalues into a dictionary or hash set, supply a custom randomizedIEqualityComparer<Slug>if HashDoS resistance is required.Slug'sGetHashCode()is ~2x faster thanGuid'sGetHashCode().
Value-type and framework integration
Slug is a readonly struct implementing:
IEquatable<Slug>,IComparable<Slug>,IComparableIComparisonOperators<Slug, Slug, bool>(ordinal ASCII byte order)IMinMaxValue<Slug>(MinValue="1111111111111111",MaxValue="zzzzzzzzzzzzzzzz")IParsable<Slug>,ISpanParsable<Slug>,IUtf8SpanParsable<Slug>IFormattable,ISpanFormattable,IUtf8SpanFormattableJsonConverter<Slug>(SlugJsonConverter) andTypeConverter(SlugTypeConverter), enabling out-of-the-box ASP.NET Core Minimal API / MVC route and query binding,System.Text.Jsonvalues and dictionary keys, andIConfigurationbinding
Benchmarks
Measured with BenchmarkDotNet v0.15.1 on x86-64 (.NET 11.0, RyuJIT AVX2):
| Operation | Slug |
Guid<br/>(or reference) |
Speedup | Allocated<br/>(Slug vs. Guid or ref) |
|---|---|---|---|---|
Generate ID (NewId() vs. Guid.NewGuid()) |
32.85 ns | 102.71 ns | 3.13× | 0 B vs. 0 B |
Generate + ToString() ("D" / "N") |
43.00 ns | 124.39 ns / 124.84 ns | 2.89× | 56 B vs. 96 B / 88 B |
Generate + ToString() (vs. RNG.GetString) |
43.00 ns | 262.44 ns | 6.10× | 56 B vs. 56 B |
Isolated ToString() ("D" / "N") |
14.64 ns | 19.53 ns / 17.17 ns | 1.33× / 1.17× | 56 B vs. 96 B / 88 B |
Format UTF-8 (TryFormat(Span<byte>)) |
2.48 ns | 3.86 ns | 1.56× | 0 B vs. 0 B |
Parse UTF-16 (TryParse "D" / "N") |
2.98 ns | 33.50 ns / 29.52 ns | 11.2× / 9.9× | 0 B vs. 0 B |
Parse UTF-8 (TryParse vs. Utf8Parser "D" / "N") |
1.89 ns | 48.56 ns / 41.56 ns | 25.7× / 22.0× | 0 B vs. 0 B |
GetHashCode() (1,024 distinct IDs) |
810.7 ns | 1,464.0 ns | 1.81× | 0 B vs. 0 B |
Sort (Span.Sort(), 10,000 IDs) |
766.4 µs | 1,058.0 µs | 1.38× | 0 B vs. 0 B |
Guid carrier interop (slug.Guid / FromGuid) |
1.36 ns / 2.05 ns | — | — | 0 B |
Notes:
Slug.NewId()achieves its 3.1× advantage overGuid.NewGuid()by amortizingRandomNumberGenerator.Fillacross a 2 KB thread-local buffer (128 IDs per OS CSPRNG call).- The 10× to 25× parsing speedup comes directly from representation isomorphism:<br/>
Slug.TryParsevalidates 16 bytes in a single pass rather than decoding hexadecimal digits into a 128-bit binary structure. Slug.AsUtf8()is even faster thanTryFormat(Span<byte>)because it returns a zero-copyReadOnlySpan<byte>directly over the struct's memory.
Comparison With Common Identifier Approaches
Slug optimizes a specific point in the identifier design space rather than replacing every format:
| Approach | In-memory size | Text length | Main characteristic |
|---|---|---|---|
| UUIDv4 | 16 bytes | 36 | 122 random bits; RFC 9562 standard |
| FastGuid | 16 bytes | 36 or 22 | Fast, Base64Url optional, 128-bit entropy |
| MsSqlGuid/PgSqlGuid | 16 bytes | 36 | Time-sortable, high-precision, 64-bit entropy |
| UUIDv7 | 16 bytes | 36 | Time-sortable RFC 9562 UUID, 20 to 74 random bits |
| ULID | 16 bytes | 26 | Time-sortable, Base32, 80-bit entropy |
| Base58 / Base62 UUID | 16 bytes | 22 | Preserves all 128 bits; requires radix conversion |
| Nano ID (default) | Heap string |
21 | 126-bit random string identifier |
Slug |
16 bytes | 16 | 93.33-bit inline, text-canonical value type |
When to Use Slug vs. Guid / FastGuid
Slug is designed to complement Guid / FastGuid, not replace them. Most real-world systems benefit from using both.
- Choose
Slugwhere identifiers are human-facing and backed by an authoritative unique constraint. - Choose
Guid/FastGuidwhere raw 128-bit entropy, offline generation, or time-ordered inserts matter more.
Remember: every
Slugis aGuid, and your database layer only seesGuids, even when they'reSlugs.
Use Slug when… |
Use Guid / FastGuid / UUIDv7 when… |
|---|---|
| IDs appear in URLs, APIs, emails, invoices, or support tickets where humans are expected to interact with the ID-containing text, and shortness and easy copy-paste matter | IDs are internal or machine-only (correlation IDs, trace spans, message/event IDs, idempotency keys) |
An authoritative database unique index can verify uniqueness on insert (and the app-layer can regenerate a Slug on the rare collision) |
IDs are generated offline, on untrusted clients, or across uncoordinated shards without a central uniqueness check |
You want 16-byte value-type / GUID column efficiency without paying for heap string allocations or constant BaseX text↔binary transcoding |
You need 122-128 bits of unretried/offline collision resistance across massive append-only streams |
| Random distribution is acceptable for the data store's insert rate | You need time-sortable primary keys (MsSqlGuid/PgSqlGuid/UUIDv7) for B-tree index locality on high-write tables |
Example: Using Both in the Same System
Consider a typical e-commerce or SaaS backend:
- Use
Slugfor customer- and API-facing entities:Order.Id(/orders/8k3mPq9xVr2nWz7B) : printed on receipts, read aloud to customer support, and passed in all API calls and backend logs.Invoice.Id,Project.Id,ShareLink.Id: short, URL-safe, stored natively in 16-byteUUID/BINARY(16)columns, with a database unique constraint (and at most a single retry on insert).
- Use
Guid/FastGuid(orMsSqlGuid/PgSqlGuid/UUIDv7) for internal plumbing:OrderPlacedEvent.EventIdand outbox message IDs: high-volume, append-only, never shown to end users.AuditLog.IdandTelemetrySpan.Id: time-ordered inserts benefit fromUUIDv7/MsSqlGuid/PgSqlGuidindex locality.CheckoutRequest.IdempotencyKey: client-generated offline with no central coordination.
public sealed record Order(
Slug Id, // Human-facing: /orders/8k3mPq9xVr2nWz7B (DB unique index)
Slug CustomerId, // Human-facing: /customers/RwjJ5FaMETnVcpYc
Guid IdempotencyKey, // Client-generated, no central uniqueness check
Guid CorrelationId); // Internal tracing / event pipeline
Slug Usage
Generate and parse
Slug id = Slug.NewId();
if (Slug.TryParse("123456789ABCDEFG", out Slug parsed))
{
Console.WriteLine(parsed);
}
// Throws FormatException on invalid length or non-Base57 characters
Slug strict = Slug.Parse("abcdabcdabcdabcd"u8);
Work directly with UTF-8
Slug id = Slug.NewId();
// Zero-copy 16-byte UTF-8 span (valid for the lifetime of the Slug variable)
ReadOnlySpan<byte> utf8 = id.AsUtf8();
// Copy into a caller-owned buffer
Span<byte> buffer = stackalloc byte[Slug.Length];
id.CopyTo(buffer);
// or: id.TryFormat(buffer, out int bytesWritten);
JSON serialization
The built-in SlugJsonConverter handles both string values and JSON object property names (Dictionary<Slug, TValue>) without heap allocations, including multi-segment ReadOnlySequence<byte> buffers and \uXXXX-escaped JSON inputs:
var map = new Dictionary<Slug, string>
{
[Slug.NewId()] = "First",
[Slug.NewId()] = "Second"
};
string json = JsonSerializer.Serialize(map);
// json: {"Q9CiRBFwbMgsBxKJ":"First","LrJVYCs7S4TExwZm":"Second"}
var restored = JsonSerializer.Deserialize<Dictionary<Slug, string>>(json);
Deterministic construction (FromEntropy)
FromEntropy() deterministically maps 16 bytes (128 bits) of well-distributed entropy - such as a truncated cryptographic hash or seeded PRNG output - into a Slug:
var digest = SHA256.HashData("tenant:42/item:79"u8);
Slug deterministicId = Slug.FromEntropy(digest[..Slug.Length]);
Important:
FromEntropyexpects uniformly distributed input bytes (do not pass zero-padded integers directly). The mapping is lossy (128 bits → ~93.33 bits) and is neither reversible nor a cryptographic hash function on its own.
API Overview
| Member | Purpose |
|---|---|
Slug.NewId() |
Generate a cryptographically random Slug |
Slug.FromEntropy(ReadOnlySpan<byte>) |
Deterministically map 16 uniform entropy bytes into a Slug |
new Slug(ReadOnlySpan<byte>) / new Slug(Guid) |
Construct a Slug from 16 valid Base57 ASCII bytes or a Base57-backed Guid |
Slug.Parse(...) / TryParse(...) |
Parse from string, ReadOnlySpan<char>, or ReadOnlySpan<byte> |
Slug.FromGuid(Guid) / TryFromGuid(...) |
Wrap a Base57-backed Guid after validating all 16 bytes (also available via explicit casts) |
Slug.IsValid(...) |
Validate a Guid, string?, ReadOnlySpan<char>, or ReadOnlySpan<byte> |
id.AsUtf8() |
Zero-copy 16-byte ReadOnlySpan<byte> view |
id.CopyTo(Span<byte>) / CopyTo(Span<char>) |
Copy the 16 ASCII bytes or UTF-16 characters directly into a destination span |
id.TryFormat(...) |
Format into a Span<char> or Span<byte> (supports "", "G", "g") |
id.ToString() |
Allocate and return the 16-character string |
id.Guid |
Access the cross-architecture 16-byte System.Guid storage carrier (new Guid(id.AsUtf8(), bigEndian: true)) |
id.IsEmpty |
true if the value is default(Slug) |
Slug.MinValue / MaxValue |
Minimum ("1111111111111111") and maximum ("zzzzzzzzzzzzzzzz") valid Slug values |
Slug.Length / Radix / Alphabet / Utf8Alphabet |
Format constants (16, 57, Base57 alphabet as string and ReadOnlySpan<byte>) |
Database Storage and Guid Interoperability
Case sensitivity and database collations
Slug is case-sensitive ('A' != 'a'). If stored as text in a relational database (CHAR(16) / VARCHAR(16)), always use a binary or case-sensitive collation (for example, Latin1_General_100_BIN2 in SQL Server, C in PostgreSQL, or utf8mb4_bin in MySQL). Using a case-insensitive collation (_CI_AS) collapses the effective keyspace from $57^{16}$ (~93.3 bits) down to $34^{16}$ (~81.4 bits) and causes false duplicate-key collisions. Alternatively and preferably, store as a native GUID/UUID/UNIQUEIDENTIFIER column, or store the raw 16 bytes in BINARY(16) or BYTEA or RAW(16).
System.Guid carrier caveats
Slug.Guid exposes a cross-architecture 16-byte System.Guid storage carrier equivalent to new Guid(slug.AsUtf8(), bigEndian: true). This Guid is a raw binary carrier, not an RFC 9562 UUID:
id.Guid.ToString()formats raw ASCII byte values as hexadecimal UUID digits, not the 16-character slug.Guid.NewGuid()almost never contains 16 valid Base57 bytes and will failSlug.FromGuid.- UUID version/variant nibbles contain raw ASCII bits, which strict external RFC 9562 UUID validators will reject.
Treat .Guid strictly as an in-process or opaque binary storage carrier; exchange canonical 16-character text (or BINARY(16)/UUID) across external system boundaries.
EF Core and Dapper Integration
Because Slug converts losslessly to and from System.Guid, you can keep Slug on your domain models while storing native UNIQUEIDENTIFIER / UUID values in the database.
Entity Framework Core
Register a single ValueConverter<Slug, Guid> in ConfigureConventions - EF Core applies it automatically to all Slug and Slug? properties across your model and translates LINQ predicates (Where(o => o.Id == id)) into parameterized Guid / UUID queries:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SecurityDriven;
public sealed class SlugToGuidConverter()
: ValueConverter<Slug, Guid>(s => s.Guid, g => Slug.FromGuid(g));
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.Properties<Slug>().HaveConversion<SlugToGuidConverter>();
}
}
Dapper
Register a SqlMapper.TypeHandler<Slug> once at application startup (handles both Slug and Slug? parameters and result columns):
using System.Data;
using Dapper;
using SecurityDriven;
public sealed class SlugTypeHandler : SqlMapper.TypeHandler<Slug>
{
public override void SetValue(IDbDataParameter parameter, Slug value)
{
parameter.DbType = DbType.Guid;
parameter.Value = value.Guid;
}
public override Slug Parse(object value) => value switch
{
Guid g => Slug.FromGuid(g),
byte[] b => new Slug(b),
string s => Slug.Parse(s),
_ => throw new DataException($"Cannot convert {value.GetType().Name} to {nameof(Slug)}.")
};
}
// Call once at startup:
SqlMapper.AddTypeHandler(new SlugTypeHandler());
Querying UNIQUEIDENTIFIER / UUID Columns by Slug in Ad-Hoc SQL
When you store Slug values in native UNIQUEIDENTIFIER, UUID, or RAW(16) columns, your application code works with Slug seamlessly - but manual SQL queries (debugging, support lookups, data fixes) cannot write WHERE Id = '8k3mPq9xVr2nWz7B' directly, and database tools display hex UUIDs rather than readable Slugs.
Since Slug.Guid uses big-endian (RFC 9562) byte order ("123456789ABCDEFG" → 31323334-3536-3738-3941-424344454647), you can convert a 16-character Slug literal into a native database key inline or via a small deterministic helper function - keeping your WHERE clauses index-friendly (Index Seek / Unique Scan, since the conversion runs on the literal rather than the column).
PostgreSQL (uuid)
PostgreSQL uuid uses big-endian byte order, matching Slug.Guid directly:
-- Inline (no schema objects required)
SELECT * FROM orders
WHERE id = encode(convert_to('123456789ABCDEFG', 'UTF8'), 'hex')::uuid;
-- Reusable helper functions
CREATE OR REPLACE FUNCTION slug_to_uuid(slug text)
RETURNS uuid
LANGUAGE sql
IMMUTABLE
STRICT
PARALLEL SAFE
AS $$
SELECT encode(convert_to(slug, 'UTF8'), 'hex')::uuid;
$$;
CREATE OR REPLACE FUNCTION uuid_to_slug(id uuid)
RETURNS text
LANGUAGE sql
IMMUTABLE
STRICT
PARALLEL SAFE
AS $$
SELECT convert_from(decode(replace(id::text, '-', ''), 'hex'), 'UTF8');
$$;
-- Usage:
-- slug_to_uuid('123456789ABCDEFG') -> 31323334-3536-3738-3941-424344454647
SELECT uuid_to_slug(id) AS slug, *
FROM orders
WHERE id = slug_to_uuid('123456789ABCDEFG');
SQL Server (UNIQUEIDENTIFIER)
SQL Server stores UNIQUEIDENTIFIER in mixed-endian layout (the first 4-, 2-, and 2-byte groups are little-endian, matching Microsoft.Data.SqlClient's System.Guid wire format). Converting an ASCII CHAR(16) slug to UNIQUEIDENTIFIER therefore reverses those first three groups before casting:
-- Inline (no schema objects required)
DECLARE @slug CHAR(16) = '123456789ABCDEFG';
SELECT * FROM Orders
WHERE Id = CAST(
CAST(
REVERSE(SUBSTRING(@slug, 1, 4)) +
REVERSE(SUBSTRING(@slug, 5, 2)) +
REVERSE(SUBSTRING(@slug, 7, 2)) +
SUBSTRING(@slug, 9, 8)
AS BINARY(16)
) AS UNIQUEIDENTIFIER
);
-- Reusable helper functions (use CHAR(16), not NCHAR(16), so ASCII is 1 byte per char)
CREATE OR ALTER FUNCTION dbo.SlugToGuid(@slug CHAR(16))
RETURNS UNIQUEIDENTIFIER
WITH SCHEMABINDING
AS
BEGIN
RETURN CAST(
CAST(
REVERSE(SUBSTRING(@slug, 1, 4)) +
REVERSE(SUBSTRING(@slug, 5, 2)) +
REVERSE(SUBSTRING(@slug, 7, 2)) +
SUBSTRING(@slug, 9, 8)
AS BINARY(16)
) AS UNIQUEIDENTIFIER
);
END;
GO
CREATE OR ALTER FUNCTION dbo.GuidToSlug(@id UNIQUEIDENTIFIER)
RETURNS CHAR(16)
WITH SCHEMABINDING
AS
BEGIN
DECLARE @s CHAR(16) = CAST(CAST(@id AS BINARY(16)) AS CHAR(16));
RETURN REVERSE(SUBSTRING(@s, 1, 4)) +
REVERSE(SUBSTRING(@s, 5, 2)) +
REVERSE(SUBSTRING(@s, 7, 2)) +
SUBSTRING(@s, 9, 8);
END;
GO
-- Usage:
-- dbo.SlugToGuid('123456789ABCDEFG') -> 31323334-3536-3738-3941-424344454647
SELECT dbo.GuidToSlug(Id) AS Slug, *
FROM Orders
WHERE Id = dbo.SlugToGuid('123456789ABCDEFG');
Oracle (RAW(16))
When storing raw Slug bytes (slug.AsUtf8()) directly in a RAW(16) column, UTL_RAW.CAST_TO_RAW / UTL_RAW.CAST_TO_VARCHAR2 map 1:1 with no byte-swapping:
-- Inline (uses Index Unique/Range Scan)
SELECT UTL_RAW.CAST_TO_VARCHAR2(id) AS slug, o.*
FROM orders o
WHERE id = UTL_RAW.CAST_TO_RAW('123456789ABCDEFG');
-- Reusable helper function
CREATE OR REPLACE FUNCTION slug_to_raw(p_slug IN VARCHAR2)
RETURN RAW
DETERMINISTIC
IS
BEGIN
IF p_slug IS NULL THEN
RETURN NULL;
END IF;
IF LENGTHB(p_slug) != 16 THEN
RAISE_APPLICATION_ERROR(-20001, 'Slug must be exactly 16 ASCII bytes.');
END IF;
RETURN UTL_RAW.CAST_TO_RAW(p_slug);
END;
/
-- Usage:
SELECT * FROM orders WHERE id = slug_to_raw('123456789ABCDEFG');
ODP.NET note: If you bind
slug.Guid(aSystem.Guid) to OracleRAW(16)using ODP.NET's defaultGuidmapping rather than rawslug.AsUtf8()bytes, ODP.NET writesGuid.ToByteArray()(mixed-endian), in which case swap the first 4-, 2-, and 2-byte groups just like SQL Server above.
Cross-Language Interoperability
Because Slug is simply 16 Base57 ASCII bytes - and Slug.Guid uses big-endian (RFC 9562) byte order - any language can generate, validate, and exchange Slug values over text, BINARY(16), or UUID columns using only its standard library.
Validation Regex (OpenAPI / JSON Schema / .NET)
| Dialect / Context | Pattern | Notes |
|---|---|---|
| ECMA-262 (OpenAPI, JSON Schema, JS/TS) | ^[1-9A-HJ-NP-Za-km-np-z]{16}$ |
\A/\z are invalid in ECMA-262; $ does not match a trailing newline without /m. |
.NET Regex (also PCRE, Ruby, Python) |
\A[1-9A-HJ-NP-Za-km-np-z]{16}\z |
Use \z instead of $ (or \Z), which in .NET matches before a trailing \n. |
In .NET runtime code, prefer
Slug.IsValid(...)orSlug.TryParse(...)overRegex- they validate all 16 characters in a single allocation-free pass.
OpenAPI 3.x / JSON Schema snippet:
Slug:
type: string
minLength: 16
maxLength: 16
pattern: "^[1-9A-HJ-NP-Za-km-np-z]{16}$"
example: "8k3mPq9xVr2nWz7B"
<details> <summary><b>Minimal <code>Python 3</code> reference implementation (standard lib only) - click</b></summary>
import secrets
import uuid
LENGTH = 16
ALPHABET = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz"
ALPHABET_SET = frozenset(ALPHABET)
RADIX = len(ALPHABET) # 57
RADIX8 = RADIX ** 8 # 57^8
KEYSPACE = RADIX ** LENGTH # 57^16
def new_slug() -> bytes:
n = secrets.randbelow(KEYSPACE)
out = bytearray(LENGTH)
for i in range(LENGTH - 1, -1, -1):
n, rem = divmod(n, RADIX)
out[i] = ALPHABET[rem]
return bytes(out)
def is_valid_slug(data: bytes) -> bool:
return len(data) == LENGTH and all(b in ALPHABET_SET for b in data)
def from_entropy(data: bytes) -> bytes:
if len(data) != LENGTH:
raise ValueError("Expected exactly 16 bytes of entropy")
out = bytearray(LENGTH)
for half in (0, 8):
v = (int.from_bytes(data[half:half + 8], "little") * RADIX8) >> 64
for i in range(half, half + 8):
v, rem = divmod(v, RADIX)
out[i] = ALPHABET[rem]
return bytes(out)
# Test vectors
assert from_entropy(bytes(range(1, 17))) == b"SiJK8tm2xEsy6pZ4"
assert from_entropy(bytes(16)) == b"1111111111111111"
assert from_entropy(b"\xff" * 16) == b"zzzzzzzzzzzzzzzz"
# Generate and convert to/from a big-endian UUID (matches .NET's Slug.Guid)
s = new_slug()
u = uuid.UUID(bytes=s)
assert u.bytes == s and is_valid_slug(u.bytes)
# Cross-language test vector
assert str(uuid.UUID(bytes=b"123456789ABCDEFG")) == "31323334-3536-3738-3941-424344454647"
for _ in range(4):
s = new_slug()
print(s, s.decode("ascii"), uuid.UUID(bytes=s))
# b'qFLBrT9MRSxttUXm' qFLBrT9MRSxttUXm 71464c42-7254-394d-5253-78747455586d
# b'D4hGWSCgNKTWyiZf' D4hGWSCgNKTWyiZf 44346847-5753-4367-4e4b-545779695a66
# b'SKqAtBT6i5fuq85y' SKqAtBT6i5fuq85y 534b7141-7442-5436-6935-667571383579
# b'4u6KyfsYnA67MKgn' 4u6KyfsYnA67MKgn 3475364b-7966-7359-6e41-36374d4b676e
</details>
Default Value Semantics
default(Slug) represents an uninitialized value, not an "empty slug":
Slug uninitialized = default;
Console.WriteLine(uninitialized.IsEmpty); // True
Because every valid Slug is 16 Base57 characters, an uninitialized default(Slug) cannot round-trip as text. Calling ToString(), TryFormat(), CopyTo(), AsUtf8(), or serializing default(Slug) to JSON throws InvalidOperationException rather than silently emitting an invalid empty string. Use Slug? when a value is optional.
Design Trade-offs and Non-Goals
- Not 128-bit: The ~93.33-bit capacity is intentional. Use FastGuid/UUIDv4 when 122+ bits are required.
- Not time-sortable: Uniform randomness trades away B-tree insertion locality; use MsSqlGuid/PgSqlGuid/UUIDv7 for time-ordered primary keys.
- Case-sensitive: Systems that fold case (case-insensitive URLs, DNS labels,
_CIdatabase columns) must not normalizeSlugvalues. - Not a general-purpose Base57 codec:
Slugis a fixed 16-byte identifier type, not an arbitrary-length byte encoder. - Not an authorization token: Never rely on identifier unguessability alone for access control.
Slug: 16 characters. 16 bytes. One canonical representation.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.1 | 60 | 12/3/2026 |
Initial v1.0 release of Slug for .NET 10+.
Highlights:
- 16-character, 16-byte Base57 value-type identifier (~93.33 bits of entropy) whose in-memory bytes are the canonical UTF-8 string.
- Fast CSPRNG generation via Slug.NewId() (buffered thread-local CSPRNG with branchless multiply-high extraction) and deterministic Slug.FromEntropy().
- SIMD-accelerated Parse, TryParse, and IsValid for string, UTF-16 spans, UTF-8 spans, and Guid.
- Zero-copy AsUtf8(), allocation-free CopyTo / TryFormat (UTF-8 and UTF-16), and hardware-accelerated CRC32C GetHashCode().
- Lossless big-endian System.Guid carrier interop (id.Guid, Slug.FromGuid, Slug.TryFromGuid, explicit casts) for native UUID / UNIQUEIDENTIFIER / BINARY(16) database storage.
- Full modern .NET integration: ISpanParsable, IUtf8SpanParsable, ISpanFormattable, IUtf8SpanFormattable, IComparisonOperators, IMinMaxValue, SlugJsonConverter (values and dictionary keys), and SlugTypeConverter (ASP.NET Core and IConfiguration binding).