Last active
October 29, 2016 06:38
-
-
Save franky47/2cbb2f1a63409b6af8376d2d35a87bcf to your computer and use it in GitHub Desktop.
Snippet for Neil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <inttypes.h> | |
#include <cstring> | |
#define _STRINGIFY(LitteralString) #LitteralString | |
#define STRINGIFY(LitteralString) _STRINGIFY(LitteralString) | |
#define ASSERT(expr) \ | |
{ \ | |
if (!(expr)) \ | |
{ \ | |
std::cout << "Assertion failed line " << __LINE__ << ": "; \ | |
std::cout << STRINGIFY(expr) << std::endl; \ | |
return 1; \ | |
} \ | |
} | |
typedef uint8_t byte; | |
// -------------------------------------------------------------------------- | |
template<unsigned Size> | |
struct NoteBuffer | |
{ | |
public: | |
inline NoteBuffer() | |
: mIndex(0) | |
{ | |
} | |
inline void reset() | |
{ | |
std::memset(mData, 0xff, Size * sizeof(byte)); | |
mIndex = 0; | |
} | |
inline void push(byte inNoteNumber) | |
{ | |
if (!has(inNoteNumber)) | |
{ | |
mData[mIndex++] = inNoteNumber; | |
} | |
} | |
inline bool has(byte inNoteNumber) const | |
{ | |
for (const byte* it = mData; it < mData + mIndex; ++it) | |
{ | |
if (*it == inNoteNumber) | |
{ | |
return true; | |
} | |
} | |
return false; | |
} | |
inline byte pop() | |
{ | |
if (mIndex == 0) | |
{ | |
return 0xff; | |
} | |
else | |
{ | |
return mData[--mIndex]; | |
} | |
} | |
byte mData[Size]; | |
unsigned mIndex; | |
}; | |
// -------------------------------------------------------------------------- | |
int main() | |
{ | |
typedef NoteBuffer<8> Buffer; | |
Buffer buffer; | |
buffer.reset(); | |
buffer.push(12); | |
buffer.push(34); | |
buffer.push(56); | |
ASSERT(buffer.mIndex == 3); | |
ASSERT(buffer.has(56)); | |
ASSERT(buffer.has(12)); | |
ASSERT(buffer.has(34)); | |
ASSERT(buffer.pop() == 56); | |
ASSERT(buffer.pop() == 34); | |
ASSERT(buffer.pop() == 12); | |
ASSERT(!buffer.has(56)); | |
ASSERT(!buffer.has(12)); | |
ASSERT(!buffer.has(34)); | |
std::cout << "All tests passed" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment