SBK2002: Slice to byte[] round trip

Analyzer SnowBank.Core
Severity Warning (performance)
Code fix Yes

Message

'{0}' copies the bytes into a temporary array. Call {1} instead.

Why

Slice decodes its own content: ToStringUtf8() and ToInt64() read the bytes in place. Encoding.UTF8.GetString(slice.ToArray()) and BitConverter.ToInt64(slice.GetBytes(), 0) first copy the bytes into a new array, then decode the copy, so every read allocates an array that nothing else uses.

The same holds when writing: Encoding.UTF8.GetBytes(text).AsSlice(), Slice.Copy(Encoding.UTF8.GetBytes(text)), and Slice.FromBytes(Encoding.UTF8.GetBytes(text)) encode into an array that the Slice then wraps or copies again. Slice.FromStringUtf8(text) encodes once.

The rule reports these five shapes. ToStringUtf8() returns null for Slice.Nil, where Encoding.UTF8.GetString returns "" for an empty array. ToInt64() reads a little-endian value of 1, 2, 4, or 8 bytes, where BitConverter.ToInt64 reads 8 bytes in the byte order of the host, which is little-endian on every platform the library runs on. new Guid(slice.ToArray()) is not reported: ToGuid() reads the RFC 4122 byte order that Slice.FromGuid writes, and new Guid(byte[]) reads the .NET layout, so the two calls give different values for the same bytes.

Bad

string name = Encoding.UTF8.GetString(value.ToArray());
long count = BitConverter.ToInt64(value.GetBytes(), 0);
Slice encoded = Encoding.UTF8.GetBytes(text).AsSlice();

Good

string? name = value.ToStringUtf8();
long count = value.ToInt64();
Slice encoded = Slice.FromStringUtf8(text);

Code fix

The fix rewrites each shape to the call named in the message.

Suppress

#pragma warning disable SBK2002 // reason

or, for a whole project, in .editorconfig:

dotnet_diagnostic.SBK2002.severity = none

The whole performance tier can be muted at once:

dotnet_analyzer_diagnostic.category-SnowBankPerformance.severity = none