-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoBitDataBuffer.cs
More file actions
115 lines (97 loc) · 2.83 KB
/
TwoBitDataBuffer.cs
File metadata and controls
115 lines (97 loc) · 2.83 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
public class TwoBitDataBuffer{
public int dataCount { get; private set; }
/// <summary>
/// Construct a new data buffer with the given size.
/// </summary>
/// <param name="dataCount"></param>
public TwoBitDataBuffer(int dataCount)
{
this.dataCount = dataCount;
data = new char[GetCharCount(dataCount)];
}
/// <summary>
/// Loads a data buffer from the given char array.
/// </summary>
public TwoBitDataBuffer(int dataCount, char[] charArray)
{
this.data = charArray;
this.dataCount = dataCount;
}
/// <summary>
/// Sets a value at given index. Value should be 0 ~ 3
/// </summary>
public void SetValue(int index, int targetValue)
{
if (index >= dataCount)
{
Debug.LogError("Index exceeds data count!");
return;
}
targetValue = Mathf.Clamp(targetValue, 0, _DataMaxValue);
int charIndex = index / _ElementPerChar;
int charOffset = index % _ElementPerChar;
var charElement = data[charIndex];
charElement = SetBit(charElement, charOffset * 2, targetValue >= 2);
charElement = SetBit(charElement, charOffset * 2 + 1, targetValue % 2 != 0);
data[charIndex] = charElement;
}
/// <summary>
/// returns a value ranged in 0 ~ 3
/// </summary>
public int GetValue(int index)
{
if (index >= dataCount)
{
Debug.LogError("Index exceeds data count!");
return 0;
}
int charIndex = index / _ElementPerChar;
int charOffset = index % _ElementPerChar;
var charElement = data[charIndex];
int upper = GetBit(charElement, charOffset * 2) ? 2 : 0;
int lower = GetBit(charElement, charOffset * 2 + 1) ? 1 : 0;
return upper + lower;
}
public char[] GetPackedData()
{
return data;
}
public void PrintValues()
{
var str = "values: ";
foreach(var bit in data)
{
str += bit.ToString() + ",";
}
Debug.Log(str);
}
#region Helper
private char[] data;
private const int _ElementPerChar = 4;
private const int _DataMaxValue = 3;
private int GetCharCount(int dataCount)
{
int offset = dataCount % _ElementPerChar > 0 ? 1 : 0;
return dataCount / _ElementPerChar + offset;
}
private char SetBit(char element, int bit, bool value)
{
if (value)
{
return (char) (element | 1 << bit);
}
else
{
return (char) (element & (~(1 << bit)));
}
}
private bool GetBit(char element, int bit)
{
return (element & (1 << bit)) != 0;
}
#endregion
}