Path: blob/master/thirdparty/icu4c/common/fixedstring.h
14710 views
// © 2025 and later: Unicode, Inc. and others.1// License & terms of use: https://www.unicode.org/copyright.html23#ifndef FIXEDSTRING_H4#define FIXEDSTRING_H56#include <string_view>7#include <utility>89#include "unicode/uobject.h"10#include "unicode/utypes.h"11#include "cmemory.h"1213U_NAMESPACE_BEGIN1415class UnicodeString;1617/**18* ICU-internal fixed-length char* string class.19* This is a complement to CharString to store fixed-length strings efficiently20* (not allocating any unnecessary storage for future additions to the string).21*22* A terminating NUL is always stored, but the length of the string isn't.23* An empty string is stored as nullptr, allocating no storage at all.24*25* This class wants to be convenient but is also deliberately minimalist.26* Please do not add methods if they only add minor convenience.27*/28class FixedString : public UMemory {29public:30FixedString() = default;31~FixedString() { operator delete[](ptr); }3233FixedString(const FixedString& other) : FixedString(other.data()) {}3435FixedString(std::string_view init) {36size_t size = init.size();37if (size > 0 && reserve(size + 1)) {38uprv_memcpy(ptr, init.data(), size);39ptr[size] = '\0';40}41}4243FixedString& operator=(const FixedString& other) {44*this = other.data();45return *this;46}4748FixedString& operator=(std::string_view init) {49if (init.empty()) {50operator delete[](ptr);51ptr = nullptr;52} else {53size_t size = init.size();54if (reserve(size + 1)) {55uprv_memcpy(ptr, init.data(), size);56ptr[size] = '\0';57}58}59return *this;60}6162FixedString(FixedString&& other) noexcept : ptr(std::exchange(other.ptr, nullptr)) {}6364FixedString& operator=(FixedString&& other) noexcept {65operator delete[](ptr);66ptr = other.ptr;67other.ptr = nullptr;68return *this;69}7071void clear() {72operator delete[](ptr);73ptr = nullptr;74}7576const char* data() const {77return isEmpty() ? "" : ptr;78}7980char* getAlias() {81return ptr;82}8384bool isEmpty() const {85return ptr == nullptr;86}8788/** Allocate storage for a new string, without initializing it. */89bool reserve(size_t size) {90operator delete[](ptr);91ptr = static_cast<char*>(operator new[](size));92return ptr != nullptr;93}9495private:96char* ptr = nullptr;97};9899U_COMMON_API void copyInvariantChars(const UnicodeString& src, FixedString& dst, UErrorCode& status);100101U_NAMESPACE_END102103#endif104105106