| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.IO; |
| | | 6 | | |
| | | 7 | | namespace CoreWCF.Channels |
| | | 8 | | { |
| | | 9 | | internal static class DecoderHelper |
| | | 10 | | { |
| | | 11 | | public static void ValidateSize(int size) |
| | | 12 | | { |
| | | 13 | | if (size <= 0) |
| | | 14 | | { |
| | | 15 | | throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(size), |
| | | 16 | | } |
| | | 17 | | } |
| | | 18 | | } |
| | | 19 | | |
| | | 20 | | internal struct IntDecoder |
| | | 21 | | { |
| | | 22 | | private int _value; |
| | | 23 | | private short _index; |
| | | 24 | | private const int LastIndex = 4; |
| | | 25 | | |
| | | 26 | | public int Value |
| | | 27 | | { |
| | | 28 | | get |
| | | 29 | | { |
| | 409 | 30 | | if (!IsValueDecoded) |
| | | 31 | | { |
| | 0 | 32 | | throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingVa |
| | | 33 | | } |
| | | 34 | | |
| | 409 | 35 | | return _value; |
| | | 36 | | } |
| | | 37 | | } |
| | | 38 | | |
| | 1555 | 39 | | public bool IsValueDecoded { get; private set; } |
| | | 40 | | |
| | | 41 | | public void Reset() |
| | | 42 | | { |
| | 328 | 43 | | _index = 0; |
| | 328 | 44 | | _value = 0; |
| | 328 | 45 | | IsValueDecoded = false; |
| | 328 | 46 | | } |
| | | 47 | | |
| | | 48 | | public int Decode(byte[] buffer, int offset, int size) |
| | | 49 | | { |
| | 409 | 50 | | DecoderHelper.ValidateSize(size); |
| | 409 | 51 | | if (IsValueDecoded) |
| | | 52 | | { |
| | 0 | 53 | | throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueN |
| | | 54 | | } |
| | 409 | 55 | | int bytesConsumed = 0; |
| | 453 | 56 | | while (bytesConsumed < size) |
| | | 57 | | { |
| | 453 | 58 | | int next = buffer[offset]; |
| | 453 | 59 | | _value |= (next & 0x7F) << (_index * 7); |
| | 453 | 60 | | bytesConsumed++; |
| | 453 | 61 | | if (_index == LastIndex && (next & 0xF8) != 0) |
| | | 62 | | { |
| | 0 | 63 | | throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.FramingSizeToo |
| | | 64 | | } |
| | 453 | 65 | | _index++; |
| | 453 | 66 | | if ((next & 0x80) == 0) |
| | | 67 | | { |
| | 409 | 68 | | IsValueDecoded = true; |
| | 409 | 69 | | break; |
| | | 70 | | } |
| | 44 | 71 | | offset++; |
| | | 72 | | } |
| | 409 | 73 | | return bytesConsumed; |
| | | 74 | | } |
| | | 75 | | } |
| | | 76 | | } |