SBK1001: Pooled buffer escaping its using scope
| Analyzer | SnowBank.Core |
| Severity | Warning (correctness) |
| Code fix | No |
Message
'{0}' points into a pooled buffer that returns to the pool at the end of this using block. Copy it with ToArray(), or return the owner with ToSliceOwner().
Why
A SliceOwner, a PooledSliceWriter, a PooledSliceAllocator, or a SliceWriter created with an ArrayPool<byte> rents its buffer from the pool and returns it when disposed. Data, Span, Memory, WrittenSlice, ToSlice(), GetSlice(...), and Allocate(...) return views into that buffer, not copies. A view that outlives the using block reads whatever the next renter writes into the same array.
The rule reports such a view, or a local initialized from one, when it is returned, assigned to a field or a property, passed to an Add method, or read inside a lambda that does not declare the owner. A view that goes through ToArray(), Slice.Copy(...), or ToSliceOwner() first is a copy or a hand-off and is not reported.
Bad
Slice Load(byte[] payload)
{
using var owner = Slice.FromBytes(payload, ArrayPool<byte>.Shared);
return owner.Data;
}
Good
Slice Load(byte[] payload)
{
using var owner = Slice.FromBytes(payload, ArrayPool<byte>.Shared);
return owner.Data.ToArray().AsSlice();
}
When the caller can dispose the buffer itself, return the owner instead of a copy: return writer.ToSliceOwner(); hands the rented buffer to a SliceOwner that the caller disposes.
Suppress
#pragma warning disable SBK1001 // reason
or, for a whole project, in .editorconfig:
dotnet_diagnostic.SBK1001.severity = none