Skip to content

Commit 8abfe1c

Browse files
authored
Use vectorized null-terminated C-string parsing in PtrToStringUTF8 for .NET 6+ (#2466)
1 parent ae744d8 commit 8abfe1c

File tree

1 file changed

+12
-7
lines changed
  • src/Confluent.Kafka/Internal

1 file changed

+12
-7
lines changed

src/Confluent.Kafka/Internal/Util.cs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
// Refer to LICENSE for more information.
1616

1717
using System;
18+
using System.Runtime.InteropServices;
1819
using System.Text;
1920
using SystemMarshal = System.Runtime.InteropServices.Marshal;
2021
using SystemGCHandle = System.Runtime.InteropServices.GCHandle;
@@ -52,31 +53,35 @@ public void Dispose()
5253
}
5354

5455
/// <summary>
55-
/// Interpret a zero terminated c string as UTF-8.
56+
/// Interpret a zero-terminated c string as UTF-8.
5657
/// </summary>
57-
public unsafe static string PtrToStringUTF8(IntPtr strPtr)
58+
public static unsafe string PtrToStringUTF8(IntPtr strPtr)
5859
{
5960
if (strPtr == IntPtr.Zero)
6061
{
6162
return null;
6263
}
6364

64-
// TODO: Is there a built in / vectorized / better way to implement this?
65+
#if NET6_0_OR_GREATER
66+
var span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)strPtr);
67+
return Encoding.UTF8.GetString(span);
68+
#else
6569
byte* pTraverse = (byte*)strPtr;
66-
while (*pTraverse != 0) { pTraverse += 1; }
70+
while (*pTraverse != 0) pTraverse++;
6771
var length = (int)(pTraverse - (byte*)strPtr);
6872

69-
return Encoding.UTF8.GetString((byte*)strPtr.ToPointer(), length);
73+
return Encoding.UTF8.GetString((byte*)strPtr, length);
74+
#endif
7075
}
7176

72-
public unsafe static string PtrToStringUTF8(IntPtr strPtr, UIntPtr strLength)
77+
public static unsafe string PtrToStringUTF8(IntPtr strPtr, UIntPtr strLength)
7378
{
7479
if (strPtr == IntPtr.Zero)
7580
{
7681
return null;
7782
}
7883

79-
return Encoding.UTF8.GetString((byte*)strPtr.ToPointer(), (int)strLength);
84+
return Encoding.UTF8.GetString((byte*)strPtr, (int)strLength);
8085
}
8186

8287
public static T PtrToStructure<T>(IntPtr ptr)

0 commit comments

Comments
 (0)