using System.Numerics; namespace EvilEngine.Adapters.Oodle; internal static class SmallCodes { public static int Zigzag(int value) { return (value & 1) == 0 ? value >> 1 : -((value + 1) >> 1); } public static int Gamma(ref BitReader bits, int maxZeros) { var zeros = bits.Unary(maxZeros); return (1 << (zeros + 1)) + (int)bits.Read(zeros + 1) - 2; } public static int TruncatedBinary(ref BitReader bits, int count) { var width = 32 - BitOperations.LeadingZeroCount((uint)(count - 1)); var unused = (1 << width) - count; var peeked = (int)bits.Peek(width); if (peeked >> 1 < unused) { bits.Position += width - 1; return peeked >> 1; } bits.Position += width; return peeked - unused; } public static int RangeCount(ref BitReader bits, int symbols) { return symbols == 256 ? 0 : TruncatedBinary(ref bits, 2 * Math.Min(symbols, 257 - symbols)); } public static int[] Ranges(ref BitReader bits, int symbols, ReadOnlySpan widths) { var list = new int[symbols]; var current = 0; var placed = 0; var next = 0; if ((widths.Length & 1) != 0) { var width = widths[next++]; if (width >= 8) throw OodleException.Corrupt("a symbol range's first gap is wider than 8 bits"); current = (int)bits.Read(width + 1) + (1 << (width + 1)) - 1; } for (var pair = 0; pair < widths.Length / 2; pair++) { var countBits = widths[next++]; var gapBits = widths[next++]; if (countBits > 8 || gapBits >= 8) throw OodleException.Corrupt("a symbol range's widths are too wide"); var count = (int)bits.Read(countBits) + (1 << countBits); if (placed + count >= symbols || current + count > 256) throw OodleException.Corrupt("symbol ranges place more symbols than the table codes"); for (var i = 0; i < count; i++) list[placed++] = current++; current += (int)bits.Read(gapBits + 1) + (1 << (gapBits + 1)) - 1; } if (current >= 256 || current + symbols - placed > 256) throw OodleException.Corrupt("the last symbol range runs past symbol 255"); while (placed < symbols) list[placed++] = current++; return list; } }