-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* - Added public `Define` methods for all externs. - Removed method which accepted an `object` parameter and dynamically checked that it was an extern. * Fixed name/module byte conversion * Improved system for converting `string` into `Span<byte>` with zero allocations. Replaces ad-hoc implementations used around the codebase.
- Loading branch information
1 parent
1aac330
commit 9562c78
Showing
3 changed files
with
67 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using System; | ||
using System.Buffers; | ||
using System.Text; | ||
|
||
namespace Wasmtime | ||
{ | ||
internal static class StringExtensions | ||
{ | ||
public static TemporaryAllocation ToUTF8(this string value, Span<byte> bytes) | ||
{ | ||
return TemporaryAllocation.FromString(value, bytes); | ||
} | ||
} | ||
|
||
internal readonly ref struct TemporaryAllocation | ||
{ | ||
public readonly Span<byte> Span; | ||
private readonly byte[]? _rented; | ||
|
||
public int Length => Span.Length; | ||
|
||
private TemporaryAllocation(Span<byte> span, byte[]? rented) | ||
{ | ||
Span = span; | ||
_rented = rented; | ||
} | ||
|
||
public static TemporaryAllocation FromString(string str, Span<byte> output) | ||
{ | ||
var length = Encoding.UTF8.GetByteCount(str); | ||
|
||
if (length <= output.Length) | ||
{ | ||
Encoding.UTF8.GetBytes(str, output); | ||
return new TemporaryAllocation(output[..length], null); | ||
} | ||
|
||
var rented = ArrayPool<byte>.Shared.Rent(length); | ||
Encoding.UTF8.GetBytes(str, rented); | ||
return new TemporaryAllocation(rented[..length], rented); | ||
} | ||
|
||
/// <summary> | ||
/// Recycle rented memory | ||
/// </summary> | ||
public void Dispose() | ||
{ | ||
if (_rented != null) | ||
{ | ||
ArrayPool<byte>.Shared.Return(_rented); | ||
} | ||
} | ||
} | ||
} |