c# - 如何有效地用流包装字符串(在 .NET 中)?

标签 c# string stream

<分区>

字符串转流的问题比较多,例如:

还有很多其他的。

但是,我还没有看到不复制原始字符串占用的内存的实现。最简单的建议是将字符串转换为字节并从中初始化一个 MemoryStream

另一个建议是将它写入StreamWriter 包裹一个MemoryStream

它们都不是内存有效的。

我带来它的原因是我必须处理一个遗留系统,它出于纯粹的愚蠢而产生了一个巨大的字符串。现在我需要对该字符串应用某些后处理并将其写入文件,我只是不想复制该死的东西。所以,我正在寻找一种内存高效的方法来做到这一点。

最佳答案

编写自定义Stream 派生类并不难,但在这种特殊情况下具有挑战性的部分是需要Encoding 支持。这是一个只读向前的实现,它使用一个小缓冲区来在需要时容纳一个完整的字符字节:

public static class StringUtils
{
    public static Stream AsStream(this string source, Encoding encoding = null)
    {
        return string.IsNullOrEmpty(source) ? Stream.Null : new StringStream(source, encoding ?? Encoding.UTF8);
    }

    class StringStream : Stream
    {
        string source;
        Encoding encoding;
        int position, length;
        int charPosition;
        int maxBytesPerChar;
        byte[] encodeBuffer;
        int encodeOffset, encodeCount;

        internal StringStream(string source, Encoding encoding)
        {
            this.source = source;
            this.encoding = encoding;
            length = encoding.GetByteCount(source);
            maxBytesPerChar = encoding.GetMaxByteCount(1);
        }

        public override bool CanRead { get { return true; } }
        public override bool CanSeek { get { return false; } }
        public override bool CanWrite { get { return false; } }
        public override long Length { get { return length; } }
        public override void SetLength(long value) { throw new NotSupportedException(); }
        public override long Position { get { return position; } set { throw new NotSupportedException(); } }
        public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
        public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
        public override void Flush() { }
        public override int Read(byte[] buffer, int offset, int count)
        {
            int readCount = 0;
            for (int byteCount; readCount < count && position < length; position += byteCount, readCount += byteCount)
            {
                if (encodeCount == 0)
                {
                    int charCount = Math.Min((count - readCount) / maxBytesPerChar, source.Length - charPosition);
                    if (charCount > 0)
                    {
                        byteCount = encoding.GetBytes(source, charPosition, charCount, buffer, offset + readCount);
                        Debug.Assert(byteCount > 0 && byteCount <= (count - readCount));
                        charPosition += charCount;
                        continue;
                    }
                    if (encodeBuffer == null) encodeBuffer = new byte[maxBytesPerChar];
                    encodeCount = encoding.GetBytes(source, charPosition, 1, encodeBuffer, encodeOffset = 0);
                    Debug.Assert(encodeCount > 0);
                }
                byteCount = Math.Min(encodeCount, count - readCount);
                for (int i = 0; i < byteCount; i++)
                    buffer[offset + readCount + i] = encodeBuffer[encodeOffset + i];
                encodeOffset += byteCount;
                if ((encodeCount -= byteCount) == 0) charPosition++;
            }
            return readCount;
        }
    }
}

关于c# - 如何有效地用流包装字符串(在 .NET 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160023/

相关文章:

c# - Controller 中带有 MVC 5 的 Unity DI

C# 从 List<Item> 中查找所有匹配项

c# - 当两个类相同时,是否可以将一个对象转换为另一个对象?

c# - 我的单例实现是否正确? C#

c++ - 我将如何准确地获取打开的文件和文件中的名称并将它们放入我的字符串 vector 中?

c - 解析文本文件的简单方法?

c - 实现一个简单的shell

node.js - 处理 Node.js 中未使用的流

java - ObjectStream 中可变对象的影响

node.js - Nodejs 在 ZIP 文件流传输期间阻塞并且无法处理下一个请求