1
0
mirror of https://github.com/OpenRCT2/OpenRCT2 synced 2026-01-15 11:03:00 +01:00

Part of #11159: Prefer std::basic_string<utf8> over raw pointer

Usage of std::basic_string to improve readability and maintainability.
This commit is contained in:
Gabriel Guedes
2020-08-29 11:16:05 -03:00
parent 332e9e76d5
commit 95ae589750

View File

@@ -10,10 +10,10 @@
#pragma once
#include "../common.h"
#include "Memory.hpp"
#include "String.hpp"
#include <algorithm>
#include <iterator>
#include <string>
/**
@@ -26,13 +26,10 @@ public:
StringBuilder() = default;
explicit StringBuilder(size_t capacity)
{
EnsureCapacity(capacity);
_buffer.reserve(capacity);
}
~StringBuilder()
{
Memory::Free(_buffer);
}
~StringBuilder() = default;
void Append(int32_t codepoint)
{
@@ -45,10 +42,9 @@ public:
void Append(codepoint_t codepoint)
{
size_t codepointLength = String::GetCodepointLength(codepoint);
EnsureCapacity(_length + codepointLength + 1);
String::WriteCodepoint(_buffer + _length, codepoint);
_length += codepointLength;
_buffer[_length] = 0;
std::basic_string<utf8> data(codepointLength, {});
String::WriteCodepoint(data.data(), codepoint);
_buffer.insert(_buffer.end(), data.begin(), data.end());
}
/**
@@ -68,10 +64,7 @@ public:
*/
void Append(const utf8* text, size_t textLength)
{
EnsureCapacity(_length + textLength + 1);
std::copy_n(text, textLength, _buffer + _length);
_length += textLength;
_buffer[_length] = 0;
_buffer.insert(_buffer.end(), text, text + textLength);
}
/**
@@ -87,11 +80,7 @@ public:
*/
void Clear()
{
_length = 0;
if (_capacity >= 1)
{
_buffer[_length] = 0;
}
_buffer.clear();
}
/**
@@ -99,7 +88,7 @@ public:
*/
std::string GetStdString() const
{
return std::string(_buffer, _length);
return std::string(GetBuffer(), GetLength());
}
/**
@@ -108,10 +97,10 @@ public:
*/
const utf8* GetBuffer() const
{
// buffer may be null, so return an immutable empty string
if (_buffer == nullptr)
// buffer may be empty, so return an immutable empty string
if (_buffer.empty())
return "";
return _buffer;
return _buffer.c_str();
}
/**
@@ -119,25 +108,9 @@ public:
*/
size_t GetLength() const
{
return _length;
return _buffer.size();
}
private:
utf8* _buffer = nullptr;
size_t _capacity = 0;
size_t _length = 0;
void EnsureCapacity(size_t capacity)
{
if (_capacity > capacity)
return;
_capacity = std::max(static_cast<size_t>(8), _capacity);
while (_capacity < capacity)
{
_capacity *= 2;
}
_buffer = Memory::ReallocateArray<utf8>(_buffer, _capacity);
}
std::basic_string<utf8> _buffer;
};