std::string 的 struct

Reverse Engineering Jun 2, 2023

逆 c++ 的时候经常碰到 std::string 比较烦

更新: 现在用的

class string final
{
private:
	union
	{
		char* ptr;
		char raw[16];
	} data_;

	size_t size_;
	size_t capacity_;

public:
	inline size_t size() { return this->size_; }
	inline void clear() { this->size_ = 0; }
	inline size_t capacity() { return this->capacity_; };
	inline char* data()
	{
		if (this->capacity() >= 0x10)
			return this->data_.ptr;

		return this->data_.raw;
	}

	inline void append(const std::string& str)
	{
		const auto new_size = str.size() + this->size_;
		const auto new_capacity = (new_size + 1) > 0x10 ? (new_size + 1) : 0x10;
		auto buffer = reinterpret_cast<char*>(game::malloc(new_capacity));

		std::memcpy(buffer, this->data(), this->size());
		std::memcpy(buffer + this->size(), str.data(), str.size());
		buffer[new_size] = 0;

		if (this->capacity() >= 0x10)
			game::free(this->data());

		this->capacity_ = new_capacity;
		this->size_ = new_size;
		this->data_.ptr = buffer;
	}
};
备: game::malloc 和 game::free 是目标应用自身的 allocator, 直接用自己的 allocator去处理我怕会和游戏自身产生兼容性问题

标签