This repository has been archived by the owner on Nov 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 314
/
Copy pathNibbleSlice.cs
82 lines (72 loc) · 2.15 KB
/
NibbleSlice.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using fNbt;
using fNbt.Serialization;
using System;
using System.Collections.ObjectModel;
namespace TrueCraft.API
{
/// <summary>
/// Represents a slice of an array of 4-bit values.
/// </summary>
public class NibbleSlice : INbtSerializable
{
/// <summary>
/// The data in the nibble array. Each byte contains
/// two nibbles, stored in big-endian.
/// </summary>
public byte[] Data { get; private set; }
public int Offset { get; private set; }
public int Length { get; private set; }
public NibbleSlice(byte[] data, int offset, int length)
{
Data = data;
Offset = offset;
Length = length;
}
/// <summary>
/// Gets or sets a nibble at the given index.
/// </summary>
[NbtIgnore]
public byte this[int index]
{
get { return (byte)(Data[Offset + index / 2] >> (index % 2 * 4) & 0xF); }
set
{
value &= 0xF;
Data[Offset + index / 2] &= (byte)(~(0xF << (index % 2 * 4)));
Data[Offset + index / 2] |= (byte)(value << (index % 2 * 4));
}
}
public byte[] ToArray()
{
byte[] array = new byte[Length];
Buffer.BlockCopy(Data, Offset, array, 0, Length);
return array;
}
public NbtTag Serialize(string tagName)
{
return new NbtByteArray(tagName, ToArray());
}
public void Deserialize(NbtTag value)
{
Length = value.ByteArrayValue.Length;
Buffer.BlockCopy(value.ByteArrayValue, 0,
Data, Offset, Length);
}
}
public class ReadOnlyNibbleArray
{
private NibbleSlice NibbleArray { get; set; }
public ReadOnlyNibbleArray(NibbleSlice array)
{
NibbleArray = array;
}
public byte this[int index]
{
get { return NibbleArray[index]; }
}
public ReadOnlyCollection<byte> Data
{
get { return Array.AsReadOnly(NibbleArray.Data); }
}
}
}