Enable C# 15 memory safety rules and annotate unsafe code

Merged
BR
18d ago
+1037-503

Summary

Enables the C# 15 preview memory safety rules (updated-memory-safety-rules) and annotates all unsafe code in Snappier so the compiler enforces where safety obligations are taken on and discharged.

Changes

  • Build
    • LangVersion is preview, and the updated-memory-safety-rules feature is on.
    • AllowUnsafeBlocks is set, and a net11.0 target is added to Snappier so the .NET 11 BCL's requires-unsafe APIs (Unsafe.*, MemoryMarshal.*, Vector128.LoadUnsafe/StoreUnsafe) are checked.
    • CI runs the test matrix on net11.0 as well.
  • Contracts: each member that passes a safety obligation to its callers is marked unsafe and documents the obligation in a /// <safety> comment.
  • Narrow unsafe regions: unsafe blocks and unsafe(expr) expressions cover only the operations that need them.
    • Each has exactly one // SAFETY: comment saying why the obligation holds at that point.
    • A blank line precedes each new unsafe block unless the line before is { or a comment.
  • UnsafeReadonly: ByteOffset, IsAddressGreaterThan and IsAddressLessThan stay safe because they only compare addresses, as in the .NET 11 BCL. The other helpers forward the Unsafe contract and document it.
  • Benchmarks and tests were updated where they call members that are now requires-unsafe.

Notes for reviewers

  • Rebased onto #156. The safety comments in SnappyDecompressor reflect its two changes:
    • Output is now bounded by ExpectedLength.
    • A long literal length that overflowed nint on 32-bit platforms is now rejected, so every length passed to Append is non-negative.
  • Known limitations are documented in the contracts, not fixed. These are existing behaviors, not regressions:
    • UnalignedCopy64/UnalignedCopy128 and UnsafeReadonly.As use typed loads that may fault on misaligned addresses on ARM32.
    • Some references computed only for comparison (bufferEnd - N, nextIp) can point outside their buffer on short inputs. The runtime doesn't formally allow that even for comparisons.
    • When RefillTag copies within scratch, the source and destination can overlap.
  • Preview dependency: this relies on a C# preview feature, so the annotation syntax may change before it ships.

Testing

  • The Release build of Snappier.slnx has 0 warnings and 0 errors.
  • dotnet test --project Snappier.Tests: 1,544 passed, 0 failed.

šŸ¤– Generated with Claude Code