NBTExplorer/Substrate/SubstrateCS/Source/Utility/NibbleArray.cs

137 lines
3.1 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
2011-04-06 21:20:35 +00:00
namespace Substrate.Utility
{
2011-05-08 08:17:20 +00:00
public class NibbleArray : ICopyable<NibbleArray>
{
protected readonly byte[] _data = null;
public NibbleArray (byte[] data)
{
_data = data;
}
2011-05-08 08:17:20 +00:00
public byte this[int index]
{
get
{
int subs = index >> 1;
2011-05-08 08:17:20 +00:00
if ((index & 1) == 0)
{
return (byte)(_data[subs] & 0x0F);
}
2011-05-08 08:17:20 +00:00
else
{
return (byte)((_data[subs] >> 4) & 0x0F);
}
}
set
{
int subs = index >> 1;
2011-05-08 08:17:20 +00:00
if ((index & 1) == 0)
{
_data[subs] = (byte)((_data[subs] & 0xF0) | (value & 0x0F));
}
2011-05-08 08:17:20 +00:00
else
{
_data[subs] = (byte)((_data[subs] & 0x0F) | ((value & 0x0F) << 4));
}
}
}
public int Length
{
get
{
return _data.Length << 1;
}
}
2011-04-16 01:46:46 +00:00
public void Clear ()
{
2011-05-08 08:17:20 +00:00
for (int i = 0; i < _data.Length; i++)
{
2011-04-16 01:46:46 +00:00
_data[i] = 0;
}
}
#region ICopyable<NibbleArray> Members
2011-05-08 08:17:20 +00:00
public virtual NibbleArray Copy ()
{
byte[] data = new byte[_data.Length];
_data.CopyTo(data, 0);
return new NibbleArray(data);
}
#endregion
}
2011-05-08 08:17:20 +00:00
public sealed class XZYNibbleArray : NibbleArray
{
private readonly int _xdim;
private readonly int _ydim;
private readonly int _zdim;
public XZYNibbleArray (int xdim, int ydim, int zdim, byte[] data)
: base(data)
{
_xdim = xdim;
_ydim = ydim;
_zdim = zdim;
if (xdim * ydim * zdim != data.Length * 2)
2011-05-08 08:17:20 +00:00
{
throw new ArgumentException("Product of dimensions must equal half length of raw data");
}
}
public byte this[int x, int y, int z]
{
get
{
int index = _ydim * (x * _zdim + z) + y;
return this[index];
}
set
{
int index = _ydim * (x * _zdim + z) + y;
this[index] = value;
}
}
public int XDim
{
get { return _xdim; }
}
public int YDim
{
get { return _ydim; }
}
public int ZDim
{
get { return _zdim; }
}
#region ICopyable<NibbleArray> Members
public override NibbleArray Copy ()
{
byte[] data = new byte[_data.Length];
_data.CopyTo(data, 0);
return new XZYNibbleArray(_xdim, _ydim, _zdim, data);
}
#endregion
}
}