private string FinishWriteUtf16String(ResizableMemory <byte> data) { try { var span = data.AsSpan(); if (Encodings.Utf8.ToUtf16Length(span, out int bytes) != OperationStatus.Done) { throw new SerializationException("Failed to convert to UTF16"); } var result = new String(' ', bytes / 2); unsafe { fixed(char *pResult = result) { var resultBytes = new Span <byte>((void *)pResult, bytes); if (Encodings.Utf8.ToUtf16(span, resultBytes, out _, out _) != OperationStatus.Done) { throw new SerializationException("Failed to convert to UTF16"); } } } return(result); } finally { _pool.Return(data.Array); } }
private ReadOnlyMemory <byte> FinishWriteUtf16Bytes(ResizableMemory <byte> data) { try { var span = data.AsSpan(); if (Encodings.Utf8.ToUtf16Length(span, out int bytes) != OperationStatus.Done) { throw new SerializationException("Failed to convert to UTF16"); } var utf16 = new byte[bytes]; if (Encodings.Utf8.ToUtf16(span, MemoryMarshal.AsBytes(utf16.AsSpan()), out _, out _) != OperationStatus.Done) { throw new SerializationException("Failed to convert to UTF16"); } return(utf16.AsMemory()); } finally { _pool.Return(data.Array); } }