StringImpl.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011
  1. /*
  2. * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  3. * (C) 1999 Antti Koivisto (koivisto@kde.org)
  4. * (C) 2001 Dirk Mueller ( mueller@kde.org )
  5. * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2013 Apple Inc. All rights reserved.
  6. * Copyright (C) 2006 Andrew Wellington (proton@wiretapped.net)
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Library General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Library General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Library General Public License
  19. * along with this library; see the file COPYING.LIB. If not, write to
  20. * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301, USA.
  22. *
  23. */
  24. #include "config.h"
  25. #include "StringImpl.h"
  26. #include "AtomicString.h"
  27. #include "StringBuffer.h"
  28. #include "StringHash.h"
  29. #include <wtf/ProcessID.h>
  30. #include <wtf/StdLibExtras.h>
  31. #include <wtf/WTFThreadData.h>
  32. #include <wtf/unicode/CharacterNames.h>
  33. #ifdef STRING_STATS
  34. #include <unistd.h>
  35. #include <wtf/DataLog.h>
  36. #endif
  37. using namespace std;
  38. namespace WTF {
  39. using namespace Unicode;
  40. COMPILE_ASSERT(sizeof(StringImpl) == 2 * sizeof(int) + 3 * sizeof(void*), StringImpl_should_stay_small);
  41. #ifdef STRING_STATS
  42. StringStats StringImpl::m_stringStats;
  43. unsigned StringStats::s_stringRemovesTillPrintStats = StringStats::s_printStringStatsFrequency;
  44. void StringStats::removeString(StringImpl* string)
  45. {
  46. unsigned length = string->length();
  47. bool isSubString = string->isSubString();
  48. --m_totalNumberStrings;
  49. if (string->has16BitShadow()) {
  50. --m_numberUpconvertedStrings;
  51. if (!isSubString)
  52. m_totalUpconvertedData -= length;
  53. }
  54. if (string->is8Bit()) {
  55. --m_number8BitStrings;
  56. if (!isSubString)
  57. m_total8BitData -= length;
  58. } else {
  59. --m_number16BitStrings;
  60. if (!isSubString)
  61. m_total16BitData -= length;
  62. }
  63. if (!--s_stringRemovesTillPrintStats) {
  64. s_stringRemovesTillPrintStats = s_printStringStatsFrequency;
  65. printStats();
  66. }
  67. }
  68. void StringStats::printStats()
  69. {
  70. dataLogF("String stats for process id %d:\n", getCurrentProcessID());
  71. unsigned long long totalNumberCharacters = m_total8BitData + m_total16BitData;
  72. double percent8Bit = m_totalNumberStrings ? ((double)m_number8BitStrings * 100) / (double)m_totalNumberStrings : 0.0;
  73. double average8bitLength = m_number8BitStrings ? (double)m_total8BitData / (double)m_number8BitStrings : 0.0;
  74. dataLogF("%8u (%5.2f%%) 8 bit %12llu chars %12llu bytes avg length %6.1f\n", m_number8BitStrings, percent8Bit, m_total8BitData, m_total8BitData, average8bitLength);
  75. double percent16Bit = m_totalNumberStrings ? ((double)m_number16BitStrings * 100) / (double)m_totalNumberStrings : 0.0;
  76. double average16bitLength = m_number16BitStrings ? (double)m_total16BitData / (double)m_number16BitStrings : 0.0;
  77. dataLogF("%8u (%5.2f%%) 16 bit %12llu chars %12llu bytes avg length %6.1f\n", m_number16BitStrings, percent16Bit, m_total16BitData, m_total16BitData * 2, average16bitLength);
  78. double percentUpconverted = m_totalNumberStrings ? ((double)m_numberUpconvertedStrings * 100) / (double)m_number8BitStrings : 0.0;
  79. double averageUpconvertedLength = m_numberUpconvertedStrings ? (double)m_totalUpconvertedData / (double)m_numberUpconvertedStrings : 0.0;
  80. dataLogF("%8u (%5.2f%%) upconverted %12llu chars %12llu bytes avg length %6.1f\n", m_numberUpconvertedStrings, percentUpconverted, m_totalUpconvertedData, m_totalUpconvertedData * 2, averageUpconvertedLength);
  81. double averageLength = m_totalNumberStrings ? (double)totalNumberCharacters / (double)m_totalNumberStrings : 0.0;
  82. unsigned long long totalDataBytes = m_total8BitData + (m_total16BitData + m_totalUpconvertedData) * 2;
  83. dataLogF("%8u Total %12llu chars %12llu bytes avg length %6.1f\n", m_totalNumberStrings, totalNumberCharacters, totalDataBytes, averageLength);
  84. unsigned long long totalSavedBytes = m_total8BitData - m_totalUpconvertedData;
  85. double percentSavings = totalSavedBytes ? ((double)totalSavedBytes * 100) / (double)(totalDataBytes + totalSavedBytes) : 0.0;
  86. dataLogF(" Total savings %12llu bytes (%5.2f%%)\n", totalSavedBytes, percentSavings);
  87. }
  88. #endif
  89. StringImpl::~StringImpl()
  90. {
  91. ASSERT(!isStatic());
  92. STRING_STATS_REMOVE_STRING(this);
  93. if (isAtomic())
  94. AtomicString::remove(this);
  95. if (isIdentifier()) {
  96. if (!wtfThreadData().currentIdentifierTable()->remove(this))
  97. CRASH();
  98. }
  99. BufferOwnership ownership = bufferOwnership();
  100. if (has16BitShadow()) {
  101. ASSERT(m_copyData16);
  102. fastFree(m_copyData16);
  103. }
  104. if (ownership == BufferInternal)
  105. return;
  106. if (ownership == BufferOwned) {
  107. // We use m_data8, but since it is a union with m_data16 this works either way.
  108. ASSERT(m_data8);
  109. fastFree(const_cast<LChar*>(m_data8));
  110. return;
  111. }
  112. #if PLATFORM(QT)
  113. if (ownership == BufferAdoptedQString) {
  114. if (!m_qStringData->ref.deref())
  115. QStringData::deallocate(m_qStringData);
  116. return;
  117. }
  118. #endif
  119. ASSERT(ownership == BufferSubstring);
  120. ASSERT(m_substringBuffer);
  121. m_substringBuffer->deref();
  122. }
  123. void StringImpl::destroy(StringImpl* stringImpl)
  124. {
  125. stringImpl->~StringImpl();
  126. #if ENABLE(DETACHED_JIT)
  127. JITSharedDataMemory::isInRange((uintptr_t)stringImpl) ? JITSharedDataMemory::shared_free(stringImpl) :
  128. #endif
  129. fastFree(stringImpl);
  130. }
  131. PassRefPtr<StringImpl> StringImpl::createFromLiteral(const char* characters, unsigned length)
  132. {
  133. ASSERT_WITH_MESSAGE(length, "Use StringImpl::empty() to create an empty string");
  134. ASSERT(charactersAreAllASCII<LChar>(reinterpret_cast<const LChar*>(characters), length));
  135. return adoptRef(new StringImpl(reinterpret_cast<const LChar*>(characters), length, DoesHaveTerminatingNullCharacter, ConstructWithoutCopying));
  136. }
  137. PassRefPtr<StringImpl> StringImpl::createFromLiteral(const char* characters)
  138. {
  139. return createFromLiteral(characters, strlen(characters));
  140. }
  141. PassRefPtr<StringImpl> StringImpl::createWithoutCopying(const UChar* characters, unsigned length, HasTerminatingNullCharacter hasTerminatingNullCharacter)
  142. {
  143. if (!length)
  144. return empty();
  145. return adoptRef(new StringImpl(characters, length, hasTerminatingNullCharacter, ConstructWithoutCopying));
  146. }
  147. PassRefPtr<StringImpl> StringImpl::createWithoutCopying(const LChar* characters, unsigned length, HasTerminatingNullCharacter hasTerminatingNullCharacter)
  148. {
  149. if (!length)
  150. return empty();
  151. return adoptRef(new StringImpl(characters, length, hasTerminatingNullCharacter, ConstructWithoutCopying));
  152. }
  153. PassRefPtr<StringImpl> StringImpl::createUninitialized(unsigned length, LChar*& data, StringImplType type)
  154. {
  155. if (!length) {
  156. data = 0;
  157. return empty();
  158. }
  159. // Allocate a single buffer large enough to contain the StringImpl
  160. // struct as well as the data which it contains. This removes one
  161. // heap allocation from this call.
  162. if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(LChar)))
  163. CRASH();
  164. size_t size = sizeof(StringImpl) + length * sizeof(LChar);
  165. StringImpl* string = static_cast<StringImpl*>(
  166. #if ENABLE(DETACHED_JIT)
  167. type == StringImplShared ? JITSharedDataMemory::shared_malloc(size) :
  168. #endif
  169. fastMalloc(size)
  170. );
  171. data = reinterpret_cast<LChar*>(string + 1);
  172. return adoptRef(new (NotNull, string) StringImpl(length, Force8BitConstructor));
  173. }
  174. PassRefPtr<StringImpl> StringImpl::createUninitialized(unsigned length, UChar*& data, StringImplType type)
  175. {
  176. if (!length) {
  177. data = 0;
  178. return empty();
  179. }
  180. // Allocate a single buffer large enough to contain the StringImpl
  181. // struct as well as the data which it contains. This removes one
  182. // heap allocation from this call.
  183. if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(UChar)))
  184. CRASH();
  185. size_t size = sizeof(StringImpl) + length * sizeof(UChar);
  186. StringImpl* string = static_cast<StringImpl*>(
  187. #if ENABLE(DETACHED_JIT)
  188. type == StringImplShared ? JITSharedDataMemory::shared_malloc(size) :
  189. #endif
  190. fastMalloc(size)
  191. );
  192. data = reinterpret_cast<UChar*>(string + 1);
  193. return adoptRef(new (NotNull, string) StringImpl(length));
  194. }
  195. PassRefPtr<StringImpl> StringImpl::reallocate(PassRefPtr<StringImpl> originalString, unsigned length, LChar*& data)
  196. {
  197. ASSERT(originalString->is8Bit());
  198. ASSERT(originalString->hasOneRef());
  199. ASSERT(originalString->bufferOwnership() == BufferInternal);
  200. if (!length) {
  201. data = 0;
  202. return empty();
  203. }
  204. // Same as createUninitialized() except here we use fastRealloc.
  205. if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(LChar)))
  206. CRASH();
  207. size_t size = sizeof(StringImpl) + length * sizeof(LChar);
  208. originalString->~StringImpl();
  209. StringImpl* string = static_cast<StringImpl*>(fastRealloc(originalString.leakRef(), size));
  210. data = reinterpret_cast<LChar*>(string + 1);
  211. return adoptRef(new (NotNull, string) StringImpl(length, Force8BitConstructor));
  212. }
  213. PassRefPtr<StringImpl> StringImpl::reallocate(PassRefPtr<StringImpl> originalString, unsigned length, UChar*& data)
  214. {
  215. ASSERT(!originalString->is8Bit());
  216. ASSERT(originalString->hasOneRef());
  217. ASSERT(originalString->bufferOwnership() == BufferInternal);
  218. if (!length) {
  219. data = 0;
  220. return empty();
  221. }
  222. // Same as createUninitialized() except here we use fastRealloc.
  223. if (length > ((std::numeric_limits<unsigned>::max() - sizeof(StringImpl)) / sizeof(UChar)))
  224. CRASH();
  225. size_t size = sizeof(StringImpl) + length * sizeof(UChar);
  226. originalString->~StringImpl();
  227. StringImpl* string = static_cast<StringImpl*>(fastRealloc(originalString.leakRef(), size));
  228. data = reinterpret_cast<UChar*>(string + 1);
  229. return adoptRef(new (NotNull, string) StringImpl(length));
  230. }
  231. PassRefPtr<StringImpl> StringImpl::create(const UChar* characters, unsigned length, StringImplType type)
  232. {
  233. if (!characters || !length)
  234. return empty();
  235. UChar* data;
  236. RefPtr<StringImpl> string = createUninitialized(length, data, type);
  237. memcpy(data, characters, length * sizeof(UChar));
  238. return string.release();
  239. }
  240. PassRefPtr<StringImpl> StringImpl::create(const LChar* characters, unsigned length, StringImplType type)
  241. {
  242. if (!characters || !length)
  243. return empty();
  244. LChar* data;
  245. RefPtr<StringImpl> string = createUninitialized(length, data, type);
  246. memcpy(data, characters, length * sizeof(LChar));
  247. return string.release();
  248. }
  249. PassRefPtr<StringImpl> StringImpl::create8BitIfPossible(const UChar* characters, unsigned length)
  250. {
  251. if (!characters || !length)
  252. return empty();
  253. LChar* data;
  254. RefPtr<StringImpl> string = createUninitialized(length, data);
  255. for (size_t i = 0; i < length; ++i) {
  256. if (characters[i] & 0xff00)
  257. return create(characters, length);
  258. data[i] = static_cast<LChar>(characters[i]);
  259. }
  260. return string.release();
  261. }
  262. PassRefPtr<StringImpl> StringImpl::create8BitIfPossible(const UChar* string)
  263. {
  264. return StringImpl::create8BitIfPossible(string, lengthOfNullTerminatedString(string));
  265. }
  266. PassRefPtr<StringImpl> StringImpl::create(const LChar* string)
  267. {
  268. if (!string)
  269. return empty();
  270. size_t length = strlen(reinterpret_cast<const char*>(string));
  271. if (length > numeric_limits<unsigned>::max())
  272. CRASH();
  273. return create(string, length);
  274. }
  275. const UChar* StringImpl::getData16SlowCase() const
  276. {
  277. if (has16BitShadow())
  278. return m_copyData16;
  279. if (bufferOwnership() == BufferSubstring) {
  280. // If this is a substring, return a pointer into the parent string.
  281. // TODO: Consider severing this string from the parent string
  282. unsigned offset = m_data8 - m_substringBuffer->characters8();
  283. return m_substringBuffer->characters() + offset;
  284. }
  285. STRING_STATS_ADD_UPCONVERTED_STRING(m_length);
  286. unsigned len = length();
  287. if (hasTerminatingNullCharacter())
  288. ++len;
  289. m_copyData16 = static_cast<UChar*>(fastMalloc(len * sizeof(UChar)));
  290. m_hashAndFlags |= s_hashFlagHas16BitShadow;
  291. upconvertCharacters(0, len);
  292. return m_copyData16;
  293. }
  294. void StringImpl::upconvertCharacters(unsigned start, unsigned end) const
  295. {
  296. ASSERT(is8Bit());
  297. ASSERT(has16BitShadow());
  298. for (size_t i = start; i < end; ++i)
  299. m_copyData16[i] = m_data8[i];
  300. }
  301. bool StringImpl::containsOnlyWhitespace()
  302. {
  303. // FIXME: The definition of whitespace here includes a number of characters
  304. // that are not whitespace from the point of view of RenderText; I wonder if
  305. // that's a problem in practice.
  306. if (is8Bit()) {
  307. for (unsigned i = 0; i < m_length; ++i) {
  308. UChar c = m_data8[i];
  309. if (!isASCIISpace(c))
  310. return false;
  311. }
  312. return true;
  313. }
  314. for (unsigned i = 0; i < m_length; ++i) {
  315. UChar c = m_data16[i];
  316. if (!isASCIISpace(c))
  317. return false;
  318. }
  319. return true;
  320. }
  321. PassRefPtr<StringImpl> StringImpl::substring(unsigned start, unsigned length)
  322. {
  323. if (start >= m_length)
  324. return empty();
  325. unsigned maxLength = m_length - start;
  326. if (length >= maxLength) {
  327. if (!start)
  328. return this;
  329. length = maxLength;
  330. }
  331. if (is8Bit())
  332. return create(m_data8 + start, length);
  333. return create(m_data16 + start, length);
  334. }
  335. UChar32 StringImpl::characterStartingAt(unsigned i)
  336. {
  337. if (is8Bit())
  338. return m_data8[i];
  339. if (U16_IS_SINGLE(m_data16[i]))
  340. return m_data16[i];
  341. if (i + 1 < m_length && U16_IS_LEAD(m_data16[i]) && U16_IS_TRAIL(m_data16[i + 1]))
  342. return U16_GET_SUPPLEMENTARY(m_data16[i], m_data16[i + 1]);
  343. return 0;
  344. }
  345. PassRefPtr<StringImpl> StringImpl::lower()
  346. {
  347. // Note: This is a hot function in the Dromaeo benchmark, specifically the
  348. // no-op code path up through the first 'return' statement.
  349. // First scan the string for uppercase and non-ASCII characters:
  350. bool noUpper = true;
  351. UChar ored = 0;
  352. if (is8Bit()) {
  353. const LChar* end = m_data8 + m_length;
  354. for (const LChar* chp = m_data8; chp != end; ++chp) {
  355. if (UNLIKELY(isASCIIUpper(*chp)))
  356. noUpper = false;
  357. ored |= *chp;
  358. }
  359. // Nothing to do if the string is all ASCII with no uppercase.
  360. if (noUpper && !(ored & ~0x7F))
  361. return this;
  362. if (m_length > static_cast<unsigned>(numeric_limits<int32_t>::max()))
  363. CRASH();
  364. int32_t length = m_length;
  365. LChar* data8;
  366. RefPtr<StringImpl> newImpl = createUninitialized(length, data8);
  367. if (!(ored & ~0x7F)) {
  368. for (int32_t i = 0; i < length; ++i)
  369. data8[i] = toASCIILower(m_data8[i]);
  370. return newImpl.release();
  371. }
  372. // Do a slower implementation for cases that include non-ASCII Latin-1 characters.
  373. for (int32_t i = 0; i < length; ++i)
  374. data8[i] = static_cast<LChar>(Unicode::toLower(m_data8[i]));
  375. return newImpl.release();
  376. }
  377. const UChar *end = m_data16 + m_length;
  378. for (const UChar* chp = m_data16; chp != end; ++chp) {
  379. if (UNLIKELY(isASCIIUpper(*chp)))
  380. noUpper = false;
  381. ored |= *chp;
  382. }
  383. // Nothing to do if the string is all ASCII with no uppercase.
  384. if (noUpper && !(ored & ~0x7F))
  385. return this;
  386. if (m_length > static_cast<unsigned>(numeric_limits<int32_t>::max()))
  387. CRASH();
  388. int32_t length = m_length;
  389. if (!(ored & ~0x7F)) {
  390. UChar* data16;
  391. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data16);
  392. for (int32_t i = 0; i < length; ++i) {
  393. UChar c = m_data16[i];
  394. data16[i] = toASCIILower(c);
  395. }
  396. return newImpl.release();
  397. }
  398. // Do a slower implementation for cases that include non-ASCII characters.
  399. UChar* data16;
  400. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data16);
  401. bool error;
  402. int32_t realLength = Unicode::toLower(data16, length, m_data16, m_length, &error);
  403. if (!error && realLength == length)
  404. return newImpl.release();
  405. newImpl = createUninitialized(realLength, data16);
  406. Unicode::toLower(data16, realLength, m_data16, m_length, &error);
  407. if (error)
  408. return this;
  409. return newImpl.release();
  410. }
  411. PassRefPtr<StringImpl> StringImpl::upper()
  412. {
  413. // This function could be optimized for no-op cases the way lower() is,
  414. // but in empirical testing, few actual calls to upper() are no-ops, so
  415. // it wouldn't be worth the extra time for pre-scanning.
  416. if (m_length > static_cast<unsigned>(numeric_limits<int32_t>::max()))
  417. CRASH();
  418. int32_t length = m_length;
  419. if (is8Bit()) {
  420. LChar* data8;
  421. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data8);
  422. // Do a faster loop for the case where all the characters are ASCII.
  423. LChar ored = 0;
  424. for (int i = 0; i < length; ++i) {
  425. LChar c = m_data8[i];
  426. ored |= c;
  427. data8[i] = toASCIIUpper(c);
  428. }
  429. if (!(ored & ~0x7F))
  430. return newImpl.release();
  431. // Do a slower implementation for cases that include non-ASCII Latin-1 characters.
  432. int numberSharpSCharacters = 0;
  433. // There are two special cases.
  434. // 1. latin-1 characters when converted to upper case are 16 bit characters.
  435. // 2. Lower case sharp-S converts to "SS" (two characters)
  436. for (int32_t i = 0; i < length; ++i) {
  437. LChar c = m_data8[i];
  438. if (UNLIKELY(c == smallLetterSharpS))
  439. ++numberSharpSCharacters;
  440. UChar upper = Unicode::toUpper(c);
  441. if (UNLIKELY(upper > 0xff)) {
  442. // Since this upper-cased character does not fit in an 8-bit string, we need to take the 16-bit path.
  443. goto upconvert;
  444. }
  445. data8[i] = static_cast<LChar>(upper);
  446. }
  447. if (!numberSharpSCharacters)
  448. return newImpl.release();
  449. // We have numberSSCharacters sharp-s characters, but none of the other special characters.
  450. newImpl = createUninitialized(m_length + numberSharpSCharacters, data8);
  451. LChar* dest = data8;
  452. for (int32_t i = 0; i < length; ++i) {
  453. LChar c = m_data8[i];
  454. if (c == smallLetterSharpS) {
  455. *dest++ = 'S';
  456. *dest++ = 'S';
  457. } else
  458. *dest++ = static_cast<LChar>(Unicode::toUpper(c));
  459. }
  460. return newImpl.release();
  461. }
  462. upconvert:
  463. const UChar* source16 = characters();
  464. UChar* data16;
  465. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data16);
  466. // Do a faster loop for the case where all the characters are ASCII.
  467. UChar ored = 0;
  468. for (int i = 0; i < length; ++i) {
  469. UChar c = source16[i];
  470. ored |= c;
  471. data16[i] = toASCIIUpper(c);
  472. }
  473. if (!(ored & ~0x7F))
  474. return newImpl.release();
  475. // Do a slower implementation for cases that include non-ASCII characters.
  476. bool error;
  477. newImpl = createUninitialized(m_length, data16);
  478. int32_t realLength = Unicode::toUpper(data16, length, source16, m_length, &error);
  479. if (!error && realLength == length)
  480. return newImpl;
  481. newImpl = createUninitialized(realLength, data16);
  482. Unicode::toUpper(data16, realLength, source16, m_length, &error);
  483. if (error)
  484. return this;
  485. return newImpl.release();
  486. }
  487. PassRefPtr<StringImpl> StringImpl::fill(UChar character)
  488. {
  489. if (!m_length)
  490. return this;
  491. if (!(character & ~0x7F)) {
  492. LChar* data;
  493. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data);
  494. for (unsigned i = 0; i < m_length; ++i)
  495. data[i] = character;
  496. return newImpl.release();
  497. }
  498. UChar* data;
  499. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data);
  500. for (unsigned i = 0; i < m_length; ++i)
  501. data[i] = character;
  502. return newImpl.release();
  503. }
  504. PassRefPtr<StringImpl> StringImpl::foldCase()
  505. {
  506. if (m_length > static_cast<unsigned>(numeric_limits<int32_t>::max()))
  507. CRASH();
  508. int32_t length = m_length;
  509. if (is8Bit()) {
  510. // Do a faster loop for the case where all the characters are ASCII.
  511. LChar* data;
  512. RefPtr <StringImpl>newImpl = createUninitialized(m_length, data);
  513. LChar ored = 0;
  514. for (int32_t i = 0; i < length; ++i) {
  515. LChar c = m_data8[i];
  516. data[i] = toASCIILower(c);
  517. ored |= c;
  518. }
  519. if (!(ored & ~0x7F))
  520. return newImpl.release();
  521. // Do a slower implementation for cases that include non-ASCII Latin-1 characters.
  522. for (int32_t i = 0; i < length; ++i)
  523. data[i] = static_cast<LChar>(Unicode::toLower(m_data8[i]));
  524. return newImpl.release();
  525. }
  526. // Do a faster loop for the case where all the characters are ASCII.
  527. UChar* data;
  528. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data);
  529. UChar ored = 0;
  530. for (int32_t i = 0; i < length; ++i) {
  531. UChar c = m_data16[i];
  532. ored |= c;
  533. data[i] = toASCIILower(c);
  534. }
  535. if (!(ored & ~0x7F))
  536. return newImpl.release();
  537. // Do a slower implementation for cases that include non-ASCII characters.
  538. bool error;
  539. int32_t realLength = Unicode::foldCase(data, length, m_data16, m_length, &error);
  540. if (!error && realLength == length)
  541. return newImpl.release();
  542. newImpl = createUninitialized(realLength, data);
  543. Unicode::foldCase(data, realLength, m_data16, m_length, &error);
  544. if (error)
  545. return this;
  546. return newImpl.release();
  547. }
  548. template <class UCharPredicate>
  549. inline PassRefPtr<StringImpl> StringImpl::stripMatchedCharacters(UCharPredicate predicate)
  550. {
  551. if (!m_length)
  552. return empty();
  553. unsigned start = 0;
  554. unsigned end = m_length - 1;
  555. // skip white space from start
  556. while (start <= end && predicate(is8Bit() ? m_data8[start] : m_data16[start]))
  557. ++start;
  558. // only white space
  559. if (start > end)
  560. return empty();
  561. // skip white space from end
  562. while (end && predicate(is8Bit() ? m_data8[end] : m_data16[end]))
  563. --end;
  564. if (!start && end == m_length - 1)
  565. return this;
  566. if (is8Bit())
  567. return create(m_data8 + start, end + 1 - start);
  568. return create(m_data16 + start, end + 1 - start);
  569. }
  570. class UCharPredicate {
  571. public:
  572. inline UCharPredicate(CharacterMatchFunctionPtr function): m_function(function) { }
  573. inline bool operator()(UChar ch) const
  574. {
  575. return m_function(ch);
  576. }
  577. private:
  578. const CharacterMatchFunctionPtr m_function;
  579. };
  580. class SpaceOrNewlinePredicate {
  581. public:
  582. inline bool operator()(UChar ch) const
  583. {
  584. return isSpaceOrNewline(ch);
  585. }
  586. };
  587. PassRefPtr<StringImpl> StringImpl::stripWhiteSpace()
  588. {
  589. return stripMatchedCharacters(SpaceOrNewlinePredicate());
  590. }
  591. PassRefPtr<StringImpl> StringImpl::stripWhiteSpace(IsWhiteSpaceFunctionPtr isWhiteSpace)
  592. {
  593. return stripMatchedCharacters(UCharPredicate(isWhiteSpace));
  594. }
  595. template <typename CharType>
  596. ALWAYS_INLINE PassRefPtr<StringImpl> StringImpl::removeCharacters(const CharType* characters, CharacterMatchFunctionPtr findMatch)
  597. {
  598. const CharType* from = characters;
  599. const CharType* fromend = from + m_length;
  600. // Assume the common case will not remove any characters
  601. while (from != fromend && !findMatch(*from))
  602. ++from;
  603. if (from == fromend)
  604. return this;
  605. StringBuffer<CharType> data(m_length);
  606. CharType* to = data.characters();
  607. unsigned outc = from - characters;
  608. if (outc)
  609. memcpy(to, characters, outc * sizeof(CharType));
  610. while (true) {
  611. while (from != fromend && findMatch(*from))
  612. ++from;
  613. while (from != fromend && !findMatch(*from))
  614. to[outc++] = *from++;
  615. if (from == fromend)
  616. break;
  617. }
  618. data.shrink(outc);
  619. return adopt(data);
  620. }
  621. PassRefPtr<StringImpl> StringImpl::removeCharacters(CharacterMatchFunctionPtr findMatch)
  622. {
  623. if (is8Bit())
  624. return removeCharacters(characters8(), findMatch);
  625. return removeCharacters(characters16(), findMatch);
  626. }
  627. template <typename CharType, class UCharPredicate>
  628. inline PassRefPtr<StringImpl> StringImpl::simplifyMatchedCharactersToSpace(UCharPredicate predicate)
  629. {
  630. StringBuffer<CharType> data(m_length);
  631. const CharType* from = getCharacters<CharType>();
  632. const CharType* fromend = from + m_length;
  633. int outc = 0;
  634. bool changedToSpace = false;
  635. CharType* to = data.characters();
  636. while (true) {
  637. while (from != fromend && predicate(*from)) {
  638. if (*from != ' ')
  639. changedToSpace = true;
  640. ++from;
  641. }
  642. while (from != fromend && !predicate(*from))
  643. to[outc++] = *from++;
  644. if (from != fromend)
  645. to[outc++] = ' ';
  646. else
  647. break;
  648. }
  649. if (outc > 0 && to[outc - 1] == ' ')
  650. --outc;
  651. if (static_cast<unsigned>(outc) == m_length && !changedToSpace)
  652. return this;
  653. data.shrink(outc);
  654. return adopt(data);
  655. }
  656. PassRefPtr<StringImpl> StringImpl::simplifyWhiteSpace()
  657. {
  658. if (is8Bit())
  659. return StringImpl::simplifyMatchedCharactersToSpace<LChar>(SpaceOrNewlinePredicate());
  660. return StringImpl::simplifyMatchedCharactersToSpace<UChar>(SpaceOrNewlinePredicate());
  661. }
  662. PassRefPtr<StringImpl> StringImpl::simplifyWhiteSpace(IsWhiteSpaceFunctionPtr isWhiteSpace)
  663. {
  664. if (is8Bit())
  665. return StringImpl::simplifyMatchedCharactersToSpace<LChar>(UCharPredicate(isWhiteSpace));
  666. return StringImpl::simplifyMatchedCharactersToSpace<UChar>(UCharPredicate(isWhiteSpace));
  667. }
  668. int StringImpl::toIntStrict(bool* ok, int base)
  669. {
  670. if (is8Bit())
  671. return charactersToIntStrict(characters8(), m_length, ok, base);
  672. return charactersToIntStrict(characters16(), m_length, ok, base);
  673. }
  674. unsigned StringImpl::toUIntStrict(bool* ok, int base)
  675. {
  676. if (is8Bit())
  677. return charactersToUIntStrict(characters8(), m_length, ok, base);
  678. return charactersToUIntStrict(characters16(), m_length, ok, base);
  679. }
  680. int64_t StringImpl::toInt64Strict(bool* ok, int base)
  681. {
  682. if (is8Bit())
  683. return charactersToInt64Strict(characters8(), m_length, ok, base);
  684. return charactersToInt64Strict(characters16(), m_length, ok, base);
  685. }
  686. uint64_t StringImpl::toUInt64Strict(bool* ok, int base)
  687. {
  688. if (is8Bit())
  689. return charactersToUInt64Strict(characters8(), m_length, ok, base);
  690. return charactersToUInt64Strict(characters16(), m_length, ok, base);
  691. }
  692. intptr_t StringImpl::toIntPtrStrict(bool* ok, int base)
  693. {
  694. if (is8Bit())
  695. return charactersToIntPtrStrict(characters8(), m_length, ok, base);
  696. return charactersToIntPtrStrict(characters16(), m_length, ok, base);
  697. }
  698. int StringImpl::toInt(bool* ok)
  699. {
  700. if (is8Bit())
  701. return charactersToInt(characters8(), m_length, ok);
  702. return charactersToInt(characters16(), m_length, ok);
  703. }
  704. unsigned StringImpl::toUInt(bool* ok)
  705. {
  706. if (is8Bit())
  707. return charactersToUInt(characters8(), m_length, ok);
  708. return charactersToUInt(characters16(), m_length, ok);
  709. }
  710. int64_t StringImpl::toInt64(bool* ok)
  711. {
  712. if (is8Bit())
  713. return charactersToInt64(characters8(), m_length, ok);
  714. return charactersToInt64(characters16(), m_length, ok);
  715. }
  716. uint64_t StringImpl::toUInt64(bool* ok)
  717. {
  718. if (is8Bit())
  719. return charactersToUInt64(characters8(), m_length, ok);
  720. return charactersToUInt64(characters16(), m_length, ok);
  721. }
  722. intptr_t StringImpl::toIntPtr(bool* ok)
  723. {
  724. if (is8Bit())
  725. return charactersToIntPtr(characters8(), m_length, ok);
  726. return charactersToIntPtr(characters16(), m_length, ok);
  727. }
  728. double StringImpl::toDouble(bool* ok)
  729. {
  730. if (is8Bit())
  731. return charactersToDouble(characters8(), m_length, ok);
  732. return charactersToDouble(characters16(), m_length, ok);
  733. }
  734. float StringImpl::toFloat(bool* ok)
  735. {
  736. if (is8Bit())
  737. return charactersToFloat(characters8(), m_length, ok);
  738. return charactersToFloat(characters16(), m_length, ok);
  739. }
  740. bool equalIgnoringCase(const LChar* a, const LChar* b, unsigned length)
  741. {
  742. while (length--) {
  743. LChar bc = *b++;
  744. if (foldCase(*a++) != foldCase(bc))
  745. return false;
  746. }
  747. return true;
  748. }
  749. bool equalIgnoringCase(const UChar* a, const LChar* b, unsigned length)
  750. {
  751. while (length--) {
  752. LChar bc = *b++;
  753. if (foldCase(*a++) != foldCase(bc))
  754. return false;
  755. }
  756. return true;
  757. }
  758. size_t StringImpl::find(CharacterMatchFunctionPtr matchFunction, unsigned start)
  759. {
  760. if (is8Bit())
  761. return WTF::find(characters8(), m_length, matchFunction, start);
  762. return WTF::find(characters16(), m_length, matchFunction, start);
  763. }
  764. size_t StringImpl::find(const LChar* matchString, unsigned index)
  765. {
  766. // Check for null or empty string to match against
  767. if (!matchString)
  768. return notFound;
  769. size_t matchStringLength = strlen(reinterpret_cast<const char*>(matchString));
  770. if (matchStringLength > numeric_limits<unsigned>::max())
  771. CRASH();
  772. unsigned matchLength = matchStringLength;
  773. if (!matchLength)
  774. return min(index, length());
  775. // Optimization 1: fast case for strings of length 1.
  776. if (matchLength == 1)
  777. return WTF::find(characters16(), length(), *matchString, index);
  778. // Check index & matchLength are in range.
  779. if (index > length())
  780. return notFound;
  781. unsigned searchLength = length() - index;
  782. if (matchLength > searchLength)
  783. return notFound;
  784. // delta is the number of additional times to test; delta == 0 means test only once.
  785. unsigned delta = searchLength - matchLength;
  786. const UChar* searchCharacters = characters() + index;
  787. // Optimization 2: keep a running hash of the strings,
  788. // only call equal if the hashes match.
  789. unsigned searchHash = 0;
  790. unsigned matchHash = 0;
  791. for (unsigned i = 0; i < matchLength; ++i) {
  792. searchHash += searchCharacters[i];
  793. matchHash += matchString[i];
  794. }
  795. unsigned i = 0;
  796. // keep looping until we match
  797. while (searchHash != matchHash || !equal(searchCharacters + i, matchString, matchLength)) {
  798. if (i == delta)
  799. return notFound;
  800. searchHash += searchCharacters[i + matchLength];
  801. searchHash -= searchCharacters[i];
  802. ++i;
  803. }
  804. return index + i;
  805. }
  806. size_t StringImpl::findIgnoringCase(const LChar* matchString, unsigned index)
  807. {
  808. // Check for null or empty string to match against
  809. if (!matchString)
  810. return notFound;
  811. size_t matchStringLength = strlen(reinterpret_cast<const char*>(matchString));
  812. if (matchStringLength > numeric_limits<unsigned>::max())
  813. CRASH();
  814. unsigned matchLength = matchStringLength;
  815. if (!matchLength)
  816. return min(index, length());
  817. // Check index & matchLength are in range.
  818. if (index > length())
  819. return notFound;
  820. unsigned searchLength = length() - index;
  821. if (matchLength > searchLength)
  822. return notFound;
  823. // delta is the number of additional times to test; delta == 0 means test only once.
  824. unsigned delta = searchLength - matchLength;
  825. const UChar* searchCharacters = characters() + index;
  826. unsigned i = 0;
  827. // keep looping until we match
  828. while (!equalIgnoringCase(searchCharacters + i, matchString, matchLength)) {
  829. if (i == delta)
  830. return notFound;
  831. ++i;
  832. }
  833. return index + i;
  834. }
  835. template <typename SearchCharacterType, typename MatchCharacterType>
  836. ALWAYS_INLINE static size_t findInner(const SearchCharacterType* searchCharacters, const MatchCharacterType* matchCharacters, unsigned index, unsigned searchLength, unsigned matchLength)
  837. {
  838. // Optimization: keep a running hash of the strings,
  839. // only call equal() if the hashes match.
  840. // delta is the number of additional times to test; delta == 0 means test only once.
  841. unsigned delta = searchLength - matchLength;
  842. unsigned searchHash = 0;
  843. unsigned matchHash = 0;
  844. for (unsigned i = 0; i < matchLength; ++i) {
  845. searchHash += searchCharacters[i];
  846. matchHash += matchCharacters[i];
  847. }
  848. unsigned i = 0;
  849. // keep looping until we match
  850. while (searchHash != matchHash || !equal(searchCharacters + i, matchCharacters, matchLength)) {
  851. if (i == delta)
  852. return notFound;
  853. searchHash += searchCharacters[i + matchLength];
  854. searchHash -= searchCharacters[i];
  855. ++i;
  856. }
  857. return index + i;
  858. }
  859. size_t StringImpl::find(StringImpl* matchString)
  860. {
  861. // Check for null string to match against
  862. if (UNLIKELY(!matchString))
  863. return notFound;
  864. unsigned matchLength = matchString->length();
  865. // Optimization 1: fast case for strings of length 1.
  866. if (matchLength == 1) {
  867. if (is8Bit()) {
  868. if (matchString->is8Bit())
  869. return WTF::find(characters8(), length(), matchString->characters8()[0]);
  870. return WTF::find(characters8(), length(), matchString->characters16()[0]);
  871. }
  872. if (matchString->is8Bit())
  873. return WTF::find(characters16(), length(), matchString->characters8()[0]);
  874. return WTF::find(characters16(), length(), matchString->characters16()[0]);
  875. }
  876. // Check matchLength is in range.
  877. if (matchLength > length())
  878. return notFound;
  879. // Check for empty string to match against
  880. if (UNLIKELY(!matchLength))
  881. return 0;
  882. if (is8Bit()) {
  883. if (matchString->is8Bit())
  884. return findInner(characters8(), matchString->characters8(), 0, length(), matchLength);
  885. return findInner(characters8(), matchString->characters16(), 0, length(), matchLength);
  886. }
  887. if (matchString->is8Bit())
  888. return findInner(characters16(), matchString->characters8(), 0, length(), matchLength);
  889. return findInner(characters16(), matchString->characters16(), 0, length(), matchLength);
  890. }
  891. size_t StringImpl::find(StringImpl* matchString, unsigned index)
  892. {
  893. // Check for null or empty string to match against
  894. if (UNLIKELY(!matchString))
  895. return notFound;
  896. unsigned matchLength = matchString->length();
  897. // Optimization 1: fast case for strings of length 1.
  898. if (matchLength == 1) {
  899. if (is8Bit())
  900. return WTF::find(characters8(), length(), (*matchString)[0], index);
  901. return WTF::find(characters16(), length(), (*matchString)[0], index);
  902. }
  903. if (UNLIKELY(!matchLength))
  904. return min(index, length());
  905. // Check index & matchLength are in range.
  906. if (index > length())
  907. return notFound;
  908. unsigned searchLength = length() - index;
  909. if (matchLength > searchLength)
  910. return notFound;
  911. if (is8Bit()) {
  912. if (matchString->is8Bit())
  913. return findInner(characters8() + index, matchString->characters8(), index, searchLength, matchLength);
  914. return findInner(characters8() + index, matchString->characters16(), index, searchLength, matchLength);
  915. }
  916. if (matchString->is8Bit())
  917. return findInner(characters16() + index, matchString->characters8(), index, searchLength, matchLength);
  918. return findInner(characters16() + index, matchString->characters16(), index, searchLength, matchLength);
  919. }
  920. template <typename SearchCharacterType, typename MatchCharacterType>
  921. ALWAYS_INLINE static size_t findIgnoringCaseInner(const SearchCharacterType* searchCharacters, const MatchCharacterType* matchCharacters, unsigned index, unsigned searchLength, unsigned matchLength)
  922. {
  923. // delta is the number of additional times to test; delta == 0 means test only once.
  924. unsigned delta = searchLength - matchLength;
  925. unsigned i = 0;
  926. // keep looping until we match
  927. while (!equalIgnoringCase(searchCharacters + i, matchCharacters, matchLength)) {
  928. if (i == delta)
  929. return notFound;
  930. ++i;
  931. }
  932. return index + i;
  933. }
  934. size_t StringImpl::findIgnoringCase(StringImpl* matchString, unsigned index)
  935. {
  936. // Check for null or empty string to match against
  937. if (!matchString)
  938. return notFound;
  939. unsigned matchLength = matchString->length();
  940. if (!matchLength)
  941. return min(index, length());
  942. // Check index & matchLength are in range.
  943. if (index > length())
  944. return notFound;
  945. unsigned searchLength = length() - index;
  946. if (matchLength > searchLength)
  947. return notFound;
  948. if (is8Bit()) {
  949. if (matchString->is8Bit())
  950. return findIgnoringCaseInner(characters8() + index, matchString->characters8(), index, searchLength, matchLength);
  951. return findIgnoringCaseInner(characters8() + index, matchString->characters16(), index, searchLength, matchLength);
  952. }
  953. if (matchString->is8Bit())
  954. return findIgnoringCaseInner(characters16() + index, matchString->characters8(), index, searchLength, matchLength);
  955. return findIgnoringCaseInner(characters16() + index, matchString->characters16(), index, searchLength, matchLength);
  956. }
  957. size_t StringImpl::findNextLineStart(unsigned index)
  958. {
  959. if (is8Bit())
  960. return WTF::findNextLineStart(characters8(), m_length, index);
  961. return WTF::findNextLineStart(characters16(), m_length, index);
  962. }
  963. size_t StringImpl::reverseFind(UChar c, unsigned index)
  964. {
  965. if (is8Bit())
  966. return WTF::reverseFind(characters8(), m_length, c, index);
  967. return WTF::reverseFind(characters16(), m_length, c, index);
  968. }
  969. template <typename SearchCharacterType, typename MatchCharacterType>
  970. ALWAYS_INLINE static size_t reverseFindInner(const SearchCharacterType* searchCharacters, const MatchCharacterType* matchCharacters, unsigned index, unsigned length, unsigned matchLength)
  971. {
  972. // Optimization: keep a running hash of the strings,
  973. // only call equal if the hashes match.
  974. // delta is the number of additional times to test; delta == 0 means test only once.
  975. unsigned delta = min(index, length - matchLength);
  976. unsigned searchHash = 0;
  977. unsigned matchHash = 0;
  978. for (unsigned i = 0; i < matchLength; ++i) {
  979. searchHash += searchCharacters[delta + i];
  980. matchHash += matchCharacters[i];
  981. }
  982. // keep looping until we match
  983. while (searchHash != matchHash || !equal(searchCharacters + delta, matchCharacters, matchLength)) {
  984. if (!delta)
  985. return notFound;
  986. --delta;
  987. searchHash -= searchCharacters[delta + matchLength];
  988. searchHash += searchCharacters[delta];
  989. }
  990. return delta;
  991. }
  992. size_t StringImpl::reverseFind(StringImpl* matchString, unsigned index)
  993. {
  994. // Check for null or empty string to match against
  995. if (!matchString)
  996. return notFound;
  997. unsigned matchLength = matchString->length();
  998. unsigned ourLength = length();
  999. if (!matchLength)
  1000. return min(index, ourLength);
  1001. // Optimization 1: fast case for strings of length 1.
  1002. if (matchLength == 1) {
  1003. if (is8Bit())
  1004. return WTF::reverseFind(characters8(), ourLength, (*matchString)[0], index);
  1005. return WTF::reverseFind(characters16(), ourLength, (*matchString)[0], index);
  1006. }
  1007. // Check index & matchLength are in range.
  1008. if (matchLength > ourLength)
  1009. return notFound;
  1010. if (is8Bit()) {
  1011. if (matchString->is8Bit())
  1012. return reverseFindInner(characters8(), matchString->characters8(), index, ourLength, matchLength);
  1013. return reverseFindInner(characters8(), matchString->characters16(), index, ourLength, matchLength);
  1014. }
  1015. if (matchString->is8Bit())
  1016. return reverseFindInner(characters16(), matchString->characters8(), index, ourLength, matchLength);
  1017. return reverseFindInner(characters16(), matchString->characters16(), index, ourLength, matchLength);
  1018. }
  1019. template <typename SearchCharacterType, typename MatchCharacterType>
  1020. ALWAYS_INLINE static size_t reverseFindIgnoringCaseInner(const SearchCharacterType* searchCharacters, const MatchCharacterType* matchCharacters, unsigned index, unsigned length, unsigned matchLength)
  1021. {
  1022. // delta is the number of additional times to test; delta == 0 means test only once.
  1023. unsigned delta = min(index, length - matchLength);
  1024. // keep looping until we match
  1025. while (!equalIgnoringCase(searchCharacters + delta, matchCharacters, matchLength)) {
  1026. if (!delta)
  1027. return notFound;
  1028. --delta;
  1029. }
  1030. return delta;
  1031. }
  1032. size_t StringImpl::reverseFindIgnoringCase(StringImpl* matchString, unsigned index)
  1033. {
  1034. // Check for null or empty string to match against
  1035. if (!matchString)
  1036. return notFound;
  1037. unsigned matchLength = matchString->length();
  1038. unsigned ourLength = length();
  1039. if (!matchLength)
  1040. return min(index, ourLength);
  1041. // Check index & matchLength are in range.
  1042. if (matchLength > ourLength)
  1043. return notFound;
  1044. if (is8Bit()) {
  1045. if (matchString->is8Bit())
  1046. return reverseFindIgnoringCaseInner(characters8(), matchString->characters8(), index, ourLength, matchLength);
  1047. return reverseFindIgnoringCaseInner(characters8(), matchString->characters16(), index, ourLength, matchLength);
  1048. }
  1049. if (matchString->is8Bit())
  1050. return reverseFindIgnoringCaseInner(characters16(), matchString->characters8(), index, ourLength, matchLength);
  1051. return reverseFindIgnoringCaseInner(characters16(), matchString->characters16(), index, ourLength, matchLength);
  1052. }
  1053. ALWAYS_INLINE static bool equalInner(const StringImpl* stringImpl, unsigned startOffset, const char* matchString, unsigned matchLength, bool caseSensitive)
  1054. {
  1055. ASSERT(stringImpl);
  1056. ASSERT(matchLength <= stringImpl->length());
  1057. ASSERT(startOffset + matchLength <= stringImpl->length());
  1058. if (caseSensitive) {
  1059. if (stringImpl->is8Bit())
  1060. return equal(stringImpl->characters8() + startOffset, reinterpret_cast<const LChar*>(matchString), matchLength);
  1061. return equal(stringImpl->characters16() + startOffset, reinterpret_cast<const LChar*>(matchString), matchLength);
  1062. }
  1063. if (stringImpl->is8Bit())
  1064. return equalIgnoringCase(stringImpl->characters8() + startOffset, reinterpret_cast<const LChar*>(matchString), matchLength);
  1065. return equalIgnoringCase(stringImpl->characters16() + startOffset, reinterpret_cast<const LChar*>(matchString), matchLength);
  1066. }
  1067. bool StringImpl::startsWith(const StringImpl* str) const
  1068. {
  1069. if (!str)
  1070. return false;
  1071. if (str->length() > length())
  1072. return false;
  1073. if (is8Bit()) {
  1074. if (str->is8Bit())
  1075. return equal(characters8(), str->characters8(), str->length());
  1076. return equal(characters8(), str->characters16(), str->length());
  1077. }
  1078. if (str->is8Bit())
  1079. return equal(characters16(), str->characters8(), str->length());
  1080. return equal(characters16(), str->characters16(), str->length());
  1081. }
  1082. bool StringImpl::startsWith(UChar character) const
  1083. {
  1084. return m_length && (*this)[0] == character;
  1085. }
  1086. bool StringImpl::startsWith(const char* matchString, unsigned matchLength, bool caseSensitive) const
  1087. {
  1088. ASSERT(matchLength);
  1089. if (matchLength > length())
  1090. return false;
  1091. return equalInner(this, 0, matchString, matchLength, caseSensitive);
  1092. }
  1093. bool StringImpl::endsWith(StringImpl* matchString, bool caseSensitive)
  1094. {
  1095. ASSERT(matchString);
  1096. if (m_length >= matchString->m_length) {
  1097. unsigned start = m_length - matchString->m_length;
  1098. return (caseSensitive ? find(matchString, start) : findIgnoringCase(matchString, start)) == start;
  1099. }
  1100. return false;
  1101. }
  1102. bool StringImpl::endsWith(UChar character) const
  1103. {
  1104. return m_length && (*this)[m_length - 1] == character;
  1105. }
  1106. bool StringImpl::endsWith(const char* matchString, unsigned matchLength, bool caseSensitive) const
  1107. {
  1108. ASSERT(matchLength);
  1109. if (matchLength > length())
  1110. return false;
  1111. unsigned startOffset = length() - matchLength;
  1112. return equalInner(this, startOffset, matchString, matchLength, caseSensitive);
  1113. }
  1114. PassRefPtr<StringImpl> StringImpl::replace(UChar oldC, UChar newC)
  1115. {
  1116. if (oldC == newC)
  1117. return this;
  1118. unsigned i;
  1119. for (i = 0; i != m_length; ++i) {
  1120. UChar c = is8Bit() ? m_data8[i] : m_data16[i];
  1121. if (c == oldC)
  1122. break;
  1123. }
  1124. if (i == m_length)
  1125. return this;
  1126. if (is8Bit()) {
  1127. if (oldC > 0xff)
  1128. // Looking for a 16 bit char in an 8 bit string, we're done.
  1129. return this;
  1130. if (newC <= 0xff) {
  1131. LChar* data;
  1132. LChar oldChar = static_cast<LChar>(oldC);
  1133. LChar newChar = static_cast<LChar>(newC);
  1134. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data);
  1135. for (i = 0; i != m_length; ++i) {
  1136. LChar ch = m_data8[i];
  1137. if (ch == oldChar)
  1138. ch = newChar;
  1139. data[i] = ch;
  1140. }
  1141. return newImpl.release();
  1142. }
  1143. // There is the possibility we need to up convert from 8 to 16 bit,
  1144. // create a 16 bit string for the result.
  1145. UChar* data;
  1146. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data);
  1147. for (i = 0; i != m_length; ++i) {
  1148. UChar ch = m_data8[i];
  1149. if (ch == oldC)
  1150. ch = newC;
  1151. data[i] = ch;
  1152. }
  1153. return newImpl.release();
  1154. }
  1155. UChar* data;
  1156. RefPtr<StringImpl> newImpl = createUninitialized(m_length, data);
  1157. for (i = 0; i != m_length; ++i) {
  1158. UChar ch = m_data16[i];
  1159. if (ch == oldC)
  1160. ch = newC;
  1161. data[i] = ch;
  1162. }
  1163. return newImpl.release();
  1164. }
  1165. PassRefPtr<StringImpl> StringImpl::replace(unsigned position, unsigned lengthToReplace, StringImpl* str)
  1166. {
  1167. position = min(position, length());
  1168. lengthToReplace = min(lengthToReplace, length() - position);
  1169. unsigned lengthToInsert = str ? str->length() : 0;
  1170. if (!lengthToReplace && !lengthToInsert)
  1171. return this;
  1172. if ((length() - lengthToReplace) >= (numeric_limits<unsigned>::max() - lengthToInsert))
  1173. CRASH();
  1174. if (is8Bit() && (!str || str->is8Bit())) {
  1175. LChar* data;
  1176. RefPtr<StringImpl> newImpl =
  1177. createUninitialized(length() - lengthToReplace + lengthToInsert, data);
  1178. memcpy(data, m_data8, position * sizeof(LChar));
  1179. if (str)
  1180. memcpy(data + position, str->m_data8, lengthToInsert * sizeof(LChar));
  1181. memcpy(data + position + lengthToInsert, m_data8 + position + lengthToReplace,
  1182. (length() - position - lengthToReplace) * sizeof(LChar));
  1183. return newImpl.release();
  1184. }
  1185. UChar* data;
  1186. RefPtr<StringImpl> newImpl =
  1187. createUninitialized(length() - lengthToReplace + lengthToInsert, data);
  1188. if (is8Bit())
  1189. for (unsigned i = 0; i < position; ++i)
  1190. data[i] = m_data8[i];
  1191. else
  1192. memcpy(data, m_data16, position * sizeof(UChar));
  1193. if (str) {
  1194. if (str->is8Bit())
  1195. for (unsigned i = 0; i < lengthToInsert; ++i)
  1196. data[i + position] = str->m_data8[i];
  1197. else
  1198. memcpy(data + position, str->m_data16, lengthToInsert * sizeof(UChar));
  1199. }
  1200. if (is8Bit()) {
  1201. for (unsigned i = 0; i < length() - position - lengthToReplace; ++i)
  1202. data[i + position + lengthToInsert] = m_data8[i + position + lengthToReplace];
  1203. } else {
  1204. memcpy(data + position + lengthToInsert, characters() + position + lengthToReplace,
  1205. (length() - position - lengthToReplace) * sizeof(UChar));
  1206. }
  1207. return newImpl.release();
  1208. }
  1209. PassRefPtr<StringImpl> StringImpl::replace(UChar pattern, StringImpl* replacement)
  1210. {
  1211. if (!replacement)
  1212. return this;
  1213. if (replacement->is8Bit())
  1214. return replace(pattern, replacement->m_data8, replacement->length());
  1215. return replace(pattern, replacement->m_data16, replacement->length());
  1216. }
  1217. PassRefPtr<StringImpl> StringImpl::replace(UChar pattern, const LChar* replacement, unsigned repStrLength)
  1218. {
  1219. ASSERT(replacement);
  1220. size_t srcSegmentStart = 0;
  1221. unsigned matchCount = 0;
  1222. // Count the matches.
  1223. while ((srcSegmentStart = find(pattern, srcSegmentStart)) != notFound) {
  1224. ++matchCount;
  1225. ++srcSegmentStart;
  1226. }
  1227. // If we have 0 matches then we don't have to do any more work.
  1228. if (!matchCount)
  1229. return this;
  1230. if (repStrLength && matchCount > numeric_limits<unsigned>::max() / repStrLength)
  1231. CRASH();
  1232. unsigned replaceSize = matchCount * repStrLength;
  1233. unsigned newSize = m_length - matchCount;
  1234. if (newSize >= (numeric_limits<unsigned>::max() - replaceSize))
  1235. CRASH();
  1236. newSize += replaceSize;
  1237. // Construct the new data.
  1238. size_t srcSegmentEnd;
  1239. unsigned srcSegmentLength;
  1240. srcSegmentStart = 0;
  1241. unsigned dstOffset = 0;
  1242. if (is8Bit()) {
  1243. LChar* data;
  1244. RefPtr<StringImpl> newImpl = createUninitialized(newSize, data);
  1245. while ((srcSegmentEnd = find(pattern, srcSegmentStart)) != notFound) {
  1246. srcSegmentLength = srcSegmentEnd - srcSegmentStart;
  1247. memcpy(data + dstOffset, m_data8 + srcSegmentStart, srcSegmentLength * sizeof(LChar));
  1248. dstOffset += srcSegmentLength;
  1249. memcpy(data + dstOffset, replacement, repStrLength * sizeof(LChar));
  1250. dstOffset += repStrLength;
  1251. srcSegmentStart = srcSegmentEnd + 1;
  1252. }
  1253. srcSegmentLength = m_length - srcSegmentStart;
  1254. memcpy(data + dstOffset, m_data8 + srcSegmentStart, srcSegmentLength * sizeof(LChar));
  1255. ASSERT(dstOffset + srcSegmentLength == newImpl->length());
  1256. return newImpl.release();
  1257. }
  1258. UChar* data;
  1259. RefPtr<StringImpl> newImpl = createUninitialized(newSize, data);
  1260. while ((srcSegmentEnd = find(pattern, srcSegmentStart)) != notFound) {
  1261. srcSegmentLength = srcSegmentEnd - srcSegmentStart;
  1262. memcpy(data + dstOffset, m_data16 + srcSegmentStart, srcSegmentLength * sizeof(UChar));
  1263. dstOffset += srcSegmentLength;
  1264. for (unsigned i = 0; i < repStrLength; ++i)
  1265. data[i + dstOffset] = replacement[i];
  1266. dstOffset += repStrLength;
  1267. srcSegmentStart = srcSegmentEnd + 1;
  1268. }
  1269. srcSegmentLength = m_length - srcSegmentStart;
  1270. memcpy(data + dstOffset, m_data16 + srcSegmentStart, srcSegmentLength * sizeof(UChar));
  1271. ASSERT(dstOffset + srcSegmentLength == newImpl->length());
  1272. return newImpl.release();
  1273. }
  1274. PassRefPtr<StringImpl> StringImpl::replace(UChar pattern, const UChar* replacement, unsigned repStrLength)
  1275. {
  1276. ASSERT(replacement);
  1277. size_t srcSegmentStart = 0;
  1278. unsigned matchCount = 0;
  1279. // Count the matches.
  1280. while ((srcSegmentStart = find(pattern, srcSegmentStart)) != notFound) {
  1281. ++matchCount;
  1282. ++srcSegmentStart;
  1283. }
  1284. // If we have 0 matches then we don't have to do any more work.
  1285. if (!matchCount)
  1286. return this;
  1287. if (repStrLength && matchCount > numeric_limits<unsigned>::max() / repStrLength)
  1288. CRASH();
  1289. unsigned replaceSize = matchCount * repStrLength;
  1290. unsigned newSize = m_length - matchCount;
  1291. if (newSize >= (numeric_limits<unsigned>::max() - replaceSize))
  1292. CRASH();
  1293. newSize += replaceSize;
  1294. // Construct the new data.
  1295. size_t srcSegmentEnd;
  1296. unsigned srcSegmentLength;
  1297. srcSegmentStart = 0;
  1298. unsigned dstOffset = 0;
  1299. if (is8Bit()) {
  1300. UChar* data;
  1301. RefPtr<StringImpl> newImpl = createUninitialized(newSize, data);
  1302. while ((srcSegmentEnd = find(pattern, srcSegmentStart)) != notFound) {
  1303. srcSegmentLength = srcSegmentEnd - srcSegmentStart;
  1304. for (unsigned i = 0; i < srcSegmentLength; ++i)
  1305. data[i + dstOffset] = m_data8[i + srcSegmentStart];
  1306. dstOffset += srcSegmentLength;
  1307. memcpy(data + dstOffset, replacement, repStrLength * sizeof(UChar));
  1308. dstOffset += repStrLength;
  1309. srcSegmentStart = srcSegmentEnd + 1;
  1310. }
  1311. srcSegmentLength = m_length - srcSegmentStart;
  1312. for (unsigned i = 0; i < srcSegmentLength; ++i)
  1313. data[i + dstOffset] = m_data8[i + srcSegmentStart];
  1314. ASSERT(dstOffset + srcSegmentLength == newImpl->length());
  1315. return newImpl.release();
  1316. }
  1317. UChar* data;
  1318. RefPtr<StringImpl> newImpl = createUninitialized(newSize, data);
  1319. while ((srcSegmentEnd = find(pattern, srcSegmentStart)) != notFound) {
  1320. srcSegmentLength = srcSegmentEnd - srcSegmentStart;
  1321. memcpy(data + dstOffset, m_data16 + srcSegmentStart, srcSegmentLength * sizeof(UChar));
  1322. dstOffset += srcSegmentLength;
  1323. memcpy(data + dstOffset, replacement, repStrLength * sizeof(UChar));
  1324. dstOffset += repStrLength;
  1325. srcSegmentStart = srcSegmentEnd + 1;
  1326. }
  1327. srcSegmentLength = m_length - srcSegmentStart;
  1328. memcpy(data + dstOffset, m_data16 + srcSegmentStart, srcSegmentLength * sizeof(UChar));
  1329. ASSERT(dstOffset + srcSegmentLength == newImpl->length());
  1330. return newImpl.release();
  1331. }
  1332. PassRefPtr<StringImpl> StringImpl::replace(StringImpl* pattern, StringImpl* replacement)
  1333. {
  1334. if (!pattern || !replacement)
  1335. return this;
  1336. unsigned patternLength = pattern->length();
  1337. if (!patternLength)
  1338. return this;
  1339. unsigned repStrLength = replacement->length();
  1340. size_t srcSegmentStart = 0;
  1341. unsigned matchCount = 0;
  1342. // Count the matches.
  1343. while ((srcSegmentStart = find(pattern, srcSegmentStart)) != notFound) {
  1344. ++matchCount;
  1345. srcSegmentStart += patternLength;
  1346. }
  1347. // If we have 0 matches, we don't have to do any more work
  1348. if (!matchCount)
  1349. return this;
  1350. unsigned newSize = m_length - matchCount * patternLength;
  1351. if (repStrLength && matchCount > numeric_limits<unsigned>::max() / repStrLength)
  1352. CRASH();
  1353. if (newSize > (numeric_limits<unsigned>::max() - matchCount * repStrLength))
  1354. CRASH();
  1355. newSize += matchCount * repStrLength;
  1356. // Construct the new data
  1357. size_t srcSegmentEnd;
  1358. unsigned srcSegmentLength;
  1359. srcSegmentStart = 0;
  1360. unsigned dstOffset = 0;
  1361. bool srcIs8Bit = is8Bit();
  1362. bool replacementIs8Bit = replacement->is8Bit();
  1363. // There are 4 cases:
  1364. // 1. This and replacement are both 8 bit.
  1365. // 2. This and replacement are both 16 bit.
  1366. // 3. This is 8 bit and replacement is 16 bit.
  1367. // 4. This is 16 bit and replacement is 8 bit.
  1368. if (srcIs8Bit && replacementIs8Bit) {
  1369. // Case 1
  1370. LChar* data;
  1371. RefPtr<StringImpl> newImpl = createUninitialized(newSize, data);
  1372. while ((srcSegmentEnd = find(pattern, srcSegmentStart)) != notFound) {
  1373. srcSegmentLength = srcSegmentEnd - srcSegmentStart;
  1374. memcpy(data + dstOffset, m_data8 + srcSegmentStart, srcSegmentLength * sizeof(LChar));
  1375. dstOffset += srcSegmentLength;
  1376. memcpy(data + dstOffset, replacement->m_data8, repStrLength * sizeof(LChar));
  1377. dstOffset += repStrLength;
  1378. srcSegmentStart = srcSegmentEnd + patternLength;
  1379. }
  1380. srcSegmentLength = m_length - srcSegmentStart;
  1381. memcpy(data + dstOffset, m_data8 + srcSegmentStart, srcSegmentLength * sizeof(LChar));
  1382. ASSERT(dstOffset + srcSegmentLength == newImpl->length());
  1383. return newImpl.release();
  1384. }
  1385. UChar* data;
  1386. RefPtr<StringImpl> newImpl = createUninitialized(newSize, data);
  1387. while ((srcSegmentEnd = find(pattern, srcSegmentStart)) != notFound) {
  1388. srcSegmentLength = srcSegmentEnd - srcSegmentStart;
  1389. if (srcIs8Bit) {
  1390. // Case 3.
  1391. for (unsigned i = 0; i < srcSegmentLength; ++i)
  1392. data[i + dstOffset] = m_data8[i + srcSegmentStart];
  1393. } else {
  1394. // Case 2 & 4.
  1395. memcpy(data + dstOffset, m_data16 + srcSegmentStart, srcSegmentLength * sizeof(UChar));
  1396. }
  1397. dstOffset += srcSegmentLength;
  1398. if (replacementIs8Bit) {
  1399. // Cases 2 & 3.
  1400. for (unsigned i = 0; i < repStrLength; ++i)
  1401. data[i + dstOffset] = replacement->m_data8[i];
  1402. } else {
  1403. // Case 4
  1404. memcpy(data + dstOffset, replacement->m_data16, repStrLength * sizeof(UChar));
  1405. }
  1406. dstOffset += repStrLength;
  1407. srcSegmentStart = srcSegmentEnd + patternLength;
  1408. }
  1409. srcSegmentLength = m_length - srcSegmentStart;
  1410. if (srcIs8Bit) {
  1411. // Case 3.
  1412. for (unsigned i = 0; i < srcSegmentLength; ++i)
  1413. data[i + dstOffset] = m_data8[i + srcSegmentStart];
  1414. } else {
  1415. // Cases 2 & 4.
  1416. memcpy(data + dstOffset, m_data16 + srcSegmentStart, srcSegmentLength * sizeof(UChar));
  1417. }
  1418. ASSERT(dstOffset + srcSegmentLength == newImpl->length());
  1419. return newImpl.release();
  1420. }
  1421. static inline bool stringImplContentEqual(const StringImpl* a, const StringImpl* b)
  1422. {
  1423. unsigned aLength = a->length();
  1424. unsigned bLength = b->length();
  1425. if (aLength != bLength)
  1426. return false;
  1427. if (a->is8Bit()) {
  1428. if (b->is8Bit())
  1429. return equal(a->characters8(), b->characters8(), aLength);
  1430. return equal(a->characters8(), b->characters16(), aLength);
  1431. }
  1432. if (b->is8Bit())
  1433. return equal(a->characters16(), b->characters8(), aLength);
  1434. return equal(a->characters16(), b->characters16(), aLength);
  1435. }
  1436. bool equal(const StringImpl* a, const StringImpl* b)
  1437. {
  1438. if (a == b)
  1439. return true;
  1440. if (!a || !b)
  1441. return false;
  1442. return stringImplContentEqual(a, b);
  1443. }
  1444. bool equal(const StringImpl* a, const LChar* b, unsigned length)
  1445. {
  1446. if (!a)
  1447. return !b;
  1448. if (!b)
  1449. return !a;
  1450. if (length != a->length())
  1451. return false;
  1452. if (a->is8Bit())
  1453. return equal(a->characters8(), b, length);
  1454. return equal(a->characters16(), b, length);
  1455. }
  1456. bool equal(const StringImpl* a, const LChar* b)
  1457. {
  1458. if (!a)
  1459. return !b;
  1460. if (!b)
  1461. return !a;
  1462. unsigned length = a->length();
  1463. if (a->is8Bit()) {
  1464. const LChar* aPtr = a->characters8();
  1465. for (unsigned i = 0; i != length; ++i) {
  1466. LChar bc = b[i];
  1467. LChar ac = aPtr[i];
  1468. if (!bc)
  1469. return false;
  1470. if (ac != bc)
  1471. return false;
  1472. }
  1473. return !b[length];
  1474. }
  1475. const UChar* aPtr = a->characters16();
  1476. for (unsigned i = 0; i != length; ++i) {
  1477. LChar bc = b[i];
  1478. if (!bc)
  1479. return false;
  1480. if (aPtr[i] != bc)
  1481. return false;
  1482. }
  1483. return !b[length];
  1484. }
  1485. bool equal(const StringImpl* a, const UChar* b, unsigned length)
  1486. {
  1487. if (!a)
  1488. return !b;
  1489. if (!b)
  1490. return false;
  1491. if (a->length() != length)
  1492. return false;
  1493. if (a->is8Bit())
  1494. return equal(a->characters8(), b, length);
  1495. return equal(a->characters16(), b, length);
  1496. }
  1497. bool equalNonNull(const StringImpl* a, const StringImpl* b)
  1498. {
  1499. ASSERT(a && b);
  1500. if (a == b)
  1501. return true;
  1502. return stringImplContentEqual(a, b);
  1503. }
  1504. bool equalIgnoringCase(const StringImpl* a, const StringImpl* b)
  1505. {
  1506. if (a == b)
  1507. return true;
  1508. if (!a || !b)
  1509. return false;
  1510. return CaseFoldingHash::equal(a, b);
  1511. }
  1512. bool equalIgnoringCase(const StringImpl* a, const LChar* b)
  1513. {
  1514. if (!a)
  1515. return !b;
  1516. if (!b)
  1517. return !a;
  1518. unsigned length = a->length();
  1519. // Do a faster loop for the case where all the characters are ASCII.
  1520. UChar ored = 0;
  1521. bool equal = true;
  1522. if (a->is8Bit()) {
  1523. const LChar* as = a->characters8();
  1524. for (unsigned i = 0; i != length; ++i) {
  1525. LChar bc = b[i];
  1526. if (!bc)
  1527. return false;
  1528. UChar ac = as[i];
  1529. ored |= ac;
  1530. equal = equal && (toASCIILower(ac) == toASCIILower(bc));
  1531. }
  1532. // Do a slower implementation for cases that include non-ASCII characters.
  1533. if (ored & ~0x7F) {
  1534. equal = true;
  1535. for (unsigned i = 0; i != length; ++i)
  1536. equal = equal && (foldCase(as[i]) == foldCase(b[i]));
  1537. }
  1538. return equal && !b[length];
  1539. }
  1540. const UChar* as = a->characters16();
  1541. for (unsigned i = 0; i != length; ++i) {
  1542. LChar bc = b[i];
  1543. if (!bc)
  1544. return false;
  1545. UChar ac = as[i];
  1546. ored |= ac;
  1547. equal = equal && (toASCIILower(ac) == toASCIILower(bc));
  1548. }
  1549. // Do a slower implementation for cases that include non-ASCII characters.
  1550. if (ored & ~0x7F) {
  1551. equal = true;
  1552. for (unsigned i = 0; i != length; ++i) {
  1553. equal = equal && (foldCase(as[i]) == foldCase(b[i]));
  1554. }
  1555. }
  1556. return equal && !b[length];
  1557. }
  1558. bool equalIgnoringCaseNonNull(const StringImpl* a, const StringImpl* b)
  1559. {
  1560. ASSERT(a && b);
  1561. if (a == b)
  1562. return true;
  1563. unsigned length = a->length();
  1564. if (length != b->length())
  1565. return false;
  1566. if (a->is8Bit()) {
  1567. if (b->is8Bit())
  1568. return equalIgnoringCase(a->characters8(), b->characters8(), length);
  1569. return equalIgnoringCase(b->characters16(), a->characters8(), length);
  1570. }
  1571. if (b->is8Bit())
  1572. return equalIgnoringCase(a->characters16(), b->characters8(), length);
  1573. return equalIgnoringCase(a->characters16(), b->characters16(), length);
  1574. }
  1575. bool equalIgnoringNullity(StringImpl* a, StringImpl* b)
  1576. {
  1577. if (!a && b && !b->length())
  1578. return true;
  1579. if (!b && a && !a->length())
  1580. return true;
  1581. return equal(a, b);
  1582. }
  1583. WTF::Unicode::Direction StringImpl::defaultWritingDirection(bool* hasStrongDirectionality)
  1584. {
  1585. for (unsigned i = 0; i < m_length; ++i) {
  1586. WTF::Unicode::Direction charDirection = WTF::Unicode::direction(is8Bit() ? m_data8[i] : m_data16[i]);
  1587. if (charDirection == WTF::Unicode::LeftToRight) {
  1588. if (hasStrongDirectionality)
  1589. *hasStrongDirectionality = true;
  1590. return WTF::Unicode::LeftToRight;
  1591. }
  1592. if (charDirection == WTF::Unicode::RightToLeft || charDirection == WTF::Unicode::RightToLeftArabic) {
  1593. if (hasStrongDirectionality)
  1594. *hasStrongDirectionality = true;
  1595. return WTF::Unicode::RightToLeft;
  1596. }
  1597. }
  1598. if (hasStrongDirectionality)
  1599. *hasStrongDirectionality = false;
  1600. return WTF::Unicode::LeftToRight;
  1601. }
  1602. PassRefPtr<StringImpl> StringImpl::adopt(StringBuffer<LChar>& buffer)
  1603. {
  1604. unsigned length = buffer.length();
  1605. if (!length)
  1606. return empty();
  1607. return adoptRef(new StringImpl(buffer.release(), length));
  1608. }
  1609. PassRefPtr<StringImpl> StringImpl::adopt(StringBuffer<UChar>& buffer)
  1610. {
  1611. unsigned length = buffer.length();
  1612. if (!length)
  1613. return empty();
  1614. return adoptRef(new StringImpl(buffer.release(), length));
  1615. }
  1616. #if PLATFORM(QT)
  1617. PassRefPtr<StringImpl> StringImpl::adopt(QStringData* qStringData)
  1618. {
  1619. ASSERT(qStringData);
  1620. if (!qStringData->size)
  1621. return empty();
  1622. return adoptRef(new StringImpl(qStringData, ConstructAdoptedQString));
  1623. }
  1624. #endif
  1625. PassRefPtr<StringImpl> StringImpl::createWithTerminatingNullCharacter(const StringImpl& string)
  1626. {
  1627. // Use createUninitialized instead of 'new StringImpl' so that the string and its buffer
  1628. // get allocated in a single memory block.
  1629. unsigned length = string.m_length;
  1630. if (length >= numeric_limits<unsigned>::max())
  1631. CRASH();
  1632. RefPtr<StringImpl> terminatedString;
  1633. if (string.is8Bit()) {
  1634. LChar* data;
  1635. terminatedString = createUninitialized(length + 1, data);
  1636. memcpy(data, string.m_data8, length * sizeof(LChar));
  1637. data[length] = 0;
  1638. } else {
  1639. UChar* data;
  1640. terminatedString = createUninitialized(length + 1, data);
  1641. memcpy(data, string.m_data16, length * sizeof(UChar));
  1642. data[length] = 0;
  1643. }
  1644. --(terminatedString->m_length);
  1645. terminatedString->m_hashAndFlags = (string.m_hashAndFlags & (~s_flagMask | s_hashFlag8BitBuffer)) | s_hashFlagHasTerminatingNullCharacter;
  1646. return terminatedString.release();
  1647. }
  1648. size_t StringImpl::sizeInBytes() const
  1649. {
  1650. // FIXME: support substrings
  1651. size_t size = length();
  1652. if (is8Bit()) {
  1653. if (has16BitShadow()) {
  1654. size += 2 * size;
  1655. if (hasTerminatingNullCharacter())
  1656. size += 2;
  1657. }
  1658. } else
  1659. size *= 2;
  1660. return size + sizeof(*this);
  1661. }
  1662. } // namespace WTF