Skip to content

Instantly share code, notes, and snippets.

@jocopa3
Last active July 10, 2016 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jocopa3/c130621c9bb6f11f6730c111b3b761a5 to your computer and use it in GitHub Desktop.
Save jocopa3/c130621c9bb6f11f6730c111b3b761a5 to your computer and use it in GitHub Desktop.
// Class wich emulates MCW10 32-byte strings
// Super basic
class String
{
union {
char charBuffer[16];
char* charPtr;
};
size_t Length = 0;
size_t Capacity = 0;
public:
String(std::string str)
{
unsigned char* bytePtr = reinterpret_cast<unsigned char*>(&str);
bytePtr += 8;
memcpy(this, (void*)bytePtr, 32);
// char buffer is too long so store it as a pointer
if (Capacity > 15)
{
char* oldptr = charPtr;
charPtr = new char[Capacity + 1];
ZeroMemory(charPtr, Capacity + 1);
memcpy(charPtr, oldptr, Length);
}
}
~String()
{
if (Capacity > 15)
delete charPtr;
}
// Hopefully bug free; copy assignment for string literal/ptr
String& operator=(const char* ptr) {
char curChar = *ptr;
int iter = 0;
// Iterate over the char ptr until a nullchar is found or the max length is exceeded
while (curChar != '\0' && iter++ < 0x1000)
{
curChar = *(ptr + iter);
}
Length = iter;
// Round capacity up to the nearst 8 bytes
// Could use sizeOf(void*) instead of hard-coding the size
Capacity = iter + 8 - (iter % 8);
// char buffer is too long so store it as a ptr
if (Capacity > 15)
{
charPtr = new char[Capacity + 1];
ZeroMemory(charPtr, Capacity + 1);
memcpy(charPtr, ptr, iter);
}
else
{
ZeroMemory(charBuffer, 16);
memcpy(charPtr, ptr, iter);
}
return *this;
}
// Probably only works with MSVC
String& operator=(std::string str) {
unsigned char* strPtr = reinterpret_cast<unsigned char*>(&str);
strPtr += 8;
memcpy(this, (void*)strPtr, 32);
// char buffer stored as a ptr
if (Capacity > 15)
{
char* oldptr = charPtr;
charPtr = new char[Capacity + 1];
ZeroMemory(charPtr, Capacity + 1);
memcpy(charPtr, oldptr, Length);
}
return *this;
}
// For compatibility with std::string.size()
size_t size()
{
return Length;
}
size_t length()
{
return Length;
}
size_t capacity()
{
return Capacity;
}
std::string ToString()
{
if (Capacity > 15)
{
return std::string(charPtr);
}
return std::string(charBuffer);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment