0.2.0-dev Download ZIP
72 lines ·2.4 KB Raw
| 1 | using System.Numerics; |
| 2 | |
| 3 | namespace EvilEngine.Adapters.Oodle; |
| 4 | |
| 5 | internal static class SmallCodes |
| 6 | { |
| 7 | public static int Zigzag(int value) |
| 8 | { |
| 9 | return (value & 1) == 0 ? value >> 1 : -((value + 1) >> 1); |
| 10 | } |
| 11 | |
| 12 | public static int Gamma(ref BitReader bits, int maxZeros) |
| 13 | { |
| 14 | var zeros = bits.Unary(maxZeros); |
| 15 | return (1 << (zeros + 1)) + (int)bits.Read(zeros + 1) - 2; |
| 16 | } |
| 17 | |
| 18 | public static int TruncatedBinary(ref BitReader bits, int count) |
| 19 | { |
| 20 | var width = 32 - BitOperations.LeadingZeroCount((uint)(count - 1)); |
| 21 | var unused = (1 << width) - count; |
| 22 | var peeked = (int)bits.Peek(width); |
| 23 | if (peeked >> 1 < unused) |
| 24 | { |
| 25 | bits.Position += width - 1; |
| 26 | return peeked >> 1; |
| 27 | } |
| 28 | |
| 29 | bits.Position += width; |
| 30 | return peeked - unused; |
| 31 | } |
| 32 | |
| 33 | public static int RangeCount(ref BitReader bits, int symbols) |
| 34 | { |
| 35 | return symbols == 256 ? 0 : TruncatedBinary(ref bits, 2 * Math.Min(symbols, 257 - symbols)); |
| 36 | } |
| 37 | |
| 38 | public static int[] Ranges(ref BitReader bits, int symbols, ReadOnlySpan<int> widths) |
| 39 | { |
| 40 | var list = new int[symbols]; |
| 41 | var current = 0; |
| 42 | var placed = 0; |
| 43 | var next = 0; |
| 44 | if ((widths.Length & 1) != 0) |
| 45 | { |
| 46 | var width = widths[next++]; |
| 47 | if (width >= 8) |
| 48 | throw OodleException.Corrupt("a symbol range's first gap is wider than 8 bits"); |
| 49 | current = (int)bits.Read(width + 1) + (1 << (width + 1)) - 1; |
| 50 | } |
| 51 | |
| 52 | for (var pair = 0; pair < widths.Length / 2; pair++) |
| 53 | { |
| 54 | var countBits = widths[next++]; |
| 55 | var gapBits = widths[next++]; |
| 56 | if (countBits > 8 || gapBits >= 8) |
| 57 | throw OodleException.Corrupt("a symbol range's widths are too wide"); |
| 58 | var count = (int)bits.Read(countBits) + (1 << countBits); |
| 59 | if (placed + count >= symbols || current + count > 256) |
| 60 | throw OodleException.Corrupt("symbol ranges place more symbols than the table codes"); |
| 61 | for (var i = 0; i < count; i++) |
| 62 | list[placed++] = current++; |
| 63 | current += (int)bits.Read(gapBits + 1) + (1 << (gapBits + 1)) - 1; |
| 64 | } |
| 65 | |
| 66 | if (current >= 256 || current + symbols - placed > 256) |
| 67 | throw OodleException.Corrupt("the last symbol range runs past symbol 255"); |
| 68 | while (placed < symbols) |
| 69 | list[placed++] = current++; |
| 70 | return list; |
| 71 | } |
| 72 | } |