Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use built-in "CreateReadOnlySpanFromNullTerminated" on NET6-specific path #2207

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/Confluent.Kafka/Internal/Util.cs
Expand Up @@ -16,6 +16,9 @@

using System;
using System.Text;
#if NET6_0_OR_GREATER
using System.Runtime.InteropServices;
#endif
using SystemMarshal = System.Runtime.InteropServices.Marshal;
using SystemGCHandle = System.Runtime.InteropServices.GCHandle;
using SystemGCHandleType = System.Runtime.InteropServices.GCHandleType;
Expand All @@ -31,7 +34,7 @@ internal static class Marshal
/// Convenience class for generating and pinning the UTF8
/// representation of a string.
/// </summary>
public class StringAsPinnedUTF8 : IDisposable
public sealed class StringAsPinnedUTF8 : IDisposable
{
private SystemGCHandle gch;

Expand Down Expand Up @@ -60,13 +63,18 @@ public unsafe static string PtrToStringUTF8(IntPtr strPtr)
{
return null;
}


#if NET6_0_OR_GREATER
var bytes = MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)strPtr.ToPointer());
return Encoding.UTF8.GetString(bytes);
#else
// TODO: Is there a built in / vectorized / better way to implement this?
byte* pTraverse = (byte*)strPtr;
while (*pTraverse != 0) { pTraverse += 1; }
var length = (int)(pTraverse - (byte*)strPtr);

return Encoding.UTF8.GetString((byte*)strPtr.ToPointer(), length);
#endif
}

public unsafe static string PtrToStringUTF8(IntPtr strPtr, UIntPtr strLength)
Expand Down