diff --git a/.github/workflows/build-packages.yml b/.github/workflows/build-packages.yml index cb15f34..17cfc77 100644 --- a/.github/workflows/build-packages.yml +++ b/.github/workflows/build-packages.yml @@ -65,7 +65,10 @@ jobs: - name: Install .NET SDK uses: actions/setup-dotnet@v5 with: - dotnet-version: 11.x + dotnet-version: | + 8.0.x + 10.0.x + 11.x - name: Install Linux build prerequisites shell: bash @@ -98,6 +101,10 @@ jobs: shell: bash run: dotnet test --solution typstsharp.slnx + - name: Run tests against the .NET Standard 2.1 assembly + shell: bash + run: dotnet test --project src/typstsharp.tests/typstsharp.tests.csproj --framework net10.0 -p:TestNetStandardLibrary=true + pack-runtime: name: Pack typstsharp.runtime.${{ matrix.rid }} runs-on: ${{ matrix.os }} diff --git a/.github/workflows/pack.yml b/.github/workflows/pack.yml index b509904..6b3292e 100644 --- a/.github/workflows/pack.yml +++ b/.github/workflows/pack.yml @@ -91,7 +91,10 @@ jobs: if: matrix.test_type == '' uses: actions/setup-dotnet@v5 with: - dotnet-version: 11.x + dotnet-version: | + 8.0.x + 10.0.x + 11.x - name: Run tests (native host) if: matrix.test_type == '' @@ -111,6 +114,10 @@ jobs: run: | docker run --rm -v ${{ github.workspace }}:/workspace -w /workspace mcr.microsoft.com/dotnet/sdk:11.0-alpine sh -c " set -eu + apk add --no-cache curl bash + curl -fsSL https://dot.net/v1/dotnet-install.sh -o /tmp/dotnet-install.sh + bash /tmp/dotnet-install.sh --channel 8.0 --runtime dotnet --install-dir /usr/share/dotnet + bash /tmp/dotnet-install.sh --channel 10.0 --runtime dotnet --install-dir /usr/share/dotnet dotnet nuget add source /workspace/artifacts --name local-artifacts dotnet nuget locals all --clear dotnet restore src/typstsharp.tests/typstsharp.tests.csproj -p:UsePackagedLibrary=true -p:PackageVersion=${{ needs.version.outputs.package_version }} @@ -124,7 +131,10 @@ jobs: docker run --rm -v ${{ github.workspace }}:/workspace -w /workspace fedora:40 sh -c " set -eu dnf install -y curl tar icu - curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel 11.0 --install-dir /usr/share/dotnet + curl -fsSL https://dot.net/v1/dotnet-install.sh -o /tmp/dotnet-install.sh + bash /tmp/dotnet-install.sh --channel 11.0 --install-dir /usr/share/dotnet + bash /tmp/dotnet-install.sh --channel 8.0 --runtime dotnet --install-dir /usr/share/dotnet + bash /tmp/dotnet-install.sh --channel 10.0 --runtime dotnet --install-dir /usr/share/dotnet ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet dotnet nuget add source /workspace/artifacts --name local-artifacts dotnet nuget locals all --clear diff --git a/README.md b/README.md index b511352..49f0834 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # typstsharp -A .NET 11.0 wrapper around the Typst 0.15 rendering stack. The managed layer in `src/typstsharp` calls into the Rust `typst_core` crate via P/Invoke and exposes convenient helpers for C# consumers plus a simple CLI. +A .NET wrapper around the Typst 0.15 rendering stack that targets .NET Standard 2.1, .NET 8, .NET 10, and .NET 11. The managed layer in `src/typstsharp` calls into the Rust `typst_core` crate via P/Invoke and exposes convenient helpers for C# consumers plus a simple CLI. For the latest changes, see our [Release Notes](RELEASENOTES.md). @@ -305,7 +305,7 @@ You only need to install the main `typstsharp` package. Portable builds (`dotnet ## Prerequisites -- [.NET SDK 11.0](https://dotnet.microsoft.com/) – required to build the managed projects. +- [.NET SDK 11.0](https://dotnet.microsoft.com/) – required to build the managed projects. Install the .NET 8 and .NET 10 runtimes as well to run the tests on all target frameworks. - [Rust toolchain](https://www.rust-lang.org/tools/install) (with `cargo`) – **only required if you are building the project from source.** The NuGet packages include pre-compiled native binaries. ## Building @@ -334,9 +334,11 @@ dotnet pack src/typstsharp.runtime/typstsharp.runtime.csproj -c Release -p:Runti ```pwsh # after a successful build - dotnet run --project src/typstsharp.cli/typstsharp.cli.csproj + dotnet run --project src/typstsharp.cli/typstsharp.cli.csproj --framework net11.0 ``` +Use `--framework net8.0` or `--framework net10.0` to run the CLI on either of those installed runtimes. + Because the Rust binary is registered as a runtime asset, `typst_core.dll`, `libtypst_core.so`, or `libtypst_core.dylib` will appear beside the CLI executable automatically. ## Notes diff --git a/RELEASENOTES.md b/RELEASENOTES.md index 615e369..71194df 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -8,7 +8,7 @@ - Fixed `ua-1` (PDF/UA-1, the accessibility standard) being rejected by `pdfStandards`. The accepted names are now taken from `typst_pdf::PdfStandard` itself, so every standard Typst supports is accepted, including ones added by later Typst releases. The documented `v-` prefix on plain PDF versions still works, and applies only to them: `v-a-2b` is not a spelling of `a-2b`. ### Changed -- **Breaking:** Upgraded target frameworks to `net10.0` and `net11.0`, removing deprecated `net8` and `net9` targets. +- The library and CLI target `net8.0`, `net10.0`, and `net11.0`. - `TypstCompiler.FromSource(...)` and the static one-shot helpers no longer copy the source onto the managed heap before handing it to the compiler. It is encoded straight into the native buffer, so a source over roughly 42,500 characters no longer puts an array on the large object heap for the duration of one call: a 200 KB source measured 200,024 bytes of managed heap before and none after. Native memory allocated while building a compiler is also released now when construction fails part way through, rather than leaking. - **Breaking (binary):** `SvgResult.GetEnumerator()` and `PngResult.GetEnumerator()` now return `PageEnumerator` rather than `IEnumerator`, so that `foreach` over a result no longer boxes the enumerator. Source-compatible: `foreach`, LINQ, `Count` and the indexer all keep compiling. Because a return type is part of the method signature and the compiler emits a direct call for pattern-based `foreach`, an assembly compiled against an earlier version throws `MissingMethodException` on that `foreach` until it is recompiled. - **Breaking:** an invalid combination of PDF standards now fails the compilation instead of silently producing an ordinary PDF. The validation error from `PdfStandards::new` was discarded and export fell back to the default, so a pipeline could believe it was writing PDF/A while it was not. Combinations such as two PDF/A levels, or a PDF/A level that contradicts the requested PDF version, now throw with the message and hints from Typst. Callers passing a contradictory combination today receive a document and will receive an exception after this change. @@ -20,6 +20,7 @@ - The native library is now built with size optimisation (`opt-level = "z"`), thin LTO (`lto = "thin"`), a single codegen unit, symbol stripping (`strip = "symbols"`), and single-target crate compilation (`--crate-type cdylib`), so that LTO runs across the dependency graph and unreferenced symbols and DWARF debug sections are stripped. ### Added +- Added a `netstandard2.1` target for the NuGet library. A compatible native Typst runtime is still required. - Added `TypstCompilerPool` for high-concurrency and ASP.NET Core workloads. It lazily pools up to `Environment.ProcessorCount` (or a configured `maxConcurrency`) `TypstCompiler` instances, bounds concurrent native compilations, applies per-request `sys.inputs` or updated source strings atomically, and returns the compiler to the pool before the caller streams the resulting zero-copy `TypstDocument`. - Added concurrent-access detection on `TypstCompiler`: using a single `TypstCompiler` instance from two threads simultaneously now throws `InvalidOperationException` with guidance to use `TypstCompilerPool`, rather than racing on the underlying native `SystemWorld`. - Added `compiler.SetSource(string source)` (and `pool.CompileSourceToDocument` / `CompileSourceToDocumentAsync`) to update an in-memory compiler's main document source in place, preserving its `FileId` and using Typst's incremental `Source::replace` diffing across compilations. diff --git a/src/typstsharp.cli/typstsharp.cli.csproj b/src/typstsharp.cli/typstsharp.cli.csproj index 4d546e7..caea681 100644 --- a/src/typstsharp.cli/typstsharp.cli.csproj +++ b/src/typstsharp.cli/typstsharp.cli.csproj @@ -2,7 +2,7 @@ Exe - net11.0 + net8.0;net10.0;net11.0 enable enable diff --git a/src/typstsharp.tests/typstsharp.tests.csproj b/src/typstsharp.tests/typstsharp.tests.csproj index 5f0b751..e12c0e0 100644 --- a/src/typstsharp.tests/typstsharp.tests.csproj +++ b/src/typstsharp.tests/typstsharp.tests.csproj @@ -4,7 +4,7 @@ enable enable Exe - net11.0 + net8.0;net10.0;net11.0 true true @@ -15,7 +15,9 @@ - + + TargetFramework=netstandard2.1 + diff --git a/src/typstsharp/Guard.cs b/src/typstsharp/Guard.cs new file mode 100644 index 0000000..721a6cc --- /dev/null +++ b/src/typstsharp/Guard.cs @@ -0,0 +1,31 @@ +using System.Diagnostics.CodeAnalysis; + +namespace typstsharp; + +internal static class Guard +{ + internal static void NotNull([NotNull] object? value, string paramName) + { + if (value is null) + throw new ArgumentNullException(paramName); + } + + internal static void NotNullOrEmpty([NotNull] string? value, string paramName) + { + NotNull(value, paramName); + if (value.Length == 0) + throw new ArgumentException("The value cannot be an empty string.", paramName); + } + + internal static void NotNegative(int value, string paramName) + { + if (value < 0) + throw new ArgumentOutOfRangeException(paramName, value, "The value must be non-negative."); + } + + internal static void NotDisposed(bool disposed, object instance) + { + if (disposed) + throw new ObjectDisposedException(instance.GetType().FullName); + } +} diff --git a/src/typstsharp/IsExternalInit.cs b/src/typstsharp/IsExternalInit.cs new file mode 100644 index 0000000..4842335 --- /dev/null +++ b/src/typstsharp/IsExternalInit.cs @@ -0,0 +1,5 @@ +#if NETSTANDARD2_1 +namespace System.Runtime.CompilerServices; + +internal static class IsExternalInit; +#endif diff --git a/src/typstsharp/NativeBuffers.cs b/src/typstsharp/NativeBuffers.cs index fd1975f..1043219 100644 --- a/src/typstsharp/NativeBuffers.cs +++ b/src/typstsharp/NativeBuffers.cs @@ -27,7 +27,7 @@ public NativeBufferMemoryManager(TypstDocument owner, byte* pointer, int length) public override Span GetSpan() { - ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner); + Guard.NotDisposed(_owner.IsDisposed, _owner); return new Span(_pointer, _length); } @@ -38,7 +38,7 @@ public override Span GetSpan() /// public override MemoryHandle Pin(int elementIndex = 0) { - ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner); + Guard.NotDisposed(_owner.IsDisposed, _owner); if ((uint)elementIndex > (uint)_length) { diff --git a/src/typstsharp/TypstCompiler.cs b/src/typstsharp/TypstCompiler.cs index 7284b1e..ce2f359 100644 --- a/src/typstsharp/TypstCompiler.cs +++ b/src/typstsharp/TypstCompiler.cs @@ -320,7 +320,7 @@ public static int MaxCacheAge get => checked((int)CsBindgen.NativeMethods.get_max_cache_age()); set { - ArgumentOutOfRangeException.ThrowIfNegative(value); + Guard.NotNegative(value, nameof(value)); CsBindgen.NativeMethods.set_max_cache_age((nuint)value); } } @@ -364,7 +364,7 @@ public static int MaxCacheAge /// Thrown if the native eviction failed. public static void EvictCache(int maxAge) { - ArgumentOutOfRangeException.ThrowIfNegative(maxAge); + Guard.NotNegative(maxAge, nameof(maxAge)); if (!CsBindgen.NativeMethods.evict_cache_with_max_age((nuint)maxAge)) { throw new InvalidOperationException("Typst failed to evict its compilation cache."); @@ -597,7 +597,7 @@ public PdfResult CompilePdf(IEnumerable? pdfStandards = null) /// The warnings reported by the Typst compiler. public IReadOnlyList CompilePdf(string outputFile, IEnumerable? pdfStandards = null) { - ArgumentException.ThrowIfNullOrEmpty(outputFile); + Guard.NotNullOrEmpty(outputFile, nameof(outputFile)); using var document = CompileToDocument("pdf", pdfStandards: pdfStandards); document.WriteOutputToFile(outputFile); @@ -614,7 +614,7 @@ public IReadOnlyList CompilePdf(string outputFile, IEnumerable? /// The warnings reported by the Typst compiler. public async Task> CompilePdfAsync(string outputFile, IEnumerable? pdfStandards = null, CancellationToken cancellationToken = default) { - ArgumentException.ThrowIfNullOrEmpty(outputFile); + Guard.NotNullOrEmpty(outputFile, nameof(outputFile)); using var document = CompileToDocument("pdf", pdfStandards: pdfStandards); await document.WriteOutputToFileAsync(outputFile, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -630,7 +630,7 @@ public async Task> CompilePdfAsync(string outputFile, IEnu /// The warnings reported by the Typst compiler. public IReadOnlyList CompilePdf(Stream destination, IEnumerable? pdfStandards = null) { - ArgumentNullException.ThrowIfNull(destination); + Guard.NotNull(destination, nameof(destination)); using var document = CompileToDocument("pdf", pdfStandards: pdfStandards); document.CopyOutputTo(destination); @@ -647,7 +647,7 @@ public IReadOnlyList CompilePdf(Stream destination, IEnumerable? /// The warnings reported by the Typst compiler. public async Task> CompilePdfAsync(Stream destination, IEnumerable? pdfStandards = null, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(destination); + Guard.NotNull(destination, nameof(destination)); using var document = CompileToDocument("pdf", pdfStandards: pdfStandards); await document.CopyOutputToAsync(destination, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -733,7 +733,7 @@ public record TypstWarning(string Message); /// The distance between neighbouring pages in a merged SVG, in points. public void Compile(string outputFile, string format, float ppi = 144.0f, IEnumerable? pdfStandards = null, float mergedGap = 0f) { - ArgumentException.ThrowIfNullOrEmpty(outputFile); + Guard.NotNullOrEmpty(outputFile, nameof(outputFile)); using var document = CompileToDocument(format, ppi, pdfStandards, mergedGap); if (document.OutputCount == 1) @@ -764,7 +764,7 @@ public void Compile(string outputFile, string format, float ppi = 144.0f, IEnume /// Thrown if the compiler is already in use on another thread or if updating the source fails. public unsafe void SetSource(string source) { - ArgumentNullException.ThrowIfNull(source); + Guard.NotNull(source, nameof(source)); EnterExclusiveUse(); try { @@ -807,7 +807,7 @@ public unsafe void SetSource(string source) /// Thrown if the inputs fail to be set in the native compiler. public void SetSysInputs(IDictionary inputs) { - ArgumentNullException.ThrowIfNull(inputs); + Guard.NotNull(inputs, nameof(inputs)); var sysInputsJson = JsonSerializer.Serialize>(inputs, sourceGenOptions); SetSysInputsJson(sysInputsJson); } @@ -823,8 +823,8 @@ public void SetSysInputs(IDictionary inputs) /// The source-generated metadata. public void SetSysInputs(T inputs, JsonTypeInfo jsonTypeInfo) { - ArgumentNullException.ThrowIfNull(inputs); - ArgumentNullException.ThrowIfNull(jsonTypeInfo); + Guard.NotNull(inputs, nameof(inputs)); + Guard.NotNull(jsonTypeInfo, nameof(jsonTypeInfo)); var sysInputsJson = JsonSerializer.Serialize(inputs, jsonTypeInfo); SetSysInputsJson(sysInputsJson); } @@ -839,7 +839,7 @@ public void SetSysInputs(T inputs, JsonTypeInfo jsonTypeInfo) /// Thrown if is not a valid JSON object or the compiler is in use on another thread. public unsafe void SetSysInputsJson(string json) { - ArgumentNullException.ThrowIfNull(json); + Guard.NotNull(json, nameof(json)); EnterExclusiveUse(); try { @@ -916,7 +916,7 @@ protected virtual unsafe void Dispose(bool disposing) private void EnterExclusiveUse() { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + Guard.NotDisposed(Volatile.Read(ref _disposed) != 0, this); if (Interlocked.CompareExchange(ref _inUse, 1, 0) != 0) { diff --git a/src/typstsharp/TypstCompilerPool.cs b/src/typstsharp/TypstCompilerPool.cs index 70a0cd1..1d6d50c 100644 --- a/src/typstsharp/TypstCompilerPool.cs +++ b/src/typstsharp/TypstCompilerPool.cs @@ -50,8 +50,8 @@ public sealed class TypstCompilerPool : IDisposable /// Thrown if is negative. public TypstCompilerPool(Func compilerFactory, int maxConcurrency = 0) { - ArgumentNullException.ThrowIfNull(compilerFactory); - ArgumentOutOfRangeException.ThrowIfNegative(maxConcurrency); + Guard.NotNull(compilerFactory, nameof(compilerFactory)); + Guard.NotNegative(maxConcurrency, nameof(maxConcurrency)); _maxConcurrency = maxConcurrency == 0 ? Math.Max(1, Environment.ProcessorCount) : maxConcurrency; _factory = compilerFactory; @@ -82,7 +82,7 @@ public static TypstCompilerPool FromFile( bool includeSystemPackages = true, int maxConcurrency = 0) { - ArgumentException.ThrowIfNullOrEmpty(path); + Guard.NotNullOrEmpty(path, nameof(path)); return new TypstCompilerPool( () => TypstCompiler.FromFile(path, fonts, sysInputs, root, packagePath, includeSystemPackages), maxConcurrency); @@ -107,7 +107,7 @@ public static TypstCompilerPool FromSource( bool includeSystemPackages = true, int maxConcurrency = 0) { - ArgumentNullException.ThrowIfNull(source); + Guard.NotNull(source, nameof(source)); return new TypstCompilerPool( () => TypstCompiler.FromSource(source, fonts, sysInputs, root, packagePath, includeSystemPackages), maxConcurrency); @@ -174,7 +174,7 @@ public TypstDocument CompileToDocumentWithJsonInputs( IEnumerable? pdfStandards = null, float mergedGap = 0f) { - ArgumentNullException.ThrowIfNull(sysInputsJson); + Guard.NotNull(sysInputsJson, nameof(sysInputsJson)); return Execute(compiler => { compiler.SetSysInputsJson(sysInputsJson); @@ -194,7 +194,7 @@ public ValueTask CompileToDocumentWithJsonInputsAsync( float mergedGap = 0f, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(sysInputsJson); + Guard.NotNull(sysInputsJson, nameof(sysInputsJson)); return ExecuteAsync(compiler => { compiler.SetSysInputsJson(sysInputsJson); @@ -214,8 +214,8 @@ public TypstDocument CompileToDocument( IEnumerable? pdfStandards = null, float mergedGap = 0f) { - ArgumentNullException.ThrowIfNull(sysInputs); - ArgumentNullException.ThrowIfNull(jsonTypeInfo); + Guard.NotNull(sysInputs, nameof(sysInputs)); + Guard.NotNull(jsonTypeInfo, nameof(jsonTypeInfo)); return Execute(compiler => { compiler.SetSysInputs(sysInputs, jsonTypeInfo); @@ -237,8 +237,8 @@ public ValueTask CompileToDocumentAsync( float mergedGap = 0f, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(sysInputs); - ArgumentNullException.ThrowIfNull(jsonTypeInfo); + Guard.NotNull(sysInputs, nameof(sysInputs)); + Guard.NotNull(jsonTypeInfo, nameof(jsonTypeInfo)); return ExecuteAsync(compiler => { compiler.SetSysInputs(sysInputs, jsonTypeInfo); @@ -258,7 +258,7 @@ public TypstDocument CompileSourceToDocument( IEnumerable? pdfStandards = null, float mergedGap = 0f) { - ArgumentNullException.ThrowIfNull(source); + Guard.NotNull(source, nameof(source)); return Execute(compiler => { compiler.SetSource(source); @@ -283,7 +283,7 @@ public ValueTask CompileSourceToDocumentAsync( float mergedGap = 0f, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(source); + Guard.NotNull(source, nameof(source)); return ExecuteAsync(compiler => { compiler.SetSource(source); @@ -316,7 +316,7 @@ public IReadOnlyList CompilePdf( IDictionary? sysInputs = null, IEnumerable? pdfStandards = null) { - ArgumentNullException.ThrowIfNull(destination); + Guard.NotNull(destination, nameof(destination)); using var document = CompileToDocument(sysInputs, format: "pdf", pdfStandards: pdfStandards); document.CopyOutputTo(destination); return document.Warnings; @@ -333,7 +333,7 @@ public async Task> CompilePdfAsync( IEnumerable? pdfStandards = null, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(destination); + Guard.NotNull(destination, nameof(destination)); using var document = await CompileToDocumentAsync(sysInputs, format: "pdf", pdfStandards: pdfStandards, cancellationToken: cancellationToken).ConfigureAwait(false); await document.CopyOutputToAsync(destination, cancellationToken: cancellationToken).ConfigureAwait(false); return document.Warnings; @@ -389,7 +389,7 @@ public PngResult CompilePng( /// public TResult Execute(Func action) { - ArgumentNullException.ThrowIfNull(action); + Guard.NotNull(action, nameof(action)); EnsureNotDisposed(); _semaphore.Wait(); @@ -414,7 +414,7 @@ public async ValueTask ExecuteAsync( Func action, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(action); + Guard.NotNull(action, nameof(action)); EnsureNotDisposed(); await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -471,7 +471,7 @@ private void ReleaseCompiler(TypstCompiler? compiler) private void EnsureNotDisposed() { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + Guard.NotDisposed(Volatile.Read(ref _disposed) != 0, this); } /// diff --git a/src/typstsharp/TypstDocument.cs b/src/typstsharp/TypstDocument.cs index a006c4a..d9af198 100644 --- a/src/typstsharp/TypstDocument.cs +++ b/src/typstsharp/TypstDocument.cs @@ -1,5 +1,7 @@ using System.Buffers; +#if !NETSTANDARD2_1 using Microsoft.Win32.SafeHandles; +#endif namespace typstsharp; @@ -144,7 +146,7 @@ public unsafe Stream OpenOutputStream(int output = 0) /// The zero-based buffer index; defaults to the only buffer of a PDF. public unsafe void CopyOutputTo(Stream destination, int output = 0) { - ArgumentNullException.ThrowIfNull(destination); + Guard.NotNull(destination, nameof(destination)); destination.Write(GetOutputSpan(output)); KeepAlive(); } @@ -162,7 +164,7 @@ public unsafe void CopyOutputTo(Stream destination, int output = 0) /// public async ValueTask CopyOutputToAsync(Stream destination, int output = 0, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(destination); + Guard.NotNull(destination, nameof(destination)); using var manager = CreateBufferManager(output); await destination.WriteAsync(manager.Memory, cancellationToken).ConfigureAwait(false); KeepAlive(); @@ -178,10 +180,17 @@ public async ValueTask CopyOutputToAsync(Stream destination, int output = 0, Can public unsafe void WriteOutputToFile(string path, int output = 0) { var content = GetOutputSpan(output); +#if NETSTANDARD2_1 + using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) + { + stream.Write(content); + } +#else using (var handle = OpenFile(path, content.Length, FileOptions.None)) { RandomAccess.Write(handle, content, fileOffset: 0); } +#endif KeepAlive(); } @@ -196,8 +205,15 @@ public unsafe void WriteOutputToFile(string path, int output = 0) public async Task WriteOutputToFileAsync(string path, int output = 0, CancellationToken cancellationToken = default) { using var manager = CreateBufferManager(output); +#if NETSTANDARD2_1 + using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.Asynchronous)) + { + await stream.WriteAsync(manager.Memory, cancellationToken).ConfigureAwait(false); + } +#else using var handle = OpenFile(path, manager.Memory.Length, FileOptions.Asynchronous); await RandomAccess.WriteAsync(handle, manager.Memory, fileOffset: 0, cancellationToken).ConfigureAwait(false); +#endif KeepAlive(); } @@ -232,6 +248,7 @@ public unsafe byte[] GetOutputBytes(int output = 0) return bytes; } +#if !NETSTANDARD2_1 private static SafeFileHandle OpenFile(string path, long length, FileOptions options) => File.OpenHandle( path, @@ -241,6 +258,7 @@ private static SafeFileHandle OpenFile(string path, long length, FileOptions opt FileShare.Read, options, preallocationSize: length); +#endif /// /// Wraps an output buffer in a so that the asynchronous overloads, @@ -255,7 +273,7 @@ private unsafe NativeBufferMemoryManager CreateBufferManager(int output) private unsafe CsBindgen.Buffer GetBuffer(int output) { - ObjectDisposedException.ThrowIf(IsDisposed, this); + Guard.NotDisposed(IsDisposed, this); if ((uint)output >= (uint)_outputCount) { @@ -353,7 +371,7 @@ internal unsafe OutputStream(TypstDocument owner, byte* pointer, long length) /// public override unsafe int Read(Span buffer) { - ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner); + Guard.NotDisposed(_owner.IsDisposed, _owner); long position = Position; @@ -376,6 +394,30 @@ public override unsafe int Read(Span buffer) // The array-shaped and asynchronous read paths funnel into Read(Span) above. ReadByte is the // exception, and deliberately so: the base already serves it straight from the pointer. +#if NETSTANDARD2_1 + private static void ValidateBufferArguments(byte[] buffer, int offset, int count) + { + Guard.NotNull(buffer, nameof(buffer)); + Guard.NotNegative(offset, nameof(offset)); + Guard.NotNegative(count, nameof(count)); + if (buffer.Length - offset < count) + throw new ArgumentException("Offset and count exceed the buffer length."); + } + + private static void ValidateCopyToArguments(Stream destination, int bufferSize) + { + Guard.NotNull(destination, nameof(destination)); + if (bufferSize <= 0) + throw new ArgumentOutOfRangeException(nameof(bufferSize)); + if (!destination.CanWrite) + { + if (!destination.CanRead) + throw new ObjectDisposedException(nameof(destination)); + throw new NotSupportedException("The destination stream does not support writing."); + } + } +#endif + public override int Read(byte[] buffer, int offset, int count) { ValidateBufferArguments(buffer, offset, count); @@ -384,7 +426,7 @@ public override int Read(byte[] buffer, int offset, int count) public override int ReadByte() { - ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner); + Guard.NotDisposed(_owner.IsDisposed, _owner); int value = base.ReadByte(); GC.KeepAlive(_owner); return value; @@ -403,7 +445,7 @@ public override int ReadByte() public override unsafe void CopyTo(Stream destination, int bufferSize) { ValidateCopyToArguments(destination, bufferSize); - ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner); + Guard.NotDisposed(_owner.IsDisposed, _owner); long position = Position; long remaining = Length - position; @@ -424,7 +466,7 @@ public override unsafe void CopyTo(Stream destination, int bufferSize) public override async Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ValidateCopyToArguments(destination, bufferSize); - ObjectDisposedException.ThrowIf(_owner.IsDisposed, _owner); + Guard.NotDisposed(_owner.IsDisposed, _owner); long position = Position; long remaining = Length - position; diff --git a/src/typstsharp/typstsharp.csproj b/src/typstsharp/typstsharp.csproj index 0846aad..621780b 100644 --- a/src/typstsharp/typstsharp.csproj +++ b/src/typstsharp/typstsharp.csproj @@ -3,7 +3,7 @@ - net10.0;net11.0 + netstandard2.1;net8.0;net10.0;net11.0 enable enable true @@ -16,6 +16,14 @@ $(MSBuildThisFileDirectory) + + 12.0 + + + + + + diff --git a/src/typstsharp/typstsharp.nuspec b/src/typstsharp/typstsharp.nuspec index 5a452dc..2b67615 100644 --- a/src/typstsharp/typstsharp.nuspec +++ b/src/typstsharp/typstsharp.nuspec @@ -10,6 +10,25 @@ $tags$ + + + + + + + + + + + + + + + + + + + @@ -32,6 +51,8 @@ + +