Table of Contents

Class HuffmanCode

Namespace
FishMMO.Shared
Assembly
FishMMO.Shared.dll

A static, canonical Huffman code over bytes, for compressing whole network packets with a table both peers already hold (no table on the wire). Every byte value has a code, so any packet can be encoded; codes are at most MaximumCodeLength bits, so decoding is one table lookup per byte.

public sealed class HuffmanCode
Inheritance
HuffmanCode
Inherited Members

Remarks

Bits are written least significant first (as DEFLATE does), with each code stored bit-reversed so the decoder can index its table with the next MaximumCodeLength bits directly. The code is defined entirely by the 256 code lengths (Lengths), which is what a trained table stores.

Constructors

HuffmanCode(byte[])

Builds the code from 256 code lengths, which must describe a complete prefix code.

public HuffmanCode(byte[] lengths)

Parameters

lengths byte[]

Exceptions

ArgumentException

The lengths are not 256 values of 1..15 forming a complete code.

Fields

MaximumCodeLength

Longest code, in bits. 15 keeps the decode table at 32,768 entries.

public const int MaximumCodeLength = 15

Field Value

int

Properties

Lengths

The code length of each byte value, 1..MaximumCodeLength.

public byte[] Lengths { get; }

Property Value

byte[]

Methods

BuildLengths(long[])

Code lengths for byte frequencies: an optimal Huffman code, flattened until no code is longer than MaximumCodeLength. Bytes never seen are counted once, so every byte stays encodable.

public static byte[] BuildLengths(long[] frequencies)

Parameters

frequencies long[]

Returns

byte[]

Decode(ReadOnlySpan<byte>, Span<byte>)

Decodes exactly destination.Length bytes from source. False when the source runs out first (a damaged or foreign packet).

public bool Decode(ReadOnlySpan<byte> source, Span<byte> destination)

Parameters

source ReadOnlySpan<byte>
destination Span<byte>

Returns

bool

Encode(ReadOnlySpan<byte>, Span<byte>)

Encodes source into destination. Returns the bytes written, or -1 when they would not fit (the caller then sends the packet uncompressed).

public int Encode(ReadOnlySpan<byte> source, Span<byte> destination)

Parameters

source ReadOnlySpan<byte>
destination Span<byte>

Returns

int

EncodedBits(long[])

The bits a byte histogram would take under this code.

public long EncodedBits(long[] histogram)

Parameters

histogram long[]

Returns

long

EncodedBits(ReadOnlySpan<byte>)

The bits data would take under this code (no header).

public long EncodedBits(ReadOnlySpan<byte> data)

Parameters

data ReadOnlySpan<byte>

Returns

long