#include <string.h>
#include <iostream>
#include <cassert>
using namespace std;
class String
{
private:
enum { MULTIPLE = 8 };
struct StrNode
{
size_t ref; //引用计数
size_t len; //字符串的长度
size_t cap; //字符串的容量
char data[]; //字符数组
};
public:
typedef char* iterator;
typedef const char* const_iterator;
iterator begin()
{
return (pstr != nullptr ? pstr->data : nullptr);
}
iterator end()
{
return (pstr != nullptr ? pstr->data + pstr->len : nullptr);
}
const_iterator begin()const
{
return (pstr != nullptr ? pstr->data : nullptr);
}
const_iterator end()const
{
return (pstr != nullptr ? pstr->data + pstr->len : nullptr);
}
private:
StrNode* pstr;
static size_t Cal_Multiple_Of_Multipe(size_t n)
{
if (n == 0)
{
return MULTIPLE;
}
return (n % MULTIPLE == 0) ? n : (n / MULTIPLE + 1) * MULTIPLE;
}
// return (n + ALIGN - 1) & ~(ALIGN - 1); //返会8的倍数
static StrNode* My_Mollac(size_t n)
{
StrNode* newdata = (StrNode*)malloc(sizeof(StrNode) + sizeof(char) * n);
memset(newdata, 0, sizeof(StrNode) + sizeof(char) * n);
assert(newdata != nullptr);
return newdata;
}
static StrNode* AddString(const char* pa, const char* pb, size_t n)
{
int total = String::Cal_Multiple_Of_Multipe(2 * n);
StrNode* newdata = My_Mollac(total);
newdata->ref = 1;
newdata->cap = total - 1;
newdata->len = n;
strcpy_s(newdata->data, newdata->cap + 1, pa);
strcat_s(newdata->data, newdata->cap + 1, pb);
return newdata;
}
static StrNode* My_Realloc(StrNode* p, size_t n)
{
StrNode* newstr = (StrNode*)realloc(p, sizeof(StrNode) + sizeof(char) * n);
assert(newstr != nullptr);
return newstr;