Skip to content

Improve stream I/O correctness and add 64-bit stream APIs - #5483

Closed
mattleibow wants to merge 37 commits into
mainfrom
mattleibow-stream-span-polyfills-and-skdata-wstream
Closed

mattleibow wants to merge 37 commits into
mainfrom
mattleibow-stream-span-polyfills-and-skdata-wstream

Conversation

@mattleibow

@mattleibow mattleibow commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Make stream-backed data creation reliable with short reads, offsets and early EOF, and make managed output streams usable without a seekable destination. Add 64-bit length, position and absolute seeking without changing existing public signatures.

SKData.Create starts at the input's current position and uses bounded 80 KiB transfer requests. Known-length copies fill the final native allocation across legal positive short reads; reaching EOF before the expected count completes disposes the partial data and returns null. There is no truncated-prefix success, rewind/reset/re-read or fallback after a known-length failure. Unknown-length input is staged in SKDynamicMemoryWStream until normal EOF and returns the accumulated data, including empty data for a zero-byte result. A zero requested count also succeeds with empty data.

The lengthless SKStream factory selects one of four managed/native and known/unknown-length routes. Known remaining length requires both length and position capabilities. Managed factory operations stay on the managed stack so original read/metadata exceptions can propagate, with cleanup that does not dispose the caller's input; a failed consuming read does not restore its cursor. Two internal front-buffer read sites likewise avoid an added nested reverse-P/Invoke boundary and free their temporary native buffer in finally. Public SKStream operations remain native-backed. Public explicit-length SKData.Create(SKStream, ...) overloads keep the native factory's at-most-one-read behavior: a legal short read can return null even when more bytes remain.

SKManagedWStream tracks bytes successfully written through this wrapper instead of querying destination Position. It writes bounded chunks, preserves its null-buffer zero-fill behavior and latches write/flush exceptions: writes return false, subsequent writes are rejected and subsequent flushes are ignored. Null constructor arguments and invalid public managed array counts are rejected before native allocation or entry. Modern data/write-stream paths use spans over native memory; net462, net48 and netstandard2.0 use array overloads with a bounded scratch rental reused across chunks. The transfer request stays at 80 KiB even if the pool returns a larger backing array.

SKManagedStream reports negative managed lengths as unavailable instead of converting them to unsigned native sizes. This includes SKFrontBufferedStream over non-seekable input, which permits buffered seeking but returns Length == -1. Its native length getter returns zero when length is unknown; position reporting remains available. For these seekable unknown-length streams, EOF follows a zero-byte read and is cleared by a successful seek, rewind or relative move. Ordinary non-seekable read/fill policy and the factory's strict known-length failure policy are unchanged.

SKFrontBufferedStream is now deprecated with a warning-only Obsolete attribute. Its implementation, public signatures, limited buffered seeking and Length == -1 compatibility behavior are retained. For image decoding, callers should pass the original .NET stream directly to SKCodec.Create or SKBitmap.Decode; those paths already select the appropriate adapter. Explicit Skia buffering uses SKFrontBufferedManagedStream, which is an SKStream, not a drop-in System.IO.Stream replacement. Source XML documents these distinctions and the replacement constructor links now point to the correct type.

This is the first open correctness layer in stack 5513: #5475 (merged) → #5479 (merged) → this PR → #5464 → #5476 → #5518 (optional allocation-only layer). Generic callback containment/error state and reader lifecycle changes belong to #5464; broader front-buffer algorithms and large-stream constructor fixes belong to #5476. No native/generated declarations, callback proxy policy or HarfBuzz behavior change here. Public managed-dispatch fast paths, Stream Span polyfills and whole-input managed pooling are not included.

Deferred buffering research

Whole-input managed pooling was measured and removed: small/medium warm copies improved on the measured Mac, but larger inputs regressed allocation/GC behavior and eventually elapsed time. The evidence did not justify a portable default or size threshold.

These are historical experiments, not performance claims about the final code; archived code predates the strict known-length EOF decision. Native staging still uses intermediate storage and gathers into contiguous SKData. The retained benchmarks compare copy strategies; they do not justify public managed/native dispatch changes or establish universal speed, allocation or RSS improvements.

Related issues

Part of the stream-fix split with #5464 and #5476. The prerequisites #5479 and #5475 are merged into main; this PR targets main.

Required skia PR

None.

Areas affected

  • Managed API (binding/)
  • Native / C API (externals/skia/src/c, include/c)
  • Generated P/Invoke bindings
  • Native dependency or Skia update (libpng, HarfBuzz, FreeType, zlib, milestone bump, …)
  • Views & integrations (MAUI, Uno, WPF, WinUI, Blazor, …)
  • Rendering output / visual behavior
  • Performance
  • Tests
  • Build, packaging, or CI
  • Documentation or samples

Changes

Public API — additions and warning-only deprecation

public long SKStream.Length64 { get; }
public long SKStream.Position64 { get; set; }
public bool SKStream.Seek(long position);

// Deprecated, retained for compatibility:
[Obsolete("Use SKFrontBufferedManagedStream for Skia stream buffering, or pass the original Stream directly to SKCodec.Create or SKBitmap.Decode.")]
public class SKFrontBufferedStream : System.IO.Stream { /* existing members retained */ }

Existing public signatures are retained. The properties follow the repository's existing *64 naming convention.

Behavior

  • Length64/Position64 decode unsigned native pointer-sized metadata before converting to long; values above Int64.MaxValue throw OverflowException. Existing int Length/Position getters now use checked conversions instead of truncating values above Int32.MaxValue.
  • Absolute seeks reject negative positions. Seek(long) and the wide position setter reject values above UInt32.MaxValue in a 32-bit process. Managed metadata/seek callbacks preserve valid unsigned 32-bit values above 2 GiB and reject unrepresentable values rather than truncating them. Relative Move retains signed offsets and backward movement.
  • Managed streams with a negative length report HasLength == false and a zero native length, not an unsigned-max allocation size. Unknown-length buffered inputs therefore use the existing read-to-EOF factory route; they retain independent position reporting.
  • Public Read/Peek/Skip reject negative counts; array reads/writes reject counts exceeding a non-null array before pinning/native entry. Null-array reads retain skip behavior, and null-buffer managed writes retain zero filling. Read validates the full unsigned native result before narrowing it to int.
  • Signed SKData.Create sizes/lengths reject negative values; native pointer-width limits are enforced. Known-length copy loops return null on incomplete input; unknown-length copies read to EOF. Empty success and positive-count failure remain distinct. Native explicit-length SKStream factories retain their documented one-shot/short-read behavior.
  • Managed data-factory failures release partial data, preserve original managed exceptions and do not dispose caller-owned input. Their direct-managed path is not a new exception guarantee for native-backed public stream operations.
  • Managed output uses wrapper-relative accounting, bounded writes and a persistent write/flush fault latch. Flush remains void and does not expose the original exception; class/member XML remarks document containment and subsequent fault behavior.
  • SKFrontBufferedStream usage produces an obsolete warning, not an error. The type and its existing runtime behavior remain available; the deprecation does not replace .NET stream semantics with Skia semantics or change the legacy unknown-length sentinel.

Testing

Current head: 15158ad8446fd76edab90551612507dd0345c459. Local runtime validation was on macOS ARM64/.NET 10, independently of upper-layer callback containment.

Command Result
dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 Passed at the current head: 6,577 core + 57 other-host tests = 6,634 passed, 0 failures, 47 existing skips unchanged. Other-host passes: gallery 50, singleton 1, Direct3D 2, Vulkan 4.
dotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -p:TargetFramework=net48 -p:TargetFrameworks=net48 -v:quiet Passed at the current head, 0 errors; compilation only, not .NET Framework runtime execution.
dotnet build binding/SkiaSharp/SkiaSharp.csproj -v:quiet Passed for all 13 configured TFMs at the current head, 0 errors. All 13 compiler XML files contain the wide APIs, migration guidance and corrected replacement constructor links.
dotnet build benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -c Release -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 -v:quiet Passed at 667ced59127ec9e7075c57e07f471d446ac0b46a; subsequent changes are the warning-only type attribute, source XML and tests, with no executable-code changes. No new benchmark measurements or public-dispatch performance claim.
pwsh -NoLogo -NoProfile -File ./scripts/infra/package/tests/AssembleArcadeAssets.Tests.ps1 Passed at the current head; the package contract requires matching compiler XML beside implementation and reference assemblies.
git diff --check Passed.

Coverage includes short reads, offsets, strict known-length EOF and no-retry behavior, empty results, unknown-length input through 10 MiB, invalid counts, bounded requests, native unsigned widths, checked legacy getters, original exception identity, nested managed reads, input ownership, constructor lifetime, output byte parity and write/flush faults.

The test-only follow-up at 7bfd6e054f0080d45e494465e55edd8321ccf797 strengthened five cases covering failures after a completed write chunk for ordinary/null buffers, zero filling across two full chunks and a partial tail, and immediate factory cleanup for managed Stream and managed SKStream. Cleanup is observed through the existing nonparallel handle-registry collection, deregistration helper and a retained native reference; it does not depend on GC or access freed memory and introduces no production test hook. Temporarily removing zero clearing/disposal and resetting completed-byte accounting made all five cases, plus two existing small zero-fill cases, fail. All mutations were reverted before the final passing suite. Dirty shared-pool reuse is best-effort; exact byte/count/chunk assertions are unconditional.

The review correction at 667ced59127ec9e7075c57e07f471d446ac0b46a fixes negative-length metadata and makes ConfigurableTestStream/ThrowingReadStream disposal-sensitive, so existing caller-ownership checks can detect a disposed input. Eight new cases failed before the fix at safe capability/getter/EOF or fixture-disposal assertions; no near-maximum native allocation was attempted. Final coverage includes real front-buffered empty, nonempty and partially consumed input, negative metadata limits, EOF after zero reads and successful seeks, and a separate short-read unknown-length managed-wrapper case. A first expanded front-buffer short-read probe encountered the older buffer-offset defect owned by #5476; the lower-layer regression isolates the metadata defect without changing those algorithms. One subsequent full run encountered the unchanged color-space reference-count assertion also seen in an earlier baseline; its focused diagnostic and the final unfiltered solution passed without modifying or skipping the test.

The user-directed deprecation follow-up adds two cases checking that the attribute is warning-only with migration guidance, that the two buffering types have distinct .NET/Skia base contracts, and that unknown Length == -1 plus buffered rewind still behave as before. Source comparison confirms executable code and member declarations are unchanged by this follow-up apart from the type's Obsolete attribute.

All nine rebuilt test-host native library copies matched source-pinned m156/Skia 748bc0c0116c3952f0a0089f5cc53edc55ae08de assets from Azure main build 1655687, producing source b45912c193582b20664445e506e92f773a1aa6e8. This is local evidence, not a claim that current-head PR CI is green.

The user-requested Claude Sonnet 5.5 review inspected the complete 17-file diff and test coverage at 7bfd6e054f0080d45e494465e55edd8321ccf797, before the negative-length correction and deprecation follow-up. It found no high-confidence introduced bugs or actionable defects at that revision and confirmed the three requested coverage gaps are genuinely covered. It reviewed source and recorded passing/mutation evidence; it did not independently execute tests, and its conclusion is not GitHub review approval. No additional independent review was run for the subsequent GitHub feedback correction or deprecation.

Limits: no 32-bit or .NET Framework runtime execution, and no other OS/device runtime execution in this session. Platform-specific branches were compiled/source-reviewed, not claimed as executed. No new rendering output or golden-image change is intended; screenshots are not applicable. No CI/branch-filter bypass or skip-policy expansion.

Checklist

  • Tests added or updated (if omitted, explain why above)
  • Changes above lists all public API and behavioral changes (or "None.")
  • New/changed public API? Added or updated accurate source /// documentation and regenerated bindings when applicable
  • Native change? Companion mono/skia PR linked above and bindings regenerated

Native companion PR and binding regeneration are not applicable: no native or generated declarations changed.

@github-actions

Copy link
Copy Markdown
Contributor

📦 Try the packages from this PR

Warning

Do not run these scripts without first reviewing the code in this PR.

Step 1 — Download the packages

bash / macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.sh | bash -s -- 5483

PowerShell / Windows:

iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 5483"

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-5483/packages --name skiasharp-pr-5483
More options
Option Description
--successful-only / -SuccessfulOnly Only use successful builds
--force / -Force Overwrite previously downloaded packages
--list / -List List available artifacts without downloading
--build-id ID / -BuildId ID Download from a specific build

Or download manually from Azure Pipelines — look for the nuget artifact on the build for this PR.

Remove the source when you're done:

dotnet nuget remove source skiasharp-pr-5483

@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

Add the automation/staging label to build and publish a documentation preview for this PR.

Removing the label removes the preview. While the label is present, each new commit updates it.


This comment is automatically updated by the documentation staging workflow.

@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from 4425ac7 to bda2bbb Compare October 28, 2026 17:43
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #5483

⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS

Informational only — this never blocks the PR. 🟢 faster / less allocation · 🔴 slower / more allocation; moves under 5% are hidden as noise.

⏱️ Times are raw BenchmarkDotNet means, and the ⭐ PR and baseline legs run on separate CI runners, so microbenchmarks can swing run-to-run — treat small time deltas as noise. Allocations are deterministic and the reliable signal. The interactive perf-dashboard (linked below) applies smoothing for the trend view.

Highlights

⏱️ Time — 🔴 63 slower · 🟢 22 faster

  • 🔴 ColorMathBenchmark.ToColor(Colors: 4096) · Linux · 5.14 µs → 15.41 µs (+200%)
  • 🔴 ColorMathBenchmark.PreMultiply(Colors: 4096) · Linux · 7.54 µs → 14.09 µs (+87%)
  • 🔴 RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) · Linux · 59.22 µs → 109.64 µs (+85%)
  • 🔴 MatrixMapPointsBenchmark.MapPoints(Points: 4096) · Linux · 1.47 µs → 2.71 µs (+84%)
  • 🔴 RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) · Linux · 144.63 µs → 264.54 µs (+83%)
  • …and 80 more (see details below)
Full per-OS benchmark deltas

Linux

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26529.13)

Benchmark baseline this PR Δ
ColorMathBenchmark.ToColor(Colors: 4096) 5.14 µs 15.41 µs 🔴 +200%
ColorMathBenchmark.PreMultiply(Colors: 4096) 7.54 µs 14.09 µs 🔴 +87%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 59.22 µs 109.64 µs 🔴 +85%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.47 µs 2.71 µs 🔴 +84%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 144.63 µs 264.54 µs 🔴 +83%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 126.3 ns 225.7 ns 🔴 +79%
ColorParseBenchmark.Parse(Iterations: 1000) 42.31 µs 74.23 µs 🔴 +75%
PathBoundsBenchmark.TightBounds(Points: 64) 593.9 ns 979.2 ns 🔴 +65%
ColorMathBenchmark.ToColorF(Colors: 4096) 8.09 µs 13.13 µs 🔴 +62%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 7.19 µs 11.39 µs 🔴 +58%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 160.47 µs 248.45 µs 🔴 +55%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 2.95 µs 4.52 µs 🔴 +53%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 615.44 µs 936.79 µs 🔴 +52%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 231.13 µs 349.74 µs 🔴 +51%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 5.07 ms 7.63 ms 🔴 +50%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 878.29 µs 1.32 ms 🔴 +50%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 48.12 µs 72.12 µs 🔴 +50%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.33 ms 1.97 ms 🔴 +47%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 9.74 µs 14.34 µs 🔴 +47%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 467.41 µs 685.13 µs 🔴 +47%
MatrixOpsBenchmark.Concat(Count: 4096) 147.90 µs 216.43 µs 🔴 +46%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 1.81 ms 2.64 ms 🔴 +46%
PathBoundsBenchmark.TightBounds(Points: 1024) 6.81 µs 9.94 µs 🔴 +46%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 157.74 µs 229.23 µs 🔴 +45%
MatrixMapPointsBenchmark.MapVector(Points: 256) 7.61 µs 10.89 µs 🔴 +43%
…and 8 more

Windows

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26529.13)

Benchmark baseline this PR Δ
ColorMathBenchmark.ToColor(Colors: 4096) 10.32 µs 15.94 µs 🔴 +54%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.71 µs 2.59 µs 🔴 +51%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 353.0 ns 186.3 ns 🟢 -47%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 9.25 µs 13.55 µs 🔴 +47%
PathBoundsBenchmark.TightBounds(Points: 1024) 14.11 µs 20.53 µs 🔴 +45%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 28.90 µs 41.32 µs 🔴 +43%
RuntimeEffectShaderBenchmark.DrawFrame 819.08 µs 1.14 ms 🔴 +39%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 3.80 µs 2.44 µs 🟢 -36%
PathBoundsBenchmark.TightBounds(Points: 64) 1.45 µs 1.89 µs 🔴 +31%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.32 ms 2.93 ms 🔴 +26%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 757.69 µs 949.00 µs 🔴 +25%
ColorMathBenchmark.PreMultiply(Colors: 4096) 10.69 µs 13.32 µs 🔴 +25%
ColorParseBenchmark.Parse(Iterations: 1000) 69.19 µs 85.51 µs 🔴 +24%
CanvasDrawBenchmark.Draw(Shapes: 512) 18.83 ms 23.24 ms 🔴 +23%
MatrixOpsBenchmark.Concat(Count: 4096) 199.99 µs 240.95 µs 🔴 +20%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 8.73 µs 10.50 µs 🔴 +20%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 139.83 µs 168.20 µs 🔴 +20%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.06 ms 1.25 ms 🔴 +18%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 211.77 µs 249.12 µs 🔴 +18%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 286.48 µs 332.09 µs 🔴 +16%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 122.45 µs 140.68 µs 🔴 +15%
MatrixMapPointsBenchmark.MapVector(Points: 256) 7.63 µs 8.72 µs 🔴 +14%
MatrixOpsBenchmark.Invert(Count: 4096) 120.88 µs 137.31 µs 🔴 +14%
ColorMathBenchmark.ToColorF(Colors: 4096) 15.24 µs 13.30 µs 🟢 -13%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 2.37 ms 2.63 ms 🔴 +11%
…and 3 more

macOS

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26529.13)

Benchmark baseline this PR Δ
SceneRenderBenchmark.RenderFrame(Complexity: 4) 6.82 ms 5.35 ms 🟢 -21%
MatrixOpsBenchmark.Invert(Count: 4096) 77.10 µs 66.28 µs 🟢 -14%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 45.77 µs 39.66 µs 🟢 -13%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 161.8 ns 140.9 ns 🟢 -13%
PathBoundsBenchmark.TightBounds(Points: 1024) 9.35 µs 8.23 µs 🟢 -12%
PathBoundsBenchmark.TightBounds(Points: 64) 983.4 ns 868.1 ns 🟢 -12%
MatrixOpsBenchmark.Concat(Count: 4096) 121.92 µs 109.36 µs 🟢 -10%
CanvasDrawBenchmark.Draw(Shapes: 512) 12.02 ms 13.21 ms 🔴 +10%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 288.12 µs 260.50 µs 🟢 -10%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.26 µs 1.14 µs 🟢 -9%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 109.38 µs 99.00 µs 🟢 -9%
ColorParseBenchmark.Parse(Iterations: 1000) 70.32 µs 75.95 µs 🔴 +8%
MatrixMapPointsBenchmark.MapVector(Points: 256) 2.68 µs 2.47 µs 🟢 -8%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 19.55 µs 18.07 µs 🟢 -8%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 697.60 µs 750.00 µs 🔴 +8%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 6.77 µs 6.27 µs 🟢 -7%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 825.30 µs 885.74 µs 🔴 +7%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 2.97 ms 2.76 ms 🟢 -7%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 7.96 µs 8.47 µs 🔴 +6%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 51.55 µs 48.33 µs 🟢 -6%
MatrixMapPointsBenchmark.MapRect(Points: 256) 3.26 µs 3.06 µs 🟢 -6%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.78 µs 1.67 µs 🟢 -6%
ColorMathBenchmark.PreMultiply(Colors: 4096) 9.13 µs 8.66 µs 🟢 -5%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 71.42 µs 67.71 µs 🟢 -5%

📈 Full interactive perf-dashboard & run details →

@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from bda2bbb to b65eb65 Compare October 28, 2026 18:22
@mattleibow mattleibow changed the title Add Stream Span polyfills and improve SKData and SKManagedWStream I/O Improve SKData stream I/O and SKManagedWStream accounting Oct 28, 2026
@mattleibow

Copy link
Copy Markdown
Contributor Author

Deferred stream-buffering research

Decision: keep this investigation for later, not in the shipping implementation of this PR.
Unknown-length managed streams will use one bounded managed scratch rental and
SKDynamicMemoryWStream, retaining the correctness, signed-length/pointer validation,
short-read/EOF handling, ownership and direct known-length read/write improvements.
No speculative cutoff, new pooling consumer or generic reader abstraction is being added.

The frozen pre-cleanup source is b00ca26bee9990fb025a6ccd07532761c595d808. The complete helper,
its dedicated tests, experimental collectors and benchmarks are preserved below.
The helper-only tests are retired with their helper; the SKData/SKManagedWStream
functional regression tests remain in the PR.

What we learned

  • Both native dynamic blocks and managed pooled chunks are length-agnostic collectors;
    either can accept managed or native-backed input. This is a storage/GC policy choice,
    not an API-type restriction.
  • The slim ref-struct owner was performance-comparable to the preceding hand-rolled
    collector at measured 4 KiB/2 MiB/3 MiB sizes. It had an inline first entry,
    append-only pooled entry blocks, fixed 64 KiB data buffers, checked 64-bit length,
    allocation-free enumeration and pattern-based using var cleanup.
  • Pooled staging was faster on ordinary-sized warm, sequential unknown-length
    managed inputs, but saved only about 0.20 ms at 8 MiB and 0.42 ms at 16 MiB here.
    At 32 MiB it still improved elapsed time while allocating about 8 MiB managed/op.
  • The original-production managed comparison was verified separately from the SKStream
    candidate. At 100 MiB the actual managed production pooled collector was 15-39%
    slower, with about 76 MiB managed allocation/op. The SKStream prototype was also
    worse at 100 MiB (25-44% slower in the matched rerun); it was never adopted.
  • Later points at 50/75/200 MiB confirmed large-input regressions. The local timing
    break-even region was roughly 36-40 MiB for full reads and about 50 MiB for
    4 KiB short reads. Error bands overlap near equality, and large-input GC behavior
    is not a smooth universal function of size.
  • At an exact 10 MiB, the pooled loop rents 160 full 64 KiB byte arrays plus another
    to discover EOF: 161 simultaneous data-buffer rentals, plus small entry arrays.
    A cold/busy cache can allocate replacements, and concurrent consumers compete for
    the same size bucket. ArrayPool is a cache, not reserved or guaranteed reusable
    capacity; returned buffers may not be retained.
  • At consolidation both approaches hold staged input plus final contiguous SKData.
    Source storage can add another copy. Low managed allocation is not low total
    memory; native allocators and shared pools can both retain released memory.
  • Known-length/ordinary seekable Stream input already reads into the final allocation.
    SKImage.FromEncodedData(Stream) can reach the collector, but SKBitmap.Decode(Stream),
    SKTypeface.FromStream and saving take different paths. These are copying
    benchmarks, not end-to-end image decoding, font parsing or disk/network I/O.
  • The repository has 76 tracked sample screenshots (median 275 KiB, p90 about 1 MiB,
    maximum 1.32 MiB); example fonts are Noto Sans 614 KiB, Inter Variable 859 KiB and
    Nabla 1.57 MiB. Two 4608x3456 JPEG photos are 6.14 and 7.44 MiB. Documentation
    images/icons/tiny test fonts do not represent a customer workload distribution.
    Encoded file sizes matter here: a 1920x1080 PNG example is 703 KiB while nominal
    four-byte RGBA pixels would take about 7.9 MiB.
  • Keep the existing 80 KiB transfer request. .NET 10/runtime-main Stream.CopyTo still
    requests 81,920 bytes, without a 32/64-bit split; shared pools commonly round that
    to 128 KiB and BCL CopyTo can use the full rental. Our loops cap the requested
    transfer. A two-run 64/80/128 KiB sweep over memory/cached-file reads and writes
    found no universal winner. Retained pooled chunks used 64 KiB to avoid that rounding.
  • System.Memory already supplies Span on the older targets. The proposed Stream Span
    extensions were removed: the few pointer-based consumers use local TFM branches,
    with one scratch rental per operation on legacy targets, not a per-chunk rental.
  • SKData.Create(address, length, releaseProc) can wrap one stable contiguous allocation
    without copying; it cannot gather disjoint pooled chunks. The public callback
    overload's int length also needs care for large inputs. An experimental unmanaged
    grower used 128 MiB capacity for 100 MiB content and avoided a final gather, but
    reallocations/capacity waste/lifetime and native memory remain; it was not adopted.
  • Direct SKManagedWStream writes remain separate accepted work: earlier paired 2/3 MiB
    runs measured about 76-77 to 39-40 us and 113-117 to 57-58 us, with zero measured
    warm managed allocation on both sides. No general cross-platform percentage is claimed.

Measurement scope and representative numbers

BenchmarkDotNet 0.13.5, Apple M3 Pro, .NET 10.0.12 ARM64, in-process paired methods,
two independent processes per comparison, output byte parity checked in setup.
The original managed baseline is the original SKManagedStream.CopyTo -> native dynamic
blocks -> DetachAsData implementation; the candidate calls the then-current actual
SKData.Create(System.IO.Stream). SKStream cases use a forward-only SKManagedStream
over the same memory-backed source, not a pure C++ file stream.

Paired and supplemental/coarse jobs: 12 measured iterations x 150 ms, 4 warmups.
Refinement: 20 x 300 ms, 5 warmups. Earlier owner/batching/transfer-size/write
comparisons: 15 x 200 ms, 5 warmups. The maintainer clarified that battery use
preceded plugging in; later run-boundary checks reported AC. Power settings were
not changed. Cold-start/concurrent/other-runtime/other-platform performance was
not established.

Representative second-run full-read means:

Input Original native blocks Pooled Pooled managed allocation/op
256 KiB 15.441 us 10.130 us 104 B
1 MiB 65.76 us 39.95 us 105 B
3 MiB 203.609 us 116.713 us 109 B
8 MiB 0.592 ms 0.396 ms 116 B
16 MiB 1.216 ms 0.800 ms 130 B
32 MiB 2.423 ms 2.054 ms 8 MiB
36 MiB 2.849 ms 2.628 ms 12 MiB
40 MiB 3.274 ms 3.433 ms 16 MiB
50 MiB 3.900 ms 4.942 ms 26 MiB
60 MiB 4.936 ms 7.768 ms 36 MiB
75 MiB 5.843 ms 9.844 ms 51 MiB
100 MiB 7.761 ms 10.748 ms 76 MiB
200 MiB 15.869 ms 33.937 ms 176 MiB

Managed allocation is allocation traffic, not live/peak/total memory.
MemoryDiagnoser excludes all native blocks/data and setup input arrays. The native
baseline's reported managed allocation was generally below 1.1 KiB/op; the 200 MiB
short-read baseline allocation was not reported, not proven zero. Full mean/error/SD,
ratios and short-read results are preserved in the companion measurement comment.

Recovering/reproducing

Restore the code from the frozen source or the fences below before running the
old pooled comparisons. Running them unchanged against the cleaned production
SKData.Create would no longer measure the old pooled implementation.

dotnet build -c Release benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*SKDataNativeStreamFallbackBenchmark*' --inProcess --iterationCount 12 --warmupCount 4 --iterationTime 150
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*New_PooledChunks*' '*Previous_HandRolledChunks*' --inProcess --iterationCount 15 --warmupCount 5 --iterationTime 200
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*New_PooledChunks*' '*DynamicStream_FilledChunks*' --inProcess --iterationCount 15 --warmupCount 5 --iterationTime 200
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*SKStreamCopyBufferSizeBenchmark*' --inProcess --iterationCount 15 --warmupCount 5 --iterationTime 200

Run each measurement twice in independent processes. The supplemental runner below
references the historical benchmark assembly/project and sets ThroughSKStream=false;
put it in a temporary console project with the same BenchmarkDotNet dependency and
native assets. Use SKDATA_BENCH_SIZES_MIB=1,8,16,32 or 40,50,75,200 with the paired
job settings, and 36,60 with refinement settings. Existing bootstrap/native assets
must match the binding; no native source changes were part of this investigation.

Recoverable source

binding/Binding.Shared/PooledByteBuffer.cs

SHA-256 of archived file: c634fe7cf4696f29d83386503adcc9c0a44f7002c28f7b0198019abc7ab9eec9.

#nullable disable

using System;
using System.Buffers;

#if HARFBUZZ
namespace HarfBuzzSharp;
#else
namespace SkiaSharp;
#endif

// Holds all buffers until disposal; pool reuse favors repeated, moderate-size input.
// Large inputs can outgrow pool retention and cause allocation/GC churn; consider native dynamic-stream staging instead.
// The crossover depends on runtime, memory pressure and concurrency, not a fixed size threshold.
internal ref struct PooledByteBuffer
{
	// An exact shared-pool bucket below the default LOH threshold; 80 KiB would rent 128 KiB.
	internal const int DataBufferSize = 64 * 1024;

	// Start with the shared pool's 16-entry bucket (~256 bytes of entries on 64-bit).
	// Those entries describe 1 MiB of data beyond the inline buffer.
	private const int InitialEntryBlockCapacity = 16;

	// Geometric entry-block growth reaches managed array-size limits before this directory fills.
	private const int MaxEntryBlocks = 32;

	private readonly ArrayPool<byte> pool;
	private BufferEntry firstEntry;

	// entryBlocks[block][entry].Buffer holds data; WrittenCount identifies its valid bytes.
	private BufferEntry[][] entryBlocks;
	private int entryBlockCount;
	private int lastBlockEntryCount;

	// Data buffers use the supplied pool; entry blocks use shared pools.
	internal PooledByteBuffer (ArrayPool<byte> pool)
	{
		this = default;
		this.pool = pool ?? throw new ArgumentNullException (nameof (pool));
	}

	// Committed bytes only, excluding unused data-buffer capacity.
	internal ulong Length { get; private set; }

	// Return writable space, renting another data buffer only when the current one is full.
	internal ArraySegment<byte> GetBuffer ()
	{
		if (pool == null)
			throw new InvalidOperationException ("The buffer has not been initialized.");

		// Keep the first entry inline so small inputs need no entry-block rental.
		if (firstEntry.Buffer == null) {
			firstEntry.Buffer = pool.Rent (DataBufferSize);
			return new ArraySegment<byte> (firstEntry.Buffer, 0, DataBufferSize);
		}

		// Reuse an existing buffer's unwritten tail before renting another one.
		if (entryBlockCount == 0 && firstEntry.WrittenCount < DataBufferSize)
			return new ArraySegment<byte> (firstEntry.Buffer, firstEntry.WrittenCount, DataBufferSize - firstEntry.WrittenCount);

		if (lastBlockEntryCount > 0) {
			var last = entryBlocks[entryBlockCount - 1][lastBlockEntryCount - 1];
			if (last.WrittenCount < DataBufferSize)
				return new ArraySegment<byte> (last.Buffer, last.WrittenCount, DataBufferSize - last.WrittenCount);
		}

		// Reserve bookkeeping space first so a failed growth cannot orphan a data-buffer rental.
		entryBlocks ??= ArrayPool<BufferEntry[]>.Shared.Rent (MaxEntryBlocks);
		if (entryBlockCount == 0 || lastBlockEntryCount == entryBlocks[entryBlockCount - 1].Length) {
			var previousCapacity = entryBlockCount == 0 ? 0 : entryBlocks[entryBlockCount - 1].Length;
			if (entryBlockCount == MaxEntryBlocks || previousCapacity > int.MaxValue / 2)
				throw new OutOfMemoryException ("The buffer contains too many data buffers.");

			// Like SegmentedArrayBuilder, append larger entry blocks without copying old entries.
			var capacity = previousCapacity == 0 ? InitialEntryBlockCapacity : previousCapacity * 2;
			var block = ArrayPool<BufferEntry>.Shared.Rent (capacity);
			entryBlocks[entryBlockCount++] = block;
			lastBlockEntryCount = 0;
		}

		var dataBuffer = pool.Rent (DataBufferSize);
		entryBlocks[entryBlockCount - 1][lastBlockEntryCount++] = new BufferEntry { Buffer = dataBuffer };

		// Ownership is recorded before writable storage is handed to the caller.
		return new ArraySegment<byte> (dataBuffer, 0, DataBufferSize);
	}

	// Commit bytes written into the range returned by GetBuffer.
	internal void Advance (int count)
	{
		if (firstEntry.Buffer == null || (entryBlockCount > 0 && lastBlockEntryCount == 0))
			throw new InvalidOperationException ("GetBuffer must be called before Advance.");

		var used = entryBlockCount == 0
			? firstEntry.WrittenCount
			: entryBlocks[entryBlockCount - 1][lastBlockEntryCount - 1].WrittenCount;

		if ((uint)count > (uint)(DataBufferSize - used))
			throw new ArgumentOutOfRangeException (nameof (count));

		// Check the total before changing either count, leaving state intact on overflow.
		var length = checked (Length + (ulong)count);
		if (entryBlockCount == 0)
			firstEntry.WrittenCount += count;
		else
			entryBlocks[entryBlockCount - 1][lastBlockEntryCount - 1].WrittenCount += count;

		Length = length;
	}

	// Expose the small-input fast path without enumerating entry blocks.
	internal bool TryGetSingleBuffer (out ArraySegment<byte> buffer)
	{
		if (firstEntry.Buffer != null && entryBlockCount == 0) {
			buffer = new ArraySegment<byte> (firstEntry.Buffer, 0, firstEntry.WrittenCount);
			return true;
		}

		buffer = default;
		return false;
	}

	// Enumerate committed ranges in order; borrowed ranges are valid until disposal.
	public Enumerator GetEnumerator () =>
		new Enumerator (firstEntry, entryBlocks, entryBlockCount, lastBlockEntryCount);

	// Return every data buffer and cleared entry block. Repeated disposal is harmless.
	public void Dispose ()
	{
		if (firstEntry.Buffer != null)
			pool.Return (firstEntry.Buffer);
		firstEntry = default;

		if (entryBlocks != null) {
			for (var i = 0; i < entryBlockCount; i++) {
				var block = entryBlocks[i];

				// Earlier blocks are full; the final block can have unused entry slots.
				var count = i == entryBlockCount - 1 ? lastBlockEntryCount : block.Length;
				for (var j = 0; j < count; j++)
					pool.Return (block[j].Buffer);

				// Pooled entry arrays must not keep returned data buffers alive.
				ArrayPool<BufferEntry>.Shared.Return (block, clearArray: true);
			}

			ArrayPool<BufferEntry[]>.Shared.Return (entryBlocks, clearArray: true);
		}

		entryBlocks = null;
		entryBlockCount = lastBlockEntryCount = 0;
		Length = 0;
	}

	internal struct BufferEntry
	{
		internal byte[] Buffer;
		internal int WrittenCount;
	}

	public ref struct Enumerator
	{
		private readonly BufferEntry firstEntry;
		private readonly BufferEntry[][] entryBlocks;
		private readonly int entryBlockCount;
		private readonly int lastBlockEntryCount;
		private int entryBlockIndex;
		private int entryIndex;

		// Capture the entry-block layout without allocating an enumerator object.
		internal Enumerator (BufferEntry firstEntry, BufferEntry[][] entryBlocks, int entryBlockCount, int lastBlockEntryCount)
		{
			this.firstEntry = firstEntry;
			this.entryBlocks = entryBlocks;
			this.entryBlockCount = entryBlockCount;
			this.lastBlockEntryCount = lastBlockEntryCount;

			entryBlockIndex = -1; // Visit the inline entry before entry block 0.
			entryIndex = 0;
			Current = default;
		}

		public ArraySegment<byte> Current { get; private set; }

		// Visit the inline entry, then each populated entry block.
		public bool MoveNext ()
		{
			if (entryBlockIndex == -1) {
				entryBlockIndex = 0;
				if (firstEntry.Buffer != null) {
					Current = new ArraySegment<byte> (firstEntry.Buffer, 0, firstEntry.WrittenCount);
					return true;
				}
			}

			while (entryBlockIndex < entryBlockCount) {
				var block = entryBlocks[entryBlockIndex];
				var count = entryBlockIndex == entryBlockCount - 1 ? lastBlockEntryCount : block.Length;

				if (entryIndex < count) {
					var entry = block[entryIndex++];
					Current = new ArraySegment<byte> (entry.Buffer, 0, entry.WrittenCount);
					return true;
				}

				entryBlockIndex++;
				entryIndex = 0;
			}

			Current = default;
			return false;
		}
	}
}
tests/Tests/SkiaSharp/PooledByteBufferTest.cs

SHA-256 of archived file: c7552a506823da90c563a96bab93ac659ec2554672b4035e1399031f7260c5f1.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using Xunit;

namespace SkiaSharp.Tests;

public class PooledByteBufferTest
{
	[Fact]
	public void EmptyBufferDoesNotRentPayload()
	{
		var pool = new TrackingPool();
		{
			using var buffer = new PooledByteBuffer(pool);
			Assert.Equal(0UL, buffer.Length);
			Assert.False(buffer.TryGetSingleBuffer(out _));
			var enumerator = buffer.GetEnumerator();
			Assert.False(enumerator.MoveNext());
		}
		Assert.Equal(0, pool.Rents);
		Assert.Equal(0, pool.Outstanding);
	}

	[Theory]
	[InlineData(false)]
	[InlineData(true)]
	public void PartialAdvancesReuseTheCurrentDataBuffer(bool afterFullFirstBuffer)
	{
		var pool = new TrackingPool();
		{
			using var buffer = new PooledByteBuffer(pool);
			if (afterFullFirstBuffer)
			{
				var prefix = buffer.GetBuffer();
				buffer.Advance(prefix.Count);
			}
			var first = buffer.GetBuffer();
			first.AsSpan().Slice(0, 17).Fill(42);
			buffer.Advance(17);
			var remaining = buffer.GetBuffer();
			Assert.Same(first.Array, remaining.Array);
			Assert.Equal(17, remaining.Offset);
			Assert.Equal(PooledByteBuffer.DataBufferSize - 17, remaining.Count);
			remaining.AsSpan().Slice(0, 3).Fill(84);
			buffer.Advance(3);

			Assert.Equal((ulong)(afterFullFirstBuffer ? PooledByteBuffer.DataBufferSize : 0) + 20, buffer.Length);
			Assert.Equal(!afterFullFirstBuffer, buffer.TryGetSingleBuffer(out var single));
			if (!afterFullFirstBuffer)
				Assert.Equal(20, single.Count);
			Assert.Equal(42, first.Array[16]);
			Assert.Equal(84, first.Array[17]);
			Assert.Equal(afterFullFirstBuffer ? 2 : 1, pool.Rents);
		}
		Assert.Equal(0, pool.Outstanding);
	}

	[Theory]
	[InlineData(1)]
	[InlineData(17)]
	[InlineData(18)]
	[InlineData(49)]
	[InlineData(50)]
	public void EnumerationPreservesDataAcrossEntryBlocks(int count)
	{
		var pool = new TrackingPool();
		{
			using var buffer = new PooledByteBuffer(pool);
			for (var i = 0; i < count; i++)
			{
				var chunk = buffer.GetBuffer();
				var length = i == count - 1 ? 7 : chunk.Count;
				chunk.AsSpan().Slice(0, length).Fill((byte)(i + 1));
				buffer.Advance(length);
			}
			Assert.Equal((ulong)(count - 1) * PooledByteBuffer.DataBufferSize + 7, buffer.Length);
			Assert.Equal(count == 1, buffer.TryGetSingleBuffer(out _));

			var expected = new byte[PooledByteBuffer.DataBufferSize];
			var index = 0;
			foreach (var chunk in buffer)
			{
				var length = index == count - 1 ? 7 : PooledByteBuffer.DataBufferSize;
				expected.AsSpan().Fill((byte)(index + 1));
				Assert.Equal(length, chunk.Count);
				Assert.True(chunk.AsSpan().SequenceEqual(expected.AsSpan(0, length)));
				index++;
			}
			Assert.Equal(count, index);
		}
		Assert.Equal(count, pool.Returns);
		Assert.Equal(0, pool.Outstanding);
	}

	[Theory]
	[InlineData(-1, 0)]
	[InlineData(PooledByteBuffer.DataBufferSize + 1, 0)]
	[InlineData(int.MaxValue, 0)]
	[InlineData(PooledByteBuffer.DataBufferSize, 1)]
	public void AdvanceRejectsInvalidCounts(int count, int alreadyWritten)
	{
		var pool = new TrackingPool();
		Assert.Throws<ArgumentOutOfRangeException>(() => AdvanceInvalid(pool, count, alreadyWritten));
		Assert.Equal(0, pool.Outstanding);
	}

	private static void AdvanceInvalid(TrackingPool pool, int count, int alreadyWritten)
	{
		using var buffer = new PooledByteBuffer(pool);
		buffer.GetBuffer();
		buffer.Advance(alreadyWritten);
		buffer.Advance(count);
	}

	[Fact]
	public void AdvanceRequiresABuffer()
	{
		Assert.Throws<InvalidOperationException>(AdvanceWithoutBuffer);

		static void AdvanceWithoutBuffer()
		{
			using var buffer = new PooledByteBuffer(ArrayPool<byte>.Shared);
			buffer.Advance(1);
		}
	}

	[Theory]
	[InlineData(1)]
	[InlineData(2)]
	[InlineData(18)]
	[InlineData(50)]
	public void FailedRentDoesNotLosePreviouslyOwnedBuffers(int failAtRent)
	{
		var pool = new TrackingPool { FailAtRent = failAtRent };
		Assert.Throws<IOException>(() => FillUntilFailure(pool, failAtRent));
		Assert.Equal(failAtRent - 1, pool.Returns);
		Assert.Equal(0, pool.Outstanding);
	}

	private static void FillUntilFailure(TrackingPool pool, int count)
	{
		using var buffer = new PooledByteBuffer(pool);
		for (var i = 0; i < count; i++)
		{
			var chunk = buffer.GetBuffer();
			buffer.Advance(chunk.Count);
		}
	}

	[Fact]
	public void DisposeReturnsEachPayloadOnceAndClearsTheOwner()
	{
		var pool = new TrackingPool();
		var buffer = new PooledByteBuffer(pool);
		buffer.GetBuffer();
		buffer.Advance(7);
		buffer.Dispose();
		buffer.Dispose();
		Assert.Equal(1, pool.Returns);
		Assert.Equal(0, pool.Outstanding);
		Assert.Equal(0UL, buffer.Length);
		Assert.False(buffer.TryGetSingleBuffer(out _));
		var enumerator = buffer.GetEnumerator();
		Assert.False(enumerator.MoveNext());
	}

	private sealed class TrackingPool : ArrayPool<byte>
	{
		private readonly HashSet<byte[]> outstanding = new();
		public int Rents { get; private set; }
		public int Returns { get; private set; }
		public int Outstanding => outstanding.Count;
		public int FailAtRent { get; set; }

		public override byte[] Rent(int minimumLength)
		{
			if (++Rents == FailAtRent)
				throw new IOException("Simulated pool exhaustion.");
			var array = new byte[minimumLength];
			Assert.True(outstanding.Add(array));
			return array;
		}

		public override void Return(byte[] array, bool clearArray = false)
		{
			Assert.True(outstanding.Remove(array), "A buffer was returned twice or was not owned.");
			Returns++;
		}
	}
}
benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKDataUnknownLengthStreamBenchmark.cs

SHA-256 of archived file: 6f8523f9c336f5ed3f839adbbf26e3d7f1a0cd4795570b359c53817f29e81a15.

using System;
using System.Buffers;
using System.IO;
using BenchmarkDotNet.Attributes;

namespace SkiaSharp.Benchmarks;

[MemoryDiagnoser]
public class SKDataUnknownLengthStreamBenchmark
{
	[Params(4096, 2097152, 3145728)]
	public int Size { get; set; }

	[Params(4096, int.MaxValue)]
	public int MaxRead { get; set; }

	[Params(false, true)]
	public bool SupportsSpan { get; set; }

	private LimitedReadStream stream;

	[GlobalSetup]
	public void Setup()
	{
		var bytes = new byte[Size];
		new Random(42).NextBytes(bytes);
		stream = new LimitedReadStream(bytes, MaxRead, SupportsSpan);
		using var old = CreateBuffered(stream, useArrayRead: false);
		stream.Position = 0;
		using var candidate = SKData.Create(stream);
		if (!candidate.AsSpan().SequenceEqual(bytes) || !candidate.AsSpan().SequenceEqual(old.AsSpan()))
			throw new InvalidOperationException("The benchmark implementations produced different data.");
		stream.Position = 0;
		using var filledChunks = CreateBufferedFilledChunks(stream);
		if (!filledChunks.AsSpan().SequenceEqual(bytes))
			throw new InvalidOperationException("The batched native stream produced different data.");
		stream.Position = 0;
		using var previous = CreateHandRolled(stream);
		if (!previous.AsSpan().SequenceEqual(bytes))
			throw new InvalidOperationException("The previous collector produced different data.");
	}

	[GlobalCleanup]
	public void Cleanup() => stream.Dispose();

	[Benchmark(Baseline = true)]
	public long Old_DynamicStream()
	{
		stream.Position = 0;
		using var data = CreateBuffered(stream, useArrayRead: false);
		return data.Size;
	}

	[Benchmark]
	public long DynamicStream_ArrayRead()
	{
		stream.Position = 0;
		using var data = CreateBuffered(stream, useArrayRead: true);
		return data.Size;
	}

	[Benchmark]
	public long New_PooledChunks()
	{
		stream.Position = 0;
		using var data = SKData.Create(stream);
		return data.Size;
	}

	[Benchmark]
	public long Previous_HandRolledChunks()
	{
		stream.Position = 0;
		using var data = CreateHandRolled(stream);
		return data.Size;
	}

	private static unsafe SKData CreateHandRolled(Stream source)
	{
		var chunks = Utils.RentArray<(byte[] Array, int Length)>(8);
		var chunkCount = 0;
		ulong totalLength = 0;
		try
		{
			while (true)
			{
				if (chunkCount == chunks.Length)
				{
					var expanded = Utils.RentArray<(byte[] Array, int Length)>(checked(chunkCount * 2));
					chunks.Span.CopyTo(expanded.Span);
					chunks.Span.Clear();
					chunks.Dispose();
					chunks = expanded;
				}
				var buffer = ArrayPool<byte>.Shared.Rent(SKData.UnknownLengthStreamChunkSize);
				chunks[chunkCount++] = (buffer, 0);
				var filled = 0;
				while (filled < SKData.UnknownLengthStreamChunkSize)
				{
					var toRead = SKData.UnknownLengthStreamChunkSize - filled;
					var read = source.Read(buffer, filled, toRead);
					if ((uint)read > (uint)toRead)
						throw new IOException("The stream returned an invalid byte count.");
					if (read == 0)
						break;
					filled += read;
				}
				chunks[chunkCount - 1] = (buffer, filled);
				totalLength = checked(totalLength + (ulong)filled);
				if (IntPtr.Size == 4 && totalLength > uint.MaxValue)
					throw new ArgumentOutOfRangeException("length");
				if (filled < SKData.UnknownLengthStreamChunkSize)
					break;
			}
			if (chunkCount == 1)
				return SKData.CreateCopy(chunks[0].Array, (ulong)chunks[0].Length);
			var data = SKData.Create(totalLength);
			if (data == null)
				return null;
			try
			{
				var dst = (byte*)data.Data;
				for (var i = 0; i < chunkCount; i++)
				{
					var (buffer, length) = chunks[i];
					new ReadOnlySpan<byte>(buffer, 0, length).CopyTo(new Span<byte>(dst, length));
					dst += length;
				}
				return data;
			}
			catch
			{
				data.Dispose();
				throw;
			}
		}
		finally
		{
			for (var i = 0; i < chunkCount; i++)
				ArrayPool<byte>.Shared.Return(chunks[i].Array);
			chunks.Span.Clear();
			chunks.Dispose();
		}
	}

	[Benchmark]
	public long DynamicStream_FilledChunks()
	{
		stream.Position = 0;
		using var data = CreateBufferedFilledChunks(stream);
		return data.Size;
	}

	private static SKData CreateBufferedFilledChunks(Stream source)
	{
		using var memory = new SKDynamicMemoryWStream();
		using var buffer = Utils.RentArray<byte>(SKData.UnknownLengthStreamChunkSize);
		while (true)
		{
			var filled = 0;
			while (filled < buffer.Length)
			{
				var toRead = buffer.Length - filled;
				var read = source.Read(buffer.Array, filled, toRead);
				if ((uint)read > (uint)toRead)
					throw new IOException("The stream returned an invalid byte count.");
				if (read == 0)
					break;
				filled += read;
			}
			if (!memory.Write(buffer.Array, filled))
				return null;
			if (filled < buffer.Length)
				break;
		}
		return memory.DetachAsData();
	}

	private static SKData CreateBuffered(Stream source, bool useArrayRead)
	{
		using var memory = new SKDynamicMemoryWStream();
		using var buffer = Utils.RentArray<byte>(SKData.CopyBufferSize);
		while (true)
		{
			var read = useArrayRead
				? source.Read(buffer.Array, 0, buffer.Length)
				: source.Read(buffer.Span);
			if ((uint)read > (uint)buffer.Length)
				throw new IOException("The stream returned an invalid byte count.");
			if (read == 0)
				break;
			if (!memory.Write(buffer.Array, read))
				return null;
		}
		return memory.DetachAsData();
	}

	private sealed class LimitedReadStream : Stream
	{
		private readonly MemoryStream inner;
		private readonly int maxRead;
		private readonly bool supportsSpan;

		public LimitedReadStream(byte[] bytes, int maxRead, bool supportsSpan)
		{
			inner = new MemoryStream(bytes, writable: false);
			this.maxRead = maxRead;
			this.supportsSpan = supportsSpan;
		}

		public override bool CanRead => true;
		public override bool CanSeek => false;
		public override bool CanWrite => false;
		public override long Length => throw new NotSupportedException();
		public override long Position { get => inner.Position; set => inner.Position = value; }
		public override void Flush() => throw new NotSupportedException();
		public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
		public override void SetLength(long value) => throw new NotSupportedException();
		public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();

		public override int Read(byte[] buffer, int offset, int count) =>
			inner.Read(buffer, offset, Math.Min(count, maxRead));

		public override int Read(Span<byte> buffer) =>
			supportsSpan
				? inner.Read(buffer.Slice(0, Math.Min(buffer.Length, maxRead)))
				: base.Read(buffer);

		protected override void Dispose(bool disposing)
		{
			if (disposing)
				inner.Dispose();
			base.Dispose(disposing);
		}
	}
}
benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKDataNativeStreamFallbackBenchmark.cs

SHA-256 of archived file: 59895a0785dd3eac7023d5d4dbeb9a3101ca659b54ccf95b547e8d17089147e0.

using System;
using System.Buffers;
using System.IO;
using BenchmarkDotNet.Attributes;

namespace SkiaSharp.Benchmarks;

// Compare the same buffering strategies through direct Stream reads or a forward-only SKManagedStream.
// MemoryDiagnoser reports managed allocations only; the baseline also allocates native blocks/data.
[MemoryDiagnoser]
public unsafe class SKDataNativeStreamFallbackBenchmark
{
	[Params(4096, 256 * 1024, 3 * 1024 * 1024, 100 * 1024 * 1024)]
	public int Size { get; set; }

	[Params(4096, int.MaxValue)]
	public int MaxRead { get; set; }

	[Params(false, true)]
	public bool ThroughSKStream { get; set; }

	private LimitedReadStream source;
	private SKManagedStream nativeStream;

	[GlobalSetup]
	public void Setup()
	{
		var bytes = new byte[Size];
		new Random(42).NextBytes(bytes);
		source = new LimitedReadStream(bytes, MaxRead);
		nativeStream = ThroughSKStream ? new SKManagedStream(source) : null;
		if (nativeStream != null && (nativeStream.HasLength || nativeStream.HasPosition))
			throw new InvalidOperationException("The benchmark must exercise the unknown-length fallback.");

		using var old = ThroughSKStream ? CreateNativeBlocks(nativeStream) : CreateNativeBlocks(source);
		source.Position = 0;
		using var candidate = ThroughSKStream ? CreatePooledCandidate(nativeStream) : SKData.Create(source);
		if (!old.AsSpan().SequenceEqual(bytes) || !candidate.AsSpan().SequenceEqual(bytes))
			throw new InvalidOperationException("The fallback implementations produced different data.");
	}

	[GlobalCleanup]
	public void Cleanup()
	{
		nativeStream?.Dispose();
		source.Dispose();
	}

	[Benchmark(Baseline = true)]
	public long Old_NativeBlocks()
	{
		source.Position = 0;
		using var data = ThroughSKStream ? CreateNativeBlocks(nativeStream) : CreateNativeBlocks(source);
		return data.Size;
	}

	[Benchmark]
	public long Candidate_PooledBuffers()
	{
		source.Position = 0;
		using var data = ThroughSKStream ? CreatePooledCandidate(nativeStream) : SKData.Create(source);
		return data.Size;
	}

	private static SKData CreateNativeBlocks(Stream stream)
	{
		// Original managed-stream implementation: the wrapper's CopyTo reads its underlying Stream directly.
		using var memory = new SKDynamicMemoryWStream();
		using (var managed = new SKManagedStream(stream))
		{
			managed.CopyTo(memory);
		}
		return memory.DetachAsData();
	}

	private static SKData CreateNativeBlocks(SKStream stream)
	{
		if (stream.HasLength && stream.HasPosition)
			throw new InvalidOperationException("Expected an unknown-length stream.");

		using var memory = new SKDynamicMemoryWStream();
		using var buffer = Utils.RentArray<byte>(SKData.CopyBufferSize);
		int read;
		while ((read = stream.Read(buffer.Array, buffer.Length)) > 0)
		{
			if (!memory.Write(buffer.Array, read))
				return null;
		}
		return memory.DetachAsData();
	}

	// Benchmark-only: SharedArrayPool staging regresses on large inputs; production keeps native blocks.
	private static SKData CreatePooledCandidate(SKStream stream)
	{
		if (stream.HasLength && stream.HasPosition)
			throw new InvalidOperationException("Expected an unknown-length stream.");

		using var chunks = new PooledByteBuffer(ArrayPool<byte>.Shared);
		while (true)
		{
			var buffer = chunks.GetBuffer();
			var filled = 0;
			fixed (byte* ptr = buffer.Array)
			{
				while (filled < buffer.Count)
				{
					var toRead = buffer.Count - filled;
					var read = stream.Read((IntPtr)(ptr + buffer.Offset + filled), toRead);
					if ((uint)read > (uint)toRead)
						throw new IOException("The stream returned an invalid byte count.");
					if (read == 0)
						break;
					filled += read;
				}
			}
			chunks.Advance(filled);
			if (IntPtr.Size == 4 && chunks.Length > uint.MaxValue)
				throw new ArgumentOutOfRangeException("length");
			if (filled < buffer.Count)
				break;
		}

		if (chunks.TryGetSingleBuffer(out var single))
			return SKData.CreateCopy(single.Array, (ulong)single.Count);

		var data = SKData.Create(chunks.Length);
		if (data == null)
			return null;
		try
		{
			var dst = (byte*)data.Data;
			foreach (var buffer in chunks)
			{
				buffer.AsSpan().CopyTo(new Span<byte>(dst, buffer.Count));
				dst += buffer.Count;
			}
			return data;
		}
		catch
		{
			data.Dispose();
			throw;
		}
	}

	private sealed class LimitedReadStream : MemoryStream
	{
		private readonly int maxRead;

		public LimitedReadStream(byte[] bytes, int maxRead)
			: base(bytes, writable: false)
		{
			this.maxRead = maxRead;
		}

		public override bool CanSeek => false;

		public override int Read(byte[] buffer, int offset, int count) =>
			base.Read(buffer, offset, Math.Min(count, maxRead));
	}
}
benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKStreamCopyBufferSizeBenchmark.cs

SHA-256 of archived file: f606ff4d61173c3a4d2263a82bae6eabde990657e00cb19b353355ee01922bcc.

using System;
using System.IO;
using BenchmarkDotNet.Attributes;

namespace SkiaSharp.Benchmarks;

[MemoryDiagnoser]
public unsafe class SKStreamCopyBufferSizeBenchmark
{
	[Params(64 * 1024, 80 * 1024, 128 * 1024)]
	public int BufferSize { get; set; }

	[Params(2 * 1024 * 1024, 3 * 1024 * 1024)]
	public int Size { get; set; }

	// Exercise both copy mechanisms on the current runtime, not a different legacy runtime.
	[Params(false, true)]
	public bool UseArrayBuffer { get; set; }

	private MemoryStream source;
	private MemoryStream destination;
	private FileStream file;
	private string filename;
	private SKData data;

	[GlobalSetup]
	public void Setup()
	{
		var bytes = new byte[Size];
		new Random(42).NextBytes(bytes);
		source = new MemoryStream(bytes, writable: false);
		destination = new MemoryStream(Size);
		data = SKData.Create(Size);
		filename = Path.Combine(Path.GetTempPath(), $"skiasharp-buffer-{Guid.NewGuid():N}.bin");
		File.WriteAllBytes(filename, bytes);
		file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read,
			bufferSize: 4096, FileOptions.SequentialScan);

		ReadMemory();
		if (!data.AsSpan().SequenceEqual(bytes))
			throw new InvalidOperationException("The memory read produced different data.");
		ReadFile();
		if (!data.AsSpan().SequenceEqual(bytes))
			throw new InvalidOperationException("The file read produced different data.");
		WriteMemory();
		if (!destination.GetBuffer().AsSpan(0, Size).SequenceEqual(bytes))
			throw new InvalidOperationException("The write produced different data.");
	}

	[GlobalCleanup]
	public void Cleanup()
	{
		file.Dispose();
		File.Delete(filename);
		source.Dispose();
		destination.Dispose();
		data.Dispose();
	}

	[Benchmark]
	public long ReadMemory()
	{
		source.Position = 0;
		return Read(source);
	}

	[Benchmark]
	public long ReadFile()
	{
		file.Position = 0;
		return Read(file);
	}

	private long Read(Stream stream)
	{
		using var scratch = UseArrayBuffer ? Utils.RentArray<byte>(BufferSize) : default;
		var dst = (byte*)data.Data;
		var remaining = Size;
		while (remaining > 0)
		{
			var count = Math.Min(remaining, BufferSize);
			var read = UseArrayBuffer
				? stream.Read(scratch.Array, 0, count)
				: stream.Read(new Span<byte>(dst, count));
			if ((uint)read > (uint)count)
				throw new IOException("The stream returned an invalid byte count.");
			if (read == 0)
				throw new EndOfStreamException();
			if (UseArrayBuffer)
				scratch.Span.Slice(0, read).CopyTo(new Span<byte>(dst, read));
			dst += read;
			remaining -= read;
		}
		return Size - remaining;
	}

	[Benchmark]
	public long WriteMemory()
	{
		destination.Position = 0;
		using var scratch = UseArrayBuffer ? Utils.RentArray<byte>(BufferSize) : default;
		var src = (byte*)data.Data;
		for (var remaining = Size; remaining > 0;)
		{
			var count = Math.Min(remaining, BufferSize);
			var span = new ReadOnlySpan<byte>(src, count);
			if (UseArrayBuffer)
			{
				span.CopyTo(scratch.Span);
				destination.Write(scratch.Array, 0, count);
			}
			else
			{
				destination.Write(span);
			}
			src += count;
			remaining -= count;
		}
		return destination.Position;
	}
}
benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKManagedWStreamCopyBenchmark.cs

SHA-256 of archived file: 6244231d7ff43a9368b654a6e8229599e9f2776d3b2135a930926c676991e7ae.

using System;
using System.IO;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;

namespace SkiaSharp.Benchmarks;

[MemoryDiagnoser]
public unsafe class SKManagedWStreamCopyBenchmark
{
	[Params(4096, 2097152, 3145728)]
	public int Size { get; set; }

	private SKData data;
	private MemoryStream destination;
	private SKManagedWStream current;
	private BufferedManagedWStream buffered;

	[GlobalSetup]
	public void Setup()
	{
		var bytes = new byte[Size];
		new Random(42).NextBytes(bytes);
		data = SKData.CreateCopy(bytes);
		destination = new MemoryStream(Size);
		current = new SKManagedWStream(destination);
		buffered = new BufferedManagedWStream(destination);
		Old_Buffered();
		if (!destination.GetBuffer().AsSpan(0, Size).SequenceEqual(bytes))
			throw new InvalidOperationException("The buffered write produced different data.");
		Current_DirectSpan();
		if (!destination.GetBuffer().AsSpan(0, Size).SequenceEqual(bytes))
			throw new InvalidOperationException("The span write produced different data.");
	}

	[GlobalCleanup]
	public void Cleanup()
	{
		buffered.Dispose();
		current.Dispose();
		destination.Dispose();
		data.Dispose();
	}

	[Benchmark(Baseline = true)]
	public long Old_Buffered()
	{
		destination.Position = 0;
		if (!SkiaApi.sk_wstream_write(buffered.Handle, (void*)data.Data, (IntPtr)Size))
			throw new IOException("The buffered write failed.");
		return destination.Position;
	}

	[Benchmark]
	public long Current_DirectSpan()
	{
		destination.Position = 0;
		if (!SkiaApi.sk_wstream_write(current.Handle, (void*)data.Data, (IntPtr)Size))
			throw new IOException("The span write failed.");
		return destination.Position;
	}

	private sealed class BufferedManagedWStream : SKAbstractManagedWStream
	{
		private readonly MemoryStream destination;

		public BufferedManagedWStream(MemoryStream destination)
		{
			this.destination = destination;
		}

		protected internal override bool OnWrite(IntPtr buffer, IntPtr size)
		{
			var count = (int)size;
			using var rented = Utils.RentArray<byte>(count);
			Marshal.Copy(buffer, rented.Array, 0, count);
			destination.Write(rented.Array, 0, count);
			return true;
		}

		protected internal override void OnFlush() => destination.Flush();

		protected internal override IntPtr OnBytesWritten() => (IntPtr)destination.Position;
	}
}
Deferred SKData collector and benchmark constant
using System.Buffers;

// Inside SKData (restore this alias for the archived comparison benchmarks):
internal const int UnknownLengthStreamChunkSize = PooledByteBuffer.DataBufferSize;

private static SKData CreateFromUnknownLengthStream (Stream stream)
		{
			// Keep the bytes in pooled chunks until their total length is known, then copy once into SKData.
			using var chunks = new PooledByteBuffer (ArrayPool<byte>.Shared);
			while (true) {
				var buffer = chunks.GetBuffer ();
				var filled = 0;
				while (filled < buffer.Count) {
					var toRead = buffer.Count - filled;
					var readLen = stream.Read (buffer.Array, buffer.Offset + filled, toRead);
					if ((uint)readLen > (uint)toRead)
						throw new IOException ("The stream returned an invalid byte count.");
					if (readLen == 0)
						break;
					filled += readLen;
				}

				chunks.Advance (filled);
				if (!PlatformConfiguration.Is64Bit && chunks.Length > UInt32.MaxValue)
					throw new ArgumentOutOfRangeException ("length", "The length exceeds the size of pointers.");
				if (filled < buffer.Count)
					break;
			}

			if (chunks.TryGetSingleBuffer (out var single))
				return CreateCopy (single.Array, (ulong)single.Count);

			var data = Create (chunks.Length);
			if (data == null)
				return null;
			try {
				var dst = (byte*)data.Data;
				foreach (var buffer in chunks) {
					new ReadOnlySpan<byte> (buffer.Array, buffer.Offset, buffer.Count).CopyTo (new Span<byte> (dst, buffer.Count));
					dst += buffer.Count;
				}
				return data;
			} catch {
				data.Dispose ();
				throw;
			}
		}
Supplemental realistic-size/crossover runner
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using SkiaSharp.Benchmarks;

BenchmarkSwitcher.FromTypes([typeof(AssetSizeStreamBufferingBenchmark)]).Run(args);

[MemoryDiagnoser]
public class AssetSizeStreamBufferingBenchmark
{
    [ParamsSource(nameof(Sizes))]
    public int Size { get; set; }

    public IEnumerable<int> Sizes =>
        (Environment.GetEnvironmentVariable("SKDATA_BENCH_SIZES_MIB") ?? "1,8,16,32")
        .Split(',')
        .Select(size => checked(int.Parse(size) * 1024 * 1024));

    [Params(4096, int.MaxValue)]
    public int MaxRead { get; set; }

    private SKDataNativeStreamFallbackBenchmark comparison = null!;

    [GlobalSetup]
    public void Setup()
    {
        comparison = new()
        {
            Size = Size,
            MaxRead = MaxRead,
            ThroughSKStream = false,
        };
        comparison.Setup();
    }

    [GlobalCleanup]
    public void Cleanup() => comparison.Cleanup();

    [Benchmark(Baseline = true)]
    public long Original_NativeBlocks() => comparison.Old_NativeBlocks();

    [Benchmark]
    public long Current_PooledBuffers() => comparison.Candidate_PooledBuffers();
}

@mattleibow

Copy link
Copy Markdown
Contributor Author

Deferred buffering measurements

Companion to the recoverable-code/research archive on this PR. These are historical pre-cleanup results, not claims about the cleaned implementation. Each fold includes the original BenchmarkDotNet job metadata, mean/error/SD, ratios and managed-only allocation measurements. Native allocations and setup input arrays are excluded; a dash/NA is not a proof of zero native or total memory.

Original managed/SKStream paired comparison, run 1
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=12  IterationTime=150.0000 ms  
WarmupCount=4  
Method Size MaxRead ThroughSKStream Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Old_NativeBlocks 4096 4096 False 785.8 ns 14.50 ns 11.32 ns 1.00 0.00 0.0515 - - 448 B 1.00
Candidate_PooledBuffers 4096 4096 False 271.8 ns 4.59 ns 3.32 ns 0.35 0.00 0.0112 - - 104 B 0.23
Old_NativeBlocks 4096 4096 True 609.4 ns 4.61 ns 3.60 ns 1.00 0.00 0.0243 - - 208 B 1.00
Candidate_PooledBuffers 4096 4096 True 390.0 ns 6.61 ns 4.78 ns 0.64 0.01 0.0103 - - 104 B 0.50
Old_NativeBlocks 4096 2147483647 False 774.7 ns 11.39 ns 8.89 ns 1.00 0.00 0.0514 - - 448 B 1.00
Candidate_PooledBuffers 4096 2147483647 False 282.8 ns 8.17 ns 6.38 ns 0.37 0.01 0.0111 - - 104 B 0.23
Old_NativeBlocks 4096 2147483647 True 634.3 ns 21.78 ns 17.01 ns 1.00 0.00 0.0244 - - 208 B 1.00
Candidate_PooledBuffers 4096 2147483647 True 406.7 ns 14.68 ns 10.61 ns 0.64 0.03 0.0111 - - 104 B 0.50
Old_NativeBlocks 262144 4096 False 16,783.7 ns 136.72 ns 98.86 ns 1.00 0.00 - - - 449 B 1.00
Candidate_PooledBuffers 262144 4096 False 11,260.7 ns 286.75 ns 223.87 ns 0.67 0.02 - - - 104 B 0.23
Old_NativeBlocks 262144 4096 True 20,916.5 ns 227.78 ns 177.84 ns 1.00 0.00 - - - 209 B 1.00
Candidate_PooledBuffers 262144 4096 True 15,840.3 ns 140.85 ns 109.97 ns 0.76 0.01 - - - 105 B 0.50
Old_NativeBlocks 262144 2147483647 False 15,554.1 ns 141.75 ns 110.67 ns 1.00 0.00 - - - 449 B 1.00
Candidate_PooledBuffers 262144 2147483647 False 10,153.4 ns 118.66 ns 92.64 ns 0.65 0.01 - - - 104 B 0.23
Old_NativeBlocks 262144 2147483647 True 18,965.9 ns 250.78 ns 195.80 ns 1.00 0.00 - - - 209 B 1.00
Candidate_PooledBuffers 262144 2147483647 True 16,669.5 ns 195.11 ns 152.33 ns 0.88 0.01 - - - 105 B 0.50
Old_NativeBlocks 3145728 4096 False 193,952.7 ns 2,734.19 ns 2,134.68 ns 1.00 0.00 - - - 456 B 1.00
Candidate_PooledBuffers 3145728 4096 False 134,195.1 ns 1,765.87 ns 1,276.84 ns 0.69 0.01 - - - 109 B 0.24
Old_NativeBlocks 3145728 4096 True 242,969.2 ns 2,299.05 ns 1,794.95 ns 1.00 0.00 - - - 218 B 1.00
Candidate_PooledBuffers 3145728 4096 True 184,927.2 ns 1,115.64 ns 806.68 ns 0.76 0.01 - - - 111 B 0.51
Old_NativeBlocks 3145728 2147483647 False 204,578.3 ns 2,013.49 ns 1,572.00 ns 1.00 0.00 - - - 456 B 1.00
Candidate_PooledBuffers 3145728 2147483647 False 117,205.2 ns 651.80 ns 508.88 ns 0.57 0.00 - - - 109 B 0.24
Old_NativeBlocks 3145728 2147483647 True 242,592.5 ns 1,647.54 ns 1,286.29 ns 1.00 0.00 - - - 218 B 1.00
Candidate_PooledBuffers 3145728 2147483647 True 188,711.6 ns 1,026.97 ns 801.79 ns 0.78 0.01 - - - 112 B 0.51
Old_NativeBlocks 104857600 4096 False 10,084,395.4 ns 174,542.17 ns 136,271.05 ns 1.00 0.00 - - - 852 B 1.00
Candidate_PooledBuffers 104857600 4096 False 11,691,347.2 ns 108,831.15 ns 84,968.20 ns 1.16 0.01 10416.6667 5416.6667 1166.6667 79730593 B 93,580.51
Old_NativeBlocks 104857600 4096 True 11,032,079.1 ns 272,091.39 ns 212,431.06 ns 1.00 0.00 - - - 674 B 1.00
Candidate_PooledBuffers 104857600 4096 True 13,829,619.3 ns 208,874.06 ns 151,029.63 ns 1.25 0.03 10400.0000 5400.0000 1100.0000 79796259 B 118,392.08
Old_NativeBlocks 104857600 2147483647 False 7,719,936.3 ns 79,177.69 ns 57,250.66 ns 1.00 0.00 - - - 638 B 1.00
Candidate_PooledBuffers 104857600 2147483647 False 10,481,657.3 ns 94,171.60 ns 73,522.99 ns 1.36 0.01 10437.5000 5437.5000 1250.0000 79730461 B 124,969.37
Old_NativeBlocks 104857600 2147483647 True 9,132,385.1 ns 98,017.64 ns 58,328.72 ns 1.00 0.00 - - - 587 B 1.00
Candidate_PooledBuffers 104857600 2147483647 True 13,000,827.1 ns 114,034.46 ns 89,030.60 ns 1.43 0.01 10400.0000 5400.0000 1100.0000 79796259 B 135,939.11
Original managed/SKStream paired comparison, run 2
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=12  IterationTime=150.0000 ms  
WarmupCount=4  
Method Size MaxRead ThroughSKStream Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Old_NativeBlocks 4096 4096 False 768.1 ns 13.69 ns 10.69 ns 1.00 0.00 0.0495 - - 448 B 1.00
Candidate_PooledBuffers 4096 4096 False 279.5 ns 5.84 ns 4.56 ns 0.36 0.01 0.0114 - - 104 B 0.23
Old_NativeBlocks 4096 4096 True 616.0 ns 8.56 ns 6.68 ns 1.00 0.00 0.0242 - - 208 B 1.00
Candidate_PooledBuffers 4096 4096 True 387.6 ns 4.51 ns 3.26 ns 0.63 0.01 0.0104 - - 104 B 0.50
Old_NativeBlocks 4096 2147483647 False 779.2 ns 20.67 ns 16.14 ns 1.00 0.00 0.0515 - - 448 B 1.00
Candidate_PooledBuffers 4096 2147483647 False 292.8 ns 6.38 ns 4.22 ns 0.38 0.01 0.0115 - - 104 B 0.23
Old_NativeBlocks 4096 2147483647 True 627.0 ns 11.87 ns 9.27 ns 1.00 0.00 0.0245 - - 208 B 1.00
Candidate_PooledBuffers 4096 2147483647 True 388.7 ns 7.55 ns 5.90 ns 0.62 0.02 0.0104 - - 104 B 0.50
Old_NativeBlocks 262144 4096 False 16,774.3 ns 118.31 ns 92.37 ns 1.00 0.00 - - - 449 B 1.00
Candidate_PooledBuffers 262144 4096 False 11,416.5 ns 54.56 ns 39.45 ns 0.68 0.00 - - - 104 B 0.23
Old_NativeBlocks 262144 4096 True 20,987.1 ns 117.47 ns 91.72 ns 1.00 0.00 - - - 209 B 1.00
Candidate_PooledBuffers 262144 4096 True 15,928.5 ns 81.62 ns 63.72 ns 0.76 0.00 - - - 105 B 0.50
Old_NativeBlocks 262144 2147483647 False 15,440.6 ns 178.51 ns 139.37 ns 1.00 0.00 - - - 449 B 1.00
Candidate_PooledBuffers 262144 2147483647 False 10,130.0 ns 470.36 ns 367.23 ns 0.66 0.02 - - - 104 B 0.23
Old_NativeBlocks 262144 2147483647 True 20,684.3 ns 334.61 ns 261.24 ns 1.00 0.00 - - - 209 B 1.00
Candidate_PooledBuffers 262144 2147483647 True 16,032.7 ns 68.50 ns 53.48 ns 0.78 0.01 - - - 105 B 0.50
Old_NativeBlocks 3145728 4096 False 196,917.5 ns 3,784.22 ns 2,954.47 ns 1.00 0.00 - - - 456 B 1.00
Candidate_PooledBuffers 3145728 4096 False 129,516.1 ns 1,248.06 ns 902.43 ns 0.66 0.01 - - - 109 B 0.24
Old_NativeBlocks 3145728 4096 True 243,089.4 ns 2,510.78 ns 1,960.26 ns 1.00 0.00 - - - 218 B 1.00
Candidate_PooledBuffers 3145728 4096 True 181,401.4 ns 1,219.15 ns 951.83 ns 0.75 0.01 - - - 111 B 0.51
Old_NativeBlocks 3145728 2147483647 False 203,609.4 ns 869.06 ns 678.51 ns 1.00 0.00 - - - 456 B 1.00
Candidate_PooledBuffers 3145728 2147483647 False 116,713.4 ns 1,526.67 ns 1,191.92 ns 0.57 0.01 - - - 109 B 0.24
Old_NativeBlocks 3145728 2147483647 True 240,335.9 ns 3,681.98 ns 2,874.64 ns 1.00 0.00 - - - 217 B 1.00
Candidate_PooledBuffers 3145728 2147483647 True 190,951.7 ns 1,844.78 ns 1,440.28 ns 0.79 0.01 - - - 112 B 0.52
Old_NativeBlocks 104857600 4096 False 10,262,219.4 ns 131,853.83 ns 87,213.15 ns 1.00 0.00 - - - 852 B 1.00
Candidate_PooledBuffers 104857600 4096 False 11,767,740.1 ns 186,468.42 ns 134,828.88 ns 1.15 0.02 10384.6154 5461.5385 1230.7692 79730783 B 93,580.73
Old_NativeBlocks 104857600 4096 True 11,110,393.6 ns 136,556.57 ns 98,739.35 ns 1.00 0.00 - - - 674 B 1.00
Candidate_PooledBuffers 104857600 4096 True 13,966,476.0 ns 168,731.14 ns 131,734.18 ns 1.26 0.02 10400.0000 5400.0000 1100.0000 79796259 B 118,392.08
Old_NativeBlocks 104857600 2147483647 False 7,761,136.6 ns 104,810.74 ns 75,785.03 ns 1.00 0.00 - - - 767 B 1.00
Candidate_PooledBuffers 104857600 2147483647 False 10,748,254.5 ns 119,185.35 ns 93,052.08 ns 1.39 0.02 10437.5000 5437.5000 1250.0000 79730461 B 103,951.06
Old_NativeBlocks 104857600 2147483647 True 9,240,099.2 ns 106,762.44 ns 83,353.09 ns 1.00 0.00 - - - 587 B 1.00
Candidate_PooledBuffers 104857600 2147483647 True 13,259,162.9 ns 202,630.52 ns 146,515.14 ns 1.44 0.02 10400.0000 5400.0000 1100.0000 79796259 B 135,939.11
1/8/16/32 MiB managed comparison, run 1
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=12  IterationTime=150.0000 ms  
WarmupCount=4  
Method Size MaxRead Mean Error StdDev Ratio RatioSD Gen0 Gen1 Allocated Alloc Ratio
Original_NativeBlocks 1048576 4096 67.60 μs 0.886 μs 0.692 μs 1.00 0.00 - - 450 B 1.00
Current_PooledBuffers 1048576 4096 42.26 μs 0.496 μs 0.387 μs 0.63 0.01 - - 106 B 0.24
Original_NativeBlocks 1048576 2147483647 62.90 μs 0.940 μs 0.680 μs 1.00 0.00 - - 450 B 1.00
Current_PooledBuffers 1048576 2147483647 38.57 μs 0.838 μs 0.606 μs 0.61 0.01 - - 105 B 0.23
Original_NativeBlocks 8388608 4096 681.03 μs 12.972 μs 10.128 μs 1.00 0.00 - - 471 B 1.00
Current_PooledBuffers 8388608 4096 388.79 μs 13.685 μs 9.895 μs 0.57 0.02 - - 117 B 0.25
Original_NativeBlocks 8388608 2147483647 576.62 μs 16.378 μs 11.842 μs 1.00 0.00 - - 467 B 1.00
Current_PooledBuffers 8388608 2147483647 353.50 μs 4.051 μs 3.163 μs 0.61 0.02 - - 116 B 0.25
Original_NativeBlocks 16777216 4096 1,484.64 μs 45.366 μs 30.007 μs 1.00 0.00 - - 493 B 1.00
Current_PooledBuffers 16777216 4096 902.89 μs 12.396 μs 8.199 μs 0.61 0.01 - - 136 B 0.28
Original_NativeBlocks 16777216 2147483647 1,209.36 μs 10.430 μs 8.143 μs 1.00 0.00 - - 488 B 1.00
Current_PooledBuffers 16777216 2147483647 797.59 μs 15.704 μs 11.355 μs 0.66 0.01 - - 130 B 0.27
Original_NativeBlocks 33554432 4096 3,184.48 μs 60.939 μs 40.307 μs 1.00 0.00 - - 553 B 1.00
Current_PooledBuffers 33554432 4096 2,407.34 μs 54.704 μs 42.709 μs 0.76 0.02 1000.0000 500.0000 8391863 B 15,175.16
Original_NativeBlocks 33554432 2147483647 2,417.23 μs 31.717 μs 22.933 μs 1.00 0.00 - - 527 B 1.00
Current_PooledBuffers 33554432 2147483647 2,039.94 μs 47.682 μs 34.477 μs 0.84 0.02 1000.0000 500.0000 8391847 B 15,923.81
1/8/16/32 MiB managed comparison, run 2
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=12  IterationTime=150.0000 ms  
WarmupCount=4  
Method Size MaxRead Mean Error StdDev Ratio RatioSD Gen0 Gen1 Allocated Alloc Ratio
Original_NativeBlocks 1048576 4096 66.20 μs 0.421 μs 0.329 μs 1.00 0.00 - - 450 B 1.00
Current_PooledBuffers 1048576 4096 44.56 μs 0.714 μs 0.472 μs 0.67 0.01 - - 105 B 0.23
Original_NativeBlocks 1048576 2147483647 65.76 μs 0.478 μs 0.373 μs 1.00 0.00 - - 450 B 1.00
Current_PooledBuffers 1048576 2147483647 39.95 μs 0.248 μs 0.193 μs 0.61 0.01 - - 105 B 0.23
Original_NativeBlocks 8388608 4096 702.64 μs 24.773 μs 16.386 μs 1.00 0.00 - - 471 B 1.00
Current_PooledBuffers 8388608 4096 403.41 μs 8.825 μs 6.890 μs 0.58 0.02 - - 117 B 0.25
Original_NativeBlocks 8388608 2147483647 591.74 μs 10.409 μs 8.127 μs 1.00 0.00 - - 468 B 1.00
Current_PooledBuffers 8388608 2147483647 395.97 μs 31.900 μs 24.906 μs 0.67 0.04 - - 116 B 0.25
Original_NativeBlocks 16777216 4096 1,486.20 μs 41.018 μs 32.024 μs 1.00 0.00 - - 493 B 1.00
Current_PooledBuffers 16777216 4096 961.95 μs 88.557 μs 64.033 μs 0.65 0.05 - - 133 B 0.27
Original_NativeBlocks 16777216 2147483647 1,216.27 μs 9.761 μs 7.621 μs 1.00 0.00 - - 488 B 1.00
Current_PooledBuffers 16777216 2147483647 800.21 μs 15.829 μs 12.359 μs 0.66 0.01 - - 130 B 0.27
Original_NativeBlocks 33554432 4096 3,218.66 μs 47.255 μs 36.893 μs 1.00 0.00 - - 553 B 1.00
Current_PooledBuffers 33554432 4096 2,407.01 μs 49.468 μs 38.621 μs 0.75 0.02 1000.0000 500.0000 8391863 B 15,175.16
Original_NativeBlocks 33554432 2147483647 2,423.25 μs 11.570 μs 7.653 μs 1.00 0.00 - - 527 B 1.00
Current_PooledBuffers 33554432 2147483647 2,053.65 μs 29.911 μs 21.628 μs 0.85 0.01 1000.0000 500.0000 8391847 B 15,923.81
40/50/75/200 MiB managed comparison, run 1
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=12  IterationTime=150.0000 ms  
WarmupCount=4  
Method MaxRead Size Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Original_NativeBlocks 4096 41943040 4.139 ms 0.1981 ms 0.1433 ms 1.00 0.00 - - - 539 B 1.00
Current_PooledBuffers 4096 41943040 3.703 ms 0.1389 ms 0.1005 ms 0.90 0.04 2375.0000 1375.0000 375.0000 16788477 B 31,147.45
Original_NativeBlocks 4096 52428800 5.136 ms 0.1787 ms 0.1395 ms 1.00 0.00 - - - 606 B 1.00
Current_PooledBuffers 4096 52428800 5.310 ms 0.2970 ms 0.2318 ms 1.04 0.06 3718.7500 1937.5000 468.7500 27277586 B 45,012.52
Original_NativeBlocks 4096 78643200 7.982 ms 0.4780 ms 0.3732 ms 1.00 0.00 - - - 764 B 1.00
Current_PooledBuffers 4096 78643200 8.545 ms 0.3697 ms 0.2887 ms 1.07 0.07 7031.2500 3656.2500 875.0000 53503361 B 70,030.58
Original_NativeBlocks 4096 209715200 20.165 ms 0.2542 ms 0.1681 ms 1.00 0.00 - - - - NA
Current_PooledBuffers 4096 209715200 38.548 ms 3.5619 ms 2.7809 ms 1.92 0.15 24000.0000 13000.0000 2250.0000 184629560 B NA
Original_NativeBlocks 2147483647 41943040 3.087 ms 0.1449 ms 0.1048 ms 1.00 0.00 - - - 527 B 1.00
Current_PooledBuffers 2147483647 41943040 3.404 ms 0.4516 ms 0.3526 ms 1.09 0.13 2333.3333 1333.3333 333.3333 16787932 B 31,855.66
Original_NativeBlocks 2147483647 52428800 4.022 ms 0.1295 ms 0.1011 ms 1.00 0.00 - - - 553 B 1.00
Current_PooledBuffers 2147483647 52428800 4.927 ms 0.2389 ms 0.1865 ms 1.23 0.06 3687.5000 1906.2500 437.5000 27277430 B 49,326.27
Original_NativeBlocks 2147483647 78643200 6.517 ms 0.5311 ms 0.3840 ms 1.00 0.00 - - - 606 B 1.00
Current_PooledBuffers 2147483647 78643200 9.964 ms 0.2558 ms 0.1850 ms 1.53 0.09 7125.0000 3750.0000 875.0000 53504784 B 88,291.72
Original_NativeBlocks 2147483647 209715200 15.785 ms 0.5828 ms 0.4214 ms 1.00 0.00 - - - 1010 B 1.00
Current_PooledBuffers 2147483647 209715200 34.435 ms 3.3600 ms 2.6232 ms 2.17 0.20 24000.0000 13000.0000 2250.0000 184629560 B 182,801.54
40/50/75/200 MiB managed comparison, run 2
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=12  IterationTime=150.0000 ms  
WarmupCount=4  
Method MaxRead Size Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Original_NativeBlocks 4096 41943040 4.546 ms 0.2484 ms 0.1796 ms 1.00 0.00 - - - 576 B 1.00
Current_PooledBuffers 4096 41943040 3.958 ms 0.2255 ms 0.1760 ms 0.87 0.06 2375.0000 1375.0000 375.0000 16788530 B 29,146.75
Original_NativeBlocks 4096 52428800 5.760 ms 0.4139 ms 0.3232 ms 1.00 0.00 - - - 606 B 1.00
Current_PooledBuffers 4096 52428800 5.504 ms 0.1142 ms 0.0826 ms 0.95 0.06 3718.7500 1937.5000 468.7500 27277586 B 45,012.52
Original_NativeBlocks 4096 78643200 8.788 ms 1.3100 ms 1.0228 ms 1.00 0.00 - - - 606 B 1.00
Current_PooledBuffers 4096 78643200 9.092 ms 0.8142 ms 0.6357 ms 1.05 0.17 7062.5000 3687.5000 875.0000 53504278 B 88,290.89
Original_NativeBlocks 4096 209715200 22.011 ms 1.2237 ms 0.9554 ms 1.00 0.00 - - - - NA
Current_PooledBuffers 4096 209715200 37.790 ms 1.3567 ms 0.9810 ms 1.72 0.10 24000.0000 13000.0000 2250.0000 184629560 B NA
Original_NativeBlocks 2147483647 41943040 3.274 ms 0.1488 ms 0.1161 ms 1.00 0.00 - - - 553 B 1.00
Current_PooledBuffers 2147483647 41943040 3.433 ms 0.0866 ms 0.0676 ms 1.05 0.05 2333.3333 1333.3333 333.3333 16787932 B 30,357.92
Original_NativeBlocks 2147483647 52428800 3.900 ms 0.1179 ms 0.0921 ms 1.00 0.00 - - - 553 B 1.00
Current_PooledBuffers 2147483647 52428800 4.942 ms 0.2022 ms 0.1462 ms 1.27 0.04 3687.5000 1906.2500 437.5000 27277430 B 49,326.27
Original_NativeBlocks 2147483647 78643200 5.843 ms 0.0744 ms 0.0581 ms 1.00 0.00 - - - 606 B 1.00
Current_PooledBuffers 2147483647 78643200 9.844 ms 0.3612 ms 0.2820 ms 1.69 0.05 7125.0000 3750.0000 875.0000 53504784 B 88,291.72
Original_NativeBlocks 2147483647 209715200 15.869 ms 0.2969 ms 0.2147 ms 1.00 0.00 - - - 1010 B 1.00
Current_PooledBuffers 2147483647 209715200 33.937 ms 0.5978 ms 0.4322 ms 2.14 0.05 24000.0000 13000.0000 2250.0000 184629560 B 182,801.54
36/60 MiB longer refinement, run 1
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=20  IterationTime=300.0000 ms  
WarmupCount=5  
Method MaxRead Size Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Original_NativeBlocks 4096 37748736 3.720 ms 0.0667 ms 0.0713 ms 1.00 0.00 - - - 494 B 1.00
Current_PooledBuffers 4096 37748736 3.272 ms 0.2518 ms 0.2900 ms 0.88 0.08 1607.1429 857.1429 107.1429 12588993 B 25,483.79
Original_NativeBlocks 4096 62914560 6.509 ms 0.1442 ms 0.1543 ms 1.00 0.00 - - - 539 B 1.00
Current_PooledBuffers 4096 62914560 8.670 ms 0.2998 ms 0.3333 ms 1.33 0.05 5479.1667 2979.1667 979.1667 37766985 B 70,068.62
Original_NativeBlocks 2147483647 37748736 2.785 ms 0.0375 ms 0.0417 ms 1.00 0.00 - - - 487 B 1.00
Current_PooledBuffers 2147483647 37748736 2.408 ms 0.0381 ms 0.0391 ms 0.86 0.01 1609.3750 859.3750 109.3750 12589016 B 25,850.14
Original_NativeBlocks 2147483647 62914560 4.719 ms 0.0747 ms 0.0830 ms 1.00 0.00 - - - 503 B 1.00
Current_PooledBuffers 2147483647 62914560 8.001 ms 0.1673 ms 0.1860 ms 1.70 0.05 5479.1667 2979.1667 979.1667 37766985 B 75,083.47
36/60 MiB longer refinement, run 2
BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
  [Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD

Toolchain=InProcessEmitToolchain  IterationCount=20  IterationTime=300.0000 ms  
WarmupCount=5  
Method MaxRead Size Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Original_NativeBlocks 4096 37748736 3.845 ms 0.0806 ms 0.0896 ms 1.00 0.00 - - - 494 B 1.00
Current_PooledBuffers 4096 37748736 3.125 ms 0.0691 ms 0.0796 ms 0.81 0.03 1604.1667 854.1667 104.1667 12588963 B 25,483.73
Original_NativeBlocks 4096 62914560 6.556 ms 0.4166 ms 0.4631 ms 1.00 0.00 - - - 539 B 1.00
Current_PooledBuffers 4096 62914560 8.492 ms 0.1530 ms 0.1701 ms 1.30 0.09 5468.7500 2968.7500 968.7500 37766986 B 70,068.62
Original_NativeBlocks 2147483647 37748736 2.849 ms 0.0725 ms 0.0776 ms 1.00 0.00 - - - 487 B 1.00
Current_PooledBuffers 2147483647 37748736 2.628 ms 0.0939 ms 0.1005 ms 0.92 0.04 1607.1429 857.1429 107.1429 12588993 B 25,850.09
Original_NativeBlocks 2147483647 62914560 4.936 ms 0.1350 ms 0.1555 ms 1.00 0.00 - - - 516 B 1.00
Current_PooledBuffers 2147483647 62914560 7.768 ms 0.1327 ms 0.1475 ms 1.58 0.07 5479.1667 2979.1667 979.1667 37766985 B 73,191.83

mattleibow pushed a commit that referenced this pull request Oct 29, 2026
Archive complete pooled-buffer source, owner tests, experimental benchmarks, findings and eight full measurement reports in collapsible notes on #5483 before removing the experiment from the branch. Restore unknown-length managed stream creation to one bounded scratch rental and SKDynamicMemoryWStream, retaining invalid-count checks, checked length tracking, pointer-width limits and ownership cleanup.

Keep functional regression cases, assert transfer requests stay bounded, and remove the now-duplicate native reference collector from tests. The retired helper's tests and research-only benchmarks remain recoverable in the PR archive. All configured SkiaSharp/HarfBuzz targets, retained benchmarks and net48 tests compile; the unfiltered net10.0 console solution passes.

Research/code: #5483 (comment)
Measurements: #5483 (comment)

Co-authored-by: Copilot App <[email protected]>
@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 12 changed managed stream, test, benchmark and documentation paths with their native-consumer, ownership, failure and target-framework contracts, including a separate final independent-blocker search.

Bound the newly widened SKStream read before entering managed callbacks (binding/SkiaSharp/SKData.cs:333)

The new lengthless SKStream path obtains a full-width remaining length and sends it to the native one-shot reader. On a 64-bit modern target, wrapping a seekable stream with 2 GiB remaining in SKManagedStream now reaches this call with size 0x80000000. After native allocation succeeds, SkData::MakeFromStream forwards that entire size to SKManagedStream.OnReadManagedStream, which narrows size to int and throws. The exception escapes an UnmanagedCallersOnly reverse-P/Invoke entry point and terminates the process instead of returning data/null or a catchable managed error. Previously the lengthless overload used the narrow public SKStream.Length property, so this full-width value did not reach that callback through this entry point.

Fix: Read this path in bounded SKStream chunks into the final allocation, or reject unsupported callback lengths in managed code before native entry. Do not send the whole remaining length to the unchanged int-sized managed reader callback.

Whole-input managed pooling and speculative size thresholds remain deliberately deferred. Native dynamic staging with one bounded scratch rental is the accepted unknown-length policy, not a claim of lower total memory or universal performance.

This is a static source-contract finding, not an executed runtime reproduction.

@github-project-automation github-project-automation Bot moved this to Changes Requested in SkiaSharp Backlog Oct 29, 2026
@mattleibow

Copy link
Copy Markdown
Contributor Author

Bound the newly widened SKStream read before entering managed callbacks

Fixed in aa84d51. The lengthless Create(SKStream) known-length path now loops over at most 80 KiB per native read into the final allocation, with short-read handling, byte-count validation and cleanup. Early EOF still seeks back before the existing native dynamic-stream fallback. Public explicit-length SKStream overloads and the managed callback implementation are unchanged.

Both new full/short-read regression cases failed before the fix because the callback received 163,850 bytes instead of at most 81,920; they pass afterward with exact bytes and final position checks. All configured binding targets and net48 tests compile, and the unfiltered net10.0 console solution passes (6,489 core tests, existing skips unchanged). A separate 64-bit probe with 2 GiB advertised length and a three-byte actual payload completed through SKManagedStream and the seek-back fallback, with every managed callback capped at 81,920 bytes; this is a large-advertised-length/early-EOF check, not a full 2-GiB payload test.

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 12 changed managed stream, test, benchmark and documentation paths with their native-consumer, ownership, failure and target-framework contracts, including a separate final independent-blocker search.

Contain managed read failures before retrying through native callbacks (binding/SkiaSharp/SKData.cs:365-368)

A seekable Stream wrapped in SKManagedStream can advertise Length=2, return one byte on its first legal short Read, then throw IOException on its second Read. The new lengthless known-length loop invokes that second Read through unchanged reverse-P/Invoke. On configured net7+ LibraryImport targets, the exception exits UnmanagedCallersOnly and terminates the process before this outer catch can dispose/rethrow. Previously native one-shot MakeFromStream returned null after the first short read and never invoked that failing callback. New seek-back replay has the same hole if the managed Position setter throws after early EOF. All requests can be only two bytes, independently of fixed oversized-request R1.

Fix: Contain managed-backed read/seek exceptions before leaving reverse-P/Invoke, recording and translating failure after native return, or keep those operations in managed code for this new lengthless path. Add short-read-then-IOException and seek-back-failure regressions while preserving intentionally unchanged explicit-length SKStream behavior.

Whole-input managed pooling and speculative size thresholds remain deliberately deferred. Native dynamic staging with one bounded scratch rental is the accepted unknown-length policy, not a claim of lower total memory or universal performance.

This is a static source-contract finding, not an executed runtime reproduction.

@mattleibow

Copy link
Copy Markdown
Contributor Author

Contain managed read failures before retrying through native callbacks

Addressed in 8693758. The lengthless factory now directly dispatches SKAbstractManagedStream virtual read/seek/metadata operations on the managed stack, including the fallback read loop, while truly native streams keep native dispatch. Bounded requests, partial-data cleanup, virtual overrides and the seek-back/native-staging policy are preserved; public explicit-length overloads and the sibling callback implementations are unchanged.

Added three cases for known/unknown short-read-then-IOException and seek-back failure, asserting the original exception instance, partial position and that the caller's input is not disposed. The full console solution passes (6,492 core tests, existing skips unchanged), and all binding targets/net48 tests compile. The earlier 2-GiB advertised-length boundary probe still passes with 80-KiB callback requests.

The two-byte probes confirmed the read/seek exceptions passed through UnmanagedCallersOnly proxy frames before the fix and no longer do afterward. This Mac/.NET 10 runtime caught both errors even before the fix, so I did not reproduce process termination locally; the change removes the unsupported exception-crossing route rather than relying on platform-specific unwinding behavior.

@dalexsoto

Copy link
Copy Markdown
Member

@mattleibow Not reviewing this request in this iteration: The read-only review worker for current head8693758 stopped with a provider-side content-filter error (422: "This content was flagged for possible cybersecurity risk."). It returned no complete canonical review report, so I am withholding a current-head formal decision. This was not a GitHub or authentication failure. I have not retried, rephrased, or switched provider/model to work around the rejection.

@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from 8693758 to 686f80a Compare October 30, 2026 02:40
mattleibow pushed a commit that referenced this pull request Oct 30, 2026
Archive complete pooled-buffer source, owner tests, experimental benchmarks, findings and eight full measurement reports in collapsible notes on #5483 before removing the experiment from the branch. Restore unknown-length managed stream creation to one bounded scratch rental and SKDynamicMemoryWStream, retaining invalid-count checks, checked length tracking, pointer-width limits and ownership cleanup.

Keep functional regression cases, assert transfer requests stay bounded, and remove the now-duplicate native reference collector from tests. The retired helper's tests and research-only benchmarks remain recoverable in the PR archive. All configured SkiaSharp/HarfBuzz targets, retained benchmarks and net48 tests compile; the unfiltered net10.0 console solution passes.

Research/code: #5483 (comment)
Measurements: #5483 (comment)

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow removed this pull request from stack #5504 October 30, 2026 02:42
@mattleibow
mattleibow changed the base branch from main to mattleibow-delegate-proxies-byte-returns-and-modern October 30, 2026 02:45
@mattleibow
mattleibow added this pull request to stack #5513 October 30, 2026 02:47

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 13 changed managed stream, test, benchmark and documentation paths with their native-consumer, ownership, failure and target-framework contracts, including a separate final independent-blocker search.

Reject negative managed write counts before unsigned widening (binding/SkiaSharp/SKManagedWStream.cs:69)

The new unsigned count conversion makes a negative size from the ordinary managed array-write overload reach an unsafe copy. SKManagedWStream inherits SKWStream.Write(byte[], int), which pins the array and forwards size as IntPtr without validating it. Write(new byte[1], -1) arrives here as native size_t all-ones; FromNativeSize turns it into UInt64.MaxValue (UInt32.MaxValue on32-bit). The first iteration creates an80-KiB unsafe span over the one-byte array and writes/copies it. The bounded chunk limit and catch/fault latch do not prevent that out-of-bounds read, which can copy unrelated memory or crash the process. In the actual target implementation, the count became-1 and ArrayPool.Rent rejected it before source memory was read; the inherited callback proxy contained that exception and returned false.

Fix: Validate the signed managed count before the public array-write overload crosses the native boundary (and validate non-null array bounds there). Preserve legitimate full-width native size_t requests rather than rejecting every high-bit IntPtr in OnWrite. Add a negative-size public Write regression asserting that the destination receives no write.

Whole-input managed pooling and speculative size thresholds remain deliberately deferred. Native dynamic staging with one bounded scratch rental is the accepted unknown-length policy, not a claim of lower total memory or universal performance.

This is a static source-contract finding, not an executed runtime reproduction.

@mattleibow

Copy link
Copy Markdown
Contributor Author

Reject negative managed write counts before unsigned widening

Fixed in fefd756. SKWStream.Write(byte[], int) now rejects negative sizes and sizes exceeding a non-null array before pinning or native entry, with ArgumentOutOfRangeException(nameof(size)). This validates the signed managed entry point rather than rejecting high-bit native callback counts; OnWrite keeps its full-width unsigned behavior and existing nonnegative null-buffer zero filling.

Five safe rejecting-callback cases fail before the guard and pass afterward, proving invalid counts no longer cross the native boundary without dereferencing any invalid pointer. Additional cases verify an actual managed destination receives no output, counts no bytes, is not faulted by argument validation, and still accepts a valid subsequent write; public null-array zero filling is also retained. All configured binding targets and net48 tests compile, and the full net10.0 console solution passes with 6,536 core tests plus 57 other-host tests, zero failures and existing skips unchanged. The PR description records the new validation contract and keeps the separate stacked-Azure trigger limitation explicit.

@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from fefd756 to 670e7cb Compare October 30, 2026 08:24
Copilot AI added 2 commits October 30, 2026 16:37
Dispatch managed SKStream virtual read, seek and metadata operations directly in the lengthless SKData factory instead of round-tripping through reverse P/Invoke. Native streams retain native dispatch, bounded requests and existing final-allocation/seek-back fallback behavior. Public explicit-length overloads and sibling callback implementations remain unchanged.

Add regression coverage preserving the original IOException, input ownership and partial position for known/unknown short-read failures and a failed seek-back. Local before/after probes show the unmanaged callback frames are eliminated; this Mac caught both failures even before the fix, so no reproduced process termination is claimed. All binding targets/net48 tests compile and the unfiltered console solution passes.

Co-authored-by: Copilot App <[email protected]>
Reject negative counts and counts beyond a non-null array before pinning and converting to native size_t. This prevents invalid managed arguments from being widened into unsafe full-width writes while preserving native callback sizes and existing null-buffer zero-fill behavior.

Use a rejecting callback for safe red regression coverage without reading invalid memory. Verify actual managed destinations receive no invalid write or fault latch and can accept the next valid write. All binding targets/net48 tests compile; the full net10 console suite passes.

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from 9697f59 to aa8eff5 Compare October 30, 2026 14:37
Reuse the existing validated SKData read dispatcher at the front-buffer adapter's two inner read sites, so short-read retries do not introduce a nested managed reverse-P/Invoke boundary. Release its existing temporary native buffer in finally. No read, EOF, seek or fill policy changes and no new reader abstraction.

Add two tiny ordinary short-read-then-IOException cases that fail on callback proxy frames before the fix and preserve original exception identity, partial position and input ownership afterward. Correct all three explicit-length SKStream XML contracts to document the unchanged native one-shot short-read behavior.

All managed targets, retained benchmarks and net48 tests compile. The unfiltered console solution passes with source-matched748bc native assets (6533 core tests plus57 other hosts); source XML/package assertions pass. Local before/after probes verify the proxy route is removed; no local process abort is claimed.

Co-authored-by: Copilot App <[email protected]>
@mattleibow

Copy link
Copy Markdown
Contributor Author

Keep new staging-loop retries out of nested managed reverse-P/Invoke

Fixed in 482582e. The two inner reads in SKFrontBufferedManagedStream reuse the existing validated managed/native read dispatcher directly, rather than routing a wrapped managed stream back through native callbacks. Only that helper's internal visibility changed; its validation/keep-alive behavior, factory retries and the adapter's read/EOF/seek/fill policy are preserved. The adapter's existing temporary native buffer is freed in finally.

Two ordinary two-byte short-read-then-IOException cases, covering front-buffer sizes zero and two, failed before the fix because the exception stack included callback proxy frames. They pass afterward with the same original exception instance, partial position and caller input ownership, and no proxy frames. The full source-matched suite passes (6,533 core tests plus 57 other-host tests, existing skips unchanged); all binding targets, retained benchmarks and net48 tests compile. This Mac caught the error even before the fix, so no local process termination is claimed.

The explicit-length SKStream int/ulong/long docs are also corrected to describe the unchanged native one-shot/no-short-read-retry behavior, and the documentation thread is resolved. Compiler XML and package assertions pass. GitHub's automatic rebase after #5479 merged was adopted only after confirming all 23 patches and the tree matched the previously published work; this correction is a normal follow-up commit on the actual main-targeting PR.

Copilot AI added 2 commits October 30, 2026 17:33
Choose the managed stream path once in the lengthless factory and keep its virtual metadata and seek calls in a dedicated helper. Remove nullable coalescing from the routing while sharing the existing bounded read and unknown-length staging loops. Preserve exception identity, capability decisions, keep-alive checks, seek-back behavior and explicit-length native factory semantics.

Co-authored-by: Copilot App <[email protected]>
Expose Length64 and Position64 as long properties and add Seek(long), using the existing native size_t APIs without changing any public signatures. Use the wide members for SKData's native metadata and seek-back path; retain direct managed exception dispatch and the explicit-length native factory contracts.

As requested, route the old int getters through checked conversions and throw OverflowException rather than wrapping oversized values. Check unsigned native results against Int64.MaxValue, and reject negative or native-width-overflow positions before the new long seek enters native code. The existing Seek(int) behavior is unchanged.

Cover native-backed memory streams, unsigned 32-bit values, the signed 64-bit boundary, legacy overflow and invalid seek arguments without huge payload allocations. All binding targets, net48 and retained benchmarks compile; the full source-matched net10 console solution passes with 6542 core tests plus 57 other-host tests. Compiler XML for all 13 built targets contains the new members and exception contracts; 32-bit runtime execution was not available locally.

Co-authored-by: Copilot App <[email protected]>
@mattleibow mattleibow changed the title Improve SKData stream I/O and SKManagedWStream accounting Improve stream I/O correctness and add 64-bit stream metadata Oct 30, 2026
Copilot AI added 7 commits October 30, 2026 18:40
Encode managed length and position callbacks as unsigned native sizes so the new 64-bit stream API works above Int32.MaxValue in 32-bit processes. Preserve rejection of positive metadata beyond the native width and reject native seek positions beyond Int64.MaxValue before changing the underlying managed cursor. Query managed metadata directly in the wide properties so callback exceptions do not cross reverse P/Invoke through these getters.

Following the maintainer's native-contract decision, delegate Seek(int) to Seek(long), reject negative read/peek/skip/seek arguments before native entry, and bound byte-array reads by their actual destination. Retain null-array skipping and signed backward Move. No additional wide transfer overloads or general callback policy are introduced.

Exercise actual SKManagedStream metadata and cursor operations with a configurable zero-payload source, native round trips, unsupported sizes and safe rejecting-callback cases. Correct the existing short-read test destination capacity without changing any input case or assertion. Four safe regressions fail before the fix; all configured binding targets, net48 and benchmarks compile, and the full source-matched net10 solution passes with 6549 core tests plus 57 other-host tests. The 32-bit-specific branch is included but not executed locally.

Co-authored-by: Copilot App <[email protected]>
Put managed/native read dispatch and unsigned byte-count validation directly in the existing public Read(IntPtr, int) method. The array overload still forwards to it, and managed overrides now propagate their original exceptions without a reverse-P/Invoke round trip. Native callbacks and explicit-length native SKData factories keep their separate entry paths.

Remove SKData.ReadStream and use the public instance method at all four existing call sites. Preserve bounded copy loops, nested front-buffer exception behavior, null-pointer skips and temporary-buffer cleanup. Keep the stream owner alive immediately after the read and before validating its result, without adding a read-wrapper try/finally.

Three safe invalid-count regressions fail before the consolidation, including a full-width result that would otherwise narrow to an apparently valid int. Add original-exception identity and built-in managed array/pointer read coverage without proxy frames. All configured binding targets, net48 and retained benchmarks compile; all 13 compiler XML contracts verify, and the full source-matched net10 console solution passes with 6555 core tests plus 57 other-host tests.

Co-authored-by: Copilot App <[email protected]>
Defer the unmeasured public managed-dispatch changes at the maintainer's request. Public Read, Length64 and Position64 consistently query native streams again, while retaining the additive wide APIs, unsigned count validation, checked conversions and argument guards.

Keep direct managed metadata, reads and seek-back together in CreateFromManagedStream, including bounded known-length allocation and unknown-length native staging with exception cleanup. Preserve the built-in front-buffer adapter's two internal managed-safe reads and count checks so the accepted nested short-read failure path still keeps original exceptions off reverse P/Invoke. No new general reader helper or public member fast path is added.

Retarget original-exception tests to the private factory contract and retain invalid-count coverage for both public native reads and factory reads. On 32-bit, unrepresentable managed metadata is exercised directly and through the managed factory, never deliberately through an uncontained native callback. All binding targets, net48 and retained copy benchmarks compile; all 13 XML contracts verify native-backed public behavior, and the full source-matched net10 solution passes with 6555 core tests plus 57 other-host tests. There are no public-dispatch performance measurements or speedup claims.

Co-authored-by: Copilot App <[email protected]>
Make Create(SKStream) the orchestrator for managed/native input with known or unknown remaining length. Move managed metadata checks and seek-back fallback beside native routing, and delegate copying to separate typed known-length and unknown-length managed helpers. Keep public stream members native-backed and preserve existing byte-count, short-read, EOF, ownership and exception behavior.

Keep the source owner alive once in the orchestrator's finally so every return and failure path is covered. Remove redundant per-read/metadata markers and the private native helper's duplicate lifetime scope. No tests or assertions are changed.

All configured binding targets, net48 and retained benchmarks compile. The full source-matched net10 console solution passes with 6555 core tests plus 57 other-host tests; existing declared skips are unchanged. This is a structural cleanup, not a measured performance optimization.

Co-authored-by: Copilot App <[email protected]>
Preserve the distinction between successful empty read-to-end/zero-length requests and failed positive exact-length requests. Keep native explicit-length one-shot behavior and the existing seek-back/fallback policy unchanged. Document the empty/null/data result contract on both lengthless stream overloads.

Query System.IO.Stream length and position once after the capability checks, and use the same len/pos/remaining structure as the managed/native SKStream routes. Keep the explicit signed remaining-byte preflight for exact requests, including past-end positions; no generic metadata helper or new return policy is added.

Add focused empty/past-end and zero-vs-positive exact-length checks across System.IO.Stream, SKManagedStream and native memory streams, plus known-length/exact-length metadata snapshot checks. All binding targets, net48 and retained benchmarks compile; the full source-matched net10 solution passes with 6559 core tests plus 57 other-host tests. Existing assertion and skip policies are unchanged.

Co-authored-by: Copilot App <[email protected]>
Restore main's incomplete-known-length failure policy at the maintainer's explicit direction. All managed copy loops still fill legal positive short reads, but zero before the expected count releases partial data and returns null. Remove System.IO.Stream partial-prefix success and both managed/native SKStream seek-back/read-to-end recovery paths. Unknown remaining lengths still read to EOF normally; zero expected bytes remain a successful empty result.

Keep public stream dispatch, native explicit-length one-shot factories, offsets, wide-size conversions and original managed read exceptions unchanged. Rename the private flag to checkRemainingLength because it now controls only the optional seekable availability preflight, not EOF behavior. Update source XML and retarget obsolete prefix/reset expectations to strict failure and no reset; preserve unknown-length partial content, input ownership and real read-failure identity checks.

Five EOF-policy cases fail before the fix and pass afterward. The baseline red run also exposed an unrelated color-space assertion; its focused diagnostic and subsequent full runs pass without changing that test. All binding TFMs, net48 and retained benchmarks compile; all 13 XML contracts verify, and the final full source-matched net10 solution passes with 6562 core tests plus 57 other-host tests, existing declared skips unchanged.

Co-authored-by: Copilot App <[email protected]>
Describe the existing write/flush exception handling and latched failure behavior on SKManagedWStream and its OnWrite/OnFlush hooks. Later writes return false and later flushes are ignored after either operation throws. Only source XML comment trivia changes; declarations and runtime code are identical to the Sonnet-reviewed revision.

All 13 configured binding targets build, the three documentation entries are verified in all compiler XML artifacts, and the reference/library XML package transport tests pass. Runtime regression evidence remains the strict EOF run at 58f1176 (6562 core plus 57 other-host tests); no runtime code changed or extra review round was started.

Co-authored-by: Copilot App <[email protected]>
Copilot AI added 2 commits October 30, 2026 22:15
Add brief comments for known-count fills, native staging of unknown input, managed exception boundaries, source-owner lifetime, bounded writes and null-buffer zero filling. Explain that checkRemainingLength rejects impossible explicit-length requests before allocation or consumption, while lengthless callers already resolved the count.

This adds only 15 ordinary comment lines. Comment-stripped source, declarations, XML documentation and tests are unchanged; git diff --check passes. Runtime and documentation validation remains the named evidence from 58f1176 and 687d13a respectively; no extra runtime suite or review round is needed for this verified comment-only delta.

Co-authored-by: Copilot App <[email protected]>
Add multi-chunk zero-fill and completed-write accounting regressions, and observe deterministic data cleanup through the existing registry and native reference count.

Co-authored-by: Copilot App <[email protected]>
@mattleibow mattleibow changed the title Improve stream I/O correctness and add 64-bit stream metadata Improve stream I/O correctness and add 64-bit stream APIs Oct 30, 2026
@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Negative stream lengths can become near-maximum native allocation sizes and trigger a fatal assertion, while disposal-insensitive test helpers cannot detect disposal of caller-owned streams.

3 open issues
1 resolved since last review

Review effort: Max

Comment thread binding/SkiaSharp/SKData.cs Resolved
Comment thread tests/Tests/Utils/ThrowingReadStream.cs Resolved
Copilot AI added 2 commits October 31, 2026 02:09
Keep unknown-length front-buffered inputs out of known-size allocations and report EOF from observed reads. Make read fixtures disposal-sensitive so caller-ownership checks detect premature closure.

Co-authored-by: Copilot App <[email protected]>
Preserve the existing implementation and unknown-length sentinel while warning callers to use automatic decoding adapters or SKFrontBufferedManagedStream for explicit Skia buffering. Clarify the distinct .NET and Skia stream contracts.

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow removed this pull request from stack #5513 October 31, 2026 00:51
mattleibow pushed a commit that referenced this pull request Oct 31, 2026
Archive complete pooled-buffer source, owner tests, experimental benchmarks, findings and eight full measurement reports in collapsible notes on #5483 before removing the experiment from the branch. Restore unknown-length managed stream creation to one bounded scratch rental and SKDynamicMemoryWStream, retaining invalid-count checks, checked length tracking, pointer-width limits and ownership cleanup.

Keep functional regression cases, assert transfer requests stay bounded, and remove the now-duplicate native reference collector from tests. The retired helper's tests and research-only benchmarks remain recoverable in the PR archive. All configured SkiaSharp/HarfBuzz targets, retained benchmarks and net48 tests compile; the unfiltered net10.0 console solution passes.

Research/code: #5483 (comment)
Measurements: #5483 (comment)

Co-authored-by: Copilot App <[email protected]>
@mattleibow

Copy link
Copy Markdown
Contributor Author

Superseded by #5464, which consolidates the stream-correctness work, regression coverage and warning-only deprecation at b9272f3802f78bfdfc9812f5833f43f429bec182. This PR is closed without merging; its final source tip 15158ad8446fd76edab90551612507dd0345c459, branch, review history and linked research archives are retained. The optional callback-allocation optimization remains separate in #5518.

@mattleibow mattleibow closed this Oct 31, 2026
@github-project-automation github-project-automation Bot moved this from Changes Requested to Done in SkiaSharp Backlog Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants