我正在尝试使用System.IO.Pipelines来解析大型文本文件。
但是我找不到从ReadOnlySequence到ReadOnlySequence的转换函数。例如,像MemoryMarshal.Cast<byte,char>。
如果只有一种特殊的类型(字节)适用,那么拥有一个通用的ReadOnlySequence<T>是非常无用的。
static async Task ReadPipeAsync(PipeReader reader, IStringValueFactory factory)
{
while (true)
{
ReadResult result = await reader.ReadAsync();
ReadOnlySequence<byte> buffer = result.Buffer;
//ReadOnlySequence<char> chars = buffer.CastTo<char>(); ???
}
}发布于 2020-01-30 00:25:37
要实现这种转换,您必须编写一个conversion operator。您不能显式强制转换它。请注意,char[]是两个字节,因此需要选择您的编码算法。
如果只有一种特殊的类型(字节)适用,那么拥有一个通用的ReadOnlySequence<T>是非常无用的。
虽然System.IO.Pipelines确实只会给你一个ReadOnlySequence<byte>,因为PipeReader被附加到一个仅仅是字节流的流上,但是ReadOnlySequence<T>还有其他的用例,例如,
ReadOnlySequence<char> roChars = new ReadOnlySequence<char>("some chars".ToCharArray());
ReadOnlySequence<string> roStrings = new ReadOnlySequence<string>(new string[] { "string1", "string2", "Another String" });您的转换操作符将具有与下面类似的逻辑,但您需要适当地设置编码。
static void Main(string[] args)
{
// create a 64k Readonly sequence of random bytes
var ros = new ReadOnlySequence<byte>(GenerateRandomBytes(64000));
//Optionally extract the section of the ReadOnlySequence we are interested in
var mySlice = ros.Slice(22222, 55555);
char[] charArray;
// Check if the slice is a single segment - not really necessary
// included for explanation only
if(mySlice.IsSingleSegment)
{
charArray = Encoding.ASCII.GetString(mySlice.FirstSpan).ToCharArray();
}
else
// Could only do this and always assume multiple spans
// which is highly likley for a PipeReader stream
{
Span<byte> theSpan = new byte[ros.Length];
mySlice.CopyTo(theSpan);
// ASCII Encoding - one byte of span = 2 bytes of char
charArray = Encoding.ASCII.GetString(theSpan).ToCharArray();
}
// Convert the char array back to a ReadOnlySegment<char>
var rosChar = new ReadOnlySequence<char>(charArray);
}
public static byte[] GenerateRandomBytes(int length)
{
// Create a buffer
byte[] randBytes;
if (length >= 1)
randBytes = new byte[length];
else
randBytes = new byte[1];
// Create a new RNGCryptoServiceProvider.
System.Security.Cryptography.RNGCryptoServiceProvider rand =
new System.Security.Cryptography.RNGCryptoServiceProvider();
// Fill the buffer with random bytes.
rand.GetBytes(randBytes);
// return the bytes.
return randBytes;
}https://stackoverflow.com/questions/59950810
复制相似问题