From 5959b149a60877d876b42f24cd3ca81243186e9b Mon Sep 17 00:00:00 2001 From: DwarfiusDan Date: Wed, 22 Jan 2025 11:40:29 +0000 Subject: [PATCH] Update: add VarInt U64 buffer read&write utility funcs Allows to avoid interacting with a stream and it's bookkeeping. Tests: Used as part of server demo playback --- .../ProtocolParser/ProtocolParserVarInt.cs | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/CodeGenerator/ProtocolParser/ProtocolParserVarInt.cs b/CodeGenerator/ProtocolParser/ProtocolParserVarInt.cs index 3f4dbe5..b660b04 100644 --- a/CodeGenerator/ProtocolParser/ProtocolParserVarInt.cs +++ b/CodeGenerator/ProtocolParser/ProtocolParserVarInt.cs @@ -266,6 +266,41 @@ public static ulong ReadUInt64(Stream stream) throw new ProtocolBufferException("Got larger VarInt than 64 bit unsigned"); } + /// + /// Unsigned VarInt format + /// + public static ulong ReadUInt64(byte[] array, int pos, out int length) + { + ulong val = 0; + length = 0; + + for (byte n = 0; n < 10; n++) + { + length++; + + if(pos >= array.Length) + { + break; + } + + byte b = array[pos++]; + if (b < 0) + throw new IOException("Stream ended too early"); + + //Check that it fits in 64 bits + if ((n == 9) && (b & 0xFE) != 0) + throw new ProtocolBufferException("Got larger VarInt than 64 bit unsigned"); + //End of check + + if ((b & 0x80) == 0) + return val | (ulong) b << (7 * n); + + val |= (ulong) (b & 0x7F) << (7 * n); + } + + throw new ProtocolBufferException("Got larger VarInt than 64 bit unsigned"); + } + /// /// Unsigned VarInt format /// @@ -289,6 +324,31 @@ public static void WriteUInt64(Stream stream, ulong val) } } + /// + /// Unsigned VarInt format + /// + public static int WriteUInt64(ulong val, byte[] buffer, int pos) + { + int len = 0; + while (true) + { + len++; + byte b = (byte)(val & 0x7F); + val = val >> 7; + if (val == 0) + { + buffer[pos] = b; + break; + } + else + { + b |= 0x80; + buffer[pos++] = b; + } + } + return len; + } + #endregion #region Varint: bool