Native memory stream length may be incorrect after calling Write (original) (raw)

This repository was archived by the owner on Dec 22, 2023. It is now read-only.

This repository was archived by the owner on Dec 22, 2023. It is now read-only.

@BetaOptimization

Description

The Write method always adds the buffer's length to the stream's length which causes an incorrect value when the position is not at the end of the stream. The fix is to change
length += count;
on line 84 to
length = Math.Max(length, position);

You can test this as follows:

using System;
using System.IO;
using ScintillaNET;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ScintillaNET.Tests
{
[TestClass]
public class NativeMemoryStreamTests
{
[TestMethod]
public void StreamLengthTest()
{
// the way it ought to work
StreamLengthTest(() => new MemoryStream());
// the way we work
StreamLengthTest(() => new NativeMemoryStream(10));
}

    public void StreamLengthTest(Func<Stream> streamMaker)
    {
        using (var stream = streamMaker())
        {
            var buffer = new byte[] { 2, 3, 4 };
            stream.Write(buffer, 0, 3);
            Assert.AreEqual(3, stream.Length);
            stream.Write(buffer, 0, 3);
            Assert.AreEqual(6, stream.Length);
            stream.Seek(0, SeekOrigin.Begin);
            stream.Write(buffer, 0, 3);
            Assert.AreEqual(6, stream.Length);
            stream.Seek(4, SeekOrigin.Begin);
            stream.Write(buffer, 0, 3);
            Assert.AreEqual(7, stream.Length);
        }
    }
}

}