unistr.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. ******************************************************************************
  5. * Copyright (C) 1999-2016, International Business Machines Corporation and
  6. * others. All Rights Reserved.
  7. ******************************************************************************
  8. *
  9. * File unistr.cpp
  10. *
  11. * Modification History:
  12. *
  13. * Date Name Description
  14. * 09/25/98 stephen Creation.
  15. * 04/20/99 stephen Overhauled per 4/16 code review.
  16. * 07/09/99 stephen Renamed {hi,lo},{byte,word} to icu_X for HP/UX
  17. * 11/18/99 aliu Added handleReplaceBetween() to make inherit from
  18. * Replaceable.
  19. * 06/25/01 grhoten Removed the dependency on iostream
  20. ******************************************************************************
  21. */
  22. #include "unicode/utypes.h"
  23. #include "unicode/appendable.h"
  24. #include "unicode/putil.h"
  25. #include "cstring.h"
  26. #include "cmemory.h"
  27. #include "unicode/ustring.h"
  28. #include "unicode/unistr.h"
  29. #include "unicode/utf.h"
  30. #include "unicode/utf16.h"
  31. #include "uelement.h"
  32. #include "ustr_imp.h"
  33. #include "umutex.h"
  34. #include "uassert.h"
  35. #if 0
  36. #include <iostream>
  37. using namespace std;
  38. //DEBUGGING
  39. void
  40. print(const UnicodeString& s,
  41. const char *name)
  42. {
  43. char16_t c;
  44. cout << name << ":|";
  45. for(int i = 0; i < s.length(); ++i) {
  46. c = s[i];
  47. if(c>= 0x007E || c < 0x0020)
  48. cout << "[0x" << hex << s[i] << "]";
  49. else
  50. cout << (char) s[i];
  51. }
  52. cout << '|' << endl;
  53. }
  54. void
  55. print(const char16_t *s,
  56. int32_t len,
  57. const char *name)
  58. {
  59. char16_t c;
  60. cout << name << ":|";
  61. for(int i = 0; i < len; ++i) {
  62. c = s[i];
  63. if(c>= 0x007E || c < 0x0020)
  64. cout << "[0x" << hex << s[i] << "]";
  65. else
  66. cout << (char) s[i];
  67. }
  68. cout << '|' << endl;
  69. }
  70. // END DEBUGGING
  71. #endif
  72. // Local function definitions for now
  73. // need to copy areas that may overlap
  74. static
  75. inline void
  76. us_arrayCopy(const char16_t *src, int32_t srcStart,
  77. char16_t *dst, int32_t dstStart, int32_t count)
  78. {
  79. if(count>0) {
  80. uprv_memmove(dst+dstStart, src+srcStart, (size_t)count*sizeof(*src));
  81. }
  82. }
  83. // u_unescapeAt() callback to get a char16_t from a UnicodeString
  84. U_CDECL_BEGIN
  85. static char16_t U_CALLCONV
  86. UnicodeString_charAt(int32_t offset, void *context) {
  87. return ((icu::UnicodeString*) context)->charAt(offset);
  88. }
  89. U_CDECL_END
  90. U_NAMESPACE_BEGIN
  91. /* The Replaceable virtual destructor can't be defined in the header
  92. due to how AIX works with multiple definitions of virtual functions.
  93. */
  94. Replaceable::~Replaceable() {}
  95. UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeString)
  96. UnicodeString U_EXPORT2
  97. operator+ (const UnicodeString &s1, const UnicodeString &s2) {
  98. return
  99. UnicodeString(s1.length()+s2.length()+1, (UChar32)0, 0).
  100. append(s1).
  101. append(s2);
  102. }
  103. //========================================
  104. // Reference Counting functions, put at top of file so that optimizing compilers
  105. // have a chance to automatically inline.
  106. //========================================
  107. void
  108. UnicodeString::addRef() {
  109. umtx_atomic_inc((u_atomic_int32_t *)fUnion.fFields.fArray - 1);
  110. }
  111. int32_t
  112. UnicodeString::removeRef() {
  113. return umtx_atomic_dec((u_atomic_int32_t *)fUnion.fFields.fArray - 1);
  114. }
  115. int32_t
  116. UnicodeString::refCount() const {
  117. return umtx_loadAcquire(*((u_atomic_int32_t *)fUnion.fFields.fArray - 1));
  118. }
  119. void
  120. UnicodeString::releaseArray() {
  121. if((fUnion.fFields.fLengthAndFlags & kRefCounted) && removeRef() == 0) {
  122. uprv_free((int32_t *)fUnion.fFields.fArray - 1);
  123. }
  124. }
  125. //========================================
  126. // Constructors
  127. //========================================
  128. // The default constructor is inline in unistr.h.
  129. UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) {
  130. fUnion.fFields.fLengthAndFlags = 0;
  131. if(count <= 0 || (uint32_t)c > 0x10ffff) {
  132. // just allocate and do not do anything else
  133. allocate(capacity);
  134. } else if(c <= 0xffff) {
  135. int32_t length = count;
  136. if(capacity < length) {
  137. capacity = length;
  138. }
  139. if(allocate(capacity)) {
  140. char16_t *array = getArrayStart();
  141. char16_t unit = (char16_t)c;
  142. for(int32_t i = 0; i < length; ++i) {
  143. array[i] = unit;
  144. }
  145. setLength(length);
  146. }
  147. } else { // supplementary code point, write surrogate pairs
  148. if(count > (INT32_MAX / 2)) {
  149. // We would get more than 2G UChars.
  150. allocate(capacity);
  151. return;
  152. }
  153. int32_t length = count * 2;
  154. if(capacity < length) {
  155. capacity = length;
  156. }
  157. if(allocate(capacity)) {
  158. char16_t *array = getArrayStart();
  159. char16_t lead = U16_LEAD(c);
  160. char16_t trail = U16_TRAIL(c);
  161. for(int32_t i = 0; i < length; i += 2) {
  162. array[i] = lead;
  163. array[i + 1] = trail;
  164. }
  165. setLength(length);
  166. }
  167. }
  168. }
  169. UnicodeString::UnicodeString(char16_t ch) {
  170. fUnion.fFields.fLengthAndFlags = kLength1 | kShortString;
  171. fUnion.fStackFields.fBuffer[0] = ch;
  172. }
  173. UnicodeString::UnicodeString(UChar32 ch) {
  174. fUnion.fFields.fLengthAndFlags = kShortString;
  175. int32_t i = 0;
  176. UBool isError = false;
  177. U16_APPEND(fUnion.fStackFields.fBuffer, i, US_STACKBUF_SIZE, ch, isError);
  178. // We test isError so that the compiler does not complain that we don't.
  179. // If isError then i==0 which is what we want anyway.
  180. if(!isError) {
  181. setShortLength(i);
  182. }
  183. }
  184. UnicodeString::UnicodeString(const char16_t *text) {
  185. fUnion.fFields.fLengthAndFlags = kShortString;
  186. doAppend(text, 0, -1);
  187. }
  188. UnicodeString::UnicodeString(const char16_t *text,
  189. int32_t textLength) {
  190. fUnion.fFields.fLengthAndFlags = kShortString;
  191. doAppend(text, 0, textLength);
  192. }
  193. UnicodeString::UnicodeString(UBool isTerminated,
  194. ConstChar16Ptr textPtr,
  195. int32_t textLength) {
  196. fUnion.fFields.fLengthAndFlags = kReadonlyAlias;
  197. const char16_t *text = textPtr;
  198. if(text == nullptr) {
  199. // treat as an empty string, do not alias
  200. setToEmpty();
  201. } else if(textLength < -1 ||
  202. (textLength == -1 && !isTerminated) ||
  203. (textLength >= 0 && isTerminated && text[textLength] != 0)
  204. ) {
  205. setToBogus();
  206. } else {
  207. if(textLength == -1) {
  208. // text is terminated, or else it would have failed the above test
  209. textLength = u_strlen(text);
  210. }
  211. setArray(const_cast<char16_t *>(text), textLength,
  212. isTerminated ? textLength + 1 : textLength);
  213. }
  214. }
  215. UnicodeString::UnicodeString(char16_t *buff,
  216. int32_t buffLength,
  217. int32_t buffCapacity) {
  218. fUnion.fFields.fLengthAndFlags = kWritableAlias;
  219. if(buff == nullptr) {
  220. // treat as an empty string, do not alias
  221. setToEmpty();
  222. } else if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) {
  223. setToBogus();
  224. } else {
  225. if(buffLength == -1) {
  226. // fLength = u_strlen(buff); but do not look beyond buffCapacity
  227. const char16_t *p = buff, *limit = buff + buffCapacity;
  228. while(p != limit && *p != 0) {
  229. ++p;
  230. }
  231. buffLength = (int32_t)(p - buff);
  232. }
  233. setArray(buff, buffLength, buffCapacity);
  234. }
  235. }
  236. UnicodeString::UnicodeString(const char *src, int32_t length, EInvariant) {
  237. fUnion.fFields.fLengthAndFlags = kShortString;
  238. if(src==nullptr) {
  239. // treat as an empty string
  240. } else {
  241. if(length<0) {
  242. length=(int32_t)uprv_strlen(src);
  243. }
  244. if(cloneArrayIfNeeded(length, length, false)) {
  245. u_charsToUChars(src, getArrayStart(), length);
  246. setLength(length);
  247. } else {
  248. setToBogus();
  249. }
  250. }
  251. }
  252. #if U_CHARSET_IS_UTF8
  253. UnicodeString::UnicodeString(const char *codepageData) {
  254. fUnion.fFields.fLengthAndFlags = kShortString;
  255. if(codepageData != 0) {
  256. setToUTF8(codepageData);
  257. }
  258. }
  259. UnicodeString::UnicodeString(const char *codepageData, int32_t dataLength) {
  260. fUnion.fFields.fLengthAndFlags = kShortString;
  261. // if there's nothing to convert, do nothing
  262. if(codepageData == 0 || dataLength == 0 || dataLength < -1) {
  263. return;
  264. }
  265. if(dataLength == -1) {
  266. dataLength = (int32_t)uprv_strlen(codepageData);
  267. }
  268. setToUTF8(StringPiece(codepageData, dataLength));
  269. }
  270. // else see unistr_cnv.cpp
  271. #endif
  272. UnicodeString::UnicodeString(const UnicodeString& that) {
  273. fUnion.fFields.fLengthAndFlags = kShortString;
  274. copyFrom(that);
  275. }
  276. UnicodeString::UnicodeString(UnicodeString &&src) noexcept {
  277. copyFieldsFrom(src, true);
  278. }
  279. UnicodeString::UnicodeString(const UnicodeString& that,
  280. int32_t srcStart) {
  281. fUnion.fFields.fLengthAndFlags = kShortString;
  282. setTo(that, srcStart);
  283. }
  284. UnicodeString::UnicodeString(const UnicodeString& that,
  285. int32_t srcStart,
  286. int32_t srcLength) {
  287. fUnion.fFields.fLengthAndFlags = kShortString;
  288. setTo(that, srcStart, srcLength);
  289. }
  290. // Replaceable base class clone() default implementation, does not clone
  291. Replaceable *
  292. Replaceable::clone() const {
  293. return nullptr;
  294. }
  295. // UnicodeString overrides clone() with a real implementation
  296. UnicodeString *
  297. UnicodeString::clone() const {
  298. LocalPointer<UnicodeString> clonedString(new UnicodeString(*this));
  299. return clonedString.isValid() && !clonedString->isBogus() ? clonedString.orphan() : nullptr;
  300. }
  301. //========================================
  302. // array allocation
  303. //========================================
  304. namespace {
  305. const int32_t kGrowSize = 128;
  306. // The number of bytes for one int32_t reference counter and capacity UChars
  307. // must fit into a 32-bit size_t (at least when on a 32-bit platform).
  308. // We also add one for the NUL terminator, to avoid reallocation in getTerminatedBuffer(),
  309. // and round up to a multiple of 16 bytes.
  310. // This means that capacity must be at most (0xfffffff0 - 4) / 2 - 1 = 0x7ffffff5.
  311. // (With more complicated checks we could go up to 0x7ffffffd without rounding up,
  312. // but that does not seem worth it.)
  313. const int32_t kMaxCapacity = 0x7ffffff5;
  314. int32_t getGrowCapacity(int32_t newLength) {
  315. int32_t growSize = (newLength >> 2) + kGrowSize;
  316. if(growSize <= (kMaxCapacity - newLength)) {
  317. return newLength + growSize;
  318. } else {
  319. return kMaxCapacity;
  320. }
  321. }
  322. } // namespace
  323. UBool
  324. UnicodeString::allocate(int32_t capacity) {
  325. if(capacity <= US_STACKBUF_SIZE) {
  326. fUnion.fFields.fLengthAndFlags = kShortString;
  327. return true;
  328. }
  329. if(capacity <= kMaxCapacity) {
  330. ++capacity; // for the NUL
  331. // Switch to size_t which is unsigned so that we can allocate up to 4GB.
  332. // Reference counter + UChars.
  333. size_t numBytes = sizeof(int32_t) + (size_t)capacity * U_SIZEOF_UCHAR;
  334. // Round up to a multiple of 16.
  335. numBytes = (numBytes + 15) & ~15;
  336. int32_t *array = (int32_t *) uprv_malloc(numBytes);
  337. if(array != nullptr) {
  338. // set initial refCount and point behind the refCount
  339. *array++ = 1;
  340. numBytes -= sizeof(int32_t);
  341. // have fArray point to the first char16_t
  342. fUnion.fFields.fArray = (char16_t *)array;
  343. fUnion.fFields.fCapacity = (int32_t)(numBytes / U_SIZEOF_UCHAR);
  344. fUnion.fFields.fLengthAndFlags = kLongString;
  345. return true;
  346. }
  347. }
  348. fUnion.fFields.fLengthAndFlags = kIsBogus;
  349. fUnion.fFields.fArray = 0;
  350. fUnion.fFields.fCapacity = 0;
  351. return false;
  352. }
  353. //========================================
  354. // Destructor
  355. //========================================
  356. #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS
  357. static u_atomic_int32_t finalLengthCounts[0x400]; // UnicodeString::kMaxShortLength+1
  358. static u_atomic_int32_t beyondCount(0);
  359. U_CAPI void unistr_printLengths() {
  360. int32_t i;
  361. for(i = 0; i <= 59; ++i) {
  362. printf("%2d, %9d\n", i, (int32_t)finalLengthCounts[i]);
  363. }
  364. int32_t beyond = beyondCount;
  365. for(; i < UPRV_LENGTHOF(finalLengthCounts); ++i) {
  366. beyond += finalLengthCounts[i];
  367. }
  368. printf(">59, %9d\n", beyond);
  369. }
  370. #endif
  371. UnicodeString::~UnicodeString()
  372. {
  373. #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS
  374. // Count lengths of strings at the end of their lifetime.
  375. // Useful for discussion of a desirable stack buffer size.
  376. // Count the contents length, not the optional NUL terminator nor further capacity.
  377. // Ignore open-buffer strings and strings which alias external storage.
  378. if((fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kReadonlyAlias|kWritableAlias)) == 0) {
  379. if(hasShortLength()) {
  380. umtx_atomic_inc(finalLengthCounts + getShortLength());
  381. } else {
  382. umtx_atomic_inc(&beyondCount);
  383. }
  384. }
  385. #endif
  386. releaseArray();
  387. }
  388. //========================================
  389. // Factory methods
  390. //========================================
  391. UnicodeString UnicodeString::fromUTF8(StringPiece utf8) {
  392. UnicodeString result;
  393. result.setToUTF8(utf8);
  394. return result;
  395. }
  396. UnicodeString UnicodeString::fromUTF32(const UChar32 *utf32, int32_t length) {
  397. UnicodeString result;
  398. int32_t capacity;
  399. // Most UTF-32 strings will be BMP-only and result in a same-length
  400. // UTF-16 string. We overestimate the capacity just slightly,
  401. // just in case there are a few supplementary characters.
  402. if(length <= US_STACKBUF_SIZE) {
  403. capacity = US_STACKBUF_SIZE;
  404. } else {
  405. capacity = length + (length >> 4) + 4;
  406. }
  407. do {
  408. char16_t *utf16 = result.getBuffer(capacity);
  409. int32_t length16;
  410. UErrorCode errorCode = U_ZERO_ERROR;
  411. u_strFromUTF32WithSub(utf16, result.getCapacity(), &length16,
  412. utf32, length,
  413. 0xfffd, // Substitution character.
  414. nullptr, // Don't care about number of substitutions.
  415. &errorCode);
  416. result.releaseBuffer(length16);
  417. if(errorCode == U_BUFFER_OVERFLOW_ERROR) {
  418. capacity = length16 + 1; // +1 for the terminating NUL.
  419. continue;
  420. } else if(U_FAILURE(errorCode)) {
  421. result.setToBogus();
  422. }
  423. break;
  424. } while(true);
  425. return result;
  426. }
  427. //========================================
  428. // Assignment
  429. //========================================
  430. UnicodeString &
  431. UnicodeString::operator=(const UnicodeString &src) {
  432. return copyFrom(src);
  433. }
  434. UnicodeString &
  435. UnicodeString::fastCopyFrom(const UnicodeString &src) {
  436. return copyFrom(src, true);
  437. }
  438. UnicodeString &
  439. UnicodeString::copyFrom(const UnicodeString &src, UBool fastCopy) {
  440. // if assigning to ourselves, do nothing
  441. if(this == &src) {
  442. return *this;
  443. }
  444. // is the right side bogus?
  445. if(src.isBogus()) {
  446. setToBogus();
  447. return *this;
  448. }
  449. // delete the current contents
  450. releaseArray();
  451. if(src.isEmpty()) {
  452. // empty string - use the stack buffer
  453. setToEmpty();
  454. return *this;
  455. }
  456. // fLength>0 and not an "open" src.getBuffer(minCapacity)
  457. fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags;
  458. switch(src.fUnion.fFields.fLengthAndFlags & kAllStorageFlags) {
  459. case kShortString:
  460. // short string using the stack buffer, do the same
  461. uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer,
  462. getShortLength() * U_SIZEOF_UCHAR);
  463. break;
  464. case kLongString:
  465. // src uses a refCounted string buffer, use that buffer with refCount
  466. // src is const, use a cast - we don't actually change it
  467. const_cast<UnicodeString &>(src).addRef();
  468. // copy all fields, share the reference-counted buffer
  469. fUnion.fFields.fArray = src.fUnion.fFields.fArray;
  470. fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity;
  471. if(!hasShortLength()) {
  472. fUnion.fFields.fLength = src.fUnion.fFields.fLength;
  473. }
  474. break;
  475. case kReadonlyAlias:
  476. if(fastCopy) {
  477. // src is a readonly alias, do the same
  478. // -> maintain the readonly alias as such
  479. fUnion.fFields.fArray = src.fUnion.fFields.fArray;
  480. fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity;
  481. if(!hasShortLength()) {
  482. fUnion.fFields.fLength = src.fUnion.fFields.fLength;
  483. }
  484. break;
  485. }
  486. // else if(!fastCopy) fall through to case kWritableAlias
  487. // -> allocate a new buffer and copy the contents
  488. U_FALLTHROUGH;
  489. case kWritableAlias: {
  490. // src is a writable alias; we make a copy of that instead
  491. int32_t srcLength = src.length();
  492. if(allocate(srcLength)) {
  493. u_memcpy(getArrayStart(), src.getArrayStart(), srcLength);
  494. setLength(srcLength);
  495. break;
  496. }
  497. // if there is not enough memory, then fall through to setting to bogus
  498. U_FALLTHROUGH;
  499. }
  500. default:
  501. // if src is bogus, set ourselves to bogus
  502. // do not call setToBogus() here because fArray and flags are not consistent here
  503. fUnion.fFields.fLengthAndFlags = kIsBogus;
  504. fUnion.fFields.fArray = 0;
  505. fUnion.fFields.fCapacity = 0;
  506. break;
  507. }
  508. return *this;
  509. }
  510. UnicodeString &UnicodeString::operator=(UnicodeString &&src) noexcept {
  511. // No explicit check for self move assignment, consistent with standard library.
  512. // Self move assignment causes no crash nor leak but might make the object bogus.
  513. releaseArray();
  514. copyFieldsFrom(src, true);
  515. return *this;
  516. }
  517. // Same as move assignment except without memory management.
  518. void UnicodeString::copyFieldsFrom(UnicodeString &src, UBool setSrcToBogus) noexcept {
  519. int16_t lengthAndFlags = fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags;
  520. if(lengthAndFlags & kUsingStackBuffer) {
  521. // Short string using the stack buffer, copy the contents.
  522. // Check for self assignment to prevent "overlap in memcpy" warnings,
  523. // although it should be harmless to copy a buffer to itself exactly.
  524. if(this != &src) {
  525. uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer,
  526. getShortLength() * U_SIZEOF_UCHAR);
  527. }
  528. } else {
  529. // In all other cases, copy all fields.
  530. fUnion.fFields.fArray = src.fUnion.fFields.fArray;
  531. fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity;
  532. if(!hasShortLength()) {
  533. fUnion.fFields.fLength = src.fUnion.fFields.fLength;
  534. }
  535. if(setSrcToBogus) {
  536. // Set src to bogus without releasing any memory.
  537. src.fUnion.fFields.fLengthAndFlags = kIsBogus;
  538. src.fUnion.fFields.fArray = nullptr;
  539. src.fUnion.fFields.fCapacity = 0;
  540. }
  541. }
  542. }
  543. void UnicodeString::swap(UnicodeString &other) noexcept {
  544. UnicodeString temp; // Empty short string: Known not to need releaseArray().
  545. // Copy fields without resetting source values in between.
  546. temp.copyFieldsFrom(*this, false);
  547. this->copyFieldsFrom(other, false);
  548. other.copyFieldsFrom(temp, false);
  549. // Set temp to an empty string so that other's memory is not released twice.
  550. temp.fUnion.fFields.fLengthAndFlags = kShortString;
  551. }
  552. //========================================
  553. // Miscellaneous operations
  554. //========================================
  555. UnicodeString UnicodeString::unescape() const {
  556. UnicodeString result(length(), (UChar32)0, (int32_t)0); // construct with capacity
  557. if (result.isBogus()) {
  558. return result;
  559. }
  560. const char16_t *array = getBuffer();
  561. int32_t len = length();
  562. int32_t prev = 0;
  563. for (int32_t i=0;;) {
  564. if (i == len) {
  565. result.append(array, prev, len - prev);
  566. break;
  567. }
  568. if (array[i++] == 0x5C /*'\\'*/) {
  569. result.append(array, prev, (i - 1) - prev);
  570. UChar32 c = unescapeAt(i); // advances i
  571. if (c < 0) {
  572. result.remove(); // return empty string
  573. break; // invalid escape sequence
  574. }
  575. result.append(c);
  576. prev = i;
  577. }
  578. }
  579. return result;
  580. }
  581. UChar32 UnicodeString::unescapeAt(int32_t &offset) const {
  582. return u_unescapeAt(UnicodeString_charAt, &offset, length(), (void*)this);
  583. }
  584. //========================================
  585. // Read-only implementation
  586. //========================================
  587. UBool
  588. UnicodeString::doEquals(const UnicodeString &text, int32_t len) const {
  589. // Requires: this & text not bogus and have same lengths.
  590. // Byte-wise comparison works for equality regardless of endianness.
  591. return uprv_memcmp(getArrayStart(), text.getArrayStart(), len * U_SIZEOF_UCHAR) == 0;
  592. }
  593. UBool
  594. UnicodeString::doEqualsSubstring( int32_t start,
  595. int32_t length,
  596. const char16_t *srcChars,
  597. int32_t srcStart,
  598. int32_t srcLength) const
  599. {
  600. // compare illegal string values
  601. if(isBogus()) {
  602. return false;
  603. }
  604. // pin indices to legal values
  605. pinIndices(start, length);
  606. if(srcChars == nullptr) {
  607. // treat const char16_t *srcChars==nullptr as an empty string
  608. return length == 0 ? true : false;
  609. }
  610. // get the correct pointer
  611. const char16_t *chars = getArrayStart();
  612. chars += start;
  613. srcChars += srcStart;
  614. // get the srcLength if necessary
  615. if(srcLength < 0) {
  616. srcLength = u_strlen(srcChars + srcStart);
  617. }
  618. if (length != srcLength) {
  619. return false;
  620. }
  621. if(length == 0 || chars == srcChars) {
  622. return true;
  623. }
  624. return u_memcmp(chars, srcChars, srcLength) == 0;
  625. }
  626. int8_t
  627. UnicodeString::doCompare( int32_t start,
  628. int32_t length,
  629. const char16_t *srcChars,
  630. int32_t srcStart,
  631. int32_t srcLength) const
  632. {
  633. // compare illegal string values
  634. if(isBogus()) {
  635. return -1;
  636. }
  637. // pin indices to legal values
  638. pinIndices(start, length);
  639. if(srcChars == nullptr) {
  640. // treat const char16_t *srcChars==nullptr as an empty string
  641. return length == 0 ? 0 : 1;
  642. }
  643. // get the correct pointer
  644. const char16_t *chars = getArrayStart();
  645. chars += start;
  646. srcChars += srcStart;
  647. int32_t minLength;
  648. int8_t lengthResult;
  649. // get the srcLength if necessary
  650. if(srcLength < 0) {
  651. srcLength = u_strlen(srcChars + srcStart);
  652. }
  653. // are we comparing different lengths?
  654. if(length != srcLength) {
  655. if(length < srcLength) {
  656. minLength = length;
  657. lengthResult = -1;
  658. } else {
  659. minLength = srcLength;
  660. lengthResult = 1;
  661. }
  662. } else {
  663. minLength = length;
  664. lengthResult = 0;
  665. }
  666. /*
  667. * note that uprv_memcmp() returns an int but we return an int8_t;
  668. * we need to take care not to truncate the result -
  669. * one way to do this is to right-shift the value to
  670. * move the sign bit into the lower 8 bits and making sure that this
  671. * does not become 0 itself
  672. */
  673. if(minLength > 0 && chars != srcChars) {
  674. int32_t result;
  675. # if U_IS_BIG_ENDIAN
  676. // big-endian: byte comparison works
  677. result = uprv_memcmp(chars, srcChars, minLength * sizeof(char16_t));
  678. if(result != 0) {
  679. return (int8_t)(result >> 15 | 1);
  680. }
  681. # else
  682. // little-endian: compare char16_t units
  683. do {
  684. result = ((int32_t)*(chars++) - (int32_t)*(srcChars++));
  685. if(result != 0) {
  686. return (int8_t)(result >> 15 | 1);
  687. }
  688. } while(--minLength > 0);
  689. # endif
  690. }
  691. return lengthResult;
  692. }
  693. /* String compare in code point order - doCompare() compares in code unit order. */
  694. int8_t
  695. UnicodeString::doCompareCodePointOrder(int32_t start,
  696. int32_t length,
  697. const char16_t *srcChars,
  698. int32_t srcStart,
  699. int32_t srcLength) const
  700. {
  701. // compare illegal string values
  702. // treat const char16_t *srcChars==nullptr as an empty string
  703. if(isBogus()) {
  704. return -1;
  705. }
  706. // pin indices to legal values
  707. pinIndices(start, length);
  708. if(srcChars == nullptr) {
  709. srcStart = srcLength = 0;
  710. }
  711. int32_t diff = uprv_strCompare(getArrayStart() + start, length, (srcChars!=nullptr)?(srcChars + srcStart):nullptr, srcLength, false, true);
  712. /* translate the 32-bit result into an 8-bit one */
  713. if(diff!=0) {
  714. return (int8_t)(diff >> 15 | 1);
  715. } else {
  716. return 0;
  717. }
  718. }
  719. int32_t
  720. UnicodeString::getLength() const {
  721. return length();
  722. }
  723. char16_t
  724. UnicodeString::getCharAt(int32_t offset) const {
  725. return charAt(offset);
  726. }
  727. UChar32
  728. UnicodeString::getChar32At(int32_t offset) const {
  729. return char32At(offset);
  730. }
  731. UChar32
  732. UnicodeString::char32At(int32_t offset) const
  733. {
  734. int32_t len = length();
  735. if((uint32_t)offset < (uint32_t)len) {
  736. const char16_t *array = getArrayStart();
  737. UChar32 c;
  738. U16_GET(array, 0, offset, len, c);
  739. return c;
  740. } else {
  741. return kInvalidUChar;
  742. }
  743. }
  744. int32_t
  745. UnicodeString::getChar32Start(int32_t offset) const {
  746. if((uint32_t)offset < (uint32_t)length()) {
  747. const char16_t *array = getArrayStart();
  748. U16_SET_CP_START(array, 0, offset);
  749. return offset;
  750. } else {
  751. return 0;
  752. }
  753. }
  754. int32_t
  755. UnicodeString::getChar32Limit(int32_t offset) const {
  756. int32_t len = length();
  757. if((uint32_t)offset < (uint32_t)len) {
  758. const char16_t *array = getArrayStart();
  759. U16_SET_CP_LIMIT(array, 0, offset, len);
  760. return offset;
  761. } else {
  762. return len;
  763. }
  764. }
  765. int32_t
  766. UnicodeString::countChar32(int32_t start, int32_t length) const {
  767. pinIndices(start, length);
  768. // if(isBogus()) then fArray==0 and start==0 - u_countChar32() checks for nullptr
  769. return u_countChar32(getArrayStart()+start, length);
  770. }
  771. UBool
  772. UnicodeString::hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const {
  773. pinIndices(start, length);
  774. // if(isBogus()) then fArray==0 and start==0 - u_strHasMoreChar32Than() checks for nullptr
  775. return u_strHasMoreChar32Than(getArrayStart()+start, length, number);
  776. }
  777. int32_t
  778. UnicodeString::moveIndex32(int32_t index, int32_t delta) const {
  779. // pin index
  780. int32_t len = length();
  781. if(index<0) {
  782. index=0;
  783. } else if(index>len) {
  784. index=len;
  785. }
  786. const char16_t *array = getArrayStart();
  787. if(delta>0) {
  788. U16_FWD_N(array, index, len, delta);
  789. } else {
  790. U16_BACK_N(array, 0, index, -delta);
  791. }
  792. return index;
  793. }
  794. void
  795. UnicodeString::doExtract(int32_t start,
  796. int32_t length,
  797. char16_t *dst,
  798. int32_t dstStart) const
  799. {
  800. // pin indices to legal values
  801. pinIndices(start, length);
  802. // do not copy anything if we alias dst itself
  803. const char16_t *array = getArrayStart();
  804. if(array + start != dst + dstStart) {
  805. us_arrayCopy(array, start, dst, dstStart, length);
  806. }
  807. }
  808. int32_t
  809. UnicodeString::extract(Char16Ptr dest, int32_t destCapacity,
  810. UErrorCode &errorCode) const {
  811. int32_t len = length();
  812. if(U_SUCCESS(errorCode)) {
  813. if(isBogus() || destCapacity<0 || (destCapacity>0 && dest==0)) {
  814. errorCode=U_ILLEGAL_ARGUMENT_ERROR;
  815. } else {
  816. const char16_t *array = getArrayStart();
  817. if(len>0 && len<=destCapacity && array!=dest) {
  818. u_memcpy(dest, array, len);
  819. }
  820. return u_terminateUChars(dest, destCapacity, len, &errorCode);
  821. }
  822. }
  823. return len;
  824. }
  825. int32_t
  826. UnicodeString::extract(int32_t start,
  827. int32_t length,
  828. char *target,
  829. int32_t targetCapacity,
  830. enum EInvariant) const
  831. {
  832. // if the arguments are illegal, then do nothing
  833. if(targetCapacity < 0 || (targetCapacity > 0 && target == nullptr)) {
  834. return 0;
  835. }
  836. // pin the indices to legal values
  837. pinIndices(start, length);
  838. if(length <= targetCapacity) {
  839. u_UCharsToChars(getArrayStart() + start, target, length);
  840. }
  841. UErrorCode status = U_ZERO_ERROR;
  842. return u_terminateChars(target, targetCapacity, length, &status);
  843. }
  844. UnicodeString
  845. UnicodeString::tempSubString(int32_t start, int32_t len) const {
  846. pinIndices(start, len);
  847. const char16_t *array = getBuffer(); // not getArrayStart() to check kIsBogus & kOpenGetBuffer
  848. if(array==nullptr) {
  849. array=fUnion.fStackFields.fBuffer; // anything not nullptr because that would make an empty string
  850. len=-2; // bogus result string
  851. }
  852. return UnicodeString(false, array + start, len);
  853. }
  854. int32_t
  855. UnicodeString::toUTF8(int32_t start, int32_t len,
  856. char *target, int32_t capacity) const {
  857. pinIndices(start, len);
  858. int32_t length8;
  859. UErrorCode errorCode = U_ZERO_ERROR;
  860. u_strToUTF8WithSub(target, capacity, &length8,
  861. getBuffer() + start, len,
  862. 0xFFFD, // Standard substitution character.
  863. nullptr, // Don't care about number of substitutions.
  864. &errorCode);
  865. return length8;
  866. }
  867. #if U_CHARSET_IS_UTF8
  868. int32_t
  869. UnicodeString::extract(int32_t start, int32_t len,
  870. char *target, uint32_t dstSize) const {
  871. // if the arguments are illegal, then do nothing
  872. if(/*dstSize < 0 || */(dstSize > 0 && target == 0)) {
  873. return 0;
  874. }
  875. return toUTF8(start, len, target, dstSize <= 0x7fffffff ? (int32_t)dstSize : 0x7fffffff);
  876. }
  877. // else see unistr_cnv.cpp
  878. #endif
  879. void
  880. UnicodeString::extractBetween(int32_t start,
  881. int32_t limit,
  882. UnicodeString& target) const {
  883. pinIndex(start);
  884. pinIndex(limit);
  885. doExtract(start, limit - start, target);
  886. }
  887. // When converting from UTF-16 to UTF-8, the result will have at most 3 times
  888. // as many bytes as the source has UChars.
  889. // The "worst cases" are writing systems like Indic, Thai and CJK with
  890. // 3:1 bytes:UChars.
  891. void
  892. UnicodeString::toUTF8(ByteSink &sink) const {
  893. int32_t length16 = length();
  894. if(length16 != 0) {
  895. char stackBuffer[1024];
  896. int32_t capacity = (int32_t)sizeof(stackBuffer);
  897. UBool utf8IsOwned = false;
  898. char *utf8 = sink.GetAppendBuffer(length16 < capacity ? length16 : capacity,
  899. 3*length16,
  900. stackBuffer, capacity,
  901. &capacity);
  902. int32_t length8 = 0;
  903. UErrorCode errorCode = U_ZERO_ERROR;
  904. u_strToUTF8WithSub(utf8, capacity, &length8,
  905. getBuffer(), length16,
  906. 0xFFFD, // Standard substitution character.
  907. nullptr, // Don't care about number of substitutions.
  908. &errorCode);
  909. if(errorCode == U_BUFFER_OVERFLOW_ERROR) {
  910. utf8 = (char *)uprv_malloc(length8);
  911. if(utf8 != nullptr) {
  912. utf8IsOwned = true;
  913. errorCode = U_ZERO_ERROR;
  914. u_strToUTF8WithSub(utf8, length8, &length8,
  915. getBuffer(), length16,
  916. 0xFFFD, // Standard substitution character.
  917. nullptr, // Don't care about number of substitutions.
  918. &errorCode);
  919. } else {
  920. errorCode = U_MEMORY_ALLOCATION_ERROR;
  921. }
  922. }
  923. if(U_SUCCESS(errorCode)) {
  924. sink.Append(utf8, length8);
  925. sink.Flush();
  926. }
  927. if(utf8IsOwned) {
  928. uprv_free(utf8);
  929. }
  930. }
  931. }
  932. int32_t
  933. UnicodeString::toUTF32(UChar32 *utf32, int32_t capacity, UErrorCode &errorCode) const {
  934. int32_t length32=0;
  935. if(U_SUCCESS(errorCode)) {
  936. // getBuffer() and u_strToUTF32WithSub() check for illegal arguments.
  937. u_strToUTF32WithSub(utf32, capacity, &length32,
  938. getBuffer(), length(),
  939. 0xfffd, // Substitution character.
  940. nullptr, // Don't care about number of substitutions.
  941. &errorCode);
  942. }
  943. return length32;
  944. }
  945. int32_t
  946. UnicodeString::indexOf(const char16_t *srcChars,
  947. int32_t srcStart,
  948. int32_t srcLength,
  949. int32_t start,
  950. int32_t length) const
  951. {
  952. if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) {
  953. return -1;
  954. }
  955. // UnicodeString does not find empty substrings
  956. if(srcLength < 0 && srcChars[srcStart] == 0) {
  957. return -1;
  958. }
  959. // get the indices within bounds
  960. pinIndices(start, length);
  961. // find the first occurrence of the substring
  962. const char16_t *array = getArrayStart();
  963. const char16_t *match = u_strFindFirst(array + start, length, srcChars + srcStart, srcLength);
  964. if(match == nullptr) {
  965. return -1;
  966. } else {
  967. return (int32_t)(match - array);
  968. }
  969. }
  970. int32_t
  971. UnicodeString::doIndexOf(char16_t c,
  972. int32_t start,
  973. int32_t length) const
  974. {
  975. // pin indices
  976. pinIndices(start, length);
  977. // find the first occurrence of c
  978. const char16_t *array = getArrayStart();
  979. const char16_t *match = u_memchr(array + start, c, length);
  980. if(match == nullptr) {
  981. return -1;
  982. } else {
  983. return (int32_t)(match - array);
  984. }
  985. }
  986. int32_t
  987. UnicodeString::doIndexOf(UChar32 c,
  988. int32_t start,
  989. int32_t length) const {
  990. // pin indices
  991. pinIndices(start, length);
  992. // find the first occurrence of c
  993. const char16_t *array = getArrayStart();
  994. const char16_t *match = u_memchr32(array + start, c, length);
  995. if(match == nullptr) {
  996. return -1;
  997. } else {
  998. return (int32_t)(match - array);
  999. }
  1000. }
  1001. int32_t
  1002. UnicodeString::lastIndexOf(const char16_t *srcChars,
  1003. int32_t srcStart,
  1004. int32_t srcLength,
  1005. int32_t start,
  1006. int32_t length) const
  1007. {
  1008. if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) {
  1009. return -1;
  1010. }
  1011. // UnicodeString does not find empty substrings
  1012. if(srcLength < 0 && srcChars[srcStart] == 0) {
  1013. return -1;
  1014. }
  1015. // get the indices within bounds
  1016. pinIndices(start, length);
  1017. // find the last occurrence of the substring
  1018. const char16_t *array = getArrayStart();
  1019. const char16_t *match = u_strFindLast(array + start, length, srcChars + srcStart, srcLength);
  1020. if(match == nullptr) {
  1021. return -1;
  1022. } else {
  1023. return (int32_t)(match - array);
  1024. }
  1025. }
  1026. int32_t
  1027. UnicodeString::doLastIndexOf(char16_t c,
  1028. int32_t start,
  1029. int32_t length) const
  1030. {
  1031. if(isBogus()) {
  1032. return -1;
  1033. }
  1034. // pin indices
  1035. pinIndices(start, length);
  1036. // find the last occurrence of c
  1037. const char16_t *array = getArrayStart();
  1038. const char16_t *match = u_memrchr(array + start, c, length);
  1039. if(match == nullptr) {
  1040. return -1;
  1041. } else {
  1042. return (int32_t)(match - array);
  1043. }
  1044. }
  1045. int32_t
  1046. UnicodeString::doLastIndexOf(UChar32 c,
  1047. int32_t start,
  1048. int32_t length) const {
  1049. // pin indices
  1050. pinIndices(start, length);
  1051. // find the last occurrence of c
  1052. const char16_t *array = getArrayStart();
  1053. const char16_t *match = u_memrchr32(array + start, c, length);
  1054. if(match == nullptr) {
  1055. return -1;
  1056. } else {
  1057. return (int32_t)(match - array);
  1058. }
  1059. }
  1060. //========================================
  1061. // Write implementation
  1062. //========================================
  1063. UnicodeString&
  1064. UnicodeString::findAndReplace(int32_t start,
  1065. int32_t length,
  1066. const UnicodeString& oldText,
  1067. int32_t oldStart,
  1068. int32_t oldLength,
  1069. const UnicodeString& newText,
  1070. int32_t newStart,
  1071. int32_t newLength)
  1072. {
  1073. if(isBogus() || oldText.isBogus() || newText.isBogus()) {
  1074. return *this;
  1075. }
  1076. pinIndices(start, length);
  1077. oldText.pinIndices(oldStart, oldLength);
  1078. newText.pinIndices(newStart, newLength);
  1079. if(oldLength == 0) {
  1080. return *this;
  1081. }
  1082. while(length > 0 && length >= oldLength) {
  1083. int32_t pos = indexOf(oldText, oldStart, oldLength, start, length);
  1084. if(pos < 0) {
  1085. // no more oldText's here: done
  1086. break;
  1087. } else {
  1088. // we found oldText, replace it by newText and go beyond it
  1089. replace(pos, oldLength, newText, newStart, newLength);
  1090. length -= pos + oldLength - start;
  1091. start = pos + newLength;
  1092. }
  1093. }
  1094. return *this;
  1095. }
  1096. void
  1097. UnicodeString::setToBogus()
  1098. {
  1099. releaseArray();
  1100. fUnion.fFields.fLengthAndFlags = kIsBogus;
  1101. fUnion.fFields.fArray = 0;
  1102. fUnion.fFields.fCapacity = 0;
  1103. }
  1104. // turn a bogus string into an empty one
  1105. void
  1106. UnicodeString::unBogus() {
  1107. if(fUnion.fFields.fLengthAndFlags & kIsBogus) {
  1108. setToEmpty();
  1109. }
  1110. }
  1111. const char16_t *
  1112. UnicodeString::getTerminatedBuffer() {
  1113. if(!isWritable()) {
  1114. return nullptr;
  1115. }
  1116. char16_t *array = getArrayStart();
  1117. int32_t len = length();
  1118. if(len < getCapacity()) {
  1119. if(fUnion.fFields.fLengthAndFlags & kBufferIsReadonly) {
  1120. // If len<capacity on a read-only alias, then array[len] is
  1121. // either the original NUL (if constructed with (true, s, length))
  1122. // or one of the original string contents characters (if later truncated),
  1123. // therefore we can assume that array[len] is initialized memory.
  1124. if(array[len] == 0) {
  1125. return array;
  1126. }
  1127. } else if(((fUnion.fFields.fLengthAndFlags & kRefCounted) == 0 || refCount() == 1)) {
  1128. // kRefCounted: Do not write the NUL if the buffer is shared.
  1129. // That is mostly safe, except when the length of one copy was modified
  1130. // without copy-on-write, e.g., via truncate(newLength) or remove().
  1131. // Then the NUL would be written into the middle of another copy's string.
  1132. // Otherwise, the buffer is fully writable and it is anyway safe to write the NUL.
  1133. // Do not test if there is a NUL already because it might be uninitialized memory.
  1134. // (That would be safe, but tools like valgrind & Purify would complain.)
  1135. array[len] = 0;
  1136. return array;
  1137. }
  1138. }
  1139. if(len<INT32_MAX && cloneArrayIfNeeded(len+1)) {
  1140. array = getArrayStart();
  1141. array[len] = 0;
  1142. return array;
  1143. } else {
  1144. return nullptr;
  1145. }
  1146. }
  1147. // setTo() analogous to the readonly-aliasing constructor with the same signature
  1148. UnicodeString &
  1149. UnicodeString::setTo(UBool isTerminated,
  1150. ConstChar16Ptr textPtr,
  1151. int32_t textLength)
  1152. {
  1153. if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) {
  1154. // do not modify a string that has an "open" getBuffer(minCapacity)
  1155. return *this;
  1156. }
  1157. const char16_t *text = textPtr;
  1158. if(text == nullptr) {
  1159. // treat as an empty string, do not alias
  1160. releaseArray();
  1161. setToEmpty();
  1162. return *this;
  1163. }
  1164. if( textLength < -1 ||
  1165. (textLength == -1 && !isTerminated) ||
  1166. (textLength >= 0 && isTerminated && text[textLength] != 0)
  1167. ) {
  1168. setToBogus();
  1169. return *this;
  1170. }
  1171. releaseArray();
  1172. if(textLength == -1) {
  1173. // text is terminated, or else it would have failed the above test
  1174. textLength = u_strlen(text);
  1175. }
  1176. fUnion.fFields.fLengthAndFlags = kReadonlyAlias;
  1177. setArray((char16_t *)text, textLength, isTerminated ? textLength + 1 : textLength);
  1178. return *this;
  1179. }
  1180. // setTo() analogous to the writable-aliasing constructor with the same signature
  1181. UnicodeString &
  1182. UnicodeString::setTo(char16_t *buffer,
  1183. int32_t buffLength,
  1184. int32_t buffCapacity) {
  1185. if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) {
  1186. // do not modify a string that has an "open" getBuffer(minCapacity)
  1187. return *this;
  1188. }
  1189. if(buffer == nullptr) {
  1190. // treat as an empty string, do not alias
  1191. releaseArray();
  1192. setToEmpty();
  1193. return *this;
  1194. }
  1195. if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) {
  1196. setToBogus();
  1197. return *this;
  1198. } else if(buffLength == -1) {
  1199. // buffLength = u_strlen(buff); but do not look beyond buffCapacity
  1200. const char16_t *p = buffer, *limit = buffer + buffCapacity;
  1201. while(p != limit && *p != 0) {
  1202. ++p;
  1203. }
  1204. buffLength = (int32_t)(p - buffer);
  1205. }
  1206. releaseArray();
  1207. fUnion.fFields.fLengthAndFlags = kWritableAlias;
  1208. setArray(buffer, buffLength, buffCapacity);
  1209. return *this;
  1210. }
  1211. UnicodeString &UnicodeString::setToUTF8(StringPiece utf8) {
  1212. unBogus();
  1213. int32_t length = utf8.length();
  1214. int32_t capacity;
  1215. // The UTF-16 string will be at most as long as the UTF-8 string.
  1216. if(length <= US_STACKBUF_SIZE) {
  1217. capacity = US_STACKBUF_SIZE;
  1218. } else {
  1219. capacity = length + 1; // +1 for the terminating NUL.
  1220. }
  1221. char16_t *utf16 = getBuffer(capacity);
  1222. int32_t length16;
  1223. UErrorCode errorCode = U_ZERO_ERROR;
  1224. u_strFromUTF8WithSub(utf16, getCapacity(), &length16,
  1225. utf8.data(), length,
  1226. 0xfffd, // Substitution character.
  1227. nullptr, // Don't care about number of substitutions.
  1228. &errorCode);
  1229. releaseBuffer(length16);
  1230. if(U_FAILURE(errorCode)) {
  1231. setToBogus();
  1232. }
  1233. return *this;
  1234. }
  1235. UnicodeString&
  1236. UnicodeString::setCharAt(int32_t offset,
  1237. char16_t c)
  1238. {
  1239. int32_t len = length();
  1240. if(cloneArrayIfNeeded() && len > 0) {
  1241. if(offset < 0) {
  1242. offset = 0;
  1243. } else if(offset >= len) {
  1244. offset = len - 1;
  1245. }
  1246. getArrayStart()[offset] = c;
  1247. }
  1248. return *this;
  1249. }
  1250. UnicodeString&
  1251. UnicodeString::replace(int32_t start,
  1252. int32_t _length,
  1253. UChar32 srcChar) {
  1254. char16_t buffer[U16_MAX_LENGTH];
  1255. int32_t count = 0;
  1256. UBool isError = false;
  1257. U16_APPEND(buffer, count, U16_MAX_LENGTH, srcChar, isError);
  1258. // We test isError so that the compiler does not complain that we don't.
  1259. // If isError (srcChar is not a valid code point) then count==0 which means
  1260. // we remove the source segment rather than replacing it with srcChar.
  1261. return doReplace(start, _length, buffer, 0, isError ? 0 : count);
  1262. }
  1263. UnicodeString&
  1264. UnicodeString::append(UChar32 srcChar) {
  1265. char16_t buffer[U16_MAX_LENGTH];
  1266. int32_t _length = 0;
  1267. UBool isError = false;
  1268. U16_APPEND(buffer, _length, U16_MAX_LENGTH, srcChar, isError);
  1269. // We test isError so that the compiler does not complain that we don't.
  1270. // If isError then _length==0 which turns the doAppend() into a no-op anyway.
  1271. return isError ? *this : doAppend(buffer, 0, _length);
  1272. }
  1273. UnicodeString&
  1274. UnicodeString::doReplace( int32_t start,
  1275. int32_t length,
  1276. const UnicodeString& src,
  1277. int32_t srcStart,
  1278. int32_t srcLength)
  1279. {
  1280. // pin the indices to legal values
  1281. src.pinIndices(srcStart, srcLength);
  1282. // get the characters from src
  1283. // and replace the range in ourselves with them
  1284. return doReplace(start, length, src.getArrayStart(), srcStart, srcLength);
  1285. }
  1286. UnicodeString&
  1287. UnicodeString::doReplace(int32_t start,
  1288. int32_t length,
  1289. const char16_t *srcChars,
  1290. int32_t srcStart,
  1291. int32_t srcLength)
  1292. {
  1293. if(!isWritable()) {
  1294. return *this;
  1295. }
  1296. int32_t oldLength = this->length();
  1297. // optimize (read-only alias).remove(0, start) and .remove(start, end)
  1298. if((fUnion.fFields.fLengthAndFlags&kBufferIsReadonly) && srcLength == 0) {
  1299. if(start == 0) {
  1300. // remove prefix by adjusting the array pointer
  1301. pinIndex(length);
  1302. fUnion.fFields.fArray += length;
  1303. fUnion.fFields.fCapacity -= length;
  1304. setLength(oldLength - length);
  1305. return *this;
  1306. } else {
  1307. pinIndex(start);
  1308. if(length >= (oldLength - start)) {
  1309. // remove suffix by reducing the length (like truncate())
  1310. setLength(start);
  1311. fUnion.fFields.fCapacity = start; // not NUL-terminated any more
  1312. return *this;
  1313. }
  1314. }
  1315. }
  1316. if(start == oldLength) {
  1317. return doAppend(srcChars, srcStart, srcLength);
  1318. }
  1319. if(srcChars == 0) {
  1320. srcLength = 0;
  1321. } else {
  1322. // Perform all remaining operations relative to srcChars + srcStart.
  1323. // From this point forward, do not use srcStart.
  1324. srcChars += srcStart;
  1325. if (srcLength < 0) {
  1326. // get the srcLength if necessary
  1327. srcLength = u_strlen(srcChars);
  1328. }
  1329. }
  1330. // pin the indices to legal values
  1331. pinIndices(start, length);
  1332. // Calculate the size of the string after the replace.
  1333. // Avoid int32_t overflow.
  1334. int32_t newLength = oldLength - length;
  1335. if(srcLength > (INT32_MAX - newLength)) {
  1336. setToBogus();
  1337. return *this;
  1338. }
  1339. newLength += srcLength;
  1340. // Check for insertion into ourself
  1341. const char16_t *oldArray = getArrayStart();
  1342. if (isBufferWritable() &&
  1343. oldArray < srcChars + srcLength &&
  1344. srcChars < oldArray + oldLength) {
  1345. // Copy into a new UnicodeString and start over
  1346. UnicodeString copy(srcChars, srcLength);
  1347. if (copy.isBogus()) {
  1348. setToBogus();
  1349. return *this;
  1350. }
  1351. return doReplace(start, length, copy.getArrayStart(), 0, srcLength);
  1352. }
  1353. // cloneArrayIfNeeded(doCopyArray=false) may change fArray but will not copy the current contents;
  1354. // therefore we need to keep the current fArray
  1355. char16_t oldStackBuffer[US_STACKBUF_SIZE];
  1356. if((fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) && (newLength > US_STACKBUF_SIZE)) {
  1357. // copy the stack buffer contents because it will be overwritten with
  1358. // fUnion.fFields values
  1359. u_memcpy(oldStackBuffer, oldArray, oldLength);
  1360. oldArray = oldStackBuffer;
  1361. }
  1362. // clone our array and allocate a bigger array if needed
  1363. int32_t *bufferToDelete = 0;
  1364. if(!cloneArrayIfNeeded(newLength, getGrowCapacity(newLength),
  1365. false, &bufferToDelete)
  1366. ) {
  1367. return *this;
  1368. }
  1369. // now do the replace
  1370. char16_t *newArray = getArrayStart();
  1371. if(newArray != oldArray) {
  1372. // if fArray changed, then we need to copy everything except what will change
  1373. us_arrayCopy(oldArray, 0, newArray, 0, start);
  1374. us_arrayCopy(oldArray, start + length,
  1375. newArray, start + srcLength,
  1376. oldLength - (start + length));
  1377. } else if(length != srcLength) {
  1378. // fArray did not change; copy only the portion that isn't changing, leaving a hole
  1379. us_arrayCopy(oldArray, start + length,
  1380. newArray, start + srcLength,
  1381. oldLength - (start + length));
  1382. }
  1383. // now fill in the hole with the new string
  1384. us_arrayCopy(srcChars, 0, newArray, start, srcLength);
  1385. setLength(newLength);
  1386. // delayed delete in case srcChars == fArray when we started, and
  1387. // to keep oldArray alive for the above operations
  1388. if (bufferToDelete) {
  1389. uprv_free(bufferToDelete);
  1390. }
  1391. return *this;
  1392. }
  1393. // Versions of doReplace() only for append() variants.
  1394. // doReplace() and doAppend() optimize for different cases.
  1395. UnicodeString&
  1396. UnicodeString::doAppend(const UnicodeString& src, int32_t srcStart, int32_t srcLength) {
  1397. if(srcLength == 0) {
  1398. return *this;
  1399. }
  1400. // pin the indices to legal values
  1401. src.pinIndices(srcStart, srcLength);
  1402. return doAppend(src.getArrayStart(), srcStart, srcLength);
  1403. }
  1404. UnicodeString&
  1405. UnicodeString::doAppend(const char16_t *srcChars, int32_t srcStart, int32_t srcLength) {
  1406. if(!isWritable() || srcLength == 0 || srcChars == nullptr) {
  1407. return *this;
  1408. }
  1409. // Perform all remaining operations relative to srcChars + srcStart.
  1410. // From this point forward, do not use srcStart.
  1411. srcChars += srcStart;
  1412. if(srcLength < 0) {
  1413. // get the srcLength if necessary
  1414. if((srcLength = u_strlen(srcChars)) == 0) {
  1415. return *this;
  1416. }
  1417. }
  1418. int32_t oldLength = length();
  1419. int32_t newLength;
  1420. if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {
  1421. setToBogus();
  1422. return *this;
  1423. }
  1424. // Check for append onto ourself
  1425. const char16_t* oldArray = getArrayStart();
  1426. if (isBufferWritable() &&
  1427. oldArray < srcChars + srcLength &&
  1428. srcChars < oldArray + oldLength) {
  1429. // Copy into a new UnicodeString and start over
  1430. UnicodeString copy(srcChars, srcLength);
  1431. if (copy.isBogus()) {
  1432. setToBogus();
  1433. return *this;
  1434. }
  1435. return doAppend(copy.getArrayStart(), 0, srcLength);
  1436. }
  1437. // optimize append() onto a large-enough, owned string
  1438. if((newLength <= getCapacity() && isBufferWritable()) ||
  1439. cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {
  1440. char16_t *newArray = getArrayStart();
  1441. // Do not copy characters when
  1442. // char16_t *buffer=str.getAppendBuffer(...);
  1443. // is followed by
  1444. // str.append(buffer, length);
  1445. // or
  1446. // str.appendString(buffer, length)
  1447. // or similar.
  1448. if(srcChars != newArray + oldLength) {
  1449. us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);
  1450. }
  1451. setLength(newLength);
  1452. }
  1453. return *this;
  1454. }
  1455. /**
  1456. * Replaceable API
  1457. */
  1458. void
  1459. UnicodeString::handleReplaceBetween(int32_t start,
  1460. int32_t limit,
  1461. const UnicodeString& text) {
  1462. replaceBetween(start, limit, text);
  1463. }
  1464. /**
  1465. * Replaceable API
  1466. */
  1467. void
  1468. UnicodeString::copy(int32_t start, int32_t limit, int32_t dest) {
  1469. if (limit <= start) {
  1470. return; // Nothing to do; avoid bogus malloc call
  1471. }
  1472. char16_t* text = (char16_t*) uprv_malloc( sizeof(char16_t) * (limit - start) );
  1473. // Check to make sure text is not null.
  1474. if (text != nullptr) {
  1475. extractBetween(start, limit, text, 0);
  1476. insert(dest, text, 0, limit - start);
  1477. uprv_free(text);
  1478. }
  1479. }
  1480. /**
  1481. * Replaceable API
  1482. *
  1483. * NOTE: This is for the Replaceable class. There is no rep.cpp,
  1484. * so we implement this function here.
  1485. */
  1486. UBool Replaceable::hasMetaData() const {
  1487. return true;
  1488. }
  1489. /**
  1490. * Replaceable API
  1491. */
  1492. UBool UnicodeString::hasMetaData() const {
  1493. return false;
  1494. }
  1495. UnicodeString&
  1496. UnicodeString::doReverse(int32_t start, int32_t length) {
  1497. if(length <= 1 || !cloneArrayIfNeeded()) {
  1498. return *this;
  1499. }
  1500. // pin the indices to legal values
  1501. pinIndices(start, length);
  1502. if(length <= 1) { // pinIndices() might have shrunk the length
  1503. return *this;
  1504. }
  1505. char16_t *left = getArrayStart() + start;
  1506. char16_t *right = left + length - 1; // -1 for inclusive boundary (length>=2)
  1507. char16_t swap;
  1508. UBool hasSupplementary = false;
  1509. // Before the loop we know left<right because length>=2.
  1510. do {
  1511. hasSupplementary |= (UBool)U16_IS_LEAD(swap = *left);
  1512. hasSupplementary |= (UBool)U16_IS_LEAD(*left++ = *right);
  1513. *right-- = swap;
  1514. } while(left < right);
  1515. // Make sure to test the middle code unit of an odd-length string.
  1516. // Redundant if the length is even.
  1517. hasSupplementary |= (UBool)U16_IS_LEAD(*left);
  1518. /* if there are supplementary code points in the reversed range, then re-swap their surrogates */
  1519. if(hasSupplementary) {
  1520. char16_t swap2;
  1521. left = getArrayStart() + start;
  1522. right = left + length - 1; // -1 so that we can look at *(left+1) if left<right
  1523. while(left < right) {
  1524. if(U16_IS_TRAIL(swap = *left) && U16_IS_LEAD(swap2 = *(left + 1))) {
  1525. *left++ = swap2;
  1526. *left++ = swap;
  1527. } else {
  1528. ++left;
  1529. }
  1530. }
  1531. }
  1532. return *this;
  1533. }
  1534. UBool
  1535. UnicodeString::padLeading(int32_t targetLength,
  1536. char16_t padChar)
  1537. {
  1538. int32_t oldLength = length();
  1539. if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) {
  1540. return false;
  1541. } else {
  1542. // move contents up by padding width
  1543. char16_t *array = getArrayStart();
  1544. int32_t start = targetLength - oldLength;
  1545. us_arrayCopy(array, 0, array, start, oldLength);
  1546. // fill in padding character
  1547. while(--start >= 0) {
  1548. array[start] = padChar;
  1549. }
  1550. setLength(targetLength);
  1551. return true;
  1552. }
  1553. }
  1554. UBool
  1555. UnicodeString::padTrailing(int32_t targetLength,
  1556. char16_t padChar)
  1557. {
  1558. int32_t oldLength = length();
  1559. if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) {
  1560. return false;
  1561. } else {
  1562. // fill in padding character
  1563. char16_t *array = getArrayStart();
  1564. int32_t length = targetLength;
  1565. while(--length >= oldLength) {
  1566. array[length] = padChar;
  1567. }
  1568. setLength(targetLength);
  1569. return true;
  1570. }
  1571. }
  1572. //========================================
  1573. // Hashing
  1574. //========================================
  1575. int32_t
  1576. UnicodeString::doHashCode() const
  1577. {
  1578. /* Delegate hash computation to uhash. This makes UnicodeString
  1579. * hashing consistent with char16_t* hashing. */
  1580. int32_t hashCode = ustr_hashUCharsN(getArrayStart(), length());
  1581. if (hashCode == kInvalidHashCode) {
  1582. hashCode = kEmptyHashCode;
  1583. }
  1584. return hashCode;
  1585. }
  1586. //========================================
  1587. // External Buffer
  1588. //========================================
  1589. char16_t *
  1590. UnicodeString::getBuffer(int32_t minCapacity) {
  1591. if(minCapacity>=-1 && cloneArrayIfNeeded(minCapacity)) {
  1592. fUnion.fFields.fLengthAndFlags|=kOpenGetBuffer;
  1593. setZeroLength();
  1594. return getArrayStart();
  1595. } else {
  1596. return nullptr;
  1597. }
  1598. }
  1599. void
  1600. UnicodeString::releaseBuffer(int32_t newLength) {
  1601. if(fUnion.fFields.fLengthAndFlags&kOpenGetBuffer && newLength>=-1) {
  1602. // set the new fLength
  1603. int32_t capacity=getCapacity();
  1604. if(newLength==-1) {
  1605. // the new length is the string length, capped by fCapacity
  1606. const char16_t *array=getArrayStart(), *p=array, *limit=array+capacity;
  1607. while(p<limit && *p!=0) {
  1608. ++p;
  1609. }
  1610. newLength=(int32_t)(p-array);
  1611. } else if(newLength>capacity) {
  1612. newLength=capacity;
  1613. }
  1614. setLength(newLength);
  1615. fUnion.fFields.fLengthAndFlags&=~kOpenGetBuffer;
  1616. }
  1617. }
  1618. //========================================
  1619. // Miscellaneous
  1620. //========================================
  1621. UBool
  1622. UnicodeString::cloneArrayIfNeeded(int32_t newCapacity,
  1623. int32_t growCapacity,
  1624. UBool doCopyArray,
  1625. int32_t **pBufferToDelete,
  1626. UBool forceClone) {
  1627. // default parameters need to be static, therefore
  1628. // the defaults are -1 to have convenience defaults
  1629. if(newCapacity == -1) {
  1630. newCapacity = getCapacity();
  1631. }
  1632. // while a getBuffer(minCapacity) is "open",
  1633. // prevent any modifications of the string by returning false here
  1634. // if the string is bogus, then only an assignment or similar can revive it
  1635. if(!isWritable()) {
  1636. return false;
  1637. }
  1638. /*
  1639. * We need to make a copy of the array if
  1640. * the buffer is read-only, or
  1641. * the buffer is refCounted (shared), and refCount>1, or
  1642. * the buffer is too small.
  1643. * Return false if memory could not be allocated.
  1644. */
  1645. if(forceClone ||
  1646. fUnion.fFields.fLengthAndFlags & kBufferIsReadonly ||
  1647. (fUnion.fFields.fLengthAndFlags & kRefCounted && refCount() > 1) ||
  1648. newCapacity > getCapacity()
  1649. ) {
  1650. // check growCapacity for default value and use of the stack buffer
  1651. if(growCapacity < 0) {
  1652. growCapacity = newCapacity;
  1653. } else if(newCapacity <= US_STACKBUF_SIZE && growCapacity > US_STACKBUF_SIZE) {
  1654. growCapacity = US_STACKBUF_SIZE;
  1655. }
  1656. // save old values
  1657. char16_t oldStackBuffer[US_STACKBUF_SIZE];
  1658. char16_t *oldArray;
  1659. int32_t oldLength = length();
  1660. int16_t flags = fUnion.fFields.fLengthAndFlags;
  1661. if(flags&kUsingStackBuffer) {
  1662. U_ASSERT(!(flags&kRefCounted)); /* kRefCounted and kUsingStackBuffer are mutally exclusive */
  1663. if(doCopyArray && growCapacity > US_STACKBUF_SIZE) {
  1664. // copy the stack buffer contents because it will be overwritten with
  1665. // fUnion.fFields values
  1666. us_arrayCopy(fUnion.fStackFields.fBuffer, 0, oldStackBuffer, 0, oldLength);
  1667. oldArray = oldStackBuffer;
  1668. } else {
  1669. oldArray = nullptr; // no need to copy from the stack buffer to itself
  1670. }
  1671. } else {
  1672. oldArray = fUnion.fFields.fArray;
  1673. U_ASSERT(oldArray!=nullptr); /* when stack buffer is not used, oldArray must have a non-nullptr reference */
  1674. }
  1675. // allocate a new array
  1676. if(allocate(growCapacity) ||
  1677. (newCapacity < growCapacity && allocate(newCapacity))
  1678. ) {
  1679. if(doCopyArray) {
  1680. // copy the contents
  1681. // do not copy more than what fits - it may be smaller than before
  1682. int32_t minLength = oldLength;
  1683. newCapacity = getCapacity();
  1684. if(newCapacity < minLength) {
  1685. minLength = newCapacity;
  1686. }
  1687. if(oldArray != nullptr) {
  1688. us_arrayCopy(oldArray, 0, getArrayStart(), 0, minLength);
  1689. }
  1690. setLength(minLength);
  1691. } else {
  1692. setZeroLength();
  1693. }
  1694. // release the old array
  1695. if(flags & kRefCounted) {
  1696. // the array is refCounted; decrement and release if 0
  1697. u_atomic_int32_t *pRefCount = ((u_atomic_int32_t *)oldArray - 1);
  1698. if(umtx_atomic_dec(pRefCount) == 0) {
  1699. if(pBufferToDelete == 0) {
  1700. // Note: cast to (void *) is needed with MSVC, where u_atomic_int32_t
  1701. // is defined as volatile. (Volatile has useful non-standard behavior
  1702. // with this compiler.)
  1703. uprv_free((void *)pRefCount);
  1704. } else {
  1705. // the caller requested to delete it himself
  1706. *pBufferToDelete = (int32_t *)pRefCount;
  1707. }
  1708. }
  1709. }
  1710. } else {
  1711. // not enough memory for growCapacity and not even for the smaller newCapacity
  1712. // reset the old values for setToBogus() to release the array
  1713. if(!(flags&kUsingStackBuffer)) {
  1714. fUnion.fFields.fArray = oldArray;
  1715. }
  1716. fUnion.fFields.fLengthAndFlags = flags;
  1717. setToBogus();
  1718. return false;
  1719. }
  1720. }
  1721. return true;
  1722. }
  1723. // UnicodeStringAppendable ------------------------------------------------- ***
  1724. UnicodeStringAppendable::~UnicodeStringAppendable() {}
  1725. UBool
  1726. UnicodeStringAppendable::appendCodeUnit(char16_t c) {
  1727. return str.doAppend(&c, 0, 1).isWritable();
  1728. }
  1729. UBool
  1730. UnicodeStringAppendable::appendCodePoint(UChar32 c) {
  1731. char16_t buffer[U16_MAX_LENGTH];
  1732. int32_t cLength = 0;
  1733. UBool isError = false;
  1734. U16_APPEND(buffer, cLength, U16_MAX_LENGTH, c, isError);
  1735. return !isError && str.doAppend(buffer, 0, cLength).isWritable();
  1736. }
  1737. UBool
  1738. UnicodeStringAppendable::appendString(const char16_t *s, int32_t length) {
  1739. return str.doAppend(s, 0, length).isWritable();
  1740. }
  1741. UBool
  1742. UnicodeStringAppendable::reserveAppendCapacity(int32_t appendCapacity) {
  1743. return str.cloneArrayIfNeeded(str.length() + appendCapacity);
  1744. }
  1745. char16_t *
  1746. UnicodeStringAppendable::getAppendBuffer(int32_t minCapacity,
  1747. int32_t desiredCapacityHint,
  1748. char16_t *scratch, int32_t scratchCapacity,
  1749. int32_t *resultCapacity) {
  1750. if(minCapacity < 1 || scratchCapacity < minCapacity) {
  1751. *resultCapacity = 0;
  1752. return nullptr;
  1753. }
  1754. int32_t oldLength = str.length();
  1755. if(minCapacity <= (kMaxCapacity - oldLength) &&
  1756. desiredCapacityHint <= (kMaxCapacity - oldLength) &&
  1757. str.cloneArrayIfNeeded(oldLength + minCapacity, oldLength + desiredCapacityHint)) {
  1758. *resultCapacity = str.getCapacity() - oldLength;
  1759. return str.getArrayStart() + oldLength;
  1760. }
  1761. *resultCapacity = scratchCapacity;
  1762. return scratch;
  1763. }
  1764. U_NAMESPACE_END
  1765. U_NAMESPACE_USE
  1766. U_CAPI int32_t U_EXPORT2
  1767. uhash_hashUnicodeString(const UElement key) {
  1768. const UnicodeString *str = (const UnicodeString*) key.pointer;
  1769. return (str == nullptr) ? 0 : str->hashCode();
  1770. }
  1771. // Moved here from uhash_us.cpp so that using a UVector of UnicodeString*
  1772. // does not depend on hashtable code.
  1773. U_CAPI UBool U_EXPORT2
  1774. uhash_compareUnicodeString(const UElement key1, const UElement key2) {
  1775. const UnicodeString *str1 = (const UnicodeString*) key1.pointer;
  1776. const UnicodeString *str2 = (const UnicodeString*) key2.pointer;
  1777. if (str1 == str2) {
  1778. return true;
  1779. }
  1780. if (str1 == nullptr || str2 == nullptr) {
  1781. return false;
  1782. }
  1783. return *str1 == *str2;
  1784. }
  1785. #ifdef U_STATIC_IMPLEMENTATION
  1786. /*
  1787. This should never be called. It is defined here to make sure that the
  1788. virtual vector deleting destructor is defined within unistr.cpp.
  1789. The vector deleting destructor is already a part of UObject,
  1790. but defining it here makes sure that it is included with this object file.
  1791. This makes sure that static library dependencies are kept to a minimum.
  1792. */
  1793. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 1100
  1794. #pragma GCC diagnostic push
  1795. #pragma GCC diagnostic ignored "-Wunused-function"
  1796. static void uprv_UnicodeStringDummy() {
  1797. delete [] (new UnicodeString[2]);
  1798. }
  1799. #pragma GCC diagnostic pop
  1800. #endif
  1801. #endif