/foundationdb-dotnet-skills:snowbank-slices-and-buffersfrom foundationdb-dotnet-skills
Teaches correct usage of Slice, SliceReader, SliceWriter, and SliceOwner for binary data in FoundationDB .NET client / SnowBank.Core. Covers Nil vs Empty, view semantics, and encoding conversions.
Ships in foundationdb-dotnet-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Slice is the workhorse for binary data in this codebase. It is a readonly struct (in namespace System) that wraps a segment of a byte[] — its three fields are Array (the backing array, possibly null), Offset, and Count. It predates Span<T> and is the logical equivalent of ReadOnlyMemory<byte>, but with a large library of helpers for turning bytes into and out of real-world types. Keys and values in the FoundationDB binding are Slices.
Two things to internalize first: (1) a
Sliceis a view, not a copy — it shares the backing array. (2)Slice.Nil(no array) andSlice.Empty(zero-length array) are different and the distinction is load-bearing. Both are covered below.
For the Span-first equivalents (SpanReader/SpanWriter, ISpanEncodable) read references/span-readers-writers.md; for pooled buffer-building (ISliceBufferWriter, SlicePool, ValueBuffer<T>, allocators) read references/buffers-and-pooling.md.
Slice.Nil | Slice.Empty | |
|---|---|---|
| backing array | none (null-like) | a zero-length array |
IsNull | true | false |
IsEmpty | false | true |
IsNullOrEmpty | true | true |
IsPresent | false | true |
GetBytes() | returns null | returns an empty array |
ToStringUtf8() | returns null | returns "" |
== | Nil != Empty | distinct |
CompareTo | Nil and Empty compare equal (both sort first) |
tr.GetAsync(key) returns Slice.Nil for a missing key, so the canonical "does it exist?" check is value.IsNull (or IsNullOrEmpty if an empty value also counts as absent). Use Nil to mean absent and Empty to mean present but zero-length.
var v = await tr.GetAsync(key);
if (v.IsNull) { /* key does not exist */ }
Constructing a Slice from a byte[] does not copy; the Slice references the array, so mutations to the array are visible through the slice (and its .Span). When you need an independent owner, copy:
byte[] buf = ...;
var view = buf.AsSlice(); // shares buf — buf[i] = x is visible through view
byte[] mine = view.ToArray(); // defensive copy
buf[0] = 0xFF; // changes `view`, not `mine`
// from arrays / spans
byte[] b = ...;
b.AsSlice(); b.AsSlice(offset, count);
new ArraySegment<byte>(b, o, n).AsSlice();
Slice.FromBytes("abc"u8); // copies a ReadOnlySpan<byte>
// from text
Slice.FromStringUtf8("héllo"); Slice.FromString("héllo"); // UTF-8
Slice.FromStringAscii("ABC"); // ASCII only — lossy/throws on chars > 0x7F
// well-known
Slice.Empty; Slice.Nil; Slice.Zero(16); // 16 zero bytes
// guids / uuids / hex
Slice.FromGuid(g); Slice.FromUuid128(u); Slice.FromHexString("00ff1234");
This is a classic source of bugs. They are not interchangeable:
| Factory | Encoding | Size (int32) | Read back with |
|---|---|---|---|
Slice.FromInt32(v) | minimal little-endian (leading zero bytes dropped) | 1–4 bytes | slice.ToInt32() |
Slice.FromFixed32(v) | fixed little-endian | always 4 bytes | slice.ToInt32() |
Slice.FromVarint32(v) | 7-bit LEB128 varint | 1–5 bytes | (via SliceReader.ReadVarInt32) |
Every variant has a big-endian twin (FromInt32BE, FromFixed32BE, …) and 16/24/64/128-bit widths, plus floats (FromSingle/FromDouble) and FromDecimal. Big-endian fixed encodings are what you want when a number must sort correctly as a key. The minimal FromInt32 is for standalone values you read whole with ToInt32() — it is not self-delimiting, so don't use it mid-stream (in a SliceWriter, use the fixed-width WriteInt32/WriteInt64 or WriteVarInt* there; see §6).
⚠️ Naming differs between
Sliceand the writer/reader. OnSlice(standalone),FromFixed32= 4 bytes andFromInt32= minimal. OnSliceWriter/SliceReader(streams), the fixed-width method is plainWriteInt32/ReadInt32(4 bytes LE;*BEfor big-endian), and the varint isWriteVarInt32/ReadVarInt32. (WriteFixed32/ReadFixed32exist but are[Obsolete]— useWriteInt32/ReadInt32.)
slice.ToInt64(); slice.ToInt32BE(); slice.ToGuid(); slice.ToUuid128();
slice.ToStringUtf8(); // Nil -> null, Empty -> ""
slice.ToArray(); // defensive copy to byte[]
slice.ToHexString();
// zero-copy access to the bytes
ReadOnlySpan<byte> span = slice.Span;
ReadOnlyMemory<byte> mem = slice.Memory;
// slicing (negative indices count from the end)
slice.Substring(7, 6); slice[2..5]; slice[^1..];
Slice compares lexicographically by raw bytes (the same order FoundationDB sorts keys), is offset/array-independent (equal content compares equal regardless of backing array or offset), and supports ==, <, >, CompareTo, StartsWith, EndsWith, IndexOf. For dictionaries/sorted sets, use Slice.Comparer.Default (an IComparer<Slice> + IEqualityComparer<Slice>).
a.CompareTo(b) < 0; // a sorts before b
key.StartsWith(prefix); // prefix match
var set = new SortedSet<Slice>(Slice.Comparer.Default);
SliceWriter is a mutable, growable builder (struct, IBufferWriter<byte>, IDisposable). Start from default(SliceWriter) (heap-backed, grows as needed) or new SliceWriter(pool) (rents from an ArrayPool<byte>):
var w = new SliceWriter();
w.WriteInt32(42); // fixed 4 bytes LE (self-delimiting)
w.WriteVarInt32(1000); // LEB128 (self-delimiting)
w.WriteVarString("hello"); // length-prefixed UTF-8
w.WriteStringUtf8("raw"); // raw UTF-8, NO length prefix
w.WriteBytes(payload); // append bytes
Slice result = w.ToSlice(); // the written region (a view into the writer's buffer)
WriteInt32/WriteInt64/…, WriteVarInt*, WriteVarString) for anything you'll parse back sequentially. A raw WriteStringUtf8/WriteBytes has no length, so the reader must already know the length.Position, Reset(), Rewind(), Skip(n), Allocate(n)/AllocateSpan(n) (reserve space to fill in place).ArrayPool<byte>, you must either Dispose() the writer or hand the buffer off with ToSliceOwner() — otherwise the rented array is never returned. ToSlice() returns a view into the writer's buffer; if the writer (or its pooled buffer) is disposed/reused, that view becomes invalid — ToArray() or ToSliceOwner() it to keep it.SliceReader is a forward cursor over a Slice. Pair each read with the matching write:
var r = result.ToSliceReader();
int n = r.ReadInt32(); // <-> WriteInt32 (fixed 4 bytes)
uint k = r.ReadVarInt32(); // <-> WriteVarInt32
string s = r.ReadVarString(); // <-> WriteVarString
// raw / fixed-length string written without a prefix: read the known number of bytes
string raw = r.ReadBytes(3).ToStringUtf8();
Slice rest = r.ReadToEnd();
Remaining, HasMore, Head (bytes already read), Tail (bytes not yet read), and non-advancing PeekByte()/PeekBytes(n) round out the API. There is no ReadStringUtf8(n) — use ReadBytes(n).ToStringUtf8().
SliceOwner is a rented Slice that returns its buffer to an ArrayPool<byte> on Dispose — the allocation-free analogue of IMemoryOwner<byte>. The contract: you MUST Dispose it, and MUST NOT use its data afterward.
using (var owner = Slice.FromBytes(payload, ArrayPool<byte>.Shared))
{
Slice data = owner.Data; // valid only inside the using
Use(data.Span);
} // buffer returned to the pool here
owner.IsValid, owner.Count, owner.Span, owner.Pool; SliceOwner.Wrap/Create/Copy and writer.ToSliceOwner() produce them. Don't let an owner's Data escape the using.
ISpanEncodableSlice interops freely with the modern primitives: slice.Span (ReadOnlySpan<byte>), slice.Memory (ReadOnlyMemory<byte>), byte[].AsSlice(). Many hot types (keys, values, the writers) implement ISpanEncodable so they can be rendered into a caller's buffer with no intermediate Slice allocation — TryGetSpan(out span) / TryGetSizeHint(out size) / TryEncode(dest, out written). That interface is how subspace.Key(...)/FdbValue.* write themselves into pooled buffers at the last moment.
For working directly over Span<byte> (a caller-owned, fixed buffer) instead of Slice, use SpanReader/SpanWriter — see references/span-readers-writers.md.
// build
var w = new SliceWriter();
w.WriteInt32(order.Id);
w.WriteVarString(order.Customer);
w.WriteVarInt64(order.Total);
Slice packed = w.ToSlice();
// parse
var r = packed.ToSliceReader();
int id = r.ReadInt32();
string cust = r.ReadVarString();
long total = (long) r.ReadVarInt64();
IsNull/IsNullOrEmpty (not == Slice.Empty) to test for a missing value?Slice as a view — copying with ToArray()/ToSliceOwner() before mutating shared arrays or outliving a pooled buffer?Fixed*/*BE for sortable keys; VarInt*/Fixed* for self-delimiting stream fields; FromInt32 only for standalone whole-slice values)?SliceWriter writes and SliceReader reads pair up (WriteInt32↔ReadInt32, VarInt↔VarInt, VarString↔VarString)?ArrayPool (SliceWriter(pool) / SliceOwner), did I Dispose/ToSliceOwner() so the buffer returns to the pool — and not use the data after disposal?What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
9 skills in this plugin
/crystaljsonHow to use CrystalJson, the custom JSON library in SnowBank.Core (namespace SnowBank.Data.Json). Covers the JsonValue DOM (JsonObject / JsonArray / JsonString / JsonNumber / JsonBoolean / JsonNull / JsonDateTime), the read-only vs mutable model, the CrystalJson static API (Serialize / Parse / Deserialize) and CrystalJsonSettings, the Roslyn source generator for fast reflection-free serializers and read-only/writable proxies ([CrystalJsonConverter] / [CrystalSerializable]), the IJsonSerializable / IJsonPackable / IJsonDeserializable interfaces, MutableJsonValue / ObservableJsonValue and JsonPath. Use whenever code parses, builds, reads, mutates, or serializes JSON with these types, reads optional fields with defaults, declares a generated JSON converter/proxy, or implements custom JSON (de)serialization. Use it even when the request only says "serializer", "converter", or "serialize/deserialize a record, document, or model" without naming JSON: in SnowBank-based code (document stores, sync layers, Layers, models) document and message (de)serialization goes through CrystalJson, not System.Text.Json or Newtonsoft./foundationdb-advanced-layersAdvanced engineering for sophisticated FoundationDB layers with the .NET client (FoundationDB.Client / SnowBank) — the cluster model and transaction lifecycle (proxies, resolvers, tlogs, storage servers, the sequencer/version clock), latency/throughput optimization (batching reads with GetValuesAsync / Task.WhenAll, removing round-trip dependencies, snapshot reads), high-contention avoidance, and distributed patterns (change feeds, version-stamp logs, watch fan-out, version-as-clock leases, retention, fencing/tombstones). Use when building or reviewing a performance-sensitive or distributed layer (a change feed, queue, pub/sub, worker pool, multi-node observable view), tuning transaction latency/throughput, or reasoning about conflicts, the 5-second limit, or cross-node liveness. Builds on the foundationdb-keys-and-layers and foundationdb-transactions skills — read those first./foundationdb-aspireHow to run a FoundationDB cluster and connect to it from .NET — getting the IFdbDatabaseProvider that the keys/transactions/layers skills assume you already have. Covers the ways to get a provider (plain DI services.AddFoundationDb, FdbDatabaseProvider.Create, or Aspire), the Aspire AppHost integration (FoundationDB.Aspire.Hosting — builder.AddFoundationDb starts a Docker cluster, AddFoundationDbCluster connects to an existing one), the Aspire client integration (FoundationDB.Aspire — builder.AddFoundationDb reads the injected connection), wiring with WithReference and WaitFor, launching with the aspire CLI vs plain dotnet run plus launchSettings, the native client (libfdb_c via UseNativeClient, the platforms FoundationDB.Client.Native ships, and the macOS system-library fallback), and the client-vs-cluster version-compatibility rule (FoundationDB.Client.Native follows the cluster's major.minor, FoundationDB.Client is independent of it, apiVersion stays within what both the binding and the native client support). Use whenever code opens or connects to a cluster, registers AddFoundationDb, runs an Aspire host, or hits libfdb_c load failures or transactions that hang on a fresh cluster./foundationdb-keys-and-layersHow to correctly encode keys and values, use subspaces and the Directory layer, and write custom "Layers" with the FoundationDB .NET client (FoundationDB.Client / SnowBank). Covers the lazy strongly-typed key structs (subspace.Key(...), FdbTupleKey, FdbRawKey, FdbKey.Increment / Successor / Dump), the tuple encoding (TuPack, IVarTuple, STuple), value encodings (FdbValue.ToBytes / ToTextUtf8 / FromTuple / ToJson / ToFixed64LittleEndian and which one a given access pattern requires), subspaces and ISubspaceLocation, the Directory layer (FdbDirectoryLayer, FdbPath, FdbDirectorySubspace), and the IFdbLayer contract with its per-transaction Resolve(tr) State that must never escape the transaction. Use whenever code reads or writes FoundationDB keys, builds or decodes a tuple key, picks a value encoding, resolves a subspace or location, designs a key layout for a table / secondary index / queue / document collection, reasons about key ordering, prefixes and range boundaries, or defines a class that stores data in FoundationDB. Also use it for "how do I model X in FoundationDB", for range scans that return too much or nothing, and for keys that are too big. Read this BEFORE writing or reviewing any such code./foundationdb-transactionsHow to correctly run transactions with the FoundationDB .NET client (FoundationDB.Client / SnowBank): the db.ReadAsync / WriteAsync / ReadWriteAsync retry loop and why a handler must be safe to run more than once, the 5-second and size limits, conflicts and how to avoid them, snapshot reads, explicit conflict ranges, atomic mutations (AtomicAdd32/64, AtomicIncrement, AtomicMin/Max and the lexicographic ByteMin/ByteMax, AtomicAnd/Or/Xor, AtomicCompareAndClear, AtomicAppendIfFits), and watches. Use whenever code opens a transaction or calls BeginTransaction, writes a read-modify-write, increments a counter, waits on a key with a watch, pages a large range scan across transactions, or hits an FdbException: NotCommitted, TransactionTooOld ("Transaction is too old to perform reads"), CommitUnknownResult, TransactionTimedOut, transaction_too_large. Also use it for "why does my transaction keep retrying / conflict / run twice", for high-contention or write-hot keys, and before deciding that a value must be read and written back. Pairs with the foundationdb-keys-and-layers skill./snowbank-betterhttpHow to make outbound HTTP calls with BetterHttpClient (SnowBank.Networking.Http) in an ASP.NET Core or generic-host .NET application - the DI story and the request API. Covers the one-policy-plane model where a client NAME maps to one effective policy that lives in the pooled handler chain, so every client gets the same behavior: a typed client, a keyed client, IHttpClientFactory.CreateClient(name), and the bare IHttpMessageHandlerFactory.CreateHandler(name). Covers AddBetterHttpClientDefaults (routes every factory client through the map), AddBetterHttpClient(name, ...) returning an IBetterHttpClientBuilder for standard chaining (AddHttpMessageHandler, AddAsKeyed, typed clients), the AddBetterHttpClientConfiguration override layer bound from an appsettings section, the mandatory INetworkMap transport seam (NetworkMap in production, the virtual network inside distributed tests, with packet capture on every chain automatically), BetterHttpClientOptions (default headers and UserAgent, cookies, credentials, TLS server-certificate callbacks and the self-signed/trusted-roots helpers, hooks, delegating handlers), the universal SendAsync(request, ctx => ...) lifecycle with BetterHttpClientContext that now runs the request stage on any client, the Create*Request builders, typed protocols (RestHttpProtocol, BetterHttpProtocolFactoryBase, the AddFooClient extension-method pattern), how to port legacy HttpWebRequest / WebClient (.NET Framework) code to this stack, and which 7.4.3 members are now soft-obsolete (IBetterHttpClientFactory, the BetterHttpClient shell, BetterHttpShellOptions, IBetterHttpFilter/Filters, AddGlobalHttpFilter/AddGlobalHttpHandler) and their native replacements. Use whenever application code registers or injects an HttpClient in a SnowBank-based app, declares a named client, configures user agents or HTTPS certificate validation, binds HTTP options from configuration, ports HttpWebRequest/.NET Framework 4.7.2 networking code to net8+/net10, or hits "You must register an implementation for INetworkMap".npx claudepluginhub snowbanksdk/foundationdb-dotnet-client --plugin foundationdb-dotnet-skillsOther plugins' skills for the same job