Exemplo n.º 1
0
    static void test_bitpacker()
    {
        Debug.Log("test_bitpacker");

        const int BufferSize = 256;

        uint[] buffer = new uint[BufferSize];

        var writer = new Network.BitWriter();

        writer.Start(buffer);

        Assert.IsTrue(writer.GetTotalBytes() == BufferSize);
        Assert.IsTrue(writer.GetBitsWritten() == 0);
        Assert.IsTrue(writer.GetBytesWritten() == 0);
        Assert.IsTrue(writer.GetBitsAvailable() == BufferSize * 8);

        writer.WriteBits(0, 1);
        writer.WriteBits(1, 1);
        writer.WriteBits(10, 8);
        writer.WriteBits(255, 8);
        writer.WriteBits(1000, 10);
        writer.WriteBits(50000, 16);
        writer.WriteBits(9999999, 32);

        writer.Finish();

        const int bitsWritten = 1 + 1 + 8 + 8 + 10 + 16 + 32;

        Assert.IsTrue(writer.GetBytesWritten() == 10);
        Assert.IsTrue(writer.GetTotalBytes() == BufferSize);
        Assert.IsTrue(writer.GetBitsWritten() == bitsWritten);
        Assert.IsTrue(writer.GetBitsAvailable() == BufferSize * 8 - bitsWritten);

        int bytesWritten = writer.GetBytesWritten();

        const int ExpectedBytesWritten = 10;

        Assert.IsTrue(bytesWritten == ExpectedBytesWritten);

        byte[] readBuffer = writer.GetData();

        Assert.IsTrue(readBuffer.Length == ExpectedBytesWritten);

        var reader = new Network.BitReader();

        reader.Start(readBuffer);

        Assert.IsTrue(reader.GetBitsRead() == 0);
        Assert.IsTrue(reader.GetBitsRemaining() == bytesWritten * 8);

        uint a = reader.ReadBits(1);
        uint b = reader.ReadBits(1);
        uint c = reader.ReadBits(8);
        uint d = reader.ReadBits(8);
        uint e = reader.ReadBits(10);
        uint f = reader.ReadBits(16);
        uint g = reader.ReadBits(32);

        reader.Finish();

        Assert.IsTrue(a == 0);
        Assert.IsTrue(b == 1);
        Assert.IsTrue(c == 10);
        Assert.IsTrue(d == 255);
        Assert.IsTrue(e == 1000);
        Assert.IsTrue(f == 50000);
        Assert.IsTrue(g == 9999999);

        Assert.IsTrue(reader.GetBitsRead() == bitsWritten);
        Assert.IsTrue(reader.GetBitsRemaining() == bytesWritten * 8 - bitsWritten);
    }