From f44059e16a2471c7f63e3cc0715a71e1058eb5e4 Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Mon, 29 Sep 2025 23:07:05 -0400 Subject: [PATCH] Add XZ variable length helper methods --- SabreTools.Serialization/Extensions/XZ.cs | 58 +++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 SabreTools.Serialization/Extensions/XZ.cs diff --git a/SabreTools.Serialization/Extensions/XZ.cs b/SabreTools.Serialization/Extensions/XZ.cs new file mode 100644 index 00000000..5bb4e9d0 --- /dev/null +++ b/SabreTools.Serialization/Extensions/XZ.cs @@ -0,0 +1,58 @@ +namespace SabreTools.Data.Extensions +{ + public static class XZ + { + /// + /// Decode a value from a variable-length integer + /// + /// Value to decode + /// Maximum number of bytes to parse + /// UInt64 representing the decoded integer + /// + public static ulong DecodeVariableLength(this byte[] value, int maxSize) + { + if (maxSize <= 0) + return 0; + + if (maxSize > 9) + maxSize = 9; + + ulong output = value[0] & 0x7F; + int i = 0; + + while (value[i++] & 0x80 != 0) + { + if (i >= maxSize || value[i] == 0x00) + return 0; + + output |= (value[i] & 0x7F) << (i * 7); + } + + return output; + } + + /// + /// Encode a value to a variable-length integer + /// + /// Value to encode + /// Byte array representing the encoded integer + /// + public static byte[] EncodeVariableLength(this ulong value) + { + if (value > long.MaxValue / 2) + return []; + + var output = new List(); + + int i = 0; + while (value >= 0x80) + { + output.Add((byte)value | 0x80); + value >>= 7; + } + + output.Add((byte)value); + return [.. output]; + } + } +} \ No newline at end of file