// --------------------------------------------------------------------------------------------------------------------
//
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
//
//
// Handles the encoding of bits for compression.
//
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Formats
{
using System.Collections.Generic;
///
/// Handles the encoding of bits for compression.
///
internal class BitEncoder
{
///
/// The current working bit.
///
private int currentBit;
///
/// The current value.
///
private int currentValue;
///
/// The inner list for collecting the bits.
///
private readonly List list = new List();
///
/// The number of bytes in the encoder.
///
internal int Length => this.list.Count;
///
/// Gets or sets the intitial bit.
///
public int IntitialBit { get; set; }
///
/// Initializes a new instance of the class.
///
///
/// The initial bits.
///
public BitEncoder(int initial)
{
this.IntitialBit = initial;
}
///
/// Adds the current byte to the end of the encoder.
///
///
/// The byte to add.
///
public void Add(int item)
{
this.currentValue |= item << this.currentBit;
this.currentBit += this.IntitialBit;
while (this.currentBit >= 8)
{
byte value = (byte)(this.currentValue & 0XFF);
this.currentValue = this.currentValue >> 8;
this.currentBit -= 8;
this.list.Add(value);
}
}
///
/// Adds the collection of bytes to the end of the encoder.
///
///
/// The collection of bytes to add.
/// The collection itself cannot be null but can contain elements that are null.
public void AddRange(byte[] collection)
{
this.list.AddRange(collection);
}
///
/// The end.
///
internal void End()
{
while (this.currentBit > 0)
{
byte value = (byte)(this.currentValue & 0XFF);
this.currentValue = this.currentValue >> 8;
this.currentBit -= 8;
this.list.Add(value);
}
}
///
/// Copies a range of elements from the encoder to a compatible one-dimensional array,
/// starting at the specified index of the target array.
///
///
/// The zero-based index in the source at which copying begins.
///
///
/// The one-dimensional Array that is the destination of the elements copied
/// from . The Array must have zero-based indexing
///
/// The zero-based index in array at which copying begins.
/// The number of bytes to copy.
public void CopyTo(int index, byte[] array, int arrayIndex, int count)
{
this.list.CopyTo(index, array, arrayIndex, count);
}
///
/// Removes all the bytes from the encoder.
///
public void Clear()
{
this.list.Clear();
}
///
/// Copies the bytes into a new array.
///
///
public byte[] ToArray()
{
return this.list.ToArray();
}
}
}