-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNstate.hpp
420 lines (348 loc) · 13.4 KB
/
Nstate.hpp
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//
// Nstate.hpp - Template for variable that can only take on values
// from [0..radix-1], and an array type which is able to
// store a series of these variables and take advantage of
// the knowledge of the constraint in order to compact them
// closer to their fundamentally minimal size.
//
// Copyright (c) 2009-2012 HostileFork.com
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://hostilefork.com/nstate for documentation.
//
#pragma once
#include "NocycleConfig.hpp"
#include <vector>
#include <map>
#include <exception>
#include <cmath>
// REVIEW: std::numeric_limits?
#include <climits>
#include <cassert>
//
// NSTATE
//
namespace nocycle {
// see: http://www.cplusplus.com/doc/tutorial/exceptions.html
class bad_nstate : public std::exception {
virtual const char* what() const throw() {
return "Invalid Nstate value";
}
};
typedef unsigned PackedTypeForNstate;
template<int radix>
class Nstate {
private:
unsigned m_value; // ranges from [0..radix-1]
private:
void ThrowExceptionIfBadValue() {
if (m_value >= radix) {
bad_nstate bt;
throw bt;
}
}
public:
// constructor is also implicit cast operator from unsigned
// see: http://www.acm.org/crossroads/xrds3-1/ovp3-1.html
Nstate(unsigned value) : m_value (value) {
ThrowExceptionIfBadValue();
}
// default constructor setting value to zero... good idea? Bad idea?
Nstate() : m_value (0) {
ThrowExceptionIfBadValue();
}
// implicit cast operator to unsigned
operator unsigned() const {
return m_value;
}
// "A base class destructor should be either public and virtual,
// or protected and nonvirtual."
// http://www.gotw.ca/publications/mill18.htm
public:
virtual ~Nstate() { }
#if NSTATE_SELFTEST
public:
static bool SelfTest(); // Class is self-testing for regression
#endif
};
class PowerTable {
private:
std::vector<unsigned> m_table;
public:
PowerTable (unsigned radix) {
unsigned nstatesInUnsigned = static_cast<unsigned>(floor(log(2)/log(radix)*CHAR_BIT*sizeof(unsigned)));
PackedTypeForNstate value = 1;
for (unsigned index = 0; index < nstatesInUnsigned; index++) {
m_table.push_back(value);
value = value * radix;
}
}
inline size_t NstatesInPackedType() const {
return m_table.size();
}
inline PackedTypeForNstate PowerForDigit(unsigned digit) const {
assert(digit < m_table.size());
return m_table[digit];
}
public:
virtual ~PowerTable () { }
};
//
// NSTATE ARRAY
//
// TODO:
// * iterators?
// * 64-bit packing or something more clever?
// * memory-mapped file implementation, with standardized packing/order
// (to work across platforms)?
template <int radix>
class NstateArray {
private:
// Note: Typical library limits of the STL for vector lengths
// are things like 1,073,741,823...
std::vector<PackedTypeForNstate> m_buffer;
size_t m_max;
private:
static const PowerTable& GetPowerTableInstance() {
// We wish to cache the PowerTable so that all NstateArray instances of the same
// radix share the same one. This is hard to do correctly and/or elegantly in
// a way that is befitting a "general" class library.
// http://stackoverflow.com/questions/9507973/how-to-mitigate-user-facing-api-effect-of-shared-members-in-templated-classes
// The power tables are not that large, and in C++11 code this is guaranteed to
static const PowerTable instance (radix);
return instance;
}
static size_t NstatesInPackedType() {
return GetPowerTableInstance().NstatesInPackedType();
}
static PackedTypeForNstate PowerForDigit(unsigned digit) {
return GetPowerTableInstance().PowerForDigit(digit);
}
private:
Nstate<radix> GetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit) const;
PackedTypeForNstate SetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit, Nstate<radix> t) const;
public:
// Derived from boost's dynamic_bitset
// http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html
class reference;
friend class NstateArray<radix>::reference;
class reference {
friend class NstateArray<radix>;
private:
NstateArray<radix>& m_na;
unsigned m_indexIntoBuffer;
unsigned m_digit;
reference(NstateArray<radix> &na, size_t indexIntoBuffer, unsigned digit) :
m_na (na),
m_indexIntoBuffer (indexIntoBuffer),
m_digit (digit)
{
}
void operator&(); // not defined
void do_assign(Nstate<radix> x) {
m_na.m_buffer[m_indexIntoBuffer] =
m_na.SetDigitInPackedValue(m_na.m_buffer[m_indexIntoBuffer], m_digit, x);
}
public:
// An automatically generated copy constructor.
reference& operator=(Nstate<radix> x) { do_assign(x); return *this; } // for b[i] = x
reference& operator=(const reference& rhs) { do_assign(rhs); return *this; } // for b[i] = b[j]
operator Nstate<radix>() const {
return m_na.GetDigitInPackedValue(m_na.m_buffer[m_indexIntoBuffer], m_digit);
}
operator unsigned() const {
return m_na.GetDigitInPackedValue(m_na.m_buffer[m_indexIntoBuffer], m_digit);
}
};
reference operator[](size_t pos) {
assert(pos < m_max); // STL will only check bounds on integer boundaries
size_t indexIntoBuffer = pos / NstatesInPackedType();
unsigned digit = pos % NstatesInPackedType();
return reference (*this, indexIntoBuffer, digit);
}
Nstate<radix> operator[](size_t pos) const {
assert(pos < m_max); // STL will only check bounds on integer boundaries.
size_t indexIntoBuffer = pos / NstatesInPackedType();
unsigned digit = pos % NstatesInPackedType();
return GetDigitInPackedValue(m_buffer[indexIntoBuffer], digit);
}
// by convention, we resize and fill available space with zeros if expanding
void ResizeWithZeros(size_t max) {
size_t oldBufferSize = m_buffer.size();
size_t newBufferSize = max / NstatesInPackedType() +
(max % NstatesInPackedType() == 0 ? 0 : 1);
unsigned oldMaxDigitNeeded = m_max % NstatesInPackedType();
if ((oldMaxDigitNeeded == 0) && (m_max > 0))
oldMaxDigitNeeded = NstatesInPackedType();
unsigned newMaxDigitNeeded = max % NstatesInPackedType();
if ((newMaxDigitNeeded == 0) && (max > 0))
newMaxDigitNeeded = NstatesInPackedType();
m_buffer.resize(newBufferSize, 0 /* fill value */);
m_max = max;
if ((newBufferSize == oldBufferSize) && (newMaxDigitNeeded < oldMaxDigitNeeded)) {
// If we did not change the size of the buffer but merely the number of
// nstates we are fitting in the lastmost packed value, we must set
// the trailing unused nstates to zero if we are using fewer nstates
// than we were before
for (auto eraseDigit = newMaxDigitNeeded; eraseDigit < oldMaxDigitNeeded; eraseDigit++) {
m_buffer[newBufferSize - 1] =
SetDigitInPackedValue(m_buffer[newBufferSize - 1], eraseDigit, 0);
}
} else if ((newBufferSize < oldBufferSize) && (newMaxDigitNeeded > 0)) {
// If the number of tristates we are using isn't an even multiple of the
// # of states that fit in a packed type, then shrinking will leave some
// residual values we need to reset to zero in the last element of the vector.
for (auto eraseDigit = newMaxDigitNeeded; eraseDigit < NstatesInPackedType(); eraseDigit++) {
m_buffer[newBufferSize - 1] =
SetDigitInPackedValue(m_buffer[newBufferSize - 1], eraseDigit, 0);
}
}
}
size_t Length() const {
return m_max;
}
// Constructors and destructors
public:
NstateArray<radix>(const size_t initial_size) :
m_max (0)
{
ResizeWithZeros(initial_size);
}
virtual ~NstateArray<radix> ()
{
}
#if NSTATE_SELFTEST
public:
static bool SelfTest(); // Class is self-testing for regression
#endif
};
//
// Static member functions
//
template <int radix>
Nstate<radix> NstateArray<radix>::GetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit) const {
// Generalized from Mark Bessey's post in the Joel on Software forum
// http://discuss.joelonsoftware.com/default.asp?joel.3.205331.14
assert(digit < NstatesInPackedType());
// lop off unused top digits - you can skip this
// for the most-significant digit
PackedTypeForNstate value = packed;
if (digit < (NstatesInPackedType()-1)) {
value = value % PowerForDigit(digit+1);
}
// truncate lower digit
value = value / PowerForDigit(digit);
return value;
}
template <int radix>
PackedTypeForNstate NstateArray<radix>::SetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit, Nstate<radix> t) const {
assert(digit < NstatesInPackedType());
PackedTypeForNstate powForDigit = PowerForDigit(digit);
PackedTypeForNstate upperPart = 0;
if (digit < (NstatesInPackedType() - 1)) {
PackedTypeForNstate powForDigitPlusOne = PowerForDigit(digit + 1);
upperPart = (packed / powForDigitPlusOne) * powForDigitPlusOne;
}
PackedTypeForNstate setPart = t * powForDigit;
PackedTypeForNstate lowerPart = 0;
if (digit > 0)
lowerPart = packed % powForDigit;
return upperPart + setPart + lowerPart;
}
} // temporary end of namespace nocycle
#if NSTATE_SELFTEST
//
// CODE FOR SELF-TESTS
//
// See: http://gcc.gnu.org/ml/gcc-bugs/2000-12/msg00168.html
// "If the definitions of member functions of a template aren't visible
// when the template is instantiated, they won't be instantiated. You
// must define template member functions in the header file itself, at
// least until the `export' keyword is implemented."
//
#include <cstdlib>
#include <iostream>
namespace nocycle {
template <int radix>
bool Nstate<radix>::SelfTest() {
for (unsigned test = 0; test < radix; test++) {
Nstate<radix> t (test);
if (t != test) {
std::cout << "FAILURE: Nstates did not preserve values properly." << std::endl;
return false;
}
}
try {
Nstate<radix> t3 (radix);
std::cout << "FAILURE: Did not detect bad Nstate construction." << std::endl;
return false;
} catch (bad_nstate& e) {
}
try {
Nstate<radix> tSet (0);
tSet = radix;
std::cout << "FAILURE: Did not detect bad Nstate SetValue." << std::endl;
return false;
} catch (bad_nstate& e) {
}
return true;
}
template <int radix>
bool NstateArray<radix>::SelfTest() {
// Basic allocation and set test
for (size_t initialSize = 0; initialSize < 1024; initialSize++) {
NstateArray<radix> nv (initialSize);
std::vector<unsigned> v (initialSize);
for (size_t index = 0; index < initialSize; index++) {
Nstate<radix> tRand (rand() % radix);
nv[index] = tRand;
v[index] = tRand;
}
for (size_t index = 0; index < initialSize; index++) {
if (nv[index] != v[index]) {
std::cout << "FAILURE: On NstateArray[" << initialSize << "] for size " << initialSize
<< ", a value was recorded as " << static_cast<int>(nv[index])
<< " when it should have been " << static_cast<int>(v[index]) << std::endl;
return false;
}
}
// Try resizing it to some smaller size
size_t newSmallerSize;
if (initialSize == 0)
newSmallerSize = 0;
else {
newSmallerSize = (rand() % initialSize);
nv.ResizeWithZeros(newSmallerSize);
v.resize(newSmallerSize, 0);
assert(nv.Length() == v.size());
for (size_t index = 0; index < newSmallerSize; index++) {
if (nv[index] != v[index]) {
std::cout << "FAILURE: On NstateArray[" << initialSize << "] after resize from " << initialSize
<< " to " << newSmallerSize
<< ", a value was recorded as " << static_cast<int>(nv[index])
<< " when it should have been " << static_cast<int>(v[index]) << std::endl;
return false;
}
}
}
// Try resizing it to some larger size
size_t newLargerSize = newSmallerSize + (rand() % 128);
nv.ResizeWithZeros(newLargerSize);
v.resize(newLargerSize, 0);
assert(nv.Length() == v.size());
for (size_t index = 0; index < newLargerSize; index++) {
if (nv[index] != v[index]) {
std::cout << "FAILURE: On NstateArray[" << initialSize << "] after resize from " << newSmallerSize
<< " to " << newLargerSize
<< ", a value was recorded as " << static_cast<int>(nv[index])
<< " when it should have been " << static_cast<int>(v[index]) << std::endl;
return false;
}
}
}
return true;
}
} // end namespace nocycle
#endif