Skip to content

Instantly share code, notes, and snippets.

@Bueddl
Created January 25, 2017 17:57
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 Bueddl/2236f6d400441190db4b30c0868070e6 to your computer and use it in GitHub Desktop.
Save Bueddl/2236f6d400441190db4b30c0868070e6 to your computer and use it in GitHub Desktop.
Implementation of small string optimization
#include <cstring>
#include <cstdio>
class my_string
{
private:
union
{
char inline_buf[16]; // sso
char *bufptr;
} data_;
unsigned int size_;
public:
my_string()
: size_(0)
{}
my_string& operator=(const char *cstr)
{
resize(std::strlen(cstr)+1);
if (size_ <= 16)
std::memcpy(data_.inline_buf, cstr, size_);
else
std::memcpy(data_.bufptr, cstr, size_);
return *this;
}
const char& operator[](int i) const
{
if (size_ <= 16)
return data_.inline_buf[i];
else
return data_.bufptr[i];
}
void resize(int size)
{
if (size_ > 16)
delete[] data_.bufptr;
size_ = size;
if (size_ > 16)
data_.bufptr = new char[size_];
}
const char *c_str() const
{
return &(*this)[0];
}
};
int main()
{
my_string str;
str = "Das ist ein Test";
std::printf("%s\nbuffer address: %p\n\n", str.c_str(), &str[0]);
str = "Und noch ein langer Test";
std::printf("%s\nbuffer address: %p\n\n", str.c_str(), &str[0]);
str = "SSO";
std::printf("%s\nbuffer address: %p\n\n", str.c_str(), &str[0]);
// Possible output:
//
// Das ist ein Test
// buffer address: 0x14ffc20
//
// Und noch ein langer Test
// buffer address: 0x1500050
//
// SSO
// buffer address: 0x7fffb5d3ec20
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment